1use crate::backend::Backend;
8use crate::compiled::CompiledGraph;
9use crate::precision::Precision;
10use rlx_driver::Device;
11use rlx_ir::Graph;
12use rlx_ir::GraphModule;
13use rlx_ir::hir::HirModule;
14use rlx_opt::PrecisionPolicy;
15
16pub struct Session {
18 device: Device,
19 precision: Precision,
20 policy: Option<PrecisionPolicy>,
24}
25
26impl Session {
27 pub fn new(device: Device) -> Self {
32 Self::new_with_precision(device, Precision::F32)
33 }
34
35 pub fn new_with_precision(device: Device, precision: Precision) -> Self {
38 assert!(
42 crate::device_ext::is_available(device),
43 "device {} is not available — {}",
44 device,
45 if crate::device_ext::feature_compiled(device) {
46 format!(
47 "the `{}` feature is enabled but no such device/driver was found on this host",
48 feature_name(device)
49 )
50 } else {
51 format!("enable the `{}` Cargo feature", feature_name(device))
52 }
53 );
54 Self {
55 device,
56 precision,
57 policy: None,
58 }
59 }
60
61 pub fn with_policy(mut self, policy: PrecisionPolicy) -> Self {
65 self.policy = Some(policy);
66 self
67 }
68
69 pub fn device(&self) -> Device {
70 self.device
71 }
72 pub fn precision(&self) -> Precision {
73 self.precision
74 }
75 pub fn policy(&self) -> Option<&PrecisionPolicy> {
76 self.policy.as_ref()
77 }
78
79 pub fn compile(&self, graph: Graph) -> CompiledGraph {
91 if rlx_ir::dynamic::has_dynamic_dims(&graph) && !self.coreml_native_flex() {
92 return self.compile_deferred(graph, self.default_options());
93 }
94 let opts = self.default_options();
95 if opts.cache_param_invariant
96 && let Some(staged) = self.try_hoist_param_invariant(&graph, &opts)
97 {
98 return staged;
99 }
100 self.compile_module(GraphModule::from_graph(graph))
101 .expect("compile MIR graph through fusion pipeline")
102 }
103
104 fn try_hoist_param_invariant(
109 &self,
110 graph: &Graph,
111 options: &crate::CompileOptions,
112 ) -> Option<CompiledGraph> {
113 let split = rlx_compile::split_param_invariant(graph)?;
114 let mut sub = options.clone();
115 sub.cache_param_invariant = false;
116 let prepare = self.compile_with(split.prepare, &sub);
117 let main = self.compile_with(split.main, &sub);
118 Some(main.with_staging(
119 prepare,
120 split.boundary,
121 split.prepare_params,
122 split.main_params,
123 ))
124 }
125
126 fn compile_deferred(&self, graph: Graph, options: crate::CompileOptions) -> CompiledGraph {
128 let backend = self.create_backend();
129 let inner = Box::new(crate::deferred::DeferredExecutable::new(
130 graph,
131 backend,
132 options,
133 self.device,
134 ));
135 CompiledGraph::new(inner, self.device)
136 }
137
138 pub fn compile_graph(&self, graph: Graph) -> CompiledGraph {
140 self.compile(graph)
141 }
142
143 pub fn compile_with(&self, graph: Graph, options: &crate::CompileOptions) -> CompiledGraph {
148 let graph = match options.scaled_quant {
153 Some(cfg) => {
154 rlx_opt::rlx_compile::scaled_quant_insert::insert_scaled_matmul(graph, cfg)
155 }
156 None => graph,
157 };
158 if rlx_ir::dynamic::has_dynamic_dims(&graph) && !self.coreml_native_flex() {
159 return self.compile_deferred(graph, options.clone());
160 }
161 if options.cache_param_invariant
162 && let Some(staged) = self.try_hoist_param_invariant(&graph, options)
163 {
164 return staged;
165 }
166 self.compile_module_with(GraphModule::from_graph(graph), options)
167 .expect("compile MIR graph through fusion pipeline")
168 }
169
170 pub fn compile_hir(&self, hir: HirModule) -> Result<CompiledGraph, rlx_ir::hir::LowerError> {
172 self.compile_hir_with(hir, &self.default_options())
173 }
174
175 pub fn compile_hir_with(
177 &self,
178 hir: HirModule,
179 options: &crate::CompileOptions,
180 ) -> Result<CompiledGraph, rlx_ir::hir::LowerError> {
181 let backend = self.create_backend();
182 let executable = backend.compile_hir(hir, self.device, options)?;
183 Ok(CompiledGraph::new(executable, self.device))
184 }
185
186 pub fn compile_module(
188 &self,
189 module: GraphModule,
190 ) -> Result<CompiledGraph, rlx_ir::hir::LowerError> {
191 self.compile_module_with(module, &self.default_options())
192 }
193
194 pub fn compile_module_with(
196 &self,
197 module: GraphModule,
198 options: &crate::CompileOptions,
199 ) -> Result<CompiledGraph, rlx_ir::hir::LowerError> {
200 let backend = self.create_backend();
201 let executable = backend.compile_module(module, self.device, options)?;
202 Ok(CompiledGraph::new(executable, self.device))
203 }
204
205 fn default_options(&self) -> crate::CompileOptions {
206 let opts = crate::CompileOptions::new().precision(self.precision);
207 match &self.policy {
208 Some(p) => opts.policy(p.clone()),
209 None => opts,
210 }
211 }
212
213 fn coreml_native_flex(&self) -> bool {
215 #[cfg(all(
216 feature = "coreml",
217 target_vendor = "apple",
218 not(target_os = "watchos")
219 ))]
220 {
221 self.device == Device::Ane
222 && std::env::var("RLX_COREML_NATIVE_FLEX").ok().as_deref() == Some("1")
223 }
224 #[cfg(not(all(
225 feature = "coreml",
226 target_vendor = "apple",
227 not(target_os = "watchos")
228 )))]
229 {
230 false
231 }
232 }
233
234 fn create_backend(&self) -> Box<dyn Backend> {
235 crate::registry::backend_for(self.device).unwrap_or_else(|| {
239 panic!(
240 "no backend registered for device {} — enable feature `{}` \
241 (or call `rlx_runtime::register_backend` for an external backend)",
242 self.device,
243 feature_name(self.device)
244 )
245 })
246 }
247}
248
249fn feature_name(device: Device) -> &'static str {
250 match device {
251 Device::Cpu => "cpu",
252 Device::Metal => "metal",
253 Device::Mlx => "mlx",
254 Device::Ane => "ane",
255 Device::Cuda => "cuda",
256 Device::Rocm => "rocm",
257 Device::Xdna => "xdna",
258 Device::OneApi => "oneapi",
259 Device::Tpu => "tpu",
260 Device::Hexagon => "qnn",
261 Device::Gpu => "gpu",
262 Device::Vulkan => "vulkan",
263 Device::OpenGl => "opengl",
264 Device::DirectX => "directx",
265 Device::WebGpu => "webgpu",
266 }
267}