use std::{path::Path, sync::Arc};
use half::{f16, slice::HalfFloatSliceExt};
use super::{
artifacts::tree::resolve_or,
config::{EMBED_SCALE, HIDDEN_SIZE, POSITION_ROWS, POSITION_TABLES, POSITION_WIDTH, VOCAB_SIZE},
error::{
Artifact, Error, ReadFailure, Result, StampDefect, StampField, TableCell, TableIdentity,
TableShape,
},
map::{Access, ReadOnlyMap},
tokenizer::bpe::TokenId,
};
pub(crate) const TOKEN_TABLE_BYTES: u64 = (VOCAB_SIZE * HIDDEN_SIZE * 2) as u64;
pub(crate) const POSITION_TABLE_BYTES: u64 =
(POSITION_TABLES * POSITION_ROWS * POSITION_WIDTH * 2) as u64;
pub(crate) const TOKEN_SENTINEL_CELLS: [TableCell; 9] = [
TableCell::token(0, 0),
TableCell::token(0, 1),
TableCell::token(0, 2),
TableCell::token(0, 3),
TableCell::token(2, 0),
TableCell::token(2, 1),
TableCell::token(506, 160),
TableCell::token(236_743, 0),
TableCell::token(262_143, 511),
];
#[cfg(test)]
pub(crate) const UPSTREAM_TOKEN_SENTINELS: [u16; 9] = [
0xbbe5, 0xbca4, 0xbd26, 0xbc2d, 0x3dd2, 0xbd47, 0xbf06, 0x3d0c, 0x3aa5,
];
pub(crate) const POSITION_SENTINEL_CELLS: [TableCell; 2] = [
TableCell::position(0, 0, 767),
TableCell::position(1, 0, 767),
];
#[cfg(test)]
pub(crate) const UPSTREAM_POSITION_SENTINELS: [u16; 2] = [0x2d68, 0xb040];
fn open_checked(
artifact: Artifact,
path: &Path,
bytes: u64,
access: Access,
cells: &[TableCell],
sentinels: &[(TableCell, u16)],
offset: impl Fn(TableCell) -> usize,
) -> Result<Arc<ReadOnlyMap>> {
let read = |e| Error::Read(ReadFailure::new(artifact, path.to_path_buf(), e));
let len = match resolve_or(path, read)? {
Some(found) => found.metadata.len(),
None => return Err(read(std::io::ErrorKind::NotFound.into())),
};
if len != bytes {
return Err(Error::TableShape(TableShape::new(artifact, bytes, len)));
}
if !sentinels.iter().map(|(cell, _)| cell).eq(cells) {
return Err(Error::Stamp(StampDefect::new(
StampField::Files,
format!(
"the sentinels of {artifact} must be exactly the cells [{}], and the stamp recorded [{}]",
Cells(cells.iter().copied()),
Cells(sentinels.iter().map(|(cell, _)| *cell)),
),
)));
}
let map = ReadOnlyMap::open(artifact, path, access)?;
let mapped = map.bytes().len() as u64;
if mapped != bytes {
return Err(Error::TableShape(TableShape::new(artifact, bytes, mapped)));
}
for &(cell, expected) in sentinels {
let at = offset(cell);
let actual = u16::from_le_bytes([map.bytes()[at], map.bytes()[at + 1]]);
if actual != expected {
return Err(Error::TableIdentity(TableIdentity::new(
artifact, cell, expected, actual,
)));
}
}
Ok(map)
}
struct Cells<I>(I);
impl<I: Iterator<Item = TableCell> + Clone> core::fmt::Display for Cells<I> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for (index, cell) in self.0.clone().enumerate() {
if index > 0 {
f.write_str("; ")?;
}
write!(f, "{cell}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GatherRefusal {
NoRow(u32),
Shape(ShapeRefusal),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ShapeRefusal {
pub(crate) ids: usize,
pub(crate) cells: usize,
}
impl From<GatherRefusal> for Error {
fn from(refusal: GatherRefusal) -> Self {
match refusal {
GatherRefusal::NoRow(id) => Error::Tensor(crate::TensorError::IndexOutOfBounds(
crate::error::IndexOutOfBounds::new(id as usize, VOCAB_SIZE),
)),
GatherRefusal::Shape(ShapeRefusal { ids, cells }) => {
Error::Tensor(crate::TensorError::ShapeMismatch(
crate::error::ShapeMismatch::new(ids.saturating_mul(HIDDEN_SIZE), cells),
))
}
}
}
}
#[cfg(test)]
#[inline]
pub(crate) fn gather_cell(bf16: u16) -> f16 {
f16::from_f32(f32::from_bits(u32::from(bf16) << 16) * EMBED_SCALE)
}
#[cfg(test)]
pub(crate) fn gather_row_scalar(row: &[u8], out: &mut [f16]) {
debug_assert_eq!(row.len(), out.len() * 2, "a row of out.len() cells");
for (cell, slot) in row.as_chunks::<2>().0.iter().zip(out.iter_mut()) {
*slot = gather_cell(u16::from_le_bytes([cell[0], cell[1]]));
}
}
pub(crate) fn gather_row(row: &[u8], out: &mut [f16]) {
debug_assert_eq!(row.len(), out.len() * 2, "a row of out.len() cells");
let mut wide = [0f32; HIDDEN_SIZE];
let wide = &mut wide[..out.len()];
for (cell, slot) in row.as_chunks::<2>().0.iter().zip(wide.iter_mut()) {
*slot = f32::from_bits(u32::from(u16::from_le_bytes([cell[0], cell[1]])) << 16) * EMBED_SCALE;
}
out.convert_from_f32_slice(wide);
}
#[derive(Debug, Clone)]
pub(crate) struct TokenTable {
map: Arc<ReadOnlyMap>,
}
impl TokenTable {
pub(crate) fn open(path: &Path, sentinels: &[(TableCell, u16)]) -> Result<Self> {
let map = open_checked(
Artifact::TokenTable,
path,
TOKEN_TABLE_BYTES,
Access::Random,
&TOKEN_SENTINEL_CELLS,
sentinels,
|cell| (cell.row() as usize * HIDDEN_SIZE + cell.column() as usize) * 2,
)?;
Ok(Self { map })
}
#[inline]
pub(crate) fn row(&self, id: u32) -> Option<&[u8]> {
let start = (id as usize).checked_mul(HIDDEN_SIZE * 2)?;
self
.map
.bytes()
.get(start..start.checked_add(HIDDEN_SIZE * 2)?)
}
pub(crate) fn gather_sequence(
&self,
ids: &[TokenId],
out: &mut [f16],
) -> core::result::Result<(), GatherRefusal> {
if !out.len().is_multiple_of(HIDDEN_SIZE) || ids.len() > out.len() / HIDDEN_SIZE {
return Err(GatherRefusal::Shape(ShapeRefusal {
ids: ids.len(),
cells: out.len(),
}));
}
let (rows, pads) = out.split_at_mut(ids.len() * HIDDEN_SIZE);
for (&id, slot) in ids.iter().zip(rows.as_chunks_mut::<HIDDEN_SIZE>().0) {
self.gather_id(id, slot)?;
}
self.gather_pad(pads)
}
#[inline]
pub(crate) fn gather_id(
&self,
id: TokenId,
out: &mut [f16],
) -> core::result::Result<(), GatherRefusal> {
if out.len() != HIDDEN_SIZE {
return Err(GatherRefusal::Shape(ShapeRefusal {
ids: 1,
cells: out.len(),
}));
}
gather_row(
self.row(id.get()).ok_or(GatherRefusal::NoRow(id.get()))?,
out,
);
Ok(())
}
pub(crate) fn gather_pad(&self, out: &mut [f16]) -> core::result::Result<(), GatherRefusal> {
if !out.len().is_multiple_of(HIDDEN_SIZE) {
return Err(GatherRefusal::Shape(ShapeRefusal {
ids: 0,
cells: out.len(),
}));
}
let Some((first, rest)) = out.split_first_chunk_mut::<HIDDEN_SIZE>() else {
return Ok(());
};
gather_row(self.row(0).ok_or(GatherRefusal::NoRow(0))?, first);
for slot in rest.as_chunks_mut::<HIDDEN_SIZE>().0 {
slot.copy_from_slice(first);
}
Ok(())
}
#[cfg(test)]
pub(crate) fn same_mapping(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.map, &other.map)
}
}
#[derive(Debug, Clone)]
pub(crate) struct PositionTable {
map: Arc<ReadOnlyMap>,
}
impl PositionTable {
pub(crate) fn open(path: &Path, sentinels: &[(TableCell, u16)]) -> Result<Self> {
let map = open_checked(
Artifact::PositionTable,
path,
POSITION_TABLE_BYTES,
Access::Default,
&POSITION_SENTINEL_CELLS,
sentinels,
|cell| {
let table = usize::from(cell.table().unwrap_or(0));
((table * POSITION_ROWS + cell.row() as usize) * POSITION_WIDTH + cell.column() as usize)
* 2
},
)?;
Ok(Self { map })
}
#[inline]
pub(crate) fn row(&self, table: usize, index: usize) -> Option<&[u8]> {
if table >= POSITION_TABLES || index >= POSITION_ROWS {
return None;
}
let start = (table * POSITION_ROWS + index) * POSITION_WIDTH * 2;
self.map.bytes().get(start..start + POSITION_WIDTH * 2)
}
#[inline]
#[cfg(test)]
pub(crate) fn same_mapping(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.map, &other.map)
}
}
const _: fn() = || {
fn shared<T: Send + Sync>() {}
shared::<TokenTable>();
shared::<PositionTable>();
shared::<Arc<ReadOnlyMap>>();
};
#[cfg(test)]
pub(crate) mod fixture;
#[cfg(test)]
mod tests;