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