llam 0.1.4

Safe, Go-style Rust bindings for the LLAM runtime
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
459
460
461
462
463
464
465
466
use crate::error::{Error, Result};
use crate::sys;
use crate::task::{self, JoinError};
use std::mem;
use std::time::Duration;

#[derive(Clone, Copy, Debug)]
pub enum Profile {
    Balanced,
    ReleaseFast,
    DebugSafe,
    IoLatency,
}

impl Profile {
    pub(crate) fn raw(self) -> u32 {
        match self {
            Self::Balanced => sys::LLAM_RUNTIME_PROFILE_BALANCED,
            Self::ReleaseFast => sys::LLAM_RUNTIME_PROFILE_RELEASE_FAST,
            Self::DebugSafe => sys::LLAM_RUNTIME_PROFILE_DEBUG_SAFE,
            Self::IoLatency => sys::LLAM_RUNTIME_PROFILE_IO_LATENCY,
        }
    }
}

#[derive(Clone, Debug)]
pub struct RuntimeBuilder {
    opts: sys::llam_runtime_opts_t,
}

impl RuntimeBuilder {
    pub fn new() -> Self {
        let mut opts = unsafe { mem::zeroed::<sys::llam_runtime_opts_t>() };
        let rc = unsafe { sys::llam_runtime_opts_init(&mut opts, mem::size_of_val(&opts)) };
        assert_eq!(rc, 0, "llam_runtime_opts_init failed");
        Self { opts }
    }

    pub fn profile(mut self, profile: Profile) -> Self {
        self.opts.profile = profile.raw();
        self
    }

    pub fn deterministic(mut self, enabled: bool) -> Self {
        self.opts.deterministic = u32::from(enabled);
        self
    }

    pub fn forced_yield_every(mut self, every: u32) -> Self {
        self.opts.forced_yield_every = every;
        self
    }

    pub fn idle_spin(mut self, duration: Duration) -> Self {
        self.opts.idle_spin_ns = duration.as_nanos().min(u128::from(u64::MAX)) as u64;
        self
    }

    pub fn idle_spin_max_iters(mut self, iters: u32) -> Self {
        self.opts.idle_spin_max_iters = iters;
        self
    }

    pub fn sqpoll_cpu(mut self, cpu: i32) -> Self {
        self.opts.sqpoll_cpu = cpu;
        self
    }

    pub fn dynamic_workers(mut self, enabled: bool) -> Self {
        self.set_flag(sys::LLAM_RUNTIME_EXPERIMENTAL_F_DYNAMIC_WORKERS, enabled);
        self
    }

    pub fn worker_rings(mut self, enabled: bool) -> Self {
        self.set_flag(sys::LLAM_RUNTIME_EXPERIMENTAL_F_WORKER_RINGS, enabled);
        self
    }

    pub fn worker_rings_multishot(mut self, enabled: bool) -> Self {
        self.set_flag(
            sys::LLAM_RUNTIME_EXPERIMENTAL_F_WORKER_RINGS_MULTISHOT,
            enabled,
        );
        self
    }

    pub fn lockfree_normq(mut self, enabled: bool) -> Self {
        self.set_flag(sys::LLAM_RUNTIME_EXPERIMENTAL_F_LOCKFREE_NORMQ, enabled);
        self
    }

    pub fn huge_alloc(mut self, enabled: bool) -> Self {
        self.set_flag(sys::LLAM_RUNTIME_EXPERIMENTAL_F_HUGE_ALLOC, enabled);
        self
    }

    pub fn sqpoll(mut self, enabled: bool) -> Self {
        self.set_flag(sys::LLAM_RUNTIME_EXPERIMENTAL_F_SQPOLL, enabled);
        self
    }

    pub fn experimental_flags(mut self, flags: u64) -> Self {
        self.opts.experimental_flags = flags;
        self
    }

    pub fn raw_options(&self) -> &sys::llam_runtime_opts_t {
        &self.opts
    }

    pub fn init(self) -> Result<Runtime> {
        let rc = unsafe { sys::llam_runtime_init_ex(&self.opts, mem::size_of_val(&self.opts)) };
        if rc == 0 {
            Ok(Runtime { active: true })
        } else {
            Err(Error::last())
        }
    }

    pub fn create_handle(self) -> Result<RuntimeHandle> {
        let mut raw = std::ptr::null_mut();
        let rc =
            unsafe { sys::llam_runtime_create(&self.opts, mem::size_of_val(&self.opts), &mut raw) };
        if rc == 0 {
            Ok(RuntimeHandle { raw, active: true })
        } else {
            Err(Error::last())
        }
    }

    pub fn run<F>(self, f: F) -> Result<()>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        let runtime = self.init()?;
        runtime.run(f)
    }

    fn set_flag(&mut self, flag: u64, enabled: bool) {
        if enabled {
            self.opts.experimental_flags |= flag;
        } else {
            self.opts.experimental_flags &= !flag;
        }
    }
}

impl Default for RuntimeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

pub struct Runtime {
    active: bool,
}

impl Runtime {
    pub fn builder() -> RuntimeBuilder {
        RuntimeBuilder::new()
    }

    pub fn init() -> Result<Self> {
        RuntimeBuilder::new().init()
    }

    pub fn run<F>(self, f: F) -> Result<()>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        let handle = task::try_spawn(f)?;
        let run_rc = unsafe { sys::llam_run() };
        let join_result = handle.join();
        self.shutdown();
        if run_rc != 0 {
            return Err(Error::last());
        }
        match join_result {
            Ok(result) => result,
            Err(JoinError::Runtime(error)) => Err(error),
            Err(JoinError::Panic(payload)) => std::panic::resume_unwind(payload),
            Err(JoinError::MissingResult) => Err(Error::from_errno(libc::EIO)),
        }
    }

    pub fn request_stop(&self) -> Result<()> {
        let rc = unsafe { sys::llam_runtime_request_stop() };
        if rc == 0 {
            Ok(())
        } else {
            Err(Error::last())
        }
    }

    pub fn stats(&self) -> Result<RuntimeStats> {
        let mut raw = unsafe { mem::zeroed::<sys::llam_runtime_stats_t>() };
        let rc = unsafe { sys::llam_runtime_collect_stats_ex(&mut raw, mem::size_of_val(&raw)) };
        if rc == 0 {
            Ok(RuntimeStats(raw))
        } else {
            Err(Error::last())
        }
    }

    pub fn shutdown(mut self) {
        self.shutdown_inner();
    }

    fn shutdown_inner(&mut self) {
        if self.active {
            unsafe { sys::llam_runtime_shutdown() };
            self.active = false;
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        self.shutdown_inner();
    }
}

#[derive(Clone, Copy, Debug)]
pub struct RuntimeStats(pub(crate) sys::llam_runtime_stats_t);

impl RuntimeStats {
    pub fn raw(&self) -> &sys::llam_runtime_stats_t {
        &self.0
    }

    pub fn ctx_switches(&self) -> u64 {
        self.0.ctx_switches
    }

    pub fn yields(&self) -> u64 {
        self.0.yields
    }

    pub fn parks(&self) -> u64 {
        self.0.parks
    }

    pub fn wakes(&self) -> u64 {
        self.0.wakes
    }

    pub fn steals(&self) -> u64 {
        self.0.steals
    }

    pub fn migrations(&self) -> u64 {
        self.0.migrations
    }

    pub fn blocking_calls(&self) -> u64 {
        self.0.blocking_calls
    }

    pub fn blocking_completions(&self) -> u64 {
        self.0.blocking_completions
    }

    pub fn io_submits(&self) -> u64 {
        self.0.io_submits
    }

    pub fn io_submit_calls(&self) -> u64 {
        self.0.io_submit_calls
    }

    pub fn io_submit_syscalls(&self) -> u64 {
        self.0.io_submit_syscalls
    }

    pub fn io_completions(&self) -> u64 {
        self.0.io_completions
    }

    pub fn idle_polls(&self) -> u64 {
        self.0.idle_polls
    }

    pub fn idle_spin_loops(&self) -> u64 {
        self.0.idle_spin_loops
    }

    pub fn idle_spin_hits(&self) -> u64 {
        self.0.idle_spin_hits
    }

    pub fn idle_spin_fallbacks(&self) -> u64 {
        self.0.idle_spin_fallbacks
    }

    pub fn idle_spin_ns(&self) -> u64 {
        self.0.idle_spin_ns
    }

    pub fn active_workers(&self) -> u32 {
        self.0.active_workers
    }

    pub fn online_workers(&self) -> u32 {
        self.0.online_workers
    }

    pub fn online_workers_floor(&self) -> u32 {
        self.0.online_workers_floor
    }

    pub fn online_workers_min(&self) -> u32 {
        self.0.online_workers_min
    }

    pub fn online_workers_max(&self) -> u32 {
        self.0.online_workers_max
    }

    pub fn active_nodes(&self) -> u32 {
        self.0.active_nodes
    }

    pub fn dynamic_workers(&self) -> bool {
        self.0.dynamic_workers != 0
    }

    pub fn worker_rings(&self) -> bool {
        self.0.worker_rings != 0
    }

    pub fn worker_rings_multishot(&self) -> bool {
        self.0.worker_rings_multishot != 0
    }

    pub fn lockfree_normq(&self) -> bool {
        self.0.lockfree_normq != 0
    }

    pub fn huge_alloc(&self) -> bool {
        self.0.huge_alloc != 0
    }

    pub fn sqpoll(&self) -> bool {
        self.0.sqpoll != 0
    }

    pub fn queue_overflows(&self) -> u64 {
        self.0.queue_overflows
    }

    pub fn overflow_depth(&self) -> u64 {
        self.0.overflow_depth
    }

    pub fn opaque_block_ns(&self) -> u64 {
        self.0.opaque_block_ns
    }

    pub fn opaque_block_samples(&self) -> u64 {
        self.0.opaque_block_samples
    }

    pub fn opaque_block_max_ns(&self) -> u64 {
        self.0.opaque_block_max_ns
    }

    pub fn opaque_enter_wait_ns(&self) -> u64 {
        self.0.opaque_enter_wait_ns
    }

    pub fn opaque_enter_wait_samples(&self) -> u64 {
        self.0.opaque_enter_wait_samples
    }

    pub fn opaque_enter_wait_max_ns(&self) -> u64 {
        self.0.opaque_enter_wait_max_ns
    }

    pub fn opaque_leave_wait_ns(&self) -> u64 {
        self.0.opaque_leave_wait_ns
    }

    pub fn opaque_leave_wait_samples(&self) -> u64 {
        self.0.opaque_leave_wait_samples
    }

    pub fn opaque_leave_wait_max_ns(&self) -> u64 {
        self.0.opaque_leave_wait_max_ns
    }

    pub fn yield_direct_attempts(&self) -> u64 {
        self.0.yield_direct_attempts
    }

    pub fn yield_direct_fast_hits(&self) -> u64 {
        self.0.yield_direct_fast_hits
    }

    pub fn yield_direct_locked_hits(&self) -> u64 {
        self.0.yield_direct_locked_hits
    }

    pub fn yield_direct_fail_context(&self) -> u64 {
        self.0.yield_direct_fail_context
    }

    pub fn yield_direct_fail_policy(&self) -> u64 {
        self.0.yield_direct_fail_policy
    }

    pub fn yield_direct_fail_no_work(&self) -> u64 {
        self.0.yield_direct_fail_no_work
    }

    pub fn yield_direct_fail_self(&self) -> u64 {
        self.0.yield_direct_fail_self
    }

    pub fn yield_direct_fail_push(&self) -> u64 {
        self.0.yield_direct_fail_push
    }
}

pub fn current_runtime_raw() -> *mut sys::llam_runtime_t {
    unsafe { sys::llam_runtime_default() }
}

pub struct RuntimeHandle {
    raw: *mut sys::llam_runtime_t,
    active: bool,
}

unsafe impl Send for RuntimeHandle {}

impl RuntimeHandle {
    pub fn run(&self) -> Result<()> {
        let rc = unsafe { sys::llam_runtime_run_handle(self.raw) };
        if rc == 0 {
            Ok(())
        } else {
            Err(Error::last())
        }
    }

    pub fn raw(&self) -> *mut sys::llam_runtime_t {
        self.raw
    }

    pub fn destroy(mut self) {
        self.destroy_inner();
    }

    fn destroy_inner(&mut self) {
        if self.active {
            unsafe { sys::llam_runtime_destroy(self.raw) };
            self.active = false;
            self.raw = std::ptr::null_mut();
        }
    }
}

impl Drop for RuntimeHandle {
    fn drop(&mut self) {
        self.destroy_inner();
    }
}