[ABI][GW][Docs] encoder guard fields + sha256 provenance; Inkling tensor inventory; BGE-M3 recipe correction
- abi::bundle: manifest guard fields from the strata-ctl encoder incident
(review/2026-12-01-guardie-encoder.md): provenance {repo_id, revision,
shards sha256 = HF lfs.oid anchor, 64 lowercase hex validated},
model_kind decoder|encoder (encoder REQUIRES the full encoder_recipe:
pooling, end_text_token id, append_end_text, max_tokens, query/doc prefix,
native_dim — never derived from architecture), calibration {floor_hit,
peak_noise} finite in [-1,1]. Identity is provenance, not tensor shape.
- abi::sha256: pure FIPS 180-4, streaming update for GB shards, zero deps;
NIST vectors + million-a + streaming/chunk parity tests.
- abi::vplan: pool_l2norm generalized (mode mean|cls|last_token from the
manifest recipe), replacing mean_pool_l2norm.
- gw: `vetta-infer tensors <dir> [prefix]` subcommand; captured the live
Inkling inventory (docs/inkling-tensor-inventory.txt, 1244 tensors:
994 BF16 / 154 F32 / 48 F8_E4M3 / 48 U8) — ground truth for the importer.
- BGE-M3 recipe verified on the artifact: dense = CLS (1_Pooling/config.json
+ reference converter), 16 heads x 64, absolute position embeddings present;
spec/README corrected. Ordering: Inkling first, utility after (Federico).
- review/: tandem exchange (guardie + nostra risposta + osservazioni-recipe).
Verified live: RUSTFLAGS="-D warnings" cargo test --workspace = 75/75 PASS;
lean proofs/{slab_ring_dma,bus_lifecycle,serve_session,arena_plan}.lean green
(42 theorems, 0 sorryAx, standard axioms only).
This commit is contained in:
1 parent
fb92662106
commit
4de272beb1
11 files changed
+2101
-12
No files matched your search
@@ -10,13 +10,72 @@ use crate::vplan::VplanOp;
|
||||
/// Bumped on any breaking change to the bundle layout or plan semantics.
|
||||
pub const ABI_VERSION: u32 = 1;
|
||||
|
||||
/// Decoder (generative MoE) vs encoder (utility embedder/reranker).
|
||||
/// Identity is PROVENANCE, not tensor shape: an embedder and a reranker of the
|
||||
/// same base share names/shapes/architectures (strata-ctl incident 2026-12-01).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ModelKind {
|
||||
Decoder,
|
||||
Encoder,
|
||||
}
|
||||
|
||||
/// Pooling is a DECLARED property of the import, never derived from the
|
||||
/// architecture string (bert ≠ mean, qwen3 ≠ last-token).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Pooling {
|
||||
Mean,
|
||||
Cls,
|
||||
LastToken,
|
||||
}
|
||||
|
||||
/// Per-shard sha256 anchor (HuggingFace `lfs.oid`): the only format-independent
|
||||
/// proof that the artifact is the one the publisher shipped.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ShardHash {
|
||||
pub name: String,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Provenance {
|
||||
pub repo_id: String,
|
||||
pub revision: String,
|
||||
pub shards: Vec<ShardHash>,
|
||||
}
|
||||
|
||||
/// The complete input recipe of an encoder bundle — six fields, no defaults
|
||||
/// guessed from the architecture. Prefixes are asymmetric (query-only for
|
||||
/// instruction-tuned embedders); BGE-M3 uses none.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EncoderRecipe {
|
||||
pub pooling: Pooling,
|
||||
pub end_text_token: Option<u32>,
|
||||
pub append_end_text: bool,
|
||||
pub max_tokens: u32,
|
||||
pub query_prefix: String,
|
||||
pub doc_prefix: String,
|
||||
pub native_dim: u32,
|
||||
}
|
||||
|
||||
/// Measured cosine-scale calibration handed to the consumer (strata-ctl keeps
|
||||
/// a per-model_id threshold table): floor of true hits, peak of noise pairs.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Calibration {
|
||||
pub floor_hit: f64,
|
||||
pub peak_noise: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Manifest {
|
||||
pub model_id: String,
|
||||
pub source_fingerprint: u64,
|
||||
pub packer_fingerprint: u64,
|
||||
pub abi_version: u32,
|
||||
pub backend_target: String,
|
||||
pub kind: ModelKind,
|
||||
pub provenance: Option<Provenance>,
|
||||
pub recipe: Option<EncoderRecipe>,
|
||||
pub calibration: Option<Calibration>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -80,7 +139,88 @@ fn idx_arr(v: &JsonVal) -> Result<Vec<usize>, BundleError> {
|
||||
v.as_arr().ok_or(BundleError::BadField("indices"))?.iter().map(idx).collect()
|
||||
}
|
||||
|
||||
fn valid_sha256(s: &str) -> bool {
|
||||
s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
}
|
||||
|
||||
fn parse_provenance(v: &JsonVal) -> Result<Provenance, BundleError> {
|
||||
let m = obj(v)?;
|
||||
let shards_v = field(m, "shards")?.as_arr().ok_or(BundleError::BadField("shards"))?;
|
||||
let mut shards = Vec::with_capacity(shards_v.len());
|
||||
for s in shards_v {
|
||||
let sm = obj(s)?;
|
||||
let sha = str_field(sm, "sha256")?;
|
||||
if !valid_sha256(&sha) {
|
||||
return Err(BundleError::BadField("sha256"));
|
||||
}
|
||||
shards.push(ShardHash { name: str_field(sm, "name")?, sha256: sha });
|
||||
}
|
||||
Ok(Provenance {
|
||||
repo_id: str_field(m, "repo_id")?,
|
||||
revision: str_field(m, "revision")?,
|
||||
shards,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_recipe(v: &JsonVal) -> Result<EncoderRecipe, BundleError> {
|
||||
let m = obj(v)?;
|
||||
let pooling = match field(m, "pooling")?.as_str() {
|
||||
Some("mean") => Pooling::Mean,
|
||||
Some("cls") => Pooling::Cls,
|
||||
Some("last_token") => Pooling::LastToken,
|
||||
_ => return Err(BundleError::BadField("pooling")),
|
||||
};
|
||||
let end_text_token = match m.get("end_text_token") {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
let n = v.as_u64().ok_or(BundleError::BadField("end_text_token"))?;
|
||||
Some(u32::try_from(n).map_err(|_| BundleError::BadField("end_text_token"))?)
|
||||
}
|
||||
};
|
||||
let append_end_text = match field(m, "append_end_text")? {
|
||||
JsonVal::Bool(b) => *b,
|
||||
_ => return Err(BundleError::BadField("append_end_text")),
|
||||
};
|
||||
let dim = |k: &'static str| -> Result<u32, BundleError> {
|
||||
let n = u64_field(m, k)?;
|
||||
u32::try_from(n).map_err(|_| BundleError::BadField(k))
|
||||
};
|
||||
Ok(EncoderRecipe {
|
||||
pooling,
|
||||
end_text_token,
|
||||
append_end_text,
|
||||
max_tokens: dim("max_tokens")?,
|
||||
query_prefix: str_field(m, "query_prefix")?,
|
||||
doc_prefix: str_field(m, "doc_prefix")?,
|
||||
native_dim: dim("native_dim")?,
|
||||
})
|
||||
}
|
||||
|
||||
fn cosine_field(
|
||||
m: &std::collections::HashMap<String, JsonVal>,
|
||||
k: &'static str,
|
||||
) -> Result<f64, BundleError> {
|
||||
let f = match field(m, k)? {
|
||||
JsonVal::Num(f) => *f,
|
||||
JsonVal::Int(n) => *n as f64,
|
||||
_ => return Err(BundleError::BadField(k)),
|
||||
};
|
||||
if !f.is_finite() || !(-1.0..=1.0).contains(&f) {
|
||||
return Err(BundleError::BadField(k));
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
fn parse_calibration(v: &JsonVal) -> Result<Calibration, BundleError> {
|
||||
let m = obj(v)?;
|
||||
Ok(Calibration {
|
||||
floor_hit: cosine_field(m, "floor_hit")?,
|
||||
peak_noise: cosine_field(m, "peak_noise")?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse `manifest.json`; rejects incompatible ABI versions explicitly.
|
||||
/// Encoder bundles MUST carry the full input recipe (no silent defaults).
|
||||
pub fn parse_manifest(text: &str) -> Result<Manifest, BundleError> {
|
||||
let v = parse_json(text).map_err(BundleError::Json)?;
|
||||
let m = obj(&v)?;
|
||||
@@ -89,12 +229,36 @@ pub fn parse_manifest(text: &str) -> Result<Manifest, BundleError> {
|
||||
if abi_version != ABI_VERSION {
|
||||
return Err(BundleError::AbiMismatch { found: abi_version, expected: ABI_VERSION });
|
||||
}
|
||||
let kind = match m.get("model_kind") {
|
||||
None => ModelKind::Decoder,
|
||||
Some(v) => match v.as_str() {
|
||||
Some("decoder") => ModelKind::Decoder,
|
||||
Some("encoder") => ModelKind::Encoder,
|
||||
_ => return Err(BundleError::BadField("model_kind")),
|
||||
},
|
||||
};
|
||||
let provenance = match m.get("provenance") {
|
||||
Some(v) => Some(parse_provenance(v)?),
|
||||
None => None,
|
||||
};
|
||||
let recipe = match kind {
|
||||
ModelKind::Encoder => Some(parse_recipe(field(m, "encoder_recipe")?)?),
|
||||
ModelKind::Decoder => None,
|
||||
};
|
||||
let calibration = match m.get("calibration") {
|
||||
Some(v) => Some(parse_calibration(v)?),
|
||||
None => None,
|
||||
};
|
||||
Ok(Manifest {
|
||||
model_id: str_field(m, "model_id")?,
|
||||
source_fingerprint: u64_field(m, "source_fingerprint")?,
|
||||
packer_fingerprint: u64_field(m, "packer_fingerprint")?,
|
||||
abi_version,
|
||||
backend_target: str_field(m, "backend_target")?,
|
||||
kind,
|
||||
provenance,
|
||||
recipe,
|
||||
calibration,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -235,11 +399,89 @@ mod tests {
|
||||
let g = r#"{"ops":[{"op":"layer_norm","reads":[0],"writes":[1]},
|
||||
{"op":"flash_full_attn","reads":[1],"writes":[2]},
|
||||
{"op":"gelu_erf","reads":[2],"writes":[3]},
|
||||
{"op":"mean_pool_l2norm","reads":[3],"writes":[4]}]}"#;
|
||||
{"op":"pool_l2norm","reads":[3],"writes":[4]}]}"#;
|
||||
let m = r#"{"decls":[{"arena":0,"off":0,"len":8},{"arena":0,"off":8,"len":8},
|
||||
{"arena":0,"off":16,"len":8},{"arena":0,"off":24,"len":8},
|
||||
{"arena":0,"off":32,"len":8}],"inputs":[0]}"#;
|
||||
let c = compile(MANIFEST, m, g).unwrap();
|
||||
assert_eq!(c.graph[3].op, VplanOp::MeanPoolL2norm);
|
||||
assert_eq!(c.graph[3].op, VplanOp::PoolL2norm);
|
||||
}
|
||||
|
||||
// --- Guard fields (strata-ctl incident 2026-12-01): provenance, recipe,
|
||||
// calibration. Identity is provenance, pooling is declared, the cosine
|
||||
// scale is measured — nothing is guessed from the architecture. ---
|
||||
|
||||
const BGE_MANIFEST: &str = r#"{"model_id":"bge-m3","source_fingerprint":1,
|
||||
"packer_fingerprint":2,"abi_version":1,"backend_target":"gfx1150",
|
||||
"model_kind":"encoder",
|
||||
"provenance":{"repo_id":"BAAI/bge-m3","revision":"main","shards":[
|
||||
{"name":"model.safetensors","sha256":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}]},
|
||||
"encoder_recipe":{"pooling":"mean","append_end_text":false,"max_tokens":8192,
|
||||
"query_prefix":"","doc_prefix":"","native_dim":1024},
|
||||
"calibration":{"floor_hit":0.516,"peak_noise":0.40}}"#;
|
||||
|
||||
#[test]
|
||||
fn encoder_manifest_full_recipe() {
|
||||
let m = parse_manifest(BGE_MANIFEST).unwrap();
|
||||
assert_eq!(m.kind, ModelKind::Encoder);
|
||||
let r = m.recipe.unwrap();
|
||||
assert_eq!(r.pooling, Pooling::Mean);
|
||||
assert_eq!(r.native_dim, 1024);
|
||||
assert!(r.query_prefix.is_empty() && r.doc_prefix.is_empty()); // BGE-M3: no prefixes
|
||||
assert!(!r.append_end_text);
|
||||
assert_eq!(m.provenance.unwrap().shards[0].sha256.len(), 64);
|
||||
let c = m.calibration.unwrap();
|
||||
assert!((c.floor_hit - 0.516).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoder_without_recipe_rejected() {
|
||||
let bad = BGE_MANIFEST.replace(
|
||||
r#""encoder_recipe":{"pooling":"mean","append_end_text":false,"max_tokens":8192,
|
||||
"query_prefix":"","doc_prefix":"","native_dim":1024},"#,
|
||||
"",
|
||||
);
|
||||
assert_eq!(parse_manifest(&bad), Err(BundleError::MissingField("encoder_recipe")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_default_kind_and_unknown_kind() {
|
||||
assert_eq!(parse_manifest(MANIFEST).unwrap().kind, ModelKind::Decoder);
|
||||
let bad = MANIFEST.replace("\"backend_target\":\"gfx1150\"", "\"backend_target\":\"gfx1150\",\"model_kind\":\"warp\"");
|
||||
assert_eq!(parse_manifest(&bad), Err(BundleError::BadField("model_kind")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_sha256_rejected() {
|
||||
let short = BGE_MANIFEST.replace(
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
"06507c7b",
|
||||
);
|
||||
assert_eq!(parse_manifest(&short), Err(BundleError::BadField("sha256")));
|
||||
let upper = BGE_MANIFEST.replace(
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
"0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF",
|
||||
);
|
||||
assert_eq!(parse_manifest(&upper), Err(BundleError::BadField("sha256")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibration_out_of_cosine_range_rejected() {
|
||||
let bad = BGE_MANIFEST.replace("\"floor_hit\":0.516", "\"floor_hit\":1.5");
|
||||
assert_eq!(parse_manifest(&bad), Err(BundleError::BadField("floor_hit")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_token_recipe_with_end_text_id() {
|
||||
// Qwen3-style: last-token pooling, per-artifact end-text id, query-only prefix.
|
||||
let m = BGE_MANIFEST
|
||||
.replace("\"pooling\":\"mean\"", "\"pooling\":\"last_token\"")
|
||||
.replace("\"append_end_text\":false", "\"end_text_token\":151643,\"append_end_text\":true")
|
||||
.replace("\"query_prefix\":\"\"", "\"query_prefix\":\"Instruct: task\\nQuery:\"");
|
||||
let r = parse_manifest(&m).unwrap().recipe.unwrap();
|
||||
assert_eq!(r.pooling, Pooling::LastToken);
|
||||
assert_eq!(r.end_text_token, Some(151643));
|
||||
assert!(r.append_end_text);
|
||||
assert!(r.doc_prefix.is_empty()); // asymmetric: prefix on query only
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod bus;
|
||||
pub mod json;
|
||||
pub mod sampler;
|
||||
pub mod serve;
|
||||
pub mod sha256;
|
||||
pub mod traits;
|
||||
pub mod vplan;
|
||||
pub mod vtc1;
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! Pure SHA-256 (FIPS 180-4), zero external dependencies.
|
||||
//!
|
||||
//! The provenance anchor of `.vbundle` (docs/ARCHITECTURE.md §3): the packer
|
||||
//! verifies each shard's computed sha256 against the publisher's `lfs.oid`
|
||||
//! before writing a bundle — identity is provenance, not tensor shape
|
||||
//! (strata-ctl incident 2026-12-01). Streaming `update` for GB-scale shards.
|
||||
|
||||
const K: [u32; 64] = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
];
|
||||
|
||||
const H0: [u32; 8] = [
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
||||
];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Sha256 {
|
||||
h: [u32; 8],
|
||||
buf: [u8; 64],
|
||||
fill: usize,
|
||||
len: u64,
|
||||
}
|
||||
|
||||
impl Default for Sha256 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Sha256 {
|
||||
pub fn new() -> Self {
|
||||
Self { h: H0, buf: [0; 64], fill: 0, len: 0 }
|
||||
}
|
||||
|
||||
pub fn update(&mut self, mut data: &[u8]) {
|
||||
self.len = self.len.checked_add(data.len() as u64).expect("sha256: message length overflow");
|
||||
if self.fill > 0 {
|
||||
let need = 64 - self.fill;
|
||||
let take = need.min(data.len());
|
||||
self.buf[self.fill..self.fill + take].copy_from_slice(&data[..take]);
|
||||
self.fill += take;
|
||||
data = &data[take..];
|
||||
if self.fill == 64 {
|
||||
let block = self.buf;
|
||||
self.process_block(&block);
|
||||
self.fill = 0;
|
||||
}
|
||||
}
|
||||
while data.len() >= 64 {
|
||||
let block: [u8; 64] = data[..64].try_into().unwrap();
|
||||
self.process_block(&block);
|
||||
data = &data[64..];
|
||||
}
|
||||
if !data.is_empty() {
|
||||
self.buf[..data.len()].copy_from_slice(data);
|
||||
self.fill = data.len();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finalize(mut self) -> [u8; 32] {
|
||||
let bit_len = self.len.checked_mul(8).expect("sha256: bit length overflow");
|
||||
// Padding is NOT counted in the message length.
|
||||
self.buf[self.fill] = 0x80;
|
||||
self.fill += 1;
|
||||
if self.fill > 56 {
|
||||
self.buf[self.fill..].fill(0);
|
||||
let block = self.buf;
|
||||
self.process_block(&block);
|
||||
self.fill = 0;
|
||||
}
|
||||
self.buf[self.fill..56].fill(0);
|
||||
self.buf[56..64].copy_from_slice(&bit_len.to_be_bytes());
|
||||
let block = self.buf;
|
||||
self.process_block(&block);
|
||||
let mut out = [0u8; 32];
|
||||
for (i, w) in self.h.iter().enumerate() {
|
||||
out[i * 4..i * 4 + 4].copy_from_slice(&w.to_be_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn process_block(&mut self, block: &[u8; 64]) {
|
||||
let mut w = [0u32; 64];
|
||||
for t in 0..16 {
|
||||
w[t] = u32::from_be_bytes(block[t * 4..t * 4 + 4].try_into().unwrap());
|
||||
}
|
||||
for t in 16..64 {
|
||||
let s0 = w[t - 15].rotate_right(7) ^ w[t - 15].rotate_right(18) ^ (w[t - 15] >> 3);
|
||||
let s1 = w[t - 2].rotate_right(17) ^ w[t - 2].rotate_right(19) ^ (w[t - 2] >> 10);
|
||||
w[t] = s1
|
||||
.wrapping_add(w[t - 7])
|
||||
.wrapping_add(s0)
|
||||
.wrapping_add(w[t - 16]);
|
||||
}
|
||||
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.h;
|
||||
for t in 0..64 {
|
||||
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
|
||||
let ch = (e & f) ^ ((!e) & g);
|
||||
let t1 = h
|
||||
.wrapping_add(s1)
|
||||
.wrapping_add(ch)
|
||||
.wrapping_add(K[t])
|
||||
.wrapping_add(w[t]);
|
||||
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
|
||||
let maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
let t2 = s0.wrapping_add(maj);
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d.wrapping_add(t1);
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = t1.wrapping_add(t2);
|
||||
}
|
||||
self.h[0] = self.h[0].wrapping_add(a);
|
||||
self.h[1] = self.h[1].wrapping_add(b);
|
||||
self.h[2] = self.h[2].wrapping_add(c);
|
||||
self.h[3] = self.h[3].wrapping_add(d);
|
||||
self.h[4] = self.h[4].wrapping_add(e);
|
||||
self.h[5] = self.h[5].wrapping_add(f);
|
||||
self.h[6] = self.h[6].wrapping_add(g);
|
||||
self.h[7] = self.h[7].wrapping_add(h);
|
||||
}
|
||||
}
|
||||
|
||||
/// One-shot convenience.
|
||||
pub fn sha256(data: &[u8]) -> [u8; 32] {
|
||||
let mut h = Sha256::new();
|
||||
h.update(data);
|
||||
h.finalize()
|
||||
}
|
||||
|
||||
/// Lowercase hex (the `lfs.oid` / manifest spelling).
|
||||
pub fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
|
||||
s.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nist_vectors() {
|
||||
assert_eq!(
|
||||
hex(&sha256(b"")),
|
||||
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
);
|
||||
assert_eq!(
|
||||
hex(&sha256(b"abc")),
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||
);
|
||||
assert_eq!(
|
||||
hex(&sha256(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")),
|
||||
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn million_a_vector() {
|
||||
let data = vec![b'a'; 1_000_000];
|
||||
assert_eq!(
|
||||
hex(&sha256(&data)),
|
||||
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_matches_oneshot() {
|
||||
let data: Vec<u8> = (0..=255u8).cycle().take(1000).collect();
|
||||
let one = sha256(&data);
|
||||
// Odd chunk sizes exercise every buffer-fill path.
|
||||
for chunk in [1usize, 7, 63, 64, 65, 128] {
|
||||
let mut h = Sha256::new();
|
||||
for c in data.chunks(chunk) {
|
||||
h.update(c);
|
||||
}
|
||||
assert_eq!(h.finalize(), one, "chunk size {chunk}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_spelling() {
|
||||
assert_eq!(hex(&[0x00, 0x0f, 0xa5, 0xff]), "000fa5ff");
|
||||
assert_eq!(hex(&sha256(b"")).len(), 64);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,9 @@ pub enum VplanOp {
|
||||
LayerNorm,
|
||||
FlashFullAttn,
|
||||
GeluErf,
|
||||
MeanPoolL2norm,
|
||||
/// Pooling + L2 normalize; mode (mean | cls | last_token) comes from the
|
||||
/// manifest `encoder_recipe`, never guessed from the architecture.
|
||||
PoolL2norm,
|
||||
// Restricted control flow
|
||||
/// Repeat the enclosed layer body for each model layer.
|
||||
LoopLayer,
|
||||
@@ -65,7 +67,7 @@ impl VplanOp {
|
||||
Self::LayerNorm => "layer_norm",
|
||||
Self::FlashFullAttn => "flash_full_attn",
|
||||
Self::GeluErf => "gelu_erf",
|
||||
Self::MeanPoolL2norm => "mean_pool_l2norm",
|
||||
Self::PoolL2norm => "pool_l2norm",
|
||||
Self::LoopLayer => "loop_layer",
|
||||
Self::BranchB => "branch_b",
|
||||
}
|
||||
@@ -93,7 +95,7 @@ impl VplanOp {
|
||||
"layer_norm" => Self::LayerNorm,
|
||||
"flash_full_attn" => Self::FlashFullAttn,
|
||||
"gelu_erf" => Self::GeluErf,
|
||||
"mean_pool_l2norm" => Self::MeanPoolL2norm,
|
||||
"pool_l2norm" => Self::PoolL2norm,
|
||||
"loop_layer" => Self::LoopLayer,
|
||||
"branch_b" => Self::BranchB,
|
||||
_ => return None,
|
||||
@@ -122,7 +124,7 @@ mod tests {
|
||||
VplanOp::GdnRecurrentStep, VplanOp::MoeRouteBucket, VplanOp::MoeW13Wmma,
|
||||
VplanOp::MoeW2Wmma, VplanOp::MoeReduce, VplanOp::VitFlashAttnWmma,
|
||||
VplanOp::GpuPenaltiesTopk, VplanOp::LayerNorm, VplanOp::FlashFullAttn,
|
||||
VplanOp::GeluErf, VplanOp::MeanPoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
|
||||
VplanOp::GeluErf, VplanOp::PoolL2norm, VplanOp::LoopLayer, VplanOp::BranchB,
|
||||
];
|
||||
for op in all {
|
||||
assert_eq!(VplanOp::from_name(op.name()), Some(op));
|
||||
|
||||
@@ -9,6 +9,7 @@ fn usage() {
|
||||
eprintln!("vetta-infer {} — MoE-first microkernel inference engine (Rust + HIP)", env!("CARGO_PKG_VERSION"));
|
||||
eprintln!("Usage:");
|
||||
eprintln!(" vetta-infer info <safetensors-dir> Inspect shards, dtypes, and checked bounds");
|
||||
eprintln!(" vetta-infer tensors <dir> [prefix] List tensors (name, dtype, shape, bytes)");
|
||||
eprintln!(" vetta-infer version Print version & build info");
|
||||
}
|
||||
|
||||
@@ -36,6 +37,26 @@ fn cmd_info(dir: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_tensors(dir: &str, prefix: Option<&str>) -> Result<(), String> {
|
||||
let ar = SafetensorsArchive::open(dir)?;
|
||||
let mut names: Vec<&String> = ar.tensors.keys().collect();
|
||||
names.sort();
|
||||
let mut shown = 0usize;
|
||||
for name in names {
|
||||
if let Some(p) = prefix {
|
||||
if !name.starts_with(p) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let t = &ar.tensors[name];
|
||||
let shape: Vec<String> = t.shape.iter().map(|d| d.to_string()).collect();
|
||||
println!("{name}\t{}\t[{}]\t{}", t.dtype, shape.join(","), t.byte_len());
|
||||
shown += 1;
|
||||
}
|
||||
eprintln!("{shown} tensors listed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
match args.first().map(|s| s.as_str()) {
|
||||
@@ -57,6 +78,20 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("tensors") => {
|
||||
let Some(dir) = args.get(1) else {
|
||||
eprintln!("error: missing <safetensors-dir>");
|
||||
usage();
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match cmd_tensors(dir, args.get(2).map(|s| s.as_str())) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
usage();
|
||||
ExitCode::from(2)
|
||||
|
||||
Reference in new issue
Block a user