diff --git a/base-convert/Cargo.lock b/base-convert/Cargo.lock index 3238a94..56e301f 100644 --- a/base-convert/Cargo.lock +++ b/base-convert/Cargo.lock @@ -151,7 +151,7 @@ dependencies = [ [[package]] name = "base-arch" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-format", @@ -162,7 +162,7 @@ dependencies = [ [[package]] name = "base-awq" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-format", @@ -176,7 +176,7 @@ dependencies = [ [[package]] name = "base-convert" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-arch", @@ -202,7 +202,7 @@ dependencies = [ [[package]] name = "base-format" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "bitflags", @@ -218,7 +218,7 @@ dependencies = [ [[package]] name = "base-hub" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-format", @@ -237,7 +237,7 @@ dependencies = [ [[package]] name = "base-quant" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-format", @@ -249,7 +249,7 @@ dependencies = [ [[package]] name = "base-readers" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-format", @@ -263,7 +263,7 @@ dependencies = [ [[package]] name = "base-sign" -version = "0.5.2" +version = "0.5.3" dependencies = [ "anyhow", "base-format", diff --git a/base-convert/Cargo.toml b/base-convert/Cargo.toml index fa05486..3ad4b49 100644 --- a/base-convert/Cargo.toml +++ b/base-convert/Cargo.toml @@ -12,7 +12,7 @@ members = [ ] [workspace.package] -version = "0.5.2" +version = "0.5.3" edition = "2021" license = "Apache-2.0" repository = "https://github.com/basecompute/baseRT" diff --git a/base-convert/crates/base-convert/src/main.rs b/base-convert/crates/base-convert/src/main.rs index 2e4ec57..270266d 100644 --- a/base-convert/crates/base-convert/src/main.rs +++ b/base-convert/crates/base-convert/src/main.rs @@ -4676,8 +4676,8 @@ fn convert_generic( let is_sidecar = canonical.ends_with(".weight_scale_2") || canonical.ends_with(".input_scale") || canonical == "d2t"; - // See GGUF path above for rationale on the f16/GPU route. Qwen3.5 GDN - // conv1d + per-head gate projections also route here (f16 on GPU). + // See GGUF path above for rationale on the f16/GPU route. The GDN + // conv1d (the mapper's `other`) also routes here (f16 on GPU). let is_norm_like = !is_sidecar && (shape.len() == 1 || is_gdn_f16(canonical)); let is_embedding = canonical == "embed_tokens.weight" || canonical == "lm_head.weight"; // GLM MLA k_b/v_b projections and router weights are raw-f16 @@ -5883,15 +5883,17 @@ fn is_gdn_f32(canonical: &str) -> bool { is_gdn_a_log(canonical) || canonical.ends_with(".linear_attn.dt_bias") } -/// GDN short causal conv (`conv1d.weight`, [3*dim, 1, K]) and the tiny -/// per-head gate projections (`in_proj_a` = decay, `in_proj_b` = beta, each -/// [n_heads, dim]). Precision-critical but not recurrence-accumulated, so -/// f16-on-GPU is enough — the point is only to escape Q4 (the conv's 4-wide -/// last dim can't even form a sane quant group). +/// GDN short causal conv (`conv1d.weight`, [3*dim, 1, K]): the mapper's +/// `other` — the recurrence's own kernel reads it, and its 4-wide last dim +/// cannot form a quant group — so it rides the f16-on-GPU route. The per-head +/// gate projections `in_proj_a` / `in_proj_b` ([n_heads, dim]) are NOT here: +/// the mapper declares them `linear` (qwen_decl::GDN_LINEARS — the encoder +/// reads them through `dispatch_gemm`), so a profile / overlay cell for them +/// is honoured like any linear's (§4.8: the class decides, never the name). +/// Until 2026-11-14 this rule kept them f16 whatever the profile said; the +/// first Flash-Next quant build then failed verify on 72 of them. fn is_gdn_f16(canonical: &str) -> bool { canonical.ends_with(".linear_attn.conv1d.weight") - || canonical.ends_with(".linear_attn.in_proj_a.weight") - || canonical.ends_with(".linear_attn.in_proj_b.weight") } /// Map an HF-style or MLX-style tensor name to canonical `.base` name. @@ -8812,12 +8814,14 @@ mod canonical_name_tests { assert!(is_gdn_f32("layers.0.linear_attn.A_log")); assert!(is_gdn_f32("layers.7.linear_attn.dt_bias")); assert!(!is_gdn_a_log("layers.0.linear_attn.dt_bias")); - // f16 conv + gate projections. + // f16 conv only; the gate projections are the mapper's `linear`. assert!(is_gdn_f16("layers.0.linear_attn.conv1d.weight")); - assert!(is_gdn_f16("layers.0.linear_attn.in_proj_a.weight")); - assert!(is_gdn_f16("layers.0.linear_attn.in_proj_b.weight")); - // Big projections + everything else quantize normally (no override). + assert!(!is_gdn_f16("layers.0.linear_attn.in_proj_a.weight")); + assert!(!is_gdn_f16("layers.0.linear_attn.in_proj_b.weight")); + // Big projections, the gate projections + everything else quantize normally (no override). for n in [ + "layers.0.linear_attn.in_proj_a.weight", + "layers.0.linear_attn.in_proj_b.weight", "layers.0.linear_attn.in_proj_qkv.weight", "layers.0.linear_attn.in_proj_z.weight", "layers.0.linear_attn.out_proj.weight", diff --git a/base-convert/crates/base-convert/src/overlay.rs b/base-convert/crates/base-convert/src/overlay.rs index 9ab6f62..70825a6 100644 --- a/base-convert/crates/base-convert/src/overlay.rs +++ b/base-convert/crates/base-convert/src/overlay.rs @@ -34,7 +34,7 @@ use super::{ QuantContext, TargetScheme, }; use anyhow::{bail, Context, Result}; -use base_format::{Layout, TensorDtype, TensorEntry}; +use base_format::{Layout, TensorDtype, TensorEntry, BLOB_ALIGNMENT, PREFIX_LEN}; use base_readers::gguf::{GgmlType, TensorInfo}; use base_readers::safetensors::SafetensorsFile; use clap::Parser; @@ -1112,21 +1112,139 @@ pub fn cmd_merge(args: MergeArgs) -> Result<()> { ); } - // Header from the base; the writer rebuilds the tensor tables and the + // Header from the base; the tensor tables are rebuilt and the // signature no longer covers these bytes. let mut header = base.header().clone(); - header.tensors.clear(); - header.mmproj = None; - header.speculator = None; if header.sig.take().is_some() { eprintln!( " note: base was signed; the merged bundle is unsigned (re-sign with `basert sign`)" ); } + let mut replaced: Vec = Vec::new(); + for t in &base.header().tensors { + if winner.contains_key(t.name.as_str()) { + replaced.push(t.name.clone()); + } + } + let merge_prov = |method: &str| { + serde_json::json!({ + "base": args.base.display().to_string(), + "overlays": args.overlays.iter().map(|p| p.display().to_string()).collect::>(), + "replaced": replaced, + "lm_only": args.lm_only, + "method": method, + }) + }; + let provenance = |merge: serde_json::Value| match base.header().provenance.clone() { + Some(serde_json::Value::Object(mut m)) => { + m.insert("merge".into(), merge); + serde_json::Value::Object(m) + } + Some(other) => serde_json::json!({"base_provenance": other, "merge": merge}), + None => serde_json::json!({"merge": merge}), + }; + // Either path writes a temp sibling and renames it over the output only + // once it is complete: a failure removes the temp and leaves whatever + // was at the output untouched. let tmp_out = temp_sibling(&args.output); - let mut writer = BaseWriter::create(&tmp_out, header) + + // ── fast path: clone the base and patch the replaced tensors in place ── + // A dense overlay of the same dtype keeps every tensor's length, so the + // base's blob layout (offsets, slots, mmproj, speculator) is reused as + // is: the output is a copy-on-write clone of the base (APFS `clonefile`, + // instant and free until written), its header region is rewritten with + // the overlay's entries at the base's offsets, and only the replaced + // bytes are written. The full rewrite below needs a whole second bundle + // on disk (a 360 GB carry's probe = 360 GB more); this needs the overlay. + let sections_kept = + !args.lm_only || (base.header().mmproj.is_none() && base.header().speculator.is_none()); + let mut patched_header = header.clone(); + let mut in_place_ok = sections_kept; + let mut patches: Vec<(usize, u64, u64)> = Vec::new(); // (overlay index, file offset, length) + if in_place_ok { + for t in patched_header.tensors.iter_mut() { + let Some(&i) = winner.get(t.name.as_str()) else { + continue; + }; + let e = overlays[i] + .header() + .tensors + .iter() + .find(|e| e.name == t.name) + .expect("winner index came from this overlay's table"); + let dense = |x: &TensorEntry| { + x.scale_offset.is_none() && x.bias_offset.is_none() && x.awq_scale_offset.is_none() + }; + if e.dtype != t.dtype || e.length != t.length || !dense(e) || !dense(t) { + in_place_ok = false; + break; + } + let mut entry = e.clone(); + entry.offset = t.offset; + patches.push((i, base.blob_offset() + t.offset, t.length)); + *t = entry; + } + } + if in_place_ok { + patched_header.provenance = Some(provenance(merge_prov("clone_patch"))); + let header_json = patched_header + .to_canonical_json() + .context("serializing the merged header")?; + // The clone keeps the base's header_len when the JSON fits in it + // (a `convert --direct-write` base reserves 64 MiB, space-padded), + // and grows it only within the base's alignment block; the blob + // start the reader derives from it must be the base's own. + let header_len = (header_json.len() as u64).max(base.header_len()); + let header_end = PREFIX_LEN + header_len; + let blob_start = (header_end + BLOB_ALIGNMENT - 1) & !(BLOB_ALIGNMENT - 1); + if blob_start == base.blob_offset() { + match clone_and_patch( + &args.base, + &tmp_out, + &header_json, + header_len, + blob_start, + &patches, + &overlays, + &replaced, + ) { + Ok(()) => { + move_into_place(&tmp_out, &args.output)?; + eprintln!( + "merge: {} tensors, {} replaced from {} overlay(s) patched into a clone of the base -> {} ({:.1}s)", + base.header().tensors.len(), + winner.len(), + overlays.len(), + args.output.display(), + t0.elapsed().as_secs_f64() + ); + return Ok(()); + } + Err(e) => { + let _ = std::fs::remove_file(&tmp_out); + eprintln!(" note: clone-and-patch unavailable ({e:#}); rewriting the bundle"); + } + } + } + } + + // ── full rewrite: every tensor's bytes streamed into the output ── + // Direct-write (the blob streams into the temp sibling at a fixed blob + // start, the header is backfilled at finish) so the peak disk usage is + // one bundle, not a bundle plus its `.blobtmp` sibling. + header.tensors.clear(); + header.mmproj = None; + header.speculator = None; + let reserve = { + let base_len = base + .header() + .to_canonical_json() + .map(|j| j.len() as u64) + .unwrap_or(0); + base_len + 2 * base_len / 10 + (1u64 << 20) + }; + let mut writer = BaseWriter::create_direct(&tmp_out, header, reserve) .with_context(|| format!("creating {}", tmp_out.display()))?; - let mut replaced: Vec = Vec::new(); let mut n_mmproj = 0usize; let mut n_spec = 0usize; let mut n_slots = 0usize; @@ -1137,7 +1255,6 @@ pub fn cmd_merge(args: MergeArgs) -> Result<()> { for t in &base.header().tensors { let (entry, bytes) = match winner.get(t.name.as_str()) { Some(&i) => { - replaced.push(t.name.clone()); let ov = &overlays[i]; let e = ov .header() @@ -1181,36 +1298,14 @@ pub fn cmd_merge(args: MergeArgs) -> Result<()> { for s in slots { writer.add_slot(s); } - - let merge_prov = serde_json::json!({ - "base": args.base.display().to_string(), - "overlays": args.overlays.iter().map(|p| p.display().to_string()).collect::>(), - "replaced": replaced, - "lm_only": args.lm_only, - }); - let prov = match base.header().provenance.clone() { - Some(serde_json::Value::Object(mut m)) => { - m.insert("merge".into(), merge_prov); - serde_json::Value::Object(m) - } - Some(other) => serde_json::json!({"base_provenance": other, "merge": merge_prov}), - None => serde_json::json!({"merge": merge_prov}), - }; - writer.set_provenance(prov); + writer.set_provenance(provenance(merge_prov("rewrite"))); writer.finish().context("writing merged bundle") })(); if let Err(e) = written { let _ = std::fs::remove_file(&tmp_out); return Err(e); } - std::fs::rename(&tmp_out, &args.output).with_context(|| { - let _ = std::fs::remove_file(&tmp_out); - format!( - "moving {} into place as {}", - tmp_out.display(), - args.output.display() - ) - })?; + move_into_place(&tmp_out, &args.output)?; eprintln!( "merge: {} tensors, {} replaced from {} overlay(s), {} mmproj, {} speculator, {} slots -> {} ({:.1}s)", base.header().tensors.len(), @@ -1225,6 +1320,112 @@ pub fn cmd_merge(args: MergeArgs) -> Result<()> { Ok(()) } +/// Rename the finished temp sibling over the output; on failure the temp is +/// removed and the output is as it was. +fn move_into_place(tmp_out: &std::path::Path, output: &std::path::Path) -> Result<()> { + std::fs::rename(tmp_out, output).with_context(|| { + let _ = std::fs::remove_file(tmp_out); + format!( + "moving {} into place as {}", + tmp_out.display(), + output.display() + ) + }) +} + +/// `basert merge`'s in-place path: `output` becomes a copy-on-write clone +/// of `base` (APFS `clonefile`; the blocks are shared until written), its +/// prefix + header region is rewritten with `header_json` (space-padded to +/// `header_len` like a direct-written header, then zero-padded to +/// `blob_start`, the base's own blob start), and each `(overlay, file +/// offset, length)` patch is written over the clone's bytes. Errors (no +/// clone support on this filesystem, a cross-volume output, …) leave the +/// caller to rewrite the bundle; the partial output (the temp sibling the +/// caller hands in) is removed by it. +#[allow(clippy::too_many_arguments)] +fn clone_and_patch( + base: &std::path::Path, + output: &std::path::Path, + header_json: &[u8], + header_len: u64, + blob_start: u64, + patches: &[(usize, u64, u64)], + overlays: &[base_format::BaseReader], + replaced: &[String], +) -> Result<()> { + use std::io::Write; + use std::os::unix::fs::FileExt; + if output.exists() { + std::fs::remove_file(output).with_context(|| format!("removing {}", output.display()))?; + } + clone_file(base, output) + .with_context(|| format!("cloning {} to {}", base.display(), output.display()))?; + let mut f = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(output) + .with_context(|| format!("opening the clone {}", output.display()))?; + { + let mut w = std::io::BufWriter::new(&mut f); + w.write_all(&base_format::MAGIC)?; + w.write_all(&base_format::FORMAT_VERSION.to_le_bytes())?; + w.write_all(&header_len.to_le_bytes())?; + w.write_all(header_json)?; + let mut fill = |byte: u8, mut n: usize| -> std::io::Result<()> { + let buf = [byte; 8192]; + while n > 0 { + let k = n.min(buf.len()); + w.write_all(&buf[..k])?; + n -= k; + } + Ok(()) + }; + fill(b' ', (header_len - header_json.len() as u64) as usize)?; + fill(0, (blob_start - PREFIX_LEN - header_len) as usize)?; + w.flush()?; + } + for (k, &(i, at, len)) in patches.iter().enumerate() { + let name = &replaced[k]; + let bytes = overlays[i].tensor_bytes(name)?; + anyhow::ensure!( + bytes.len() as u64 == len, + "{name}: {} overlay bytes for {len} in the base", + bytes.len() + ); + f.write_all_at(bytes, at) + .with_context(|| format!("{name}: writing {len} bytes at {at}"))?; + } + f.sync_all()?; + Ok(()) +} + +/// A copy-on-write file clone (macOS `clonefile(2)`): instant, and the +/// clone shares the source's blocks until either is written. +#[cfg(target_os = "macos")] +fn clone_file(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> { + use std::ffi::CString; + use std::os::raw::{c_char, c_int}; + use std::os::unix::ffi::OsStrExt; + extern "C" { + fn clonefile(src: *const c_char, dst: *const c_char, flags: c_int) -> c_int; + } + let s = CString::new(src.as_os_str().as_bytes())?; + let d = CString::new(dst.as_os_str().as_bytes())?; + // Safety: two NUL-terminated paths; the call creates `dst` or fails. + if unsafe { clonefile(s.as_ptr(), d.as_ptr(), 0) } != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(not(target_os = "macos"))] +fn clone_file(_src: &std::path::Path, _dst: &std::path::Path) -> std::io::Result<()> { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "file cloning is only implemented on macOS (APFS clonefile)", + )) +} + /// Decode one bundle tensor to f32: GGUF super-blocks (`layout: gguf_super`) /// through the GGUF reader's own dequant, the canonical-quant dtypes through /// `unpack_rtn` (the packer's own inverse), f16 / bf16 / f32 directly. diff --git a/base-convert/crates/base-convert/tests/merge.rs b/base-convert/crates/base-convert/tests/merge.rs new file mode 100644 index 0000000..5a1151b --- /dev/null +++ b/base-convert/crates/base-convert/tests/merge.rs @@ -0,0 +1,357 @@ +//! `basert merge`: a dense overlay of the base's own dtypes is patched into +//! a copy-on-write clone of the base (no second bundle on disk); anything +//! else (a dtype change, a different length) rewrites the bundle. Either +//! way the output holds the overlay's bytes where it replaced a tensor and +//! the base's everywhere else, its slots and provenance included. +use base_format::{ + AlignmentConfig, BaseReader, BaseWriter, ComputeRegion, Header, HeaderFlags, ModelConfig, + QuantScheme, Slot, SlotKind, SourceInfo, TargetBackend, TensorDtype, TensorEntry, TensorFlags, + TensorPayload, TokenizerBlob, +}; +use std::collections::BTreeMap; +use std::path::Path; +use std::process::Command; + +fn basert() -> Command { + Command::new(env!("CARGO_BIN_EXE_basert")) +} + +fn header(provenance: Option) -> Header { + Header { + schema: 1, + arch: "test".to_string(), + quant_scheme: QuantScheme::BaseQ4, + min_hw: "apple_m1".to_string(), + created: "2026-04-24T00:00:00Z".to_string(), + base_rt_version: "0.1.0-test".to_string(), + source: SourceInfo { + format: "test".to_string(), + sha256: "0".repeat(64), + filename: "synthetic".to_string(), + }, + tokenizer: TokenizerBlob { + fields: BTreeMap::new(), + }, + config: ModelConfig { + fields: BTreeMap::new(), + }, + metadata: BTreeMap::new(), + target_backend: TargetBackend::Metal, + quant_profile: String::new(), + alignment: AlignmentConfig::default(), + flags: HeaderFlags::empty(), + layers: vec![], + tensors: vec![], + mmproj: None, + speculator: None, + calibration: None, + provenance, + sig: None, + } +} + +fn entry(name: &str, dtype: TensorDtype, shape: Vec) -> TensorEntry { + TensorEntry { + name: name.to_string(), + dtype, + shape, + offset: 0, + length: 0, + scale_offset: None, + scale_length: None, + bias_offset: None, + bias_length: None, + awq_scale_offset: None, + awq_scale_length: None, + group_size: None, + layout: None, + residency: None, + compute_region: ComputeRegion::Gpu, + scale_dtype: None, + symmetric: false, + flags: TensorFlags::empty(), + checksum_xxh64: None, + source_ggml_type: None, + algo: None, + awq_alpha: None, + } +} + +fn write( + path: &Path, + prov: Option, + tensors: &[(&str, TensorDtype, Vec, Vec)], + slots: bool, +) { + write_with(path, prov, tensors, slots, None); +} + +/// `reserve`: `Some(n)` writes through `BaseWriter::create_direct` with an +/// n-byte header reserve (the `convert --direct-write` layout: header_len = +/// n, the JSON space-padded to it); `None` is the compact `create`. +fn write_with( + path: &Path, + prov: Option, + tensors: &[(&str, TensorDtype, Vec, Vec)], + slots: bool, + reserve: Option, +) { + let mut w = match reserve { + Some(n) => BaseWriter::create_direct(path, header(prov), n).unwrap(), + None => BaseWriter::create(path, header(prov)).unwrap(), + }; + for (name, dtype, shape, bytes) in tensors { + w.add_tensor(TensorPayload { + entry: entry(name, *dtype, shape.clone()), + data: bytes.clone(), + }); + } + if slots { + w.add_slot(Slot::new(SlotKind::LoraWeights, b"slot bytes".to_vec())); + } + w.finish().unwrap(); +} + +fn pattern(seed: u8, n: usize) -> Vec { + (0..n).map(|i| seed.wrapping_add((i % 251) as u8)).collect() +} + +fn merge(base: &Path, overlay: &Path, out: &Path) -> String { + let o = basert() + .args([ + "merge", + base.to_str().unwrap(), + overlay.to_str().unwrap(), + "-o", + out.to_str().unwrap(), + ]) + .output() + .unwrap(); + assert!( + o.status.success(), + "merge failed: {}", + String::from_utf8_lossy(&o.stderr) + ); + String::from_utf8_lossy(&o.stderr).to_string() +} + +fn method(out: &Path) -> String { + let r = BaseReader::open(out).unwrap(); + r.header().provenance.as_ref().unwrap()["merge"]["method"] + .as_str() + .unwrap() + .to_string() +} + +#[test] +fn a_dense_overlay_of_the_same_dtype_is_patched_into_a_clone() { + let dir = tempfile::tempdir().unwrap(); + let (base, overlay, out) = ( + dir.path().join("base.base"), + dir.path().join("ov.base"), + dir.path().join("out.base"), + ); + let (a, b, c) = ( + pattern(1, 4096), + pattern(2, 2 * 64 * 65), + pattern(3, 4 * 33), + ); + let prov = serde_json::json!({"tensors": {"a": {"src": ["a.src"]}}}); + write( + &base, + Some(prov), + &[ + ("a", TensorDtype::Bf16, vec![32, 64], a.clone()), + ("b", TensorDtype::Bf16, vec![64, 65], b.clone()), + ("c", TensorDtype::F32, vec![33], c.clone()), + ], + true, + ); + let b2 = pattern(9, b.len()); + write( + &overlay, + None, + &[("b", TensorDtype::Bf16, vec![64, 65], b2.clone())], + false, + ); + let log = merge(&base, &overlay, &out); + let r = BaseReader::open(&out).unwrap(); + assert_eq!(r.tensor_bytes("a").unwrap(), &a[..]); + assert_eq!(r.tensor_bytes("b").unwrap(), &b2[..], "the overlay's bytes"); + assert_eq!(r.tensor_bytes("c").unwrap(), &c[..]); + for n in ["a", "b", "c"] { + r.verify_tensor(n).unwrap(); + } + let slots = r.slots().unwrap(); + assert_eq!(slots.len(), 1, "the base's slots survive"); + assert_eq!(slots[0].payload, b"slot bytes"); + let prov = r.header().provenance.as_ref().unwrap(); + assert_eq!( + prov["tensors"]["a"]["src"][0], "a.src", + "the base's provenance is kept" + ); + assert_eq!(prov["merge"]["replaced"], serde_json::json!(["b"])); + if cfg!(target_os = "macos") { + assert_eq!(prov["merge"]["method"], "clone_patch", "{log}"); + assert!(log.contains("patched into a clone"), "{log}"); + // the clone keeps the base's layout: same blob start, same offsets + let rb = BaseReader::open(&base).unwrap(); + assert_eq!(r.blob_offset(), rb.blob_offset()); + for n in ["a", "b", "c"] { + assert_eq!( + r.tensor_file_offset(n).unwrap(), + rb.tensor_file_offset(n).unwrap(), + "{n}" + ); + } + } else { + assert_eq!(prov["merge"]["method"], "rewrite"); + } + // the base is untouched + let rb = BaseReader::open(&base).unwrap(); + assert_eq!(rb.tensor_bytes("b").unwrap(), &b[..]); + rb.verify_tensor("b").unwrap(); +} + +/// The 16-byte prefix's header_len field: what the reader parses as the +/// header, space padding included. +fn header_len(path: &Path) -> u64 { + let bytes = std::fs::read(path).unwrap(); + u64::from_le_bytes(bytes[8..16].try_into().unwrap()) +} + +#[test] +fn a_direct_written_base_keeps_its_reserved_header_in_the_clone() { + // `convert --direct-write` reserves 64 MiB for the header and pads its + // JSON with spaces; the merged header fits in the reserve with room to + // spare, so the clone keeps header_len = reserve and the base's blob + // start instead of rewriting a model-sized bundle. + const RESERVE: u64 = 64 * 1024 * 1024; + let dir = tempfile::tempdir().unwrap(); + let (base, overlay, out) = ( + dir.path().join("base.base"), + dir.path().join("ov.base"), + dir.path().join("out.base"), + ); + let (a, b) = (pattern(1, 4096), pattern(2, 2 * 64 * 65)); + write_with( + &base, + None, + &[ + ("a", TensorDtype::Bf16, vec![32, 64], a.clone()), + ("b", TensorDtype::Bf16, vec![64, 65], b.clone()), + ], + true, + Some(RESERVE), + ); + assert_eq!(header_len(&base), RESERVE); + let rb = BaseReader::open(&base).unwrap(); + assert_eq!(rb.blob_offset(), RESERVE + 64 * 1024); + let b2 = pattern(9, b.len()); + write( + &overlay, + None, + &[("b", TensorDtype::Bf16, vec![64, 65], b2.clone())], + false, + ); + let log = merge(&base, &overlay, &out); + let r = BaseReader::open(&out).unwrap(); + assert_eq!(r.tensor_bytes("a").unwrap(), &a[..]); + assert_eq!(r.tensor_bytes("b").unwrap(), &b2[..], "the overlay's bytes"); + r.verify_tensor("a").unwrap(); + r.verify_tensor("b").unwrap(); + assert_eq!(r.slots().unwrap().len(), 1); + assert_eq!( + r.header().provenance.as_ref().unwrap()["merge"]["replaced"], + serde_json::json!(["b"]) + ); + if cfg!(target_os = "macos") { + assert_eq!(method(&out), "clone_patch", "{log}"); + assert_eq!(header_len(&out), RESERVE, "the reserve survives the merge"); + assert_eq!(r.blob_offset(), rb.blob_offset()); + for n in ["a", "b"] { + assert_eq!( + r.tensor_file_offset(n).unwrap(), + rb.tensor_file_offset(n).unwrap(), + "{n}" + ); + } + } else { + assert_eq!(method(&out), "rewrite"); + } +} + +#[test] +fn a_dtype_change_rewrites_the_bundle() { + let dir = tempfile::tempdir().unwrap(); + let (base, overlay, out) = ( + dir.path().join("base.base"), + dir.path().join("ov.base"), + dir.path().join("out.base"), + ); + let (a, b) = (pattern(1, 4096), pattern(2, 2 * 64 * 65)); + write( + &base, + None, + &[ + ("a", TensorDtype::Bf16, vec![32, 64], a.clone()), + ("b", TensorDtype::Bf16, vec![64, 65], b.clone()), + ], + true, + ); + // f16 has bf16's length: the dtype alone sends the merge down the rewrite path + let b2 = pattern(9, b.len()); + write( + &overlay, + None, + &[("b", TensorDtype::F16, vec![64, 65], b2.clone())], + false, + ); + merge(&base, &overlay, &out); + assert_eq!(method(&out), "rewrite"); + let r = BaseReader::open(&out).unwrap(); + assert_eq!(r.tensor_bytes("a").unwrap(), &a[..]); + assert_eq!(r.tensor_bytes("b").unwrap(), &b2[..]); + assert_eq!(r.find_entry("b").unwrap().dtype, TensorDtype::F16); + r.verify_tensor("a").unwrap(); + r.verify_tensor("b").unwrap(); + assert_eq!(r.slots().unwrap().len(), 1); + assert!( + !dir.path().join("out.base.blobtmp").exists(), + "direct write: no temp blob" + ); +} + +#[test] +fn a_shape_mismatch_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let (base, overlay, out) = ( + dir.path().join("base.base"), + dir.path().join("ov.base"), + dir.path().join("out.base"), + ); + write( + &base, + None, + &[("a", TensorDtype::Bf16, vec![32, 64], pattern(1, 4096))], + false, + ); + write( + &overlay, + None, + &[("a", TensorDtype::Bf16, vec![64, 32], pattern(2, 4096))], + false, + ); + let o = basert() + .args([ + "merge", + base.to_str().unwrap(), + overlay.to_str().unwrap(), + "-o", + out.to_str().unwrap(), + ]) + .output() + .unwrap(); + assert!(!o.status.success()); + assert!(String::from_utf8_lossy(&o.stderr).contains("shape")); +} diff --git a/base-convert/crates/base-format/src/reader.rs b/base-convert/crates/base-format/src/reader.rs index fb8a44a..8bb7ab7 100644 --- a/base-convert/crates/base-format/src/reader.rs +++ b/base-convert/crates/base-format/src/reader.rs @@ -10,6 +10,7 @@ use std::path::Path; pub struct BaseReader { mmap: Mmap, header: Header, + header_len: u64, blob_offset: u64, } @@ -71,6 +72,7 @@ impl BaseReader { Ok(Self { mmap, header, + header_len, blob_offset, }) } @@ -79,6 +81,13 @@ impl BaseReader { &self.header } + /// The prefix's header_len: the bytes parsed as the header JSON, the + /// space padding of a direct-written (reserved) header included. The + /// blob starts at `align_up(PREFIX_LEN + header_len, BLOB_ALIGNMENT)`. + pub fn header_len(&self) -> u64 { + self.header_len + } + /// Parse only the header without mmapping the whole file. Reads the /// 16-byte prefix to learn `header_len`, then reads exactly the header /// JSON. Cheap enough to scan a directory of multi-GB `.base` files for diff --git a/bindings/node/package.json b/bindings/node/package.json index b31c3d6..b7c5163 100644 --- a/bindings/node/package.json +++ b/bindings/node/package.json @@ -1,6 +1,6 @@ { "name": "@baseRT/node", - "version": "0.5.2", + "version": "0.5.3", "private": true, "description": "Node.js bindings for BaseRT — LLM inference engine for Apple Silicon (Metal)", "main": "dist/index.js", diff --git a/bindings/node/src/index.ts b/bindings/node/src/index.ts index d289b6b..bc5c82d 100644 --- a/bindings/node/src/index.ts +++ b/bindings/node/src/index.ts @@ -702,7 +702,7 @@ export const Engine = { setPagedWeights(mode: number): void { lib().baseRT_set_paged_weights(mode); }, - /** The prefill's Neural Engine split: true=on (default), false=GPU alone. */ + /** The prefill's coprocessor split (Neural Engine on Apple silicon, XDNA NPU on AMD Strix): true=on (default), false=GPU alone. */ setNeuralEngine(enable: boolean): void { lib().baseRT_set_neural_engine(enable ? 1 : 0); }, diff --git a/bindings/python/baseRT/__init__.py b/bindings/python/baseRT/__init__.py index 01816bb..bdada10 100644 --- a/bindings/python/baseRT/__init__.py +++ b/bindings/python/baseRT/__init__.py @@ -21,7 +21,7 @@ from pathlib import Path from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union -__version__ = "0.5.2" +__version__ = "0.5.3" # --------------------------------------------------------------------------- # Library loading @@ -480,6 +480,10 @@ class TensorInfo: def _setup_signatures(lib: ctypes.CDLL) -> None: """Declare argtypes / restype for every C function we call.""" + # Process-wide switches (set before a model loads) + lib.baseRT_set_neural_engine.argtypes = [ctypes.c_int] + lib.baseRT_set_neural_engine.restype = None + # Model lifecycle lib.baseRT_load_model.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] lib.baseRT_load_model.restype = ctypes.c_void_p @@ -741,6 +745,17 @@ def get_error() -> Optional[str]: return None +def set_neural_engine(enable: bool) -> None: + """Switch the prefill's coprocessor split for the models loaded afterwards. + + On by default: where the box has one, part of each long prefill runs on + the Neural Engine (Apple silicon) or the XDNA NPU (AMD Strix). ``False`` + runs every prefill on the GPU alone. Process-wide; call it before + ``Model(...)``. + """ + _get_lib().baseRT_set_neural_engine(1 if enable else 0) + + class BaseRTError(RuntimeError): """Raised when the BaseRT C library reports an error.""" diff --git a/bindings/python/setup.py b/bindings/python/setup.py index 7e066c2..79602dd 100644 --- a/bindings/python/setup.py +++ b/bindings/python/setup.py @@ -6,7 +6,7 @@ setup( name="baseRT", - version="0.5.2", + version="0.5.3", description="Python bindings for the BaseRT LLM inference engine", long_description=long_description, long_description_content_type="text/markdown", diff --git a/bindings/python/tests/test_baseRT.py b/bindings/python/tests/test_baseRT.py index ec25b65..d6ebc9f 100644 --- a/bindings/python/tests/test_baseRT.py +++ b/bindings/python/tests/test_baseRT.py @@ -542,6 +542,17 @@ def test_message(self): assert str(err) == "test error message" +class TestSetNeuralEngine: + """The process-wide switch of the prefill's coprocessor split.""" + + def test_passes_the_switch_to_the_engine(self): + fake_lib = mock.MagicMock() + with mock.patch("baseRT._get_lib", return_value=fake_lib): + baseRT.set_neural_engine(False) + baseRT.set_neural_engine(True) + assert [c.args for c in fake_lib.baseRT_set_neural_engine.call_args_list] == [(0,), (1,)] + + class TestCheckModel: """Test _check_model helper.""" diff --git a/bindings/rust/baseRT-sys/Cargo.toml b/bindings/rust/baseRT-sys/Cargo.toml index dab66c0..1352023 100644 --- a/bindings/rust/baseRT-sys/Cargo.toml +++ b/bindings/rust/baseRT-sys/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "baseRT-sys" -version = "0.5.2" +version = "0.5.3" edition = "2021" description = "Raw FFI bindings for the BaseRT LLM inference engine" license = "Apache-2.0" diff --git a/bindings/rust/baseRT/Cargo.toml b/bindings/rust/baseRT/Cargo.toml index 7d79499..915884d 100644 --- a/bindings/rust/baseRT/Cargo.toml +++ b/bindings/rust/baseRT/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "baseRT" -version = "0.5.2" +version = "0.5.3" edition = "2021" description = "Safe Rust bindings for the BaseRT LLM inference engine (Apple Silicon)" license = "Apache-2.0" diff --git a/bindings/swift/Sources/BaseRT/BaseRTEngine.swift b/bindings/swift/Sources/BaseRT/BaseRTEngine.swift index e97a369..dda5286 100644 --- a/bindings/swift/Sources/BaseRT/BaseRTEngine.swift +++ b/bindings/swift/Sources/BaseRT/BaseRTEngine.swift @@ -23,8 +23,9 @@ public enum BaseRTEngine { baseRT_set_paged_kv(enable ? 1 : 0) } - /// The prefill's Neural Engine split for subsequent loads: on by default; - /// false runs every prefill on the GPU alone. + /// The prefill's coprocessor split for subsequent loads (the Neural + /// Engine on Apple silicon; the XDNA NPU where the engine runs on AMD + /// Strix): on by default; false runs every prefill on the GPU alone. public static func setNeuralEngine(_ enable: Bool) { baseRT_set_neural_engine(enable ? 1 : 0) } diff --git a/bindings/swift/Sources/CBaseRT/include/baseRT.h b/bindings/swift/Sources/CBaseRT/include/baseRT.h index c8cbb86..4e39763 100644 --- a/bindings/swift/Sources/CBaseRT/include/baseRT.h +++ b/bindings/swift/Sources/CBaseRT/include/baseRT.h @@ -64,7 +64,7 @@ extern "C" { #define BASERT_VERSION_MAJOR 0 #define BASERT_VERSION_MINOR 5 -#define BASERT_VERSION_PATCH 2 +#define BASERT_VERSION_PATCH 3 /// Compile-time version, packed as `(MAJOR<<16) | (MINOR<<8) | PATCH`. /// Useful for `#if BASERT_VERSION >= 0x000200` feature checks. @@ -253,10 +253,11 @@ void baseRT_set_prefill_chunk(int n); /// Process-wide; read at load. Set before baseRT_load_model. void baseRT_set_paged_weights(int mode); -/// The prefill's Neural Engine split (Apple silicon, Metal backend). +/// The prefill's coprocessor split: with the Neural Engine on Apple silicon +/// (Metal backend), with the XDNA NPU on AMD Strix (ROCm backend). /// enable = 1 → on (default): a prefill chunk's dense FFN / projections are -/// split between the GPU and the Neural Engine where that is faster for -/// the chip and the model +/// split between the GPU and the coprocessor where the box has one and +/// that is faster for the chip and the model /// enable = 0 → off: the GPU runs every prefill alone (bit-for-bit the /// GPU path; the split's int8 part differs from it by ~2.5% RMS) /// Process-wide; read at load. Set before baseRT_load_model. diff --git a/include/baseRT/baseRT.h b/include/baseRT/baseRT.h index c8cbb86..4e39763 100644 --- a/include/baseRT/baseRT.h +++ b/include/baseRT/baseRT.h @@ -64,7 +64,7 @@ extern "C" { #define BASERT_VERSION_MAJOR 0 #define BASERT_VERSION_MINOR 5 -#define BASERT_VERSION_PATCH 2 +#define BASERT_VERSION_PATCH 3 /// Compile-time version, packed as `(MAJOR<<16) | (MINOR<<8) | PATCH`. /// Useful for `#if BASERT_VERSION >= 0x000200` feature checks. @@ -253,10 +253,11 @@ void baseRT_set_prefill_chunk(int n); /// Process-wide; read at load. Set before baseRT_load_model. void baseRT_set_paged_weights(int mode); -/// The prefill's Neural Engine split (Apple silicon, Metal backend). +/// The prefill's coprocessor split: with the Neural Engine on Apple silicon +/// (Metal backend), with the XDNA NPU on AMD Strix (ROCm backend). /// enable = 1 → on (default): a prefill chunk's dense FFN / projections are -/// split between the GPU and the Neural Engine where that is faster for -/// the chip and the model +/// split between the GPU and the coprocessor where the box has one and +/// that is faster for the chip and the model /// enable = 0 → off: the GPU runs every prefill alone (bit-for-bit the /// GPU path; the split's int8 part differs from it by ~2.5% RMS) /// Process-wide; read at load. Set before baseRT_load_model. diff --git a/packaging/python/pyproject.toml b/packaging/python/pyproject.toml index 11dd235..85d3d61 100644 --- a/packaging/python/pyproject.toml +++ b/packaging/python/pyproject.toml @@ -45,7 +45,9 @@ packages = ["baseRT"] include-package-data = false [tool.setuptools.package-data] -baseRT = ["_engine/*"] +# npu-designs/: the XDNA NPU design sets of the Linux ROCm engine (one folder +# down; a glob does not descend). +baseRT = ["_engine/*", "_engine/npu-designs/*"] [tool.setuptools.dynamic] version = { attr = "baseRT.__version__" } diff --git a/tests/scripts/test_packaging.py b/tests/scripts/test_packaging.py index bead62d..9ee0873 100644 --- a/tests/scripts/test_packaging.py +++ b/tests/scripts/test_packaging.py @@ -685,8 +685,7 @@ def test_each_bundle_makes_the_wheel_for_its_platform(self) -> None: @unittest.skipUnless(INSTALL_SH.is_file(), "install.sh is in the open repo only") class InstallScriptTests(unittest.TestCase): """install.sh, run with stand-ins for uname and curl and a folder standing - in for / (BASERT_INSTALL_TEST_ROOT) where the AMD GPU, ROCm and NPU checks - look.""" + in for / (BASERT_INSTALL_TEST_ROOT) where the AMD GPU and ROCm checks look.""" V = "1.2.3" UNAME = '#!/bin/sh\ncase "$1" in -s) echo "$STUB_OS" ;; -m) echo "$STUB_ARCH" ;; *) exit 1 ;; esac\n' @@ -966,216 +965,6 @@ def test_a_kfd_this_user_cannot_open_is_pointed_out(self) -> None: self.assertEqual(run.returncode, 0, run.stderr) self.assertIn("render", run.stderr) - # --- the XDNA2 NPU: optional, so every run below installs and exits 0 --- - - NPU_INTRO = "Optional: this machine has an XDNA2 NPU" - XRT_LIBS = "usr/lib/x86_64-linux-gnu" - - def npu_release(self) -> None: - """The ROCm bundle of a release whose engine uses the NPU: it has the NPU module.""" - name = "basert-engine-linux-x64-rocm" - refuse = b"#!/bin/sh\nexit 1\n" - bundle( - self.assets / f"{name}-{self.V}.tar.gz", - {"basert": refuse, "basert-chat": refuse, f"lib-{name}": b"engine", "baseRT_rocm_npu.so": b"npu module"}, - {}, - ) - - def npu(self, node: bool = True, pci: bool = True, driver: bool = True, firmware: bool = True, rev: str = "0x11") -> None: - """A Strix machine's NPU as the kernel shows it: the PCI device (beside - another AMD one of the same class), the amdxdna driver, the firmware - folder for that revision and /dev/accel/accel0.""" - devices = self.root / "sys/bus/pci/devices" - ids = [("0000:c4:00.7", "0x1022", "0x164a", "0x00")] - if pci: - ids.append(("0000:c5:00.1", "0x1022", "0x17f0", rev)) - for slot, vendor, device, revision in ids: - (devices / slot).mkdir(parents=True) - for name, value in (("vendor", vendor), ("device", device), ("revision", revision), ("class", "0x118000")): - (devices / slot / name).write_text(value + "\n") - if driver: - (self.root / "sys/bus/pci/drivers/amdxdna").mkdir(parents=True) - if firmware: - (self.root / "lib/firmware/amdnpu" / f"17f0_{rev[2:]}").mkdir(parents=True) - if node: - (self.root / "dev/accel").mkdir(parents=True, exist_ok=True) - (self.root / "dev/accel/accel0").write_text("") - - def xrt(self, plugin: bool = True, where: str = XRT_LIBS) -> None: - """What `apt install libxrt2` (and libxrt-npu2, the plugin) put where the loader looks.""" - lib = self.root / where - lib.mkdir(parents=True, exist_ok=True) - for name in ["libxrt_coreutil"] + (["libxrt_driver_xdna"] if plugin else []): - (lib / f"{name}.so.2.21.75").write_text("xrt") - os.symlink(f"{name}.so.2.21.75", lib / f"{name}.so.2") - - def memlock(self, soft: str) -> None: - """/proc/self/limits with this soft locked-memory limit (bytes, or "unlimited").""" - rows = (("Limit", "Soft Limit", "Hard Limit", "Units"), ("Max cpu time", "unlimited", "unlimited", "seconds"), - ("Max locked memory", soft, "unlimited", "bytes"), ("Max address space", "unlimited", "unlimited", "bytes")) - (self.root / "proc/self").mkdir(parents=True, exist_ok=True) - (self.root / "proc/self/limits").write_text("".join(f"{a:<26}{b:<21}{c:<21}{d:<10}\n" for a, b, c, d in rows)) - - def strix(self, release: tuple[str, str] | None = ("ubuntu", "26.04")) -> None: - """A new Strix Halo with ROCm, to which a test adds the NPU's pieces, and a release that uses the NPU.""" - self.fresh(110501) - if release: - self.os_release(*release) - self.npu_release() - - def npu_lines(self, run: subprocess.CompletedProcess) -> list[str]: - """The NPU part of the closing notes: from its first line to the next blank one, or the end.""" - self.assertEqual(run.returncode, 0, run.stderr) - self.assertTrue((self.dest / "lib-basert-engine-linux-x64-rocm").is_file()) - self.assertNotIn("NPU", run.stderr) - lines = run.stdout.splitlines() - at = next((i for i, line in enumerate(lines) if self.NPU_INTRO in line), None) - if at is None: - self.assertNotIn("NPU", run.stdout) - self.assertNotIn("XRT", run.stdout) - return [] - end = lines.index("", at) if "" in lines[at:] else len(lines) - self.assertIn("BaseRT works without it, on the GPU alone.", " ".join(lines[at:end])) - return [line.strip() for line in lines[at + 2:end]] - - def test_a_machine_without_an_npu_is_told_nothing_about_one(self) -> None: - # No XRT and a low limit: only the missing NPU keeps the installer quiet. - self.strix() - self.npu(node=False, pci=False, driver=False, firmware=False) - self.memlock("8388608") - self.assertEqual(self.npu_lines(self.install()), []) - - def test_an_npu_with_everything_it_needs_is_told_nothing(self) -> None: - for rev, limit in (("0x11", "unlimited"), ("0x10", str(64 << 20))): - with self.subTest(rev=rev, limit=limit): - self.strix() - self.npu(rev=rev) - self.xrt() - self.memlock(limit) - self.assertEqual(self.npu_lines(self.install()), []) - - def test_an_npu_without_xrt_is_told_its_apt_line(self) -> None: - self.strix() - self.npu() - self.memlock("unlimited") - lines = self.npu_lines(self.install()) - self.assertEqual(len(lines), 2, lines) - self.assertIn("XRT, the runtime the engine reaches the NPU through, is not installed (libxrt_coreutil.so.2).", lines[0]) - self.assertEqual(lines[1], "sudo apt install libxrt2 libxrt-npu2") - - def test_xrt_without_its_npu_plugin_is_told_the_plugins_package(self) -> None: - self.strix() - self.npu() - self.xrt(plugin=False) - self.memlock("unlimited") - lines = self.npu_lines(self.install()) - self.assertEqual(len(lines), 2, lines) - self.assertIn("without its NPU plugin (libxrt_driver_xdna.so.2)", lines[0]) - self.assertEqual(lines[1], "sudo apt install libxrt-npu2") - - def test_xrt_is_looked_for_where_the_loader_looks(self) -> None: - # Outside the loader's own folders XRT counts only when ld.so.conf.d - # or LD_LIBRARY_PATH names its folder. - self.strix() - self.npu() - self.xrt(where="opt/xrt/lib") - self.memlock("unlimited") - self.assertIn("sudo apt install libxrt2 libxrt-npu2", self.npu_lines(self.install())) - self.assertEqual(self.npu_lines(self.install(BASERT_FORCE="1", LD_LIBRARY_PATH="/nowhere:/opt/xrt/lib")), []) - conf = self.root / "etc/ld.so.conf.d" - conf.mkdir(parents=True) - (conf / "xrt.conf").write_text("# XRT\n/opt/xrt/lib\n") - self.assertEqual(self.npu_lines(self.install(BASERT_FORCE="1")), []) - - def test_another_release_is_told_where_xrt_is_packaged(self) -> None: - for release in (("ubuntu", "24.04"), None): - with self.subTest(release=release): - self.strix(release) - self.npu() - self.memlock("unlimited") - lines = self.npu_lines(self.install()) - self.assertEqual(len(lines), 2, lines) - self.assertTrue(lines[0].endswith("(libxrt_coreutil.so.2). Ubuntu 26.04 has it as:"), lines[0]) - self.assertEqual(lines[1], "sudo apt install libxrt2 libxrt-npu2") - - def test_a_low_locked_memory_limit_is_told_the_limits_file_and_the_service_line(self) -> None: - self.strix() - self.npu() - self.xrt() - self.memlock("8388608") - lines = self.npu_lines(self.install()) - self.assertIn("the locked-memory limit here is 8192 KiB, and XRT locks a 64 MiB heap", lines[0]) - self.assertEqual( - lines[2:], - ["echo '* - memlock unlimited' | sudo tee /etc/security/limits.d/99-basert-npu.conf", - "For a systemd service, in its [Service] section:", "LimitMEMLOCK=infinity"], - ) - - def test_npu_hardware_without_its_device_node_is_told_what_is_missing(self) -> None: - cases = ( - ({"driver": False, "firmware": False}, "kernel driver, amdxdna, is not loaded", "sudo modprobe amdxdna"), - ({"firmware": False}, "the NPU's firmware is not installed", "/lib/firmware/amdnpu/17f0_11"), - ({}, "is loaded but made no /dev/accel/accel0", "sudo dmesg | grep amdxdna"), - ) - for missing, what, fix in cases: - with self.subTest(missing=missing): - self.strix() - self.npu(node=False, **missing) - self.xrt() - self.memlock("unlimited") - lines = self.npu_lines(self.install()) - self.assertIn(what, lines[0]) - self.assertEqual(lines[-1], fix) - self.assertEqual(sum(line.startswith("- ") for line in lines), 1, lines) - - def test_every_missing_piece_gets_its_own_line(self) -> None: - self.strix() - self.npu(node=False, driver=False, firmware=False) - self.memlock("65536") - lines = self.npu_lines(self.install()) - self.assertEqual([line.split(",")[0].split(" is ")[0] for line in lines if line.startswith("- ")], - ["- the NPU's kernel driver", "- XRT", "- the locked-memory limit here"]) - - def test_a_release_without_the_npu_module_is_told_nothing(self) -> None: - # An engine before 0.5.3 does not use the NPU, whatever the machine has. - self.amd(0, 110501) - self.rocm("gfx1151") - self.npu() - self.memlock("8388608") - self.assertEqual(self.npu_lines(self.install()), []) - - def test_a_run_that_installs_nothing_still_names_the_npu_steps(self) -> None: - self.strix() - self.npu() - self.memlock("unlimited") - first = self.npu_lines(self.install()) - self.log.write_text("") - again = self.install() - self.assertIn("nothing to do", again.stdout) - self.assertEqual(self.downloaded(), []) - self.assertEqual(self.npu_lines(again), first) - self.assertIn("sudo apt install libxrt2 libxrt-npu2", first) - - @unittest.skipIf(os.geteuid() == 0, "root opens any file") - def test_an_npu_this_user_cannot_open_is_pointed_out(self) -> None: - self.strix() - self.npu() - self.xrt() - self.memlock("unlimited") - os.chmod(self.root / "dev/accel/accel0", 0) - lines = self.npu_lines(self.install()) - self.assertIn("you cannot open /dev/accel/accel0", lines[0]) - self.assertEqual(lines[1], 'sudo usermod -aG render "$USER"') - - def test_the_npu_is_not_looked_for_on_the_other_platforms(self) -> None: - self.npu() - self.memlock("8388608") - refuse = b"#!/bin/sh\nexit 1\n" - bundle(self.assets / f"basert-engine-macos-arm64-{self.V}.tar.gz", {"basert": refuse, "baseRT_rocm_npu.so": b"x"}, {}) - run = self.install("Darwin", "arm64") - self.assertEqual(run.returncode, 0, run.stderr) - self.assertNotIn("NPU", run.stdout + run.stderr) - def test_the_other_platforms_are_unchanged(self) -> None: run = self.install("Darwin", "arm64") self.assertEqual(run.returncode, 0, run.stderr)