Skip to content

Commit 566d771

Browse files
voidstackloopclaude
andcommitted
StreamingLoader: sharded streaming with shuffle buffer, rank split, deterministic resume; lint fix
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent d19707d commit 566d771

2 files changed

Lines changed: 171 additions & 5 deletions

File tree

‎crates/oxideon-core/src/grammar/regex.rs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,12 @@ impl RegexConstraint {
385385
}
386386
}
387387

388+
impl std::fmt::Debug for RegexConstraint {
389+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390+
write!(f, "RegexConstraint({} live states)", self.state.len())
391+
}
392+
}
393+
388394
#[cfg(test)]
389395
mod tests {
390396
use super::*;
@@ -471,8 +477,3 @@ mod tests {
471477
}
472478
}
473479

474-
impl std::fmt::Debug for RegexConstraint {
475-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476-
write!(f, "RegexConstraint({} live states)", self.state.len())
477-
}
478-
}

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

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,139 @@ impl Drop for PrefetchIter {
166166
}
167167
}
168168

169+
// ------------------------------------------------------------------------------------------------ streaming shards
170+
171+
/// Datasets too large to index randomly: a list of shards (each read front to back), shuffled by shard order and by a
172+
/// bounded shuffle buffer, optionally split across `world_size` ranks. Every epoch's order is a pure function of
173+
/// `(seed, epoch)`; [`epoch_from`](Self::epoch_from) resumes by replaying and discarding the batches already consumed.
174+
pub struct StreamingLoader {
175+
shards: Vec<Arc<dyn Dataset + Send + Sync>>,
176+
batch_size: usize,
177+
buffer: usize,
178+
seed: u64,
179+
rank: usize,
180+
world: usize,
181+
drop_last: bool,
182+
}
183+
184+
impl StreamingLoader {
185+
/// `buffer` samples are held for shuffling (1 disables intra-stream shuffling).
186+
pub fn new(shards: Vec<Arc<dyn Dataset + Send + Sync>>, batch_size: usize, buffer: usize, seed: u64) -> Self {
187+
Self { shards, batch_size: batch_size.max(1), buffer: buffer.max(1), seed, rank: 0, world: 1, drop_last: false }
188+
}
189+
/// This process reads shards `i` of the epoch's shard order with `i % world_size == rank`.
190+
pub fn rank(mut self, rank: usize, world_size: usize) -> Self {
191+
self.world = world_size.max(1);
192+
self.rank = rank.min(self.world - 1);
193+
self
194+
}
195+
pub fn drop_last(mut self, on: bool) -> Self {
196+
self.drop_last = on;
197+
self
198+
}
199+
pub fn epoch(&self, epoch: u64) -> StreamIter {
200+
self.epoch_from(epoch, 0)
201+
}
202+
pub fn epoch_from(&self, epoch: u64, start_batch: usize) -> StreamIter {
203+
let order = epoch_order(self.shards.len(), true, self.seed, epoch);
204+
let queue: std::collections::VecDeque<usize> = order.into_iter().enumerate().filter(|(i, _)| i % self.world == self.rank).map(|(_, s)| s).collect();
205+
let mut it = StreamIter {
206+
shards: self.shards.clone(),
207+
queue,
208+
cur: None,
209+
buf: Vec::new(),
210+
cap: self.buffer,
211+
batch: self.batch_size,
212+
drop_last: self.drop_last,
213+
rng: self.seed ^ epoch.wrapping_mul(0xA24B_AED4_963E_E407) ^ ((self.rank as u64) << 48),
214+
failed: false,
215+
};
216+
for _ in 0..start_batch {
217+
if it.next().is_none() {
218+
break;
219+
}
220+
}
221+
it
222+
}
223+
}
224+
225+
pub struct StreamIter {
226+
shards: Vec<Arc<dyn Dataset + Send + Sync>>,
227+
queue: std::collections::VecDeque<usize>,
228+
cur: Option<(usize, usize)>,
229+
buf: Vec<(Tensor, Tensor)>,
230+
cap: usize,
231+
batch: usize,
232+
drop_last: bool,
233+
rng: u64,
234+
failed: bool,
235+
}
236+
237+
impl StreamIter {
238+
fn read_next(&mut self) -> Result<Option<(Tensor, Tensor)>> {
239+
loop {
240+
if self.cur.is_none() {
241+
match self.queue.pop_front() {
242+
Some(s) => self.cur = Some((s, 0)),
243+
None => return Ok(None),
244+
}
245+
}
246+
let (s, pos) = self.cur.unwrap();
247+
if pos >= self.shards[s].len() {
248+
self.cur = None;
249+
continue;
250+
}
251+
self.cur = Some((s, pos + 1));
252+
return self.shards[s].get(pos).map(Some);
253+
}
254+
}
255+
256+
/// The next sample after the shuffle buffer: top it up, then swap a random element out for the next incoming one.
257+
fn next_sample(&mut self) -> Result<Option<(Tensor, Tensor)>> {
258+
while self.buf.len() < self.cap {
259+
match self.read_next()? {
260+
Some(x) => self.buf.push(x),
261+
None => break,
262+
}
263+
}
264+
if self.buf.is_empty() {
265+
return Ok(None);
266+
}
267+
let j = (splitmix(&mut self.rng) % self.buf.len() as u64) as usize;
268+
Ok(Some(match self.read_next()? {
269+
Some(incoming) => std::mem::replace(&mut self.buf[j], incoming),
270+
None => self.buf.swap_remove(j),
271+
}))
272+
}
273+
}
274+
275+
impl Iterator for StreamIter {
276+
type Item = Batch;
277+
fn next(&mut self) -> Option<Batch> {
278+
if self.failed {
279+
return None;
280+
}
281+
let (mut xs, mut ys) = (Vec::new(), Vec::new());
282+
while xs.len() < self.batch {
283+
match self.next_sample() {
284+
Ok(Some((x, y))) => {
285+
xs.push(x);
286+
ys.push(y);
287+
}
288+
Ok(None) => break,
289+
Err(e) => {
290+
self.failed = true;
291+
return Some(Err(e));
292+
}
293+
}
294+
}
295+
if xs.is_empty() || (self.drop_last && xs.len() < self.batch) {
296+
return None;
297+
}
298+
Some(Tensor::stack(&xs, 0).and_then(|x| Tensor::stack(&ys, 0).map(|y| (x, y))))
299+
}
300+
}
301+
169302
// ------------------------------------------------------------------------------------------------ on-disk arrays
170303

171304
fn read_at(f: &std::fs::File, buf: &mut [u8], offset: u64) -> std::io::Result<()> {
@@ -317,6 +450,38 @@ mod tests {
317450
assert_eq!(loader.epoch(0).len(), full.len());
318451
}
319452

453+
#[test]
454+
fn streaming_shards_cover_everything_once_shuffle_deterministically_split_by_rank_and_resume() {
455+
let shards: Vec<Arc<dyn Dataset + Send + Sync>> = (0..5)
456+
.map(|s| {
457+
let x: Vec<f32> = (0..7).map(|i| (s * 7 + i) as f32).collect();
458+
Arc::new(TensorDataset::new(Tensor::from_slice(&x, &[7, 1]).unwrap(), Tensor::from_slice(&x, &[7, 1]).unwrap())) as Arc<dyn Dataset + Send + Sync>
459+
})
460+
.collect();
461+
let ids = |it: StreamIter| -> Vec<i64> { it.flat_map(|b| b.unwrap().1.to_vec::<f32>().unwrap().into_iter().map(|v| v as i64)).collect() };
462+
let l = StreamingLoader::new(shards.clone(), 4, 10, 9);
463+
let e0 = ids(l.epoch(0));
464+
let mut sorted = e0.clone();
465+
sorted.sort_unstable();
466+
assert_eq!(sorted, (0..35).collect::<Vec<i64>>()); // nothing lost, nothing repeated
467+
assert_ne!(e0, sorted); // but shuffled
468+
assert_eq!(e0, ids(l.epoch(0))); // reproducible
469+
assert_ne!(e0, ids(l.epoch(1)));
470+
// two ranks partition the shards: disjoint and together complete
471+
let r0 = ids(StreamingLoader::new(shards.clone(), 4, 10, 9).rank(0, 2).epoch(3));
472+
let r1 = ids(StreamingLoader::new(shards.clone(), 4, 10, 9).rank(1, 2).epoch(3));
473+
assert!(r0.iter().all(|v| !r1.contains(v)));
474+
let mut all: Vec<i64> = [r0, r1].concat();
475+
all.sort_unstable();
476+
assert_eq!(all, (0..35).collect::<Vec<i64>>());
477+
// resume at batch 3 gives the tail of the full epoch; drop_last drops the short batch
478+
let full: Vec<Vec<i64>> = l.epoch(2).map(|b| b.unwrap().1.to_vec::<f32>().unwrap().into_iter().map(|v| v as i64).collect()).collect();
479+
let tail: Vec<Vec<i64>> = l.epoch_from(2, 3).map(|b| b.unwrap().1.to_vec::<f32>().unwrap().into_iter().map(|v| v as i64).collect()).collect();
480+
assert_eq!(tail, full[3..].to_vec());
481+
assert_eq!(full.len(), 9);
482+
assert_eq!(StreamingLoader::new(shards, 4, 10, 9).drop_last(true).epoch(2).count(), 8);
483+
}
484+
320485
#[test]
321486
fn npy_rows_are_read_lazily_from_disk() {
322487
let dir = std::env::temp_dir().join("oxideon_npy_ds_test");

0 commit comments

Comments
 (0)