1pub 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
11pub struct Sample {
15 pub x: Matrix,
17 pub y: Option<Matrix>,
19}
20
21impl Sample {
22 pub fn new(x: Matrix) -> Self {
24 Self { x, y: None }
25 }
26
27 pub fn new_with_label(x: Matrix, y: Matrix) -> Self {
29 Self { x, y: Some(y) }
30 }
31
32 pub fn has_label(&self) -> bool {
34 self.y.is_some()
35 }
36}
37
38pub trait Dataset {
42 fn len(&self) -> i64;
44
45 fn is_empty(&self) -> bool {
47 self.len() == 0
48 }
49
50 fn get_sample(&self, index: i64) -> Result<Sample> {
55 Ok(Sample::new(self.get_item(index)?))
56 }
57
58 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 fn get_item(&self, index: i64) -> Result<Matrix>;
73
74 fn subset(&self, indices: Vec<i64>) -> Result<Subset<'_>>
82 where
83 Self: Sized,
84 {
85 Subset::new(self, indices)
86 }
87
88 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
105pub struct MatrixDataset {
114 x: Matrix,
115 y: Matrix,
116}
117
118impl MatrixDataset {
119 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 #[must_use]
151 pub const fn x(&self) -> &Matrix {
152 &self.x
153 }
154
155 #[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
183pub struct Subset<'ds> {
190 parent: &'ds dyn Dataset,
191 indices: Vec<i64>,
192}
193
194impl<'ds> Subset<'ds> {
195 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 pub fn indices(&self) -> &[i64] {
220 &self.indices
221 }
222
223 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 pub fn is_valid(&self) -> bool {
246 self.x.num_elements() > 0
247 }
248}
249
250pub 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 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 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 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 pub fn next_batch(&mut self) -> Result<Option<Batch>> {
425 if self.current_batch >= self.num_batches() {
426 return Ok(None);
427 }
428 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 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 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 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 pub fn current_batch(&self) -> i64 {
485 self.current_batch
486 }
487
488 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
519pub 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
555pub 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
593pub 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
695struct 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 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#[derive(Clone, Debug)]
732pub enum HostValues {
733 F32(Vec<f32>),
735 U32(Vec<u32>),
737 I32(Vec<i32>),
739 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#[derive(Clone, Debug)]
833pub struct HostTensor {
834 pub shape: Vec<usize>,
836 pub values: HostValues,
838}
839
840impl HostTensor {
841 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 pub fn num_elements(&self) -> usize {
858 self.shape.iter().product()
859 }
860
861 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 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#[derive(Clone, Debug)]
894pub struct HostSample {
895 pub x: HostTensor,
897 pub y: Option<HostTensor>,
899}
900
901#[derive(Clone, Debug)]
903pub struct HostBatch {
904 pub x: HostTensor,
906 pub y: Option<HostTensor>,
908}
909
910impl HostBatch {
911 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
928pub 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
989pub trait HostDataset: Send + Sync {
997 fn len(&self) -> i64;
999
1000 fn is_empty(&self) -> bool {
1002 self.len() == 0
1003 }
1004
1005 fn get_host_sample(&self, index: i64) -> Result<HostSample>;
1011}
1012
1013pub struct HostTensorDataset {
1019 x: HostTensor,
1020 y: HostTensor,
1021}
1022
1023impl HostTensorDataset {
1024 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 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
1087pub 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}
1107
1108impl PrefetchDataLoader {
1109 pub fn new(
1116 dataset: Arc<dyn HostDataset>,
1117 config: DataLoaderConfig,
1118 prefetch_batches: usize,
1119 ) -> Result<Self> {
1120 if config.batch_size <= 0 {
1121 return Err(Error::invalid_argument(
1122 "prefetch data loader batch size must be positive",
1123 ));
1124 }
1125 if prefetch_batches == 0 {
1126 return Err(Error::invalid_argument(
1127 "prefetch data loader requires at least one queued batch",
1128 ));
1129 }
1130 let mut loader = Self {
1131 dataset,
1132 config,
1133 prefetch_batches,
1134 receiver: None,
1135 worker: None,
1136 epoch: 0,
1137 };
1138 loader.spawn_epoch(0)?;
1139 Ok(loader)
1140 }
1141
1142 pub fn next_batch(&mut self) -> Result<Option<HostBatch>> {
1152 let Some(receiver) = &self.receiver else {
1153 return Ok(None);
1154 };
1155 match receiver.recv() {
1156 Ok(Ok(batch)) => Ok(Some(batch)),
1157 Ok(Err(error)) => {
1158 self.receiver = None;
1159 Err(error)
1160 }
1161 Err(mpsc::RecvError) => {
1162 self.receiver = None;
1163 Ok(None)
1164 }
1165 }
1166 }
1167
1168 pub fn next_batch_on(&mut self, runtime: &Runtime) -> Result<Option<Batch>> {
1174 self
1175 .next_batch()?
1176 .map(|batch| batch.upload_on(runtime))
1177 .transpose()
1178 }
1179
1180 pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
1189 self.spawn_epoch(epoch)
1190 }
1191
1192 pub fn num_batches(&self) -> i64 {
1194 let n = self.dataset.len().max(0);
1195 let b = i64::from(self.config.batch_size);
1196 n / b + i64::from(!self.config.drop_last && n % b != 0)
1197 }
1198
1199 fn spawn_epoch(&mut self, epoch: u64) -> Result<()> {
1200 let mut indices = make_indices_host(self.dataset.len())?;
1201 if self.config.shuffle {
1202 shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
1203 }
1204 let (sender, receiver) = mpsc::sync_channel(self.prefetch_batches);
1205 let dataset = Arc::clone(&self.dataset);
1206 let batch_size = usize::try_from(self.config.batch_size)
1207 .map_err(|_| Error::invalid_argument("batch size must fit usize"))?;
1208 let drop_last = self.config.drop_last;
1209 self.receiver = Some(receiver);
1210 self.worker = Some(std::thread::spawn(move || {
1211 let mut start = 0_usize;
1212 while start < indices.len() {
1213 let count = batch_size.min(indices.len() - start);
1214 if drop_last && count < batch_size {
1215 break;
1216 }
1217 let produced = indices[start..start + count]
1218 .iter()
1219 .map(|&index| dataset.get_host_sample(index))
1220 .collect::<Result<Vec<_>>>()
1221 .and_then(|samples| collate_host(&samples));
1222 let keep_going = produced.is_ok();
1223 if sender.send(produced).is_err() || !keep_going {
1224 return;
1225 }
1226 start += count;
1227 }
1228 }));
1229 self.epoch = epoch;
1230 Ok(())
1231 }
1232}
1233
1234fn make_indices_host(count: i64) -> Result<Vec<i64>> {
1235 let length = usize::try_from(count)
1236 .map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
1237 let mut indices = Vec::new();
1238 indices
1239 .try_reserve_exact(length)
1240 .map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
1241 indices.extend(0..count);
1242 Ok(indices)
1243}