Skip to main content

ultrafast_render/
kernels.rs

1//! Kernel cache and background compiler.
2//!
3//! Kernels are identified by the hash of their generated code. Tier-0 kernels
4//! (one per op, plus utility kernels) are compiled once at startup. Fused
5//! kernels are compiled on a background thread when a plan needs them; until
6//! one is ready the executor runs that group as a chain of tier-0 kernels,
7//! so structural edits never stall a frame on the shader compiler.
8
9use crate::codegen;
10use crate::ops::OPS;
11use std::collections::HashMap;
12use std::sync::mpsc::{Sender, channel};
13use std::sync::{Arc, Condvar, Mutex};
14use std::time::Instant;
15use ultrafast_gpu::{Device, Kernel};
16use ultrafast_shaderc::{Compiler, Target};
17
18#[derive(Clone)]
19pub enum KernelState {
20    Pending,
21    Ready(Kernel),
22    Failed(String),
23}
24
25/// Statistics a caller can show to explain compile behaviour.
26#[derive(Debug, Clone, Copy, Default)]
27pub struct CompileStats {
28    pub jobs: u64,
29    pub kernels: u64,
30    pub cache_hits: u64,
31    pub slang_ms: f64,
32    pub native_ms: f64,
33}
34
35struct Shared {
36    map: Mutex<HashMap<String, KernelState>>,
37    cv: Condvar,
38    stats: Mutex<CompileStats>,
39}
40
41struct Job {
42    kernels: Vec<(String, String)>,
43}
44
45/// Tier-0 kernel for one op: its key and the order its texture bindings map
46/// to the op's ports (`usize::MAX` = the resource texture).
47#[derive(Debug, Clone)]
48pub struct Tier0 {
49    pub key: String,
50    pub bindings: Vec<usize>,
51}
52
53pub struct Kernels {
54    shared: Arc<Shared>,
55    /// Closed on drop, which ends the compile threads.
56    tx: Option<Sender<Job>>,
57    tier0: HashMap<&'static str, Tier0>,
58    /// Tier-0 kernels' code by key, for compiling one when it is first
59    /// needed ([`Kernels::on_demand`]).
60    tier0_code: HashMap<String, String>,
61    workers: Vec<std::thread::JoinHandle<()>>,
62}
63
64impl Drop for Kernels {
65    /// Ends the compile threads and waits for them: each holds the device,
66    /// which must be let go here, not on a thread still running while the
67    /// process exits (the GPU driver tears down under it).
68    fn drop(&mut self) {
69        self.tx.take();
70        for w in self.workers.drain(..) {
71            let _ = w.join();
72        }
73    }
74}
75
76/// Utility kernels from the op library, compiled with tier 0.
77pub const UTILITY: &[&str] = &[
78    "k_blur",
79    "k_prep_srgb8",
80    "k_prep_video",
81    "k_encode_srgb8",
82    "k_encode_nv12",
83    "k_clear",
84    "k_raster_lines",
85    "k_raster_resolve",
86    "k_atlas_put",
87    "k_present",
88    "k_accumulate",
89    "k_blur_region",
90    "k_resample",
91    "k_diff",
92    "k_dof",
93    "k_dof_mix",
94    "k_fl_curl",
95    "k_fl_force",
96    "k_fl_div",
97    "k_fl_jacobi",
98    "k_fl_project",
99    "k_fl_advect",
100    "k_copy",
101    "k_over_frames",
102];
103
104impl Kernels {
105    /// Starts the compile threads and builds tier 0 (blocking): every op's
106    /// kernel, so a new structure renders op by op at once (the live
107    /// player, the render service).
108    pub fn new(device: Device) -> Result<Self, String> {
109        Self::build(device, true)
110    }
111
112    /// Starts the compile threads and builds the utility kernels only;
113    /// an op's tier-0 kernel compiles when something first needs it
114    /// ([`Kernels::tier0_kernel`]). For one render that waits for its
115    /// fused kernels anyway (an export, a frame): the first run after an
116    /// install or an upgrade doesn't compile ~30 kernels it never uses
117    /// (about 0.9 s on 8 threads).
118    pub fn on_demand(device: Device) -> Result<Self, String> {
119        Self::build(device, false)
120    }
121
122    fn build(device: Device, eager: bool) -> Result<Self, String> {
123        let shared = Arc::new(Shared {
124            map: Mutex::new(HashMap::new()),
125            cv: Condvar::new(),
126            stats: Mutex::new(CompileStats::default()),
127        });
128        let (tx, rx) = channel::<Job>();
129        let target = match device.backend() {
130            "metal" => Target::Metal,
131            _ => Target::Spirv,
132        };
133        // Every kernel is its own module, so its compiled code (and the
134        // driver's pipeline for it) is cached under a key of its own source
135        // alone: the same kernel hits the cache in any process, whatever
136        // else that process compiled before. Modules compile on a pool of
137        // threads (ULTRAFAST_COMPILE_THREADS).
138        let rx = Arc::new(Mutex::new(rx));
139        let threads = std::env::var("ULTRAFAST_COMPILE_THREADS")
140            .ok()
141            .and_then(|v| v.parse::<usize>().ok())
142            .unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()).min(8))
143            .max(1);
144        let mut workers = Vec::with_capacity(threads);
145        for i in 0..threads {
146            let rx = rx.clone();
147            let worker_shared = shared.clone();
148            let worker_device = device.clone();
149            let handle = std::thread::Builder::new()
150                .name(format!("ultrafast-compile-{i}"))
151                .spawn(move || {
152                    let mut compiler = Compiler::new();
153                    loop {
154                        let job = match rx.lock().unwrap().recv() {
155                            Ok(job) => job,
156                            Err(_) => break,
157                        };
158                        run_job(&mut compiler, &worker_device, target, &worker_shared, job);
159                    }
160                })
161                .map_err(|e| e.to_string())?;
162            workers.push(handle);
163        }
164
165        let mut tier0 = HashMap::new();
166        let mut jobs = Vec::new();
167        for def in OPS {
168            if let Some(g) = codegen::single_op(def) {
169                let resource_ext = def.ports.len();
170                let bindings = g
171                    .bindings
172                    .iter()
173                    .map(|&b| if b == resource_ext { usize::MAX } else { b })
174                    .collect();
175                tier0.insert(
176                    def.func,
177                    Tier0 {
178                        key: g.key.clone(),
179                        bindings,
180                    },
181                );
182                jobs.push((g.key, g.body));
183            }
184        }
185        let mut k = Kernels {
186            shared,
187            tx: Some(tx),
188            tier0,
189            tier0_code: HashMap::new(),
190            workers,
191        };
192        // Utility kernels are plain entry points in the library itself:
193        // first in the queue, as every render needs some.
194        k.request_utility();
195        if eager {
196            k.request(jobs);
197            for t in k.tier0.values() {
198                if let KernelState::Failed(e) = k.wait(&t.key) {
199                    return Err(format!("tier-0 kernel failed to build: {e}"));
200                }
201            }
202        } else {
203            k.tier0_code = jobs.into_iter().collect();
204        }
205        for u in UTILITY {
206            if let KernelState::Failed(e) = k.wait(u) {
207                return Err(format!("utility kernel {u} failed to build: {e}"));
208            }
209        }
210        Ok(k)
211    }
212
213    fn request_utility(&self) {
214        let mut map = self.shared.map.lock().unwrap();
215        for u in UTILITY {
216            map.insert(u.to_string(), KernelState::Pending);
217        }
218        drop(map);
219        if let Some(tx) = &self.tx {
220            let _ = tx.send(Job {
221                kernels: vec![(String::new(), String::new())],
222            });
223        }
224    }
225
226    pub fn tier0(&self, func: &str) -> Option<&Tier0> {
227        self.tier0.get(func)
228    }
229
230    /// The tier-0 kernel for op function `func`, compiled now if it hasn't
231    /// been (blocks until it is).
232    pub fn tier0_kernel(&self, func: &str) -> Result<Kernel, String> {
233        let t = self
234            .tier0
235            .get(func)
236            .ok_or_else(|| format!("no tier-0 kernel for {func}"))?;
237        if self.get(&t.key).is_none() {
238            let code = self.tier0_code.get(&t.key).cloned().unwrap_or_default();
239            self.request(vec![(t.key.clone(), code)]);
240        }
241        match self.wait(&t.key) {
242            KernelState::Ready(k) => Ok(k),
243            KernelState::Failed(e) => Err(format!("tier-0 kernel for {func} failed to build: {e}")),
244            KernelState::Pending => unreachable!("wait returns once a kernel is done"),
245        }
246    }
247
248    /// Queues kernels that are not known yet. Returns how many were queued.
249    pub fn request(&self, kernels: Vec<(String, String)>) -> usize {
250        let mut map = self.shared.map.lock().unwrap();
251        let mut todo = Vec::new();
252        for (key, body) in kernels {
253            if !map.contains_key(&key) && !todo.iter().any(|(k, _): &(String, String)| *k == key) {
254                map.insert(key.clone(), KernelState::Pending);
255                todo.push((key, body));
256            }
257        }
258        drop(map);
259        let n = todo.len();
260        if let Some(tx) = &self.tx {
261            for k in todo {
262                let _ = tx.send(Job { kernels: vec![k] });
263            }
264        }
265        n
266    }
267
268    pub fn get(&self, key: &str) -> Option<KernelState> {
269        self.shared.map.lock().unwrap().get(key).cloned()
270    }
271
272    /// Ready kernel for `key`, if any.
273    pub fn ready(&self, key: &str) -> Option<Kernel> {
274        match self.get(key) {
275            Some(KernelState::Ready(k)) => Some(k),
276            _ => None,
277        }
278    }
279
280    /// Blocks until `key` is no longer pending.
281    pub fn wait(&self, key: &str) -> KernelState {
282        let mut map = self.shared.map.lock().unwrap();
283        loop {
284            match map.get(key) {
285                Some(KernelState::Pending) => map = self.shared.cv.wait(map).unwrap(),
286                Some(s) => return s.clone(),
287                None => return KernelState::Failed(format!("kernel {key} was never requested")),
288            }
289        }
290    }
291
292    pub fn utility(&self, name: &str) -> Kernel {
293        self.ready(name)
294            .unwrap_or_else(|| panic!("utility kernel {name} missing"))
295    }
296
297    pub fn pending(&self) -> usize {
298        self.shared
299            .map
300            .lock()
301            .unwrap()
302            .values()
303            .filter(|s| matches!(s, KernelState::Pending))
304            .count()
305    }
306
307    pub fn stats(&self) -> CompileStats {
308        *self.shared.stats.lock().unwrap()
309    }
310}
311
312fn run_job(compiler: &mut Compiler, device: &Device, target: Target, shared: &Shared, job: Job) {
313    let utility = job.kernels.len() == 1 && job.kernels[0].0.is_empty();
314    let pairs: Vec<(&str, &str)> = if utility {
315        Vec::new()
316    } else {
317        job.kernels.iter().map(|(k, b)| (k.as_str(), b.as_str())).collect()
318    };
319    let source = codegen::module(&pairs);
320    // ULTRAFAST_DUMP_KERNELS=dir writes every compiled module for inspection.
321    if let Some(dir) = std::env::var_os("ULTRAFAST_DUMP_KERNELS") {
322        let dir = std::path::PathBuf::from(dir);
323        let _ = std::fs::create_dir_all(&dir);
324        let name = blake3::hash(source.as_bytes()).to_hex()[..16].to_string();
325        let _ = std::fs::write(dir.join(format!("{name}.slang")), &source);
326    }
327    let names: Vec<String> = if utility {
328        UTILITY.iter().map(|s| s.to_string()).collect()
329    } else {
330        job.kernels.iter().map(|(k, _)| codegen::entry_name(k)).collect()
331    };
332    let keys: Vec<String> = if utility {
333        UTILITY.iter().map(|s| s.to_string()).collect()
334    } else {
335        job.kernels.iter().map(|(k, _)| k.clone()).collect()
336    };
337    let entries: Vec<&str> = names.iter().map(String::as_str).collect();
338
339    let t0 = Instant::now();
340    let result = compiler
341        .compile(&source, &entries, target)
342        .map_err(|e| e.to_string())
343        .and_then(|out| {
344            let slang_ms = out.ms;
345            let t1 = Instant::now();
346            let lib = device.library(&out.code).map_err(|e| e.to_string())?;
347            let native_ms = t1.elapsed().as_secs_f64() * 1000.0;
348            Ok((lib, out.cached, slang_ms, native_ms))
349        });
350
351    match result {
352        Ok((lib, cached, slang_ms, native_ms)) => {
353            let built: Vec<KernelState> = names
354                .iter()
355                .map(|n| match lib.kernel(n) {
356                    Ok(k) => KernelState::Ready(k),
357                    Err(e) => KernelState::Failed(e.to_string()),
358                })
359                .collect();
360            let mut st = shared.stats.lock().unwrap();
361            st.jobs += 1;
362            st.kernels += names.len() as u64;
363            st.cache_hits += cached as u64;
364            st.slang_ms += slang_ms;
365            st.native_ms += native_ms;
366            drop(st);
367            let mut map = shared.map.lock().unwrap();
368            for (k, s) in keys.into_iter().zip(built) {
369                map.insert(k, s);
370            }
371        }
372        Err(e) if keys.len() > 1 && !utility => {
373            // One bad kernel (say, an agent shader with a typo) must not take
374            // the others down: retry individually to isolate it.
375            let _ = t0;
376            for (k, b) in job.kernels {
377                run_job(compiler, device, target, shared, Job { kernels: vec![(k, b)] });
378            }
379            let _ = e;
380            shared.cv.notify_all();
381            return;
382        }
383        Err(e) => {
384            let mut map = shared.map.lock().unwrap();
385            for k in keys {
386                map.insert(k, KernelState::Failed(e.clone()));
387            }
388        }
389    }
390    shared.cv.notify_all();
391}