Skip to main content

memra_runtime/
lib.rs

1//! memra inference runtime. Correctness-first: every GPU op is validated against a
2//! CPU reference before any sm_120 fast-path replaces it.
3
4use cudarc::cublaslt::{CudaBlasLT, Matmul, MatmulConfig};
5use cudarc::driver::{CudaContext, CudaStream, sys as cu};
6use std::sync::Arc;
7
8pub use memra_gguf;
9
10/// CPU reference matmul for a linear layer y = x @ W^T.
11/// Conventions (ggml/GGUF): a weight tensor with ne=[in, out] is stored row-major as
12/// `out` rows of `in` contiguous elements — i.e. W[o*in + i]. A linear layer computes
13/// y[o] = sum_i x[i] * W[o*in + i], for each of `out` outputs. Batched over `m` tokens:
14///   x: [m, in] row-major (x[t*in + i]); w: [out, in] row-major (w[o*in + i]); y: [m, out].
15pub fn cpu_linear(x: &[f32], w: &[f32], m: usize, in_f: usize, out_f: usize) -> Vec<f32> {
16    assert_eq!(x.len(), m * in_f);
17    assert_eq!(w.len(), out_f * in_f);
18    let mut y = vec![0f32; m * out_f];
19    for t in 0..m {
20        for o in 0..out_f {
21            let mut acc = 0f32;
22            let xr = &x[t * in_f..t * in_f + in_f];
23            let wr = &w[o * in_f..o * in_f + in_f];
24            for i in 0..in_f {
25                acc += xr[i] * wr[i];
26            }
27            y[t * out_f + o] = acc;
28        }
29    }
30    y
31}
32
33/// GPU runtime handle: a context + stream + cuBLASLt.
34pub struct Gpu {
35    pub ctx: Arc<CudaContext>,
36    /// The MAIN compute stream. PRIVATE since M1 increment 2: every launch site reads
37    /// `stream()` so the pp2 per-stage stream override (below) is a single seam. Naked
38    /// paths (no override pushed) get exactly this stream back — behavior unchanged.
39    stream: Arc<CudaStream>,
40    blas: Arc<CudaBlasLT>,
41    /// TOKEN-PIPELINE phase streams (step37 chain): two extra stream/cuBLASLt pairs so
42    /// alternate tokens' host-issue rides disjoint streams. Lazily built (first
43    /// enter_main under an active decode phase); None everywhere else — zero cost.
44    phase: std::sync::Mutex<Option<[(Arc<CudaStream>, Arc<CudaBlasLT>); 2]>>,
45}
46
47// ---------------------------------------------------------------------------------------
48// M1-PP2 increment 2: AMBIENT STREAM OVERRIDE (per-stage CUDA streams).
49//
50// The engine's entire launch surface reads `Gpu::stream()`. A pipeline stage redirects it
51// by pushing a per-stage stream onto this thread-local stack for the stage's host-issue
52// scope (RAII guard pops it). Decode is single-threaded host-issue, so thread-local is the
53// natural scope; cost when the stack is empty (every naked path) is one TLS lookup + a
54// branch + one Arc clone per launch — nanoseconds against a kernel launch.
55//
56// SAFETY CONTRACT (the multi-stream law): cudarc's per-arg event tracking stays DISABLED
57// (see memra-engine Engine::new) — cross-stream ordering is the OVERRIDER's job, via
58// explicit CudaEvents (pp2's boundary TX/RX choreography). The async mem pool is configured
59// below with opportunistic reuse OFF + internal dependencies ON, so a block freed on stream
60// A and re-allocated on stream B carries a driver-inserted dependency — alloc reuse cannot
61// race across stages. Buffers that one stream writes and another reads must be evented by
62// the caller; pp2 routes ALL cross-stage bytes through its persistent boundary slots.
63// ---------------------------------------------------------------------------------------
64struct StreamBinding {
65    stream: Arc<CudaStream>,
66    blas: Arc<CudaBlasLT>,
67}
68
69thread_local! {
70    static STREAM_OVERRIDE: std::cell::RefCell<Vec<StreamBinding>> =
71        const { std::cell::RefCell::new(Vec::new()) };
72}
73
74thread_local! {
75    static DECODE_PHASE: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
76}
77
78thread_local! {
79    /// RANK0 STREAM MERGE (step37): while set to a (ctx, stream, blas) binding, enter_main
80    /// on the MATCHING context binds THIS stream instead of the gpu's own main stream —
81    /// the same-device rank's work then rides the model engine's stream and every
82    /// e<->rank0 event hop becomes same-stream program order.
83    static RANK0_REDIRECT: std::cell::RefCell<Option<(usize, Arc<CudaStream>, Arc<CudaBlasLT>)>> =
84        const { std::cell::RefCell::new(None) };
85}
86
87/// Install/clear the rank0 redirect (ctx ordinal + stream/blas of the model engine).
88pub fn set_rank0_redirect(binding: Option<(usize, Arc<CudaStream>, Arc<CudaBlasLT>)>) {
89    RANK0_REDIRECT.with(|c| *c.borrow_mut() = binding);
90}
91
92/// RAII scope for the rank0 redirect: clears on drop (panic-safe).
93pub struct Rank0RedirectGuard(());
94pub fn rank0_redirect_scope(
95    ordinal: usize,
96    stream: Arc<CudaStream>,
97    blas: Arc<CudaBlasLT>,
98) -> Rank0RedirectGuard {
99    set_rank0_redirect(Some((ordinal, stream, blas)));
100    Rank0RedirectGuard(())
101}
102impl Drop for Rank0RedirectGuard {
103    fn drop(&mut self) {
104        set_rank0_redirect(None);
105    }
106}
107fn rank0_redirect_for(ordinal: usize) -> Option<(Arc<CudaStream>, Arc<CudaBlasLT>)> {
108    RANK0_REDIRECT.with(|c| {
109        c.borrow()
110            .as_ref()
111            .filter(|(o, ..)| *o == ordinal)
112            .map(|(_, s, b)| (s.clone(), b.clone()))
113    })
114}
115
116/// TOKEN-PIPELINE phase (step37 chain): while `Some(p)`, `enter_main` binds each gpu's
117/// phase-p stream instead of its main stream, so alternate tokens' rank-local work rides
118/// disjoint streams. Cross-stream ordering is the SETTER's job (the multi-stream law
119/// above): the chain wires per-layer KV events between phases.
120pub fn set_decode_phase(p: Option<usize>) {
121    DECODE_PHASE.with(|c| c.set(p));
122}
123pub fn decode_phase() -> Option<usize> {
124    DECODE_PHASE.with(|c| c.get())
125}
126
127/// RAII scope: while alive, `Gpu::stream()` on THIS thread returns the pushed stream.
128/// Nest freely (stack). Popping on Drop keeps panic paths consistent.
129pub struct StreamOverride(());
130
131/// A rank-local CUDA scope nested inside another engine's PP stage scope.
132///
133/// CUDA contexts are a per-thread stack. The stream override alone is not enough: every rank-local
134/// allocation and launch must make that rank's context current, then restore the caller's context
135/// before the PP owner resumes issuing work.
136pub struct GpuMainOverride {
137    stream: Option<StreamOverride>,
138    expected_ctx: cu::CUcontext,
139}
140
141/// Push a matched stream/cuBLASLt binding for the current thread until the guard drops.
142pub fn push_stream_override(stream: Arc<CudaStream>, blas: Arc<CudaBlasLT>) -> StreamOverride {
143    STREAM_OVERRIDE.with(|o| o.borrow_mut().push(StreamBinding { stream, blas }));
144    StreamOverride(())
145}
146
147impl Drop for StreamOverride {
148    fn drop(&mut self) {
149        STREAM_OVERRIDE.with(|o| {
150            o.borrow_mut().pop();
151        });
152    }
153}
154
155impl Drop for GpuMainOverride {
156    fn drop(&mut self) {
157        // Restore the ambient PP stream/cuBLAS binding before restoring its CUDA context.
158        drop(self.stream.take());
159        // cudarc binds the context of every stream operation with cuCtxSetCurrent. NVIDIA defines
160        // that call as replacing the top entry of an existing context stack, so a cross-context
161        // operation may replace the slot that enter_main pushed. Put the owning context back in
162        // that slot before popping it; the untouched PP context beneath it then becomes current.
163        let set_rc = unsafe { cu::cuCtxSetCurrent(self.expected_ctx) };
164        let mut popped = std::ptr::null_mut();
165        let pop_rc = unsafe { cu::cuCtxPopCurrent_v2(&mut popped) };
166        if set_rc != cu::CUresult::CUDA_SUCCESS
167            || pop_rc != cu::CUresult::CUDA_SUCCESS
168            || popped != self.expected_ctx
169        {
170            let message = format!(
171                "rank-local CUDA context restore failed: set_rc={set_rc:?} pop_rc={pop_rc:?} \
172                 expected={:?} popped={popped:?}",
173                self.expected_ctx,
174            );
175            if std::thread::panicking() {
176                eprintln!("{message}");
177            } else {
178                panic!("{message}");
179            }
180        }
181    }
182}
183
184impl Gpu {
185    /// The stream every engine op launches on: the thread's override if one is pushed
186    /// (pp2 stage scopes), else the main compute stream. By-value Arc so callers hold a
187    /// stable handle across the call regardless of later pushes/pops.
188    #[inline]
189    pub fn stream(&self) -> Arc<CudaStream> {
190        STREAM_OVERRIDE
191            .with(|o| o.borrow().last().map(|binding| binding.stream.clone()))
192            .unwrap_or_else(|| self.stream.clone())
193    }
194
195    /// The cuBLASLt handle bound to the same stream returned by `stream()`.
196    #[inline]
197    pub fn blas(&self) -> Arc<CudaBlasLT> {
198        STREAM_OVERRIDE
199            .with(|o| o.borrow().last().map(|binding| binding.blas.clone()))
200            .unwrap_or_else(|| self.blas.clone())
201    }
202
203    /// The main compute stream, override-blind (graph capture pins itself here; the pp2
204    /// runtime uses it to fence stage streams against load-time state).
205    #[inline]
206    pub fn main_stream(&self) -> &Arc<CudaStream> {
207        &self.stream
208    }
209
210    /// Enter this GPU's own context and matched main stream/cuBLASLt binding, even when the
211    /// calling thread currently carries a pipeline-stage stream override for another engine.
212    ///
213    /// Multi-context TP/EP helpers invoke rank-local engines from inside a PP stage scope. Without
214    /// this nested binding, `stream()` would inherit the PP owner's stream and launch rank-local
215    /// pointers through the wrong CUDA context.
216    pub fn enter_main(&self) -> Result<GpuMainOverride, Box<dyn std::error::Error>> {
217        let rc = unsafe { cu::cuCtxPushCurrent_v2(self.ctx.cu_ctx()) };
218        if rc != cu::CUresult::CUDA_SUCCESS {
219            return Err(format!("rank-local CUDA context push failed: {rc:?}").into());
220        }
221        // Token-pipeline phase / rank0 redirect: bind the override stream when armed.
222        let (stream, blas) = if let Some(pair) = rank0_redirect_for(self.ctx.ordinal()) {
223            pair
224        } else {
225            match decode_phase() {
226                Some(p) => self.phase_pair(p)?,
227                None => (self.stream.clone(), self.blas.clone()),
228            }
229        };
230        Ok(GpuMainOverride {
231            stream: Some(push_stream_override(stream, blas)),
232            expected_ctx: self.ctx.cu_ctx(),
233        })
234    }
235
236    /// The phase-`p` stream/cuBLASLt pair, lazily created. Caller must have this gpu's
237    /// context current (enter_main does; external callers use enter_main first).
238    pub fn phase_pair(
239        &self,
240        p: usize,
241    ) -> Result<(Arc<CudaStream>, Arc<CudaBlasLT>), Box<dyn std::error::Error>> {
242        let mut guard = self
243            .phase
244            .lock()
245            .map_err(|_| "gpu phase lock is poisoned")?;
246        if guard.is_none() {
247            let s0 = self.ctx.new_stream()?;
248            let s1 = self.ctx.new_stream()?;
249            let b0 = Arc::new(CudaBlasLT::new(s0.clone())?);
250            let b1 = Arc::new(CudaBlasLT::new(s1.clone())?);
251            *guard = Some([(s0, b0), (s1, b1)]);
252        }
253        let arr = guard.as_ref().expect("armed above");
254        Ok((arr[p & 1].0.clone(), arr[p & 1].1.clone()))
255    }
256}
257
258impl Gpu {
259    pub fn new(ordinal: usize) -> Result<Self, Box<dyn std::error::Error>> {
260        let ctx = CudaContext::new(ordinal)?;
261        // A NON-BLOCKING created stream (NOT the legacy NULL/default stream): the NULL stream cannot be
262        // CUDA-graph captured (cuStreamBeginCapture -> CUDA_ERROR_STREAM_CAPTURE_UNSUPPORTED). All
263        // engine kernels launch on this stream, so making it capturable enables the decode CUDA-graph
264        // capture/replay path (CUDA-GRAPH-PLAN Phase 3). Behaviorally identical for the existing single-
265        // stream paths (just a real stream id instead of NULL).
266        let stream = ctx.new_stream()?;
267        // DETERMINISM FIX (decode bit-stability): the default stream-ordered async memory pool
268        // (cuMemAllocAsync/cuMemFreeAsync, used by cudarc's `alloc`/`alloc_zeros`) reuses freed
269        // blocks OPPORTUNISTICALLY — it hands a freed block to the next alloc as soon as the HOST
270        // observes the GPU has passed the free, WITHOUT inserting a stream dependency. Whether that
271        // reuse happens is a function of how far the async GPU has progressed at host-alloc time, so
272        // it is timing-dependent. Our decode path launches kernels through the raw launch builder
273        // (no cudarc read/write event tracking on the args), so the per-step scratch buffers are
274        // freed-and-reused inside the async window: under opportunistic reuse a buffer can be
275        // recycled and overwritten by a later kernel while an earlier kernel that still references
276        // the same physical block is in flight — a WAR/RAW hazard that produces RUN-TO-RUN
277        // nondeterministic results (two identical prompt primes diverge; per-step sync hides it).
278        // Disable opportunistic reuse and require the pool to insert INTERNAL stream dependencies
279        // before reusing a freed block. This makes every reuse stream-ordered and deterministic with
280        // negligible cost (one-time pool config; the dependency is the same ordering the single
281        // stream already implies, just made explicit). The release threshold is set to MAX so freed
282        // blocks stay in the pool (no give-back to the OS between steps -> stable reuse, no per-step
283        // cuMemMap churn).
284        // (A/B-verified perf-neutral: decode ~80 tok/s with this on, off, or absent — full-power noise
285        // band. The real determinism fix is the SSM ping-pong in decode.rs; this is cheap belt-and-
286        // suspenders against any other per-step async-pool reuse hazard.)
287        unsafe {
288            use cudarc::driver::sys;
289            let dev = ctx.cu_device();
290            let mut pool: sys::CUmemoryPool = std::ptr::null_mut();
291            if sys::cuDeviceGetDefaultMemPool(&mut pool, dev) == sys::CUresult::CUDA_SUCCESS
292                && !pool.is_null()
293            {
294                let off: std::os::raw::c_int = 0;
295                let _ = sys::cuMemPoolSetAttribute(
296                    pool,
297                    sys::CUmemPool_attribute::CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC,
298                    &off as *const _ as *mut std::os::raw::c_void,
299                );
300                let on: std::os::raw::c_int = 1;
301                let _ = sys::cuMemPoolSetAttribute(
302                    pool,
303                    sys::CUmemPool_attribute::CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES,
304                    &on as *const _ as *mut std::os::raw::c_void,
305                );
306                let thresh: u64 = u64::MAX;
307                let _ = sys::cuMemPoolSetAttribute(
308                    pool,
309                    sys::CUmemPool_attribute::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD,
310                    &thresh as *const _ as *mut std::os::raw::c_void,
311                );
312            }
313        }
314        let blas = Arc::new(CudaBlasLT::new(stream.clone())?);
315        Ok(Self {
316            ctx,
317            stream,
318            blas,
319            phase: std::sync::Mutex::new(None),
320        })
321    }
322
323    /// GPU linear y = x @ W^T using cuBLASLt (f32), matching `cpu_linear` exactly.
324    ///
325    /// Layout reasoning (cuBLASLt is column-major):
326    /// We want y[m,out] row-major = y^T[out,m] column-major. Treat:
327    ///   - x[m,in] row-major == x^T[in,m] col-major  (an in×m col-major matrix)
328    ///   - w[out,in] row-major == w^T[in,out] col-major (an in×out col-major matrix)
329    /// Compute C[out,m] col-major = W_colmajor(out×in) * X_colmajor(in×m)
330    ///   => set A = w (interpreted col-major as in×out, so transa to get out×in),
331    ///      B = x (col-major in×m), C = y (col-major out×m == y[m,out] row-major).
332    /// cfg: m_=out, n_=m_tokens, k=in. A is in×out (lda=in, transa=true -> out×in),
333    ///      B is in×m (ldb=in), C is out×m (ldc=out).
334    pub fn linear_f32(
335        &self,
336        x: &cudarc::driver::CudaSlice<f32>,
337        w: &cudarc::driver::CudaSlice<f32>,
338        m_tokens: usize,
339        in_f: usize,
340        out_f: usize,
341    ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
342        let stream = self.stream();
343        let mut c = stream.alloc_zeros::<f32>(m_tokens * out_f)?;
344        let cfg = MatmulConfig {
345            transa: true, // A stored in×out col-major -> use as out×in
346            transb: false,
347            transc: false,
348            m: out_f as u64,
349            n: m_tokens as u64,
350            k: in_f as u64,
351            alpha: 1.0,
352            lda: in_f as i64, // A leading dim = in (col-major in×out)
353            ldb: in_f as i64, // B leading dim = in (col-major in×m)
354            beta: 0.0,
355            ldc: out_f as i64, // C leading dim = out (col-major out×m)
356            stride_a: None,
357            stride_b: None,
358            stride_c: None,
359            stride_bias: None,
360            batch_size: None,
361        };
362        let blas = self.blas();
363        unsafe {
364            blas.matmul(cfg, w, x, &mut c, None, None)?;
365        }
366        let y = stream.clone_dtoh(&c)?;
367        stream.synchronize()?;
368        Ok(y)
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn cpu_linear_tiny() {
378        // m=1, in=2, out=2; x=[1,2], W=[[1,0],[0,1]] (identity) -> y=[1,2]
379        let x = vec![1.0, 2.0];
380        let w = vec![1.0, 0.0, 0.0, 1.0]; // row0=[1,0], row1=[0,1]
381        let y = cpu_linear(&x, &w, 1, 2, 2);
382        assert_eq!(y, vec![1.0, 2.0]);
383        // W=[[1,1],[2,0]] -> y[0]=1*1+2*1=3, y[1]=1*2+2*0=2
384        let w2 = vec![1.0, 1.0, 2.0, 0.0];
385        let y2 = cpu_linear(&x, &w2, 1, 2, 2);
386        assert_eq!(y2, vec![3.0, 2.0]);
387    }
388}