inky-engine 2.0.3

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Thin, zero-overhead-ish wrapper around objc2-metal for compute work.

use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_foundation::NSString;
use objc2_metal::*;
use std::collections::HashMap;
use std::ffi::c_void;
use std::ptr::NonNull;

pub type Buf = Retained<ProtocolObject<dyn MTLBuffer>>;
pub type Pso = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
pub type CmdBuf = Retained<ProtocolObject<dyn MTLCommandBuffer>>;

/// Check every submitted command before returning the first failure. Buffers
/// use unretained references, so callers must finish draining before releasing resources.
pub fn wait_all<T>(
    commands: impl IntoIterator<Item = T>,
    mut wait: impl FnMut(T) -> Result<(), String>,
) -> Result<(), String> {
    let mut result = Ok(());
    for command in commands {
        result = result.and(wait(command));
    }
    result
}

/// Expose the oldest command's result only after it completes. On failure,
/// finish the commands already queued after it before returning the error.
pub fn wait_or_drain<T>(
    first: T,
    pending: impl IntoIterator<Item = T>,
    mut wait: impl FnMut(T) -> Result<(), String>,
) -> Result<(), String> {
    if let Err(error) = wait(first) {
        let _ = wait_all(pending, wait);
        return Err(error);
    }
    Ok(())
}

#[cfg(test)]
std::thread_local! {
    static INJECTED_WAIT_FAILURE: std::cell::Cell<Option<(&'static str, usize)>> = const { std::cell::Cell::new(None) };
    static WAIT_STAGE_CALLS: std::cell::RefCell<HashMap<String, usize>> = std::cell::RefCell::new(HashMap::new());
}

#[cfg(test)]
pub fn inject_wait_failure(stage: &'static str, failing_call_index: usize) {
    WAIT_STAGE_CALLS.with(|m| m.borrow_mut().clear());
    INJECTED_WAIT_FAILURE.with(|f| f.set(Some((stage, failing_call_index))));
}

#[cfg(test)]
pub fn clear_wait_failure() {
    WAIT_STAGE_CALLS.with(|m| m.borrow_mut().clear());
    INJECTED_WAIT_FAILURE.with(|f| f.set(None));
}

pub fn wait_completed(cb: &CmdBuf, stage: &str, pos: usize) -> Result<(), String> {
    cb.waitUntilCompleted();
    #[cfg(test)]
    if let Some((want_stage, want_idx)) = INJECTED_WAIT_FAILURE.with(|f| f.get()) {
        if stage == want_stage {
            let idx = WAIT_STAGE_CALLS.with(|m| {
                let mut map = m.borrow_mut();
                let c = map.entry(stage.to_string()).or_insert(0);
                let cur = *c;
                *c += 1;
                cur
            });
            if idx == want_idx {
                INJECTED_WAIT_FAILURE.with(|f| f.set(None));
                return Err(format!("Metal {stage} at token {pos} failed (InjectedTestError)"));
            }
        }
    }
    let status = cb.status();
    if status == MTLCommandBufferStatus::Completed { return Ok(()); }
    let detail = cb.error().map(|err| format!(": {}", err.localizedDescription())).unwrap_or_default();
    Err(format!("Metal {stage} at token {pos} failed ({status:?}){detail}"))
}

pub struct Gpu {
    pub dev: Retained<ProtocolObject<dyn MTLDevice>>,
    pub queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
    lib: Retained<ProtocolObject<dyn MTLLibrary>>,
    psos: std::cell::RefCell<HashMap<String, Pso>>,
}

impl Gpu {
    pub fn new(src: &str, kernels: &[&str]) -> Gpu {
        Self::new_with_lang(src, kernels, true)
    }

    pub fn new_with_lang(src: &str, kernels: &[&str], metal4: bool) -> Gpu {
        let dev = MTLCreateSystemDefaultDevice().expect("no Metal device");
        let queue = dev.newCommandQueue().expect("queue");
        let opts = MTLCompileOptions::new();
        opts.setMathMode(MTLMathMode::Safe);
        opts.setLanguageVersion(if metal4 { MTLLanguageVersion::Version4_0 } else { MTLLanguageVersion::Version3_2 });
        let lib = dev
            .newLibraryWithSource_options_error(&NSString::from_str(src), Some(&opts))
            .unwrap_or_else(|e| panic!("Metal compile failed:\n{}", e.localizedDescription()));
        let g = Gpu { dev, queue, lib, psos: Default::default() };
        for k in kernels { g.pso(k); }
        g
    }

    /// pipeline state by kernel name (compiled on first use; production kernels are pre-built at load)
    pub fn pso(&self, name: &str) -> Pso {
        trace_push(name);
        if let Some(p) = self.psos.borrow().get(name) { return p.clone(); }
        let f = self.lib.newFunctionWithName(&NSString::from_str(name)).unwrap_or_else(|| panic!("kernel {name} missing"));
        let p = self.dev.newComputePipelineStateWithFunction_error(&f).unwrap_or_else(|e| panic!("pso {name}: {}", e.localizedDescription()));
        pso_names().lock().unwrap().insert(Retained::as_ptr(&p) as *const c_void as usize, name.to_string());
        self.psos.borrow_mut().insert(name.to_string(), p.clone());
        p
    }

    pub fn buffer(&self, len: usize) -> Buf {
        self.dev.newBufferWithLength_options(len.max(16), MTLResourceOptions::StorageModeShared).expect("alloc buffer")
    }

    pub fn buffer_with(&self, data: &[u8]) -> Buf {
        let b = self.buffer(data.len());
        unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), b.contents().as_ptr() as *mut u8, data.len()); }
        b
    }

    /// Wrap existing page-aligned memory (e.g. an mmapped model file) without copying.
    pub fn buffer_nocopy(&self, ptr: *mut u8, len: usize) -> Buf {
        unsafe {
            self.dev
                .newBufferWithBytesNoCopy_length_options_deallocator(
                    NonNull::new(ptr as *mut c_void).unwrap(), len, MTLResourceOptions::StorageModeShared, None)
                .expect("no-copy buffer (needs page-aligned ptr/len)")
        }
    }

    pub fn cmd(&self) -> CmdBuf { self.queue.commandBufferWithUnretainedReferences().expect("cmdbuf") }

    /// Metal's recommended maximum working set size in bytes, queried directly from MTLDevice.
    pub fn recommended_max_working_set_size(&self) -> u64 {
        self.dev.recommendedMaxWorkingSetSize()
    }

    /// Bytes currently allocated on the Metal device.
    pub fn current_allocated_size(&self) -> usize {
        self.dev.currentAllocatedSize()
    }
}

/// Memory barriers encoded so far by every `Enc` of the process (`inky binv` reports each prefill's count: barriered
/// dispatches are machine-independent, unlike wall time).
pub static BARRIERS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Compute dispatches encoded so far by every `Enc` of the process (profiling counters only).
pub static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// kernel name of every pipeline `Gpu::pso` compiled, by pipeline address (read by the dispatch profiler only)
fn pso_names() -> &'static std::sync::Mutex<HashMap<usize, String>> {
    static M: std::sync::OnceLock<std::sync::Mutex<HashMap<usize, String>>> = std::sync::OnceLock::new();
    M.get_or_init(Default::default)
}

/// One timed compute encoder of a profiled command buffer: a run of consecutive dispatches of one kernel (`tag`: the
/// engine kernel class the dispatch was issued under, when it named one).
#[derive(Clone, Debug, PartialEq)]
pub struct ProfSeg {
    pub kernel: String,
    pub tag: Option<u32>,
    pub dispatches: usize,
    /// GPU timestamps (ticks) at the encoder's start and end; `None` when the sample buffer had no room left
    pub ticks: Option<(u64, u64)>,
}

/// samples per counter sample buffer (Metal caps one at 32 KiB of 8-byte timestamps)
const PROF_SAMPLES_PER_BUF: usize = 4096;

struct ProfState {
    sbs: Vec<Retained<ProtocolObject<dyn MTLCounterSampleBuffer>>>,
    /// samples taken so far, across the buffers in order
    next: usize,
    segs: Vec<ProfSeg>,
    /// the first of the two samples of each segment (parallel to `segs`)
    idx: Vec<Option<usize>>,
}

std::thread_local! {
    static PROF: std::cell::RefCell<Option<ProfState>> = const { std::cell::RefCell::new(None) };
}

/// Arm the dispatch profiler on this thread: until `prof_take`, every `Enc` created here splits into one compute
/// encoder per run of same-kernel dispatches and samples the GPU timestamp at each encoder's start and end. The split
/// changes no arithmetic (buffers are hazard-tracked, so the encoders run in order); it adds encoder transitions,
/// which the caller reports as the profiled step's overhead.
pub fn prof_arm(dev: &ProtocolObject<dyn MTLDevice>, max_encoders: usize) -> Result<(), String> {
    if !dev.supportsCounterSampling(MTLCounterSamplingPoint::AtStageBoundary) {
        return Err("this GPU cannot sample timestamps at encoder boundaries".into());
    }
    let sets = dev.counterSets().ok_or("no GPU counter sets")?;
    let want = unsafe { MTLCommonCounterSetTimestamp };
    let set = (0..sets.count())
        .map(|i| sets.objectAtIndex(i))
        .find(|s| s.name().to_string() == want.to_string())
        .ok_or("no timestamp counter set")?;
    let d = MTLCounterSampleBufferDescriptor::new();
    d.setCounterSet(Some(&set));
    d.setStorageMode(MTLStorageMode::Shared);
    unsafe { d.setSampleCount(PROF_SAMPLES_PER_BUF) };
    let sbs = (0..(2 * max_encoders).div_ceil(PROF_SAMPLES_PER_BUF).max(1))
        .map(|_| dev.newCounterSampleBufferWithDescriptor_error(&d).map_err(|e| format!("counter sample buffer: {}", e.localizedDescription())))
        .collect::<Result<Vec<_>, _>>()?;
    PROF.with(|p| *p.borrow_mut() = Some(ProfState { sbs, next: 0, segs: Vec::new(), idx: Vec::new() }));
    Ok(())
}

/// Disarm the profiler and return its segments in encode order. Call after every profiled command buffer completed.
pub fn prof_take() -> Vec<ProfSeg> {
    let Some(st) = PROF.with(|p| p.borrow_mut().take()) else { return Vec::new() };
    let mut ts: Vec<u64> = Vec::with_capacity(st.next);
    for (b, sb) in st.sbs.iter().enumerate() {
        let n = st.next.saturating_sub(b * PROF_SAMPLES_PER_BUF).min(PROF_SAMPLES_PER_BUF);
        if n == 0 {
            break;
        }
        let data = unsafe { sb.resolveCounterRange(objc2_foundation::NSRange::new(0, n)) };
        let mut v: Vec<u64> = data.map(|d| d.to_vec().as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c)).collect()).unwrap_or_default();
        v.resize(n, u64::MAX);
        ts.extend(v);
    }
    let mut segs = st.segs;
    for (s, i) in segs.iter_mut().zip(&st.idx) {
        s.ticks = i.and_then(|i| {
            let (a, b) = (*ts.get(i)?, *ts.get(i + 1)?);
            // MTLCounterErrorValue (all ones) or a zero sample: not measured
            (a != u64::MAX && b != u64::MAX && a != 0 && b >= a).then_some((a, b))
        });
    }
    segs
}

/// a new compute encoder on `cb`, timed when the profiler is armed (and has room for two more samples), with the
/// index of its profiler segment
fn new_encoder(cb: &CmdBuf) -> (Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>, usize) {
    let timed = PROF.with(|p| {
        let mut p = p.borrow_mut();
        let st = p.as_mut()?;
        // a segment's two samples stay in one buffer (PROF_SAMPLES_PER_BUF is even)
        let slot = (st.next + 2 <= st.sbs.len() * PROF_SAMPLES_PER_BUF).then_some(st.next);
        if slot.is_some() {
            st.next += 2;
        }
        st.segs.push(ProfSeg { kernel: String::new(), tag: None, dispatches: 0, ticks: None });
        st.idx.push(slot);
        let at = slot.map(|i| (st.sbs[i / PROF_SAMPLES_PER_BUF].clone(), i % PROF_SAMPLES_PER_BUF));
        Some((at, st.segs.len() - 1))
    });
    match timed {
        None => (cb.computeCommandEncoderWithDispatchType(MTLDispatchType::Concurrent).expect("encoder"), 0),
        Some((at, seg)) => {
            let d = MTLComputePassDescriptor::computePassDescriptor();
            d.setDispatchType(MTLDispatchType::Concurrent);
            if let Some((sb, i)) = at {
                let a = unsafe { d.sampleBufferAttachments().objectAtIndexedSubscript(0) };
                a.setSampleBuffer(Some(&sb));
                unsafe {
                    a.setStartOfEncoderSampleIndex(i);
                    a.setEndOfEncoderSampleIndex(i + 1);
                }
            }
            (cb.computeCommandEncoderWithDescriptor(&d).expect("encoder"), seg)
        }
    }
}

/// what a profiled `Enc` re-binds on each new encoder: the latest buffer and bytes of every index
#[derive(Default)]
struct EncProf {
    cb: Option<CmdBuf>,
    seg: std::cell::Cell<usize>,
    tag: std::cell::Cell<Option<u32>>,
    bufs: std::cell::RefCell<HashMap<usize, (Buf, usize)>>,
    bytes: std::cell::RefCell<HashMap<usize, Vec<u8>>>,
}

pub struct Enc {
    e: std::cell::RefCell<Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>>,
    /// set only while the dispatch profiler is armed
    prof: Option<Box<EncProf>>,
}

impl Enc {
    pub fn new(cb: &CmdBuf) -> Enc {
        let armed = PROF.with(|p| p.borrow().is_some());
        let (e, seg) = new_encoder(cb);
        let prof = armed.then(|| Box::new(EncProf { cb: Some(cb.clone()), seg: seg.into(), ..Default::default() }));
        Enc { e: std::cell::RefCell::new(e), prof }
    }
    /// the engine kernel class of the next dispatch (read by the profiler only)
    #[inline] pub fn tag(&self, cls: u32) {
        if let Some(p) = &self.prof { p.tag.set(Some(cls)); }
    }
    #[inline] pub fn pso(&self, p: &Pso) {
        if let Some(pr) = &self.prof { self.prof_split(pr, p); }
        self.e.borrow().setComputePipelineState(p);
    }
    /// profiler: start a new timed encoder when this dispatch's kernel (or class) differs from the current segment's
    fn prof_split(&self, pr: &EncProf, p: &Pso) {
        let kernel = pso_names().lock().unwrap().get(&(Retained::as_ptr(p) as *const c_void as usize)).cloned().unwrap_or_else(|| "?".into());
        let tag = pr.tag.take();
        let split = PROF.with(|s| {
            let mut s = s.borrow_mut();
            let Some(st) = s.as_mut() else { return false };
            let cur = &mut st.segs[pr.seg.get()];
            if cur.dispatches == 0 || (cur.kernel == kernel && cur.tag == tag) {
                cur.kernel = kernel.clone();
                cur.tag = tag;
                cur.dispatches += 1;
                false
            } else {
                true
            }
        });
        if !split { return; }
        let cb = pr.cb.as_ref().unwrap();
        // a command buffer encodes one encoder at a time: end this one before starting the next
        self.e.borrow().endEncoding();
        let (ne, seg) = new_encoder(cb);
        pr.seg.set(seg);
        PROF.with(|s| {
            if let Some(st) = s.borrow_mut().as_mut() {
                let cur = &mut st.segs[seg];
                cur.kernel = kernel;
                cur.tag = tag;
                cur.dispatches = 1;
            }
        });
        *self.e.borrow_mut() = ne;
        let e = self.e.borrow();
        for (&idx, (b, off)) in pr.bufs.borrow().iter() {
            unsafe { e.setBuffer_offset_atIndex(Some(b), *off, idx); }
        }
        for (&idx, v) in pr.bytes.borrow().iter() {
            unsafe { e.setBytes_length_atIndex(NonNull::new(v.as_ptr() as *mut c_void).unwrap(), v.len(), idx); }
        }
    }
    #[inline] pub fn buf(&self, b: &Buf, off: usize, idx: usize) {
        if let Some(p) = &self.prof { p.bufs.borrow_mut().insert(idx, (b.clone(), off)); }
        unsafe { self.e.borrow().setBuffer_offset_atIndex(Some(b), off, idx); }
    }
    #[inline] pub fn bytes<T>(&self, v: &T, idx: usize) {
        if let Some(p) = &self.prof {
            let raw = unsafe { std::slice::from_raw_parts(v as *const T as *const u8, std::mem::size_of::<T>()) };
            p.bytes.borrow_mut().insert(idx, raw.to_vec());
        }
        unsafe { self.e.borrow().setBytes_length_atIndex(NonNull::new(v as *const T as *mut c_void).unwrap(), std::mem::size_of::<T>(), idx); }
    }
    #[inline] pub fn bytes_slice<T>(&self, v: &[T], idx: usize) {
        if let Some(p) = &self.prof {
            let raw = unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, std::mem::size_of_val(v)) };
            p.bytes.borrow_mut().insert(idx, raw.to_vec());
        }
        unsafe { self.e.borrow().setBytes_length_atIndex(NonNull::new(v.as_ptr() as *mut c_void).unwrap(), std::mem::size_of_val(v), idx); }
    }
    #[inline] pub fn dispatch(&self, grid: (usize, usize, usize), tg: usize) {
        DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        self.e.borrow().dispatchThreadgroups_threadsPerThreadgroup(
            MTLSize { width: grid.0, height: grid.1, depth: grid.2 }, MTLSize { width: tg, height: 1, depth: 1 });
    }
    /// grid size read on the GPU from 3 uint32 at `off` bytes into `b` (written by an earlier kernel of the same encoder)
    #[inline] pub fn dispatch_indirect(&self, b: &Buf, off: usize, tg: usize) {
        DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        unsafe { self.e.borrow().dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup(b, off, MTLSize { width: tg, height: 1, depth: 1 }); }
    }
    #[inline] pub fn barrier(&self) { trace_push("|"); BARRIERS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); self.e.borrow().memoryBarrierWithScope(MTLBarrierScope::Buffers); }
    pub fn end(self) { self.e.borrow().endEncoding(); }
}

#[cfg(test)]
mod prof_tests {
    use super::*;

    const SRC: &str = "#include <metal_stdlib>\nusing namespace metal;\n\
        kernel void t_add(device uint *a [[buffer(0)]], constant uint &k [[buffer(5)]], uint i [[thread_position_in_grid]]) { a[i] += k; }\n\
        kernel void t_mul(device uint *a [[buffer(0)]], constant uint &k [[buffer(5)]], uint i [[thread_position_in_grid]]) { a[i] *= k; }\n";

    /// encodes add 1, add 2, mul 3, add 4 over 256 words bound once at index 0
    fn run(g: &Gpu, buf: &Buf) {
        let cb = g.cmd();
        let e = Enc::new(&cb);
        e.buf(buf, 0, 0);
        for (k, (name, tag)) in [("t_add", 7u32), ("t_add", 7), ("t_mul", 8), ("t_add", 7)].iter().enumerate() {
            e.tag(*tag);
            e.pso(&g.pso(name));
            e.bytes(&[[1u32, 2, 3, 4][k]], 5);
            e.dispatch((1, 1, 1), 256);
            e.barrier();
        }
        e.end();
        cb.commit();
        cb.waitUntilCompleted();
    }

    #[test]
    fn profiled_encoder_split_keeps_results_and_times_each_kernel_run() {
        let g = Gpu::new_with_lang(SRC, &["t_add", "t_mul"], false);
        let words = |b: &Buf| unsafe { std::slice::from_raw_parts(b.contents().as_ptr() as *const u32, 256).to_vec() };
        let plain = g.buffer_with(&[0u8; 1024]);
        run(&g, &plain);
        assert!(words(&plain).iter().all(|&w| w == 13)); // ((0 + 1 + 2) * 3) + 4
        if prof_arm(&g.dev, 16).is_err() {
            return; // no stage-boundary timestamps on this GPU: nothing to profile
        }
        let profiled = g.buffer_with(&[0u8; 1024]);
        run(&g, &profiled);
        let segs = prof_take();
        // the split re-bound buffer 0 on every new encoder: the arithmetic is the plain run's
        assert_eq!(words(&profiled), words(&plain));
        let runs: Vec<(&str, Option<u32>, usize)> = segs.iter().map(|s| (s.kernel.as_str(), s.tag, s.dispatches)).collect();
        assert_eq!(runs, vec![("t_add", Some(7), 2), ("t_mul", Some(8), 1), ("t_add", Some(7), 1)]);
        assert!(segs.iter().all(|s| s.ticks.is_some()), "{segs:?}");
        // disarmed: a later encoder is not profiled
        assert!(prof_take().is_empty());
        let again = g.buffer_with(&[0u8; 1024]);
        run(&g, &again);
        assert!(prof_take().is_empty());
    }
}

/// Profiling trace of pipeline lookups and barriers on this thread (off unless `trace_begin` ran): a dispatch
/// sequence for `inky dbatch` with `INK_DB_B1_TRACE`. Timing/diagnostics only.
static TRACING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
thread_local! {
    static TRACE: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) };
    static TRACE_NAMES: std::cell::RefCell<HashMap<String, &'static str>> = std::cell::RefCell::new(HashMap::new());
}

#[inline]
fn trace_push(name: &str) {
    if !TRACING.load(std::sync::atomic::Ordering::Relaxed) {
        return;
    }
    let s = TRACE_NAMES.with(|m| {
        *m.borrow_mut().entry(name.to_string()).or_insert_with(|| Box::leak(name.to_string().into_boxed_str()))
    });
    TRACE.with(|t| t.borrow_mut().push(s));
}

pub fn trace_begin() {
    TRACE.with(|t| t.borrow_mut().clear());
    TRACING.store(true, std::sync::atomic::Ordering::Relaxed);
}

pub fn trace_take() -> Vec<&'static str> {
    TRACING.store(false, std::sync::atomic::Ordering::Relaxed);
    TRACE.with(|t| std::mem::take(&mut *t.borrow_mut()))
}