Compare commits

...
2 Commits
Author SHA1 Message Date
adm 01d8a48d51 [Core] fix 2x expert VRAM: prewarm loads device-MoE arenas, not per-expert copies
prewarm eagerly loaded all per-expert ExpertMatrix tensors (host run_experts
path, ~16 GiB), but the production serve uses device-routed MoE which loads a
SECOND contiguous ExpertArena copy of the same expert bytes lazily on the first
forward. Measured: 25 GiB after prewarm climbing to 42 GiB during the first
prefill chunk (~0.6-0.9 GiB/layer = arena load), near the 48 GiB HIP aperture.

Fix: prewarm now loads the expert ARENAS (the layout device MoE actually reads);
the forward reuses the memoized arenas. VRAM 42 -> 20 GiB (-22), prefill 60 -> 56 s
(no lazy arena NVMe load mid-forward). Parity EXACT (serve GPU 4/4, ld 23, hip 33).
Also adds VETTA_PROF batched phase+VRAM profiling (BPROF) used to diagnose this.
2026-12-02 00:55:31 +01:00
adm 66a40631ee [HIP] add synchronize + vram_used profiling bindings (hipDeviceSynchronize / hipMemGetInfo) for batched-forward phase + VRAM instrumentation 2026-12-02 00:55:31 +01:00
3 changed files with 59 additions and 10 deletions

No files matched your search

+19
View File
@@ -31,6 +31,8 @@ mod ffi {
pub fn vetta_buf_d2h(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy(dst: *mut c_void, src: *const c_void, bytes: usize) -> c_int;
pub fn vetta_buf_copy2d(dst: *mut c_void, dpitch: usize, src: *const c_void, spitch: usize, width: usize, height: usize) -> c_int;
pub fn vetta_synchronize() -> c_int;
pub fn vetta_vram_used(out: *mut usize) -> c_int;
pub fn vetta_rms_norm_f32(
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,
@@ -210,6 +212,23 @@ pub fn set_buf_pool_enabled(on: bool) {
POOL_ENABLED.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// Block until all queued GPU work completes. Used at profiling phase boundaries
/// (the batched forward is fully async otherwise); not on the hot path.
#[cfg(feature = "hip")]
pub fn synchronize() -> Result<(), String> {
let rc = unsafe { ffi::vetta_synchronize() };
if rc != 0 { return Err("hipDeviceSynchronize failed".into()); }
Ok(())
}
/// VRAM used bytes (total - free via hipMemGetInfo), for allocation profiling.
#[cfg(feature = "hip")]
pub fn vram_used() -> usize {
let mut used = 0usize;
unsafe { ffi::vetta_vram_used(&mut used) };
used
}
#[cfg(feature = "hip")]
fn pool_enabled() -> bool {
POOL_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
+27 -10
View File
@@ -164,12 +164,19 @@ impl WeightCache {
/// Eagerly load the WHOLE model to device: trunk (embed/norms/unembed/output
/// query/cross-pass queries), every attention layer (SWA or full), the core
/// loop controllers, and all expert matrices. After this the cache is fully
/// resident: VRAM is populated at boot and NO request pays NVMe reads or
/// uploads (the model is ~18 GiB, within the <=80 GiB full-UMA-residency
/// policy). This is the serve default; `VETTA_LAZY_LOAD=1` defers to first use
/// (still resident across requests once loaded). Idempotent: each loader
/// memoizes, so calling it twice uploads nothing new.
/// loop controllers, and all expert ARENAS (the contiguous device-MoE layout).
/// After this the cache is fully resident: VRAM is populated at boot and NO
/// request pays NVMe reads or uploads (the model is ~18 GiB, within the <=80
/// GiB full-UMA-residency policy). This is the serve default; `VETTA_LAZY_LOAD=1`
/// defers to first use (still resident across requests once loaded). Idempotent:
/// each loader memoizes, so calling it twice uploads nothing new.
///
/// Loads the expert ARENAS (not the per-expert `ExpertMatrix` copies): the
/// production serve uses the device-routed MoE (`VETTA_DEVICE_MOE`), which
/// reads the arena. Prewarming the per-expert matrices too would hold a SECOND
/// full copy of the ~16 GiB expert weights (the arena loads lazily on the first
/// forward), nearly doubling VRAM. The legacy host `run_experts` path loads
/// per-expert matrices lazily on demand if ever selected.
pub fn prewarm(&self, d: &Dims, n_layers: usize) -> Result<(), String> {
self.raw("model.llm.embed.weight")?;
self.bf16_f32("model.llm.embed_norm.weight")?;
@@ -183,10 +190,8 @@ impl WeightCache {
if (6..18).contains(&ip) { self.controllers(ip)?; }
}
for ip in 0..n_layers {
for e in 0..d.n_experts {
self.expert(ip, e, "w13")?;
self.expert(ip, e, "w2")?;
}
self.expert_arena(ip, "w13")?;
self.expert_arena(ip, "w2")?;
}
Ok(())
}
@@ -954,6 +959,10 @@ pub fn forward_batch(
if bu == 0 { return Err("forward_batch: empty tokens".into()); }
let b = bu as i32;
let max_pos = base_pos + b - 1;
let prof = std::env::var("VETTA_PROF").is_ok();
let tp0 = std::time::Instant::now();
let gb = |x: usize| x as f64 / 1e9;
if prof { eprintln!("[BPROF] B={bu} base_pos={base_pos} vram_start={:.2}GB", gb(vetta_infer_hip::vram_used())); }
// Embed B tokens (gather + RMS-norm rows=B).
let table = cache.raw("model.llm.embed.weight")?;
let tok_bytes: Vec<u8> = tokens.iter().flat_map(|t| t.to_le_bytes()).collect();
@@ -968,6 +977,7 @@ pub fn forward_batch(
let mut blocks = BatchBlocks::new(bu, h, 8)?;
// Prelude.
for ip in 0..6 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; }
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] prelude {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
let n_prelude_blocks = blocks.count;
let prelude = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::copy_f32(&cur, &prelude, bu * h)?;
// Core: 3 passes with device-side bank rollback.
@@ -998,7 +1008,9 @@ pub fn forward_batch(
}
}
// Coda.
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] core {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
for ip in 18..24 { run_layer_batched(cache, d, ip, &cur, &mut blocks, states, max_seq, &dpos, max_pos, 0, b, None)?; }
if prof { vetta_infer_hip::synchronize()?; eprintln!("[BPROF] coda {:.1}ms vram={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, gb(vetta_infer_hip::vram_used())); }
// Final depth mix + unembed the LAST token.
let oq = cache.raw("model.llm.attn_res.output_query")?;
let mix = DeviceBuf::alloc(bu * h * 4)?;
@@ -1006,6 +1018,11 @@ pub fn forward_batch(
let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?;
let logits = unembed_logits(cache, &last, h, vocab, d.eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
if prof {
vetta_infer_hip::synchronize()?;
let exp = EXPERT_NS.with(|c| c.replace(0));
eprintln!("[BPROF] total {:.1}ms moe_launch={:.1}ms vram_end={:.2}GB", tp0.elapsed().as_secs_f64()*1e3, exp as f64/1e6, gb(vetta_infer_hip::vram_used()));
}
Ok(logits)
}
+13
View File
@@ -82,6 +82,19 @@ extern "C" int vetta_buf_copy2d(void* dst, size_t dpitch, const void* src,
HIP_CHECK(hipMemcpy2D(dst, dpitch, src, spitch, width, height, hipMemcpyDeviceToDevice));
return 0;
}
// Block until all queued GPU work completes (profiling phase boundaries; the
// batched forward is otherwise fully async with no host sync until final d2h).
extern "C" int vetta_synchronize(void) {
HIP_CHECK(hipDeviceSynchronize());
return 0;
}
// VRAM used bytes (hipMemGetInfo: total-free), for allocation profiling.
extern "C" int vetta_vram_used(size_t* out) {
size_t free_b = 0, total_b = 0;
HIP_CHECK(hipMemGetInfo(&free_b, &total_b));
if (out) *out = total_b - free_b;
return 0;
}
// ---- k_rms_norm (kernel #2): y = x * rsqrt(mean(x^2)+eps) * w --------------
// One block per row; block-wide reduction over D. f32 in/out.