use oa::data::{Dataset, Sample};
use oa::matrix::{self, Matrix};
use oa::{Engine, Error, Result};
use crate::decode::{Decoded, MatrixData};
use crate::pack::{self, FetchProgress};
#[path = "tiny_shakespeare.gen.rs"]
mod generated;
pub(crate) use generated::SHAKESPEARE_PACK;
pub use generated::TinyShakespeareConfig;
pub struct TinyShakespeare {
tokens: Matrix,
text: String,
seq_len: usize,
}
impl TinyShakespeare {
pub fn decode(config: &TinyShakespeareConfig) -> Result<Decoded> {
Self::decode_with_progress(config, &mut |_| true)
}
pub fn decode_with_progress(
config: &TinyShakespeareConfig,
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(&SHAKESPEARE_PACK, &root, progress)?;
let text = std::fs::read_to_string(dir.join("input.txt"))
.map_err(|error| Error::io("read tiny_shakespeare text", error))?;
let values = text.bytes().map(f32::from).collect::<Vec<_>>();
let count = values.len();
Ok(Decoded {
matrices: vec![MatrixData {
name: "tokens",
shape: vec![count],
values,
}],
text: Some(text),
seq_len: 0,
})
}
pub fn load_with_progress_on(
engine: &Engine,
config: &TinyShakespeareConfig,
progress: &mut impl FnMut(FetchProgress) -> bool,
) -> Result<Self> {
if config.seq_len == 0 {
return Err(Error::invalid_argument(
"tiny_shakespeare seq_len must be at least 1",
));
}
let decoded = Self::decode_with_progress(config, progress)?;
let count = decoded.matrix("tokens")?.shape[0];
if count <= config.seq_len {
return Err(Error::invalid_argument(format!(
"tiny_shakespeare seq_len {} leaves no sample in {count} bytes",
config.seq_len,
)));
}
Ok(Self {
tokens: decoded.upload("tokens", engine)?,
text: decoded.text.unwrap_or_default(),
seq_len: config.seq_len,
})
}
#[must_use]
pub const fn tokens(&self) -> &Matrix {
&self.tokens
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
#[must_use]
pub const fn seq_len(&self) -> usize {
self.seq_len
}
fn check_index(&self, index: i64) -> Result<()> {
if index < 0 || index >= self.len() {
return Err(Error::out_of_range(
"tiny_shakespeare index is outside the dataset",
));
}
Ok(())
}
}
impl Dataset for TinyShakespeare {
fn len(&self) -> i64 {
i64::try_from(self.tokens.shape()[0].saturating_sub(self.seq_len)).unwrap_or(i64::MAX)
}
fn get_item(&self, index: i64) -> Result<Matrix> {
self.check_index(index)?;
matrix::slice(&self.tokens, 0, index, index + self.seq_len as i64)
}
fn get_sample(&self, index: i64) -> Result<Sample> {
self.check_index(index)?;
let end = index + self.seq_len as i64;
let x = matrix::slice(&self.tokens, 0, index, end)?;
let y = matrix::slice(&self.tokens, 0, index + 1, end + 1)?;
Ok(Sample::new_with_label(x, y))
}
}