Skip to main content

mlx_native/
graph.rs

1//! [`GraphExecutor`] — batched Metal dispatch for single-encoder forward passes.
2//!
3//! llama.cpp's speed advantage over candle is NOT the kernels (Phase 0 proved
4//! candle's are as fast or faster per-call).  It is the dispatch pattern:
5//! 1 encoder per command buffer instead of ~120.  This module implements that
6//! pattern.
7//!
8//! # Usage
9//!
10//! ```ignore
11//! let mut executor = GraphExecutor::new(device.clone());
12//! let mut session = executor.begin()?;
13//!
14//! // All ops encode into the same command buffer — no per-op encoder creation.
15//! session.rms_norm(&mut registry, device.metal_device(), input, weight, output, params, rows, dim)?;
16//! session.quantized_matmul(&mut registry, &device, input, weight, scales, biases, &qparams)?;
17//! session.elementwise_add(&mut registry, device.metal_device(), a, b, out, n, DType::F32)?;
18//!
19//! // Single GPU sync point for the entire forward pass.
20//! session.finish()?;
21//! ```
22//!
23//! # Design
24//!
25//! The `GraphSession` holds a single `CommandEncoder`.  Each op method delegates
26//! to the existing op dispatch functions in [`crate::ops`], passing the session's
27//! shared encoder.  No new Metal code is needed — the ops already work with a
28//! shared encoder.  The executor just prevents creating a new encoder per op.
29//!
30//! # Phase 4e.1 — Graph IR
31//!
32//! The `ComputeGraph` type captures dispatches into a `Vec<CapturedNode>` for
33//! later replay.  `GraphExecutor::begin_recorded()` starts a session in capture
34//! mode: all op calls are intercepted at the `CommandEncoder` level and recorded
35//! instead of being sent to Metal.  `GraphSession::finish()` detects capture
36//! mode, extracts the recorded graph, and replays it into a fresh encoder via
37//! `ComputeGraph::encode_sequential()`.
38//!
39//! The existing direct-dispatch path (`begin()`) is completely unchanged.
40
41use metal::foreign_types::ForeignType;
42
43use crate::device::MlxDevice;
44use crate::encoder::{CapturedNode, CapturedOpKind, CommandEncoder, MemRange, RecordedBinding};
45use crate::error::Result;
46use crate::kernel_registry::KernelRegistry;
47use crate::ops;
48
49// Re-export types used in the public API so callers don't need separate imports.
50pub use crate::buffer::MlxBuffer;
51pub use crate::dtypes::DType;
52
53// ---------------------------------------------------------------------------
54// OpKind — operation classification for the reorder safety whitelist (4e.3)
55// ---------------------------------------------------------------------------
56
57/// Classification of a compute operation for reorder safety analysis.
58///
59/// Operations marked as reorderable can be freely reordered by the graph
60/// optimizer (Phase 4e.3) as long as their data dependencies allow it.
61/// Non-reorderable operations have side effects or dependencies that
62/// require them to stay in their original sequential position.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum OpKind {
65    /// Matrix multiplication (reorderable).
66    MatMul,
67    /// Expert-routed matrix multiplication (reorderable).
68    MatMulId,
69    /// Normalization — RMS norm, layer norm (reorderable).
70    Norm,
71    /// Rotary position embedding (reorderable).
72    Rope,
73    /// Elementwise ops — add, mul, scale, gelu, softcap, etc. (reorderable).
74    Elementwise,
75    /// Memory copy — KV cache copy, embedding gather (reorderable).
76    Copy,
77    /// Gather/scatter (reorderable).
78    Gather,
79    /// Scaled dot-product attention (NOT reorderable).
80    Sdpa,
81    /// Softmax (NOT reorderable).
82    Softmax,
83    /// MoE gate with CPU readback dependency (NOT reorderable).
84    MoeGate,
85    /// Anything else (NOT reorderable).
86    Other,
87}
88
89impl OpKind {
90    /// Whether this op kind is safe to reorder in the graph optimizer.
91    pub fn is_reorderable(&self) -> bool {
92        matches!(
93            self,
94            Self::MatMul
95                | Self::MatMulId
96                | Self::Norm
97                | Self::Rope
98                | Self::Elementwise
99                | Self::Copy
100                | Self::Gather
101        )
102    }
103}
104
105// ---------------------------------------------------------------------------
106// ComputeGraph — the recorded graph IR
107// ---------------------------------------------------------------------------
108
109/// A recorded sequence of GPU compute dispatches and barriers.
110///
111/// Created by running a forward pass with the encoder in capture mode.
112/// Can be replayed into a real `CommandEncoder` via `encode_sequential()`,
113/// producing identical Metal dispatch behavior to the original direct path.
114///
115/// Future phases (4e.2, 4e.3) will add fusion and reorder passes that
116/// transform the graph before encoding.
117pub struct ComputeGraph {
118    nodes: Vec<CapturedNode>,
119}
120
121impl ComputeGraph {
122    /// Create an empty compute graph.
123    pub fn new() -> Self {
124        Self {
125            nodes: Vec::with_capacity(128),
126        }
127    }
128
129    /// Create a compute graph from a pre-built list of captured nodes.
130    pub fn from_nodes(nodes: Vec<CapturedNode>) -> Self {
131        Self { nodes }
132    }
133
134    /// Record a captured node into the graph.
135    pub fn record(&mut self, node: CapturedNode) {
136        self.nodes.push(node);
137    }
138
139    /// Number of nodes (dispatches + barriers) in the graph.
140    pub fn len(&self) -> usize {
141        self.nodes.len()
142    }
143
144    /// Whether the graph contains no nodes.
145    pub fn is_empty(&self) -> bool {
146        self.nodes.is_empty()
147    }
148
149    /// Number of dispatch nodes (excludes barriers).
150    pub fn dispatch_count(&self) -> usize {
151        self.nodes
152            .iter()
153            .filter(|n| matches!(n, CapturedNode::Dispatch { .. }))
154            .count()
155    }
156
157    /// Number of barrier nodes.
158    pub fn barrier_count(&self) -> usize {
159        self.nodes
160            .iter()
161            .filter(|n| matches!(n, CapturedNode::Barrier))
162            .count()
163    }
164
165    /// Borrow the node list.
166    pub fn nodes(&self) -> &[CapturedNode] {
167        &self.nodes
168    }
169
170    /// Count dispatch nodes that have empty read/write range annotations.
171    ///
172    /// Used for diagnostics: if >0, the reorder pass cannot guarantee
173    /// correctness because it relies on complete annotations.
174    pub fn unannotated_dispatch_count(&self) -> usize {
175        self.nodes
176            .iter()
177            .filter(|n| matches!(n, CapturedNode::Dispatch { reads, writes, .. }
178                if reads.is_empty() || writes.is_empty()))
179            .count()
180    }
181
182    /// Take ownership of the node list, consuming the graph.
183    pub fn into_nodes(self) -> Vec<CapturedNode> {
184        self.nodes
185    }
186
187    /// Encode all nodes sequentially into the given encoder.
188    ///
189    /// Barrier sentinel nodes emit a Metal memory barrier.  Dispatch nodes
190    /// are replayed through `CommandEncoder::replay_dispatch()`.
191    ///
192    /// This produces identical GPU behavior to the direct-dispatch path —
193    /// same pipeline bindings, same dispatch dimensions, same barrier
194    /// placement.
195    ///
196    /// Returns the number of barriers emitted.
197    pub fn encode_sequential(&self, encoder: &mut CommandEncoder) -> u32 {
198        let mut barrier_count = 0u32;
199        for node in &self.nodes {
200            match node {
201                CapturedNode::Barrier => {
202                    encoder.memory_barrier();
203                    barrier_count += 1;
204                }
205                CapturedNode::Dispatch {
206                    pipeline,
207                    bindings,
208                    threads_per_grid,
209                    threads_per_threadgroup,
210                    threadgroup_memory,
211                    dispatch_kind,
212                    op_kind,
213                    ..
214                } => {
215                    // ADR-015: forward captured op_kind
216                    // into replay_dispatch via pending_op_kind so the
217                    // per-dispatch profile entries from a recorded graph
218                    // (GraphExecutor::begin_recorded path) are tagged with
219                    // the same op label as direct-dispatch encoding.
220                    encoder.set_op_kind(*op_kind);
221                    encoder.replay_dispatch(
222                        pipeline,
223                        bindings,
224                        threadgroup_memory,
225                        *threads_per_grid,
226                        *threads_per_threadgroup,
227                        *dispatch_kind,
228                    );
229                }
230            }
231        }
232        barrier_count
233    }
234
235    /// Encode the graph into a Metal command buffer, computing barriers on the
236    /// fly from each node's read/write buffer ranges.
237    ///
238    /// This is the correct encoding method for reordered graphs where barrier
239    /// sentinels have been stripped.  Mirrors llama.cpp's encode-time barrier
240    /// insertion via `ggml_metal_op_concurrency_check`.
241    ///
242    /// Returns the number of barriers emitted.
243    pub fn encode_with_barriers(&self, encoder: &mut CommandEncoder) -> u32 {
244        let mut tracker = ReorderConflictTracker::new();
245        let mut barrier_count = 0u32;
246
247        for node in &self.nodes {
248            match node {
249                CapturedNode::Dispatch {
250                    pipeline,
251                    bindings,
252                    threads_per_grid,
253                    threads_per_threadgroup,
254                    threadgroup_memory,
255                    dispatch_kind,
256                    reads,
257                    writes,
258                    op_kind,
259                    ..
260                } => {
261                    let has_ranges = !reads.is_empty() || !writes.is_empty();
262                    if has_ranges && tracker.conflicts(reads, writes) {
263                        encoder.memory_barrier();
264                        tracker.reset();
265                        barrier_count += 1;
266                    }
267                    if has_ranges {
268                        tracker.add(reads, writes);
269                    }
270                    // ADR-015: see encode_sequential note.
271                    encoder.set_op_kind(*op_kind);
272                    encoder.replay_dispatch(
273                        pipeline,
274                        bindings,
275                        threadgroup_memory,
276                        *threads_per_grid,
277                        *threads_per_threadgroup,
278                        *dispatch_kind,
279                    );
280                }
281                CapturedNode::Barrier => {
282                    // Explicit barriers still force a barrier boundary
283                    encoder.memory_barrier();
284                    tracker.reset();
285                    barrier_count += 1;
286                }
287            }
288        }
289        barrier_count
290    }
291
292    /// Encode the graph using two command buffers for CPU/GPU overlap.
293    ///
294    /// The first `n0` dispatches are encoded into `encoder0` and committed
295    /// immediately (GPU starts executing).  The remaining dispatches are encoded
296    /// into `encoder1`.  The caller is responsible for committing `encoder1`.
297    ///
298    /// This matches llama.cpp's dual command buffer pattern from
299    /// `ggml_metal_graph_compute` (ggml-metal-context.m:441-644):
300    /// `n_nodes_0 = MAX(64, 0.1 * n_nodes)` for the first buffer.
301    ///
302    /// Command buffers submitted to the same `MTLCommandQueue` execute in
303    /// submission order, so `encoder0.commit()` followed by `encoder1.commit()`
304    /// guarantees enc0 finishes before enc1 starts.  The win: the GPU starts
305    /// executing enc0 while the CPU is still encoding enc1.
306    ///
307    /// Returns `(barriers_buf0, barriers_buf1)`.
308    pub fn encode_dual_buffer(
309        &self,
310        encoder0: &mut CommandEncoder,
311        encoder1: &mut CommandEncoder,
312    ) -> (u32, u32) {
313        let dispatch_total = self.dispatch_count();
314        let n0 = std::cmp::max(64, dispatch_total / 10);
315
316        // Find the split point: the index of the n0-th dispatch node.
317        let split_idx = find_dispatch_split_index(&self.nodes, n0);
318
319        // Encode first chunk with barrier recomputation, then commit immediately.
320        let barriers0 = encode_chunk_with_barriers(&self.nodes[..split_idx], encoder0);
321        encoder0.commit();
322
323        // Encode second chunk with barrier recomputation.
324        let barriers1 = encode_chunk_with_barriers(&self.nodes[split_idx..], encoder1);
325
326        (barriers0, barriers1)
327    }
328
329    /// Run the RMS norm + MUL fusion pass over the graph.
330    ///
331    /// Scans for the pattern:
332    ///   Dispatch(RmsNorm) → Barrier(s) → Dispatch(ElemMul)
333    /// where the MUL reads the norm's output buffer, and replaces the
334    /// sequence with a single fused `rms_norm_mul_*` dispatch.
335    ///
336    /// The fused dispatch:
337    /// - Reads the norm's input (buffer 0) and weight (buffer 1)
338    /// - Reads the MUL's second operand as the scale (buffer 2)
339    /// - Writes to the MUL's output (buffer 3)
340    /// - Carries the norm's params (buffer 4)
341    /// - Uses the norm's threadgroup config and shared memory
342    ///
343    /// Returns the number of fusions applied.
344    ///
345    /// # Arguments
346    ///
347    /// * `registry` - Kernel registry for compiling the fused pipeline.
348    /// * `device`   - Metal device for pipeline compilation.
349    pub fn fuse(
350        &mut self,
351        registry: &mut KernelRegistry,
352        device: &metal::DeviceRef,
353    ) -> Result<u32> {
354        let mut result: Vec<CapturedNode> = Vec::with_capacity(self.nodes.len());
355        let mut fusions = 0u32;
356        let mut i = 0;
357
358        while i < self.nodes.len() {
359            // Check if current node is an RMS norm dispatch.
360            let is_rms_norm = matches!(
361                &self.nodes[i],
362                CapturedNode::Dispatch { op_kind: CapturedOpKind::RmsNorm, .. }
363            );
364
365            if !is_rms_norm {
366                result.push(self.nodes[i].clone());
367                i += 1;
368                continue;
369            }
370
371            // Look ahead: skip barriers, then check for ElemMul.
372            let mut j = i + 1;
373            let mut barrier_count = 0usize;
374            while j < self.nodes.len() && matches!(&self.nodes[j], CapturedNode::Barrier) {
375                barrier_count += 1;
376                j += 1;
377            }
378
379            // Must have at least one barrier and the next node must be ElemMul.
380            if barrier_count == 0 || j >= self.nodes.len() {
381                result.push(self.nodes[i].clone());
382                i += 1;
383                continue;
384            }
385
386            let is_elem_mul = matches!(
387                &self.nodes[j],
388                CapturedNode::Dispatch { op_kind: CapturedOpKind::ElemMul, .. }
389            );
390
391            if !is_elem_mul {
392                result.push(self.nodes[i].clone());
393                i += 1;
394                continue;
395            }
396
397            // Extract norm and mul dispatch fields.
398            let (norm_pipeline, norm_bindings, norm_tpg, norm_tptg, norm_tgmem, norm_dk) =
399                match &self.nodes[i] {
400                    CapturedNode::Dispatch {
401                        pipeline,
402                        bindings,
403                        threads_per_grid,
404                        threads_per_threadgroup,
405                        threadgroup_memory,
406                        dispatch_kind,
407                        ..
408                    } => (pipeline, bindings, threads_per_grid, threads_per_threadgroup, threadgroup_memory, dispatch_kind),
409                    _ => unreachable!(),
410                };
411
412            let (mul_bindings, _mul_tpg, _mul_tptg) = match &self.nodes[j] {
413                CapturedNode::Dispatch {
414                    bindings,
415                    threads_per_grid,
416                    threads_per_threadgroup,
417                    ..
418                } => (bindings, threads_per_grid, threads_per_threadgroup),
419                _ => unreachable!(),
420            };
421
422            // Verify data dependency: the norm's output buffer (slot 2) must
423            // appear as one of the MUL's input buffers (slot 0 or 1).
424            //
425            // Norm binding layout: (0=input, 1=weight, 2=output, 3=params)
426            // MUL binding layout:  (0=a, 1=b, 2=output, 3=params_bytes)
427            let norm_output_ptr = Self::buffer_ptr_for_slot(norm_bindings, 2);
428            let mul_a_ptr = Self::buffer_ptr_for_slot(mul_bindings, 0);
429            let mul_b_ptr = Self::buffer_ptr_for_slot(mul_bindings, 1);
430
431            if norm_output_ptr.is_none() || (norm_output_ptr != mul_a_ptr && norm_output_ptr != mul_b_ptr) {
432                // Data dependency not confirmed — don't fuse.
433                result.push(self.nodes[i].clone());
434                i += 1;
435                continue;
436            }
437
438            // Determine which MUL input is the scale (the one that is NOT
439            // the norm's output).
440            let scale_slot = if norm_output_ptr == mul_a_ptr { 1 } else { 0 };
441
442            // Build fused bindings:
443            //   0 = norm input
444            //   1 = norm weight
445            //   2 = scale (from MUL)
446            //   3 = MUL output
447            //   4 = norm params
448            // Gather all required bindings; bail if any are missing.
449            let (norm_input, norm_weight, scale, mul_output, norm_params) = match (
450                Self::get_binding(norm_bindings, 0),
451                Self::get_binding(norm_bindings, 1),
452                Self::get_binding(mul_bindings, scale_slot),
453                Self::get_binding(mul_bindings, 2),
454                Self::get_binding(norm_bindings, 3),
455            ) {
456                (Some(a), Some(b), Some(c), Some(d), Some(e)) => (a, b, c, d, e),
457                _ => {
458                    // Missing bindings — don't fuse.
459                    result.push(self.nodes[i].clone());
460                    i += 1;
461                    continue;
462                }
463            };
464
465            // Select fused pipeline based on the original norm pipeline name.
466            // The norm pipeline name is "rms_norm_f32", "rms_norm_f16", or
467            // "rms_norm_bf16" — we need the corresponding fused pipeline.
468            let fused_name = match Self::fused_pipeline_name(norm_pipeline) {
469                Some(name) => name,
470                None => {
471                    result.push(self.nodes[i].clone());
472                    i += 1;
473                    continue;
474                }
475            };
476
477            let fused_pipeline = registry.get_pipeline(fused_name, device)?;
478
479            let fused_bindings = vec![
480                (0, norm_input),
481                (1, norm_weight),
482                (2, scale),
483                (3, mul_output),
484                (4, norm_params),
485            ];
486
487            // Merge read/write ranges from both the norm and mul nodes for the
488            // fused dispatch.  The fused op reads everything the norm reads
489            // plus the mul's scale input, and writes to the mul's output.
490            let (fused_reads, fused_writes) = match (&self.nodes[i], &self.nodes[j]) {
491                (
492                    CapturedNode::Dispatch { reads: nr, writes: _nw, .. },
493                    CapturedNode::Dispatch { reads: mr, writes: mw, .. },
494                ) => {
495                    let mut reads = nr.clone();
496                    reads.extend_from_slice(mr);
497                    (reads, mw.clone())
498                }
499                _ => (Vec::new(), Vec::new()),
500            };
501
502            result.push(CapturedNode::Dispatch {
503                pipeline: fused_pipeline.to_owned(),
504                bindings: fused_bindings,
505                threads_per_grid: *norm_tpg,
506                threads_per_threadgroup: *norm_tptg,
507                threadgroup_memory: norm_tgmem.clone(),
508                dispatch_kind: *norm_dk,
509                op_kind: CapturedOpKind::Other, // Fused ops are not further fuseable
510                reads: fused_reads,
511                writes: fused_writes,
512            });
513
514            fusions += 1;
515            // Skip past the norm, barrier(s), and mul nodes.
516            i = j + 1;
517        }
518
519        self.nodes = result;
520        Ok(fusions)
521    }
522
523    /// Run the reorder pass over the graph to improve GPU concurrency.
524    ///
525    /// Port of llama.cpp's `ggml_metal_graph_optimize_reorder` — a greedy
526    /// 64-node lookahead that pulls independent dispatches forward to fill
527    /// larger concurrent groups between barriers.
528    ///
529    /// **Prerequisites:** Call `fuse()` first if desired.  The reorder pass
530    /// operates on the post-fusion graph.  Barrier sentinel nodes are stripped
531    /// before reordering (they will be recomputed at encode time by the
532    /// `ConflictTracker` in `encode_sequential`).
533    ///
534    /// **Algorithm (matching llama.cpp exactly):**
535    /// 1. Strip all `CapturedNode::Barrier` nodes.
536    /// 2. For each unprocessed node `i0`:
537    ///    - If it conflicts with the current concurrent group (`mrs0`):
538    ///      * Initialize `mrs1` from `i0`'s ranges (skipped-over set)
539    ///      * Lookahead up to 64 nodes for candidates that:
540    ///        (a) Are reorderable (`CapturedOpKind::is_reorderable()`)
541    ///        (b) Don't conflict with `mrs0` (current group)
542    ///        (c) Don't conflict with `mrs1` (skipped-over nodes)
543    ///      * Pull qualifying candidates into the current group
544    ///      * Non-reorderable ops break the lookahead
545    ///    - Reset `mrs0` (new concurrent group)
546    ///    - Add `i0` to the new group
547    ///
548    /// Returns the number of nodes that were moved to earlier positions.
549    pub fn reorder(&mut self) -> u32 {
550        // Step 1: Strip barrier nodes.  After fusion + reorder, barriers will
551        // be recomputed by the ConflictTracker at encode time.
552        self.nodes.retain(|n| !matches!(n, CapturedNode::Barrier));
553
554        let n = self.nodes.len();
555        if n == 0 {
556            return 0;
557        }
558
559        let mut result: Vec<usize> = Vec::with_capacity(n);
560        let mut used = vec![false; n];
561
562        // mrs0: memory ranges for the current concurrent group
563        let mut mrs0 = ReorderConflictTracker::new();
564        // mrs1: memory ranges for skipped-over (unprocessed) nodes
565        let mut mrs1 = ReorderConflictTracker::new();
566
567        const N_FORWARD: usize = 64;
568
569        for i0 in 0..n {
570            if used[i0] {
571                continue;
572            }
573
574            let node0 = &self.nodes[i0];
575
576            // Extract reads/writes for conflict check.
577            let (reads0, writes0, op_kind0) = match node0 {
578                CapturedNode::Dispatch { reads, writes, op_kind, .. } => {
579                    (reads.as_slice(), writes.as_slice(), *op_kind)
580                }
581                CapturedNode::Barrier => continue, // stripped, but be safe
582            };
583
584            // Check if node0 conflicts with the current concurrent group.
585            // Empty nodes (no ranges) never conflict — like llama.cpp's is_empty.
586            let has_ranges = !reads0.is_empty() || !writes0.is_empty();
587            if has_ranges && mrs0.conflicts(reads0, writes0) {
588                // Before starting a new group, look forward for nodes that
589                // can be pulled into the CURRENT group.
590                mrs1.reset();
591                mrs1.add(reads0, writes0);
592
593                let end = (i0 + N_FORWARD).min(n);
594                for i1 in (i0 + 1)..end {
595                    if used[i1] {
596                        continue;
597                    }
598
599                    let node1 = &self.nodes[i1];
600                    let (reads1, writes1, op_kind1) = match node1 {
601                        CapturedNode::Dispatch { reads, writes, op_kind, .. } => {
602                            (reads.as_slice(), writes.as_slice(), *op_kind)
603                        }
604                        CapturedNode::Barrier => continue,
605                    };
606
607                    // Non-reorderable ops break the lookahead.
608                    if !op_kind1.is_reorderable() {
609                        break;
610                    }
611
612                    let is_empty1 = reads1.is_empty() && writes1.is_empty();
613
614                    // A node can be reordered into the current group if:
615                    // 1. It's empty (no ranges) OR doesn't conflict with mrs0
616                    // 2. It doesn't conflict with mrs1 (skipped-over nodes)
617                    if (is_empty1 || !mrs0.conflicts(reads1, writes1))
618                        && !mrs1.conflicts(reads1, writes1)
619                    {
620                        // Pull into current concurrent group.
621                        mrs0.add(reads1, writes1);
622                        result.push(i1);
623                        used[i1] = true;
624                    } else {
625                        // Not eligible — expand the skipped-over set.
626                        mrs1.add(reads1, writes1);
627                    }
628                }
629
630                // Finalize the current concurrent group.
631                mrs0.reset();
632            }
633
634            // Expand the concurrent group with node0.
635            // (Barriers were stripped, so this is always a Dispatch.)
636            let _ = op_kind0; // suppress unused warning
637            mrs0.add(reads0, writes0);
638            result.push(i0);
639        }
640
641        // Apply the permutation to produce the reordered node list.
642        let mut reordered_count = 0u32;
643        for (pos, &orig_idx) in result.iter().enumerate() {
644            if orig_idx != pos {
645                reordered_count += 1;
646            }
647        }
648
649        // Build the reordered nodes vec.
650        let old_nodes = std::mem::take(&mut self.nodes);
651        self.nodes = result.iter().map(|&idx| old_nodes[idx].clone()).collect();
652
653        // Debug dump if requested.
654        if std::env::var("HF2Q_REORDER_DUMP").is_ok() {
655            eprintln!(
656                "  [REORDER] nodes={} reordered={} ({:.1}%)",
657                n,
658                reordered_count,
659                100.0 * reordered_count as f64 / n as f64,
660            );
661        }
662
663        reordered_count
664    }
665
666    /// Get the Metal buffer pointer for a binding at the given slot index.
667    ///
668    /// Returns `Some(ptr)` if the slot has a `RecordedBinding::Buffer`,
669    /// `None` otherwise.
670    fn buffer_ptr_for_slot(bindings: &[(u64, RecordedBinding)], slot: u64) -> Option<*const std::ffi::c_void> {
671        for (idx, binding) in bindings {
672            if *idx == slot {
673                if let RecordedBinding::Buffer { metal_buffer, offset: _ } = binding {
674                    // Use the Metal buffer's GPU address as the identity key.
675                    // On Apple Silicon unified memory, this uniquely identifies
676                    // the allocation.
677                    let ptr: *const std::ffi::c_void = metal_buffer.as_ptr() as *const _;
678                    return Some(ptr);
679                }
680            }
681        }
682        None
683    }
684
685    /// Clone the binding at the given slot index.
686    fn get_binding(bindings: &[(u64, RecordedBinding)], slot: u64) -> Option<RecordedBinding> {
687        for (idx, binding) in bindings {
688            if *idx == slot {
689                return Some(binding.clone());
690            }
691        }
692        None
693    }
694
695    /// Map a norm pipeline to its fused norm+mul pipeline name.
696    ///
697    /// The pipeline's `label()` is set by Metal to the function name, so we
698    /// can match on it.  Returns `None` if the pipeline is not a known norm.
699    fn fused_pipeline_name(pipeline: &metal::ComputePipelineState) -> Option<&'static str> {
700        match pipeline.label() {
701            "rms_norm_f32" => Some("rms_norm_mul_f32"),
702            "rms_norm_f16" => Some("rms_norm_mul_f16"),
703            "rms_norm_bf16" => Some("rms_norm_mul_bf16"),
704            _ => None,
705        }
706    }
707}
708
709impl Default for ComputeGraph {
710    fn default() -> Self {
711        Self::new()
712    }
713}
714
715// ---------------------------------------------------------------------------
716// Dual-buffer encoding helpers (Phase 4e.4)
717// ---------------------------------------------------------------------------
718
719/// Find the node index where the n0-th dispatch starts.
720///
721/// Counts `CapturedNode::Dispatch` nodes until `n0` are reached, then returns
722/// the index of the n0-th dispatch (i.e., the first node of the second chunk).
723/// If `n0 >= dispatch_count`, returns `nodes.len()` (everything in chunk 0).
724fn find_dispatch_split_index(nodes: &[CapturedNode], n0: usize) -> usize {
725    let mut dispatches_seen = 0usize;
726    for (i, node) in nodes.iter().enumerate() {
727        if matches!(node, CapturedNode::Dispatch { .. }) {
728            dispatches_seen += 1;
729            if dispatches_seen == n0 {
730                return i + 1; // split AFTER the n0-th dispatch
731            }
732        }
733    }
734    nodes.len()
735}
736
737/// Encode a slice of captured nodes into a command encoder, recomputing
738/// barriers on the fly from each node's read/write buffer ranges.
739///
740/// This is the chunked counterpart of `ComputeGraph::encode_with_barriers()`.
741/// Factored out so both halves of a dual-buffer encode can use it.
742///
743/// Returns the number of barriers emitted.
744fn encode_chunk_with_barriers(nodes: &[CapturedNode], encoder: &mut CommandEncoder) -> u32 {
745    let mut tracker = ReorderConflictTracker::new();
746    let mut barrier_count = 0u32;
747
748    for node in nodes {
749        match node {
750            CapturedNode::Dispatch {
751                pipeline,
752                bindings,
753                threads_per_grid,
754                threads_per_threadgroup,
755                threadgroup_memory,
756                dispatch_kind,
757                reads,
758                writes,
759                op_kind,
760                ..
761            } => {
762                let has_ranges = !reads.is_empty() || !writes.is_empty();
763                if has_ranges && tracker.conflicts(reads, writes) {
764                    encoder.memory_barrier();
765                    tracker.reset();
766                    barrier_count += 1;
767                }
768                if has_ranges {
769                    tracker.add(reads, writes);
770                }
771                // ADR-015: forward captured op_kind so the
772                // per-dispatch profile dump groups dual-buffer chunked replay
773                // entries by the same op_kind label as direct dispatch.
774                encoder.set_op_kind(*op_kind);
775                encoder.replay_dispatch(
776                    pipeline,
777                    bindings,
778                    threadgroup_memory,
779                    *threads_per_grid,
780                    *threads_per_threadgroup,
781                    *dispatch_kind,
782                );
783            }
784            CapturedNode::Barrier => {
785                encoder.memory_barrier();
786                tracker.reset();
787                barrier_count += 1;
788            }
789        }
790    }
791    barrier_count
792}
793
794// ---------------------------------------------------------------------------
795// ReorderConflictTracker — range-based conflict detection for the reorder pass
796// ---------------------------------------------------------------------------
797
798/// Memory range conflict tracker for the reorder pass (Phase 4e.3).
799///
800/// Works with `MemRange` tuples `(start, end)` stored on `CapturedNode::Dispatch`,
801/// rather than requiring live `&MlxBuffer` references.  This is the reorder-time
802/// equivalent of the runtime `ConflictTracker`.
803///
804/// Conflict rules match llama.cpp's `ggml_mem_ranges_check`:
805/// - Two read ranges: OK (read-read is concurrent-safe)
806/// - A new read overlapping an existing write: CONFLICT (RAW)
807/// - A new write overlapping any existing range: CONFLICT (WAR/WAW)
808struct ReorderConflictTracker {
809    /// (start, end, is_write) for all ranges in the tracked set.
810    ranges: Vec<(usize, usize, bool)>,
811}
812
813impl ReorderConflictTracker {
814    fn new() -> Self {
815        Self {
816            ranges: Vec::with_capacity(64),
817        }
818    }
819
820    fn reset(&mut self) {
821        self.ranges.clear();
822    }
823
824    /// Check if a dispatch with the given read/write ranges conflicts with
825    /// any range in this tracker.
826    fn conflicts(&self, reads: &[MemRange], writes: &[MemRange]) -> bool {
827        // New reads vs existing writes (RAW)
828        for &(r_start, r_end) in reads {
829            for &(s, e, is_write) in &self.ranges {
830                if is_write && r_start < e && r_end > s {
831                    return true;
832                }
833            }
834        }
835        // New writes vs all existing ranges (WAR/WAW)
836        for &(w_start, w_end) in writes {
837            for &(s, e, _) in &self.ranges {
838                if w_start < e && w_end > s {
839                    return true;
840                }
841            }
842        }
843        false
844    }
845
846    /// Add read and write ranges to the tracked set.
847    fn add(&mut self, reads: &[MemRange], writes: &[MemRange]) {
848        for &(start, end) in reads {
849            self.ranges.push((start, end, false));
850        }
851        for &(start, end) in writes {
852            self.ranges.push((start, end, true));
853        }
854    }
855}
856
857/// Batched Metal dispatch — encodes multiple ops into a single `CommandEncoder`.
858///
859/// Create one per model (or per forward-pass loop).  Call [`begin`](Self::begin)
860/// at the start of each forward pass to get a [`GraphSession`] that holds the
861/// shared encoder.
862pub struct GraphExecutor {
863    device: MlxDevice,
864}
865
866impl GraphExecutor {
867    /// Create a new graph executor backed by the given device.
868    pub fn new(device: MlxDevice) -> Self {
869        Self { device }
870    }
871
872    /// Begin a new forward pass (direct-dispatch mode).
873    ///
874    /// Returns a [`GraphSession`] that holds a fresh `CommandEncoder`.  All ops
875    /// encoded through the session share this single encoder.  Call
876    /// [`GraphSession::finish`] to commit and wait.
877    pub fn begin(&self) -> Result<GraphSession<'_>> {
878        let encoder = self.device.command_encoder()?;
879        // ADR-015: start a programmatic capture if
880        // MLX_METAL_CAPTURE+METAL_CAPTURE_ENABLED are set.  No-op when
881        // unset; one-shot per process so subsequent forward passes do
882        // not pay the env-check cost more than once.
883        let metal_capture = {
884            let mut c = crate::metal_capture::MetalCapture::from_env(&self.device);
885            if let Some(ref mut cap) = c {
886                cap.begin();
887            }
888            c
889        };
890        Ok(GraphSession {
891            encoder,
892            device: &self.device,
893            barrier_count: 0,
894            tracker: ConflictTracker::new(),
895            dispatch_in_group: 0,
896            total_dispatches: 0,
897            group_sizes: [0; 8],
898            recording: false,
899            metal_capture,
900        })
901    }
902
903    /// Begin a new forward pass in capture (record) mode.
904    ///
905    /// All op calls are recorded into a `ComputeGraph` instead of being
906    /// dispatched to Metal.  When [`GraphSession::finish`] is called, the
907    /// recorded graph is replayed into a fresh encoder via
908    /// `ComputeGraph::encode_sequential()`.
909    ///
910    /// The API is identical to `begin()` — callers do not need to change
911    /// any op call code.  The only behavioral difference: GPU work happens
912    /// at `finish()` time rather than at each op call.
913    pub fn begin_recorded(&self) -> Result<GraphSession<'_>> {
914        let mut encoder = self.device.command_encoder()?;
915        encoder.start_capture();
916        // ADR-015: see GraphExecutor::begin().
917        let metal_capture = {
918            let mut c = crate::metal_capture::MetalCapture::from_env(&self.device);
919            if let Some(ref mut cap) = c {
920                cap.begin();
921            }
922            c
923        };
924        Ok(GraphSession {
925            encoder,
926            device: &self.device,
927            barrier_count: 0,
928            tracker: ConflictTracker::new(),
929            dispatch_in_group: 0,
930            total_dispatches: 0,
931            group_sizes: [0; 8],
932            recording: true,
933            metal_capture,
934        })
935    }
936
937    /// Borrow the underlying device.
938    pub fn device(&self) -> &MlxDevice {
939        &self.device
940    }
941}
942
943/// A single forward pass execution context.
944///
945/// All ops are encoded into one `CommandEncoder`.  Call [`finish`](Self::finish)
946/// to commit the command buffer and wait for GPU completion — this is the ONLY
947/// sync point per forward pass.
948///
949/// If an op returns an error, the session can be dropped without committing.
950/// The underlying command buffer is abandoned (never committed to the GPU).
951/// Tracks buffer address ranges for automatic barrier elision.
952///
953/// Mirrors llama.cpp's `ggml_mem_ranges` — accumulates the read and write
954/// ranges of all dispatches in the current concurrent group. When a new
955/// dispatch's reads overlap with an existing write (RAW), or its writes
956/// overlap with an existing read or write (WAR/WAW), a barrier is needed.
957/// Otherwise the dispatch can run concurrently and the barrier is elided.
958///
959/// Uses CPU-visible `contents_ptr()` addresses, which on Apple Silicon
960/// unified memory equal the GPU addresses.
961pub struct ConflictTracker {
962    /// (start, end, is_write) tuples for the current concurrent group.
963    ranges: Vec<(usize, usize, bool)>,
964}
965
966impl ConflictTracker {
967    fn new() -> Self {
968        Self {
969            ranges: Vec::with_capacity(32),
970        }
971    }
972
973    /// Reset the tracker — called after emitting a barrier.
974    fn reset(&mut self) {
975        self.ranges.clear();
976    }
977
978    /// Check if a new dispatch with the given reads and writes conflicts
979    /// with the current concurrent group.
980    ///
981    /// Conflict rules (same as llama.cpp `ggml_mem_ranges_check`):
982    /// - Two SRC (read) ranges in the same buffer: OK (read-read)
983    /// - A new SRC overlapping an existing DST: CONFLICT (RAW)
984    /// - A new DST overlapping an existing SRC or DST: CONFLICT (WAR/WAW)
985    /// Check for conflicts and return the reason if one is found.
986    /// Returns (conflict_type, new_buf_ptr, existing_buf_ptr) or None.
987    fn conflicts_reason(&self, reads: &[&MlxBuffer], writes: &[&MlxBuffer])
988        -> Option<(&'static str, usize, usize)>
989    {
990        // Check new reads against existing writes (RAW)
991        for r in reads {
992            let r_start = r.contents_ptr() as usize;
993            let r_end = r_start + r.byte_len();
994            for &(s, e, is_write) in &self.ranges {
995                if is_write && r_start < e && r_end > s {
996                    return Some(("RAW", r_start, s));
997                }
998            }
999        }
1000        // Check new writes against existing reads and writes (WAR/WAW)
1001        for w in writes {
1002            let w_start = w.contents_ptr() as usize;
1003            let w_end = w_start + w.byte_len();
1004            for &(s, e, is_write) in &self.ranges {
1005                if w_start < e && w_end > s {
1006                    let kind = if is_write { "WAW" } else { "WAR" };
1007                    return Some((kind, w_start, s));
1008                }
1009            }
1010        }
1011        None
1012    }
1013
1014    /// Add read and write ranges to the current concurrent group.
1015    fn add(&mut self, reads: &[&MlxBuffer], writes: &[&MlxBuffer]) {
1016        for r in reads {
1017            let start = r.contents_ptr() as usize;
1018            let end = start + r.byte_len();
1019            self.ranges.push((start, end, false));
1020        }
1021        for w in writes {
1022            let start = w.contents_ptr() as usize;
1023            let end = start + w.byte_len();
1024            self.ranges.push((start, end, true));
1025        }
1026    }
1027}
1028
1029pub struct GraphSession<'a> {
1030    encoder: CommandEncoder,
1031    device: &'a MlxDevice,
1032    barrier_count: u32,
1033    tracker: ConflictTracker,
1034    dispatch_in_group: u32,
1035    total_dispatches: u32,
1036    /// Histogram: group_sizes[i] = number of concurrent groups with (i+1) dispatches
1037    group_sizes: [u32; 8],
1038    /// Whether this session was created in capture/record mode.
1039    recording: bool,
1040    /// ADR-015: optional Metal frame capture wrapping
1041    /// this session's GPU work.  Populated by `MetalCapture::from_env`
1042    /// when `MLX_METAL_CAPTURE=<path>` + `METAL_CAPTURE_ENABLED=1` are
1043    /// both set in the process env AND the process-global one-shot
1044    /// latch has not yet flipped.  `None` in all other cases (default
1045    /// production path).  Capture scope is begun in
1046    /// [`GraphExecutor::begin`] / [`GraphExecutor::begin_recorded`]
1047    /// and ended in [`Self::finish`] / [`Self::commit`] BEFORE the
1048    /// CB is committed, so all enqueued CBs land inside the trace.
1049    metal_capture: Option<crate::metal_capture::MetalCapture>,
1050}
1051
1052impl<'a> GraphSession<'a> {
1053    /// Encode an RMS normalization into this session's encoder.
1054    ///
1055    /// Delegates to [`ops::rms_norm::dispatch_rms_norm`].
1056    pub fn rms_norm(
1057        &mut self,
1058        registry: &mut KernelRegistry,
1059        device: &metal::DeviceRef,
1060        input: &MlxBuffer,
1061        weight: &MlxBuffer,
1062        output: &MlxBuffer,
1063        params_buf: &MlxBuffer,
1064        rows: u32,
1065        dim: u32,
1066    ) -> Result<()> {
1067        ops::rms_norm::dispatch_rms_norm(
1068            &mut self.encoder,
1069            registry,
1070            device,
1071            input,
1072            weight,
1073            output,
1074            params_buf,
1075            rows,
1076            dim,
1077        )
1078    }
1079
1080    /// Encode a quantized matrix multiplication into this session's encoder.
1081    ///
1082    /// Delegates to [`ops::quantized_matmul::quantized_matmul`].
1083    /// Returns the freshly allocated output buffer.
1084    pub fn quantized_matmul(
1085        &mut self,
1086        registry: &mut KernelRegistry,
1087        device: &MlxDevice,
1088        input: &MlxBuffer,
1089        weight: &MlxBuffer,
1090        scales: &MlxBuffer,
1091        biases: &MlxBuffer,
1092        params: &ops::quantized_matmul::QuantizedMatmulParams,
1093    ) -> Result<MlxBuffer> {
1094        ops::quantized_matmul::quantized_matmul(
1095            &mut self.encoder,
1096            registry,
1097            device,
1098            input,
1099            weight,
1100            scales,
1101            biases,
1102            params,
1103        )
1104    }
1105
1106    /// Encode a SIMD-optimized quantized matmul into this session's encoder.
1107    ///
1108    /// Delegates to [`ops::quantized_matmul::quantized_matmul_simd`].
1109    /// Returns the freshly allocated output buffer.
1110    pub fn quantized_matmul_simd(
1111        &mut self,
1112        registry: &mut KernelRegistry,
1113        device: &MlxDevice,
1114        input: &MlxBuffer,
1115        weight: &MlxBuffer,
1116        scales: &MlxBuffer,
1117        biases: &MlxBuffer,
1118        params: &ops::quantized_matmul::QuantizedMatmulParams,
1119    ) -> Result<MlxBuffer> {
1120        ops::quantized_matmul::quantized_matmul_simd(
1121            &mut self.encoder,
1122            registry,
1123            device,
1124            input,
1125            weight,
1126            scales,
1127            biases,
1128            params,
1129        )
1130    }
1131
1132    /// Encode a GGML block-format quantized mat-vec into this session's encoder.
1133    ///
1134    /// Delegates to [`ops::quantized_matmul_ggml::quantized_matmul_ggml`].
1135    pub fn quantized_matmul_ggml(
1136        &mut self,
1137        registry: &mut KernelRegistry,
1138        device: &MlxDevice,
1139        input: &MlxBuffer,
1140        weight: &MlxBuffer,
1141        output: &MlxBuffer,
1142        params: &ops::quantized_matmul_ggml::GgmlQuantizedMatmulParams,
1143    ) -> Result<()> {
1144        ops::quantized_matmul_ggml::quantized_matmul_ggml(
1145            &mut self.encoder,
1146            registry,
1147            device,
1148            input,
1149            weight,
1150            output,
1151            params,
1152        )
1153    }
1154
1155    /// Encode an expert-routed GGML block-format quantized mat-vec into this session's encoder.
1156    ///
1157    /// Delegates to [`ops::quantized_matmul_id_ggml::quantized_matmul_id_ggml`].
1158    #[allow(clippy::too_many_arguments)]
1159    pub fn quantized_matmul_id_ggml(
1160        &mut self,
1161        registry: &mut KernelRegistry,
1162        device: &MlxDevice,
1163        input: &MlxBuffer,
1164        weight: &MlxBuffer,
1165        ids: &MlxBuffer,
1166        output: &MlxBuffer,
1167        params: &ops::quantized_matmul_id_ggml::GgmlQuantizedMatmulIdParams,
1168    ) -> Result<()> {
1169        ops::quantized_matmul_id_ggml::quantized_matmul_id_ggml(
1170            &mut self.encoder,
1171            registry,
1172            device,
1173            input,
1174            weight,
1175            ids,
1176            output,
1177            params,
1178        )
1179    }
1180
1181    /// Byte-identity-required variant of [`Self::quantized_matmul_id_ggml`] —
1182    /// always routes to the per-token `mv_id` kernel (ADR-040 Phase F
1183    /// `iter-F-moe-mvid`). The gemma4 `[N,hidden]` batched decode body calls
1184    /// this for its MoE gate_up/down `_id` dispatches so that at N≥5 (where the
1185    /// down projection's `n_tokens = N*top_k > 32` would otherwise cross into
1186    /// the `mm_id` grouped kernel, whose reduction order is not bit-identical
1187    /// to serial) the batched forward stays byte-identical to N serial decodes.
1188    pub fn quantized_matmul_id_ggml_mv(
1189        &mut self,
1190        registry: &mut KernelRegistry,
1191        device: &MlxDevice,
1192        input: &MlxBuffer,
1193        weight: &MlxBuffer,
1194        ids: &MlxBuffer,
1195        output: &MlxBuffer,
1196        params: &ops::quantized_matmul_id_ggml::GgmlQuantizedMatmulIdParams,
1197    ) -> Result<()> {
1198        ops::quantized_matmul_id_ggml::quantized_matmul_id_ggml_mv(
1199            &mut self.encoder,
1200            registry,
1201            device,
1202            input,
1203            weight,
1204            ids,
1205            output,
1206            params,
1207        )
1208    }
1209
1210    /// Pooled-scratch variant of [`Self::quantized_matmul_id_ggml`] — the
1211    /// `IdMmScratch` is caller-owned so batched prefill amortises the
1212    /// per-call allocations that the auto entry point incurs (ADR-011
1213    /// Phase 3 Wave P3b).
1214    #[allow(clippy::too_many_arguments)]
1215    pub fn quantized_matmul_id_ggml_pooled(
1216        &mut self,
1217        registry: &mut KernelRegistry,
1218        device: &MlxDevice,
1219        input: &MlxBuffer,
1220        weight: &MlxBuffer,
1221        ids: &MlxBuffer,
1222        output: &MlxBuffer,
1223        scratch: &mut ops::quantized_matmul_id_ggml::IdMmScratch,
1224        params: &ops::quantized_matmul_id_ggml::GgmlQuantizedMatmulIdParams,
1225    ) -> Result<()> {
1226        ops::quantized_matmul_id_ggml::quantized_matmul_id_ggml_pooled(
1227            &mut self.encoder,
1228            registry,
1229            device,
1230            input,
1231            weight,
1232            ids,
1233            output,
1234            scratch,
1235            params,
1236        )
1237    }
1238
1239    /// Encode scaled dot-product attention into this session's encoder.
1240    ///
1241    /// Delegates to [`ops::sdpa::sdpa`].
1242    pub fn sdpa(
1243        &mut self,
1244        registry: &mut KernelRegistry,
1245        device: &MlxDevice,
1246        q: &MlxBuffer,
1247        k: &MlxBuffer,
1248        v: &MlxBuffer,
1249        output: &MlxBuffer,
1250        params: &ops::sdpa::SdpaParams,
1251        batch_size: u32,
1252    ) -> Result<()> {
1253        ops::sdpa::sdpa(
1254            &mut self.encoder,
1255            registry,
1256            device,
1257            q,
1258            k,
1259            v,
1260            output,
1261            params,
1262            batch_size,
1263        )
1264    }
1265
1266    /// Encode flash attention vector (SIMD-vectorized decode-path SDPA).
1267    ///
1268    /// Delegates to [`ops::flash_attn_vec::flash_attn_vec`].
1269    pub fn flash_attn_vec(
1270        &mut self,
1271        registry: &mut KernelRegistry,
1272        device: &MlxDevice,
1273        q: &MlxBuffer,
1274        k: &MlxBuffer,
1275        v: &MlxBuffer,
1276        output: &MlxBuffer,
1277        tmp: &MlxBuffer,
1278        params: &ops::flash_attn_vec::FlashAttnVecParams,
1279    ) -> Result<()> {
1280        ops::flash_attn_vec::flash_attn_vec(
1281            &mut self.encoder,
1282            registry,
1283            device,
1284            q,
1285            k,
1286            v,
1287            output,
1288            tmp,
1289            params,
1290        )
1291    }
1292
1293    /// Encode an elementwise add into this session's encoder.
1294    ///
1295    /// Delegates to [`ops::elementwise::elementwise_add`].
1296    pub fn elementwise_add(
1297        &mut self,
1298        registry: &mut KernelRegistry,
1299        device: &metal::DeviceRef,
1300        a: &MlxBuffer,
1301        b: &MlxBuffer,
1302        output: &MlxBuffer,
1303        n_elements: usize,
1304        dtype: DType,
1305    ) -> Result<()> {
1306        ops::elementwise::elementwise_add(
1307            &mut self.encoder,
1308            registry,
1309            device,
1310            a,
1311            b,
1312            output,
1313            n_elements,
1314            dtype,
1315        )
1316    }
1317
1318    /// Encode an elementwise multiply into this session's encoder.
1319    ///
1320    /// Delegates to [`ops::elementwise::elementwise_mul`].
1321    pub fn elementwise_mul(
1322        &mut self,
1323        registry: &mut KernelRegistry,
1324        device: &metal::DeviceRef,
1325        a: &MlxBuffer,
1326        b: &MlxBuffer,
1327        output: &MlxBuffer,
1328        n_elements: usize,
1329        dtype: DType,
1330    ) -> Result<()> {
1331        ops::elementwise::elementwise_mul(
1332            &mut self.encoder,
1333            registry,
1334            device,
1335            a,
1336            b,
1337            output,
1338            n_elements,
1339            dtype,
1340        )
1341    }
1342
1343    /// Encode a RoPE transform into this session's encoder.
1344    ///
1345    /// Delegates to [`ops::rope::dispatch_rope`].
1346    pub fn rope(
1347        &mut self,
1348        registry: &mut KernelRegistry,
1349        device: &metal::DeviceRef,
1350        input: &MlxBuffer,
1351        output: &MlxBuffer,
1352        params_buf: &MlxBuffer,
1353        positions_buf: &MlxBuffer,
1354        seq_len: u32,
1355        head_dim: u32,
1356    ) -> Result<()> {
1357        ops::rope::dispatch_rope(
1358            &mut self.encoder,
1359            registry,
1360            device,
1361            input,
1362            output,
1363            params_buf,
1364            positions_buf,
1365            seq_len,
1366            head_dim,
1367        )
1368    }
1369
1370    /// Encode a GELU activation into this session's encoder.
1371    ///
1372    /// Delegates to [`ops::gelu::dispatch_gelu`].
1373    pub fn gelu(
1374        &mut self,
1375        registry: &mut KernelRegistry,
1376        device: &metal::DeviceRef,
1377        input: &MlxBuffer,
1378        output: &MlxBuffer,
1379    ) -> Result<()> {
1380        ops::gelu::dispatch_gelu(
1381            &mut self.encoder,
1382            registry,
1383            device,
1384            input,
1385            output,
1386        )
1387    }
1388
1389    /// Encode a softmax into this session's encoder.
1390    ///
1391    /// Delegates to [`ops::softmax::dispatch_softmax`].
1392    pub fn softmax(
1393        &mut self,
1394        registry: &mut KernelRegistry,
1395        device: &metal::DeviceRef,
1396        input: &MlxBuffer,
1397        output: &MlxBuffer,
1398        params_buf: &MlxBuffer,
1399        rows: u32,
1400        cols: u32,
1401    ) -> Result<()> {
1402        ops::softmax::dispatch_softmax(
1403            &mut self.encoder,
1404            registry,
1405            device,
1406            input,
1407            output,
1408            params_buf,
1409            rows,
1410            cols,
1411        )
1412    }
1413
1414    /// Encode a softcap into this session's encoder.
1415    ///
1416    /// Delegates to [`ops::softcap::dispatch_softcap`].
1417    pub fn softcap(
1418        &mut self,
1419        registry: &mut KernelRegistry,
1420        device: &metal::DeviceRef,
1421        input: &MlxBuffer,
1422        output: &MlxBuffer,
1423        params_buf: &MlxBuffer,
1424        cap: f32,
1425    ) -> Result<()> {
1426        ops::softcap::dispatch_softcap(
1427            &mut self.encoder,
1428            registry,
1429            device,
1430            input,
1431            output,
1432            params_buf,
1433            cap,
1434        )
1435    }
1436
1437    /// Encode an RMS norm without learned scale (f32) into this session's encoder.
1438    ///
1439    /// Delegates to [`ops::rms_norm::dispatch_rms_norm_no_scale_f32`].
1440    pub fn rms_norm_no_scale_f32(
1441        &mut self,
1442        registry: &mut KernelRegistry,
1443        device: &metal::DeviceRef,
1444        input: &MlxBuffer,
1445        output: &MlxBuffer,
1446        params_buf: &MlxBuffer,
1447        rows: u32,
1448        dim: u32,
1449    ) -> Result<()> {
1450        ops::rms_norm::dispatch_rms_norm_no_scale_f32(
1451            &mut self.encoder,
1452            registry,
1453            device,
1454            input,
1455            output,
1456            params_buf,
1457            rows,
1458            dim,
1459        )
1460    }
1461
1462    /// Encode a NeoX RoPE (f32) with optional freq_factors into this session's encoder.
1463    ///
1464    /// Delegates to [`ops::rope::dispatch_rope_neox_f32`].
1465    #[allow(clippy::too_many_arguments)]
1466    pub fn rope_neox_f32(
1467        &mut self,
1468        registry: &mut KernelRegistry,
1469        device: &metal::DeviceRef,
1470        input: &MlxBuffer,
1471        output: &MlxBuffer,
1472        params_buf: &MlxBuffer,
1473        positions_buf: &MlxBuffer,
1474        freq_factors: Option<&MlxBuffer>,
1475        seq_len: u32,
1476        n_heads: u32,
1477        head_dim: u32,
1478        rope_dim: u32,
1479    ) -> Result<()> {
1480        ops::rope::dispatch_rope_neox_f32(
1481            &mut self.encoder,
1482            registry,
1483            device,
1484            input,
1485            output,
1486            params_buf,
1487            positions_buf,
1488            freq_factors,
1489            seq_len,
1490            n_heads,
1491            head_dim,
1492            rope_dim,
1493        )
1494    }
1495
1496    /// Insert a GPU memory barrier (MTLBarrierScopeBuffers).
1497    ///
1498    /// Unconditional barrier — always emits. Use `barrier_between` for
1499    /// automatic conflict detection that can elide unnecessary barriers.
1500    #[inline]
1501    pub fn barrier(&mut self) {
1502        // Record the outgoing group size
1503        if self.dispatch_in_group > 0 {
1504            let idx = (self.dispatch_in_group as usize).min(self.group_sizes.len()) - 1;
1505            self.group_sizes[idx] += 1;
1506        }
1507        self.encoder.memory_barrier();
1508        self.tracker.reset();
1509        self.barrier_count += 1;
1510        self.dispatch_in_group = 0;
1511    }
1512
1513    /// Smart barrier with conflict detection.
1514    ///
1515    /// Checks if the next dispatch (with the given read and write buffers)
1516    /// actually conflicts with any dispatch in the current concurrent group.
1517    /// If yes, emits a Metal barrier and resets the tracker. If no, the
1518    /// barrier is elided and the dispatch can run concurrently.
1519    ///
1520    /// This mirrors llama.cpp's `ggml_metal_op_concurrency_check` +
1521    /// `ggml_metal_op_concurrency_reset` pattern.
1522    #[inline]
1523    pub fn barrier_between(&mut self, reads: &[&MlxBuffer], writes: &[&MlxBuffer]) {
1524        // In capture mode, stash the read/write ranges so the next captured
1525        // dispatch node carries them for the reorder pass (Phase 4e.3).
1526        if self.recording {
1527            let read_ranges: Vec<MemRange> = reads
1528                .iter()
1529                .map(|b| {
1530                    let start = b.contents_ptr() as usize;
1531                    (start, start + b.byte_len())
1532                })
1533                .collect();
1534            let write_ranges: Vec<MemRange> = writes
1535                .iter()
1536                .map(|b| {
1537                    let start = b.contents_ptr() as usize;
1538                    (start, start + b.byte_len())
1539                })
1540                .collect();
1541            self.encoder.set_pending_buffer_ranges(read_ranges, write_ranges);
1542        }
1543
1544        let reason = self.tracker.conflicts_reason(reads, writes);
1545        if let Some((_kind, _new_ptr, _existing_ptr)) = reason {
1546            // Record the outgoing group size before resetting
1547            if self.dispatch_in_group > 0 {
1548                let idx = (self.dispatch_in_group as usize).min(self.group_sizes.len()) - 1;
1549                self.group_sizes[idx] += 1;
1550            }
1551            self.encoder.memory_barrier();
1552            self.tracker.reset();
1553            self.barrier_count += 1;
1554            self.dispatch_in_group = 0;
1555        }
1556        self.dispatch_in_group += 1;
1557        self.total_dispatches += 1;
1558        self.tracker.add(reads, writes);
1559    }
1560
1561    /// Print group size histogram to stderr (for HF2Q_MLX_TIMING debug).
1562    pub fn dump_group_stats(&self) {
1563        // Record the final (unterminated) group
1564        let mut gs = self.group_sizes;
1565        if self.dispatch_in_group > 0 {
1566            let idx = (self.dispatch_in_group as usize).min(gs.len()) - 1;
1567            gs[idx] += 1;
1568        }
1569        let total_groups: u32 = gs.iter().sum();
1570        eprintln!("  [GROUP_STATS] dispatches={} barriers={} groups={} ratio={:.2}",
1571            self.total_dispatches, self.barrier_count, total_groups,
1572            if total_groups > 0 { self.total_dispatches as f64 / total_groups as f64 } else { 0.0 });
1573        for (i, &count) in gs.iter().enumerate() {
1574            if count > 0 {
1575                eprintln!("    size {}: {} groups", i + 1, count);
1576            }
1577        }
1578    }
1579
1580    /// Register a dispatch's buffer ranges without checking for conflicts.
1581    ///
1582    /// Use after dispatching an op that doesn't need a barrier check (e.g.,
1583    /// the first dispatch in a session, or dispatches known to be concurrent).
1584    ///
1585    /// In recording mode, also retroactively annotates the most recently
1586    /// captured dispatch node with these ranges if it was missing them.
1587    /// That keeps the reorder pass able to reason about dispatches that
1588    /// were preceded by `track_dispatch` rather than `barrier_between`.
1589    #[inline]
1590    pub fn track_dispatch(&mut self, reads: &[&MlxBuffer], writes: &[&MlxBuffer]) {
1591        if self.recording {
1592            let read_ranges: Vec<MemRange> = reads
1593                .iter()
1594                .map(|b| {
1595                    let start = b.contents_ptr() as usize;
1596                    (start, start + b.byte_len())
1597                })
1598                .collect();
1599            let write_ranges: Vec<MemRange> = writes
1600                .iter()
1601                .map(|b| {
1602                    let start = b.contents_ptr() as usize;
1603                    (start, start + b.byte_len())
1604                })
1605                .collect();
1606            self.encoder
1607                .annotate_last_dispatch_if_missing(read_ranges, write_ranges);
1608        }
1609        self.tracker.add(reads, writes);
1610    }
1611
1612    /// Return the number of barriers inserted so far in this session.
1613    #[inline]
1614    pub fn barrier_count(&self) -> u32 {
1615        self.barrier_count
1616    }
1617
1618    /// Cumulative nanoseconds spent in ConflictTracker checks (diagnostic).
1619    /// Returns 0 when timing is not compiled in.
1620    pub fn tracker_overhead_ns(&self) -> u64 {
1621        0
1622    }
1623
1624    /// Borrow the underlying command encoder for direct op dispatch.
1625    ///
1626    /// Use this when you need to call an op function that is not wrapped by
1627    /// a `GraphSession` method.  The returned encoder is the same shared
1628    /// encoder — all dispatches still go into the same command buffer.
1629    pub fn encoder_mut(&mut self) -> &mut CommandEncoder {
1630        &mut self.encoder
1631    }
1632
1633    /// Borrow the device reference.
1634    pub fn device(&self) -> &MlxDevice {
1635        self.device
1636    }
1637
1638    /// Whether this session is in capture/record mode.
1639    pub fn is_recording(&self) -> bool {
1640        self.recording
1641    }
1642
1643    /// Commit the command buffer and wait for GPU completion.
1644    ///
1645    /// This is the ONLY sync point per forward pass.  After this call, all
1646    /// output buffers are readable by the CPU.
1647    ///
1648    /// In recording mode: extracts the captured graph, replays it into
1649    /// the encoder via `ComputeGraph::encode_sequential()`, then commits
1650    /// and waits.  The result is identical to the direct-dispatch path.
1651    ///
1652    /// Consumes the session — no further ops can be encoded.
1653    pub fn finish(mut self) -> Result<()> {
1654        if self.recording {
1655            if let Some(nodes) = self.encoder.take_capture() {
1656                let graph = ComputeGraph::from_nodes(nodes);
1657                graph.encode_sequential(&mut self.encoder);
1658            }
1659        }
1660        self.encoder.commit_and_wait()
1661    }
1662
1663    /// Commit the command buffer WITHOUT waiting.
1664    ///
1665    /// The GPU begins executing immediately.  Use this for fire-and-forget
1666    /// dispatch when you do not need results until later.
1667    ///
1668    /// In recording mode: replays the captured graph before committing.
1669    ///
1670    /// Consumes the session.
1671    pub fn commit(mut self) -> CommandEncoder {
1672        if self.recording {
1673            if let Some(nodes) = self.encoder.take_capture() {
1674                let graph = ComputeGraph::from_nodes(nodes);
1675                graph.encode_sequential(&mut self.encoder);
1676            }
1677        }
1678        self.encoder.commit();
1679        // ADR-015: close the capture window AFTER
1680        // commit (so the CB is recorded inside the trace) but BEFORE
1681        // returning the encoder (so the trace finalizes promptly).
1682        // `MTLCaptureManager.stopCapture` marks the recording
1683        // boundary at exactly this point.  CBs committed BEFORE this
1684        // line are in the trace; any work done by the caller through
1685        // the returned encoder is NOT.  This matches llama.cpp's
1686        // ggml-metal-context.m:608 pattern (`stopCapture` after the
1687        // last `commit + waitUntilCompleted`).
1688        //
1689        // Note: for the async commit() path, the GPU may still be
1690        // executing the CB when stopCapture fires.  Apple's
1691        // MTLCaptureManager is documented to flush in-flight work
1692        // into the trace before finalizing the file.
1693        if let Some(mut cap) = self.metal_capture.take() {
1694            cap.end();
1695        }
1696        self.encoder
1697    }
1698
1699    /// Commit the command buffer and wait, returning split timing.
1700    ///
1701    /// Returns `(encoding_ns, gpu_wait_ns)` where:
1702    /// - `encoding_ns` is the time from session begin to commit (CPU encoding)
1703    /// - `gpu_wait_ns` is the time from commit to GPU completion
1704    ///
1705    /// The `session_begin` instant should be captured right after `exec.begin()`.
1706    ///
1707    /// In recording mode: replays the captured graph before committing.
1708    ///
1709    /// Consumes the session.
1710    pub fn finish_with_timing(mut self, session_begin: std::time::Instant) -> Result<(u64, u64)> {
1711        if self.recording {
1712            if let Some(nodes) = self.encoder.take_capture() {
1713                let graph = ComputeGraph::from_nodes(nodes);
1714                graph.encode_sequential(&mut self.encoder);
1715            }
1716        }
1717        let commit_start = std::time::Instant::now();
1718        let encoding_ns = commit_start.duration_since(session_begin).as_nanos() as u64;
1719        self.encoder.commit();
1720        self.encoder.wait_until_completed()?;
1721        let gpu_wait_ns = commit_start.elapsed().as_nanos() as u64;
1722        Ok((encoding_ns, gpu_wait_ns))
1723    }
1724
1725    /// Finish this session and return the GPU wall-clock interval in ns.
1726    ///
1727    /// Returns `(gpu_interval_ns,)` where `gpu_interval_ns` is the CFTimeInterval
1728    /// difference between `MTLCommandBuffer.GPUEndTime` and
1729    /// `MTLCommandBuffer.GPUStartTime`, converted to ns.  Excludes CPU
1730    /// commit+wait overhead — that appears in the residual when bucket
1731    /// sums are compared to the outer wall-clock.
1732    ///
1733    /// Used by `HF2Q_PROFILE_GPU_TS=1` to accumulate pure GPU time per
1734    /// op bucket.  In recording mode: replays the captured graph before
1735    /// committing.
1736    ///
1737    /// Consumes the session.
1738    pub fn finish_with_gpu_time(mut self) -> Result<u64> {
1739        if self.recording {
1740            if let Some(nodes) = self.encoder.take_capture() {
1741                let graph = ComputeGraph::from_nodes(nodes);
1742                graph.encode_sequential(&mut self.encoder);
1743            }
1744        }
1745        let (gs, ge) = self.encoder.commit_wait_with_gpu_time()?;
1746        // GPUStartTime/GPUEndTime are CFTimeInterval (seconds, double).
1747        // Guard against negative deltas (can happen on the first CB of
1748        // a run if the kernel driver lazily initialises the timeline;
1749        // clamp to zero in that case).
1750        let delta = (ge - gs).max(0.0);
1751        Ok((delta * 1.0e9) as u64)
1752    }
1753
1754    /// Finish with fusion: run the RMS norm + MUL fusion pass before
1755    /// replaying the graph.
1756    ///
1757    /// Only meaningful in recording mode.  In direct-dispatch mode, this
1758    /// behaves identically to `finish()`.
1759    ///
1760    /// Returns `(fusions_applied,)` on success.
1761    pub fn finish_with_fusion(
1762        mut self,
1763        registry: &mut KernelRegistry,
1764        device: &metal::DeviceRef,
1765    ) -> Result<u32> {
1766        let mut fusions = 0;
1767        if self.recording {
1768            if let Some(nodes) = self.encoder.take_capture() {
1769                let mut graph = ComputeGraph::from_nodes(nodes);
1770                fusions = graph.fuse(registry, device)?;
1771                graph.encode_sequential(&mut self.encoder);
1772            }
1773        }
1774        self.encoder.commit_and_wait()?;
1775        Ok(fusions)
1776    }
1777
1778    /// Async-commit variant of `finish_with_fusion`.
1779    ///
1780    /// Runs the fusion pass on the captured graph, replays the fused
1781    /// graph into a fresh command buffer, then commits *without waiting*
1782    /// (fire-and-forget — GPU executes asynchronously while CPU returns).
1783    /// Mirrors `commit()` semantics, plus the fusion optimization pass.
1784    ///
1785    /// Used by the prefill per-layer pattern where the next layer's CPU
1786    /// encoding should overlap with this layer's GPU execution — peer's
1787    /// llama.cpp Metal backend uses the same async-commit-with-graph-opt
1788    /// pattern at `ggml-metal-context.m:617-621`.
1789    ///
1790    /// In direct-dispatch mode (recording=false), behaves identically to
1791    /// `commit()`: no fusion happens, just an async commit.
1792    ///
1793    /// Consumes the session.  Returns `(encoder, fusions_applied)`.
1794    ///
1795    /// ADR-029: first step of graph_opt port to prefill.
1796    pub fn commit_with_fusion(
1797        mut self,
1798        registry: &mut KernelRegistry,
1799        device: &metal::DeviceRef,
1800    ) -> Result<(CommandEncoder, u32)> {
1801        let mut fusions = 0;
1802        if self.recording {
1803            if let Some(nodes) = self.encoder.take_capture() {
1804                let mut graph = ComputeGraph::from_nodes(nodes);
1805                fusions = graph.fuse(registry, device)?;
1806                graph.encode_sequential(&mut self.encoder);
1807            }
1808        }
1809        self.encoder.commit();
1810        // Close the metal_capture window after commit (same pattern as `commit`).
1811        if let Some(mut cap) = self.metal_capture.take() {
1812            cap.end();
1813        }
1814        Ok((self.encoder, fusions))
1815    }
1816
1817    /// Finish with fusion and split timing.
1818    ///
1819    /// Like `finish_with_timing` but runs the fusion pass first.
1820    /// Returns `(encoding_ns, gpu_wait_ns, fusions_applied)`.
1821    pub fn finish_with_fusion_and_timing(
1822        mut self,
1823        registry: &mut KernelRegistry,
1824        device: &metal::DeviceRef,
1825        session_begin: std::time::Instant,
1826    ) -> Result<(u64, u64, u32)> {
1827        let mut fusions = 0;
1828        if self.recording {
1829            if let Some(nodes) = self.encoder.take_capture() {
1830                let mut graph = ComputeGraph::from_nodes(nodes);
1831                fusions = graph.fuse(registry, device)?;
1832                graph.encode_sequential(&mut self.encoder);
1833            }
1834        }
1835        let commit_start = std::time::Instant::now();
1836        let encoding_ns = commit_start.duration_since(session_begin).as_nanos() as u64;
1837        self.encoder.commit();
1838        self.encoder.wait_until_completed()?;
1839        let gpu_wait_ns = commit_start.elapsed().as_nanos() as u64;
1840        Ok((encoding_ns, gpu_wait_ns, fusions))
1841    }
1842
1843    /// Finish with fusion AND reorder: run both graph optimization passes
1844    /// before replaying the graph.
1845    ///
1846    /// Only meaningful in recording mode.  In direct-dispatch mode, this
1847    /// behaves identically to `finish()`.
1848    ///
1849    /// Returns `(fusions_applied, nodes_reordered)` on success.
1850    pub fn finish_with_fusion_and_reorder(
1851        mut self,
1852        registry: &mut KernelRegistry,
1853        device: &metal::DeviceRef,
1854    ) -> Result<(u32, u32)> {
1855        let mut fusions = 0;
1856        let mut reordered = 0;
1857        if self.recording {
1858            if let Some(nodes) = self.encoder.take_capture() {
1859                let mut graph = ComputeGraph::from_nodes(nodes);
1860                fusions = graph.fuse(registry, device)?;
1861                reordered = graph.reorder();
1862                graph.encode_with_barriers(&mut self.encoder);
1863            }
1864        }
1865        self.encoder.commit_and_wait()?;
1866        Ok((fusions, reordered))
1867    }
1868
1869    /// Finish with fusion, reorder, and split timing.
1870    ///
1871    /// Like `finish_with_fusion_and_timing` but also runs the reorder pass.
1872    /// Returns `(encoding_ns, gpu_wait_ns, fusions_applied, nodes_reordered)`.
1873    pub fn finish_with_fusion_reorder_and_timing(
1874        mut self,
1875        registry: &mut KernelRegistry,
1876        device: &metal::DeviceRef,
1877        session_begin: std::time::Instant,
1878    ) -> Result<(u64, u64, u32, u32)> {
1879        let mut fusions = 0;
1880        let mut reordered = 0;
1881        if self.recording {
1882            if let Some(nodes) = self.encoder.take_capture() {
1883                let mut graph = ComputeGraph::from_nodes(nodes);
1884                fusions = graph.fuse(registry, device)?;
1885                reordered = graph.reorder();
1886                graph.encode_with_barriers(&mut self.encoder);
1887            }
1888        }
1889        let commit_start = std::time::Instant::now();
1890        let encoding_ns = commit_start.duration_since(session_begin).as_nanos() as u64;
1891        self.encoder.commit();
1892        self.encoder.wait_until_completed()?;
1893        let gpu_wait_ns = commit_start.elapsed().as_nanos() as u64;
1894        Ok((encoding_ns, gpu_wait_ns, fusions, reordered))
1895    }
1896
1897    /// Finish with the full optimization pipeline: fuse, reorder, dual-buffer
1898    /// encode.
1899    ///
1900    /// Runs the fusion pass, reorder pass, then encodes the graph into two
1901    /// Metal command buffers for CPU/GPU overlap.  The first ~10% of dispatches
1902    /// are committed immediately so the GPU can start executing while the CPU
1903    /// encodes the remaining ~90%.
1904    ///
1905    /// Only meaningful in recording mode.  In direct-dispatch mode, this
1906    /// behaves identically to `finish()`.
1907    ///
1908    /// Returns `(fusions_applied, nodes_reordered, barriers_buf0, barriers_buf1)`.
1909    pub fn finish_optimized(
1910        mut self,
1911        registry: &mut KernelRegistry,
1912        device: &metal::DeviceRef,
1913    ) -> Result<(u32, u32, u32, u32)> {
1914        let mut fusions = 0;
1915        let mut reordered = 0;
1916        let mut barriers0 = 0u32;
1917        let mut barriers1 = 0u32;
1918
1919        if self.recording {
1920            if let Some(nodes) = self.encoder.take_capture() {
1921                // Commit the capture encoder's empty command buffer so its
1922                // MTLCommandQueue pool slot is freed (same fix as timing variant).
1923                self.encoder.commit();
1924
1925                let mut graph = ComputeGraph::from_nodes(nodes);
1926                fusions = graph.fuse(registry, device)?;
1927                reordered = graph.reorder();
1928
1929                let mut enc0 = self.device.command_encoder()?;
1930                let mut enc1 = self.device.command_encoder()?;
1931
1932                let (b0, b1) = graph.encode_dual_buffer(&mut enc0, &mut enc1);
1933                barriers0 = b0;
1934                barriers1 = b1;
1935
1936                // enc0 was already committed inside encode_dual_buffer.
1937                // Commit enc1 and wait — Metal queue ordering guarantees enc0
1938                // finishes before enc1 starts executing.
1939                enc1.commit_and_wait()?;
1940
1941                // The original encoder was never committed (capture mode drained
1942                // it). We need to end it cleanly — dropping it will end the
1943                // active encoder if any, and the uncommitted command buffer is
1944                // abandoned.  That is safe: Metal silently drops uncommitted
1945                // command buffers.
1946                return Ok((fusions, reordered, barriers0, barriers1));
1947            }
1948        }
1949
1950        // Direct-dispatch fallback: just commit the original encoder.
1951        self.encoder.commit_and_wait()?;
1952        Ok((fusions, reordered, barriers0, barriers1))
1953    }
1954
1955    /// Finish with the full optimization pipeline and split timing.
1956    ///
1957    /// Like `finish_optimized` but returns timing information.
1958    /// Returns `(encoding_ns, gpu_wait_ns, fusions, reordered, barriers_buf0, barriers_buf1)`.
1959    ///
1960    /// Timing breakdown:
1961    /// - `encoding_ns`: CPU time from session begin to first buffer commit
1962    ///   (fusion + reorder + encode chunk 0)
1963    /// - `gpu_wait_ns`: wall time from second buffer commit to GPU completion
1964    ///   (includes GPU execution of both buffers, overlapped with chunk 1 encoding)
1965    pub fn finish_optimized_with_timing(
1966        mut self,
1967        registry: &mut KernelRegistry,
1968        device: &metal::DeviceRef,
1969        session_begin: std::time::Instant,
1970    ) -> Result<(u64, u64, u32, u32, u32, u32)> {
1971        let mut fusions = 0;
1972        let mut reordered = 0;
1973        let mut barriers0 = 0u32;
1974        let mut barriers1 = 0u32;
1975
1976        if self.recording {
1977            if let Some(nodes) = self.encoder.take_capture() {
1978                // Commit the capture encoder's empty command buffer so its
1979                // MTLCommandQueue pool slot is freed.  Without this, each
1980                // token leaks one uncommitted buffer and the queue exhausts
1981                // its ~64-slot pool after ~64 tokens, causing a deadlock.
1982                self.encoder.commit();
1983
1984                let opt_t0 = std::time::Instant::now();
1985                let mut graph = ComputeGraph::from_nodes(nodes);
1986                let fuse_t0 = std::time::Instant::now();
1987                fusions = graph.fuse(registry, device)?;
1988                let fuse_us = fuse_t0.elapsed().as_micros();
1989
1990                let reorder_t0 = std::time::Instant::now();
1991                let unannotated = graph.unannotated_dispatch_count();
1992                if unannotated == 0 {
1993                    reordered = graph.reorder();
1994                } else if std::env::var("HF2Q_MLX_TIMING").is_ok() {
1995                    eprintln!("  [GRAPH_OPT] WARN: skipping reorder — {} of {} dispatches lack range annotations",
1996                        unannotated, graph.dispatch_count());
1997                }
1998                let reorder_us = reorder_t0.elapsed().as_micros();
1999                let opt_us = opt_t0.elapsed().as_micros();
2000
2001                let diag = std::env::var("HF2Q_GRAPH_DIAG").is_ok();
2002                let t0 = std::time::Instant::now();
2003                let mut enc0 = self.device.command_encoder()?;
2004                let mut enc1 = self.device.command_encoder()?;
2005                let enc_create_us = t0.elapsed().as_micros();
2006
2007                let t1 = std::time::Instant::now();
2008                let (b0, b1) = graph.encode_dual_buffer(&mut enc0, &mut enc1);
2009                barriers0 = b0;
2010                barriers1 = b1;
2011                let encode_us = t1.elapsed().as_micros();
2012
2013                let encoding_ns = session_begin.elapsed().as_nanos() as u64;
2014
2015                let wait_start = std::time::Instant::now();
2016                enc1.commit_and_wait()?;
2017                let gpu_wait_ns = wait_start.elapsed().as_nanos() as u64;
2018
2019                if diag {
2020                    eprintln!("  [DIAG] fuse={:.1}ms reorder={:.1}ms opt_total={:.1}ms enc_create={:.1}ms encode={:.1}ms gpu_wait={:.1}ms barriers={}+{}",
2021                        fuse_us as f64 / 1e3, reorder_us as f64 / 1e3, opt_us as f64 / 1e3,
2022                        enc_create_us as f64 / 1e3, encode_us as f64 / 1e3,
2023                        gpu_wait_ns as f64 / 1e6, b0, b1);
2024                }
2025
2026                return Ok((encoding_ns, gpu_wait_ns, fusions, reordered, barriers0, barriers1));
2027            }
2028        }
2029
2030        // Direct-dispatch fallback.
2031        let commit_start = std::time::Instant::now();
2032        let encoding_ns = commit_start.duration_since(session_begin).as_nanos() as u64;
2033        self.encoder.commit();
2034        self.encoder.wait_until_completed()?;
2035        let gpu_wait_ns = commit_start.elapsed().as_nanos() as u64;
2036        Ok((encoding_ns, gpu_wait_ns, fusions, reordered, barriers0, barriers1))
2037    }
2038}