Skip to main content

rlx_ir/
lib.rs

1// RLX — versatile ML compiler + runtime.
2// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! RLX Tensor IR — the intermediate representation for the RLX ML compiler.
6//!
7//! This IR is:
8//! - **Standalone**: no runtime, no backend, no framework coupling
9//! - **Serializable**: graphs can be saved/loaded for AOT compilation
10//! - **Optimizable**: designed for pattern-matching fusion and buffer planning
11//!
12//! The compiler pipeline has three named levels:
13//!
14//! - **HIR** ([`hir`]) — block-oriented IR for model builders (`Linear`,
15//!   `SwiGLU`, `ResidualRmsNorm`, …).
16//! - **MIR** ([`mir`]) — fused tensor DAG; input to `rlx_opt`.
17//! - **LIR** ([`lir`]) — optimized MIR + arena buffer plan for backends.
18//!
19//! [`Graph`] is the primary DX surface. Use [`Graph::define`] for
20//! fusion-first HIR builders, or [`Graph::new`] / [`GraphModule::mir`]
21//! for primitive MIR. [`GraphModule`] tracks pipeline stage (HIR/MIR/LIR).
22//!
23//! - [`Graph`]: a DAG of tensor operations (like XLA's HloModule)
24//! - [`Node`]: a single operation with typed inputs/outputs
25//! - [`Op`]: the operation kind with parameters
26
27pub mod ad;
28pub mod apple_bnns;
29pub mod async_copy;
30pub mod attention_layout;
31pub mod audio;
32pub mod capability;
33pub mod const_check;
34pub mod dtype;
35pub mod dynamic;
36pub mod env;
37pub mod env_catalog;
38pub mod env_registry;
39pub mod equivalence;
40pub mod fft;
41pub mod gdn;
42pub mod graph;
43pub mod hir;
44pub mod infer;
45pub mod infer_shape;
46pub mod inspect;
47pub mod kernel_schedule;
48pub mod lanes;
49pub mod layout;
50pub mod lir;
51pub mod logical_kernel;
52pub mod lowp_codec;
53pub mod measure;
54pub mod mir;
55pub mod module;
56pub mod numeric_check;
57pub mod nvfp4;
58pub mod op;
59pub mod op_registry;
60pub mod opcodes;
61pub mod ops;
62pub mod perfetto;
63pub mod phase;
64pub mod pretty;
65pub mod provenance;
66pub mod quant;
67pub mod region_encode;
68pub mod repr_check;
69pub mod residual;
70pub mod rng;
71pub mod tensor_inspect;
72pub use nvfp4::{FP4_E2M1_LUT, NVFP4_GROUP_SIZE, fp4_e2m1_to_f32, fp8_e4m3_scale_to_f32};
73pub mod binding_manifest;
74pub mod component;
75pub mod hir_extension;
76pub mod reflect;
77pub mod rf;
78/// One constructible `Op` per `OpKind`, for gates that must cover the whole
79/// op set. Feature `test-support`.
80#[cfg(feature = "test-support")]
81pub mod sample_ops;
82#[cfg(feature = "serialize")]
83pub mod serialize;
84pub mod shape;
85pub mod target;
86pub mod text;
87pub mod variant;
88pub mod verify;
89
90pub use ad::AdPipelineStage;
91pub use async_copy::{AsyncCopy, BarrierToken, DoubleBuffer, SyncCopy};
92pub use attention_layout::{
93    ATTENTION_FLASH_MAX_HEAD_DIM, AttentionGeom, AttentionLaunchStrides,
94    attention_dispatch_use_row, attention_geom, attention_launch_strides, cpu_attention_bshd,
95    cpu_attention_packed_bshd_qkv, detect_packed_bshd_qkv_attention, mask_strides_bhsd,
96    mask_strides_for_shape, packed_bshd_narrow_elidable, packed_bshd_qkv_strides, strides_bhsd,
97    strides_bshd, strides_for_shape,
98};
99pub use capability::{N_KINDS, OpCaps, fused_kinds};
100pub use dtype::{DType, Element, ElementSubtype, scalar_constant_bytes};
101pub use dynamic::sym;
102pub use dynamic::{
103    DimEnv, bind_graph, collect_dynamic_symbols, has_dynamic_dims, infer_bindings_from_f32_inputs,
104    infer_bindings_from_inputs, same_binding, sync_concat_shapes, sync_expand_ops,
105    sync_graph_shapes, sync_narrow_ops, sync_reshape_ops,
106};
107pub use env::{RlxEnv, RuntimeOverrides, flag, is_unset, parse_or, set, unset, var, var_os};
108pub use env_catalog::{EnvVarDoc, format_catalog as format_env_catalog};
109pub use env_registry::{
110    EnvKind, EnvLayer, EnvStability, EnvVarEntry, REGISTRY as ENV_REGISTRY, canonical_name,
111    format_registry_markdown, is_registered, lookup as env_lookup, public_catalog_docs,
112};
113
114/// Public `RLX_*` catalog (`just env-catalog`).
115pub fn env_catalog() -> &'static [EnvVarDoc] {
116    public_catalog_docs()
117}
118
119pub use equivalence::{
120    IgnoreConfig, fingerprint, node_value_key, ops_deep_eq, structural_hash, structurally_eq,
121};
122pub use fft::{FftGpuPlan, FftMeta, FftNorm, fft_meta, fftn_axes_all, normalize_fftn_axes};
123pub use gdn::GdnBackwardLayout;
124pub use graph::{Graph, Node, NodeId};
125pub use hir::{
126    FusionPolicy, HirGraphExt, HirModule, HirMut, HirNode, HirNodeId, HirOp,
127    window_token_gather_bsn, window_token_scatter_bsn,
128};
129pub use infer::GraphExt;
130pub use inspect::{
131    inspect_buffer_plan, inspect_graph, inspect_graph_diff, inspect_hir, inspect_hir_stats,
132    inspect_lir, inspect_mir, inspect_mir_diff, inspect_mir_stats,
133};
134pub use layout::{Coord2, Ragged, ShapeTuple, Strides2, Strides3, Tile2, Tile3};
135pub use lir::{
136    LirBufferPlan, LirBufferSlot, LirFingerprint, LirIoManifest, LirModule, LirViewAlias,
137};
138pub use logical_kernel::{
139    KernelDispatchConfig, KernelDispatchPolicy, LogicalKernelEntry, logical_kinds_in_graph,
140    registered_logical_kernels, should_lower_to_common,
141};
142pub use measure::{CacheBuster, Tick, time_ns};
143pub use mir::{MirModule, MirNode, MirNodeId, MirOp};
144pub use module::{GraphModule, GraphStage};
145pub use numeric_check::{BadValue, DebugMode, DebugScanner, NanReport, check_node, first_bad};
146pub use op::{
147    AdaNormKind, ChainOperand, ChainStep, Op, OpKind, PadMode, RegionPrologue, RopeStyle,
148    ScatterNdReduction, SpdMatFn, SynthBwdWrt, SynthKind, TransformStep,
149};
150pub use op_registry::{
151    CustomOpError, JvpContext, LowerContext, OpExtension, OpRegistry, VjpContext, VmapContext,
152    global_registry, is_op_registered, lookup_op, register_op, register_op_strict,
153};
154pub use ops::attention::attention_kind_op;
155pub use ops::backward::{unpack_ada_layer_norm_backward, unpack_gated_residual_backward};
156pub use ops::dsp::{FirMode, iir_impulse_response};
157pub use phase::{Phase, PhaseSchedule, derive_phases};
158pub use provenance::{NodeOrigin, node_label, stamp_pass_origins};
159/// Alias kept for existing `ENV_CATALOG` imports.
160pub use public_catalog_docs as ENV_CATALOG;
161pub use quant::{QuantMap, QuantScheme, ScaleLayout, ScaledFormat};
162pub use region_encode::{
163    FK_BATCH_SINGLE_KERNEL_MAX, PrologueLaunchGrid, REGION_META_WORDS, REGION_PROLOGUE_NONE,
164    REGION_PROLOGUE_RESIZE_NEAREST_2X_NCHW, RegionNchwDims, batch_region_slice_dst_off_f32,
165    batch_region_slice_elems, batch_region_slice_shape, encode_chain_operand, encode_chain_steps,
166    encode_elementwise_region_meta, encode_prologue_tail, fk_batch_single_kernel_enabled,
167    fk_batch_use_single_launch,
168};
169pub use rng::{
170    BNNS_AES_CTR_STATE_SIZE, BnnsAesCtr128, GUMBEL_UNIFORM_EPS, NativeBnnsGumbelMax, Philox4x32,
171    RngBackend, RngOptions, argmax_f32, bnns_categorical_from_uniform, bnns_entropy_seed,
172    bnns_generator_state_is_fresh, bnns_gumbel_from_uniform, bnns_gumbel01_from_bytes,
173    bnns_seed_from_generator_state, bnns_uniform_f32_from_bytes, bnns_uniform_f32_from_u32,
174    bnns_uniform_int_from_u32, combine_seed, fill_normal_like, fill_uniform_like,
175    gumbel_max_argmax_with, gumbel01_from_uniform, ort_engine_seed,
176};
177#[cfg(feature = "serialize")]
178pub use serialize::{
179    LIR_BIN_VERSION, hir_from_json, hir_to_json, lir_from_bytes, lir_from_json, lir_to_bytes,
180    lir_to_json,
181};
182pub use verify::{VerifyError, verify, verify_all, verify_shapes, verify_unique_leaf_names};
183
184/// Lower a HIR module to MIR, then extract the legacy [`Graph`] API surface.
185pub fn hir_to_graph(hir: HirModule) -> Result<Graph, hir::LowerError> {
186    Ok(hir.lower_to_mir()?.into_graph())
187}
188pub use binding_manifest::{BindingManifest, IoBindingEntry, WeightBlock};
189pub use component::{CompilationMode, ModelComponent};
190pub use hir_extension::{
191    HirExtensionFn, apply_hir_extensions, apply_hir_extensions_named, register_hir_extension,
192    registered_hir_extensions,
193};
194pub use reflect::{
195    BlockSpecialization, HirReflection, ManifestDiff, MirReflection, SpecializeBlockRecord,
196    layout_for_binding, layout_from_lir, probe_block_specialization, symbolic_layout_hint,
197};
198pub use rf::{
199    complex_div, const_f32, cs_degen_z_in, find_param_node, find_param_nodes, mag2, s11_from_z,
200    scalar_f32,
201};
202pub use shape::{Dim, DimBinding, Shape, ada_modulation_launch, ada_modulation_lead_pack};
203pub use variant::{ModelPhase, ModelVariant};