Skip to content

Commit 48a8949

Browse files
voidstackloopclaude
andcommitted
perf: recycle large f32 buffers (pool), borrow instead of cloning storage on reads, general strided binary kernel; core ops benchmark vs torch
Elementwise 1M ops ~2.5x faster, layer_norm 30x, softmax / broadcast / strided add 2-4x. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 76f3f5f commit 48a8949

9 files changed

Lines changed: 432 additions & 17 deletions

File tree

‎crates/oxideon-core/src/backend/cpu.rs‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,83 @@ use crate::error::{Error, Result};
99
use crate::gemm::{batched_gemm_f32, batched_gemm_f64};
1010
use crate::layout::{DimMap, Layout, ViewSpec, broadcast_shapes};
1111

12+
/// The smallest and largest storage index a layout can reach, or `None` if it has no elements.
13+
fn layout_extent(l: &Layout) -> Option<(isize, isize)> {
14+
let (mut lo, mut hi) = (l.offset() as isize, l.offset() as isize);
15+
for (&d, &st) in l.shape().iter().zip(l.strides()) {
16+
if d == 0 {
17+
return None;
18+
}
19+
let span = (d as isize - 1) * st as isize;
20+
if span < 0 { lo += span } else { hi += span }
21+
}
22+
Some((lo, hi))
23+
}
24+
25+
/// Binary kernel for two arbitrary layouts of one shape (broadcast dims have stride 0, views any stride): the leading
26+
/// dimensions are walked row by row (in parallel for large outputs) and the last dimension runs as a tight loop, with
27+
/// slice-based fast paths for the stride pairs that occur in practice. `None` if a layout does not fit its storage.
28+
fn strided_binary<T, F>(a: &[T], la: &Layout, b: &[T], lb: &Layout, f: F) -> Option<Vec<T>>
29+
where
30+
T: Copy + Default + Send + Sync + 'static,
31+
F: Fn(T, T) -> T + Sync,
32+
{
33+
let shape = la.shape();
34+
let nd = shape.len();
35+
if nd == 0 || shape != lb.shape() {
36+
return None;
37+
}
38+
let (alo, ahi) = layout_extent(la)?;
39+
let (blo, bhi) = layout_extent(lb)?;
40+
if alo < 0 || blo < 0 || ahi as usize >= a.len() || bhi as usize >= b.len() {
41+
return None;
42+
}
43+
let cols = shape[nd - 1];
44+
let total: usize = shape.iter().product();
45+
let (sa, sb) = (la.strides()[nd - 1] as isize, lb.strides()[nd - 1] as isize);
46+
let lead = &shape[..nd - 1];
47+
let (lsa, lsb) = (&la.strides()[..nd - 1], &lb.strides()[..nd - 1]);
48+
let (oa, ob) = (la.offset() as isize, lb.offset() as isize);
49+
let row = |r: usize, out: &mut [T]| {
50+
// storage offsets of the first element of row `r`
51+
let (mut pa, mut pb, mut rem) = (oa, ob, r);
52+
for d in (0..lead.len()).rev() {
53+
let c = (rem % lead[d]) as isize;
54+
rem /= lead[d];
55+
pa += c * lsa[d] as isize;
56+
pb += c * lsb[d] as isize;
57+
}
58+
let (pa, pb) = (pa as usize, pb as usize);
59+
match (sa, sb) {
60+
(1, 1) => out.iter_mut().zip(&a[pa..pa + cols]).zip(&b[pb..pb + cols]).for_each(|((o, &x), &y)| *o = f(x, y)),
61+
(1, 0) => {
62+
let y = b[pb];
63+
out.iter_mut().zip(&a[pa..pa + cols]).for_each(|(o, &x)| *o = f(x, y));
64+
}
65+
(0, 1) => {
66+
let x = a[pa];
67+
out.iter_mut().zip(&b[pb..pb + cols]).for_each(|(o, &y)| *o = f(x, y));
68+
}
69+
(sa, 1) if sa > 1 => out.iter_mut().zip(a[pa..].iter().step_by(sa as usize)).zip(&b[pb..pb + cols]).for_each(|((o, &x), &y)| *o = f(x, y)),
70+
(1, sb) if sb > 1 => out.iter_mut().zip(&a[pa..pa + cols]).zip(b[pb..].iter().step_by(sb as usize)).for_each(|((o, &x), &y)| *o = f(x, y)),
71+
_ => {
72+
for (j, o) in out.iter_mut().enumerate() {
73+
let j = j as isize;
74+
*o = f(a[(pa as isize + j * sa) as usize], b[(pb as isize + j * sb) as usize]);
75+
}
76+
}
77+
}
78+
};
79+
let mut out = crate::pool::take::<T>(total).unwrap_or_else(|| vec![T::default(); total]);
80+
#[cfg(feature = "rayon")]
81+
if total >= 16384 {
82+
out.par_chunks_mut(cols).enumerate().for_each(|(r, o)| row(r, o));
83+
return Some(out);
84+
}
85+
out.chunks_mut(cols).enumerate().for_each(|(r, o)| row(r, o));
86+
Some(out)
87+
}
88+
1289
/// Host-memory storage supporting all 8 [`DType`] variants.
1390
#[derive(Clone, Debug, PartialEq)]
1491
pub enum CpuStorage {
@@ -459,6 +536,13 @@ impl CpuStorage {
459536
macro_rules! run_unary {
460537
($variant:ident, $v:expr, $map_fn:expr) => {{
461538
if let Some(range) = layout.contiguous_range_in($v.len()) {
539+
if let Some(mut out) = crate::pool::take(range.len()) {
540+
#[cfg(feature = "rayon")]
541+
out.par_iter_mut().zip($v[range].par_iter()).for_each(|(o, &x)| *o = ($map_fn)(x));
542+
#[cfg(not(feature = "rayon"))]
543+
out.iter_mut().zip($v[range].iter()).for_each(|(o, &x)| *o = ($map_fn)(x));
544+
return Ok(Self::$variant(out));
545+
}
462546
#[cfg(feature = "rayon")]
463547
if range.len() >= 16384 {
464548
return Ok(Self::$variant(
@@ -612,6 +696,13 @@ impl CpuStorage {
612696
(Some(ra), Some(rb)) => {
613697
let sa = &$a[ra];
614698
let sb = &$b[rb];
699+
if let Some(mut out) = crate::pool::take(sa.len().min(sb.len())) {
700+
#[cfg(feature = "rayon")]
701+
out.par_iter_mut().zip(sa.par_iter().zip(sb.par_iter())).for_each(|(o, (&x, &y))| *o = ($f)(x, y));
702+
#[cfg(not(feature = "rayon"))]
703+
out.iter_mut().zip(sa.iter().zip(sb.iter())).for_each(|(o, (&x, &y))| *o = ($f)(x, y));
704+
return Ok(Self::$variant(out));
705+
}
615706
#[cfg(feature = "rayon")]
616707
if sa.len() >= 16384 {
617708
return Ok(Self::$variant(
@@ -638,6 +729,13 @@ impl CpuStorage {
638729
let ra = lhs_l.contiguous_range_in($a.len()).unwrap();
639730
let b_val = $b[rhs_l.offset()];
640731
let sa = &$a[ra];
732+
if let Some(mut out) = crate::pool::take(sa.len()) {
733+
#[cfg(feature = "rayon")]
734+
out.par_iter_mut().zip(sa.par_iter()).for_each(|(o, &x)| *o = ($f)(x, b_val));
735+
#[cfg(not(feature = "rayon"))]
736+
out.iter_mut().zip(sa.iter()).for_each(|(o, &x)| *o = ($f)(x, b_val));
737+
return Ok(Self::$variant(out));
738+
}
641739
#[cfg(feature = "rayon")]
642740
if sa.len() >= 16384 {
643741
return Ok(Self::$variant(
@@ -655,6 +753,13 @@ impl CpuStorage {
655753
let rb = rhs_l.contiguous_range_in($b.len()).unwrap();
656754
let a_val = $a[lhs_l.offset()];
657755
let sb = &$b[rb];
756+
if let Some(mut out) = crate::pool::take(sb.len()) {
757+
#[cfg(feature = "rayon")]
758+
out.par_iter_mut().zip(sb.par_iter()).for_each(|(o, &y)| *o = ($f)(a_val, y));
759+
#[cfg(not(feature = "rayon"))]
760+
out.iter_mut().zip(sb.iter()).for_each(|(o, &y)| *o = ($f)(a_val, y));
761+
return Ok(Self::$variant(out));
762+
}
658763
#[cfg(feature = "rayon")]
659764
if sb.len() >= 16384 {
660765
return Ok(Self::$variant(
@@ -665,6 +770,10 @@ impl CpuStorage {
665770
sb.iter().map(|&y| ($f)(a_val, y)).collect(),
666771
));
667772
}
773+
// Any other pair of strided / broadcast layouts: one tight loop per row of the last dimension
774+
if let Some(out) = strided_binary(&$a[..], lhs_l, &$b[..], rhs_l, $f) {
775+
return Ok(Self::$variant(out));
776+
}
668777
// 3. Trailing row broadcast RHS: [.., cols] where RHS has stride 1 on last dim and 0 on preceding dims
669778
if !shape.is_empty()
670779
&& rhs_l.strides().last() == Some(&1)

‎crates/oxideon-core/src/backend/mod.rs‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,31 @@ impl Tracked {
163163
impl Drop for Tracked {
164164
fn drop(&mut self) {
165165
crate::memory::on_free(self.bytes);
166+
// large f32 buffers go back to the pool instead of to the operating system
167+
if self.bytes >= crate::pool::MIN_LEN * 4
168+
&& let Ok(StorageInner::Cpu(CpuStorage::F32(v))) = self.lock.get_mut()
169+
{
170+
crate::pool::give(std::mem::take(v));
171+
}
172+
}
173+
}
174+
175+
/// Borrowed (or, for GPU storage, read-back) host data; dereferences to [`CpuStorage`].
176+
pub enum CpuRef<'a> {
177+
Borrowed(RwLockReadGuard<'a, StorageInner>),
178+
Owned(CpuStorage),
179+
}
180+
181+
impl std::ops::Deref for CpuRef<'_> {
182+
type Target = CpuStorage;
183+
fn deref(&self) -> &CpuStorage {
184+
match self {
185+
Self::Owned(s) => s,
186+
Self::Borrowed(g) => match &**g {
187+
StorageInner::Cpu(s) | StorageInner::Accelerator { storage: s, .. } => s,
188+
_ => unreachable!("cpu_ref only borrows host storage"),
189+
},
190+
}
166191
}
167192
}
168193

@@ -243,6 +268,20 @@ impl Storage {
243268
}
244269

245270
/// Downloads/copies storage to CPU (no-op clone if already on CPU).
271+
/// Read access to the host data without copying it (host and simulated-accelerator storage are borrowed under the
272+
/// read lock; GPU storage is read back once).
273+
pub fn cpu_ref(&self) -> Result<CpuRef<'_>> {
274+
let guard = self.read();
275+
match &*guard {
276+
StorageInner::Cpu(_) | StorageInner::Accelerator { .. } => Ok(CpuRef::Borrowed(guard)),
277+
#[cfg(feature = "wgpu")]
278+
StorageInner::Wgpu(s) => Ok(CpuRef::Owned(s.to_cpu()?)),
279+
StorageInner::Meta { .. } => Err(Error::Msg(
280+
"Cannot access raw memory of a Meta tensor (device='meta')".into(),
281+
)),
282+
}
283+
}
284+
246285
pub fn to_cpu_storage(&self) -> Result<CpuStorage> {
247286
match &*self.read() {
248287
StorageInner::Cpu(s) => Ok(s.clone()),
@@ -593,9 +632,9 @@ impl Storage {
593632
{
594633
return Ok(Self::new_wgpu(out));
595634
}
596-
let cc = cond.to_cpu_storage()?;
597-
let ct = t.to_cpu_storage()?;
598-
let cf = f.to_cpu_storage()?;
635+
let cc = cond.cpu_ref()?;
636+
let ct = t.cpu_ref()?;
637+
let cf = f.cpu_ref()?;
599638
let out = CpuStorage::where_cond(&cc, cond_l, &ct, t_l, &cf, f_l)?;
600639
match &dev {
601640
Device::Cpu => Ok(Self::new_cpu(out)),
@@ -790,7 +829,7 @@ impl Storage {
790829
"Cannot move Meta tensor to physical device without data materialization".into(),
791830
));
792831
}
793-
let cpu = self.to_cpu_storage()?.to_contiguous(layout)?;
832+
let cpu = self.cpu_ref()?.to_contiguous(layout)?;
794833
match dst {
795834
Device::Cpu => Ok(Self::new_cpu(cpu)),
796835
#[cfg(feature = "wgpu")]
@@ -806,7 +845,7 @@ impl Storage {
806845
let n = Self::meta_len("view_scatter", &spec.dst_shape)?;
807846
return Ok(Self::new_meta(self.dtype(), n));
808847
}
809-
let cpu = self.to_cpu_storage()?;
848+
let cpu = self.cpu_ref()?;
810849
let out = cpu.view_scatter(src_layout, spec)?;
811850
match &dev {
812851
Device::Cpu => Ok(Self::new_cpu(out)),

‎crates/oxideon-core/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ pub mod hub;
117117
pub mod loader;
118118
pub mod memory;
119119
pub mod train_loop;
120+
pub mod pool;
120121
pub mod profiler;
121122
pub mod summary_writer;
122123
pub mod transforms;

‎crates/oxideon-core/src/ops.rs‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2483,7 +2483,7 @@ impl Tensor {
24832483
crate::limits::check_elements("index_select", &out_shape)?;
24842484
let cpu =
24852485
self.storage()
2486-
.to_cpu_storage()?
2486+
.cpu_ref()?
24872487
.index_select_vals(self.layout(), ax, &idx_vec)?;
24882488
let storage = Storage::new_cpu(cpu)
24892489
.to_device(&Layout::contiguous(out_shape.clone()), &self.device())?;
@@ -2524,9 +2524,9 @@ impl Tensor {
25242524
}
25252525

25262526
let shape = self.shape().to_vec();
2527-
let cpu = self.storage().to_cpu_storage()?.index_add_vals(
2527+
let cpu = self.storage().cpu_ref()?.index_add_vals(
25282528
self.layout(),
2529-
&source.storage().to_cpu_storage()?,
2529+
&*source.storage().cpu_ref()?,
25302530
source.layout(),
25312531
ax,
25322532
&idx_vec,
@@ -2575,7 +2575,7 @@ impl Tensor {
25752575
let idx = index.to_vec::<i64>()?;
25762576
let cpu =
25772577
self.storage()
2578-
.to_cpu_storage()?
2578+
.cpu_ref()?
25792579
.gather_vals(self.layout(), ax, &idx_shape, &idx)?;
25802580
let storage = Storage::new_cpu(cpu)
25812581
.to_device(&Layout::contiguous(idx_shape.clone()), &self.device())?;
@@ -2621,9 +2621,9 @@ impl Tensor {
26212621
let idx_shape = index.shape().to_vec();
26222622
let idx = index.to_vec::<i64>()?;
26232623
let shape = self.shape().to_vec();
2624-
let cpu = self.storage().to_cpu_storage()?.scatter_add_vals(
2624+
let cpu = self.storage().cpu_ref()?.scatter_add_vals(
26252625
self.layout(),
2626-
&src.storage().to_cpu_storage()?,
2626+
&*src.storage().cpu_ref()?,
26272627
src.layout(),
26282628
&idx_shape,
26292629
ax,
@@ -2680,9 +2680,9 @@ impl Tensor {
26802680
let idx_shape = index.shape().to_vec();
26812681
let idx = index.to_vec::<i64>()?;
26822682
let shape = self.shape().to_vec();
2683-
let cpu = self.storage().to_cpu_storage()?.scatter_vals(
2683+
let cpu = self.storage().cpu_ref()?.scatter_vals(
26842684
self.layout(),
2685-
&src.storage().to_cpu_storage()?,
2685+
&*src.storage().cpu_ref()?,
26862686
src.layout(),
26872687
&idx_shape,
26882688
ax,

0 commit comments

Comments
 (0)