Skip to main content

rlx_runtime/
lib.rs

1// RLX — versatile ML compiler + runtime.
2// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, version 3.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with this program. If not, see <https://www.gnu.org/licenses/>.
15
16//! RLX Runtime — the user-facing API.
17//!
18//! Provides a unified [`Session`] that compiles and executes IR graphs
19//! on the selected backend. Backend selection is via Cargo features:
20//!
21//! ```toml
22//! [dependencies]
23//! rlx-runtime = { version = "0.1", features = ["cpu"] }                # CPU (default)
24//! rlx-runtime = { version = "0.1", features = ["blas-accelerate"] }    # CPU + Apple Accelerate
25//! rlx-runtime = { version = "0.1", features = ["blas-mkl"] }           # CPU + Intel MKL
26//! # rlx-runtime = { version = "0.1", features = ["gpu"] }             # GPU via wgpu
27//! # rlx-runtime = { version = "0.1", features = ["cuda"] }            # GPU via CUDA
28//! ```
29//!
30//! # Example
31//! ```rust,no_run
32//! use rlx_runtime::*;
33//! use rlx_ir::*;
34//!
35//! // Build a graph
36//! let mut g = Graph::new("example");
37//! let x = g.input("x", Shape::new(&[2, 4], DType::F32));
38//! let w = g.param("w", Shape::new(&[4, 3], DType::F32));
39//! let b = g.param("b", Shape::new(&[3], DType::F32));
40//! let mm = g.matmul(x, w, Shape::new(&[2, 3], DType::F32));
41//! let out = g.binary(op::BinaryOp::Add, mm, b, Shape::new(&[2, 3], DType::F32));
42//! g.set_outputs(vec![out]);
43//!
44//! // Compile and execute
45//! let session = Session::new(Device::Cpu);
46//! let mut compiled = session.compile(g);
47//! compiled.set_param("w", &[1.0f32; 12]);
48//! compiled.set_param("b", &[0.0f32; 3]);
49//! let result = compiled.run(&[("x", &[1.0f32; 8])]);
50//! ```
51
52// Driver-layer concerns (device, arena, handle, stream, buffer)
53// live in rlx-driver as of plan #58; re-exported below so
54// existing callers compile unchanged.
55pub mod aot_cache;
56pub mod attn_mask;
57pub mod backend;
58pub mod backends_manifest;
59pub mod compile_cache;
60pub mod compile_config;
61pub mod compiled;
62pub mod cost;
63mod cpu_low_precision;
64pub mod device_bench;
65pub mod device_ext;
66pub mod device_parse;
67pub mod device_policy;
68pub mod expert_pool;
69pub mod jacfwd;
70pub mod kernel_trace;
71pub mod kv_cache;
72pub mod lora_scheduler;
73pub mod memory_estimate;
74pub mod model_pipeline;
75pub mod moe_expert_store;
76pub mod op_registry;
77pub mod options;
78pub mod paged_kv;
79pub mod precision;
80pub mod precompile;
81pub mod record_replay;
82pub mod reflect;
83pub mod registry;
84pub mod router;
85pub mod session;
86pub mod stages;
87pub mod subgraph;
88pub mod trace;
89pub mod weight_registry;
90pub mod weights;
91pub mod worker_pool;
92/// PLAN L3 — Perfetto / chrome-trace JSON tracing. Lives in `rlx-ir`
93/// (alongside the `Tick` cycle counter it depends on) so every backend
94/// can instrument per-thunk without crate-dep gymnastics. Re-exported
95/// here so callers see one consistent `rlx_runtime::perfetto::TraceSpan`.
96pub use rlx_ir::perfetto;
97pub mod custom_ops;
98pub mod device_router;
99pub mod flexible_session;
100pub mod graph_devices;
101pub mod hwinfo;
102pub mod lm;
103pub mod logit_verify;
104pub mod nan_check;
105pub mod phase;
106pub mod spec_decode;
107pub mod telemetry;
108pub mod validators;
109
110// Always-available now that serde is a non-optional dep + #32
111// router consumes the OpenAI-shaped structs unconditionally.
112pub mod mock_requests;
113
114// Driver-layer types — re-exported from rlx-driver (plan #58).
115pub use rlx_driver::{Buffer, BufferHandle, CommandStream, Device, DeviceArena, SyncStream};
116// Symmetric-memory primitives (plan #49) — foundation for #12.
117pub use rlx_driver::{
118    CollectiveError, LocalTransport, Rank, SymmetricBuffer, SymmetricHeap, SymmetricTransport,
119};
120// Collective ops (plan #12).
121pub use aot_cache::{AotCache, AotCacheError};
122pub use backend::{Backend, ExecutableGraph, compile_hir, compile_module};
123pub use backends_manifest::BackendsManifest;
124pub use compile_cache::{
125    BucketedCompileCache, CacheRunInput, CompileCache, DynamicDimCompileCache, pad_rows, slice_rows,
126};
127pub use compile_config::{
128    COMPILE_OUTPUT_CAP_ENV, COMPILE_OUTPUT_CAP_ENV_MLX, DEFAULT_COMPILE_OUTPUT_CAP,
129    compile_output_cap, device_has_compile_output_cap, reset_compile_output_cap,
130    set_compile_output_cap,
131};
132pub use compiled::CompiledGraph;
133pub use cost::fastest_device_for;
134pub use device_bench::{DeviceBenchResult, benchmark_devices, warm_all};
135#[cfg(feature = "apple")]
136pub use device_ext::available_apple_devices;
137pub use device_ext::{
138    available_devices, devices_for, dispatch_report_for_device,
139    dispatch_report_for_device_with_options, fastest_device, first_unsupported_op,
140    first_unsupported_op_with_options, full_name, is_available, legalize_graph_for_device,
141    legalize_graph_for_device_with_options, legalize_graph_for_device_with_report, supports,
142    supports_graph, supports_graph_with_options, supports_run_slots,
143};
144pub use device_parse::{ParseDeviceError, device_label, parse_device, parse_device_list};
145pub use device_policy::{
146    DeviceCandidate, DeviceFallbackError, DevicePickStrategy, DevicePolicy, device_chain_from_env,
147    device_chain_from_env_key, device_from_env, device_from_env_key, device_report,
148    devices_for_with_policy, resolve_device, resolve_device_chain, run_with_fallback,
149};
150pub use device_router::DeviceRouter;
151pub use expert_pool::{
152    ExpertPool, ExpertPoolConfig, ExpertPoolStats, ExpertRefreshPolicy, ExpertRefreshResult,
153    MoEExecMode, gpu_expert_budget_from_vram,
154};
155pub use flexible_session::FlexibleSession;
156pub use graph_devices::{GraphDevices, graph_param_names};
157pub use kv_cache::LayerKvCache;
158pub use lm::{
159    ConfigSource, LmRunner, LmRunnerBuilder, ModelRegistration, PACKED_GGUF_AUTO_THRESHOLD_BYTES,
160    SampleOpts, WeightFormat, auto_runner_name, registered_models,
161};
162pub use memory_estimate::{MoeOffloadEstimate, estimate_moe_offload};
163pub use model_pipeline::ModelCompilePipeline;
164pub use options::CompileOptions;
165pub use precision::Precision;
166pub use reflect::{ModelReflection, load_hir_template_with_extensions, specialize_entry};
167pub use registry::{BackendFactory, backend_for, register_backend, registered_devices};
168
169/// Alias for [`COMPILE_OUTPUT_CAP_ENV`].
170pub const MLX_COMPILE_OUTPUT_CAP_ENV: &str = COMPILE_OUTPUT_CAP_ENV;
171
172/// Alias for [`DEFAULT_COMPILE_OUTPUT_CAP`].
173pub const DEFAULT_MLX_COMPILE_OUTPUT_CAP: usize = DEFAULT_COMPILE_OUTPUT_CAP;
174
175/// Alias for [`compile_output_cap`].
176#[inline]
177pub fn mlx_compile_output_cap() -> usize {
178    compile_output_cap()
179}
180
181/// Alias for [`set_compile_output_cap`].
182#[inline]
183pub fn set_mlx_compile_output_cap(cap: usize) {
184    set_compile_output_cap(cap);
185}
186
187/// Alias for [`reset_compile_output_cap`].
188#[inline]
189pub fn reset_mlx_compile_output_cap() {
190    reset_compile_output_cap();
191}
192
193#[cfg(feature = "cpu")]
194pub use rlx_cpu::moe_residency::MoeResidencyStats;
195#[cfg(feature = "cpu")]
196pub use rlx_cpu::moe_topk_capture::MoeTopkCapture;
197pub use rlx_driver::{ReduceKind, all_gather, all_reduce, reduce_scatter};
198pub use rlx_ir::env::{self, RlxEnv, RuntimeOverrides};
199pub use session::Session;
200pub use stages::{
201    compile_graph_stages, compile_graph_stages_for_backend, compile_hir_stages,
202    compile_module_stages, fusion_target_for, graph_from_lir, maybe_log_fusion,
203    options_with_supported_ops, pipeline_for,
204};
205pub use subgraph::{SubgraphCache, run_if, run_while};
206
207pub use expert_pool::{merged_resident_mask, per_layer_resident_masks};
208pub use moe_expert_store::{ExpertStackF32, LayerMoeWeights, MoeExpertStore};
209pub use weight_registry::{WeightEntry, WeightHandle, WeightKind, WeightRegistry};
210pub use weights::{BytesWeightLoader, WeightLoader};
211
212// Cycle-accurate timing primitive lives in rlx-ir (lowest crate); re-export
213// here so `rlx_runtime::Tick` works without forcing callers to add the IR
214// crate as a direct dep.
215pub use rlx_ir::{AsyncCopy, BarrierToken, DoubleBuffer, SyncCopy};
216pub use rlx_ir::{CacheBuster, Tick, time_ns};
217
218// Re-export precision policy from rlx-opt for convenience
219pub use rlx_ir::{
220    inspect_graph, inspect_hir, inspect_hir_stats, inspect_lir, inspect_mir, inspect_mir_stats,
221};
222pub use rlx_opt::{OpKind, PrecisionPolicy};
223pub use rlx_opt::{PipelineInspect, inspect_pipeline};
224
225// Re-export IR types for convenience
226pub use rlx_ir::logical_kernel::{KernelDispatchConfig, KernelDispatchPolicy};
227pub use rlx_ir::op;
228pub use rlx_ir::{
229    BindingManifest, CompilationMode, DType, Graph, HirExtensionFn, HirReflection, IoBindingEntry,
230    ManifestDiff, ModelComponent, ModelPhase, ModelVariant, Node, NodeId, Op, Shape, WeightBlock,
231    apply_hir_extensions, register_hir_extension, registered_hir_extensions,
232};
233
234// Re-export proc macro
235pub use rlx_macros::pipeline_schedule;
236pub use rlx_macros::rlx_model;