STRA-338 size-fn: rustfmt of the files this batch changed (strata-control, strata-desktop-core, runtime-client, deploy)

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 19:11:35 +01:00
parent 521c3d0d91
commit ec2dbe54e1
24 changed files with 311 additions and 88 deletions
+19 -4
View File
@@ -53,7 +53,12 @@ impl Fetcher {
}
/// Fetch one tensor into `path` (resuming a partial file) until it matches `want`; returns its SHA-256.
pub(super) async fn download_verified(&self, row: &Row, path: &Path, want: Option<&str>) -> Result<String> {
pub(super) async fn download_verified(
&self,
row: &Row,
path: &Path,
want: Option<&str>,
) -> Result<String> {
let mut digest = String::new();
for attempt in 0..2 {
self.download_tensor(row, path).await?;
@@ -95,7 +100,10 @@ impl Fetcher {
while position <= row.end {
let end = (position + CHUNK - 1).min(row.end);
let data = self
.get(&format!("{}{}", self.repo, row.shard), Some((position, end)))
.get(
&format!("{}{}", self.repo, row.shard),
Some((position, end)),
)
.await?;
file.write_all(&data)?;
position = end + 1;
@@ -116,10 +124,17 @@ impl Fetcher {
}
/// Remove a tensor left by another revision unless it is the pinned revision's (size and sha256).
pub(super) fn drop_foreign_file(path: &Path, row: &Row, same: bool, want: Option<&str>) -> Result<()> {
pub(super) fn drop_foreign_file(
path: &Path,
row: &Row,
same: bool,
want: Option<&str>,
) -> Result<()> {
if path.exists()
&& !same
&& (want.is_none() || fs::metadata(path)?.len() != row.bytes || Some(sha256_of(path)?.as_str()) != want)
&& (want.is_none()
|| fs::metadata(path)?.len() != row.bytes
|| Some(sha256_of(path)?.as_str()) != want)
{
fs::remove_file(path)?;
}
+12 -3
View File
@@ -18,7 +18,10 @@ impl Fetcher {
client: crate::model::http_client()?,
repo,
pinned,
sha256: SHA256.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
sha256: SHA256
.iter()
.map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
.collect(),
backoff: |attempt| Duration::from_secs(1 << attempt),
})
}
@@ -101,7 +104,9 @@ impl Fetcher {
&& response.status() == StatusCode::NOT_FOUND
&& !self.repo.contains("/resolve/main/")
{
crate::elog!("the checkpoint's pinned revision is gone: reading its current files (main)");
crate::elog!(
"the checkpoint's pinned revision is gone: reading its current files (main)"
);
if let Some(at) = self.repo.rfind("/resolve/") {
self.repo = format!("{}/resolve/main/", &self.repo[..at]);
}
@@ -157,7 +162,11 @@ impl Fetcher {
let want = self.wanted_hash(row);
drop_foreign_file(&path, row, same, want.as_deref())?;
let digest = self.download_verified(row, &path, want.as_deref()).await?;
manifest.push((row, path.strip_prefix(out)?.to_string_lossy().into_owned(), digest));
manifest.push((
row,
path.strip_prefix(out)?.to_string_lossy().into_owned(),
digest,
));
}
write_manifest(out, &manifest)
}
+15 -3
View File
@@ -16,7 +16,12 @@ impl Fetcher {
.ok_or("index has no weight_map")?
.iter()
.filter(|(k, _)| k.starts_with("mtp."))
.map(|(k, v)| Ok((k.clone(), v.as_str().ok_or("shard name expected")?.to_owned())))
.map(|(k, v)| {
Ok((
k.clone(),
v.as_str().ok_or("shard name expected")?.to_owned(),
))
})
.collect()
}
@@ -59,7 +64,10 @@ pub(super) fn check_all_found(rows: &[Row], mtp: &BTreeMap<String, String>) -> R
let found: BTreeSet<&String> = rows.iter().map(|r| &r.name).collect();
let missing: Vec<&String> = mtp.keys().filter(|k| !found.contains(k)).collect();
if !missing.is_empty() {
return Err(format!("tensors named in the index but absent from their shard headers: {missing:?}").into());
return Err(format!(
"tensors named in the index but absent from their shard headers: {missing:?}"
)
.into());
}
Ok(())
}
@@ -84,7 +92,11 @@ pub(super) fn inventory_markdown(rows: &[Row], total: u64) -> String {
"| `{}` | {} | {} | {:.1} |",
r.name,
r.dtype,
r.shape.iter().map(u64::to_string).collect::<Vec<_>>().join("x"),
r.shape
.iter()
.map(u64::to_string)
.collect::<Vec<_>>()
.join("x"),
r.bytes as f64 / 1e6
));
}
+9 -2
View File
@@ -24,7 +24,9 @@ pub(super) fn mtime_ns(metadata: &fs::Metadata) -> i128 {
/// process exit code.
pub async fn cli(args: &[String]) -> Result<i32> {
let [command, rest @ ..] = args else {
return Err("usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into());
return Err(
"usage: tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR]".into(),
);
};
let out = PathBuf::from(flag_value(rest, "--out")?.ok_or("--out is required")?);
let mut fetcher = build_fetcher(rest)?;
@@ -61,7 +63,12 @@ fn flag_value<'a>(rest: &'a [String], name: &str) -> Result<Option<&'a str>> {
}
}
async fn run_command(command: &str, fetcher: &mut Fetcher, out: &Path, rest: &[String]) -> Result<i32> {
async fn run_command(
command: &str,
fetcher: &mut Fetcher,
out: &Path,
rest: &[String],
) -> Result<i32> {
match command {
"verify" => {
let bad = fetcher.verify(out);
+72 -15
View File
@@ -22,21 +22,56 @@ const REQUIRED: &[(&str, &str, u64, u64)] = &[
("mlp.shared_expert.gate_proj.weight", "q8_0", 640, 2560),
("mlp.shared_expert.up_proj.weight", "q8_0", 640, 2560),
("mlp.shared_expert.down_proj.weight", "q8_0", 2560, 640),
("attn_hyper_connection.block_inject_weight.weight", "bf16", 4, 10240),
("attn_hyper_connection.input_mix_weight_down.weight", "bf16", 320, 10240),
("attn_hyper_connection.input_mix_weight_up.weight", "bf16", 10240, 320),
(
"attn_hyper_connection.block_inject_weight.weight",
"bf16",
4,
10240,
),
(
"attn_hyper_connection.input_mix_weight_down.weight",
"bf16",
320,
10240,
),
(
"attn_hyper_connection.input_mix_weight_up.weight",
"bf16",
10240,
320,
),
(
"hyper_connection_mixer.input_mix_weight_down.weight",
"bf16",
320,
10240,
),
("hyper_connection_mixer.input_mix_weight_up.weight", "bf16", 10240, 320),
(
"hyper_connection_mixer.input_mix_weight_up.weight",
"bf16",
10240,
320,
),
("mlp.gate.weight", "bf16", 512, 2560),
("mlp.shared_expert_gate.weight", "bf16", 1, 2560),
("mlp_hyper_connection.block_inject_weight.weight", "bf16", 4, 10240),
("mlp_hyper_connection.input_mix_weight_down.weight", "bf16", 320, 10240),
("mlp_hyper_connection.input_mix_weight_up.weight", "bf16", 10240, 320),
(
"mlp_hyper_connection.block_inject_weight.weight",
"bf16",
4,
10240,
),
(
"mlp_hyper_connection.input_mix_weight_down.weight",
"bf16",
320,
10240,
),
(
"mlp_hyper_connection.input_mix_weight_up.weight",
"bf16",
10240,
320,
),
("attn_hyper_connection.hc_norm.weight", "f32", 1, 10240),
("hyper_connection_mixer.hc_norm.weight", "f32", 1, 10240),
("mlp_hyper_connection.hc_norm.weight", "f32", 1, 10240),
@@ -59,8 +94,12 @@ fn regular(path: &Path) -> Result<File, &'static str> {
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
let file = options.open(path).map_err(|_| "cannot open MTP runtime file")?;
let meta = file.metadata().map_err(|_| "cannot inspect MTP runtime file")?;
let file = options
.open(path)
.map_err(|_| "cannot open MTP runtime file")?;
let meta = file
.metadata()
.map_err(|_| "cannot inspect MTP runtime file")?;
if !meta.is_file()
|| fs::symlink_metadata(path)
.map_err(|_| "cannot inspect MTP file path")?
@@ -75,7 +114,12 @@ fn regular(path: &Path) -> Result<File, &'static str> {
/// The text of `dense.txt`, which must be a regular UTF-8 file of at most `INDEX_LIMIT` bytes.
fn read_index(directory: &Path) -> Result<String, &'static str> {
let index = regular(&directory.join("dense.txt"))?;
if index.metadata().map_err(|_| "cannot inspect MTP index")?.len() > INDEX_LIMIT {
if index
.metadata()
.map_err(|_| "cannot inspect MTP index")?
.len()
> INDEX_LIMIT
{
return Err("MTP index exceeds 64 KiB limit");
}
let mut text = String::new();
@@ -135,7 +179,9 @@ fn check_row_head(fields: &[&str], tensors: &Shapes) -> Result<(), &'static str>
}
let name = fields[0];
if name.len() > 180
|| !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b))
|| !name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b))
|| tensors.contains_key(name)
{
return Err("invalid or duplicate MTP tensor name");
@@ -149,7 +195,9 @@ fn parse_row(fields: &[&str], dense_bytes: u64) -> Result<(u64, u64, (u64, u64))
if row_size(fields[1], rows, cols)?.checked_mul(rows) != Some(bytes) {
return Err("MTP tensor byte count mismatch");
}
let end = offset.checked_add(bytes).ok_or("MTP tensor range overflow")?;
let end = offset
.checked_add(bytes)
.ok_or("MTP tensor range overflow")?;
if end > dense_bytes {
return Err("MTP dense tensor extends beyond file");
}
@@ -164,7 +212,12 @@ fn row_numbers(fields: &[&str]) -> Result<(u64, u64, u64, u64), &'static str> {
.collect::<Result<Vec<_>, _>>()
.map_err(|_| "invalid MTP tensor dimensions or offsets")?;
let (rows, cols, offset, bytes) = (numbers[0], numbers[1], numbers[2], numbers[3]);
if rows == 0 || cols == 0 || rows > i32::MAX as u64 || cols > i32::MAX as u64 || offset % 256 != 0 {
if rows == 0
|| cols == 0
|| rows > i32::MAX as u64
|| cols > i32::MAX as u64
|| offset % 256 != 0
{
return Err("invalid MTP tensor dimensions or alignment");
}
Ok((rows, cols, offset, bytes))
@@ -189,7 +242,10 @@ fn check_shapes(tensors: &Shapes) -> Result<(), &'static str> {
}
}
for &(name, kind, rows, cols) in OPTIONAL {
if tensors.get(name).is_some_and(|shape| *shape != (kind, rows, cols)) {
if tensors
.get(name)
.is_some_and(|shape| *shape != (kind, rows, cols))
{
return Err("MTP optional tensor dtype or geometry does not match the current runtime");
}
}
@@ -297,7 +353,8 @@ mod tests {
#[cfg(unix)]
{
fs::remove_file(dir.join("dense.txt")).unwrap();
let path = std::ffi::CString::new(dir.join("dense.txt").as_os_str().as_encoded_bytes()).unwrap();
let path = std::ffi::CString::new(dir.join("dense.txt").as_os_str().as_encoded_bytes())
.unwrap();
assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
assert!(check(dir).is_err()); // Must return without waiting for a FIFO writer.
}
+18 -4
View File
@@ -28,7 +28,12 @@ const FILES: &[&str] = &[
/// Files only the opt-in `iq_pack.py` modes write (`--compat-bf16`, `--base`, `--experts-bin`). A receipt lists the
/// ones present; the default pack has none.
const OPTIONAL_FILES: &[&str] = &["compat-bf16.json", "extra.bin", "experts.bin", "experts.bin.src.json"];
const OPTIONAL_FILES: &[&str] = &[
"compat-bf16.json",
"extra.bin",
"experts.bin",
"experts.bin.src.json",
];
#[derive(Clone, Copy, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
@@ -49,7 +54,10 @@ pub struct NativeModel {
fn check_manifests_outside(all: &[AssetBundle], directories: &[PathBuf]) -> Result<()> {
for asset in all {
let manifest = resolved(&asset.manifest)?;
if directories.iter().any(|directory| manifest.starts_with(directory)) {
if directories
.iter()
.any(|directory| manifest.starts_with(directory))
{
return Err("asset manifests must be outside generated directories".into());
}
}
@@ -86,7 +94,10 @@ impl NativeModel {
directory: a.directory.clone(),
}));
asset_bundle::validate(&all)?;
let directories = all.iter().map(|a| resolved(&a.directory)).collect::<Result<Vec<_>>>()?;
let directories = all
.iter()
.map(|a| resolved(&a.directory))
.collect::<Result<Vec<_>>>()?;
check_no_overlap(&directories)?;
check_manifests_outside(&all, &directories)
}
@@ -245,7 +256,10 @@ fn exact_dir(dir: &Path, expected: Vec<&str>) -> Result<()> {
.map(|r| r.map(|e| e.file_name()))
.collect::<std::io::Result<Vec<_>>>()?;
actual.sort();
let mut expected = expected.into_iter().map(std::ffi::OsString::from).collect::<Vec<_>>();
let mut expected = expected
.into_iter()
.map(std::ffi::OsString::from)
.collect::<Vec<_>>();
expected.sort();
if actual != expected {
return Err("pack file set differs from receipt schema".into());
@@ -6,7 +6,8 @@ use super::*;
/// Whether any recorded conversion rounded a weight (`exact: false`).
pub(super) fn conversions_inexact(stage: &Path) -> Result<bool> {
let value: serde_json::Value = serde_json::from_slice(&fs::read(stage.join("conversions.json"))?)?;
let value: serde_json::Value =
serde_json::from_slice(&fs::read(stage.join("conversions.json"))?)?;
Ok(value["tensors"]
.as_array()
.is_some_and(|t| t.iter().any(|r| r["exact"] == false)))
@@ -81,7 +82,8 @@ fn copy_expert_blobs(shards: &[Shard], layout: &Layout, output: &Path) -> Result
.iter()
.map(|s| File::open(&s.path))
.collect::<std::io::Result<Vec<_>>>()?;
let mut out = std::io::BufWriter::with_capacity(8 << 20, File::create(output.join("experts.bin"))?);
let mut out =
std::io::BufWriter::with_capacity(8 << 20, File::create(output.join("experts.bin"))?);
let mut buffer = Vec::new();
for roles in &layout.layers {
for expert in 0..layout.n_expert {
@@ -115,11 +117,12 @@ type Named<'a> = BTreeMap<&'a str, &'a gguf::TensorInfo>;
/// this model, checked), tensors that are float here but quantized there go to `extra.bin`, quantized ones are
/// served natively. Rows follow the base index.
pub(super) fn base_files(shards: &[Shard], output: &Path, base: &Path) -> Result<()> {
if shards
.iter()
.skip(1)
.any(|s| s.index.tensors.iter().any(|t| t.name != "per_layer_token_embd.weight"))
{
if shards.iter().skip(1).any(|s| {
s.index
.tensors
.iter()
.any(|t| t.name != "per_layer_token_embd.weight")
}) {
return Err("--base needs a model whose tensors are all in shard 1".into());
}
let base_source = base_shard_one(base)?;
@@ -132,7 +135,8 @@ pub(super) fn base_files(shards: &[Shard], output: &Path, base: &Path) -> Result
/// The base pack's shard 1, named by its `manifest.json`.
fn base_shard_one(base: &Path) -> Result<PathBuf> {
let manifest: serde_json::Value = serde_json::from_slice(&fs::read(base.join("manifest.json"))?)?;
let manifest: serde_json::Value =
serde_json::from_slice(&fs::read(base.join("manifest.json"))?)?;
Ok(manifest["source"]["shard1"]
.as_str()
.map(PathBuf::from)
@@ -152,7 +156,11 @@ fn rebuild_from_base(
.flat_map(|s| s.index.tensors.iter())
.map(|t| (t.name.as_str(), t))
.collect();
let old: Named = base_index.tensors.iter().map(|t| (t.name.as_str(), t)).collect();
let old: Named = base_index
.tensors
.iter()
.map(|t| (t.name.as_str(), t))
.collect();
let rows = base_index_rows(base)?;
let mut rebuild = Rebuild {
new_start: shards[0].index.summary.data_start,
@@ -190,7 +198,10 @@ fn base_index_rows(base: &Path) -> Result<Vec<Vec<String>>> {
if line.starts_with('#') {
continue;
}
let fields = line.split_whitespace().map(str::to_owned).collect::<Vec<_>>();
let fields = line
.split_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>();
if fields.len() < 9 {
return Err("base pack index row is too short".into());
}
@@ -266,9 +277,14 @@ impl Rebuild {
if t.kind != 30 {
return Err(format!("unexpected float type {} for {name}", kind_name(t.kind)).into());
}
let offset: usize = self.extra.iter().map(|b| b.len() + (64 - b.len() % 64) % 64).sum();
let offset: usize = self
.extra
.iter()
.map(|b| b.len() + (64 - b.len() % 64) % 64)
.sum();
let mut bytes = vec![0u8; t.bytes as usize];
self.new_file.seek(SeekFrom::Start(self.new_start + t.offset))?;
self.new_file
.seek(SeekFrom::Start(self.new_start + t.offset))?;
self.new_file.read_exact(&mut bytes)?;
self.extra.push(bytes);
self.rows.push(extra_row(name, fields, offset, t.bytes));
@@ -136,7 +136,10 @@ impl<'a> Conv<'a> {
write_counted(dense, &mut self.written, &self.out)
})?;
let method = if matches!(self.src, 0 | 1 | 30) {
format!("{}->bf16 round-to-nearest-even (--compat-bf16)", self.src_lower())
format!(
"{}->bf16 round-to-nearest-even (--compat-bf16)",
self.src_lower()
)
} else {
"dequantize->bf16 round-to-nearest-even (--compat-bf16)".to_owned()
};
@@ -176,7 +179,10 @@ impl<'a> Conv<'a> {
(
5,
self.written,
format!("{}->f16 round-to-nearest-even (--compat-bf16)", self.src_lower()),
format!(
"{}->f16 round-to-nearest-even (--compat-bf16)",
self.src_lower()
),
)
}
}
+56 -12
View File
@@ -89,9 +89,16 @@ impl Dense<'_> {
/// Pad the tensor to 64 bytes in `dense.bin` and move the file and pool offsets past it.
fn pad_and_advance(&mut self, written: u64, dst: u64) -> Result<()> {
let padded = align(written)?;
self.file.write_all(&[0u8; 64][..(padded - written) as usize])?;
self.at = self.at.checked_add(padded).ok_or("dense file offset overflow")?;
self.pool = self.pool.checked_add(align(dst)?).ok_or("dense pool overflow")?;
self.file
.write_all(&[0u8; 64][..(padded - written) as usize])?;
self.at = self
.at
.checked_add(padded)
.ok_or("dense file offset overflow")?;
self.pool = self
.pool
.checked_add(align(dst)?)
.ok_or("dense pool overflow")?;
Ok(())
}
@@ -104,14 +111,27 @@ impl Dense<'_> {
tensor: &gguf::TensorInfo,
target: u32,
) -> Result<(u32, u64, u64)> {
let converted = convert_tensor(input, shard, tensor, target, self.options.compat_bf16, &mut self.file)?;
let converted = convert_tensor(
input,
shard,
tensor,
target,
self.options.compat_bf16,
&mut self.file,
)?;
let shape = (converted.index_kind, converted.written, converted.dst);
self.note_conversion(shard_name, tensor, target, converted);
Ok(shape)
}
/// Record the conversion in `conversions.json` (and in `compat-bf16.json` when it used `--compat-bf16`).
fn note_conversion(&mut self, shard_name: &str, tensor: &gguf::TensorInfo, target: u32, converted: Converted) {
fn note_conversion(
&mut self,
shard_name: &str,
tensor: &gguf::TensorInfo,
target: u32,
converted: Converted,
) {
let (method, exact, max_abs_err) = converted.record.clone().unwrap();
if method.contains("--compat-bf16") {
self.compat_entries.push(json!({"name":tensor.name,
@@ -135,13 +155,18 @@ fn matrix_dims(tensor: &gguf::TensorInfo) -> Result<(u64, u64)> {
if tensor.dimensions.len() > 2 {
return Err("dense pack index accepts at most two dimensions".into());
}
Ok((tensor.dimensions[0], tensor.dimensions.get(1).copied().unwrap_or(0)))
Ok((
tensor.dimensions[0],
tensor.dimensions.get(1).copied().unwrap_or(0),
))
}
/// A quantized tensor with no required form (and the native PLE key) is served from the GGUF, not packed.
fn serves_natively(tensor: &gguf::TensorInfo, required: Option<u32>) -> bool {
let float = matches!(tensor.kind, 0 | 1 | 30);
!float && (required.is_none() || (tensor.name == "blk.1.ple_key.weight" && native_ple_key(tensor.kind)))
!float
&& (required.is_none()
|| (tensor.name == "blk.1.ple_key.weight" && native_ple_key(tensor.kind)))
}
/// Stored as the engine reads it (or an unlisted float): copied verbatim.
@@ -192,7 +217,12 @@ fn conversions_value(shards: &[Shard], records: &[Record], options: &Options) ->
"source_shards":sources,"tensors":tensors})
}
pub(super) fn write_index(output: &Path, shards: &[Shard], pool: u64, rows: &[String]) -> Result<()> {
pub(super) fn write_index(
output: &Path,
shards: &[Shard],
pool: u64,
rows: &[String],
) -> Result<()> {
let source = shards[0].path.file_name().unwrap().to_str().unwrap();
let text = format!(
concat!(
@@ -208,7 +238,10 @@ pub(super) fn write_index(output: &Path, shards: &[Shard], pool: u64, rows: &[St
}
pub(super) fn write_conversions(output: &Path, value: &serde_json::Value) -> Result<()> {
write(output.join("conversions.json"), &serde_json::to_vec_pretty(value)?)
write(
output.join("conversions.json"),
&serde_json::to_vec_pretty(value)?,
)
}
pub(super) fn write(path: PathBuf, bytes: &[u8]) -> Result<()> {
@@ -218,7 +251,11 @@ pub(super) fn write(path: PathBuf, bytes: &[u8]) -> Result<()> {
Ok(())
}
pub async fn prepare(manifest: &model::Manifest, source: &Path, output: &Path) -> Result<serde_json::Value> {
pub async fn prepare(
manifest: &model::Manifest,
source: &Path,
output: &Path,
) -> Result<serde_json::Value> {
prepare_with(manifest, source, output, &Options::default()).await
}
@@ -263,7 +300,9 @@ fn create_stage(output: &Path) -> Result<(PathBuf, PathBuf)> {
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
let name = output.file_name().ok_or("native pack output has no filename")?;
let name = output
.file_name()
.ok_or("native pack output has no filename")?;
let mut stage_name = std::ffi::OsString::from(".");
stage_name.push(name);
stage_name.push(format!(".native-pack-{}.tmp", std::process::id()));
@@ -320,7 +359,12 @@ fn publish_stage(stage: &Path, output: &Path, parent: &Path) -> Result<()> {
}
/// The weights, tokenizer, expert layout and conversion record of a pack; returns whether a conversion was lossy.
fn write_stage_files(shards: &[Shard], layout: &Layout, options: &Options, stage: &Path) -> Result<bool> {
fn write_stage_files(
shards: &[Shard],
layout: &Layout,
options: &Options,
stage: &Path,
) -> Result<bool> {
match &options.base {
Some(base) => base_files(shards, stage, base)?,
None => dense_files(shards, stage, options)?,
+35 -7
View File
@@ -79,7 +79,13 @@ struct Table<'a> {
}
impl<'a> Table<'a> {
fn push_layer(&mut self, shards: &[Shard], tensors: &Tensors<'a>, layer: u64, experts: u64) -> Result<()> {
fn push_layer(
&mut self,
shards: &[Shard],
tensors: &Tensors<'a>,
layer: u64,
experts: u64,
) -> Result<()> {
let router = layer_router(tensors, layer, experts)?;
let roles = layer_roles(tensors, layer, experts)?;
self.layers.push(roles);
@@ -111,9 +117,15 @@ fn blob_bytes([gate, up, down]: [&gguf::TensorInfo; 3], experts: u64) -> Result<
/ experts)
}
fn layer_router<'a>(tensors: &Tensors<'a>, layer: u64, experts: u64) -> Result<&'a gguf::TensorInfo> {
fn layer_router<'a>(
tensors: &Tensors<'a>,
layer: u64,
experts: u64,
) -> Result<&'a gguf::TensorInfo> {
let router_name = format!("blk.{layer}.ffn_gate_inp.weight");
let (_, router) = tensors.get(router_name.as_str()).ok_or("missing layer router")?;
let (_, router) = tensors
.get(router_name.as_str())
.ok_or("missing layer router")?;
if router.dimensions.len() != 2 || router.dimensions[1] != experts {
return Err("routers disagree on expert count".into());
}
@@ -126,7 +138,10 @@ fn layer_roles<'a>(tensors: &Tensors<'a>, layer: u64, experts: u64) -> Result<Ro
for role in ["gate", "up", "down"] {
let name = format!("blk.{layer}.ffn_{role}_exps.weight");
let (shard, tensor) = *tensors.get(name.as_str()).ok_or("missing expert role")?;
if tensor.dimensions.len() != 3 || tensor.dimensions[2] != experts || !tensor.bytes.is_multiple_of(experts) {
if tensor.dimensions.len() != 3
|| tensor.dimensions[2] != experts
|| !tensor.bytes.is_multiple_of(experts)
{
return Err("invalid expert shape".into());
}
roles.push((shard, tensor));
@@ -134,7 +149,11 @@ fn layer_roles<'a>(tensors: &Tensors<'a>, layer: u64, experts: u64) -> Result<Ro
Ok([roles[0], roles[1], roles[2]])
}
fn check_geometry(layer: u64, router: &gguf::TensorInfo, [gate, up, down]: [&gguf::TensorInfo; 3]) -> Result<()> {
fn check_geometry(
layer: u64,
router: &gguf::TensorInfo,
[gate, up, down]: [&gguf::TensorInfo; 3],
) -> Result<()> {
// Strata 0.1.50 `expert_layout` gives an NVFP4 expert blob a 16-byte tail {s_gate, s_up, s_down, 0} read from the
// `blk.N.ffn_*_exps.scale` tensors and forces `experts.bin`. This packer does not write the tails, and the runtime
// here does not read them: a pack without them would be silently wrong, so it is refused.
@@ -168,7 +187,13 @@ fn shard_column(shards: &[Shard], roles: &Roles<'_>) -> (bool, String) {
if *s == 0 {
String::new()
} else {
shards[*s].path.file_name().unwrap().to_str().unwrap().to_owned()
shards[*s]
.path
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned()
}
})
.collect::<Vec<_>>();
@@ -277,7 +302,10 @@ impl Error64 {
}
pub(super) fn values_of(bits: &[u8]) -> impl Iterator<Item = f32> + '_ {
bits.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))
bits.as_chunks::<4>()
.0
.iter()
.map(|b| f32::from_le_bytes(*b))
}
/// Stream one tensor's values as F32 (floats exactly, quantized kinds through the pinned dequantizers).
+12 -7
View File
@@ -4,7 +4,10 @@
use super::*;
pub(super) fn safe_name(name: &str) -> bool {
!name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
!name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}
pub(super) fn align(bytes: u64) -> Result<u64> {
@@ -126,11 +129,9 @@ fn family_prefix(first: &Shard, count: u64) -> Result<Option<&str>> {
let filename = first.path.file_name().unwrap().to_str().unwrap();
let suffix = format!("-00001-of-{count:05}.gguf");
if count > 1 {
Ok(Some(
filename
.strip_suffix(&suffix)
.ok_or("first shard filename does not match split count")?,
))
Ok(Some(filename.strip_suffix(&suffix).ok_or(
"first shard filename does not match split count",
)?))
} else {
Ok(None)
}
@@ -153,7 +154,11 @@ fn check_split_identity(
if summary.split_tensors_count.is_some_and(|n| n != total) {
return Err("GGUF split tensor total does not match manifest shards".into());
}
if summary.architecture.as_ref().is_some_and(|arch| arch != "qwen4exp") {
if summary
.architecture
.as_ref()
.is_some_and(|arch| arch != "qwen4exp")
{
return Err("GGUF shard architecture mismatch".into());
}
Ok(())
+18 -5
View File
@@ -44,7 +44,9 @@ fn one_layer(kind: u32) -> Vec<Shard> {
/// whose experts the engine would read without their scales.
#[test]
fn nvfp4_experts_are_refused_and_other_experts_are_laid_out() {
let error = expert_layout(&one_layer(40)).err().expect("NVFP4 is refused");
let error = expert_layout(&one_layer(40))
.err()
.expect("NVFP4 is refused");
assert!(error.to_string().contains("NVFP4 experts"), "{error}");
let shards = one_layer(21);
let layout = expert_layout(&shards).expect("IQ3_S experts");
@@ -84,7 +86,11 @@ fn f16_and_bf16_rounding_match_numpy_and_gguf_py() {
let value = f32::from_bits(bits);
if value.is_finite() {
// the packer refuses non-finite inputs before rounding; NaN payloads are not compared
assert_eq!(kar_codec::f32_to_f16_bits(value), f16, "f16 of {bits:#010x}");
assert_eq!(
kar_codec::f32_to_f16_bits(value),
f16,
"f16 of {bits:#010x}"
);
}
assert_eq!(bf16_round_nearest_even(value), bf16, "bf16 of {bits:#010x}");
checked += 1;
@@ -220,8 +226,13 @@ fn add_golden_layer(files: &mut Files, experts: u64, row: &[String]) {
offset: 0,
bytes: HIDDEN * experts * 4,
});
for (i, (role, kind, dimensions, bytes)) in role_shapes(row, x, experts).into_iter().enumerate() {
let s = if names[i].is_empty() { 0 } else { files.at(&names[i]) };
for (i, (role, kind, dimensions, bytes)) in role_shapes(row, x, experts).into_iter().enumerate()
{
let s = if names[i].is_empty() {
0
} else {
files.at(&names[i])
};
files.tensors[s].push(gguf::TensorInfo {
name: format!("blk.{layer}.ffn_{role}_exps.weight"),
dimensions,
@@ -269,7 +280,9 @@ fn real_golden_expert_tables_are_reproduced() {
let produced = layout.text.lines().skip(1).collect::<Vec<_>>();
let wanted = text.lines().skip(1).collect::<Vec<_>>();
assert_eq!(produced, wanted, "{}", golden.name);
if golden.header.contains("native experts v3") || golden.header.contains("native experts v4") {
if golden.header.contains("native experts v3")
|| golden.header.contains("native experts v4")
{
assert_eq!(layout.text, text, "{}", golden.name);
}
}
-1
View File
@@ -2,7 +2,6 @@
// The error value is the finished HTTP response: the handler returns it as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;
@@ -3,7 +3,6 @@
// The error value is the finished HTTP response: the handler returns it as it is, so it is large by design.
#![allow(clippy::result_large_err)]
use super::*;
pub(super) fn server_refusal(code: &'static str, message: &str, status: StatusCode) -> Response {
@@ -2,7 +2,6 @@
// The error value is the finished HTTP response: the handler returns it as it is, so it is large by design.
#![allow(clippy::result_large_err)]
use super::*;
use crate::{ports::engine::SharedEngine, wire::Done};
@@ -123,7 +123,9 @@ fn native_config(
}
/// Start the engine with the observer of the evaluation policy named by the environment.
fn spawn_observed(config: NativeBackendConfig) -> Result<Box<dyn leleka_backend_api::Backend>, Failure> {
fn spawn_observed(
config: NativeBackendConfig,
) -> Result<Box<dyn leleka_backend_api::Backend>, Failure> {
let policy = evaluation_measurement::EvaluationPolicy::from_environment()?;
let observer = evaluation_measurement::observer(policy)?;
let backend = match policy {
@@ -10,7 +10,9 @@ type OwnerSpawn = fn(NativeBackendConfig, RankedExpertProfileSource) -> Spawned;
const ADAPTIVE_SLOTS_PROFILE_FAULT: &str = "adaptive_slots_requires_ranked_expert_profile";
/// Resolve the serve mode and start the engine; the transport stays closed for model admission.
pub(super) fn start_backend(operator: Operator) -> Result<Box<dyn leleka_backend_api::Backend>, Failure> {
pub(super) fn start_backend(
operator: Operator,
) -> Result<Box<dyn leleka_backend_api::Backend>, Failure> {
let Operator {
config,
requested_mode,
+3 -1
View File
@@ -21,7 +21,9 @@ pub(crate) async fn run(args: &[String]) -> Result<(), Failure> {
("start" | "stop", [id]) => control(&mut client, &token, action, id).await?,
("operation", [id]) => operation(&mut client, &token, id).await?,
_ => {
return Err("invalid worker action; supply a stable operation UUID for commands".into());
return Err(
"invalid worker action; supply a stable operation UUID for commands".into(),
);
}
};
println!("{}", serde_json::to_string(&value)?);
-1
View File
@@ -2,7 +2,6 @@
// The error value is the finished HTTP response: it is returned as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;
@@ -2,7 +2,6 @@
// The error value is the finished HTTP response: it is returned as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;
use std::pin::Pin;
@@ -2,7 +2,6 @@
// The error value is the finished HTTP response: it is returned as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;
@@ -2,7 +2,6 @@
// The error value is the finished HTTP response: it is returned as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;
@@ -3,7 +3,6 @@
// The error value is the finished HTTP response: it is returned as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;
@@ -3,7 +3,6 @@
// The error value is the finished HTTP response: it is returned as it is, so it is large by design.
#![allow(clippy::result_large_err)]
#[allow(unused_imports)]
use super::*;