Skip to content

Commit fe3cec1

Browse files
voidstackloopclaude
andcommitted
Data pipeline: order-deterministic prefetching multi-worker loader with resume, lazy NpyDataset
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 1fce151 commit fe3cec1

3 files changed

Lines changed: 372 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ pub mod serving;
111111
pub mod signal;
112112
pub mod sparse;
113113
pub mod structured;
114+
pub mod loader;
114115
pub mod profiler;
115116
pub mod summary_writer;
116117
pub mod transforms;

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

Lines changed: 342 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,342 @@
1+
//! Data pipeline pieces beyond the in-memory [`DataLoader`](crate::data::DataLoader):
2+
//! - [`PrefetchLoader`]: worker threads build batches ahead of the training loop. Batches always come out in the same order
3+
//! whatever the number of workers, the order of epoch `e` is a pure function of `(seed, e)`, and an epoch can be resumed
4+
//! from any batch (deterministic resume after a restart).
5+
//! - [`NpyDataset`]: random access to the rows of `.npy` files without loading them (the file stays on disk).
6+
7+
use crate::data::Dataset;
8+
use crate::error::{Error, Result};
9+
use crate::serialize::npy::npy_header;
10+
use crate::tensor::Tensor;
11+
use std::collections::BTreeMap;
12+
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
13+
use std::sync::{Arc, Condvar, Mutex};
14+
15+
fn splitmix(state: &mut u64) -> u64 {
16+
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
17+
let mut z = *state;
18+
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
19+
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
20+
z ^ (z >> 31)
21+
}
22+
23+
/// The sample order of an epoch: a permutation fixed by `(seed, epoch)` (or the identity without shuffling).
24+
pub fn epoch_order(len: usize, shuffle: bool, seed: u64, epoch: u64) -> Vec<usize> {
25+
let mut idx: Vec<usize> = (0..len).collect();
26+
if shuffle {
27+
let mut st = seed ^ epoch.wrapping_mul(0xD6E8_FEB8_6659_FD93).wrapping_add(0x1234_5678);
28+
for i in (1..len).rev() {
29+
let j = (splitmix(&mut st) % (i as u64 + 1)) as usize;
30+
idx.swap(i, j);
31+
}
32+
}
33+
idx
34+
}
35+
36+
type Batch = Result<(Tensor, Tensor)>;
37+
38+
struct Shared {
39+
next_job: AtomicUsize,
40+
consumed: AtomicUsize,
41+
stop: AtomicBool,
42+
ready: Mutex<BTreeMap<usize, Batch>>,
43+
cv: Condvar,
44+
}
45+
46+
/// Multi-threaded, order-preserving, bounded-prefetch loader over a shared dataset.
47+
pub struct PrefetchLoader<D: Dataset + Send + Sync + 'static> {
48+
dataset: Arc<D>,
49+
batch_size: usize,
50+
shuffle: bool,
51+
seed: u64,
52+
workers: usize,
53+
prefetch: usize,
54+
drop_last: bool,
55+
}
56+
57+
impl<D: Dataset + Send + Sync + 'static> PrefetchLoader<D> {
58+
pub fn new(dataset: Arc<D>, batch_size: usize, shuffle: bool, seed: u64) -> Self {
59+
Self { dataset, batch_size: batch_size.max(1), shuffle, seed, workers: 2, prefetch: 4, drop_last: false }
60+
}
61+
/// Number of worker threads (at least 1).
62+
pub fn workers(mut self, n: usize) -> Self {
63+
self.workers = n.max(1);
64+
self
65+
}
66+
/// How many batches may be built ahead of the one the consumer is on (at least 1).
67+
pub fn prefetch(mut self, n: usize) -> Self {
68+
self.prefetch = n.max(1);
69+
self
70+
}
71+
pub fn drop_last(mut self, on: bool) -> Self {
72+
self.drop_last = on;
73+
self
74+
}
75+
76+
pub fn num_batches(&self) -> usize {
77+
if self.drop_last { self.dataset.len() / self.batch_size } else { self.dataset.len().div_ceil(self.batch_size) }
78+
}
79+
80+
/// The batches of epoch `epoch`.
81+
pub fn epoch(&self, epoch: u64) -> PrefetchIter {
82+
self.epoch_from(epoch, 0)
83+
}
84+
85+
/// The batches of epoch `epoch` starting at batch `start_batch` (resume after a checkpoint).
86+
pub fn epoch_from(&self, epoch: u64, start_batch: usize) -> PrefetchIter {
87+
let order = epoch_order(self.dataset.len(), self.shuffle, self.seed, epoch);
88+
let mut batches: Vec<Vec<usize>> = order.chunks(self.batch_size).map(<[usize]>::to_vec).collect();
89+
if self.drop_last {
90+
batches.retain(|b| b.len() == self.batch_size);
91+
}
92+
let batches = Arc::new(batches.split_off(start_batch.min(batches.len())));
93+
let total = batches.len();
94+
let shared = Arc::new(Shared { next_job: AtomicUsize::new(0), consumed: AtomicUsize::new(0), stop: AtomicBool::new(false), ready: Mutex::new(BTreeMap::new()), cv: Condvar::new() });
95+
let handles = (0..self.workers.min(total.max(1)))
96+
.map(|_| {
97+
let (ds, sh, bs, prefetch) = (self.dataset.clone(), shared.clone(), batches.clone(), self.prefetch);
98+
std::thread::spawn(move || loop {
99+
let i = sh.next_job.fetch_add(1, Ordering::SeqCst);
100+
if i >= bs.len() {
101+
break;
102+
}
103+
// bounded read-ahead: wait until the consumer is within `prefetch` batches of this one
104+
let mut g = sh.ready.lock().unwrap();
105+
while i >= sh.consumed.load(Ordering::SeqCst) + prefetch && !sh.stop.load(Ordering::SeqCst) {
106+
g = sh.cv.wait(g).unwrap();
107+
}
108+
drop(g);
109+
if sh.stop.load(Ordering::SeqCst) {
110+
break;
111+
}
112+
let b = ds.get_batch(&bs[i]);
113+
sh.ready.lock().unwrap().insert(i, b);
114+
sh.cv.notify_all();
115+
})
116+
})
117+
.collect();
118+
PrefetchIter { shared, handles, pos: 0, total }
119+
}
120+
}
121+
122+
pub struct PrefetchIter {
123+
shared: Arc<Shared>,
124+
handles: Vec<std::thread::JoinHandle<()>>,
125+
pos: usize,
126+
total: usize,
127+
}
128+
129+
impl Iterator for PrefetchIter {
130+
type Item = Batch;
131+
fn next(&mut self) -> Option<Batch> {
132+
if self.pos >= self.total {
133+
return None;
134+
}
135+
let mut g = self.shared.ready.lock().unwrap();
136+
loop {
137+
if let Some(b) = g.remove(&self.pos) {
138+
self.pos += 1;
139+
self.shared.consumed.store(self.pos, Ordering::SeqCst);
140+
drop(g);
141+
self.shared.cv.notify_all();
142+
return Some(b);
143+
}
144+
if self.handles.iter().all(|h| h.is_finished()) && !g.contains_key(&self.pos) {
145+
// the workers ended without producing this batch (a panic in the dataset)
146+
self.pos = self.total;
147+
return Some(Err(Error::Msg("PrefetchLoader: a worker thread died before producing the batch".into())));
148+
}
149+
g = self.shared.cv.wait_timeout(g, std::time::Duration::from_millis(50)).unwrap().0;
150+
}
151+
}
152+
fn size_hint(&self) -> (usize, Option<usize>) {
153+
(self.total - self.pos, Some(self.total - self.pos))
154+
}
155+
}
156+
157+
impl ExactSizeIterator for PrefetchIter {}
158+
159+
impl Drop for PrefetchIter {
160+
fn drop(&mut self) {
161+
self.shared.stop.store(true, Ordering::SeqCst);
162+
self.shared.cv.notify_all();
163+
for h in self.handles.drain(..) {
164+
let _ = h.join();
165+
}
166+
}
167+
}
168+
169+
// ------------------------------------------------------------------------------------------------ on-disk arrays
170+
171+
fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
172+
#[cfg(unix)]
173+
{
174+
use std::os::unix::fs::FileExt;
175+
f.read_exact_at(buf, offset)
176+
}
177+
#[cfg(windows)]
178+
{
179+
use std::os::windows::fs::FileExt;
180+
let mut done = 0;
181+
while done < buf.len() {
182+
let n = f.seek_read(&mut buf[done..], offset + done as u64)?;
183+
if n == 0 {
184+
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read"));
185+
}
186+
done += n;
187+
}
188+
Ok(())
189+
}
190+
}
191+
192+
struct NpyFile {
193+
file: std::fs::File,
194+
shape: Vec<usize>,
195+
row_elems: usize,
196+
esize: usize,
197+
kind: (u8, usize),
198+
data_offset: u64,
199+
}
200+
201+
impl NpyFile {
202+
fn open(path: &std::path::Path) -> Result<Self> {
203+
let io = |e: std::io::Error| Error::Msg(format!("NpyDataset: {}: {e}", path.display()));
204+
let file = std::fs::File::open(path).map_err(io)?;
205+
let mut head = vec![0u8; 4096];
206+
let mut f2 = &file;
207+
let n = std::io::Read::read(&mut f2, &mut head).map_err(io)?;
208+
head.truncate(n);
209+
let info = npy_header(&head)?;
210+
if info.fortran || info.descr.starts_with('>') {
211+
return Err(Error::Msg("NpyDataset: only little-endian C-order arrays are supported".into()));
212+
}
213+
let kind = info.descr.as_bytes()[1];
214+
let esize: usize = info.descr[2..].parse().map_err(|_| Error::Msg("NpyDataset: unsupported dtype".into()))?;
215+
if info.shape.is_empty() {
216+
return Err(Error::Msg("NpyDataset: the array needs at least one dimension".into()));
217+
}
218+
let row_elems = info.shape[1..].iter().product::<usize>().max(1);
219+
Ok(Self { file, shape: info.shape, row_elems, esize, kind: (kind, esize), data_offset: info.data_offset as u64 })
220+
}
221+
222+
fn rows(&self) -> usize {
223+
self.shape[0]
224+
}
225+
226+
fn row(&self, i: usize) -> Result<Tensor> {
227+
if i >= self.rows() {
228+
return Err(Error::Msg(format!("NpyDataset: row {i} out of range for {} rows", self.rows())));
229+
}
230+
let mut buf = vec![0u8; self.row_elems * self.esize];
231+
let at = self.data_offset + (i * buf.len()) as u64;
232+
read_at(&self.file, &mut buf, at).map_err(|e| Error::Msg(format!("NpyDataset: {e}")))?;
233+
let shape = &self.shape[1..];
234+
match self.kind {
235+
(b'f', 4) => Tensor::from_slice(&buf.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect::<Vec<_>>(), shape),
236+
(b'f', 8) => Tensor::from_slice(&buf.chunks_exact(8).map(|c| f64::from_le_bytes(c.try_into().unwrap())).collect::<Vec<_>>(), shape),
237+
(b'i', 8) => Tensor::from_slice(&buf.chunks_exact(8).map(|c| i64::from_le_bytes(c.try_into().unwrap())).collect::<Vec<_>>(), shape),
238+
(b'i', 4) => Tensor::from_slice(&buf.chunks_exact(4).map(|c| i32::from_le_bytes(c.try_into().unwrap())).collect::<Vec<_>>(), shape),
239+
(b'u', 1) => Tensor::from_slice(&buf, shape),
240+
other => Err(Error::Msg(format!("NpyDataset: unsupported element type {other:?}"))),
241+
}
242+
}
243+
}
244+
245+
/// Features and targets stored as `.npy` files; only the requested rows are read from disk.
246+
pub struct NpyDataset {
247+
x: NpyFile,
248+
y: NpyFile,
249+
}
250+
251+
impl NpyDataset {
252+
pub fn open(features: impl AsRef<std::path::Path>, targets: impl AsRef<std::path::Path>) -> Result<Self> {
253+
let (x, y) = (NpyFile::open(features.as_ref())?, NpyFile::open(targets.as_ref())?);
254+
if x.rows() != y.rows() {
255+
return Err(Error::Msg(format!("NpyDataset: {} feature rows vs {} target rows", x.rows(), y.rows())));
256+
}
257+
Ok(Self { x, y })
258+
}
259+
}
260+
261+
impl Dataset for NpyDataset {
262+
fn len(&self) -> usize {
263+
self.x.rows()
264+
}
265+
fn get(&self, index: usize) -> Result<(Tensor, Tensor)> {
266+
Ok((self.x.row(index)?, self.y.row(index)?))
267+
}
268+
}
269+
270+
#[cfg(test)]
271+
mod tests {
272+
use super::*;
273+
use crate::data::TensorDataset;
274+
use crate::serialize::npy::save_npy;
275+
276+
fn dataset(n: usize) -> TensorDataset {
277+
let x: Vec<f32> = (0..n * 3).map(|i| i as f32).collect();
278+
let y: Vec<f32> = (0..n).map(|i| i as f32).collect();
279+
TensorDataset::new(Tensor::from_slice(&x, &[n, 3]).unwrap(), Tensor::from_slice(&y, &[n, 1]).unwrap())
280+
}
281+
282+
fn ids(it: impl Iterator<Item = Batch>) -> Vec<Vec<i64>> {
283+
it.map(|b| b.unwrap().1.to_vec::<f32>().unwrap().into_iter().map(|v| v as i64).collect()).collect()
284+
}
285+
286+
#[test]
287+
fn order_is_independent_of_worker_count_and_covers_every_sample_once() {
288+
let ds = Arc::new(dataset(103));
289+
let one = ids(PrefetchLoader::new(ds.clone(), 10, true, 7).workers(1).epoch(0));
290+
let many = ids(PrefetchLoader::new(ds.clone(), 10, true, 7).workers(5).prefetch(2).epoch(0));
291+
assert_eq!(one, many);
292+
assert_eq!(one.len(), 11);
293+
let mut all: Vec<i64> = one.concat();
294+
all.sort_unstable();
295+
assert_eq!(all, (0..103).collect::<Vec<i64>>());
296+
// another epoch has another order; the same epoch always the same
297+
let e1 = ids(PrefetchLoader::new(ds.clone(), 10, true, 7).epoch(1));
298+
assert_ne!(one, e1);
299+
assert_eq!(e1, ids(PrefetchLoader::new(ds.clone(), 10, true, 7).workers(3).epoch(1)));
300+
// no shuffle: the natural order; drop_last removes the short batch
301+
let plain = ids(PrefetchLoader::new(ds.clone(), 10, false, 0).drop_last(true).epoch(0));
302+
assert_eq!(plain.len(), 10);
303+
assert_eq!(plain[3], (30..40).collect::<Vec<i64>>());
304+
}
305+
306+
#[test]
307+
fn resume_continues_where_the_epoch_stopped_and_dropping_early_is_safe() {
308+
let ds = Arc::new(dataset(60));
309+
let loader = PrefetchLoader::new(ds, 8, true, 3).workers(4);
310+
let full = ids(loader.epoch(2));
311+
let tail = ids(loader.epoch_from(2, 3));
312+
assert_eq!(tail, full[3..].to_vec());
313+
// abandoning an iterator mid-epoch joins the workers without hanging
314+
let mut it = loader.epoch(0);
315+
it.next().unwrap().unwrap();
316+
drop(it);
317+
assert_eq!(loader.epoch(0).len(), full.len());
318+
}
319+
320+
#[test]
321+
fn npy_rows_are_read_lazily_from_disk() {
322+
let dir = std::env::temp_dir().join("oxideon_npy_ds_test");
323+
std::fs::create_dir_all(&dir).unwrap();
324+
let (xp, yp) = (dir.join("x.npy"), dir.join("y.npy"));
325+
let x = Tensor::from_slice(&(0..40).map(|i| i as f32 * 0.5).collect::<Vec<_>>(), &[10, 4]).unwrap();
326+
let y = Tensor::from_slice(&(0..10).map(|i| i as i64).collect::<Vec<_>>(), &[10]).unwrap();
327+
save_npy(&x, &xp).unwrap();
328+
save_npy(&y, &yp).unwrap();
329+
let ds = NpyDataset::open(&xp, &yp).unwrap();
330+
assert_eq!(ds.len(), 10);
331+
let (a, b) = ds.get(7).unwrap();
332+
assert_eq!(a.to_vec::<f32>().unwrap(), vec![14.0, 14.5, 15.0, 15.5]);
333+
assert_eq!(b.item::<i64>().unwrap(), 7);
334+
assert!(ds.get(10).is_err());
335+
let batch = ds.get_batch(&[0, 9]).unwrap();
336+
assert_eq!(batch.0.shape(), [2, 4]);
337+
// and it works behind the prefetching loader
338+
let n: usize = PrefetchLoader::new(Arc::new(ds), 4, false, 0).epoch(0).map(|b| b.unwrap().0.shape()[0]).sum();
339+
assert_eq!(n, 10);
340+
let _ = std::fs::remove_dir_all(&dir);
341+
}
342+
}

‎crates/oxideon-core/src/serialize/npy.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,35 @@ fn parse_header(text: &str) -> Result<Header> {
113113
Ok(Header { descr, fortran, shape })
114114
}
115115

116+
/// What the header of an `.npy` file says (`data_offset` is where the raw array starts).
117+
pub struct NpyInfo {
118+
pub descr: String,
119+
pub fortran: bool,
120+
pub shape: Vec<usize>,
121+
pub data_offset: usize,
122+
}
123+
124+
/// Reads just the header from the first bytes of an `.npy` file.
125+
pub fn npy_header(bytes: &[u8]) -> Result<NpyInfo> {
126+
if bytes.len() < 10 || &bytes[..6] != MAGIC {
127+
return Err(err("not an .npy file (bad magic)"));
128+
}
129+
let (hl, start) = match bytes[6] {
130+
1 => (u16::from_le_bytes([bytes[8], bytes[9]]) as usize, 10),
131+
2 | 3 if bytes.len() >= 12 => (u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize, 12),
132+
_ => return Err(err("unsupported or truncated .npy header")),
133+
};
134+
let end = start + hl;
135+
if bytes.len() < end {
136+
return Err(err("truncated .npy header"));
137+
}
138+
let h = parse_header(std::str::from_utf8(&bytes[start..end]).map_err(|_| err("npy header is not valid UTF-8"))?)?;
139+
if h.descr.len() < 3 {
140+
return Err(err(format!("unsupported npy dtype '{}'", h.descr)));
141+
}
142+
Ok(NpyInfo { descr: h.descr, fortran: h.fortran, shape: h.shape, data_offset: end })
143+
}
144+
116145
/// Parses `.npy` bytes into a tensor.
117146
pub fn from_npy_bytes(bytes: &[u8]) -> Result<Tensor> {
118147
if bytes.len() < 10 || &bytes[..6] != MAGIC {

0 commit comments

Comments
 (0)