[LD] GPU weight packer + FIRST real-weight GPU run (Inkling trunk)

- 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).
This commit is contained in:
adm committed 2026-12-01 14:19:54 +01:00
1 parent 1b3896bba9
commit fb94f2321c
4 files changed
+102 -1

No files matched your search

Generated
+2
View File
@@ -45,6 +45,8 @@ name = "vetta-infer-ld"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"vetta-infer-abi", "vetta-infer-abi",
"vetta-infer-hip",
"vetta-infer-rt",
] ]
[[package]] [[package]]
+7 -1
View File
@@ -5,4 +5,10 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
vetta-infer-abi = { path = "../vetta-infer-abi" } 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"]
+3
View File
@@ -14,6 +14,9 @@ pub mod inkling_ir;
pub mod inkling_plan; pub mod inkling_plan;
pub mod inkling_graph; pub mod inkling_graph;
#[cfg(feature = "hip")]
pub mod packer;
use std::collections::{BTreeSet, HashMap}; use std::collections::{BTreeSet, HashMap};
use std::fs::{self, File, OpenOptions}; use std::fs::{self, File, OpenOptions};
use std::os::unix::fs::FileExt; use std::os::unix::fs::FileExt;
+90
View File
@@ -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<DeviceBuf, String> {
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<DeviceBuf, String> {
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<f32> = 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<usize> = (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);
}
}