use std::path::PathBuf;
use oa::data::{Dataset, Sample};
use oa::matrix::{self, Matrix};
use oa::{Engine, Error, Result};
use crate::decode::{Decoded, MatrixData};
use crate::extract;
use crate::idx::IdxSplit;
use crate::pack::{self, FetchProgress, Pack, PackFile};
const RECORD_LEN: usize = 3_073;
pub(crate) const CIFAR10_PACK: Pack = Pack {
name: "cifar10",
version: "1.0.0",
license: "unspecified",
files: &[PackFile {
name: "cifar-10-binary.tar.gz",
size: 170_052_171,
shake256: "0dbab965f3e25ad6875fa5f79eb7e79f41ee8b81aa3f7049e2a5b92209958e80",
urls: &["https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz"],
}],
};
const TRAIN_MEMBERS: &[&str] = &[
"data_batch_1.bin",
"data_batch_2.bin",
"data_batch_3.bin",
"data_batch_4.bin",
"data_batch_5.bin",
];
const TEST_MEMBERS: &[&str] = &["test_batch.bin"];
pub type Cifar10Split = IdxSplit;
#[derive(Clone, Debug)]
pub struct Cifar10Config {
pub split: Cifar10Split,
pub cache_dir: Option<PathBuf>,
pub normalize: bool,
}
impl Default for Cifar10Config {
fn default() -> Self {
Self {
split: IdxSplit::Train,
cache_dir: None,
normalize: true,
}
}
}
pub struct Cifar10 {
images: Matrix,
labels: Matrix,
split: Cifar10Split,
}
impl Cifar10 {
pub fn decode(config: &Cifar10Config) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &Cifar10Config,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Decoded> {
let root = match &config.cache_dir {
Some(dir) => dir.clone(),
None => pack::data_root()?,
};
let dir = pack::ensure_pack_with_progress(&CIFAR10_PACK, &root, progress)?;
let tar = extract::gunzip(&dir.join("cifar-10-binary.tar.gz"))?;
let members = match config.split {
IdxSplit::Train => TRAIN_MEMBERS,
IdxSplit::Test => TEST_MEMBERS,
};
let mut labels = Vec::new();
let mut pixels = Vec::new();
for member in members {
read_records(extract::tar_member(&tar, member)?, &mut labels, &mut pixels)?;
}
let scale = if config.normalize { 1.0 / 255.0 } else { 1.0 };
let count = labels.len();
Ok(Decoded {
matrices: vec![
MatrixData {
name: "images",
shape: vec![count, 3, 32, 32],
values: pixels
.iter()
.map(|&v| f32::from(v) * scale)
.collect::<Vec<_>>(),
},
MatrixData {
name: "labels",
shape: vec![count],
values: labels.iter().map(|&v| f32::from(v)).collect::<Vec<_>>(),
},
],
text: None,
seq_len: 0,
})
}
pub fn load(engine: &Engine, config: &Cifar10Config) -> Result<Self> {
Self::load_with_progress(engine, config, &mut |_| true)
}
pub fn load_with_progress(
engine: &Engine,
config: &Cifar10Config,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
let decoded = Self::decode_with_progress(config, progress)?;
Ok(Self {
images: decoded.upload("images", engine)?,
labels: decoded.upload("labels", engine)?,
split: config.split,
})
}
#[must_use]
pub const fn images(&self) -> &Matrix {
&self.images
}
#[must_use]
pub const fn labels(&self) -> &Matrix {
&self.labels
}
#[must_use]
pub const fn split(&self) -> Cifar10Split {
self.split
}
fn check_index(&self, index: i64) -> Result<()> {
if index < 0 || index >= self.len() {
return Err(Error::out_of_range("cifar10 index is outside the dataset"));
}
Ok(())
}
}
impl Dataset for Cifar10 {
fn len(&self) -> i64 {
i64::try_from(self.labels.shape()[0]).unwrap_or(i64::MAX)
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.check_index(index)?;
matrix::slice(&self.images, 0, index, index + 1)?.squeeze(0)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
self.check_index(index)?;
let x = matrix::slice(&self.images, 0, index, index + 1)?.squeeze(0)?;
let y = matrix::slice(&self.labels, 0, index, index + 1)?;
Ok(Sample::new_with_label(x, y))
}
}
fn read_records(member: &[u8], labels: &mut Vec<u8>, pixels: &mut Vec<u8>) -> Result<()> {
if !member.len().is_multiple_of(RECORD_LEN) {
return Err(Error::data_loss(format!(
"cifar10 member holds {} bytes, not a multiple of {RECORD_LEN}",
member.len()
)));
}
let (records, _) = member.as_chunks::<RECORD_LEN>();
for record in records {
labels.push(record[0]);
pixels.extend_from_slice(&record[1..]);
}
Ok(())
}