STRA-338 size: model-format: kar inspect_file split into header, records, nested (fn_lines 232->30, complexity 93->10)
This commit is contained in:
@@ -3,235 +3,44 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
mod header;
|
||||
mod nested;
|
||||
mod records;
|
||||
|
||||
use header::KarHeader;
|
||||
use records::RecordScan;
|
||||
|
||||
pub(super) fn inspect_file(mut file: File) -> Result<Parsed, String> {
|
||||
let file_bytes = file.metadata().map_err(|error| error.to_string())?.len();
|
||||
let header = read_region(&mut file, 0, HEADER_BYTES)?;
|
||||
if &header[0..8] != b"KARCHIV2" || u32_at(&header, 8) != 2 {
|
||||
return Err("unsupported KAR archive magic or version".into());
|
||||
}
|
||||
if u32_at(&header, 12) != 0x04030201
|
||||
|| u32_at(&header, 16) != HEADER_BYTES as u32
|
||||
|| u32_at(&header, 20) != RECORD_BYTES as u32
|
||||
{
|
||||
return Err("invalid KAR byte order or record size".into());
|
||||
}
|
||||
if crc32(&header[..192]) != u32_at(&header, 192) {
|
||||
return Err("KAR header CRC-32 mismatch".into());
|
||||
}
|
||||
let directory_offset = u64_at(&header, 24);
|
||||
let tensor_count = u32_at(&header, 32);
|
||||
let string_offset = u64_at(&header, 40);
|
||||
let string_bytes = u64_at(&header, 48);
|
||||
let payload_offset = u64_at(&header, 56);
|
||||
let archive_bytes = u64_at(&header, 64);
|
||||
let total_elements = u64_at(&header, 72);
|
||||
let payload_bits = u64_at(&header, 80);
|
||||
let source_total_elements = u64_at(&header, 88);
|
||||
let source_bytes = u64_at(&header, 120);
|
||||
let accounted_bpw = f64::from_le_bytes(header[96..104].try_into().unwrap());
|
||||
let mut source_digest = [0; 32];
|
||||
source_digest.copy_from_slice(&header[128..160]);
|
||||
if archive_bytes != file_bytes || archive_bytes < HEADER_BYTES as u64 {
|
||||
return Err("KAR archive length mismatch".into());
|
||||
}
|
||||
if tensor_count == 0 || tensor_count as usize > MAX_TENSORS || string_bytes > MAX_NAMES as u64 {
|
||||
return Err("KAR metadata exceeds bounded inspector limits".into());
|
||||
}
|
||||
if u32_at(&header, 36) != 0
|
||||
|| header[106] != 1
|
||||
|| total_elements == 0
|
||||
|| total_elements > source_total_elements
|
||||
|| source_bytes == 0
|
||||
{
|
||||
return Err("invalid KAR flags, digest algorithm, or element counts".into());
|
||||
}
|
||||
let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64;
|
||||
if !accounted_bpw.is_finite() || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) {
|
||||
return Err("KAR accounted_bpw does not match archive size".into());
|
||||
}
|
||||
let directory_bytes =
|
||||
(tensor_count as u64).checked_mul(RECORD_BYTES as u64).ok_or("KAR directory length overflow")?;
|
||||
let directory_end = directory_offset.checked_add(directory_bytes).ok_or("KAR directory overflow")?;
|
||||
let string_end = string_offset.checked_add(string_bytes).ok_or("KAR string table overflow")?;
|
||||
if !directory_offset.is_multiple_of(64)
|
||||
|| !string_offset.is_multiple_of(64)
|
||||
|| !payload_offset.is_multiple_of(256)
|
||||
|| directory_offset < HEADER_BYTES as u64
|
||||
|| directory_end > string_offset
|
||||
|| string_end > payload_offset
|
||||
|| payload_offset > archive_bytes
|
||||
{
|
||||
return Err("invalid KAR metadata offsets or alignment".into());
|
||||
}
|
||||
let names = read_region(&mut file, string_offset, string_bytes as usize)?;
|
||||
let directory = read_region(&mut file, directory_offset, directory_bytes as usize)?;
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(&names);
|
||||
digest.update(&directory);
|
||||
if digest.finalize().as_slice() != &header[160..192] {
|
||||
return Err("KAR directory digest mismatch".into());
|
||||
}
|
||||
|
||||
let mut seen_names = HashSet::new();
|
||||
seen_names.try_reserve(tensor_count as usize).map_err(|_| "KAR allocation failed")?;
|
||||
let mut elements_sum = 0u64;
|
||||
let mut bits_sum = 0u64;
|
||||
let mut previous_end = payload_offset;
|
||||
let mut min_planes = u8::MAX;
|
||||
let mut max_planes = 0u8;
|
||||
let mut sections = Vec::new();
|
||||
sections.try_reserve_exact(tensor_count as usize).map_err(|_| "KAR allocation failed")?;
|
||||
let mut sources = Vec::new();
|
||||
sources.try_reserve_exact(tensor_count as usize).map_err(|_| "KAR allocation failed")?;
|
||||
let header_bytes = read_region(&mut file, 0, HEADER_BYTES)?;
|
||||
let header = KarHeader::parse(&header_bytes, file_bytes)?;
|
||||
let names = read_region(&mut file, header.string_offset, header.string_bytes as usize)?;
|
||||
let directory = read_region(&mut file, header.directory_offset, header.directory_bytes as usize)?;
|
||||
check_directory_digest(&header_bytes, &names, &directory)?;
|
||||
let mut scan = RecordScan::new(&header)?;
|
||||
let (records, remainder) = directory.as_chunks::<RECORD_BYTES>();
|
||||
debug_assert!(remainder.is_empty());
|
||||
for record in records {
|
||||
let name_start = u32_at(record, 0) as usize;
|
||||
let name_len = u16_at(record, 4) as usize;
|
||||
let name_end = name_start.checked_add(name_len).ok_or("KAR name offset overflow")?;
|
||||
if name_end >= names.len() || names[name_end] != 0 {
|
||||
return Err("invalid KAR tensor name bounds".into());
|
||||
}
|
||||
let name = std::str::from_utf8(&names[name_start..name_end]).map_err(|_| "KAR tensor name is not UTF-8")?;
|
||||
if !seen_names.insert(name) {
|
||||
return Err("duplicate KAR tensor name".into());
|
||||
}
|
||||
let n_dims = record[6] as usize;
|
||||
let storage = record[7];
|
||||
if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 {
|
||||
return Err("unsupported KAR tensor layout".into());
|
||||
}
|
||||
let dims = (0..4).map(|index| u64_at(record, 8 + index * 8)).collect::<Vec<_>>();
|
||||
if dims[n_dims..].iter().any(|dim| *dim != 1) {
|
||||
return Err("invalid KAR unused dimension".into());
|
||||
}
|
||||
let product = dims[..n_dims]
|
||||
.iter()
|
||||
.try_fold(1u64, |acc, dim| acc.checked_mul(*dim))
|
||||
.ok_or("KAR tensor shape overflow")?;
|
||||
let n_elements = u64_at(record, 48);
|
||||
if product != n_elements || n_elements == 0 {
|
||||
return Err("KAR tensor element count mismatch".into());
|
||||
}
|
||||
elements_sum = elements_sum.checked_add(n_elements).ok_or("KAR model element count overflow")?;
|
||||
let mut source_digest = [0u8; 32];
|
||||
source_digest.copy_from_slice(&record[128..160]);
|
||||
sources.push(KarTensorSource {
|
||||
name: name.to_owned(),
|
||||
dimensions: dims[..n_dims].to_vec(),
|
||||
dtype: record[41],
|
||||
digest: source_digest,
|
||||
offset: u64_at(record, 160),
|
||||
section_bytes: u64_at(record, 120),
|
||||
storage_class: storage,
|
||||
n_elements,
|
||||
planes_min: record[43],
|
||||
planes_max: record[44],
|
||||
section_offset: u64_at(record, 112),
|
||||
planes_offset: u64_at(record, 96),
|
||||
plane_stride_bytes: u32_at(record, 104),
|
||||
});
|
||||
let section_offset = u64_at(record, 112);
|
||||
let section_bytes = u64_at(record, 120);
|
||||
let section_end = section_offset.checked_add(section_bytes).ok_or("KAR tensor section overflow")?;
|
||||
if section_offset != previous_end || !section_offset.is_multiple_of(256) || section_end > archive_bytes {
|
||||
return Err("KAR tensor sections are not contiguous or bounded".into());
|
||||
}
|
||||
previous_end = section_end;
|
||||
sections.push(Section { offset: section_offset, bytes: section_bytes, crc32: u32_at(record, 108) });
|
||||
if storage == 0 {
|
||||
let group = u16_at(record, 46) as u64;
|
||||
let planes = record[42];
|
||||
let n_padded = u64_at(record, 56);
|
||||
if group == 0
|
||||
|| group > 1024
|
||||
|| !group.is_multiple_of(32)
|
||||
|| !(1..=16).contains(&planes)
|
||||
|| record[43] == 0
|
||||
|| record[43] > record[44]
|
||||
|| record[44] > planes
|
||||
|| record[45] > 1
|
||||
{
|
||||
return Err("invalid KAR nested tensor parameters".into());
|
||||
}
|
||||
let rounded = n_elements.div_ceil(group).checked_mul(group).ok_or("KAR padded count overflow")?;
|
||||
if n_padded != rounded {
|
||||
return Err("KAR padded tensor count mismatch".into());
|
||||
}
|
||||
let scales_offset = u64_at(record, 64);
|
||||
let scales_bytes = u64_at(record, 72);
|
||||
let books_offset = u64_at(record, 80);
|
||||
let books_bytes = u64_at(record, 88);
|
||||
let planes_offset = u64_at(record, 96);
|
||||
let stride = u32_at(record, 104) as u64;
|
||||
let expected_scales = (n_padded / group).checked_mul(2).ok_or("KAR scale count overflow")?;
|
||||
let expected_books = (1u64 << (planes as u32 + 2)) - 4;
|
||||
let plane_words_bytes = (n_padded / 32).checked_mul(4).ok_or("KAR plane size overflow")?;
|
||||
let expected_stride = round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?;
|
||||
let books_start = scales_offset
|
||||
.checked_add(scales_bytes)
|
||||
.and_then(|value| round_up(value, 16))
|
||||
.ok_or("KAR books offset overflow")?;
|
||||
let planes_start = books_offset
|
||||
.checked_add(books_bytes)
|
||||
.and_then(|value| round_up(value, 16))
|
||||
.ok_or("KAR planes offset overflow")?;
|
||||
if scales_offset != section_offset
|
||||
|| scales_bytes != expected_scales
|
||||
|| books_offset != books_start
|
||||
|| books_bytes != expected_books
|
||||
|| planes_offset != planes_start
|
||||
|| stride != expected_stride
|
||||
|| planes_offset.checked_add(planes as u64 * stride).is_none_or(|end| end > section_end)
|
||||
{
|
||||
return Err("invalid KAR nested tensor section layout".into());
|
||||
}
|
||||
let tensor_bits = (planes as u64)
|
||||
.checked_mul(n_padded)
|
||||
.and_then(|bits| (n_padded / group).checked_mul(16).and_then(|scale_bits| bits.checked_add(scale_bits)))
|
||||
.ok_or("KAR tensor bit count overflow")?;
|
||||
bits_sum = bits_sum.checked_add(tensor_bits).ok_or("KAR coded bit count overflow")?;
|
||||
min_planes = min_planes.min(record[43]);
|
||||
max_planes = max_planes.max(record[44]);
|
||||
} else {
|
||||
if record[42..48].iter().any(|value| *value != 0)
|
||||
|| u64_at(record, 56) != n_elements
|
||||
|| record[64..104].iter().any(|value| *value != 0)
|
||||
|| u32_at(record, 104) != 0
|
||||
{
|
||||
return Err("invalid KAR raw tensor metadata".into());
|
||||
}
|
||||
let width = if record[41] == 0 { 4 } else { 2 };
|
||||
if section_bytes < n_elements.checked_mul(width).ok_or("KAR raw tensor size overflow")? {
|
||||
return Err("KAR raw tensor section is too small".into());
|
||||
}
|
||||
}
|
||||
scan.record(&header, &names, record)?;
|
||||
}
|
||||
if previous_end != archive_bytes
|
||||
|| elements_sum != total_elements
|
||||
|| bits_sum != payload_bits
|
||||
|| header[104] != if min_planes == u8::MAX { 0 } else { min_planes }
|
||||
|| header[105] != max_planes
|
||||
{
|
||||
return Err("KAR aggregate metadata mismatch".into());
|
||||
}
|
||||
let summary = KarSummary {
|
||||
archive_bytes,
|
||||
tensor_count,
|
||||
total_elements,
|
||||
source_total_elements,
|
||||
accounted_bpw,
|
||||
source_digest,
|
||||
source_bytes,
|
||||
max_planes,
|
||||
};
|
||||
scan.finish(&header, &header_bytes)?;
|
||||
Ok(Parsed {
|
||||
summary,
|
||||
summary: header.summary(scan.max_planes),
|
||||
file,
|
||||
sections,
|
||||
sources,
|
||||
sections: scan.sections,
|
||||
sources: scan.sources,
|
||||
directory,
|
||||
payload_offset,
|
||||
metadata_bytes: HEADER_BYTES as u64 + string_bytes + directory_bytes,
|
||||
payload_offset: header.payload_offset,
|
||||
metadata_bytes: HEADER_BYTES as u64 + header.string_bytes + header.directory_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
fn check_directory_digest(header: &[u8], names: &[u8], directory: &[u8]) -> Result<(), String> {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(names);
|
||||
digest.update(directory);
|
||||
if digest.finalize().as_slice() != &header[160..192] {
|
||||
return Err("KAR directory digest mismatch".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The 256-byte KAR header: its fields, and the bounded checks that run before any table is read.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The header fields `inspect_file` uses once the header checks passed.
|
||||
pub(super) struct KarHeader {
|
||||
pub(super) directory_offset: u64,
|
||||
pub(super) tensor_count: u32,
|
||||
pub(super) string_offset: u64,
|
||||
pub(super) string_bytes: u64,
|
||||
pub(super) payload_offset: u64,
|
||||
pub(super) archive_bytes: u64,
|
||||
pub(super) total_elements: u64,
|
||||
pub(super) payload_bits: u64,
|
||||
pub(super) source_total_elements: u64,
|
||||
pub(super) source_bytes: u64,
|
||||
pub(super) accounted_bpw: f64,
|
||||
pub(super) source_digest: [u8; 32],
|
||||
/// `tensor_count * RECORD_BYTES`; a u32 count times 192 cannot overflow u64.
|
||||
pub(super) directory_bytes: u64,
|
||||
}
|
||||
|
||||
impl KarHeader {
|
||||
pub(super) fn parse(header: &[u8], file_bytes: u64) -> Result<Self, String> {
|
||||
check_identity(header)?;
|
||||
let parsed = Self::read(header);
|
||||
parsed.check_sizes(header, file_bytes)?;
|
||||
parsed.check_offsets()?;
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
fn read(header: &[u8]) -> Self {
|
||||
let mut source_digest = [0; 32];
|
||||
source_digest.copy_from_slice(&header[128..160]);
|
||||
let tensor_count = u32_at(header, 32);
|
||||
Self {
|
||||
directory_offset: u64_at(header, 24),
|
||||
tensor_count,
|
||||
string_offset: u64_at(header, 40),
|
||||
string_bytes: u64_at(header, 48),
|
||||
payload_offset: u64_at(header, 56),
|
||||
archive_bytes: u64_at(header, 64),
|
||||
total_elements: u64_at(header, 72),
|
||||
payload_bits: u64_at(header, 80),
|
||||
source_total_elements: u64_at(header, 88),
|
||||
source_bytes: u64_at(header, 120),
|
||||
accounted_bpw: f64::from_le_bytes(header[96..104].try_into().unwrap()),
|
||||
source_digest,
|
||||
directory_bytes: tensor_count as u64 * RECORD_BYTES as u64,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn summary(&self, max_planes: u8) -> KarSummary {
|
||||
KarSummary {
|
||||
archive_bytes: self.archive_bytes,
|
||||
tensor_count: self.tensor_count,
|
||||
total_elements: self.total_elements,
|
||||
source_total_elements: self.source_total_elements,
|
||||
accounted_bpw: self.accounted_bpw,
|
||||
source_digest: self.source_digest,
|
||||
source_bytes: self.source_bytes,
|
||||
max_planes,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_sizes(&self, header: &[u8], file_bytes: u64) -> Result<(), String> {
|
||||
if self.archive_bytes != file_bytes || self.archive_bytes < HEADER_BYTES as u64 {
|
||||
return Err("KAR archive length mismatch".into());
|
||||
}
|
||||
if self.tensor_count == 0 || self.tensor_count as usize > MAX_TENSORS || self.string_bytes > MAX_NAMES as u64 {
|
||||
return Err("KAR metadata exceeds bounded inspector limits".into());
|
||||
}
|
||||
self.check_flags(header)?;
|
||||
self.check_bits_per_weight()
|
||||
}
|
||||
|
||||
fn check_flags(&self, header: &[u8]) -> Result<(), String> {
|
||||
if u32_at(header, 36) != 0
|
||||
|| header[106] != 1
|
||||
|| self.total_elements == 0
|
||||
|| self.total_elements > self.source_total_elements
|
||||
|| self.source_bytes == 0
|
||||
{
|
||||
return Err("invalid KAR flags, digest algorithm, or element counts".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_bits_per_weight(&self) -> Result<(), String> {
|
||||
let expected = self.archive_bytes as f64 * 8.0 / self.total_elements as f64;
|
||||
if !self.accounted_bpw.is_finite() || ((self.accounted_bpw - expected) / expected).abs() > 2f64.powi(-40) {
|
||||
return Err("KAR accounted_bpw does not match archive size".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_offsets(&self) -> Result<(), String> {
|
||||
let directory_end = self.directory_offset.checked_add(self.directory_bytes).ok_or("KAR directory overflow")?;
|
||||
let string_end = self.string_offset.checked_add(self.string_bytes).ok_or("KAR string table overflow")?;
|
||||
if !self.aligned()
|
||||
|| self.directory_offset < HEADER_BYTES as u64
|
||||
|| directory_end > self.string_offset
|
||||
|| string_end > self.payload_offset
|
||||
|| self.payload_offset > self.archive_bytes
|
||||
{
|
||||
return Err("invalid KAR metadata offsets or alignment".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn aligned(&self) -> bool {
|
||||
self.directory_offset.is_multiple_of(64)
|
||||
&& self.string_offset.is_multiple_of(64)
|
||||
&& self.payload_offset.is_multiple_of(256)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_identity(header: &[u8]) -> Result<(), String> {
|
||||
if &header[0..8] != b"KARCHIV2" || u32_at(header, 8) != 2 {
|
||||
return Err("unsupported KAR archive magic or version".into());
|
||||
}
|
||||
if u32_at(header, 12) != 0x04030201
|
||||
|| u32_at(header, 16) != HEADER_BYTES as u32
|
||||
|| u32_at(header, 20) != RECORD_BYTES as u32
|
||||
{
|
||||
return Err("invalid KAR byte order or record size".into());
|
||||
}
|
||||
if crc32(&header[..192]) != u32_at(header, 192) {
|
||||
return Err("KAR header CRC-32 mismatch".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! The nested (storage class 0) record of the KAR directory: parameters, section layout and coded bits.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The group, plane count and padded element count of one nested tensor.
|
||||
pub(super) struct Nested {
|
||||
group: u64,
|
||||
planes: u8,
|
||||
n_padded: u64,
|
||||
}
|
||||
|
||||
/// The offsets and sizes a nested record states for the pieces of its section.
|
||||
#[derive(PartialEq)]
|
||||
struct Spans {
|
||||
scales_offset: u64,
|
||||
scales_bytes: u64,
|
||||
books_offset: u64,
|
||||
books_bytes: u64,
|
||||
planes_offset: u64,
|
||||
stride: u64,
|
||||
}
|
||||
|
||||
impl Spans {
|
||||
fn read(record: &[u8]) -> Self {
|
||||
Self {
|
||||
scales_offset: u64_at(record, 64),
|
||||
scales_bytes: u64_at(record, 72),
|
||||
books_offset: u64_at(record, 80),
|
||||
books_bytes: u64_at(record, 88),
|
||||
planes_offset: u64_at(record, 96),
|
||||
stride: u32_at(record, 104) as u64,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the pieces must lie for a section that starts at `section_offset`, given the sizes this record states.
|
||||
fn expected(&self, nested: &Nested, section_offset: u64) -> Result<Self, String> {
|
||||
let scales_bytes = (nested.n_padded / nested.group).checked_mul(2).ok_or("KAR scale count overflow")?;
|
||||
let books_bytes = (1u64 << (nested.planes as u32 + 2)) - 4;
|
||||
let stride = nested.plane_stride()?;
|
||||
let books_offset = self
|
||||
.scales_offset
|
||||
.checked_add(self.scales_bytes)
|
||||
.and_then(|value| round_up(value, 16))
|
||||
.ok_or("KAR books offset overflow")?;
|
||||
let planes_offset = self
|
||||
.books_offset
|
||||
.checked_add(self.books_bytes)
|
||||
.and_then(|value| round_up(value, 16))
|
||||
.ok_or("KAR planes offset overflow")?;
|
||||
Ok(Self { scales_offset: section_offset, scales_bytes, books_offset, books_bytes, planes_offset, stride })
|
||||
}
|
||||
|
||||
fn planes_fit(&self, planes: u8, section_end: u64) -> bool {
|
||||
self.planes_offset.checked_add(planes as u64 * self.stride).is_some_and(|end| end <= section_end)
|
||||
}
|
||||
}
|
||||
|
||||
impl Nested {
|
||||
pub(super) fn read(record: &[u8], n_elements: u64) -> Result<Self, String> {
|
||||
let group = u16_at(record, 46) as u64;
|
||||
let planes = record[42];
|
||||
let n_padded = u64_at(record, 56);
|
||||
if !valid_parameters(record, group, planes) {
|
||||
return Err("invalid KAR nested tensor parameters".into());
|
||||
}
|
||||
let rounded = n_elements.div_ceil(group).checked_mul(group).ok_or("KAR padded count overflow")?;
|
||||
if n_padded != rounded {
|
||||
return Err("KAR padded tensor count mismatch".into());
|
||||
}
|
||||
Ok(Self { group, planes, n_padded })
|
||||
}
|
||||
|
||||
fn plane_stride(&self) -> Result<u64, String> {
|
||||
let plane_words_bytes = (self.n_padded / 32).checked_mul(4).ok_or("KAR plane size overflow")?;
|
||||
round_up(plane_words_bytes, 16).ok_or_else(|| "KAR plane stride overflow".to_owned())
|
||||
}
|
||||
|
||||
pub(super) fn check_layout(&self, record: &[u8], section_offset: u64, section_end: u64) -> Result<(), String> {
|
||||
let actual = Spans::read(record);
|
||||
let expected = actual.expected(self, section_offset)?;
|
||||
if actual != expected || !actual.planes_fit(self.planes, section_end) {
|
||||
return Err("invalid KAR nested tensor section layout".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn coded_bits(&self) -> Result<u64, String> {
|
||||
let scale_bits = (self.n_padded / self.group).checked_mul(16);
|
||||
(self.planes as u64)
|
||||
.checked_mul(self.n_padded)
|
||||
.and_then(|bits| scale_bits.and_then(|scale_bits| bits.checked_add(scale_bits)))
|
||||
.ok_or_else(|| "KAR tensor bit count overflow".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_parameters(record: &[u8], group: u64, planes: u8) -> bool {
|
||||
group != 0
|
||||
&& group <= 1024
|
||||
&& group.is_multiple_of(32)
|
||||
&& (1..=16).contains(&planes)
|
||||
&& record[43] != 0
|
||||
&& record[43] <= record[44]
|
||||
&& record[44] <= planes
|
||||
&& record[45] <= 1
|
||||
}
|
||||
|
||||
/// The checks of a raw (storage class 1) record.
|
||||
pub(super) fn check_raw(record: &[u8], n_elements: u64) -> Result<(), String> {
|
||||
if record[42..48].iter().any(|value| *value != 0)
|
||||
|| u64_at(record, 56) != n_elements
|
||||
|| record[64..104].iter().any(|value| *value != 0)
|
||||
|| u32_at(record, 104) != 0
|
||||
{
|
||||
return Err("invalid KAR raw tensor metadata".into());
|
||||
}
|
||||
let width = if record[41] == 0 { 4 } else { 2 };
|
||||
if u64_at(record, 120) < n_elements.checked_mul(width).ok_or("KAR raw tensor size overflow")? {
|
||||
return Err("KAR raw tensor section is too small".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! The directory records of a KAR archive, checked one by one against the header totals.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
use super::nested::{Nested, check_raw};
|
||||
|
||||
/// The running totals of the record loop; `finish` compares them with the header.
|
||||
pub(super) struct RecordScan<'a> {
|
||||
seen_names: HashSet<&'a str>,
|
||||
elements_sum: u64,
|
||||
bits_sum: u64,
|
||||
previous_end: u64,
|
||||
min_planes: u8,
|
||||
pub(super) max_planes: u8,
|
||||
pub(super) sections: Vec<Section>,
|
||||
pub(super) sources: Vec<KarTensorSource>,
|
||||
}
|
||||
|
||||
impl<'a> RecordScan<'a> {
|
||||
pub(super) fn new(header: &KarHeader) -> Result<Self, String> {
|
||||
let count = header.tensor_count as usize;
|
||||
let mut seen_names = HashSet::new();
|
||||
seen_names.try_reserve(count).map_err(|_| "KAR allocation failed")?;
|
||||
let mut sections = Vec::new();
|
||||
sections.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?;
|
||||
let mut sources = Vec::new();
|
||||
sources.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?;
|
||||
Ok(Self {
|
||||
seen_names,
|
||||
elements_sum: 0,
|
||||
bits_sum: 0,
|
||||
previous_end: header.payload_offset,
|
||||
min_planes: u8::MAX,
|
||||
max_planes: 0,
|
||||
sections,
|
||||
sources,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn record(&mut self, header: &KarHeader, names: &'a [u8], record: &[u8]) -> Result<(), String> {
|
||||
let name = self.unique_name(names, record)?;
|
||||
let dims = record_dims(record)?;
|
||||
let n_elements = element_count(record, &dims)?;
|
||||
self.elements_sum = self.elements_sum.checked_add(n_elements).ok_or("KAR model element count overflow")?;
|
||||
self.sources.push(tensor_source(name, &dims, record, n_elements));
|
||||
let section_end = self.add_section(header, record)?;
|
||||
if record[7] == 0 { self.nested(record, n_elements, section_end) } else { check_raw(record, n_elements) }
|
||||
}
|
||||
|
||||
pub(super) fn finish(&self, header: &KarHeader, header_bytes: &[u8]) -> Result<(), String> {
|
||||
let min_planes = if self.min_planes == u8::MAX { 0 } else { self.min_planes };
|
||||
if self.previous_end != header.archive_bytes
|
||||
|| self.elements_sum != header.total_elements
|
||||
|| self.bits_sum != header.payload_bits
|
||||
|| header_bytes[104] != min_planes
|
||||
|| header_bytes[105] != self.max_planes
|
||||
{
|
||||
return Err("KAR aggregate metadata mismatch".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unique_name(&mut self, names: &'a [u8], record: &[u8]) -> Result<&'a str, String> {
|
||||
let name_start = u32_at(record, 0) as usize;
|
||||
let name_len = u16_at(record, 4) as usize;
|
||||
let name_end = name_start.checked_add(name_len).ok_or("KAR name offset overflow")?;
|
||||
if name_end >= names.len() || names[name_end] != 0 {
|
||||
return Err("invalid KAR tensor name bounds".into());
|
||||
}
|
||||
let name = std::str::from_utf8(&names[name_start..name_end]).map_err(|_| "KAR tensor name is not UTF-8")?;
|
||||
if !self.seen_names.insert(name) {
|
||||
return Err("duplicate KAR tensor name".into());
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Checks that the section follows the previous one and lies inside the archive; returns its end.
|
||||
fn add_section(&mut self, header: &KarHeader, record: &[u8]) -> Result<u64, String> {
|
||||
let section_offset = u64_at(record, 112);
|
||||
let section_bytes = u64_at(record, 120);
|
||||
let section_end = section_offset.checked_add(section_bytes).ok_or("KAR tensor section overflow")?;
|
||||
if section_offset != self.previous_end
|
||||
|| !section_offset.is_multiple_of(256)
|
||||
|| section_end > header.archive_bytes
|
||||
{
|
||||
return Err("KAR tensor sections are not contiguous or bounded".into());
|
||||
}
|
||||
self.previous_end = section_end;
|
||||
self.sections.push(Section { offset: section_offset, bytes: section_bytes, crc32: u32_at(record, 108) });
|
||||
Ok(section_end)
|
||||
}
|
||||
|
||||
fn nested(&mut self, record: &[u8], n_elements: u64, section_end: u64) -> Result<(), String> {
|
||||
let nested = Nested::read(record, n_elements)?;
|
||||
nested.check_layout(record, u64_at(record, 112), section_end)?;
|
||||
self.bits_sum = self.bits_sum.checked_add(nested.coded_bits()?).ok_or("KAR coded bit count overflow")?;
|
||||
self.min_planes = self.min_planes.min(record[43]);
|
||||
self.max_planes = self.max_planes.max(record[44]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The dimensions of a record (as many as it declares) after the layout and unused-dimension checks.
|
||||
fn record_dims(record: &[u8]) -> Result<Vec<u64>, String> {
|
||||
let n_dims = record[6] as usize;
|
||||
if !(1..=4).contains(&n_dims) || record[7] > 1 || record[40] != 0 || record[41] > 2 {
|
||||
return Err("unsupported KAR tensor layout".into());
|
||||
}
|
||||
let mut dims = (0..4).map(|index| u64_at(record, 8 + index * 8)).collect::<Vec<_>>();
|
||||
if dims[n_dims..].iter().any(|dim| *dim != 1) {
|
||||
return Err("invalid KAR unused dimension".into());
|
||||
}
|
||||
dims.truncate(n_dims);
|
||||
Ok(dims)
|
||||
}
|
||||
|
||||
fn element_count(record: &[u8], dims: &[u64]) -> Result<u64, String> {
|
||||
let product = dims.iter().try_fold(1u64, |acc, dim| acc.checked_mul(*dim)).ok_or("KAR tensor shape overflow")?;
|
||||
let n_elements = u64_at(record, 48);
|
||||
if product != n_elements || n_elements == 0 {
|
||||
return Err("KAR tensor element count mismatch".into());
|
||||
}
|
||||
Ok(n_elements)
|
||||
}
|
||||
|
||||
fn tensor_source(name: &str, dims: &[u64], record: &[u8], n_elements: u64) -> KarTensorSource {
|
||||
let mut digest = [0u8; 32];
|
||||
digest.copy_from_slice(&record[128..160]);
|
||||
KarTensorSource {
|
||||
name: name.to_owned(),
|
||||
dimensions: dims.to_vec(),
|
||||
dtype: record[41],
|
||||
digest,
|
||||
offset: u64_at(record, 160),
|
||||
section_bytes: u64_at(record, 120),
|
||||
storage_class: record[7],
|
||||
n_elements,
|
||||
planes_min: record[43],
|
||||
planes_max: record[44],
|
||||
section_offset: u64_at(record, 112),
|
||||
planes_offset: u64_at(record, 96),
|
||||
plane_stride_bytes: u32_at(record, 104),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user