From fb94f2321cd1dc4f71ea7350936d611da7a23459 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 14:19:54 +0100 Subject: [PATCH] [LD] GPU weight packer + FIRST real-weight GPU run (Inkling trunk) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ld::packer (feature hip): load_raw (tensor bytes -> DeviceBuf, dtype preserved) + load_bf16_as_f32 (BF16 norm weights upcast to f32 for the rms_norm kernel, matching the reference). The bridge from canonical IR to GPU-resident weights; the seam where the per-layer loading/precision policy (engine-side composition) will be applied. - FIRST REAL-WEIGHT GPU RUN: load the real Inkling trunk (~1.85 GB: embed + unembed [201024,2304] BF16, embed_norm + final_norm) and run embed -> embed_norm -> final_norm -> cast -> unembed on gfx1150, producing real logits over vocab 201024 + argmax token (20612, logit 27.77, all finite). Trunk-only skip-layer baseline — proves packer + executor + sampling on real data end-to-end. The full layered forward + Inkling parity refinements (AttnRes block-mix etc.) come next for correct generation. - ld: optional hip + rt deps, feature-gated (default workspace stays host-independent). Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; lean proofs (4 files, 42 theorems) green; real-weight trunk run PASS (--features hip, --ignored). --- Cargo.lock | 2 + crates/vetta-infer-ld/Cargo.toml | 8 ++- crates/vetta-infer-ld/src/lib.rs | 3 + crates/vetta-infer-ld/src/packer.rs | 90 +++++++++++++++++++++++++++++ 4 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 crates/vetta-infer-ld/src/packer.rs diff --git a/Cargo.lock b/Cargo.lock index fe2ca24..9d62a40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -45,6 +45,8 @@ name = "vetta-infer-ld" version = "0.1.0" dependencies = [ "vetta-infer-abi", + "vetta-infer-hip", + "vetta-infer-rt", ] [[package]] diff --git a/crates/vetta-infer-ld/Cargo.toml b/crates/vetta-infer-ld/Cargo.toml index c9342ec..5db5e3d 100644 --- a/crates/vetta-infer-ld/Cargo.toml +++ b/crates/vetta-infer-ld/Cargo.toml @@ -5,4 +5,10 @@ edition.workspace = true license.workspace = true [dependencies] -vetta-infer-abi = { path = "../vetta-infer-abi" } \ No newline at end of file +vetta-infer-abi = { path = "../vetta-infer-abi" } +vetta-infer-hip = { path = "../vetta-infer-hip", optional = true } +vetta-infer-rt = { path = "../vetta-infer-rt", optional = true } + +[features] +# GPU packer + real-weight run tests (links HIP backend + executor). +hip = ["dep:vetta-infer-hip", "vetta-infer-hip/hip", "dep:vetta-infer-rt", "vetta-infer-rt/hip"] \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/lib.rs b/crates/vetta-infer-ld/src/lib.rs index 5b06768..9e08dd5 100644 --- a/crates/vetta-infer-ld/src/lib.rs +++ b/crates/vetta-infer-ld/src/lib.rs @@ -14,6 +14,9 @@ pub mod inkling_ir; pub mod inkling_plan; pub mod inkling_graph; +#[cfg(feature = "hip")] +pub mod packer; + use std::collections::{BTreeSet, HashMap}; use std::fs::{self, File, OpenOptions}; use std::os::unix::fs::FileExt; diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs new file mode 100644 index 0000000..83052ec --- /dev/null +++ b/crates/vetta-infer-ld/src/packer.rs @@ -0,0 +1,90 @@ +//! GPU weight packer (feature `hip`): load real `.safetensors` tensors into +//! device buffers, the bridge from the canonical IR to GPU-resident weights. +//! This is where the per-layer loading/precision policy will be applied +//! (engine-side model composition); today it loads the trunk for the first +//! real-weight GPU run. + +use crate::SafetensorsArchive; +use vetta_infer_hip::DeviceBuf; + +/// Load a tensor's raw bytes into a device buffer (dtype preserved). +pub fn load_raw(ar: &SafetensorsArchive, name: &str) -> Result { + let info = ar.tensors.get(name).ok_or_else(|| format!("tensor not found: {name}"))?; + let bytes = info.byte_len() as usize; + let mut host = vec![0u8; bytes]; + ar.read_slice(name, 0, &mut host)?; + let buf = DeviceBuf::alloc(bytes)?; + buf.h2d_bytes(&host)?; + Ok(buf) +} + +fn bf16_to_f32(h: u16) -> f32 { f32::from_bits((h as u32) << 16) } + +/// Load a BF16 tensor converted to f32 (e.g. norm weights for the f32 rms_norm +/// kernel — the reference upcasts BF16 norms to f32 at load). +pub fn load_bf16_as_f32(ar: &SafetensorsArchive, name: &str) -> Result { + let info = ar.tensors.get(name).ok_or_else(|| format!("tensor not found: {name}"))?; + if info.dtype != "BF16" { return Err(format!("{name}: expected BF16, got {}", info.dtype)); } + let bytes = info.byte_len() as usize; + let mut host = vec![0u8; bytes]; + ar.read_slice(name, 0, &mut host)?; + let f: Vec = host.chunks_exact(2).map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]]))).collect(); + let buf = DeviceBuf::alloc(f.len() * 4)?; + buf.h2d(&f)?; + Ok(buf) +} + +#[cfg(test)] +mod tests { + use super::*; + use vetta_infer_abi::vplan::VplanOp; + use vetta_infer_rt::executor::{execute, ExecOp, OpParams}; + + /// FIRST REAL-WEIGHT GPU RUN: load the real Inkling trunk weights and run + /// embed -> embed_norm -> final_norm -> cast -> unembed on GPU, producing + /// real logits over vocab 201024 and an argmax token. Trunk-only (skip-layer + /// baseline) — proves packer + executor + sampling on real data; the full + /// layered forward + Inkling parity refinements come next. + #[test] + #[ignore] // requires GPU + --features hip + /mnt/models/Inkling + fn trunk_run_real_weights() { + let ar = SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap(); + let hidden = 2304usize; + let vocab = 201024usize; + let token_id = 100i32; + + let embed = load_raw(&ar, "model.llm.embed.weight").unwrap(); + let embed_norm = load_bf16_as_f32(&ar, "model.llm.embed_norm.weight").unwrap(); + let final_norm = load_bf16_as_f32(&ar, "model.llm.norm.weight").unwrap(); + let unembed = load_raw(&ar, "model.llm.unembed.weight").unwrap(); + + let tokens = DeviceBuf::alloc(4).unwrap(); + tokens.h2d_bytes(&token_id.to_le_bytes()).unwrap(); + let residual = DeviceBuf::alloc(hidden * 4).unwrap(); + let norm1 = DeviceBuf::alloc(hidden * 4).unwrap(); + let norm2 = DeviceBuf::alloc(hidden * 4).unwrap(); + let normbf = DeviceBuf::alloc(hidden * 2).unwrap(); + let logits = DeviceBuf::alloc(vocab * 4).unwrap(); + + // 0 embed, 1 tokens, 2 embed_norm, 3 final_norm, 4 unembed, + // 5 residual, 6 norm1, 7 norm2, 8 normbf, 9 logits. + let buffers = vec![embed, tokens, embed_norm, final_norm, unembed, residual, norm1, norm2, normbf, logits]; + let ops = vec![ + ExecOp { op: VplanOp::EmbedBf16, reads: vec![0, 1], writes: vec![5], params: OpParams::Embed { b: 1, d: hidden as i32, vocab: vocab as i32 } }, + ExecOp { op: VplanOp::RmsNorm, reads: vec![5, 2], writes: vec![6], params: OpParams::RmsNorm { rows: 1, d: hidden as i32, eps: 1e-6 } }, + ExecOp { op: VplanOp::RmsNorm, reads: vec![6, 3], writes: vec![7], params: OpParams::RmsNorm { rows: 1, d: hidden as i32, eps: 1e-6 } }, + ExecOp { op: VplanOp::CastF32Bf16, reads: vec![7], writes: vec![8], params: OpParams::Cast { n: hidden } }, + ExecOp { op: VplanOp::GemmBf16, reads: vec![8, 4], writes: vec![9], params: OpParams::Gemm { m: 1, n: vocab as i32, k: hidden as i32 } }, + ]; + execute(&buffers, &ops).unwrap(); + let mut lg = vec![0f32; vocab]; + buffers[9].d2h(&mut lg).unwrap(); + + assert!(lg.iter().all(|v| v.is_finite()), "logits must be finite"); + let mut idx: Vec = (0..vocab).collect(); + idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap()); + let top5: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect(); + eprintln!("FIRST REAL-WEIGHT GPU RUN (trunk-only): argmax token={} top5={:?}", idx[0], top5); + assert!(idx[0] < vocab); + } +} \ No newline at end of file