diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 5e0814c..f60fecf 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -130,9 +130,33 @@ pub struct DeviceBuf { pub bytes: usize, } +/// Size-bucketed free list of device buffers. The layer forward allocates and +/// frees ~25 short-lived intermediates per visit (~1200 hipMalloc/hipFree per +/// token); hipMalloc/hipFree each synchronize the device, dominating decode +/// latency. Reusing freed buffers by exact size removes that churn. Safe because +/// all launches share the default stream and every host copy (hipMemcpy) is +/// blocking: a buffer is only recycled after its last use is ordered before the +/// next launch that reuses it. Thread-local (cargo test runs tests in parallel). +/// Escape hatch: VETTA_NO_BUF_POOL=1 forces raw hipMalloc/hipFree. +#[cfg(feature = "hip")] +thread_local! { + static BUF_POOL: std::cell::RefCell>> = + std::cell::RefCell::new(std::collections::HashMap::new()); +} + +#[cfg(feature = "hip")] +fn pool_enabled() -> bool { + std::env::var("VETTA_NO_BUF_POOL").is_err() +} + #[cfg(feature = "hip")] impl DeviceBuf { pub fn alloc(bytes: usize) -> Result { + if pool_enabled() { + if let Some(ptr) = BUF_POOL.with(|p| p.borrow_mut().get_mut(&bytes).and_then(|v| v.pop())) { + return Ok(Self { ptr, bytes }); + } + } let mut ptr: *mut std::os::raw::c_void = std::ptr::null_mut(); let rc = unsafe { ffi::vetta_buf_alloc(&mut ptr, bytes) }; if rc != 0 || ptr.is_null() { return Err(format!("hipMalloc({bytes}) failed")); } @@ -169,7 +193,11 @@ impl DeviceBuf { #[cfg(feature = "hip")] impl Drop for DeviceBuf { fn drop(&mut self) { - unsafe { ffi::vetta_buf_free(self.ptr); } + if pool_enabled() && !self.ptr.is_null() { + BUF_POOL.with(|p| p.borrow_mut().entry(self.bytes).or_default().push(self.ptr)); + } else { + unsafe { ffi::vetta_buf_free(self.ptr); } + } } } diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 1def3a7..df4f245 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -586,7 +586,7 @@ extern "C" int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, int N, int K, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 16) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; - k_nvfp4_gemv<<>>(packed, scales, outer_scale, x, y, N, K); + k_nvfp4_gemv<<>>(packed, scales, outer_scale, x, y, N, K); HIP_CHECK(hipGetLastError()); return 0; } @@ -683,7 +683,7 @@ extern "C" int vetta_mxfp8_gemv(const uint8_t* weights, const uint8_t* scales, vetta_stream_t stream) { if (N <= 0 || K <= 0 || (K % 32) != 0) return 1; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; - k_mxfp8_gemv<<>>(weights, scales, x, y, N, K); + k_mxfp8_gemv<<>>(weights, scales, x, y, N, K); HIP_CHECK(hipGetLastError()); return 0; }