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