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;
62// On-device (ANE) gradient-based training + MLUpdateTask eligibility probe.
63#[cfg(all(feature = "coreml", feature = "training"))]
64pub mod coreml_training;
65pub mod cost;
66mod cpu_low_precision;
67mod deferred;
68pub mod device_bench;
69pub mod device_ext;
70pub mod device_parse;
71pub mod device_policy;
72pub mod expert_pool;
73pub mod graph_io;
74pub mod jacfwd;
75pub mod kernel_trace;
76pub mod kv_cache;
77pub mod lora_scheduler;
78pub mod memory_estimate;
79pub mod model_pipeline;
80pub mod moe_expert_store;
81#[cfg(feature = "cpu")]
82pub mod onnx_active;
83pub mod op_registry;
84pub mod options;
85pub mod paged_kv;
86pub mod precision;
87pub mod precompile;
88pub mod quantized_kv;
89pub mod record_replay;
90pub mod reflect;
91pub mod registry;
92pub mod router;
93pub mod samplers;
94pub mod session;
95pub mod stages;
96pub mod subgraph;
97pub mod trace;
98pub mod weight_registry;
99pub mod weights;
100pub mod worker_pool;
101/// PLAN L3 — Perfetto / chrome-trace JSON tracing. Lives in `rlx-ir`
102/// (alongside the `Tick` cycle counter it depends on) so every backend
103/// can instrument per-thunk without crate-dep gymnastics. Re-exported
104/// here so callers see one consistent `rlx_runtime::perfetto::TraceSpan`.
105pub use rlx_ir::perfetto;
106pub mod custom_ops;
107pub mod device_router;
108pub mod flexible_session;
109pub mod graph_devices;
110pub mod hwinfo;
111pub mod lm;
112pub mod logit_verify;
113pub mod nan_check;
114pub mod phase;
115pub mod spec_decode;
116pub mod telemetry;
117pub mod validators;
118
119// Always-available now that serde is a non-optional dep + #32
120// router consumes the OpenAI-shaped structs unconditionally.
121pub mod mock_requests;
122
123// Driver-layer types — re-exported from rlx-driver (plan #58).
124pub use rlx_driver::{Buffer, BufferHandle, CommandStream, Device, DeviceArena, SyncStream};
125// Symmetric-memory primitives (plan #49) — foundation for #12.
126pub use rlx_driver::{
127    CollectiveError, LocalTransport, Rank, SymmetricBuffer, SymmetricHeap, SymmetricTransport,
128};
129// Collective ops (plan #12).
130pub use aot_cache::{AotCache, AotCacheError};
131pub use backend::{Backend, ExecutableGraph, compile_hir, compile_module};
132pub use backends_manifest::BackendsManifest;
133pub use compile_cache::{
134    BucketedCompileCache, CacheRunInput, CompileCache, DynamicDimCompileCache, pad_rows, slice_rows,
135};
136pub use compile_config::{
137    COMPILE_OUTPUT_CAP_ENV, COMPILE_OUTPUT_CAP_ENV_MLX, DEFAULT_COMPILE_OUTPUT_CAP,
138    compile_output_cap, device_has_compile_output_cap, reset_compile_output_cap,
139    set_compile_output_cap,
140};
141pub use compiled::CompiledGraph;
142#[cfg(all(feature = "coreml", feature = "training"))]
143pub use coreml_training::{
144    CoremlTrainingSession, MlUpdateEligibility, Optimizer, StepReport, TrainConfig, UpdatePath,
145};
146pub use cost::fastest_device_for;
147pub use device_bench::{DeviceBenchResult, benchmark_devices, warm_all};
148#[cfg(feature = "apple")]
149pub use device_ext::available_apple_devices;
150pub use device_ext::{
151    available_devices, devices_for, dispatch_report_for_device,
152    dispatch_report_for_device_with_options, fastest_device, first_unsupported_op,
153    first_unsupported_op_with_options, full_name, is_available, legalize_graph_for_device,
154    legalize_graph_for_device_with_options, legalize_graph_for_device_with_report, supports,
155    supports_graph, supports_graph_with_options, supports_run_slots,
156};
157pub use device_parse::{ParseDeviceError, device_label, parse_device, parse_device_list};
158pub use device_policy::{
159    DeviceCandidate, DeviceFallbackError, DevicePickStrategy, DevicePolicy, device_chain_from_env,
160    device_chain_from_env_key, device_from_env, device_from_env_key, device_report,
161    devices_for_with_policy, resolve_device, resolve_device_chain, run_with_fallback,
162};
163pub use device_router::DeviceRouter;
164pub use expert_pool::{
165    ExpertPool, ExpertPoolConfig, ExpertPoolStats, ExpertRefreshPolicy, ExpertRefreshResult,
166    MoEExecMode, gpu_expert_budget_from_vram,
167};
168pub use flexible_session::FlexibleSession;
169pub use graph_devices::{GraphDevices, graph_param_names};
170pub use kv_cache::LayerKvCache;
171pub use lm::{
172    ConfigSource, LmRunner, LmRunnerBuilder, MirostatMode, ModelRegistration,
173    PACKED_GGUF_AUTO_THRESHOLD_BYTES, SampleOpts, WeightFormat, auto_runner_name,
174    registered_models,
175};
176pub use memory_estimate::{
177    DEFAULT_SOFT_MEMORY_FRACTION, MoeOffloadEstimate, available_unified_memory,
178    estimate_moe_offload, llama_decode_bucket_compile_peak_bytes,
179    llama_decode_oneshot_compile_peak_bytes, memory_headroom_bytes, process_rss_bytes,
180    soft_memory_budget_bytes, soft_memory_fraction, would_exceed_soft_budget,
181};
182pub use model_pipeline::ModelCompilePipeline;
183pub use options::CompileOptions;
184pub use precision::Precision;
185pub use reflect::{ModelReflection, load_hir_template_with_extensions, specialize_entry};
186pub use registry::{BackendFactory, backend_for, register_backend, registered_devices};
187
188/// Alias for [`COMPILE_OUTPUT_CAP_ENV`].
189pub const MLX_COMPILE_OUTPUT_CAP_ENV: &str = COMPILE_OUTPUT_CAP_ENV;
190
191/// Alias for [`DEFAULT_COMPILE_OUTPUT_CAP`].
192pub const DEFAULT_MLX_COMPILE_OUTPUT_CAP: usize = DEFAULT_COMPILE_OUTPUT_CAP;
193
194/// Alias for [`compile_output_cap`].
195#[inline]
196pub fn mlx_compile_output_cap() -> usize {
197    compile_output_cap()
198}
199
200/// Alias for [`set_compile_output_cap`].
201#[inline]
202pub fn set_mlx_compile_output_cap(cap: usize) {
203    set_compile_output_cap(cap);
204}
205
206/// Alias for [`reset_compile_output_cap`].
207#[inline]
208pub fn reset_mlx_compile_output_cap() {
209    reset_compile_output_cap();
210}
211
212#[cfg(feature = "cpu")]
213pub use rlx_cpu::moe_residency::MoeResidencyStats;
214#[cfg(feature = "cpu")]
215pub use rlx_cpu::moe_topk_capture::MoeTopkCapture;
216pub use rlx_driver::{
217    DEFAULT_HEAP_BYTES, NetTransport, ProcessGroup, TcpTransport, ThunderboltTransport, Transport,
218};
219pub use rlx_driver::{ReduceKind, all_gather, all_reduce, reduce_scatter};
220pub use rlx_ir::env::{self, RlxEnv, RuntimeOverrides};
221pub use session::Session;
222pub use stages::{
223    compile_graph_stages, compile_graph_stages_for_backend, compile_hir_stages,
224    compile_module_stages, fusion_target_for, graph_from_lir, maybe_log_fusion,
225    options_with_supported_ops, pipeline_for,
226};
227pub use subgraph::{SubgraphCache, run_if, run_while};
228
229pub use expert_pool::{merged_resident_mask, per_layer_resident_masks};
230pub use moe_expert_store::{ExpertStackF32, LayerMoeWeights, MoeExpertStore};
231pub use weight_registry::{WeightEntry, WeightHandle, WeightKind, WeightRegistry};
232pub use weights::{BytesWeightLoader, WeightLoader};
233
234// Cycle-accurate timing primitive lives in rlx-ir (lowest crate); re-export
235// here so `rlx_runtime::Tick` works without forcing callers to add the IR
236// crate as a direct dep.
237pub use rlx_ir::{AsyncCopy, BarrierToken, DoubleBuffer, SyncCopy};
238pub use rlx_ir::{CacheBuster, Tick, time_ns};
239
240// Re-export precision policy from rlx-opt for convenience
241pub use rlx_ir::{
242    inspect_graph, inspect_hir, inspect_hir_stats, inspect_lir, inspect_mir, inspect_mir_stats,
243};
244pub use rlx_opt::{OpKind, PrecisionPolicy};
245pub use rlx_opt::{PipelineInspect, inspect_pipeline};
246
247// Re-export IR types for convenience
248pub use rlx_ir::logical_kernel::{KernelDispatchConfig, KernelDispatchPolicy};
249pub use rlx_ir::op;
250pub use rlx_ir::{
251    BindingManifest, CompilationMode, DType, Graph, HirExtensionFn, HirReflection, IoBindingEntry,
252    ManifestDiff, ModelComponent, ModelPhase, ModelVariant, Node, NodeId, Op, RngBackend,
253    RngOptions, Shape, WeightBlock, apply_hir_extensions, register_hir_extension,
254    registered_hir_extensions,
255};
256
257// Re-export proc macro
258pub use rlx_macros::pipeline_schedule;
259pub use rlx_macros::rlx_model;