pub use super::types::{DataLoaderConfig, SplitResult};
pub use crate::data::types::Batch;
use crate::{DType, Error, Matrix, Result, Runtime, matrix};
use std::sync::{Arc, mpsc};
use std::thread::JoinHandle;
pub struct Sample {
pub x: Matrix,
pub y: Option<Matrix>,
}
impl Sample {
pub fn new(x: Matrix) -> Self {
Self { x, y: None }
}
pub fn new_with_label(x: Matrix, y: Matrix) -> Self {
Self { x, y: Some(y) }
}
pub fn has_label(&self) -> bool {
self.y.is_some()
}
}
pub trait Dataset {
fn len(&self) -> i64;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn get_sample(&self, index: i64) -> Result<Sample> {
Ok(Sample::new(self.get_item(index)?))
}
fn get_batch(&self, indices: &[i64]) -> Result<Batch> {
let samples = indices
.iter()
.map(|&index| self.get_sample(index))
.collect::<Result<Vec<_>>>()?;
collate(&samples)
}
fn get_item(&self, index: i64) -> Result<Matrix>;
fn subset(&self, indices: Vec<i64>) -> Result<Subset<'_>>
where
Self: Sized,
{
Subset::new(self, indices)
}
fn shuffled_subset(&self, seed: u64) -> Result<Subset<'_>>
where
Self: Sized,
{
let mut indices = make_indices(checked_len(self)?)?;
shuffle(&mut indices, seed)?;
self.subset(indices)
}
}
pub struct MatrixDataset {
x: Matrix,
y: Matrix,
}
impl MatrixDataset {
pub fn new(x: Matrix, y: Matrix) -> Result<Self> {
if x.shape().is_empty() || y.shape().len() != 1 || x.shape()[0] != y.shape()[0] {
return Err(Error::invalid_argument(
"matrix dataset requires [N, ...] features and [N] labels with equal counts",
));
}
if x.dtype() != crate::DType::F32 || y.dtype() != crate::DType::F32 {
return Err(Error::invalid_argument(
"matrix dataset requires F32 features and labels",
));
}
if !x.same_runtime(&y) {
return Err(Error::invalid_argument(
"matrix dataset features and labels must share one runtime",
));
}
Ok(Self { x, y })
}
#[must_use]
pub const fn x(&self) -> &Matrix {
&self.x
}
#[must_use]
pub const fn y(&self) -> &Matrix {
&self.y
}
}
impl Dataset for MatrixDataset {
fn len(&self) -> i64 {
i64::try_from(self.x.shape()[0]).unwrap_or(i64::MAX)
}
fn get_item(&self, index: i64) -> Result<Matrix> {
if index < 0 || index >= self.len() {
return Err(Error::out_of_range(
"matrix dataset index is outside the dataset",
));
}
matrix::slice(&self.x, 0, index, index + 1)?.squeeze(0)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
let x = self.get_item(index)?;
let y = matrix::slice(&self.y, 0, index, index + 1)?;
Ok(Sample::new_with_label(x, y))
}
}
pub struct Subset<'ds> {
parent: &'ds dyn Dataset,
indices: Vec<i64>,
}
impl<'ds> Subset<'ds> {
pub fn new(parent: &'ds dyn Dataset, indices: Vec<i64>) -> Result<Self> {
let count = checked_len(parent)?;
if indices.iter().any(|&index| index < 0 || index >= count) {
return Err(Error::out_of_range(
"subset index is outside the parent dataset",
));
}
Ok(Self { parent, indices })
}
fn parent_index(&self, index: i64) -> Result<i64> {
usize::try_from(index)
.ok()
.and_then(|index| self.indices.get(index))
.copied()
.ok_or_else(|| Error::out_of_range("index is outside the subset"))
}
pub fn indices(&self) -> &[i64] {
&self.indices
}
pub fn parent(&self) -> &dyn Dataset {
self.parent
}
}
impl Dataset for Subset<'_> {
fn len(&self) -> i64 {
self.indices.len() as i64
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.parent.get_item(self.parent_index(index)?)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
self.parent.get_sample(self.parent_index(index)?)
}
}
impl Batch {
pub fn is_valid(&self) -> bool {
self.x.num_elements() > 0
}
}
pub struct DataLoader<'ds> {
dataset: DatasetSource<'ds>,
config: DataLoaderConfig,
indices: Vec<i64>,
current_batch: i64,
}
enum DatasetSource<'ds> {
Borrowed(&'ds dyn Dataset),
Owned(Box<dyn Dataset + 'ds>),
}
impl DatasetSource<'_> {
fn get(&self) -> &dyn Dataset {
match self {
Self::Borrowed(dataset) => *dataset,
Self::Owned(dataset) => dataset.as_ref(),
}
}
}
struct ClassificationDataset {
runtime: Runtime,
input: Matrix,
rows: Matrix,
start: usize,
labels: Vec<u32>,
}
impl Dataset for ClassificationDataset {
fn len(&self) -> i64 {
self.labels.len() as i64
}
fn get_item(&self, index: i64) -> Result<Matrix> {
let batch = self.get_batch(&[index])?;
batch.x.squeeze(0)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
let batch = self.get_batch(&[index])?;
Ok(Sample {
x: batch.x.squeeze(0)?,
y: batch.y,
})
}
fn get_batch(&self, indices: &[i64]) -> Result<Batch> {
let mut rows = Vec::with_capacity(indices.len());
let mut labels = Vec::with_capacity(indices.len());
for &index in indices {
let row = u32::try_from(index)
.map_err(|_| Error::out_of_range("classification batch index is invalid"))?;
let label = self
.labels
.get(row as usize)
.ok_or_else(|| Error::out_of_range("classification batch index is outside the dataset"))?;
rows.push(row + self.start as u32);
labels.push(*label);
}
let shape = [rows.len()];
let indices = Matrix::new_from_slice_on(&self.runtime, shape, &rows)?;
let y = Matrix::new_from_slice_on(&self.runtime, shape, &labels)?;
let mut batch_shape = self.input.shape().to_vec();
batch_shape[0] = rows.len();
let x = self.rows.gather(&indices)?.reshape(batch_shape)?;
Ok(Batch { x, y: Some(y) })
}
}
impl DataLoader<'static> {
pub fn classification(
runtime: &Runtime,
input: Matrix,
labels: Vec<u32>,
config: DataLoaderConfig,
) -> Result<Self> {
if input.shape().first() != Some(&labels.len()) {
return Err(Error::invalid_argument(
"classification inputs and labels must have the same sample count",
));
}
Self::classification_subset(runtime, input, 0, labels, config)
}
pub fn classification_subset(
runtime: &Runtime,
input: Matrix,
start: usize,
labels: Vec<u32>,
config: DataLoaderConfig,
) -> Result<Self> {
let count = input.shape().first().copied().unwrap_or(0);
if labels.is_empty()
|| count > u32::MAX as usize
|| start
.checked_add(labels.len())
.is_none_or(|end| end > count)
|| input.dtype() != crate::DType::F32
|| !runtime.owns_matrix(&input)
|| input.num_elements() == 0
{
return Err(Error::invalid_argument(
"classification loader requires a nonempty range with matching labels and FP32 inputs on the selected runtime",
));
}
let rows = input.reshape([count, input.num_elements() / count])?;
Self::from_source(
DatasetSource::Owned(Box::new(ClassificationDataset {
runtime: runtime.clone(),
input,
rows,
start,
labels,
})),
config,
)
}
}
impl<'ds> DataLoader<'ds> {
pub fn new(dataset: &'ds dyn Dataset, config: DataLoaderConfig) -> Result<Self> {
Self::from_source(DatasetSource::Borrowed(dataset), config)
}
fn from_source(dataset: DatasetSource<'ds>, config: DataLoaderConfig) -> Result<Self> {
if config.batch_size <= 0 {
return Err(Error::invalid_argument(
"data loader batch size must be positive",
));
}
let mut loader = Self {
dataset,
config,
indices: Vec::new(),
current_batch: 0,
};
loader.reset()?;
Ok(loader)
}
pub fn next_batch(&mut self) -> Result<Option<Batch>> {
if self.current_batch >= self.num_batches() {
return Ok(None);
}
let start = self.current_batch as usize * self.config.batch_size as usize;
let count = (self.config.batch_size as usize).min(self.indices.len() - start);
let batch = self
.dataset
.get()
.get_batch(&self.indices[start..start + count])?;
self.current_batch += 1;
Ok(Some(batch))
}
pub fn reset(&mut self) -> Result<()> {
let mut indices = make_indices(checked_len(self.dataset.get())?)?;
if self.config.shuffle {
shuffle(&mut indices, self.config.seed)?;
}
self.indices = indices;
self.current_batch = 0;
Ok(())
}
pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
let mut indices = make_indices(checked_len(self.dataset.get())?)?;
if self.config.shuffle {
shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
}
self.indices = indices;
self.current_batch = 0;
Ok(())
}
pub fn num_batches(&self) -> i64 {
let n = self.indices.len() as i64;
let b = i64::from(self.config.batch_size);
n / b + i64::from(!self.config.drop_last && n % b != 0)
}
pub fn current_batch(&self) -> i64 {
self.current_batch
}
pub fn seek(&mut self, epoch: u64, cursor: i64) -> Result<()> {
let mut indices = make_indices(checked_len(self.dataset.get())?)?;
if self.config.shuffle {
shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
}
let n = indices.len() as i64;
let b = i64::from(self.config.batch_size);
let num_batches = n / b + i64::from(!self.config.drop_last && n % b != 0);
if cursor < 0 || cursor > num_batches {
return Err(Error::invalid_argument(
"data loader seek cursor outside the epoch",
));
}
self.indices = indices;
self.current_batch = cursor;
Ok(())
}
}
pub fn shuffle(indices: &mut [i64], seed: u64) -> Result<()> {
if indices.len() < 2 {
return Ok(());
}
let seed = if seed == 0 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| Error::failed_precondition("dataset shuffle clock precedes Unix epoch"))?
.as_nanos() as u64
} else {
seed
};
let mut rng = Pcg32::new(seed);
for count in (2..=indices.len()).rev() {
let range = count as u64;
let reject = range.wrapping_neg() % range;
let value = loop {
let value = rng.next_u64();
if value >= reject {
break value;
}
};
indices.swap(count - 1, (value % range) as usize);
}
Ok(())
}
pub fn random_split(
total_size: i64,
train_ratio: f32,
val_ratio: f32,
seed: u64,
) -> Result<SplitResult> {
if !train_ratio.is_finite() || !val_ratio.is_finite() {
return Err(Error::invalid_argument(
"dataset split ratios must be finite",
));
}
let mut all = make_indices(total_size)?;
let train_ratio = train_ratio.clamp(0.0, 1.0);
let val_ratio = val_ratio.clamp(0.0, 1.0 - train_ratio);
let n = all.len();
let train_count = ((n as f32 * train_ratio) as usize).min(n);
let val_count = ((n as f32 * val_ratio) as usize).min(n - train_count);
shuffle(&mut all, seed)?;
let test = all.split_off(train_count + val_count);
let val = all.split_off(train_count);
Ok(SplitResult {
train: all,
val,
test,
})
}
pub fn collate(samples: &[Sample]) -> Result<Batch> {
let first = samples
.first()
.ok_or_else(|| Error::invalid_argument("collate requires at least one sample"))?;
for sample in samples {
validate_component(&sample.x, &first.x)?;
match (&sample.y, &first.y) {
(Some(value), Some(reference)) => {
validate_component(value, reference)?;
if !value.runtime().same_as(first.x.runtime()) {
return Err(Error::invalid_argument(
"collate inputs and labels must share one runtime",
));
}
}
(None, None) => {}
_ => {
return Err(Error::invalid_argument(
"collate label presence must match for every sample",
));
}
}
}
if let [only] = samples {
return Ok(Batch {
x: only.x.unsqueeze(0)?,
y: only
.y
.as_ref()
.map(|value| value.unsqueeze(0))
.transpose()?,
});
}
let x_views = samples
.iter()
.map(|sample| sample.x.unsqueeze(0))
.collect::<Result<Vec<_>>>()?;
let y_views = samples
.iter()
.filter_map(|sample| sample.y.as_ref())
.map(|value| value.unsqueeze(0))
.collect::<Result<Vec<_>>>()?;
let x = matrix::concat(&x_views, 0)?;
let y = if y_views.is_empty() {
None
} else {
Some(matrix::concat(&y_views, 0)?)
};
Ok(Batch { x, y })
}
fn validate_component(value: &Matrix, reference: &Matrix) -> Result<()> {
if value.shape().len() > 3 {
return Err(Error::invalid_argument(
"collate requires samples of rank at most three",
));
}
if value.num_elements() == 0
|| value.shape() != reference.shape()
|| value.dtype() != reference.dtype()
|| !value.runtime().same_as(reference.runtime())
{
return Err(Error::invalid_argument(
"collate requires nonempty, same-shape, same-dtype, same-runtime components",
));
}
Ok(())
}
fn checked_len(dataset: &dyn Dataset) -> Result<i64> {
let count = dataset.len();
if count < 0 {
return Err(Error::invalid_argument(
"dataset length must be nonnegative",
));
}
Ok(count)
}
fn make_indices(count: i64) -> Result<Vec<i64>> {
let length = usize::try_from(count)
.map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
let mut indices = Vec::new();
indices
.try_reserve_exact(length)
.map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
indices.extend(0..count);
Ok(indices)
}
struct Pcg32 {
state: u64,
}
impl Pcg32 {
fn new(seed: u64) -> Self {
let mut rng = Self { state: 0 };
rng.next_u32();
rng.state = rng.state.wrapping_add(seed);
rng.next_u32();
rng
}
fn next_u32(&mut self) -> u32 {
let old = self.state;
self.state = old.wrapping_mul(6364136223846793005).wrapping_add(3);
let shifted = (((old >> 18) ^ old) >> 27) as u32;
shifted.rotate_right((old >> 59) as u32)
}
fn next_u64(&mut self) -> u64 {
(u64::from(self.next_u32()) << 32) | u64::from(self.next_u32())
}
}
#[derive(Clone, Debug)]
pub enum HostValues {
F32(Vec<f32>),
U32(Vec<u32>),
I32(Vec<i32>),
U8(Vec<u8>),
}
impl HostValues {
fn dtype(&self) -> DType {
match self {
Self::F32(_) => DType::F32,
Self::U32(_) => DType::U32,
Self::I32(_) => DType::I32,
Self::U8(_) => DType::U8,
}
}
fn len(&self) -> usize {
match self {
Self::F32(values) => values.len(),
Self::U32(values) => values.len(),
Self::I32(values) => values.len(),
Self::U8(values) => values.len(),
}
}
fn slice(&self, start: usize, count: usize) -> Self {
match self {
Self::F32(values) => Self::F32(values[start..start + count].to_vec()),
Self::U32(values) => Self::U32(values[start..start + count].to_vec()),
Self::I32(values) => Self::I32(values[start..start + count].to_vec()),
Self::U8(values) => Self::U8(values[start..start + count].to_vec()),
}
}
fn concat(parts: &[&Self]) -> Result<Self> {
let first = parts
.first()
.ok_or_else(|| Error::invalid_argument("host concat requires a part"))?;
Ok(match first {
Self::F32(_) => {
let mut values = Vec::new();
for part in parts {
let Self::F32(part) = part else {
return Err(Error::invalid_argument(
"host concat requires one dtype across parts",
));
};
values.extend_from_slice(part);
}
Self::F32(values)
}
Self::U32(_) => {
let mut values = Vec::new();
for part in parts {
let Self::U32(part) = part else {
return Err(Error::invalid_argument(
"host concat requires one dtype across parts",
));
};
values.extend_from_slice(part);
}
Self::U32(values)
}
Self::I32(_) => {
let mut values = Vec::new();
for part in parts {
let Self::I32(part) = part else {
return Err(Error::invalid_argument(
"host concat requires one dtype across parts",
));
};
values.extend_from_slice(part);
}
Self::I32(values)
}
Self::U8(_) => {
let mut values = Vec::new();
for part in parts {
let Self::U8(part) = part else {
return Err(Error::invalid_argument(
"host concat requires one dtype across parts",
));
};
values.extend_from_slice(part);
}
Self::U8(values)
}
})
}
}
#[derive(Clone, Debug)]
pub struct HostTensor {
pub shape: Vec<usize>,
pub values: HostValues,
}
impl HostTensor {
pub fn new(shape: impl Into<Vec<usize>>, values: HostValues) -> Result<Self> {
let tensor = Self {
shape: shape.into(),
values,
};
tensor.check_count()?;
Ok(tensor)
}
pub fn num_elements(&self) -> usize {
self.shape.iter().product()
}
pub fn dtype(&self) -> DType {
self.values.dtype()
}
fn check_count(&self) -> Result<()> {
if self.num_elements() != self.values.len() {
return Err(Error::invalid_argument(
"host tensor shape and value count disagree",
));
}
Ok(())
}
pub fn to_matrix_on(&self, runtime: &Runtime) -> Result<Matrix> {
self.check_count()?;
match &self.values {
HostValues::F32(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
HostValues::U32(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
HostValues::I32(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
HostValues::U8(values) => Matrix::new_from_slice_on(runtime, self.shape.clone(), values),
}
}
}
#[derive(Clone, Debug)]
pub struct HostSample {
pub x: HostTensor,
pub y: Option<HostTensor>,
}
#[derive(Clone, Debug)]
pub struct HostBatch {
pub x: HostTensor,
pub y: Option<HostTensor>,
}
impl HostBatch {
pub fn upload_on(&self, runtime: &Runtime) -> Result<Batch> {
Ok(Batch {
x: self.x.to_matrix_on(runtime)?,
y: self
.y
.as_ref()
.map(|label| label.to_matrix_on(runtime))
.transpose()?,
})
}
}
pub fn collate_host(samples: &[HostSample]) -> Result<HostBatch> {
let first = samples
.first()
.ok_or_else(|| Error::invalid_argument("collate_host requires at least one sample"))?;
for sample in samples {
validate_host_component(&sample.x, &first.x)?;
match (&sample.y, &first.y) {
(Some(value), Some(reference)) => validate_host_component(value, reference)?,
(None, None) => {}
_ => {
return Err(Error::invalid_argument(
"collate_host label presence must match for every sample",
));
}
}
}
let stack = |tensors: Vec<&HostTensor>| -> Result<HostTensor> {
let mut shape = tensors[0].shape.clone();
shape.insert(0, tensors.len());
HostTensor::new(
shape,
HostValues::concat(
&tensors
.iter()
.map(|tensor| &tensor.values)
.collect::<Vec<_>>(),
)?,
)
};
Ok(HostBatch {
x: stack(samples.iter().map(|sample| &sample.x).collect())?,
y: samples
.iter()
.filter_map(|sample| sample.y.as_ref())
.collect::<Vec<_>>()
.split_first()
.map(|_| stack(samples.iter().filter_map(|s| s.y.as_ref()).collect()))
.transpose()?,
})
}
fn validate_host_component(value: &HostTensor, reference: &HostTensor) -> Result<()> {
if value.num_elements() == 0
|| value.shape != reference.shape
|| value.dtype() != reference.dtype()
{
return Err(Error::invalid_argument(
"collate_host requires nonempty, same-shape, same-dtype components",
));
}
Ok(())
}
pub trait HostDataset: Send + Sync {
fn len(&self) -> i64;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn get_host_sample(&self, index: i64) -> Result<HostSample>;
}
pub struct HostTensorDataset {
x: HostTensor,
y: HostTensor,
}
impl HostTensorDataset {
pub fn new(x: HostTensor, y: HostTensor) -> Result<Self> {
if x.shape.is_empty() || y.shape.len() != 1 || x.shape[0] != y.shape[0] {
return Err(Error::invalid_argument(
"host tensor dataset requires [N, ...] features and [N] labels with equal counts",
));
}
Ok(Self { x, y })
}
pub fn from_f32_matrices(x: &Matrix, y: &Matrix) -> Result<Self> {
if x.shape().is_empty() || y.shape().len() != 1 || x.shape()[0] != y.shape()[0] {
return Err(Error::invalid_argument(
"host tensor dataset requires [N, ...] features and [N] labels with equal counts",
));
}
Self::new(
HostTensor::new(x.shape().to_vec(), HostValues::F32(x.read_f32()?))?,
HostTensor::new(y.shape().to_vec(), HostValues::F32(y.read_f32()?))?,
)
}
}
impl HostDataset for HostTensorDataset {
fn len(&self) -> i64 {
i64::try_from(self.x.shape[0]).unwrap_or(i64::MAX)
}
fn get_host_sample(&self, index: i64) -> Result<HostSample> {
let count = self.len();
if index < 0 || index >= count {
return Err(Error::invalid_argument(
"host tensor dataset index out of range",
));
}
let index = usize::try_from(index)
.map_err(|_| Error::invalid_argument("host tensor dataset index out of range"))?;
let stride: usize = self.x.shape[1..].iter().product();
Ok(HostSample {
x: HostTensor::new(
self.x.shape[1..].to_vec(),
self.x.values.slice(index * stride, stride),
)?,
y: Some(HostTensor::new(vec![1], self.y.values.slice(index, 1))?),
})
}
}
pub struct PrefetchDataLoader {
dataset: Arc<dyn HostDataset>,
config: DataLoaderConfig,
prefetch_batches: usize,
receiver: Option<mpsc::Receiver<Result<HostBatch>>>,
worker: Option<JoinHandle<()>>,
epoch: u64,
current_batch: i64,
}
impl PrefetchDataLoader {
pub fn new(
dataset: Arc<dyn HostDataset>,
config: DataLoaderConfig,
prefetch_batches: usize,
) -> Result<Self> {
if config.batch_size <= 0 {
return Err(Error::invalid_argument(
"prefetch data loader batch size must be positive",
));
}
if prefetch_batches == 0 {
return Err(Error::invalid_argument(
"prefetch data loader requires at least one queued batch",
));
}
let mut loader = Self {
dataset,
config,
prefetch_batches,
receiver: None,
worker: None,
epoch: 0,
current_batch: 0,
};
loader.spawn_epoch_from(0, 0)?;
Ok(loader)
}
pub fn next_batch(&mut self) -> Result<Option<HostBatch>> {
let Some(receiver) = &self.receiver else {
return Ok(None);
};
match receiver.recv() {
Ok(Ok(batch)) => {
self.current_batch += 1;
Ok(Some(batch))
}
Ok(Err(error)) => {
self.receiver = None;
Err(error)
}
Err(mpsc::RecvError) => {
self.receiver = None;
Ok(None)
}
}
}
pub fn next_batch_on(&mut self, runtime: &Runtime) -> Result<Option<Batch>> {
self
.next_batch()?
.map(|batch| batch.upload_on(runtime))
.transpose()
}
pub fn reset_epoch(&mut self, epoch: u64) -> Result<()> {
self.spawn_epoch_from(epoch, 0)
}
pub fn num_batches(&self) -> i64 {
let n = self.dataset.len().max(0);
let b = i64::from(self.config.batch_size);
n / b + i64::from(!self.config.drop_last && n % b != 0)
}
pub fn current_batch(&self) -> i64 {
self.current_batch
}
pub fn seek(&mut self, epoch: u64, cursor: i64) -> Result<()> {
self.spawn_epoch_from(epoch, cursor)
}
fn spawn_epoch_from(&mut self, epoch: u64, cursor: i64) -> Result<()> {
let mut indices = make_indices_host(self.dataset.len())?;
if self.config.shuffle {
shuffle(&mut indices, self.config.seed.wrapping_add(epoch))?;
}
let n = indices.len() as i64;
let b = i64::from(self.config.batch_size);
let num_batches = n / b + i64::from(!self.config.drop_last && n % b != 0);
if cursor < 0 || cursor > num_batches {
return Err(Error::invalid_argument(
"prefetch data loader seek cursor outside the epoch",
));
}
let (sender, receiver) = mpsc::sync_channel(self.prefetch_batches);
let dataset = Arc::clone(&self.dataset);
let batch_size = usize::try_from(self.config.batch_size)
.map_err(|_| Error::invalid_argument("batch size must fit usize"))?;
let start_index = (cursor as usize)
.checked_mul(batch_size)
.ok_or_else(|| Error::invalid_argument("prefetch data loader seek offset overflow"))?;
let drop_last = self.config.drop_last;
self.receiver = Some(receiver);
self.worker = Some(std::thread::spawn(move || {
let mut start = start_index;
while start < indices.len() {
let count = batch_size.min(indices.len() - start);
if drop_last && count < batch_size {
break;
}
let produced = indices[start..start + count]
.iter()
.map(|&index| dataset.get_host_sample(index))
.collect::<Result<Vec<_>>>()
.and_then(|samples| collate_host(&samples));
let keep_going = produced.is_ok();
if sender.send(produced).is_err() || !keep_going {
return;
}
start += count;
}
}));
self.epoch = epoch;
self.current_batch = cursor;
Ok(())
}
}
fn make_indices_host(count: i64) -> Result<Vec<i64>> {
let length = usize::try_from(count)
.map_err(|_| Error::invalid_argument("dataset size must fit usize and be nonnegative"))?;
let mut indices = Vec::new();
indices
.try_reserve_exact(length)
.map_err(|_| Error::resource_exhausted("dataset index allocation failed"))?;
indices.extend(0..count);
Ok(indices)
}