diff --git a/README.md b/README.md index 949eb8a..1b040b7 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ Built from the measured hardware physics and engineering lessons of our hardened C++/HIP baseline ([`strata`](http://192.168.50.18:3000/iz0eyj/strata)), targeting unified-memory AMD RDNA 3.5 APUs (**Sogliola**: Ryzen AI 9 HX 370 / Radeon 890M `gfx1150`, 48 GiB VRAM carveout + 96 GiB UMA, 81.7 GB/s DRAM, 44 TFLOP/s INT8 WMMA, dual Gen4 NVMe) with optional LAN co-processing on **Lyra** (2.5 Gbps Ethernet). +> **New here?** If you come from vLLM / llama.cpp / SGLang, read [`docs/ORIENTATION.md`](docs/ORIENTATION.md) first — it explains the mental model, the crate map, the honest current state, and the road to the goal. + ## Core Design Principles 1. **MoE-first on UMA (`gfx1150`):** designed vertically around sparse Mixture-of-Experts architectures (Transformer SWA/Full + Vision, Hybrid GDN+GQA, native MTP / Block-Diffusion). Large dense *decoder* LMs are out of scope (bandwidth physics); small fully-resident utility **encoders** (BGE-M3 embedder lane, M1.5) are in. diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 8a4a37a..93c22db 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -32,6 +32,14 @@ mod ffi { x: *const c_float, w: *const c_float, y: *mut c_float, rows: c_int, d: c_int, eps: c_float, stream: *mut c_void, ) -> c_int; + pub fn vetta_embed_bf16_gather( + table: *const u16, tokens: *const i32, out: *mut c_float, + b: c_int, d: c_int, vocab: c_int, stream: *mut c_void, + ) -> c_int; + pub fn vetta_gemm_bf16( + x: *const u16, w: *const u16, y: *mut c_float, + m: c_int, n: c_int, k: c_int, stream: *mut c_void, + ) -> c_int; } } @@ -101,6 +109,18 @@ impl DeviceBuf { if rc != 0 { return Err("d2h failed".into()); } Ok(()) } + pub fn h2d_bytes(&self, src: &[u8]) -> Result<(), String> { + if src.len() > self.bytes { return Err("h2d overflow".into()); } + let rc = unsafe { ffi::vetta_buf_h2d(self.ptr, src.as_ptr() as *const _, src.len()) }; + if rc != 0 { return Err("h2d failed".into()); } + Ok(()) + } + pub fn d2h_bytes(&self, dst: &mut [u8]) -> Result<(), String> { + if dst.len() > self.bytes { return Err("d2h overflow".into()); } + let rc = unsafe { ffi::vetta_buf_d2h(dst.as_mut_ptr() as *mut _, self.ptr, dst.len()) }; + if rc != 0 { return Err("d2h failed".into()); } + Ok(()) + } } #[cfg(feature = "hip")] @@ -121,6 +141,26 @@ pub fn rms_norm_f32(x: &DeviceBuf, w: Option<&DeviceBuf>, y: &DeviceBuf, rows: i Ok(()) } +/// Launch k_embed_bf16_gather: `b` token rows from BF16 table `[vocab, d]` → f32. +#[cfg(feature = "hip")] +pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf, b: i32, d: i32, vocab: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_embed_bf16_gather(table.ptr as *const u16, tokens.ptr as *const i32, out.ptr as *mut f32, b, d, vocab, std::ptr::null_mut()) + }; + if rc != 0 { return Err("embed launch failed".into()); } + Ok(()) +} + +/// Launch k_gemm_bf16: y[m,n] = x[m,k] @ w[n,k]^T (BF16 in, f32 accumulate). +#[cfg(feature = "hip")] +pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_gemm_bf16(x.ptr as *const u16, w.ptr as *const u16, y.ptr as *mut f32, m, n, k, std::ptr::null_mut()) + }; + if rc != 0 { return Err("gemm launch failed".into()); } + Ok(()) +} + #[cfg(all(test, feature = "hip"))] mod gpu_tests { use super::*; @@ -173,4 +213,66 @@ mod gpu_tests { assert!(max_rel < 1e-4, "rms_norm parity failed: {max_rel}"); } } + + fn f32_to_bf16(v: f32) -> u16 { (v.to_bits() >> 16) as u16 } + fn bf16_to_f32(h: u16) -> f32 { f32::from_bits((h as u32) << 16) } + + #[test] + #[ignore] + fn embed_bf16_parity_exact() { + let (vocab, d, b) = (16usize, 64usize, 3usize); + let table: Vec = (0..vocab * d).map(|i| f32_to_bf16(((i % 53) as f32 - 26.0) * 0.07)).collect(); + let tokens: Vec = vec![1, 5, 15]; + let mut want = vec![0f32; b * d]; + for (bi, &tok) in tokens.iter().enumerate() { + for i in 0..d { want[bi * d + i] = bf16_to_f32(table[tok as usize * d + i]); } + } + let dt = DeviceBuf::alloc(table.len() * 2).unwrap(); + let dk = DeviceBuf::alloc(tokens.len() * 4).unwrap(); + let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); + dt.h2d_bytes(bytemuck_u16(&table)).unwrap(); + dk.h2d_bytes(bytemuck_i32(&tokens)).unwrap(); + embed_bf16_gather(&dt, &dk, &dy, b as i32, d as i32, vocab as i32).unwrap(); + let mut got = vec![0f32; want.len()]; + dy.d2h(&mut got).unwrap(); + assert_eq!(got, want, "embed gather must be exact"); + } + + #[test] + #[ignore] + fn gemm_bf16_parity_vs_cpu() { + for &(m, n, k) in &[(2usize, 8usize, 16usize), (4, 32, 64), (1, 128, 256)] { + let x: Vec = (0..m * k).map(|i| f32_to_bf16(((i % 41) as f32 - 20.0) * 0.05)).collect(); + let w: Vec = (0..n * k).map(|i| f32_to_bf16(((i % 29) as f32 - 14.0) * 0.06)).collect(); + let mut want = vec![0f32; m * n]; + for mi in 0..m { + for ni in 0..n { + let mut acc = 0f32; + for kk in 0..k { acc += bf16_to_f32(x[mi * k + kk]) * bf16_to_f32(w[ni * k + kk]); } + want[mi * n + ni] = acc; + } + } + let dx = DeviceBuf::alloc(x.len() * 2).unwrap(); + let dw = DeviceBuf::alloc(w.len() * 2).unwrap(); + let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); + dx.h2d_bytes(bytemuck_u16(&x)).unwrap(); + dw.h2d_bytes(bytemuck_u16(&w)).unwrap(); + gemm_bf16(&dx, &dw, &dy, m as i32, n as i32, k as i32).unwrap(); + let mut got = vec![0f32; want.len()]; + dy.d2h(&mut got).unwrap(); + let mut max_rel = 0f32; + for (g, wnt) in got.iter().zip(want.iter()) { + max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); + } + eprintln!("gemm m={m} n={n} k={k} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-3, "gemm parity failed: {max_rel}"); + } + } + + fn bytemuck_u16(v: &[u16]) -> &[u8] { + unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) } + } + fn bytemuck_i32(v: &[i32]) -> &[u8] { + unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4) } + } } \ No newline at end of file diff --git a/docs/ORIENTATION.md b/docs/ORIENTATION.md new file mode 100644 index 0000000..3f3d93a --- /dev/null +++ b/docs/ORIENTATION.md @@ -0,0 +1,138 @@ +# Orientation: what you're looking at + +If you come from vLLM, llama.cpp, SGLang, or TensorRT-LLM, this repo will feel +alien at first. That's expected — it's built on a different mental model. This +document explains what `vetta-infer` is, why it looks the way it does, and the +road ahead. Read this before diving into the code. + +## What it is, in one paragraph + +`vetta-infer` is a **MoE-first microkernel inference engine** written in safe +Rust with a minimal set of AMD ROCm HIP kernels. It is **not** a general-purpose +engine: it targets one specific machine — an AMD Ryzen AI 9 HX 370 APU +(`gfx1150`, RDNA 3.5) with **96 GiB of unified memory** and dual NVMe — and one +class of models: **Mixture-of-Experts decoder LMs** (first target: +Inkling-2-Mini). Small dense *utility encoders* (e.g. BGE-M3 embeddings) are in +scope as a secondary lane; dense decoder LMs are deliberately **out of scope**. +The engine is co-designed with its consumer, the `vetta-agents` framework +(evolved from `strata-ctl`), and ultimately serves a principal named Iris. + +## Why it looks different (the mental-model shift) + +Five ideas explain almost everything that will surprise you: + +1. **Pure microkernel + services.** There is no monolithic runtime. A tiny + kernel (`kn`) owns the bus, registry, and UMA/DMA broker and contains *zero + model logic*. Everything else — loading, compilation, execution, sampling, + speculative decoding, telemetry, the wire gateway — is a separate service + crate. Control flow stays in safe, CPU-testable Rust; `unsafe` is confined to + the HIP FFI (`hip`) and IO syscalls (`io`). + +2. **Models are compiled, not loaded.** A dual-step loader turns a HuggingFace + `.safetensors` model into a canonical IR, then a `BackendPacker` lowers it + into a portable **`.vbundle/`** (manifest + weights + plans). You don't point + the engine at raw weights; you build a bundle once and boot from it. The + manifest carries identity-by-provenance (sha256), ABI version, and target. + +3. **The forward pass is a declared, validated plan.** Instead of imperative + kernel calls scattered through C++ files, the model's compute is expressed as + `graph.vplan` (an op sequence) + `memory.vplan` (buffer arenas). At boot these + lower to a flat `CompiledPlan`. **Before any GPU launch**, the plan is checked + by an arena validator (no buffer overlap, checked bounds, no + use-before-write) whose correctness is **proven in Lean 4**. The graph is + data, not code. + +4. **Proof-first for complex logic.** Non-trivial state machines — the DMA slab + ring, bus lifecycle, serve session, arena plans — are modeled and verified in + `proofs/*.lean` (0 `sorryAx`, standard axioms only) *before* the Rust is + written. Simple logic just gets ordinary CPU tests. This is a hard rule, not + a nicety: it eliminates whole classes of bugs by construction. + +5. **Parity discipline, no unmeasured claims.** Every kernel is checked against + a CPU oracle (and the hardened `strata` C++/HIP reference) before it is wired + in. Every performance claim must carry real measurements and the exact + hardware/model/flags. "It should be fast" is not a sentence we accept. + +## The crate map + +| Crate | Responsibility | +| --- | --- | +| `vetta-infer-abi` | Shared contracts: `.vbundle` manifest/plans, vplan opcodes, arena validator, JSON, sha256, serve wire types. | +| `vetta-infer-kn` | The microkernel: bus, registry, UMA/DMA broker. No model logic. | +| `vetta-infer-ld` | Loader: safetensors reader, ModelImporter (config → IR → graph), BackendPacker, bundle I/O. | +| `vetta-infer-hip` | HIP FFI/DMA backend (gfx1150). `unsafe` isolated here. Feature-gated kernel build. | +| `vetta-infer-cc` | Compilation/control services. | +| `vetta-infer-rt` | Operational runtime: executes the `CompiledPlan` on the HIP backend. | +| `vetta-infer-lab` | Laboratory/probing runtime; shares the `rt` executor core. | +| `vetta-infer-sp` | Speculative decoding / MTP verification. | +| `vetta-infer-nt` | NVMe streaming / disk cache (io_uring, write-once `O_RDONLY`). | +| `vetta-infer-tm` | Telemetry. | +| `vetta-infer-gw` | Wire gateway: the stdin/stdout line protocol the agent speaks; CLI. | + +## Current state (honest) + +- **CPU planning pipeline: complete and live-verified.** Inkling config → + total tensor classification (1244/1244) → canonical IR → physical schedule + (looped core unrolled to 48 steps) → a full base decode graph (675 ops) that + passes the Lean-proven arena validator. +- **GPU execution: begun.** Three kernels verified on the real `gfx1150` + (embed_bf16 exact, gemm_bf16 exact, rms_norm ~1e-6 relative error). The + hipcc → static-lib → FFI → launch → parity pipeline works end-to-end. +- **No token generated yet.** The engine does not currently run inference. The + GPU execution half (remaining kernels + executor + packer + serve wiring) is + the work in progress. Do not mistake the validated *plan* for a running + *engine*. + +## The road to the goal + +The destination: a working, measured inference engine that the agent framework +can talk to over the wire, replacing the old `strata` engine for a real +conversation. The path, in order: + +1. **Inkling graph parity** — layer the model-specific refinements onto the base + graph: the learned attention-residual block-mix, loop controllers, ShortConv4, + relative-position bias, sliding-window attention, paged KV. (Blueprint: + `docs/inkling-forward-design.md`.) +2. **Remaining kernels** — flash attention (GQA, SWA, split-KV), MoE NVFP4 + routing + experts + reduce, RoPE/KV-write, penalties/top-k. Each + parity-verified before use. +3. **Executor (`rt`)** — lower the `CompiledPlan` to kernel launches, UMA arena + broker, KV-cache management. +4. **BackendPacker + `.vbundle`** — weights → device, the real bundle build. +5. **Serve wiring** — connect the (already proven) serve-session FSM to real + generation and to `vetta-agents` over the line protocol. **First chat.** +6. **M2 performance** — WMMA tiling, expert residency/streaming, measured + tok/s against the reference. +7. **M3 Lyra co-processor** — remote drafting, semantic domain routing, + domain-aware expert prefetch. + +## How to verify + +```sh +# CPU workspace tests (host-independent, no GPU/toolchain needed): +RUSTFLAGS="-D warnings" cargo test --workspace + +# Lean proofs (0 sorryAx, standard axioms): +lean proofs/slab_ring_dma.lean +lean proofs/bus_lifecycle.lean +lean proofs/serve_session.lean +lean proofs/arena_plan.lean + +# Opt-in live tests against the real Inkling artifact: +cargo test -p vetta-infer-ld -- --ignored inkling + +# GPU kernel parity (requires gfx1150 + ROCm; builds kernels via hipcc): +cargo test -p vetta-infer-hip --features hip -- --ignored +``` + +## Where to read next + +- `docs/ARCHITECTURE.md` — the decision-complete spec (microkernel, services, + `.vbundle`, plans, wire contract, milestones). +- `docs/inkling-forward-design.md` — the Inkling forward pass, extracted from + the reference, that the graph emitter follows. +- `proofs/*.lean` — the verified state machines and arena plan. +- `AGENTS.md` — the engineering rules and hard invariants. + +Welcome. Take your time with the mental model first; the code reads much more +naturally once the five ideas above click. \ No newline at end of file diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h index 66ecdc1..9088d26 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -36,6 +36,15 @@ int vetta_buf_d2h(void* dst, const void* src, size_t bytes); int vetta_rms_norm_f32(const float* x, const float* w, float* y, int rows, int D, float eps, vetta_stream_t stream); +// k_embed_bf16 (kernel #1): gather token rows from a BF16 table -> f32. +int vetta_embed_bf16_gather(const uint16_t* table, const int32_t* tokens, + float* out, int B, int D, int vocab, + vetta_stream_t stream); + +// k_gemm_bf16: y[M,N] = x[M,K] @ w[N,K]^T, BF16 inputs, f32 accumulate. +int vetta_gemm_bf16(const uint16_t* x, const uint16_t* w, float* y, + int M, int N, int K, vetta_stream_t stream); + // Core <15 microkernel entry points (implemented progressively in M1 & M2): // 1. k_embed_bf16 // 2. k_rms_norm diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index e8683a3..581b652 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -102,4 +102,66 @@ extern "C" int vetta_rms_norm_f32(const float* x, const float* w, float* y, k_rms_norm_f32<<>>(x, w, y, D, eps); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- BF16 helpers ---------------------------------------------------------- + +__device__ __forceinline__ float bf16_to_f32(uint16_t h) { + return __uint_as_float(((uint32_t)h) << 16); +} + +// ---- k_embed_bf16 (kernel #1): gather token rows from a BF16 table --------- +// out[b, :] = bf16_to_f32(table[token[b], :]). Exact (no arithmetic). + +__global__ void k_embed_bf16_gather(const uint16_t* __restrict__ table, + const int32_t* __restrict__ tokens, + float* __restrict__ out, int D, int vocab) { + const int b = blockIdx.x; + const int tok = tokens[b]; + const int tid = threadIdx.x; + const int nthreads = blockDim.x; + if (tok < 0 || tok >= vocab) return; + const uint16_t* row = table + (size_t)tok * D; + float* orow = out + (size_t)b * D; + for (int i = tid; i < D; i += nthreads) orow[i] = bf16_to_f32(row[i]); +} + +extern "C" int vetta_embed_bf16_gather(const uint16_t* table, const int32_t* tokens, + float* out, int B, int D, int vocab, + vetta_stream_t stream) { + if (B <= 0 || D <= 0) return 1; + int threads = D < 256 ? ((D + 31) / 32) * 32 : 256; + if (threads < 32) threads = 32; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_embed_bf16_gather<<>>(table, tokens, out, D, vocab); + HIP_CHECK(hipGetLastError()); + return 0; +} + +// ---- k_gemm_bf16: y[M,N] = x[M,K] @ w[N,K]^T, f32 accumulate --------------- +// x BF16 row-major [M,K], w BF16 row-major [N,K], y f32 [M,N]. One thread per +// output element (correctness-first; WMMA tiling is the performance pass). + +__global__ void k_gemm_bf16(const uint16_t* __restrict__ x, + const uint16_t* __restrict__ w, + float* __restrict__ y, int M, int N, int K) { + const int n = blockIdx.x * blockDim.x + threadIdx.x; + const int m = blockIdx.y * blockDim.y + threadIdx.y; + if (m >= M || n >= N) return; + const uint16_t* xr = x + (size_t)m * K; + const uint16_t* wr = w + (size_t)n * K; + float acc = 0.f; + for (int kk = 0; kk < K; ++kk) acc += bf16_to_f32(xr[kk]) * bf16_to_f32(wr[kk]); + y[(size_t)m * N + n] = acc; +} + +extern "C" int vetta_gemm_bf16(const uint16_t* x, const uint16_t* w, float* y, + int M, int N, int K, vetta_stream_t stream) { + if (M <= 0 || N <= 0 || K <= 0) return 1; + dim3 block(16, 16); + dim3 grid((N + 15) / 16, (M + 15) / 16); + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_gemm_bf16<<>>(x, w, y, M, N, K); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file