Skip to main content

fuel_graph/
registry.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! FusedOpRegistry — metadata side. Phase 7.6 step 1 (skeleton).
3//!
4//! Architecture v1.0 splits op identity into two layers:
5//! - the closed [`crate::Op`] enum carries primitive variants exhaustively;
6//! - one arm — `Op::Fused(FusedOpId, FusedOpParams)` — delegates to an
7//!   open registry of fused-op entries populated at process startup.
8//!
9//! This module holds the *graph-side metadata* half of the registry:
10//! identity ([`FusedOpId`], [`FusedOps`]), pattern + decomposition + backward
11//! identity, and shape/dtype rules. The *kernel side* (BackendImpl with
12//! its function-pointer KernelRef, cost estimate, PrecisionGuarantee, caps,
13//! revision hash) lives in `fuel-storage::fused` because it carries
14//! `KernelRef`, which fuel-graph cannot import without inverting the
15//! existing fuel-storage → fuel-graph dependency direction. The two halves
16//! are joined at runtime by [`FusedOpId`].
17//!
18//! See [docs/fused-op-registry.md](../../docs/fused-op-registry.md) for the
19//! full design and [docs/architecture/03-ir.md](../../docs/architecture/03-ir.md)
20//! for the architectural commitment.
21//!
22//! ## Status (step 1)
23//!
24//! Types only. No callers; no behavior change. Subsequent steps:
25//! - Step 2: extend `Op` with `Op::Fused(FusedOpId, FusedOpParams)` arm.
26//! - Step 3: migrate SoftmaxLastDim end-to-end through the registry.
27//! - Step 4: migrate the remaining 12 fused ops.
28//! - Step 5: drop the per-fused-op `Op` variants once nothing emits them.
29
30use crate::{Graph, NodeId};
31use fireline_grammar::PatternNode;
32use fuel_ir::storage::OutputViewSpec;
33use fuel_ir::{DType, DynScalar, Shape};
34use std::collections::HashMap;
35
36pub mod awq_matmul;
37pub mod causal_conv1d;
38pub mod conv2d;
39pub mod conv_transpose_2d;
40pub mod flash_attn;
41pub mod flash_attn_backward;
42pub mod fused_linear;
43pub mod fused_softmax_cross_entropy;
44pub mod inplace_affine;
45pub mod layer_norm_last_dim;
46pub mod layer_norm_last_dim_backward;
47pub mod matmul_top_k;
48pub mod nf4_matmul;
49pub mod paged_attn;
50pub mod powi_backward;
51pub mod qmatmul;
52pub mod reduce_max_to_backward;
53pub mod rms_norm_last_dim;
54pub mod rms_norm_last_dim_backward;
55pub mod rope;
56pub mod row_scaled_matmul;
57pub mod selective_scan;
58pub mod softmax_last_dim;
59pub mod softmax_last_dim_backward;
60pub mod ssd_chunk_scan;
61pub mod top_k_last_dim;
62
63/// Stable identifier for a registered fused op. Indexes into
64/// `FusedOpRegistry::entries`. Newtype over `u16` (~65K capacity is
65/// plenty; today's catalog is 13-14 entries).
66///
67/// Constants for the well-known ids are exposed via [`FusedOps`]
68/// associated constants for ergonomic pattern matching in rule code.
69#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
70pub struct FusedOpId(pub u16);
71
72/// Reserved sentinel: an unallocated id. Never appears in a populated
73/// registry; useful as a placeholder during step-2-and-step-3 migration
74/// where a `BackwardKind::Fused(id)` may be written before the backward's
75/// own id is assigned.
76impl FusedOpId {
77    pub const UNASSIGNED: FusedOpId = FusedOpId(0);
78
79    /// The first id reserved for **runtime-registered** (e.g. JIT-synthesized
80    /// or import-time) fused ops. Static build-time ids are dense
81    /// `1..RUNTIME_FUSED_BASE`; runtime ids are allocated from
82    /// `RUNTIME_FUSED_BASE..` so the two spaces never collide and
83    /// [`Self::is_runtime`] is the routing bit. See
84    /// `docs/specs/runtime-fused-op-registration.md`.
85    pub const RUNTIME_FUSED_BASE: u16 = 0x8000;
86
87    /// Whether this id names a runtime-registered fused op — its metadata lives
88    /// in the `runtime_fused` sidecar, not the static [`default_registry`].
89    pub fn is_runtime(self) -> bool {
90        self.0 >= Self::RUNTIME_FUSED_BASE
91    }
92}
93
94/// Per-fused-op metadata. Identity, pattern, decomposition, backward,
95/// shape/dtype rules. The kernel-side metadata (per-backend KernelRef +
96/// cost + PrecisionGuarantee + caps) lives in `fuel-storage::fused` and is
97/// joined to this entry by [`FusedOpEntry::id`].
98pub struct FusedOpEntry {
99    /// Stable id for this fused op.
100    pub id: FusedOpId,
101    /// Stable human-readable name. Shows up in op_short_name, error
102    /// messages, telemetry.
103    pub name: &'static str,
104    /// Categorical bucket. Used by telemetry and for cost-model defaults.
105    pub family: FusedOpFamily,
106    /// Canonical primitive subgraph this fused op represents. Used by
107    /// fusion rules to recognize the pattern in a base map.
108    pub pattern: SubgraphPattern,
109    /// Decompose a fused-op node into its primitive subgraph. Used by
110    /// lowering rules (and by autograd when [`Self::backward`] is
111    /// `BackwardKind::Decompose`).
112    ///
113    /// Contract: the function appends primitive nodes to `graph` and
114    /// returns the [`NodeId`] of the new root that replaces the fused
115    /// node identified by the second argument. The fused node itself
116    /// remains in the arena; the driver rewrites consumer edges to point
117    /// at the returned id.
118    pub decompose: fn(&mut Graph, NodeId, &FusedOpParams) -> NodeId,
119    /// Backward identity for this fused op.
120    pub backward: BackwardKind,
121    /// Output shape rule, computed from input shapes and params.
122    /// For a multi-output op, this must return slot 0's shape (which
123    /// is also the primary `Node::shape` of the producer).
124    pub shape_rule: fn(&[Shape], &FusedOpParams) -> Shape,
125    /// Output dtype rule, computed from input dtypes and params.
126    /// For a multi-output op, this must return slot 0's dtype (which
127    /// is also the primary `Node::dtype` of the producer).
128    pub dtype_rule: fn(&[DType], &FusedOpParams) -> DType,
129    /// Multi-output authoring contract (Option C, Session 2).
130    ///
131    /// `None` for single-output ops (the default) — the op produces
132    /// one logical output whose shape/dtype come from `shape_rule`
133    /// and `dtype_rule`, and the realized storage is a plain
134    /// non-bundled [`fuel_backend_contract::Storage`].
135    ///
136    /// `Some(fn)` for multi-output ops: returns the per-slot specs
137    /// from input shapes + dtypes + params. The Graph and the realized
138    /// storage allocator both consume the same Vec — `set_output_views`
139    /// on `Graph::push` and `allocate_bundled_storage` at realization
140    /// time — so the slot count and per-slot shapes/dtypes are a
141    /// single source of truth.
142    ///
143    /// Contract for multi-output ops:
144    /// - `output_views(...)[0].dtype` MUST equal `dtype_rule(...)`.
145    /// - `output_views(...)[0].shape` MUST equal `shape_rule(...)`.
146    /// - The returned Vec must be non-empty; a "multi-output op" with
147    ///   one slot is just a single-output op (drop `output_views`).
148    ///
149    /// `Graph::push_fused` (the multi-output-aware emit path that
150    /// Session 2 introduces) checks these at graph-build time. The
151    /// raw `Graph::push` + `Graph::set_output_views` route preserves
152    /// the same invariants via `set_output_views`'s validation pass.
153    #[expect(
154        clippy::type_complexity,
155        reason = "optional output-view rule fn-pointer; a type alias would add indirection for a single field"
156    )]
157    pub output_views: Option<fn(&[Shape], &[DType], &FusedOpParams) -> Vec<OutputViewSpec>>,
158
159    /// Which input index this fused op DESTROYS (mutates in place) on execution,
160    /// or `None` if it is non-destructive (produces a fresh output, every input
161    /// stays readable). **Mandatory** — declared here, beside `decompose`/
162    /// `pattern`, so a fused op cannot be registered without stating it (the
163    /// recipe principle extended: a third required property of the same object).
164    /// `Op::destructive_input` reads this via `default_registry().entry(id)`
165    /// instead of a separate hand-maintained match, so the fact lives with the
166    /// thing and cannot drift out of sync. A destructive op needs the scheduler
167    /// to pin it after every non-destructive reader of the destroyed input
168    /// (`opt::derive_ordering`); a wrong `None` here is a silent data race. There
169    /// is deliberately no default: `Option<usize>` is the *value* (which input,
170    /// or none), but the field itself must be set at every construction site.
171    /// GAP-076.
172    pub destructive_input: Option<usize>,
173}
174
175/// Categorical bucket for a fused op. Drives telemetry grouping and
176/// some cost-model defaults; not load-bearing for dispatch.
177#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
178pub enum FusedOpFamily {
179    Forward,
180    Backward,
181    Quantized,
182    Attention,
183    Norm,
184}
185
186/// Per-instance parameters carried by `Op::Fused(id, params)` nodes.
187/// Step 1 ships only the SoftmaxLastDim variant — the proof-of-concept
188/// migration target. Step 4 extends this enum with the remaining 12
189/// fused-op variants, one per migrated op.
190///
191/// The variant tag is implicitly aligned with the registry entry's
192/// [`FusedOpId`] via the convention that registering an id places its
193/// matching variant here. CSE and `op_key` derive a hashable key from
194/// the tuple `(FusedOpId, FusedOpParams)` so identical fused-op nodes
195/// with identical params dedupe.
196#[derive(Debug, Clone, PartialEq)]
197pub enum FusedOpParams {
198    /// SoftmaxLastDim has no per-instance parameters; the last-dim axis
199    /// is implicit in the input shape.
200    SoftmaxLastDim,
201    /// FusedLinear ((a @ b) + bias). No per-instance parameters: the
202    /// matmul shape and bias rank are implicit in the three inputs.
203    FusedLinear,
204    /// RmsNormLastDim — carries the epsilon term used to stabilize the
205    /// division by RMS magnitude. The last-dim axis itself is implicit
206    /// in the input shape.
207    RmsNormLastDim { eps: f64 },
208    /// LayerNormLastDim — carries the epsilon term used to stabilize
209    /// the division by sqrt(variance + eps). Like RmsNormLastDim, the
210    /// last-dim axis is implicit in the input shape.
211    LayerNormLastDim { eps: f64 },
212    /// Rope — rotary position embedding with caller-supplied cos/sin
213    /// tables. No per-instance parameters: `seq` and `head_dim` are
214    /// recovered from the inputs at execution time (see
215    /// `fuel-storage::pipelined::op_to_op_params`).
216    Rope,
217    /// Conv2D — 2-D cross-correlation with stride / padding / groups.
218    /// Spatial dilation is always 1 today; the field is omitted from
219    /// the param payload until backward's dilation-as-stride trick
220    /// forces the primitive variant to grow one (per the comments
221    /// in `NodeHandle::backward`'s `Op::Conv2D` arm).
222    Conv2D {
223        stride: (usize, usize),
224        padding: (usize, usize),
225        groups: usize,
226    },
227    /// SoftmaxLastDimBackward — `s * (g - sum(g * s, last, keepdim))`.
228    /// Two inputs (forward_y, upstream); parameterless. Higher-order
229    /// gradients panic per `NodeHandle::backward`'s MVP behavior.
230    SoftmaxLastDimBackward,
231    /// LayerNormLastDimBackward — recomputes mean/variance from the
232    /// original x. Two inputs (x, upstream) + eps.
233    LayerNormLastDimBackward { eps: f64 },
234    /// RmsNormLastDimBackward — `r_rms · (g − x·s / (n·(mean_sq + eps)))`.
235    /// Two inputs (x, upstream) + eps.
236    RmsNormLastDimBackward { eps: f64 },
237    /// ReduceMaxToBackward — routes upstream to argmax positions
238    /// (fair-share on ties). Two inputs (x, upstream); parameterless.
239    ReduceMaxToBackward,
240    /// PowIBackward — `grad_x = exp · x^(exp-1) · upstream`. Two
241    /// inputs `(x, upstream)`. Carries the same `exp` as the forward
242    /// `Op::PowI(exp)` so the backward kernel can evaluate the
243    /// derivative coefficient directly.
244    PowIBackward { exp: i32 },
245    /// ConvTranspose2D — fractionally-strided 2-D convolution.
246    /// Two inputs `[x, weight]` (no bias). Carries the full
247    /// stride/padding/output_padding/dilation/groups bundle.
248    ConvTranspose2D {
249        stride: (usize, usize),
250        padding: (usize, usize),
251        output_padding: (usize, usize),
252        dilation: (usize, usize),
253        groups: usize,
254    },
255    /// FlashAttn — multi-head scaled-dot-product attention with
256    /// FlashAttention-shaped kernel hooks. 4-5 inputs (q, k, v,
257    /// optional alibi).
258    ///
259    /// `k_len` (Phase D symbolic extents): `None` ⇒ the attended K/V
260    /// length is the full K extent `k.dims()[2]` (today's behavior).
261    /// `Some(dyn)` ⇒ the K/V buffers are a fixed **capacity**
262    /// `[B, Hkv, max_seq, D]` and only the first `dyn.resolve(env)` rows
263    /// are attended (the live prefix), with the causal mask
264    /// bottom-right-aligned at offset `k_len - Sq` (the standard FA2
265    /// convention, = `cached_len` in decode). This is the runtime
266    /// `k_len` decoupled from K's allocated shape that backs flash
267    /// decode over a persistent capacity KV-cache. Build via
268    /// [`NodeHandle::flash_attn_dyn`](crate::NodeHandle::flash_attn_dyn).
269    FlashAttn {
270        softmax_scale: f32,
271        causal: bool,
272        window_size_left: Option<usize>,
273        window_size_right: Option<usize>,
274        softcap: Option<f32>,
275        k_len: Option<DynScalar>,
276    },
277    /// PagedAttn — paged-cache attention. 5-6 inputs (q, k_cache,
278    /// v_cache, block_table, context_lens, optional alibi).
279    PagedAttn {
280        softmax_scale: f32,
281        block_size: usize,
282        softcap: Option<f32>,
283    },
284    /// QMatMul — quantized matrix multiply `C = A @ dequant(W_Q)`.
285    /// Two inputs `[a, w_q_bytes]`. The U32-typed w_q_bytes carries
286    /// a Q-type block stream; `quant_type` selects the dequant
287    /// implementation; `k` / `n` are the logical weight dims.
288    QMatMul {
289        quant_type: crate::QuantType,
290        k: usize,
291        n: usize,
292    },
293    /// InplaceAffine — `x = mul·x + add`, mutating input 0. Single
294    /// input. Destructive on index 0 (marked via
295    /// `Op::destructive_input`). Phase 1 of the in-place ops
296    /// infrastructure.
297    InplaceAffine { mul: f64, add: f64 },
298    /// SsdChunkScan — Mamba-2's State-Space Duality chunked scan
299    /// (forward only). Five inputs:
300    /// - `x`:   `[batch, seqlen, heads, head_dim]`
301    /// - `dt`:  `[batch, seqlen, heads]`
302    /// - `a`:   `[heads]` — per-head scalar log A.
303    /// - `b`/`c`: `[batch, seqlen, heads, state_dim]`
304    ///
305    /// Output: `y: [batch, seqlen, heads, head_dim]`.
306    ///
307    /// `chunk_size` is the SSD block size (typically 256 in Mamba-2).
308    /// It controls GPU parallelism granularity but doesn't affect the
309    /// mathematical result — the CPU kernel runs a sequential scan
310    /// regardless. Any `chunk_size ∈ [1, seqlen]` that divides
311    /// `seqlen` is valid.
312    SsdChunkScan { chunk_size: usize },
313    /// Nf4Matmul — bitsandbytes-style 4-bit NormalFloat quantized
314    /// matrix multiply. Three inputs:
315    /// - `activations`: `[..., M, K]`
316    /// - `w_packed`:    `[N, K/2]` U8 (two 4-bit codes per byte,
317    ///   K must be even).
318    /// - `absmax`:      `[N, K/block_size]` F32 (per-output-row,
319    ///   per-block scales).
320    ///
321    /// Output: `[..., M, N]` matching the activations' dtype.
322    ///
323    /// `block_size` is the NF4 quantization block size (typically
324    /// 64 in bitsandbytes). The NF4 NormalFloat lookup table is
325    /// baked into the kernel — not a runtime input.
326    Nf4Matmul { block_size: usize },
327    /// AwqMatmul — AWQ (mit-han-lab) asymmetric int4 weight-only
328    /// matmul: `dequant(q) = (q - zero_point) * scale`, per-group.
329    /// Four inputs, the quantized three in the baracuda W4A16 kernel
330    /// layout (OC-major):
331    /// - `activations`: `[..., M, K]`
332    /// - `weight`:      `[N, K/8]` U32 (eight int4 codes per word,
333    ///   sequential nibble order, K must be a multiple of 8).
334    /// - `zeros`:       `[N, zeros_w]` U32 (group `g` is nibble
335    ///   `g % 8` of word `g / 8`); `zeros_w` is
336    ///   [`crate::registry::awq_matmul::awq_zeros_w`].
337    /// - `scales`:      `[N, 8 * zeros_w]` F16 (entry `g` is group
338    ///   `g`'s scale).
339    ///
340    /// Output: `[..., M, N]` matching the activations' dtype.
341    ///
342    /// `group_size` must be 64 or 128 and evenly divide `K`.
343    /// `split_k_iters` is a CUDA-kernel launch-tuning parameter (unused
344    /// by the decompose path; carried so the fused CUDA dispatch does
345    /// not need a second params shape).
346    ///
347    /// See the module doc on [`crate::registry::awq_matmul`] for the
348    /// layout rationale and the decompose recipe.
349    AwqMatmul {
350        group_size: usize,
351        split_k_iters: i32,
352    },
353    /// RowScaledMatMul: `(a @ b) * row_scale`, no per-instance parameters
354    /// (the shapes are implicit in the three inputs).
355    RowScaledMatMul,
356    /// TopKLastDim: the `k` largest values along the last axis (`k` static).
357    TopKLastDim { k: usize },
358    /// MatMulTopK: `TopKLastDim(a @ b)` fused (`k` static).
359    MatMulTopK { k: usize },
360    /// FlashAttnBackward — shared params for the Q/K/V backward
361    /// variants. Carries the same shape parameters as the forward
362    /// `FlashAttn` so the recompute pass produces identical scores.
363    /// All three FusedOpId-marked variants (FLASH_ATTN_BACKWARD_Q/K/V)
364    /// use this single variant; the FusedOpId distinguishes which
365    /// gradient is being computed.
366    FlashAttnBackward {
367        softmax_scale: f32,
368        causal: bool,
369        window_size_left: Option<usize>,
370        window_size_right: Option<usize>,
371        softcap: Option<f32>,
372    },
373    /// SelectiveScan — Mamba-1's selective state-space scan
374    /// (forward only). Five inputs:
375    /// - `u`:     `[batch, seqlen, dim]` — input sequence.
376    /// - `delta`: `[batch, seqlen, dim]` — per-step state-update rate.
377    /// - `a`:     `[dim, dstate]` — recurrence matrix log.
378    /// - `b`:     `[batch, seqlen, dstate]` — selective input matrix.
379    /// - `c`:     `[batch, seqlen, dstate]` — selective output matrix.
380    ///
381    /// Output: `y: [batch, seqlen, dim]` — the scanned sequence.
382    ///
383    /// `delta_softplus` toggles the standard softplus(delta)
384    /// activation before use (matches baracuda's `selective_scan_*_run`
385    /// flag). The optional inputs (d_skip, z, delta_bias) from the
386    /// full Mamba algorithm are NOT exposed in v1 — they're
387    /// mechanical extensions when a consumer needs them.
388    ///
389    /// Multi-output Option C (item 3, 2026-06-01): the op now always
390    /// produces a bundled output with two slots — slot 0 `y` (the
391    /// scanned sequence) and slot 1 `last_state` (the final
392    /// h-state). Consumers project via `Op::View` / `Op::ViewOwned`.
393    /// The earlier `return_state: bool` flag retired here.
394    SelectiveScan { delta_softplus: bool },
395    /// CausalConv1d — depthwise 1-D convolution with causal masking
396    /// (left-pad-only) + optional fused SiLU. Three inputs:
397    /// - `x`: `[batch, channels, seq + (kernel - 1)]` — caller pre-pads
398    ///   with `kernel - 1` zeros on the left for the causal mask.
399    /// - `weight`: `[channels, 1, kernel]` — depthwise, one filter per
400    ///   channel (groups == channels in conv terminology).
401    /// - `bias`: `[channels]`.
402    ///
403    /// Output: `[batch, channels, seq]`, same dtype as inputs.
404    ///
405    /// Designed to mirror baracuda's `causal_conv1d_*_run` signature
406    /// (which already carries a `use_silu` flag) and the Mamba-1 /
407    /// Mamba-2 prefill convolution. See
408    /// [[match-external-convention-for-well-known-ops]] for the
409    /// "match baracuda's contract exactly" reasoning.
410    CausalConv1d { use_silu: bool },
411    /// FusedSoftmaxCrossEntropy — fused softmax + negative log-likelihood
412    /// over class-indexed targets, the standard PyTorch / Liger-Kernel
413    /// training-time loss. Two inputs:
414    /// - `logits: [..., V]` (F32) — pre-computed unnormalized class scores
415    /// - `targets: [...]` (I64) — class indices, matching the rest of
416    ///   PyTorch / baracuda CE convention (see
417    ///   [[match-external-convention-for-well-known-ops]])
418    ///
419    /// Output is F32 regardless of input dtype (loss values are
420    /// accumulated in F32 for stability):
421    /// - `Reduction::Mean` / `Reduction::Sum` → scalar `[]`
422    /// - `Reduction::None` → same shape as `targets` (`[...]`)
423    ///
424    /// `ignore_index` rows are dropped from the loss accumulator and
425    /// from the Mean denominator. The conventional sentinel is `-100`.
426    FusedSoftmaxCrossEntropy {
427        reduction: Reduction,
428        ignore_index: i64,
429    },
430    /// A **runtime-registered** fused op (JIT-synthesized or import-time). The
431    /// op's identity is the runtime [`FusedOpId`] in `Op::Fused`; its recipe is
432    /// the region in the `runtime_fused` sidecar. This variant carries only the
433    /// extracted scalar args (the `extract:` slots, in slot order) — a
434    /// parameterless runtime op carries `scalars: []`. See
435    /// `docs/specs/runtime-fused-op-registration.md`.
436    Runtime { scalars: Vec<f64> },
437}
438
439/// Reduction mode for losses with per-sample outputs. Matches PyTorch's
440/// `reduction` parameter shape (`'mean' | 'sum' | 'none'`).
441#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
442pub enum Reduction {
443    /// Sum the per-sample losses and divide by the count of contributing
444    /// samples (rows not masked by `ignore_index`). Standard training-time
445    /// scalar.
446    Mean,
447    /// Sum the per-sample losses without dividing.
448    Sum,
449    /// No reduction — return the per-sample losses with `targets.shape`.
450    None,
451}
452
453impl Reduction {
454    /// Stable per-variant key for hashable encodings (`FusedOpParams::key`
455    /// and the kernel-side `OpParams` payload). The variant tag space is
456    /// local to whichever enum carries this discriminant.
457    pub(crate) fn key(self) -> i64 {
458        match self {
459            Reduction::Mean => 0,
460            Reduction::Sum => 1,
461            Reduction::None => 2,
462        }
463    }
464}
465
466/// Hashable key for [`FusedOpParams`]. Used by `op_key`/CSE so that two
467/// `Op::Fused(id, params)` nodes with identical params dedupe.
468///
469/// The encoding is variant-tag + payload as a `Vec<u64>` (bit patterns
470/// for floats, repr for ints/usize). Mirrors the existing
471/// [`crate::opt`]-style `OpKey` encoding so future extensions slot in
472/// without rebuilding the CSE map.
473#[derive(Debug, Clone, PartialEq, Eq, Hash)]
474pub struct FusedOpParamsKey {
475    pub tag: u16,
476    pub bits: Vec<u64>,
477    pub ints: Vec<i64>,
478}
479
480impl FusedOpParams {
481    /// Hashable encoding. Step 4 adds variants per-fused-op as each
482    /// migrates; the tag uniquely identifies the variant and the
483    /// bits/ints slots carry any payload (none for parameterless ops
484    /// like SoftmaxLastDim and FusedLinear).
485    pub fn key(&self) -> FusedOpParamsKey {
486        match self {
487            FusedOpParams::SoftmaxLastDim => FusedOpParamsKey {
488                tag: 1,
489                bits: Vec::new(),
490                ints: Vec::new(),
491            },
492            FusedOpParams::FusedLinear => FusedOpParamsKey {
493                tag: 2,
494                bits: Vec::new(),
495                ints: Vec::new(),
496            },
497            FusedOpParams::RmsNormLastDim { eps } => FusedOpParamsKey {
498                tag: 3,
499                // Encode eps as its raw bit pattern so CSE on two
500                // RmsNormLastDim nodes with the same eps dedupes
501                // (and two with different eps don't).
502                bits: vec![eps.to_bits()],
503                ints: Vec::new(),
504            },
505            FusedOpParams::LayerNormLastDim { eps } => FusedOpParamsKey {
506                tag: 4,
507                bits: vec![eps.to_bits()],
508                ints: Vec::new(),
509            },
510            FusedOpParams::Rope => FusedOpParamsKey {
511                tag: 5,
512                bits: Vec::new(),
513                ints: Vec::new(),
514            },
515            FusedOpParams::Conv2D {
516                stride,
517                padding,
518                groups,
519            } => FusedOpParamsKey {
520                tag: 6,
521                bits: Vec::new(),
522                // Stride.{0,1}, padding.{0,1}, groups. Five i64 slots
523                // — enough that two Conv2D nodes with different
524                // strides or paddings hash to distinct CSE keys.
525                ints: vec![
526                    stride.0 as i64,
527                    stride.1 as i64,
528                    padding.0 as i64,
529                    padding.1 as i64,
530                    *groups as i64,
531                ],
532            },
533            FusedOpParams::SoftmaxLastDimBackward => FusedOpParamsKey {
534                tag: 7,
535                bits: Vec::new(),
536                ints: Vec::new(),
537            },
538            FusedOpParams::LayerNormLastDimBackward { eps } => FusedOpParamsKey {
539                tag: 8,
540                bits: vec![eps.to_bits()],
541                ints: Vec::new(),
542            },
543            FusedOpParams::RmsNormLastDimBackward { eps } => FusedOpParamsKey {
544                tag: 9,
545                bits: vec![eps.to_bits()],
546                ints: Vec::new(),
547            },
548            FusedOpParams::ReduceMaxToBackward => FusedOpParamsKey {
549                tag: 10,
550                bits: Vec::new(),
551                ints: Vec::new(),
552            },
553            FusedOpParams::ConvTranspose2D {
554                stride,
555                padding,
556                output_padding,
557                dilation,
558                groups,
559            } => FusedOpParamsKey {
560                tag: 11,
561                bits: Vec::new(),
562                // 9 i64 slots: stride.{0,1}, padding.{0,1},
563                // output_padding.{0,1}, dilation.{0,1}, groups.
564                ints: vec![
565                    stride.0 as i64,
566                    stride.1 as i64,
567                    padding.0 as i64,
568                    padding.1 as i64,
569                    output_padding.0 as i64,
570                    output_padding.1 as i64,
571                    dilation.0 as i64,
572                    dilation.1 as i64,
573                    *groups as i64,
574                ],
575            },
576            FusedOpParams::FlashAttn {
577                softmax_scale,
578                causal,
579                window_size_left,
580                window_size_right,
581                softcap,
582                k_len,
583            } => {
584                // Encode the optional dynamic k_len as (tag, value) so
585                // two flash nodes whose attended-length symbol differs
586                // are NOT CSE-merged. None → (0,0); Concrete(v) → (1,v);
587                // Sym(s) → (2, s.0).
588                let (k_tag, k_val): (i64, i64) = match k_len {
589                    None => (0, 0),
590                    Some(DynScalar::Concrete(v)) => (1, *v as i64),
591                    Some(DynScalar::Sym(s)) => (2, s.0 as i64),
592                };
593                FusedOpParamsKey {
594                    tag: 12,
595                    // softmax_scale f32 → u64 bit pattern; softcap
596                    // f32 → u64 bit pattern (NaN sentinel for None so
597                    // two FlashAttn nodes with no softcap still hash
598                    // equal).
599                    bits: vec![
600                        softmax_scale.to_bits() as u64,
601                        softcap.map(|s| s.to_bits() as u64).unwrap_or(u64::MAX),
602                    ],
603                    // causal as i64; window sizes carry MIN as the
604                    // "None" sentinel so a real Some(0) still distinguishes.
605                    ints: vec![
606                        if *causal { 1 } else { 0 },
607                        window_size_left.map(|w| w as i64).unwrap_or(i64::MIN),
608                        window_size_right.map(|w| w as i64).unwrap_or(i64::MIN),
609                        k_tag,
610                        k_val,
611                    ],
612                }
613            }
614            FusedOpParams::PagedAttn {
615                softmax_scale,
616                block_size,
617                softcap,
618            } => FusedOpParamsKey {
619                tag: 13,
620                bits: vec![
621                    softmax_scale.to_bits() as u64,
622                    softcap.map(|s| s.to_bits() as u64).unwrap_or(u64::MAX),
623                ],
624                ints: vec![*block_size as i64],
625            },
626            FusedOpParams::QMatMul { quant_type, k, n } => FusedOpParamsKey {
627                tag: 14,
628                bits: Vec::new(),
629                // QuantType encoded as stable per-variant i64; k, n
630                // as usize.
631                ints: vec![quant_type_key(*quant_type), *k as i64, *n as i64],
632            },
633            FusedOpParams::PowIBackward { exp } => FusedOpParamsKey {
634                tag: 15,
635                bits: Vec::new(),
636                ints: vec![*exp as i64],
637            },
638            FusedOpParams::InplaceAffine { mul, add } => FusedOpParamsKey {
639                tag: 16,
640                bits: vec![mul.to_bits(), add.to_bits()],
641                ints: Vec::new(),
642            },
643            FusedOpParams::FusedSoftmaxCrossEntropy {
644                reduction,
645                ignore_index,
646            } => FusedOpParamsKey {
647                tag: 17,
648                bits: Vec::new(),
649                ints: vec![reduction.key(), *ignore_index],
650            },
651            FusedOpParams::CausalConv1d { use_silu } => FusedOpParamsKey {
652                tag: 18,
653                bits: Vec::new(),
654                ints: vec![*use_silu as i64],
655            },
656            FusedOpParams::SelectiveScan { delta_softplus } => FusedOpParamsKey {
657                tag: 19,
658                bits: Vec::new(),
659                ints: vec![*delta_softplus as i64],
660            },
661            FusedOpParams::SsdChunkScan { chunk_size } => FusedOpParamsKey {
662                tag: 20,
663                bits: Vec::new(),
664                ints: vec![*chunk_size as i64],
665            },
666            FusedOpParams::Nf4Matmul { block_size } => FusedOpParamsKey {
667                tag: 21,
668                bits: Vec::new(),
669                ints: vec![*block_size as i64],
670            },
671            FusedOpParams::AwqMatmul {
672                group_size,
673                split_k_iters,
674            } => FusedOpParamsKey {
675                tag: 23,
676                bits: Vec::new(),
677                ints: vec![*group_size as i64, *split_k_iters as i64],
678            },
679            FusedOpParams::RowScaledMatMul => FusedOpParamsKey {
680                tag: 24,
681                bits: Vec::new(),
682                ints: Vec::new(),
683            },
684            FusedOpParams::TopKLastDim { k } => FusedOpParamsKey {
685                tag: 25,
686                bits: Vec::new(),
687                ints: vec![*k as i64],
688            },
689            FusedOpParams::MatMulTopK { k } => FusedOpParamsKey {
690                tag: 26,
691                bits: Vec::new(),
692                ints: vec![*k as i64],
693            },
694            FusedOpParams::FlashAttnBackward {
695                softmax_scale,
696                causal,
697                window_size_left,
698                window_size_right,
699                softcap,
700            } => FusedOpParamsKey {
701                // Distinct tag from forward FlashAttn (12) so the
702                // forward and backward nodes can't collide in CSE.
703                tag: 22,
704                bits: vec![
705                    softmax_scale.to_bits() as u64,
706                    softcap.map(|s| s.to_bits() as u64).unwrap_or(u64::MAX),
707                ],
708                ints: vec![
709                    if *causal { 1 } else { 0 },
710                    window_size_left.map(|w| w as i64).unwrap_or(i64::MIN),
711                    window_size_right.map(|w| w as i64).unwrap_or(i64::MIN),
712                ],
713            },
714            // Runtime-registered fused ops share one tag (0xF000); the runtime
715            // FusedOpId in `Op::Fused` disambiguates distinct ops, and the
716            // scalar bits disambiguate instances of the same op.
717            FusedOpParams::Runtime { scalars } => FusedOpParamsKey {
718                tag: 0xF000,
719                bits: scalars.iter().map(|s| s.to_bits()).collect(),
720                ints: Vec::new(),
721            },
722        }
723    }
724}
725
726/// Stable per-variant key for [`crate::QuantType`]. Used by
727/// [`FusedOpParams::key`] so CSE on two `Op::Fused(QMATMUL, _)`
728/// nodes with the same `(quant_type, k, n)` collapses correctly.
729fn quant_type_key(q: crate::QuantType) -> i64 {
730    use crate::QuantType::*;
731    match q {
732        Q4_0 => 1,
733        Q4_1 => 2,
734        Q5_0 => 3,
735        Q5_1 => 4,
736        Q8_0 => 5,
737        Q8_1 => 6,
738        Q2K => 7,
739        Q3K => 8,
740        Q4_K_M => 9,
741        Q5K => 10,
742        Q6K => 11,
743        Iq4Nl => 12,
744        Iq4Xs => 13,
745        Iq3S => 14,
746    }
747}
748
749/// What kind of backward this fused op has.
750///
751/// - `Fused(id)` — emit a fused-backward op with the given id. Used by
752///   ops whose backward is awkward to express as a primitive
753///   decomposition (e.g. SoftmaxLastDimBackward's fused subtract-and-
754///   project formula).
755/// - `Decompose` — autograd derives the backward from the primitive
756///   decomposition (lower the fused node, then run autograd over the
757///   primitives).
758/// - `NotDifferentiable` — backward returns Err / panics cleanly.
759///   Matches today's QMatMul / ArgMaxDim treatment.
760#[derive(Copy, Clone, Debug, PartialEq, Eq)]
761pub enum BackwardKind {
762    Fused(FusedOpId),
763    Decompose,
764    NotDifferentiable,
765}
766
767/// Canonical primitive-subgraph pattern that a fused op represents.
768/// Used by fusion rules.
769///
770/// Two reasonable shapes; the registry supports both:
771/// - `Callable` — a closure-style matcher, mirrors PR 3's
772///   `canonical_softmax_pattern`. Maximally flexible (consumer-count
773///   guards, cross-checks); less analyzable.
774/// - `Declarative` — a recursive `PatternTree` that the rule engine
775///   compiles to a matcher. More analyzable; auto-generation from the
776///   registry entry is straightforward.
777///
778/// Step 3 ports SoftmaxLastDim's existing matcher to `Callable`. The
779/// declarative form (see Q1 in `docs/fused-op-registry.md`) is wired up
780/// in step 4 once a second op exercises the abstraction.
781#[expect(
782    clippy::large_enum_variant,
783    reason = "matcher pattern enum; boxing the large variant is deferred to the same follow-up as PatternNode (docs/gaps.md GAP-215) -- a cross-cutting change to construction/match sites, not a lint-commit change"
784)]
785pub enum SubgraphPattern {
786    Declarative(PatternTree),
787    Callable(fn(&Graph, NodeId) -> Option<PatternMatch>),
788}
789
790/// A declarative subgraph pattern: the §3 grammar root plus the
791/// [`FusedOpParams`] to stamp on the matched fused node. The rule engine
792/// ([`crate::opt::FusionRule`] / `PatternKind::Declarative`) walks `root`
793/// against the graph (via [`crate::jit::match_region`]) and emits
794/// `Op::Fused(id, params)`.
795#[derive(Debug, Clone)]
796pub struct PatternTree {
797    /// The region/pattern root (the subgraph SINK, fkc-fusion-patterns §3a.1).
798    pub root: crate::jit::PatternNode,
799    /// The per-instance params stamped on the emitted fused node. A
800    /// parameterless declarative op carries its unit variant; scalar-param ops
801    /// recover their payload via the `extract:` layer (a follow-up) — for now
802    /// the template lives here.
803    pub params: FusedOpParams,
804}
805
806/// Result of a successful pattern match. Carries the bindings — the
807/// concrete `NodeId`s that the pattern's variables matched against in
808/// the host graph — plus the [`FusedOpParams`] payload the fusion rule
809/// should stamp onto the emitted `Op::Fused(id, params)` node.
810///
811/// `bindings` is index-keyed: bindings sorted by index become the
812/// fused-op node's input list (`inputs[0]` ← index 0, `inputs[1]` ←
813/// index 1, …). SoftmaxLastDim's match has one binding `(0, x_id)`
814/// and so emits a single-input node; FusedLinear (3 inputs:
815/// `[a, b, bias]`) emits three bindings indexed 0–2.
816///
817/// `params` is the matcher's authority on the resulting fused-op's
818/// per-instance parameters. The matcher knows what variant of
819/// [`FusedOpParams`] it's recognizing; carrying that decision in the
820/// match result keeps `crate::opt::FusionRule::rewrite` generic
821/// across all registered fused ops.
822#[derive(Debug, Clone)]
823pub struct PatternMatch {
824    /// Variable-id → resolved NodeId. The fusion rule sorts by index
825    /// and uses the resolved ids in order as the emitted node's inputs.
826    pub bindings: Vec<(usize, NodeId)>,
827    /// Per-instance parameters the matcher stamps onto the fused-op
828    /// node it produces. Parameterless ops (SoftmaxLastDim, FusedLinear)
829    /// stamp their unit variant; parameterized ops (RmsNormLastDim,
830    /// FlashAttn) recover their payload from the matched subgraph.
831    pub params: FusedOpParams,
832}
833
834/// The metadata-side registry. Built at process startup, frozen
835/// thereafter (architecture v1.0: no runtime extensibility). Lookups
836/// are by [`FusedOpId`] (O(1)) or by name.
837#[derive(Default)]
838pub struct FusedOpRegistry {
839    entries: Vec<FusedOpEntry>,
840    by_name: HashMap<&'static str, FusedOpId>,
841}
842
843impl FusedOpRegistry {
844    /// Empty registry. Step 3 builds one with `with_entry(...)` calls.
845    pub fn new() -> Self {
846        Self::default()
847    }
848
849    /// Register an entry. Returns self for builder-style chaining.
850    /// Idempotent on (id, name); a duplicate id is a programming bug
851    /// (asserts in debug builds, last-writer-wins in release).
852    ///
853    /// Pattern-hash indexing is reserved for step 4's declarative
854    /// pattern engine; the `Declarative` arm wires into it then.
855    pub fn with_entry(mut self, entry: FusedOpEntry) -> Self {
856        debug_assert!(
857            !self.by_name.contains_key(entry.name),
858            "FusedOpRegistry: duplicate entry name {:?}",
859            entry.name
860        );
861        debug_assert!(
862            entry.id.0 as usize == self.entries.len() + 1 || self.entry(entry.id).is_none(),
863            "FusedOpRegistry: id {:?} already populated",
864            entry.id
865        );
866        self.by_name.insert(entry.name, entry.id);
867        // Grow `entries` so direct id-indexing works. Slot 0 stays
868        // reserved (FusedOpId::UNASSIGNED).
869        let slot = entry.id.0 as usize;
870        if self.entries.len() <= slot {
871            self.entries.reserve(slot + 1 - self.entries.len());
872            // Step 1 doesn't need to fill placeholder slots — production
873            // paths register every id starting from 1 contiguously, so
874            // the Vec stays dense. If a gap arises, the lookup helper
875            // returns `None` for missing ids.
876        }
877        // Insert at the matching index when contiguous; otherwise
878        // append. Step 3's first registration is FusedOpId(1), so the
879        // simple append-with-slot-0-empty path is what we'll exercise.
880        if self.entries.is_empty() {
881            // Reserve slot 0 with a unit placeholder. Direct indexing is
882            // the hot path; we accept one wasted slot.
883            self.entries.push(placeholder_entry());
884        }
885        if slot < self.entries.len() {
886            self.entries[slot] = entry;
887        } else {
888            // Pad if necessary, then push.
889            while self.entries.len() < slot {
890                self.entries.push(placeholder_entry());
891            }
892            self.entries.push(entry);
893        }
894        self
895    }
896
897    /// Look up an entry by id. Returns `None` for `FusedOpId::UNASSIGNED`
898    /// or any unregistered id.
899    pub fn entry(&self, id: FusedOpId) -> Option<&FusedOpEntry> {
900        let slot = id.0 as usize;
901        if slot == 0 || slot >= self.entries.len() {
902            return None;
903        }
904        let e = &self.entries[slot];
905        if e.id == FusedOpId::UNASSIGNED {
906            None
907        } else {
908            Some(e)
909        }
910    }
911
912    /// Look up an entry by name. Returns the [`FusedOpId`] when present.
913    pub fn id_for_name(&self, name: &str) -> Option<FusedOpId> {
914        self.by_name.get(name).copied()
915    }
916
917    /// Iterate over every registered (non-placeholder) entry. Used by
918    /// [`crate::opt::RuleRegistry::default_rules`] to auto-generate
919    /// one [`crate::opt::LoweringRule`] + [`crate::opt::FusionRule`]
920    /// pair per fused op without naming each entry by hand.
921    pub fn entries_iter(&self) -> impl Iterator<Item = &FusedOpEntry> {
922        self.entries
923            .iter()
924            .filter(|e| e.id != FusedOpId::UNASSIGNED)
925    }
926
927    /// Number of registered (non-placeholder) entries.
928    pub fn len(&self) -> usize {
929        self.entries
930            .iter()
931            .filter(|e| e.id != FusedOpId::UNASSIGNED)
932            .count()
933    }
934
935    /// Whether the registry has any registered entries.
936    pub fn is_empty(&self) -> bool {
937        self.len() == 0
938    }
939}
940
941/// Hash of a primitive-subgraph pattern. Reserved for step 4's
942/// declarative pattern engine; the hashing function is filled in alongside
943/// `PatternTree`. (The static catalog's `by_pattern_hash` index placeholder
944/// was removed unread; re-add it with that engine.)
945#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
946pub struct PatternHash(pub u64);
947
948/// Internal placeholder used to keep id-indexed `entries` dense. Never
949/// Decompose the fused node `id` by re-emitting a **data recipe** — the
950/// static-registry bridge onto the one region re-emitter (Increment C
951/// slice 1, T5 / design D6). A migrated entry's `decompose` body becomes:
952///
953/// ```ignore
954/// fn recipe() -> &'static PatternNode              // OnceLock-built data
955/// fn scalars(params: &FusedOpParams) -> Option<Vec<f64>>  // per-entry projection
956/// pub fn decompose(g, id, params) -> NodeId {
957///     decompose_via_recipe(g, id, recipe(), scalars(params))
958/// }
959/// ```
960///
961/// The fused node's `inputs` are the recipe's binds (in bind-index order);
962/// `scalars` fill the recipe's open scalar slots in pattern pre-order (the
963/// per-entry projection maps the params payload — e.g. an `eps` — onto
964/// them). The `FusedOpEntry.decompose` surface is UNCHANGED — imperative
965/// bodies remain legal for param-conditional ops.
966///
967/// **Totality (G2, the recipe principle):** ANY failure returns `id` — the
968/// fused node stays in place as a surfaced opaque-op gap (the lowering
969/// driver records no progress), NEVER a panic:
970/// * `scalars == None` — a wrong params payload for this entry;
971/// * a recipe that fails `crate::runtime_fused::validate_recipe` — a
972///   semantics-absent op token with no primitive re-emission (the
973///   flip-withdrawal posture: unknown/non-registry tokens are surfaced
974///   honest-miss declines, never accepted), non-contiguous binds, a
975///   matcher-only node, or structurally-unresolvable rel attrs;
976/// * a bind-count / node-input arity mismatch;
977/// * a scalar-slot count mismatch;
978/// * a shape-relative resolution decline at THESE input shapes (symbolic
979///   extent, negative result, …);
980/// * anything else — a `catch_unwind` last-resort guard converts an
981///   unanticipated panic into the same fixpoint.
982///
983/// The first four decline BEFORE any emission (no partial nodes). An
984/// emit-time decline can leave already-pushed child nodes behind as
985/// unreferenced dead nodes — inert, the documented push-only-graph posture.
986/// Declines are telemetered on stderr (the surfaced-gap channel until a
987/// structured gap inventory exists).
988/// **A fused node's recipe as portable data — the generic accessor the JIT seam
989/// needs.** Returns the same [`PatternNode`] the op's `decompose` lowers,
990/// *without touching the graph*.
991///
992/// `fireline_synth::JitRequest::region` is documented as "the recipe's
993/// `decompose` (the primitive subgraph)", so a synthesizer can be asked to build
994/// one kernel for a region the consumer discovered at runtime. Lowering needs
995/// every primitive bound on the target device; **handing the region over needs
996/// none of them** — which is the whole reason this accessor exists.
997///
998/// Dispatches on the fused op id. `None` means "this op does not expose its
999/// recipe as data (yet)", which is a *surfaced gap*, never a crash — the same
1000/// G2 posture as a `decompose` fixpoint self-return. Adding an op is one arm.
1001///
1002/// Today only [`FusedOps::PAGED_ATTN`] implements it, because it is the op that
1003/// forced the question: no GPU backend implements the fused form at all, so the
1004/// JIT route is the only one that does not depend on every primitive being
1005/// pre-registered.
1006pub fn recipe_for(graph: &Graph, id: NodeId) -> Option<PatternNode> {
1007    let (fused_id, params) = match &graph.node(id).op {
1008        crate::Op::Fused(fid, p) => (*fid, p.clone()),
1009        _ => return None,
1010    };
1011    match fused_id {
1012        FusedOps::PAGED_ATTN => crate::registry::paged_attn::recipe_for(graph, id, &params),
1013        _ => None,
1014    }
1015}
1016
1017pub fn decompose_via_recipe(
1018    graph: &mut Graph,
1019    id: NodeId,
1020    recipe: &PatternNode,
1021    scalars: Option<Vec<f64>>,
1022) -> NodeId {
1023    let Some(scalars) = scalars else {
1024        eprintln!(
1025            "decompose_via_recipe: wrong params payload for node {id:?} — \
1026             typed decline, node stays fused (G2 fixpoint)"
1027        );
1028        return id;
1029    };
1030    if let Err(err) = crate::runtime_fused::validate_recipe(recipe) {
1031        eprintln!(
1032            "decompose_via_recipe: recipe declined for node {id:?}: {err:?} — \
1033             surfaced honest miss, node stays fused (G2 fixpoint)"
1034        );
1035        return id;
1036    }
1037    let inputs = graph.node(id).inputs.clone();
1038    if recipe.bind_indices().len() != inputs.len() {
1039        eprintln!(
1040            "decompose_via_recipe: recipe binds {} != node inputs {} for node {id:?} — \
1041             typed decline, node stays fused (G2 fixpoint)",
1042            recipe.bind_indices().len(),
1043            inputs.len(),
1044        );
1045        return id;
1046    }
1047    if scalars.len() != crate::runtime_fused::count_scalar_slots(recipe) {
1048        eprintln!(
1049            "decompose_via_recipe: {} projected scalars for {} open slots on node {id:?} — \
1050             typed decline, node stays fused (G2 fixpoint)",
1051            scalars.len(),
1052            crate::runtime_fused::count_scalar_slots(recipe),
1053        );
1054        return id;
1055    }
1056    // The resolving emit. A rel-attr decline at these shapes is a
1057    // value-dependent gap (`Err` arm); `catch_unwind` is the never-panic
1058    // last resort for anything validation didn't anticipate (same posture as
1059    // `register_runtime_fused`'s hash guard) — a partial emission left by
1060    // either failure mode is inert dead nodes in the push-only graph.
1061    let emitted = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1062        crate::runtime_fused::try_emit_region(graph, recipe, &inputs, &scalars)
1063    }));
1064    match emitted {
1065        Ok(Ok(root)) => root,
1066        Ok(Err(err)) => {
1067            eprintln!(
1068                "decompose_via_recipe: rel-attr resolution declined for node {id:?}: {err:?} — \
1069                 surfaced gap, node stays fused (G2 fixpoint)"
1070            );
1071            id
1072        }
1073        Err(_) => {
1074            eprintln!(
1075                "decompose_via_recipe: emit panicked for node {id:?} — \
1076                 caught (never-panic last resort), node stays fused (G2 fixpoint)"
1077            );
1078            id
1079        }
1080    }
1081}
1082
1083/// returned by [`FusedOpRegistry::entry`].
1084fn placeholder_entry() -> FusedOpEntry {
1085    FusedOpEntry {
1086        destructive_input: None,
1087        id: FusedOpId::UNASSIGNED,
1088        name: "<unassigned>",
1089        family: FusedOpFamily::Forward,
1090        pattern: SubgraphPattern::Callable(|_g, _id| None),
1091        decompose: |_g, id, _p| id,
1092        backward: BackwardKind::NotDifferentiable,
1093        shape_rule: |_shapes, _params| Shape::from_dims(&[]),
1094        dtype_rule: |_dtypes, _params| DType::F32,
1095        output_views: None,
1096    }
1097}
1098
1099/// Associated constants for the well-known fused-op ids. Rule code
1100/// matches `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)` — almost as
1101/// ergonomic as today's `Op::SoftmaxLastDim`. Steps 3-4 fill these in
1102/// as each fused op migrates to the registry.
1103pub struct FusedOps;
1104
1105impl FusedOps {
1106    /// SoftmaxLastDim — proof-of-concept migration target (step 3).
1107    pub const SOFTMAX_LAST_DIM: FusedOpId = FusedOpId(1);
1108    /// FusedLinear — first multi-input fused op migrated to the
1109    /// registry (step 4). Three inputs `[a, b, bias]`, output
1110    /// `(a @ b) + bias`. The CUTLASS bias-epilogue integration in the
1111    /// baracuda-cutlass alpha.13 plan registers here.
1112    pub const FUSED_LINEAR: FusedOpId = FusedOpId(2);
1113    /// RmsNormLastDim — `x / sqrt(mean(x²) + eps)` along the last dim.
1114    /// Migrated in step 4 (continued). Single input + eps param.
1115    pub const RMS_NORM_LAST_DIM: FusedOpId = FusedOpId(3);
1116    /// LayerNormLastDim — `(x - mean) / sqrt(var + eps)` along the
1117    /// last dim (no affine). Single input + eps param.
1118    pub const LAYER_NORM_LAST_DIM: FusedOpId = FusedOpId(4);
1119    /// Rope — rotary position embedding with caller-supplied cos/sin
1120    /// tables. Three inputs `[x, cos, sin]`, parameterless (the seq/
1121    /// head_dim shape parameters live in the input shapes).
1122    pub const ROPE: FusedOpId = FusedOpId(5);
1123    /// Conv2D — 2-D cross-correlation. Two or three inputs `[x,
1124    /// weight]` or `[x, weight, bias]`; carries stride / padding /
1125    /// groups in [`FusedOpParams::Conv2D`].
1126    pub const CONV2D: FusedOpId = FusedOpId(6);
1127    /// SoftmaxLastDimBackward — fused backward helper for the
1128    /// SoftmaxLastDim forward. Two inputs `[y, upstream]`,
1129    /// parameterless. Wired through `BackwardKind::Fused` from
1130    /// `SOFTMAX_LAST_DIM`'s entry.
1131    pub const SOFTMAX_LAST_DIM_BACKWARD: FusedOpId = FusedOpId(7);
1132    /// LayerNormLastDimBackward — fused backward helper for the
1133    /// LayerNormLastDim forward. Two inputs `[x, upstream]` + eps.
1134    pub const LAYER_NORM_LAST_DIM_BACKWARD: FusedOpId = FusedOpId(8);
1135    /// RmsNormLastDimBackward — fused backward helper for the
1136    /// RmsNormLastDim forward. Two inputs `[x, upstream]` + eps.
1137    pub const RMS_NORM_LAST_DIM_BACKWARD: FusedOpId = FusedOpId(9);
1138    /// ReduceMaxToBackward — fused backward helper for the
1139    /// `Op::ReduceMaxTo` primitive (routes upstream to argmax
1140    /// positions, fair-share on ties). Two inputs `[x, upstream]`,
1141    /// parameterless. Note this is the backward of a *primitive*
1142    /// (`Op::ReduceMaxTo`), not of a fused forward — there's no
1143    /// `BackwardKind::Fused` edge wired to this helper, autograd
1144    /// reaches it directly from `Op::ReduceMaxTo`'s arm.
1145    pub const REDUCE_MAX_TO_BACKWARD: FusedOpId = FusedOpId(10);
1146    /// ConvTranspose2D — fractionally-strided 2-D convolution.
1147    /// Two inputs `[x, weight]` (no bias); carries
1148    /// stride/padding/output_padding/dilation/groups in
1149    /// [`FusedOpParams::ConvTranspose2D`].
1150    pub const CONV_TRANSPOSE2D: FusedOpId = FusedOpId(11);
1151    /// FlashAttn — multi-head attention with FlashAttention-shaped
1152    /// kernel hooks. 4-5 inputs (q, k, v, optional alibi).
1153    pub const FLASH_ATTN: FusedOpId = FusedOpId(12);
1154    /// PagedAttn — paged-cache attention. 5-6 inputs.
1155    pub const PAGED_ATTN: FusedOpId = FusedOpId(13);
1156    /// QMatMul — quantized matmul `C = A @ dequant(W_Q)`. Two
1157    /// inputs `[a, w_q_bytes]`.
1158    pub const QMATMUL: FusedOpId = FusedOpId(14);
1159    /// PowIBackward — fused backward helper for `Op::PowI(n)`.
1160    /// `grad_x = n · x^(n-1) · upstream`. Two inputs `[x, upstream]`,
1161    /// carries `exp: i32` in [`FusedOpParams::PowIBackward`]. Replaces
1162    /// the autograd primitive decomposition (PowI(n-1) → MulScalar →
1163    /// Mul, 3 nodes) with a single launch of baracuda alpha.31's
1164    /// `unary_powi_backward_*` kernel. Note this is the backward of a
1165    /// primitive (`Op::PowI`), not of a fused forward — autograd
1166    /// reaches it directly from `Op::PowI`'s arm rather than via a
1167    /// `BackwardKind::Fused` edge.
1168    pub const POWI_BACKWARD: FusedOpId = FusedOpId(15);
1169
1170    /// In-place affine: `x = mul·x + add`. Single input (the mutated
1171    /// tensor), single launch into baracuda's `affine_inplace_*`
1172    /// symbol on CUDA. Carries `mul: f64, add: f64` in
1173    /// [`FusedOpParams::InplaceAffine`]. Marked destructive on input
1174    /// 0 via `Op::destructive_input`, so `opt::derive_ordering` pins
1175    /// it to run after every non-destructive reader. Phase 1 of the
1176    /// in-place ops infrastructure
1177    /// (`docs/session-prompts/in-place-ops-infrastructure.md`);
1178    /// dispatch + autograd integration deferred to Phases 3 + 4.
1179    pub const INPLACE_AFFINE: FusedOpId = FusedOpId(16);
1180
1181    /// FusedSoftmaxCrossEntropy — fused softmax + NLL over class-indexed
1182    /// targets. Two inputs `[logits, targets]`; carries
1183    /// `{ reduction, ignore_index }` in
1184    /// [`FusedOpParams::FusedSoftmaxCrossEntropy`]. The forward kernel
1185    /// avoids materializing the `[..., V]` softmax/log-softmax
1186    /// intermediates that the primitive composition does (`fuel-core::
1187    /// train::cross_entropy_with_logits`). Backward via Decompose runs
1188    /// the primitive chain; the in-place Liger-style fused backward is a
1189    /// later session (needs in-place mutation infrastructure).
1190    pub const FUSED_SOFTMAX_CROSS_ENTROPY: FusedOpId = FusedOpId(17);
1191
1192    /// CausalConv1d — depthwise 1-D convolution + causal masking +
1193    /// optional fused SiLU. Three inputs `[x, weight, bias]` where
1194    /// `x: [batch, channels, seq + kernel - 1]`,
1195    /// `weight: [channels, 1, kernel]`, `bias: [channels]`. Carries
1196    /// `use_silu: bool` in [`FusedOpParams::CausalConv1d`]. The forward
1197    /// kernel matches baracuda's `causal_conv1d_*_run` contract.
1198    /// `BackwardKind::NotDifferentiable` for v1 (Mamba inference path
1199    /// today is inference-only).
1200    pub const CAUSAL_CONV1D: FusedOpId = FusedOpId(18);
1201
1202    /// SelectiveScan — Mamba-1's selective state-space scan
1203    /// (forward only). Five inputs `[u, delta, a, b, c]`; one output
1204    /// `y: [batch, seqlen, dim]`. Carries `delta_softplus: bool` in
1205    /// [`FusedOpParams::SelectiveScan`]. v1 drops the optional
1206    /// inputs (d_skip, z, delta_bias) and the `last_state` second
1207    /// output — both are mechanical follow-ups when a consumer needs
1208    /// them. `BackwardKind::NotDifferentiable` for v1.
1209    pub const SELECTIVE_SCAN: FusedOpId = FusedOpId(19);
1210
1211    /// SsdChunkScan — Mamba-2's State-Space Duality chunked scan
1212    /// (forward only). Five inputs `[x, dt, a, b, c]`; one output
1213    /// `y: [batch, seqlen, heads, head_dim]`. Carries
1214    /// `chunk_size: usize` in [`FusedOpParams::SsdChunkScan`]
1215    /// (parallelism granularity for the GPU path; the CPU kernel
1216    /// runs sequential and any positive `chunk_size` dividing
1217    /// `seqlen` produces the same mathematical answer).
1218    /// `BackwardKind::NotDifferentiable` for v1.
1219    pub const SSD_CHUNK_SCAN: FusedOpId = FusedOpId(20);
1220
1221    /// Nf4Matmul — bitsandbytes-style 4-bit NormalFloat quantized
1222    /// matrix multiply. Three inputs `[activations, w_packed, absmax]`
1223    /// where `w_packed: [N, K/2] U8` and `absmax: [N, K/block_size] F32`.
1224    /// Output `[..., M, N]` matching activations' dtype (F32/F16/BF16
1225    /// in v1). Carries `block_size: usize` in
1226    /// [`FusedOpParams::Nf4Matmul`]. `BackwardKind::NotDifferentiable`
1227    /// (NF4 weights are frozen; the dequant-then-matmul fallback is
1228    /// the wrong path for the cases NF4 exists to optimize).
1229    pub const NF4_MATMUL: FusedOpId = FusedOpId(21);
1230
1231    /// FlashAttnBackwardQ — produces dQ from `(q, k, v, do, [alibi])`.
1232    /// See [`fuel_ir::dispatch::OpKind::FlashAttnBackwardQ`]. Three
1233    /// separate FusedOp ids (Q/K/V) is the v1 design — a single
1234    /// multi-output op would share the recompute pass across all three
1235    /// gradients but needs multi-output infrastructure that doesn't
1236    /// exist yet. Reuses [`FusedOpParams::FlashAttnBackward`].
1237    pub const FLASH_ATTN_BACKWARD_Q: FusedOpId = FusedOpId(22);
1238    /// FlashAttnBackwardK — produces dK. See [`Self::FLASH_ATTN_BACKWARD_Q`].
1239    pub const FLASH_ATTN_BACKWARD_K: FusedOpId = FusedOpId(23);
1240    /// FlashAttnBackwardV — produces dV. See [`Self::FLASH_ATTN_BACKWARD_Q`].
1241    pub const FLASH_ATTN_BACKWARD_V: FusedOpId = FusedOpId(24);
1242
1243    /// AwqMatmul — AWQ (mit-han-lab) asymmetric int4 weight-only
1244    /// matmul. Four inputs `[activations, weight, zeros, scales]`
1245    /// (one more than NF4's three — AWQ's zero-point is a fourth
1246    /// operand, not baked into the dequant like NF4's codebook) where
1247    /// `weight: [N, K/8] U32`, `zeros: [N, zeros_w] U32`,
1248    /// `scales: [N, 8 * zeros_w] F16` — the baracuda kernel layout.
1249    /// Output `[..., M, N]` matching activations' dtype
1250    /// (F32/F16/BF16 in v1). Carries `{ group_size, split_k_iters }`
1251    /// in [`FusedOpParams::AwqMatmul`]. `BackwardKind::Decompose`
1252    /// (the weight is frozen; the activation gradient flows through
1253    /// the decompose). Unlike NF4 (a non-linear codebook with no
1254    /// primitive spelling), AWQ's affine dequant decomposes cleanly
1255    /// into primitives — see the module doc on
1256    /// [`crate::registry::awq_matmul`] for the recipe.
1257    pub const AWQ_MATMUL: FusedOpId = FusedOpId(25);
1258
1259    /// RowScaledMatMul: `(a @ b) * row_scale` with `row_scale [..batch, M, 1]`
1260    /// (a per-row / per-token scale; ROADMAP row 172 item 1).
1261    pub const ROW_SCALED_MATMUL: FusedOpId = FusedOpId(26);
1262
1263    /// TopKLastDim: the `k` largest values along the last axis and their
1264    /// indices (multi-output; ROADMAP row 172 item 2 step A).
1265    pub const TOP_K_LAST_DIM: FusedOpId = FusedOpId(27);
1266
1267    /// MatMulTopK: `TopKLastDim(a @ b)` as one fused node (the TopK epilogue on
1268    /// the matmul; ROADMAP row 172 item 2 step B).
1269    pub const MATMUL_TOP_K: FusedOpId = FusedOpId(28);
1270}
1271
1272/// Process-wide default registry: the union of every fused op's
1273/// metadata-side entry. Built once on first access via
1274/// [`std::sync::OnceLock`]; immutable thereafter (architecture v1.0:
1275/// no runtime extensibility).
1276///
1277/// Step 3 populates only SoftmaxLastDim; step 4 fills in the other
1278/// 12 fused ops as they migrate.
1279pub fn default_registry() -> &'static FusedOpRegistry {
1280    use std::sync::OnceLock;
1281    static REGISTRY: OnceLock<FusedOpRegistry> = OnceLock::new();
1282    REGISTRY.get_or_init(|| {
1283        FusedOpRegistry::new()
1284            .with_entry(softmax_last_dim::entry())
1285            .with_entry(fused_linear::entry())
1286            .with_entry(rms_norm_last_dim::entry())
1287            .with_entry(layer_norm_last_dim::entry())
1288            .with_entry(rope::entry())
1289            .with_entry(conv2d::entry())
1290            .with_entry(softmax_last_dim_backward::entry())
1291            .with_entry(layer_norm_last_dim_backward::entry())
1292            .with_entry(rms_norm_last_dim_backward::entry())
1293            .with_entry(reduce_max_to_backward::entry())
1294            .with_entry(conv_transpose_2d::entry())
1295            .with_entry(flash_attn::entry())
1296            .with_entry(flash_attn_backward::entry_q())
1297            .with_entry(flash_attn_backward::entry_k())
1298            .with_entry(flash_attn_backward::entry_v())
1299            .with_entry(paged_attn::entry())
1300            .with_entry(qmatmul::entry())
1301            .with_entry(powi_backward::entry())
1302            .with_entry(inplace_affine::entry())
1303            .with_entry(fused_softmax_cross_entropy::entry())
1304            .with_entry(causal_conv1d::entry())
1305            .with_entry(selective_scan::entry())
1306            .with_entry(ssd_chunk_scan::entry())
1307            .with_entry(nf4_matmul::entry())
1308            .with_entry(awq_matmul::entry())
1309            .with_entry(row_scaled_matmul::entry())
1310            .with_entry(top_k_last_dim::entry())
1311            .with_entry(matmul_top_k::entry())
1312    })
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    /// Smoke: id newtype is comparable + hashable.
1320    #[test]
1321    fn fused_op_id_basic() {
1322        let a = FusedOpId(1);
1323        let b = FusedOpId(1);
1324        let c = FusedOpId(2);
1325        assert_eq!(a, b);
1326        assert_ne!(a, c);
1327    }
1328
1329    /// Smoke: empty registry has no entries.
1330    #[test]
1331    fn registry_empty() {
1332        let r = FusedOpRegistry::new();
1333        assert!(r.is_empty());
1334        assert_eq!(r.len(), 0);
1335        assert!(r.entry(FusedOpId(1)).is_none());
1336        assert!(r.entry(FusedOpId::UNASSIGNED).is_none());
1337        assert!(r.id_for_name("anything").is_none());
1338    }
1339
1340    /// Smoke: register one entry, look it up by id and by name.
1341    #[test]
1342    fn registry_register_one() {
1343        fn dummy_decompose(_g: &mut Graph, id: NodeId, _p: &FusedOpParams) -> NodeId {
1344            id
1345        }
1346        fn dummy_pattern(_g: &Graph, _id: NodeId) -> Option<PatternMatch> {
1347            None
1348        }
1349        fn dummy_shape(_s: &[Shape], _p: &FusedOpParams) -> Shape {
1350            Shape::from_dims(&[1])
1351        }
1352        fn dummy_dtype(_d: &[DType], _p: &FusedOpParams) -> DType {
1353            DType::F32
1354        }
1355
1356        let r = FusedOpRegistry::new().with_entry(FusedOpEntry {
1357            destructive_input: None,
1358            id: FusedOps::SOFTMAX_LAST_DIM,
1359            name: "SoftmaxLastDim",
1360            family: FusedOpFamily::Forward,
1361            pattern: SubgraphPattern::Callable(dummy_pattern),
1362            decompose: dummy_decompose,
1363            backward: BackwardKind::NotDifferentiable,
1364            shape_rule: dummy_shape,
1365            dtype_rule: dummy_dtype,
1366            output_views: None,
1367        });
1368
1369        assert_eq!(r.len(), 1);
1370        assert!(!r.is_empty());
1371        let entry = r.entry(FusedOps::SOFTMAX_LAST_DIM).expect("registered");
1372        assert_eq!(entry.name, "SoftmaxLastDim");
1373        assert_eq!(entry.family, FusedOpFamily::Forward);
1374        assert_eq!(
1375            r.id_for_name("SoftmaxLastDim"),
1376            Some(FusedOps::SOFTMAX_LAST_DIM)
1377        );
1378    }
1379
1380    /// FusedOpParams::key produces a stable encoding.
1381    #[test]
1382    fn fused_op_params_key_softmax() {
1383        let k1 = FusedOpParams::SoftmaxLastDim.key();
1384        let k2 = FusedOpParams::SoftmaxLastDim.key();
1385        assert_eq!(k1, k2);
1386        assert_eq!(k1.tag, 1);
1387        assert!(k1.bits.is_empty());
1388        assert!(k1.ints.is_empty());
1389    }
1390}