Skip to main content

rlx_runtime/
compiled.rs

1// RLX — versatile ML compiler + runtime.
2// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, version 3.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with this program. If not, see <https://www.gnu.org/licenses/>.
15
16//! Compiled graph — the hot-path execution object.
17
18use crate::backend::ExecutableGraph;
19use rlx_driver::Device;
20
21/// A compiled graph ready for execution.
22///
23/// Created by [`crate::Session::compile`]. Holds the fused + memory-planned
24/// graph and all pre-allocated execution state. Call
25/// [`CompiledGraph::run`] repeatedly with different inputs — zero
26/// allocation per call.
27pub struct CompiledGraph {
28    inner: Box<dyn ExecutableGraph>,
29    device: Device,
30}
31
32impl Clone for CompiledGraph {
33    /// Deep-clones the underlying executable via `ExecutableGraph::clone_box`.
34    /// Backends that don't support cloning will panic at this point.
35    fn clone(&self) -> Self {
36        Self {
37            inner: self.inner.clone_box(),
38            device: self.device,
39        }
40    }
41}
42
43impl CompiledGraph {
44    pub(crate) fn new(inner: Box<dyn ExecutableGraph>, device: Device) -> Self {
45        Self { inner, device }
46    }
47
48    /// Which device this graph runs on.
49    pub fn device(&self) -> Device {
50        self.device
51    }
52
53    /// Set a named parameter (model weight).
54    /// Call once per parameter after compilation.
55    pub fn set_param(&mut self, name: &str, data: &[f32]) {
56        self.inner.set_param(name, data);
57    }
58
59    /// Execute the graph with named inputs.
60    /// Returns one `Vec<f32>` per graph output (copies from arena).
61    pub fn run(&mut self, inputs: &[(&str, &[f32])]) -> Vec<Vec<f32>> {
62        self.inner.run(inputs)
63    }
64
65    /// Run and read back only selected outputs (logits-only decode on MLX).
66    pub fn run_read_outputs(
67        &mut self,
68        inputs: &[(&str, &[f32])],
69        read_indices: Option<&[usize]>,
70    ) -> Vec<Vec<f32>> {
71        self.inner.run_read_outputs(inputs, read_indices)
72    }
73
74    /// Read one row from a row-major output tensor after a forward pass.
75    pub fn read_output_row(
76        &self,
77        out_idx: usize,
78        row: usize,
79        row_inner: usize,
80    ) -> Option<Vec<f32>> {
81        self.inner.read_output_row(out_idx, row, row_inner)
82    }
83
84    /// Execute and return raw pointers to output data (zero-copy).
85    /// Data is valid until the next `run`/`run_raw` call.
86    ///
87    /// # Safety
88    /// The returned pointers point into the arena. Do not use after
89    /// the next call to run/run_raw (arena data will be overwritten).
90    pub fn run_raw(&mut self, inputs: &[(&str, &[f32])]) -> Vec<(*const f32, usize)> {
91        self.inner.run_raw(inputs)
92    }
93
94    /// Fastest execution: inputs by slot index (order matches graph input declaration).
95    /// Returns output (offset, len) pairs. Read data via `arena_ptr().add(offset)`.
96    /// Zero HashMap lookup, zero Vec allocation, zero name matching.
97    pub fn run_slots(&mut self, inputs: &[&[f32]]) -> &[(usize, usize)] {
98        self.inner.run_slots(inputs)
99    }
100
101    /// Arena pointer for reading output data after `run_slots`.
102    pub fn arena_ptr(&self) -> *const u8 {
103        self.inner.arena_ptr()
104    }
105
106    /// Bind a persistent buffer (KV-cache, optimizer state, etc.).
107    /// Stays alive across `run()` calls; the backend uses it as the
108    /// graph input with the matching name.
109    /// Returns true if the backend supports persistent handles.
110    pub fn bind_handle(&mut self, name: &str, data: &[f32]) -> bool {
111        self.inner.bind_handle(name, data)
112    }
113
114    /// Read the current contents of a persistent buffer.
115    pub fn read_handle(&self, name: &str) -> Option<Vec<f32>> {
116        self.inner.read_handle(name)
117    }
118
119    /// GPU-resident MLX input (no-op on non-MLX backends).
120    pub fn bind_gpu_handle(&mut self, name: &str, data: &[f32]) -> bool {
121        self.inner.bind_gpu_handle(name, data)
122    }
123
124    pub fn has_gpu_handle(&self, name: &str) -> bool {
125        self.inner.has_gpu_handle(name)
126    }
127
128    pub fn set_gpu_handle_feed(&mut self, handle_name: &str, output_index: usize) -> bool {
129        self.inner.set_gpu_handle_feed(handle_name, output_index)
130    }
131
132    pub fn read_gpu_handle(&self, name: &str) -> Option<Vec<f32>> {
133        self.inner.read_gpu_handle(name)
134    }
135
136    /// Register a targeted row feed for resident KV decode (graphs that emit the
137    /// new token at the last bucket-padded output row). No-op (false) on
138    /// backends without GPU-resident handle support. See [`Self::feed_kv_row`].
139    pub fn register_kv_row_feed(&mut self, handle_name: &str, output_index: usize) -> bool {
140        self.inner.register_kv_row_feed(handle_name, output_index)
141    }
142
143    /// Fold each registered row feed's new-token row (`src_row` of its output)
144    /// into the resident handle slot at `dst_row` (`row_elems` = kv_dim),
145    /// in-place on device. Returns false when unsupported.
146    pub fn feed_kv_row(&mut self, src_row: usize, dst_row: usize, row_elems: usize) -> bool {
147        self.inner.feed_kv_row(src_row, dst_row, row_elems)
148    }
149
150    /// Run, refresh GPU handle from output, return that output vector.
151    pub fn run_feed_gpu_handle(
152        &mut self,
153        inputs: &[(&str, &[f32])],
154        handle_name: &str,
155        output_index: usize,
156    ) -> Option<Vec<f32>> {
157        self.inner
158            .run_feed_gpu_handle(inputs, handle_name, output_index)
159    }
160
161    /// Hint subsequent `run` calls to process only the first `actual`
162    /// rows along the bucket axis (out of `upper`, the compile extent).
163    /// Backends that support per-kernel active-extent dispatch honor
164    /// this; others ignore it. Pass `None` to clear.
165    ///
166    /// See `BucketedCompileCache::run_padded` for the canonical caller.
167    pub fn set_active_extent(&mut self, extent: Option<(usize, usize)>) {
168        #[cfg(feature = "cpu")]
169        if let Some((actual, _)) = extent {
170            crate::onnx_active::set_active_token_count(Some(actual))
171        }
172        self.inner.set_active_extent(extent);
173    }
174
175    /// TIDE merged MoE placement (`mask[expert]` device-resident if any layer has it).
176    pub fn set_moe_resident_experts(&mut self, mask: &[bool]) {
177        self.inner.set_moe_resident_experts(mask);
178    }
179
180    /// Per MoE layer placement (forward order). Preferred on CPU over merged mask.
181    pub fn set_moe_resident_experts_per_layer(&mut self, masks: &[&[bool]]) {
182        self.inner.set_moe_resident_experts_per_layer(masks);
183    }
184
185    /// Capture MoE router TopK on next forward (CPU). Returns false if unsupported.
186    pub fn enable_moe_topk_capture(&mut self, num_experts: usize) -> bool {
187        self.inner.enable_moe_topk_capture(num_experts)
188    }
189
190    /// Per-layer expert indices from the last forward (MoE router TopK order).
191    pub fn take_moe_topk_capture(&mut self) -> Option<Vec<Vec<u32>>> {
192        self.inner.take_moe_topk_capture()
193    }
194
195    /// GroupedMatMul GPU/CPU token accounting from the last forward (CPU).
196    pub fn take_moe_residency_stats(&mut self) -> Option<crate::MoeResidencyStats> {
197        self.inner.take_moe_residency_stats()
198    }
199
200    // ── Pipelined / async execution (Phase C) ─────────────────────────
201
202    /// Encode + commit a forward pass without waiting for the device.
203    ///
204    /// Outputs of intermediate calls are stomped — use `run_pipelined`
205    /// when you need each call's outputs back. Pair with `sync_pending`
206    /// to drain. CPU is synchronous, so this falls back to `run`.
207    pub fn commit_no_wait(&mut self, inputs: &[(&str, &[f32])]) {
208        self.inner.commit_no_wait(inputs);
209    }
210
211    /// Wait for every command queued by `commit_no_wait`. CPU is a no-op.
212    pub fn sync_pending(&mut self) {
213        self.inner.sync_pending();
214    }
215
216    /// Pipelined batch run. Issues one commit per input set, syncs once
217    /// at the end. On Metal, each commit gets its own output snapshot
218    /// (allocated + blit-copied), so subsequent commits stomping the
219    /// shared arena don't corrupt earlier runs' outputs.
220    /// Returns `out[run_idx][output_idx][element_idx]`.
221    pub fn run_pipelined(&mut self, input_sets: &[Vec<(&str, &[f32])>]) -> Vec<Vec<Vec<f32>>> {
222        self.inner.run_pipelined(input_sets)
223    }
224
225    /// Set a named parameter from raw bytes in the given dtype. The
226    /// backend handles the widen-to-f32 (or zero-widen, when supported
227    /// natively) on the way in. Lets callers feed F16/BF16 weights
228    /// without a host-side cast.
229    pub fn set_param_typed(&mut self, name: &str, data: &[u8], dtype: rlx_ir::DType) {
230        self.inner.set_param_typed(name, data, dtype);
231    }
232
233    /// Finish param upload — warms backend caches when supported.
234    pub fn finalize_params(&mut self) {
235        self.inner.finalize_params();
236    }
237
238    /// Execute with typed inputs and return outputs in their declared
239    /// graph dtype, byte-encoded. Mirrors the wgpu / MLX zero-widen
240    /// semantics on f32-arena backends (CPU + Metal) by widening at
241    /// the boundary.
242    pub fn run_typed(
243        &mut self,
244        inputs: &[(&str, &[u8], rlx_ir::DType)],
245    ) -> Vec<(Vec<u8>, rlx_ir::DType)> {
246        self.inner.run_typed(inputs)
247    }
248
249    /// Override RNG policy for in-graph random ops without recompiling.
250    pub fn set_rng(&mut self, rng: rlx_ir::RngOptions) {
251        self.inner.set_rng(rng);
252    }
253
254    /// Current RNG compile/execute policy.
255    pub fn rng(&self) -> rlx_ir::RngOptions {
256        self.inner.rng()
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use crate::*;
263
264    #[test]
265    #[cfg(feature = "cpu")]
266    fn end_to_end_session() {
267        let mut g = Graph::new("matmul_bias_gelu");
268        let x = g.input("x", Shape::new(&[2, 4], DType::F32));
269        let w = g.param("w", Shape::new(&[4, 3], DType::F32));
270        let b = g.param("b", Shape::new(&[3], DType::F32));
271        let mm = g.matmul(x, w, Shape::new(&[2, 3], DType::F32));
272        let add = g.binary(op::BinaryOp::Add, mm, b, Shape::new(&[2, 3], DType::F32));
273        let out = g.activation(op::Activation::Gelu, add, Shape::new(&[2, 3], DType::F32));
274        g.set_outputs(vec![out]);
275
276        // Compile
277        let session = Session::new(Device::Cpu);
278        let mut compiled = session.compile(g);
279
280        // Set weights
281        // w = identity-ish [4, 3]: first 3 rows are I, last row is 0
282        compiled.set_param(
283            "w",
284            &[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
285        );
286        compiled.set_param("b", &[0.5, -0.5, 0.0]);
287
288        // Run
289        let x_data = vec![
290            1.0, 0.0, 0.0, 0.0, // row 0: [1,0,0,0] @ w = [1,0,0] + bias = [1.5,-0.5,0]
291            0.0, 1.0, 0.0, 0.0, // row 1: [0,1,0,0] @ w = [0,1,0] + bias = [0.5, 0.5,0]
292        ];
293        let outputs = compiled.run(&[("x", &x_data)]);
294
295        assert_eq!(outputs.len(), 1);
296        let result = &outputs[0];
297        assert_eq!(result.len(), 6); // [2, 3]
298
299        // gelu(1.5) ≈ 1.399, gelu(-0.5) ≈ -0.154, gelu(0) = 0
300        assert!(
301            (result[0] - 1.399).abs() < 0.01,
302            "gelu(1.5) = {}",
303            result[0]
304        );
305        assert!(
306            (result[1] - -0.154).abs() < 0.01,
307            "gelu(-0.5) = {}",
308            result[1]
309        );
310        assert!((result[2]).abs() < 0.01, "gelu(0) = {}", result[2]);
311
312        // gelu(0.5) ≈ 0.346, gelu(0.5) ≈ 0.346, gelu(0) = 0
313        assert!(
314            (result[3] - 0.346).abs() < 0.01,
315            "gelu(0.5) = {}",
316            result[3]
317        );
318        assert!(
319            (result[4] - 0.346).abs() < 0.01,
320            "gelu(0.5) = {}",
321            result[4]
322        );
323
324        // Run again with different input — zero allocation
325        let x2 = vec![0.0f32; 8];
326        let outputs2 = compiled.run(&[("x", &x2)]);
327        // All zeros input → gelu(bias) for each output
328        let r2 = &outputs2[0];
329        assert!((r2[0] - 0.346).abs() < 0.01, "gelu(0.5) = {}", r2[0]); // gelu(0+0.5)
330    }
331
332    #[test]
333    #[cfg(feature = "cpu")]
334    fn device_display() {
335        use crate::device_ext::is_available;
336        assert!(format!("{}", Device::Cpu).starts_with("CPU"));
337        assert!(is_available(Device::Cpu));
338        // Backend availability is feature-gated; only assert
339        // unavailable when the corresponding feature is off.
340        #[cfg(not(feature = "gpu"))]
341        assert!(!is_available(Device::Gpu));
342        #[cfg(not(feature = "cuda"))]
343        assert!(!is_available(Device::Cuda));
344        #[cfg(not(feature = "rocm"))]
345        assert!(!is_available(Device::Rocm));
346        #[cfg(not(feature = "tpu"))]
347        assert!(!is_available(Device::Tpu));
348    }
349}