Skip to main content

oa/data/
dataset.rs

1//! Dataset values, batch iteration, and stateless dataset operations.
2//!
3//! Donor: `oa/data/dataset.h`, `oa/data/dsSubset.h`, `oa/data/fnDataset.h`
4
5pub use super::types::{DataLoaderConfig, SplitResult};
6pub use crate::data::types::Batch;
7use crate::{DType, Error, Matrix, Result, Runtime, matrix};
8use std::sync::{Arc, mpsc};
9use std::thread::JoinHandle;
10
11/// Multi-tensor sample: input `x` and optional label `y`.
12///
13/// Corresponds to `oa::Dataset::Sample`.
14pub struct Sample {
15	/// Input value.
16	pub x: Matrix,
17	/// Label / target value.  `None` when the dataset has no labels.
18	pub y: Option<Matrix>,
19}
20
21impl Sample {
22	/// Construct an unlabeled sample.
23	pub fn new(x: Matrix) -> Self {
24		Self { x, y: None }
25	}
26
27	/// Construct a labeled sample.
28	pub fn new_with_label(x: Matrix, y: Matrix) -> Self {
29		Self { x, y: Some(y) }
30	}
31
32	/// Return `true` when a label is present.
33	pub fn has_label(&self) -> bool {
34		self.y.is_some()
35	}
36}
37
38/// Object-safe dataset contract: indexed access and a total count.
39///
40/// Corresponds to the C++ pure-virtual `oa::Dataset` base class.
41pub trait Dataset {
42	/// Total number of items in the dataset.
43	fn len(&self) -> i64;
44
45	/// Return `true` when the dataset contains no items.
46	fn is_empty(&self) -> bool {
47		self.len() == 0
48	}
49
50	/// Retrieve one sample by index.
51	///
52	/// The default implementation wraps [`Dataset::get_item`] for single-output
53	/// datasets.  Override to return a labeled sample.
54	fn get_sample(&self, index: i64) -> Result<Sample> {
55		Ok(Sample::new(self.get_item(index)?))
56	}
57
58	/// Retrieve and collate the given sample indices in order.
59	///
60	/// # Errors
61	///
62	/// Returns sample or collation errors.
63	fn get_batch(&self, indices: &[i64]) -> Result<Batch> {
64		let samples = indices
65			.iter()
66			.map(|&index| self.get_sample(index))
67			.collect::<Result<Vec<_>>>()?;
68		collate(&samples)
69	}
70
71	/// Retrieve one input `Matrix` by index.
72	fn get_item(&self, index: i64) -> Result<Matrix>;
73
74	/// Return a zero-copy indexed view over this dataset.
75	///
76	/// Corresponds to `oa::DsSubset`.
77	///
78	/// # Errors
79	///
80	/// Returns an error for a negative parent length or an out-of-range index.
81	fn subset(&self, indices: Vec<i64>) -> Result<Subset<'_>>
82	where
83		Self: Sized,
84	{
85		Subset::new(self, indices)
86	}
87
88	/// Return a zero-copy view over every item in deterministic [`shuffle`]
89	/// order. A nonzero seed reproduces the same permutation on each call.
90	///
91	/// # Errors
92	///
93	/// Returns the index-building, shuffle, and subset errors of the pieces
94	/// it composes.
95	fn shuffled_subset(&self, seed: u64) -> Result<Subset<'_>>
96	where
97		Self: Sized,
98	{
99		let mut indices = make_indices(checked_len(self)?)?;
100		shuffle(&mut indices, seed)?;
101		self.subset(indices)
102	}
103}
104
105/// Dense labeled feature/label pair implementing [`Dataset`].
106///
107/// `x` is a rank-≥1 `[N, ...]` F32 feature matrix and `y` a `[N]` F32
108/// label vector on the same runtime. `get_item` returns the rank-(N-1)
109/// feature slice; `get_sample` pairs it with the `[1]` label slice —
110/// the contract [`DataLoader`]/[`collate`] expect for labeled corpora.
111/// Dataset packs and synthetic benchmarks build their `Dataset` impl on
112/// this type instead of repeating bounds, slice, and pairing logic.
113pub struct MatrixDataset {
114	x: Matrix,
115	y: Matrix,
116}
117
118impl MatrixDataset {
119	/// Wrap caller-owned matrices as a labeled dataset.
120	///
121	/// `x` must have a leading sample dimension and `y` must be rank-1
122	/// with the same leading count; both must be F32 on one runtime —
123	/// [`matrix::slice`] is F32-only.
124	///
125	/// # Errors
126	///
127	/// Returns an error for a rank-0 feature matrix, non-vector labels,
128	/// mismatched leading counts, non-F32 dtypes, or matrices owned by
129	/// different runtimes.
130	pub fn new(x: Matrix, y: Matrix) -> Result<Self> {
131		if x.shape().is_empty() || y.shape().len() != 1 || x.shape()[0] != y.shape()[0] {
132			return Err(Error::invalid_argument(
133				"matrix dataset requires [N, ...] features and [N] labels with equal counts",
134			));
135		}
136		if x.dtype() != crate::DType::F32 || y.dtype() != crate::DType::F32 {
137			return Err(Error::invalid_argument(
138				"matrix dataset requires F32 features and labels",
139			));
140		}
141		if !x.same_runtime(&y) {
142			return Err(Error::invalid_argument(
143				"matrix dataset features and labels must share one runtime",
144			));
145		}
146		Ok(Self { x, y })
147	}
148
149	/// Full `[N, ...]` feature matrix on the owning runtime.
150	#[must_use]
151	pub const fn x(&self) -> &Matrix {
152		&self.x
153	}
154
155	/// Full `[N]` label matrix on the owning runtime.
156	#[must_use]
157	pub const fn y(&self) -> &Matrix {
158		&self.y
159	}
160}
161
162impl Dataset for MatrixDataset {
163	fn len(&self) -> i64 {
164		i64::try_from(self.x.shape()[0]).unwrap_or(i64::MAX)
165	}
166
167	fn get_item(&self, index: i64) -> Result<Matrix> {
168		if index < 0 || index >= self.len() {
169			return Err(Error::out_of_range(
170				"matrix dataset index is outside the dataset",
171			));
172		}
173		matrix::slice(&self.x, 0, index, index + 1)?.squeeze(0)
174	}
175
176	fn get_sample(&self, index: i64) -> Result<Sample> {
177		let x = self.get_item(index)?;
178		let y = matrix::slice(&self.y, 0, index, index + 1)?;
179		Ok(Sample::new_with_label(x, y))
180	}
181}
182
183/// Zero-copy indexed view returned by [`Dataset::subset`].
184///
185/// Used for train/val/test splits, subsampling, and index filtering.
186/// `get_item(i)` forwards to `parent.get_item(indices[i])` without copying data.
187///
188/// Corresponds to `oa::DsSubset`.
189pub struct Subset<'ds> {
190	parent: &'ds dyn Dataset,
191	indices: Vec<i64>,
192}
193
194impl<'ds> Subset<'ds> {
195	/// Borrow a dataset, including a trait object, with checked parent indices.
196	///
197	/// # Errors
198	///
199	/// Returns an error for a negative parent length or an out-of-range index.
200	pub fn new(parent: &'ds dyn Dataset, indices: Vec<i64>) -> Result<Self> {
201		let count = checked_len(parent)?;
202		if indices.iter().any(|&index| index < 0 || index >= count) {
203			return Err(Error::out_of_range(
204				"subset index is outside the parent dataset",
205			));
206		}
207		Ok(Self { parent, indices })
208	}
209
210	fn parent_index(&self, index: i64) -> Result<i64> {
211		usize::try_from(index)
212			.ok()
213			.and_then(|index| self.indices.get(index))
214			.copied()
215			.ok_or_else(|| Error::out_of_range("index is outside the subset"))
216	}
217
218	/// Read-only view of the stored index list.
219	pub fn indices(&self) -> &[i64] {
220		&self.indices
221	}
222
223	/// Borrow the parent dataset.
224	pub fn parent(&self) -> &dyn Dataset {
225		self.parent
226	}
227}
228
229impl Dataset for Subset<'_> {
230	fn len(&self) -> i64 {
231		self.indices.len() as i64
232	}
233
234	fn get_item(&self, index: i64) -> Result<Matrix> {
235		self.parent.get_item(self.parent_index(index)?)
236	}
237
238	fn get_sample(&self, index: i64) -> Result<Sample> {
239		self.parent.get_sample(self.parent_index(index)?)
240	}
241}
242
243impl Batch {
244	/// Return `true` when the batch contains at least one sample.
245	pub fn is_valid(&self) -> bool {
246		self.x.num_elements() > 0
247	}
248}
249
250/// Stateful batch iterator over a borrowed [`Dataset`].
251///
252/// Corresponds to `oa::DataLoader`.
253pub struct DataLoader<'ds> {
254	dataset: DatasetSource<'ds>,
255	config: DataLoaderConfig,
256	indices: Vec<i64>,
257	current_batch: i64,
258}
259
260enum DatasetSource<'ds> {
261	Borrowed(&'ds dyn Dataset),
262	Owned(Box<dyn Dataset + 'ds>),
263}
264
265impl DatasetSource<'_> {
266	fn get(&self) -> &dyn Dataset {
267		match self {
268			Self::Borrowed(dataset) => *dataset,
269			Self::Owned(dataset) => dataset.as_ref(),
270		}
271	}
272}
273
274struct ClassificationDataset {
275	runtime: Runtime,
276	input: Matrix,
277	rows: Matrix,
278	start: usize,
279	labels: Vec<u32>,
280}
281
282impl Dataset for ClassificationDataset {
283	fn len(&self) -> i64 {
284		self.labels.len() as i64
285	}
286
287	fn get_item(&self, index: i64) -> Result<Matrix> {
288		let batch = self.get_batch(&[index])?;
289		batch.x.squeeze(0)
290	}
291
292	fn get_sample(&self, index: i64) -> Result<Sample> {
293		let batch = self.get_batch(&[index])?;
294		Ok(Sample {
295			x: batch.x.squeeze(0)?,
296			y: batch.y,
297		})
298	}
299
300	fn get_batch(&self, indices: &[i64]) -> Result<Batch> {
301		let mut rows = Vec::with_capacity(indices.len());
302		let mut labels = Vec::with_capacity(indices.len());
303		for &index in indices {
304			let row = u32::try_from(index)
305				.map_err(|_| Error::out_of_range("classification batch index is invalid"))?;
306			let label = self
307				.labels
308				.get(row as usize)
309				.ok_or_else(|| Error::out_of_range("classification batch index is outside the dataset"))?;
310			rows.push(row + self.start as u32);
311			labels.push(*label);
312		}
313		let shape = [rows.len()];
314		let indices = Matrix::new_from_slice_on(&self.runtime, shape, &rows)?;
315		let y = Matrix::new_from_slice_on(&self.runtime, shape, &labels)?;
316		let mut batch_shape = self.input.shape().to_vec();
317		batch_shape[0] = rows.len();
318		let x = self.rows.gather(&indices)?.reshape(batch_shape)?;
319		Ok(Batch { x, y: Some(y) })
320	}
321}
322
323impl DataLoader<'static> {
324	/// Batch dense FP32 inputs and host class indices with one device row gather.
325	///
326	/// The input is `[N, ...]`. Each output target is a U32 vector with one
327	/// class index per sample. Shuffle, epoch seeds and partial batches follow
328	/// the ordinary loader configuration.
329	///
330	/// # Errors
331	///
332	/// Returns an error for invalid shape, count, runtime ownership or loader configuration.
333	pub fn classification(
334		runtime: &Runtime,
335		input: Matrix,
336		labels: Vec<u32>,
337		config: DataLoaderConfig,
338	) -> Result<Self> {
339		if input.shape().first() != Some(&labels.len()) {
340			return Err(Error::invalid_argument(
341				"classification inputs and labels must have the same sample count",
342			));
343		}
344		Self::classification_subset(runtime, input, 0, labels, config)
345	}
346
347	/// Batch a contiguous subset of a shared dense input without copying the split.
348	///
349	/// Labels correspond to the rows beginning at `start`. Shuffle and epoch
350	/// reset apply to those rows only.
351	///
352	/// # Errors
353	///
354	/// Returns an error for invalid shape, range, runtime ownership, or loader configuration.
355	pub fn classification_subset(
356		runtime: &Runtime,
357		input: Matrix,
358		start: usize,
359		labels: Vec<u32>,
360		config: DataLoaderConfig,
361	) -> Result<Self> {
362		let count = input.shape().first().copied().unwrap_or(0);
363		if labels.is_empty()
364			|| count > u32::MAX as usize
365			|| start
366				.checked_add(labels.len())
367				.is_none_or(|end| end > count)
368			|| input.dtype() != crate::DType::F32
369			|| !runtime.owns_matrix(&input)
370			|| input.num_elements() == 0
371		{
372			return Err(Error::invalid_argument(
373				"classification loader requires a nonempty range with matching labels and FP32 inputs on the selected runtime",
374			));
375		}
376
377		let rows = input.reshape([count, input.num_elements() / count])?;
378		Self::from_source(
379			DatasetSource::Owned(Box::new(ClassificationDataset {
380				runtime: runtime.clone(),
381				input,
382				rows,
383				start,
384				labels,
385			})),
386			config,
387		)
388	}
389}
390
391impl<'ds> DataLoader<'ds> {
392	/// Construct a data loader and build the initial index order.
393	///
394	/// # Errors
395	///
396	/// Returns an error for a non-positive batch size, a negative dataset length,
397	/// index allocation failure, or an unavailable clock for seed zero.
398	pub fn new(dataset: &'ds dyn Dataset, config: DataLoaderConfig) -> Result<Self> {
399		Self::from_source(DatasetSource::Borrowed(dataset), config)
400	}
401
402	fn from_source(dataset: DatasetSource<'ds>, config: DataLoaderConfig) -> Result<Self> {
403		if config.batch_size <= 0 {
404			return Err(Error::invalid_argument(
405				"data loader batch size must be positive",
406			));
407		}
408		let mut loader = Self {
409			dataset,
410			config,
411			indices: Vec::new(),
412			current_batch: 0,
413		};
414		loader.reset()?;
415		Ok(loader)
416	}
417
418	/// Advance to the next batch; `None` means the epoch is exhausted.
419	///
420	/// # Errors
421	///
422	/// Sample and collation failures are propagated without dropping samples or
423	/// advancing the batch cursor. A caller may retry or explicitly reset.
424	pub fn next_batch(&mut self) -> Result<Option<Batch>> {
425		if self.current_batch >= self.num_batches() {
426			return Ok(None);
427		}
428		// The cursor is below num_batches, so start is inside the allocated index list.
429		let start = self.current_batch as usize * self.config.batch_size as usize;
430		let count = (self.config.batch_size as usize).min(self.indices.len() - start);
431		let batch = self
432			.dataset
433			.get()
434			.get_batch(&self.indices[start..start + count])?;
435		self.current_batch += 1;
436		Ok(Some(batch))
437	}
438
439	/// Reset the epoch, rebuilding its index order from the configured seed.
440	///
441	/// Nonzero seeds reproduce the same order on every reset, matching the donor.
442	///
443	/// # Errors
444	///
445	/// Returns the index-building errors described by [`Self::new`]. A failed
446	/// reset leaves the existing order and cursor unchanged.
447	pub fn reset(&mut self) -> Result<()> {
448		let mut indices = make_indices(checked_len(self.dataset.get())?)?;
449		if self.config.shuffle {
450			shuffle(&mut indices, self.config.seed)?;
451		}
452		self.indices = indices;
453		self.current_batch = 0;
454		Ok(())
455	}
456
457	/// Reset for a new data pass, deriving the shuffle order from the
458	/// configured seed mixed with the epoch number so each epoch iterates a
459	/// different deterministic order — the equivalent of reshuffling a
460	/// dataset between epochs. `reset_epoch(0)` reproduces [`Self::reset`].
461	///
462	/// # Errors
463	///
464	/// Returns the index-building errors described by [`Self::new`]. A failed
465	/// reset leaves the existing order and cursor unchanged.
466	pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
467		let mut indices = make_indices(checked_len(self.dataset.get())?)?;
468		if self.config.shuffle {
469			shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
470		}
471		self.indices = indices;
472		self.current_batch = 0;
473		Ok(())
474	}
475
476	/// Number of batches in the current epoch.
477	pub fn num_batches(&self) -> i64 {
478		let n = self.indices.len() as i64;
479		let b = i64::from(self.config.batch_size);
480		n / b + i64::from(!self.config.drop_last && n % b != 0)
481	}
482
483	/// Index of the next batch that will be returned.
484	pub fn current_batch(&self) -> i64 {
485		self.current_batch
486	}
487
488	/// Restore a recorded loader position: rebuild the deterministic shuffle
489	/// order for `epoch` exactly as [`Self::reset_epoch`] would, then place the
490	/// batch cursor at `cursor`. Together with the configured seed this
491	/// reproduces the exact sample sequence a checkpointed run would have
492	/// consumed next, which is the loader half of exact training resume.
493	/// `cursor` may equal the epoch's batch count, denoting an exhausted epoch.
494	///
495	/// # Errors
496	///
497	/// Returns the index-building errors described by [`Self::new`], or an
498	/// invalid-argument error when `cursor` exceeds the epoch's batch count.
499	/// A failed seek leaves the existing order and cursor unchanged.
500	pub fn seek(&mut self, epoch: u64, cursor: i64) -> Result<()> {
501		let mut indices = make_indices(checked_len(self.dataset.get())?)?;
502		if self.config.shuffle {
503			shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
504		}
505		let n = indices.len() as i64;
506		let b = i64::from(self.config.batch_size);
507		let num_batches = n / b + i64::from(!self.config.drop_last && n % b != 0);
508		if cursor < 0 || cursor > num_batches {
509			return Err(Error::invalid_argument(
510				"data loader seek cursor outside the epoch",
511			));
512		}
513		self.indices = indices;
514		self.current_batch = cursor;
515		Ok(())
516	}
517}
518
519/// Fisher-Yates shuffle using the donor's PCG32 stream and unbiased rejection.
520///
521/// A nonzero seed reproduces the C++ `oa::Random(seed)` permutation. Zero uses
522/// the system clock. This generator is for sampling, not cryptography.
523///
524/// # Errors
525///
526/// Returns an error when seed zero cannot be derived from the system clock.
527pub fn shuffle(indices: &mut [i64], seed: u64) -> Result<()> {
528	if indices.len() < 2 {
529		return Ok(());
530	}
531	let seed = if seed == 0 {
532		use std::time::{SystemTime, UNIX_EPOCH};
533		SystemTime::now()
534			.duration_since(UNIX_EPOCH)
535			.map_err(|_| Error::failed_precondition("dataset shuffle clock precedes Unix epoch"))?
536			.as_nanos() as u64
537	} else {
538		seed
539	};
540	let mut rng = Pcg32::new(seed);
541	for count in (2..=indices.len()).rev() {
542		let range = count as u64;
543		let reject = range.wrapping_neg() % range;
544		let value = loop {
545			let value = rng.next_u64();
546			if value >= reject {
547				break value;
548			}
549		};
550		indices.swap(count - 1, (value % range) as usize);
551	}
552	Ok(())
553}
554
555/// Randomly split indices into train, validation, and test subsets.
556///
557/// Matches donor `FnDataset::randomSplit`: clamp train to `[0, 1]` and validation
558/// to `[0, 1 - train]`, truncate their FP32 counts, and assign the remainder to
559/// test. The donor header's claim that the remainder goes to train contradicts
560/// its implementation; this port follows the implementation.
561///
562/// # Errors
563///
564/// Returns an error for a negative size, non-finite ratios, allocation failure,
565/// or failure to derive a clock seed when seed is zero.
566pub fn random_split(
567	total_size: i64,
568	train_ratio: f32,
569	val_ratio: f32,
570	seed: u64,
571) -> Result<SplitResult> {
572	if !train_ratio.is_finite() || !val_ratio.is_finite() {
573		return Err(Error::invalid_argument(
574			"dataset split ratios must be finite",
575		));
576	}
577	let mut all = make_indices(total_size)?;
578	let train_ratio = train_ratio.clamp(0.0, 1.0);
579	let val_ratio = val_ratio.clamp(0.0, 1.0 - train_ratio);
580	let n = all.len();
581	let train_count = ((n as f32 * train_ratio) as usize).min(n);
582	let val_count = ((n as f32 * val_ratio) as usize).min(n - train_count);
583	shuffle(&mut all, seed)?;
584	let test = all.split_off(train_count + val_count);
585	let val = all.split_off(train_count);
586	Ok(SplitResult {
587		train: all,
588		val,
589		test,
590	})
591}
592
593/// Stack samples into a leading batch dimension using device-side concatenation.
594///
595/// Inputs must be nonempty matrices of rank at most three, with any admitted
596/// Matrix dtype (U8, F32, I32, or U32). Labels must be present on every sample or
597/// absent on every sample. Each component must have equal shapes, dtypes, and
598/// one runtime owner. A one-sample batch reuses its Matrix storage through
599/// zero-copy views. No default Runtime or host readback is used.
600///
601/// # Errors
602///
603/// Returns an error for empty input, inconsistent samples, unsupported rank,
604/// allocation failure, or GPU recording failure.
605pub fn collate(samples: &[Sample]) -> Result<Batch> {
606	let first = samples
607		.first()
608		.ok_or_else(|| Error::invalid_argument("collate requires at least one sample"))?;
609	for sample in samples {
610		validate_component(&sample.x, &first.x)?;
611		match (&sample.y, &first.y) {
612			(Some(value), Some(reference)) => {
613				validate_component(value, reference)?;
614				if !value.runtime().same_as(first.x.runtime()) {
615					return Err(Error::invalid_argument(
616						"collate inputs and labels must share one runtime",
617					));
618				}
619			}
620			(None, None) => {}
621			_ => {
622				return Err(Error::invalid_argument(
623					"collate label presence must match for every sample",
624				));
625			}
626		}
627	}
628	if let [only] = samples {
629		return Ok(Batch {
630			x: only.x.unsqueeze(0)?,
631			y: only
632				.y
633				.as_ref()
634				.map(|value| value.unsqueeze(0))
635				.transpose()?,
636		});
637	}
638	let x_views = samples
639		.iter()
640		.map(|sample| sample.x.unsqueeze(0))
641		.collect::<Result<Vec<_>>>()?;
642	let y_views = samples
643		.iter()
644		.filter_map(|sample| sample.y.as_ref())
645		.map(|value| value.unsqueeze(0))
646		.collect::<Result<Vec<_>>>()?;
647	let x = matrix::concat(&x_views, 0)?;
648	let y = if y_views.is_empty() {
649		None
650	} else {
651		Some(matrix::concat(&y_views, 0)?)
652	};
653	Ok(Batch { x, y })
654}
655
656fn validate_component(value: &Matrix, reference: &Matrix) -> Result<()> {
657	if value.shape().len() > 3 {
658		return Err(Error::invalid_argument(
659			"collate requires samples of rank at most three",
660		));
661	}
662	if value.num_elements() == 0
663		|| value.shape() != reference.shape()
664		|| value.dtype() != reference.dtype()
665		|| !value.runtime().same_as(reference.runtime())
666	{
667		return Err(Error::invalid_argument(
668			"collate requires nonempty, same-shape, same-dtype, same-runtime components",
669		));
670	}
671	Ok(())
672}
673
674fn checked_len(dataset: &dyn Dataset) -> Result<i64> {
675	let count = dataset.len();
676	if count < 0 {
677		return Err(Error::invalid_argument(
678			"dataset length must be nonnegative",
679		));
680	}
681	Ok(count)
682}
683
684fn make_indices(count: i64) -> Result<Vec<i64>> {
685	let length = usize::try_from(count)
686		.map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
687	let mut indices = Vec::new();
688	indices
689		.try_reserve_exact(length)
690		.map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
691	indices.extend(0..count);
692	Ok(indices)
693}
694
695// Donor: oa/core/std/random.h, Random. Mechanical integer/ownership adaptation;
696// retain its PCG32 sequence=1 and two-draw nextU64 order for seed compatibility.
697struct Pcg32 {
698	state: u64,
699}
700
701impl Pcg32 {
702	fn new(seed: u64) -> Self {
703		let mut rng = Self { state: 0 };
704		rng.next_u32();
705		rng.state = rng.state.wrapping_add(seed);
706		rng.next_u32();
707		rng
708	}
709
710	fn next_u32(&mut self) -> u32 {
711		let old = self.state;
712		self.state = old.wrapping_mul(6364136223846793005).wrapping_add(3);
713		// Truncation to 32 bits is part of the donor PCG permutation.
714		let shifted = (((old >> 18) ^ old) >> 27) as u32;
715		shifted.rotate_right((old >> 59) as u32)
716	}
717
718	fn next_u64(&mut self) -> u64 {
719		(u64::from(self.next_u32()) << 32) | u64::from(self.next_u32())
720	}
721}
722
723// ---- Async prefetch ---------------------------------------------------------
724
725/// Typed host values carried by worker-produced samples and batches.
726///
727/// The runtime and `Matrix` are `!Send`, so prefetch production happens on
728/// host values; the consumer uploads a collated [`HostBatch`] on its own
729/// thread. Variants cover the admitted dataset element types; `F16` host
730/// staging is not admitted because host readback never produces half values.
731#[derive(Clone, Debug)]
732pub enum HostValues {
733	/// F32 elements.
734	F32(Vec<f32>),
735	/// U32 elements.
736	U32(Vec<u32>),
737	/// I32 elements.
738	I32(Vec<i32>),
739	/// U8 elements.
740	U8(Vec<u8>),
741}
742
743impl HostValues {
744	fn dtype(&self) -> DType {
745		match self {
746			Self::F32(_) => DType::F32,
747			Self::U32(_) => DType::U32,
748			Self::I32(_) => DType::I32,
749			Self::U8(_) => DType::U8,
750		}
751	}
752
753	fn len(&self) -> usize {
754		match self {
755			Self::F32(values) => values.len(),
756			Self::U32(values) => values.len(),
757			Self::I32(values) => values.len(),
758			Self::U8(values) => values.len(),
759		}
760	}
761
762	fn slice(&self, start: usize, count: usize) -> Self {
763		match self {
764			Self::F32(values) => Self::F32(values[start..start + count].to_vec()),
765			Self::U32(values) => Self::U32(values[start..start + count].to_vec()),
766			Self::I32(values) => Self::I32(values[start..start + count].to_vec()),
767			Self::U8(values) => Self::U8(values[start..start + count].to_vec()),
768		}
769	}
770
771	fn concat(parts: &[&Self]) -> Result<Self> {
772		let first = parts
773			.first()
774			.ok_or_else(|| Error::invalid_argument("host concat requires a part"))?;
775		Ok(match first {
776			Self::F32(_) => {
777				let mut values = Vec::new();
778				for part in parts {
779					let Self::F32(part) = part else {
780						return Err(Error::invalid_argument(
781							"host concat requires one dtype across parts",
782						));
783					};
784					values.extend_from_slice(part);
785				}
786				Self::F32(values)
787			}
788			Self::U32(_) => {
789				let mut values = Vec::new();
790				for part in parts {
791					let Self::U32(part) = part else {
792						return Err(Error::invalid_argument(
793							"host concat requires one dtype across parts",
794						));
795					};
796					values.extend_from_slice(part);
797				}
798				Self::U32(values)
799			}
800			Self::I32(_) => {
801				let mut values = Vec::new();
802				for part in parts {
803					let Self::I32(part) = part else {
804						return Err(Error::invalid_argument(
805							"host concat requires one dtype across parts",
806						));
807					};
808					values.extend_from_slice(part);
809				}
810				Self::I32(values)
811			}
812			Self::U8(_) => {
813				let mut values = Vec::new();
814				for part in parts {
815					let Self::U8(part) = part else {
816						return Err(Error::invalid_argument(
817							"host concat requires one dtype across parts",
818						));
819					};
820					values.extend_from_slice(part);
821				}
822				Self::U8(values)
823			}
824		})
825	}
826}
827
828/// A dense tensor living in host memory.
829///
830/// Shape semantics match `Matrix`: `num_elements` is the shape product and
831/// `shape[0]` is the leading (sample or batch) dimension.
832#[derive(Clone, Debug)]
833pub struct HostTensor {
834	/// Logical shape.
835	pub shape: Vec<usize>,
836	/// Element values in row-major order.
837	pub values: HostValues,
838}
839
840impl HostTensor {
841	/// Construct a host tensor, checking the element count against the shape.
842	///
843	/// # Errors
844	///
845	/// Returns an error when the shape product overflows or differs from the
846	/// value count.
847	pub fn new(shape: impl Into<Vec<usize>>, values: HostValues) -> Result<Self> {
848		let tensor = Self {
849			shape: shape.into(),
850			values,
851		};
852		tensor.check_count()?;
853		Ok(tensor)
854	}
855
856	/// Element count implied by the shape.
857	pub fn num_elements(&self) -> usize {
858		self.shape.iter().product()
859	}
860
861	/// Element dtype.
862	pub fn dtype(&self) -> DType {
863		self.values.dtype()
864	}
865
866	fn check_count(&self) -> Result<()> {
867		if self.num_elements() != self.values.len() {
868			return Err(Error::invalid_argument(
869				"host tensor shape and value count disagree",
870			));
871		}
872		Ok(())
873	}
874
875	/// Upload to `runtime`, producing a device `Matrix`.
876	///
877	/// # Errors
878	///
879	/// Returns an error when storage allocation or upload fails.
880	pub fn to_matrix_on(&self, runtime: &Runtime) -> Result<Matrix> {
881		self.check_count()?;
882		match &self.values {
883			HostValues::F32(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
884			HostValues::U32(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
885			HostValues::I32(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
886			HostValues::U8(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
887		}
888	}
889}
890
891/// Host-side sample: input `x` and optional label `y`, as produced by
892/// [`HostDataset::get_host_sample`].
893#[derive(Clone, Debug)]
894pub struct HostSample {
895	/// Input value.
896	pub x: HostTensor,
897	/// Label / target value, absent for unlabeled datasets.
898	pub y: Option<HostTensor>,
899}
900
901/// Collated host batch: `[B, ...]` tensors stacked along a new leading axis.
902#[derive(Clone, Debug)]
903pub struct HostBatch {
904	/// Batched inputs.
905	pub x: HostTensor,
906	/// Batched labels, present iff every sample carried one.
907	pub y: Option<HostTensor>,
908}
909
910impl HostBatch {
911	/// Upload both components to `runtime`, producing a device [`Batch`].
912	///
913	/// # Errors
914	///
915	/// Returns an error when storage allocation or upload fails.
916	pub fn upload_on(&self, runtime: &Runtime) -> Result<Batch> {
917		Ok(Batch {
918			x: self.x.to_matrix_on(runtime)?,
919			y: self
920				.y
921				.as_ref()
922				.map(|label| label.to_matrix_on(runtime))
923				.transpose()?,
924		})
925	}
926}
927
928/// Collate host samples into one `[B, ...]` batch.
929///
930/// Mirrors [`collate`]: identical per-sample shapes and dtypes are required,
931/// and label presence must match across the batch.
932///
933/// # Errors
934///
935/// Returns an error for an empty sample list or mismatched components.
936pub fn collate_host(samples: &[HostSample]) -> Result<HostBatch> {
937	let first = samples
938		.first()
939		.ok_or_else(|| Error::invalid_argument("collate_host requires at least one sample"))?;
940	for sample in samples {
941		validate_host_component(&sample.x, &first.x)?;
942		match (&sample.y, &first.y) {
943			(Some(value), Some(reference)) => validate_host_component(value, reference)?,
944			(None, None) => {}
945			_ => {
946				return Err(Error::invalid_argument(
947					"collate_host label presence must match for every sample",
948				));
949			}
950		}
951	}
952	let stack = |tensors: Vec<&HostTensor>| -> Result<HostTensor> {
953		let mut shape = tensors[0].shape.clone();
954		shape.insert(0, tensors.len());
955		HostTensor::new(
956			shape,
957			HostValues::concat(
958				&tensors
959					.iter()
960					.map(|tensor| &tensor.values)
961					.collect::<Vec<_>>(),
962			)?,
963		)
964	};
965	Ok(HostBatch {
966		x: stack(samples.iter().map(|sample| &sample.x).collect())?,
967		y: samples
968			.iter()
969			.filter_map(|sample| sample.y.as_ref())
970			.collect::<Vec<_>>()
971			.split_first()
972			.map(|_| stack(samples.iter().filter_map(|s| s.y.as_ref()).collect()))
973			.transpose()?,
974	})
975}
976
977fn validate_host_component(value: &HostTensor, reference: &HostTensor) -> Result<()> {
978	if value.num_elements() == 0
979		|| value.shape != reference.shape
980		|| value.dtype() != reference.dtype()
981	{
982		return Err(Error::invalid_argument(
983			"collate_host requires nonempty, same-shape, same-dtype components",
984		));
985	}
986	Ok(())
987}
988
989/// Thread-shareable host dataset contract for [`PrefetchDataLoader`].
990///
991/// `Runtime` is `!Send`, so async prefetch runs on host values: worker
992/// threads index a `HostDataset`, collate host-side, and the consumer
993/// thread uploads each batch to the device — the same split as
994/// `DataLoader(num_workers>0, pin_memory=True)` in torch, where workers
995/// also produce host tensors.
996pub trait HostDataset: Send + Sync {
997	/// Total number of items in the dataset.
998	fn len(&self) -> i64;
999
1000	/// Return `true` when the dataset contains no items.
1001	fn is_empty(&self) -> bool {
1002		self.len() == 0
1003	}
1004
1005	/// Retrieve one host sample by index.
1006	///
1007	/// # Errors
1008	///
1009	/// Returns an error for an out-of-range index or a failed read.
1010	fn get_host_sample(&self, index: i64) -> Result<HostSample>;
1011}
1012
1013/// Dense labeled feature/label pair implementing [`HostDataset`].
1014///
1015/// `x` is a rank-≥1 `[N, ...]` host tensor and `y` a `[N]` label vector
1016/// with the same leading count and dtype class as [`collate_host`]
1017/// accepts. `get_host_sample` slices along the leading axis.
1018pub struct HostTensorDataset {
1019	x: HostTensor,
1020	y: HostTensor,
1021}
1022
1023impl HostTensorDataset {
1024	/// Wrap caller-owned host tensors as a labeled dataset.
1025	///
1026	/// # Errors
1027	///
1028	/// Returns an error for a rank-0 feature tensor, non-vector labels, or
1029	/// mismatched leading counts.
1030	pub fn new(x: HostTensor, y: HostTensor) -> Result<Self> {
1031		if x.shape.is_empty() || y.shape.len() != 1 || x.shape[0] != y.shape[0] {
1032			return Err(Error::invalid_argument(
1033				"host tensor dataset requires [N, ...] features and [N] labels with equal counts",
1034			));
1035		}
1036		Ok(Self { x, y })
1037	}
1038
1039	/// Materialize a host mirror of F32 device matrices.
1040	///
1041	/// Reads `x` and `y` back once on the calling thread; afterwards the
1042	/// dataset is pure host data that prefetch workers may index without
1043	/// touching the runtime.
1044	///
1045	/// # Errors
1046	///
1047	/// Returns an error for a rank-0 feature matrix, non-vector labels,
1048	/// mismatched leading counts, or a failed readback.
1049	pub fn from_f32_matrices(x: &Matrix, y: &Matrix) -> Result<Self> {
1050		if x.shape().is_empty() || y.shape().len() != 1 || x.shape()[0] != y.shape()[0] {
1051			return Err(Error::invalid_argument(
1052				"host tensor dataset requires [N, ...] features and [N] labels with equal counts",
1053			));
1054		}
1055		Self::new(
1056			HostTensor::new(x.shape().to_vec(), HostValues::F32(x.read_f32()?))?,
1057			HostTensor::new(y.shape().to_vec(), HostValues::F32(y.read_f32()?))?,
1058		)
1059	}
1060}
1061
1062impl HostDataset for HostTensorDataset {
1063	fn len(&self) -> i64 {
1064		i64::try_from(self.x.shape[0]).unwrap_or(i64::MAX)
1065	}
1066
1067	fn get_host_sample(&self, index: i64) -> Result<HostSample> {
1068		let count = self.len();
1069		if index < 0 || index >= count {
1070			return Err(Error::invalid_argument(
1071				"host tensor dataset index out of range",
1072			));
1073		}
1074		let index = usize::try_from(index)
1075			.map_err(|_| Error::invalid_argument("host tensor dataset index out of range"))?;
1076		let stride: usize = self.x.shape[1..].iter().product();
1077		Ok(HostSample {
1078			x: HostTensor::new(
1079				self.x.shape[1..].to_vec(),
1080				self.x.values.slice(index * stride, stride),
1081			)?,
1082			y: Some(HostTensor::new(vec![1], self.y.values.slice(index, 1))?),
1083		})
1084	}
1085}
1086
1087/// Asynchronous batch iterator over a shared [`HostDataset`].
1088///
1089/// A single worker thread walks the epoch's index order, calls
1090/// `get_host_sample`, collates, and pushes [`HostBatch`] values into a
1091/// queue bounded at `prefetch_batches`. `next_batch` pops on the caller
1092/// thread, so sample production overlaps consumption; `next_batch_on`
1093/// additionally uploads the collated batch to the runtime. Shuffle order,
1094/// `drop_last`, and epoch resets share the [`DataLoader`] seed contract.
1095///
1096/// One worker is the admitted contract: the queue depth already decouples
1097/// production from consumption, and multi-worker partitioning would add
1098/// index ownership without changing the device boundary.
1099pub struct PrefetchDataLoader {
1100	dataset: Arc<dyn HostDataset>,
1101	config: DataLoaderConfig,
1102	prefetch_batches: usize,
1103	receiver: Option<mpsc::Receiver<Result<HostBatch>>>,
1104	worker: Option<JoinHandle<()>>,
1105	epoch: u64,
1106	current_batch: i64,
1107}
1108
1109impl PrefetchDataLoader {
1110	/// Construct a prefetching loader and start the epoch-0 worker.
1111	///
1112	/// # Errors
1113	///
1114	/// Returns an error for a non-positive batch size, a zero prefetch
1115	/// depth, a negative dataset length, or index allocation failure.
1116	pub fn new(
1117		dataset: Arc<dyn HostDataset>,
1118		config: DataLoaderConfig,
1119		prefetch_batches: usize,
1120	) -> Result<Self> {
1121		if config.batch_size <= 0 {
1122			return Err(Error::invalid_argument(
1123				"prefetch data loader batch size must be positive",
1124			));
1125		}
1126		if prefetch_batches == 0 {
1127			return Err(Error::invalid_argument(
1128				"prefetch data loader requires at least one queued batch",
1129			));
1130		}
1131		let mut loader = Self {
1132			dataset,
1133			config,
1134			prefetch_batches,
1135			receiver: None,
1136			worker: None,
1137			epoch: 0,
1138			current_batch: 0,
1139		};
1140		loader.spawn_epoch_from(0, 0)?;
1141		Ok(loader)
1142	}
1143
1144	/// Advance to the next host batch; `None` means the epoch is exhausted.
1145	///
1146	/// The call blocks only when the queue is empty and the worker is still
1147	/// producing; a worker-side failure is delivered once and ends the
1148	/// epoch.
1149	///
1150	/// # Errors
1151	///
1152	/// Returns the first worker-side sample or collation error.
1153	pub fn next_batch(&mut self) -> Result<Option<HostBatch>> {
1154		let Some(receiver) = &self.receiver else {
1155			return Ok(None);
1156		};
1157		match receiver.recv() {
1158			Ok(Ok(batch)) => {
1159				self.current_batch += 1;
1160				Ok(Some(batch))
1161			}
1162			Ok(Err(error)) => {
1163				self.receiver = None;
1164				Err(error)
1165			}
1166			Err(mpsc::RecvError) => {
1167				self.receiver = None;
1168				Ok(None)
1169			}
1170		}
1171	}
1172
1173	/// Pop the next batch and upload it to `runtime`.
1174	///
1175	/// # Errors
1176	///
1177	/// Returns worker errors plus upload failures.
1178	pub fn next_batch_on(&mut self, runtime: &Runtime) -> Result<Option<Batch>> {
1179		self
1180			.next_batch()?
1181			.map(|batch| batch.upload_on(runtime))
1182			.transpose()
1183	}
1184
1185	/// Reset for a new data pass, deriving the shuffle order from the
1186	/// configured seed mixed with the epoch number — matching
1187	/// [`DataLoader::reset_epoch`]. A new worker replaces the old one;
1188	/// queued batches from the previous epoch are discarded.
1189	///
1190	/// # Errors
1191	///
1192	/// Returns the index-building errors described by [`Self::new`].
1193	pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
1194		self.spawn_epoch_from(epoch, 0)
1195	}
1196
1197	/// Number of batches in the current epoch.
1198	pub fn num_batches(&self) -> i64 {
1199		let n = self.dataset.len().max(0);
1200		let b = i64::from(self.config.batch_size);
1201		n / b + i64::from(!self.config.drop_last && n % b != 0)
1202	}
1203
1204	/// Index of the next batch that will be returned.
1205	pub fn current_batch(&self) -> i64 {
1206		self.current_batch
1207	}
1208
1209	/// Restore a recorded loader position (`epoch`, `cursor`), matching
1210	/// [`DataLoader::seek`].
1211	///
1212	/// # Errors
1213	///
1214	/// Returns index-building errors or an invalid-argument error when
1215	/// `cursor` is outside `0..=num_batches()`. A failed seek leaves the
1216	/// existing worker and cursor unchanged.
1217	pub fn seek(&mut self, epoch: u64, cursor: i64) -> Result<()> {
1218		self.spawn_epoch_from(epoch, cursor)
1219	}
1220
1221	fn spawn_epoch_from(&mut self, epoch: u64, cursor: i64) -> Result<()> {
1222		let mut indices = make_indices_host(self.dataset.len())?;
1223		if self.config.shuffle {
1224			shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
1225		}
1226		let n = indices.len() as i64;
1227		let b = i64::from(self.config.batch_size);
1228		let num_batches = n / b + i64::from(!self.config.drop_last && n % b != 0);
1229		if cursor < 0 || cursor > num_batches {
1230			return Err(Error::invalid_argument(
1231				"prefetch data loader seek cursor outside the epoch",
1232			));
1233		}
1234		let (sender, receiver) = mpsc::sync_channel(self.prefetch_batches);
1235		let dataset = Arc::clone(&self.dataset);
1236		let batch_size = usize::try_from(self.config.batch_size)
1237			.map_err(|_| Error::invalid_argument("batch size must fit usize"))?;
1238		let start_index = (cursor as usize)
1239			.checked_mul(batch_size)
1240			.ok_or_else(|| Error::invalid_argument("prefetch data loader seek offset overflow"))?;
1241		let drop_last = self.config.drop_last;
1242		self.receiver = Some(receiver);
1243		self.worker = Some(std::thread::spawn(move || {
1244			let mut start = start_index;
1245			while start < indices.len() {
1246				let count = batch_size.min(indices.len() - start);
1247				if drop_last && count < batch_size {
1248					break;
1249				}
1250				let produced = indices[start..start + count]
1251					.iter()
1252					.map(|&index| dataset.get_host_sample(index))
1253					.collect::<Result<Vec<_>>>()
1254					.and_then(|samples| collate_host(&samples));
1255				let keep_going = produced.is_ok();
1256				if sender.send(produced).is_err() || !keep_going {
1257					return;
1258				}
1259				start += count;
1260			}
1261		}));
1262		self.epoch = epoch;
1263		self.current_batch = cursor;
1264		Ok(())
1265	}
1266}
1267
1268fn make_indices_host(count: i64) -> Result<Vec<i64>> {
1269	let length = usize::try_from(count)
1270		.map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
1271	let mut indices = Vec::new();
1272	indices
1273		.try_reserve_exact(length)
1274		.map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
1275	indices.extend(0..count);
1276	Ok(indices)
1277}