polydat 0.1.0

Polydat — generation kernel for deterministic variate generation in nb-rs (formerly nbrs-variates)
Documentation
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Phase 2: compiled u64-only kernels with flat buffer evaluation.
//!
//! Four monomorphic kernel types, each produced by a distinct compiler
//! path. No runtime branching for optimization strategy — the eval
//! loop is baked in at construction time.
//!
//! | Type | Push (per-node skip) | Pull (cone guard) |
//! |------|---------------------|-------------------|
//! | `CompiledKernelRaw` | — | — |
//! | `CompiledKernelPush` | yes | — |
//! | `CompiledKernelPull` | — | yes |
//! | `CompiledKernelPushPull` | yes | yes |

use std::collections::HashMap;

use crate::node::CompiledU64Op;

/// A single evaluation step in the compiled kernel.
struct CompiledStep {
    op: CompiledU64Op,
    input_slots: Vec<usize>,
    output_slots: Vec<usize>,
}

/// Common fields shared by all kernel variants.
struct KernelCore {
    buffer: Vec<u64>,
    coord_count: usize,
    steps: Vec<CompiledStep>,
    output_map: HashMap<String, usize>,
    gather_buf: Vec<u64>,
    scatter_buf: Vec<u64>,
}

/// Build kernel core from raw step data.
fn build_core(
    coord_count: usize,
    total_slots: usize,
    steps: Vec<(CompiledU64Op, Vec<usize>, Vec<usize>)>,
    output_map: HashMap<String, usize>,
) -> KernelCore {
    let max_inputs = steps.iter().map(|s| s.1.len()).max().unwrap_or(0);
    let max_outputs = steps.iter().map(|s| s.2.len()).max().unwrap_or(0);
    let compiled_steps: Vec<CompiledStep> = steps.into_iter()
        .map(|(op, input_slots, output_slots)| CompiledStep { op, input_slots, output_slots })
        .collect();
    KernelCore {
        buffer: vec![0u64; total_slots],
        coord_count,
        steps: compiled_steps,
        output_map,
        gather_buf: vec![0u64; max_inputs],
        scatter_buf: vec![0u64; max_outputs],
    }
}

/// Compute per-slot provenance bitmasks from input_dependents.
///
/// Returns `slot_provenance[slot]` = bitmask of which inputs affect
/// that buffer slot. Used by pull-side cone guard.
fn compute_slot_provenance(
    coord_count: usize,
    total_slots: usize,
    input_dependents: &[Vec<usize>],
    steps: &[CompiledStep],
) -> Vec<u64> {
    let step_count = steps.len();
    let mut step_prov = vec![0u64; step_count];
    for (input_idx, deps) in input_dependents.iter().enumerate() {
        for &step_idx in deps {
            if step_idx < step_count {
                step_prov[step_idx] |= 1u64 << input_idx;
            }
        }
    }
    let mut slot_provenance = vec![0u64; total_slots];
    for i in 0..coord_count.min(64) {
        slot_provenance[i] = 1u64 << i;
    }
    for (step_idx, step) in steps.iter().enumerate() {
        for &slot in &step.output_slots {
            if slot < slot_provenance.len() {
                slot_provenance[slot] = step_prov[step_idx];
            }
        }
    }
    slot_provenance
}

// ── Shared accessor methods ────────────────────────────────────

macro_rules! kernel_accessors {
    () => {
        pub fn coord_count(&self) -> usize { self.core.coord_count }

        pub fn resolve_output(&self, name: &str) -> Option<usize> {
            self.core.output_map.get(name).copied()
        }

        pub fn output_names(&self) -> Vec<&str> {
            self.core.output_map.keys().map(|s| s.as_str()).collect()
        }

        /// Read an output by pre-resolved slot index.
        #[inline]
        pub fn get_slot(&self, slot: usize) -> u64 {
            self.core.buffer[slot]
        }

        /// Read a named output variate after `eval()`.
        #[inline]
        pub fn get(&self, name: &str) -> u64 {
            self.core.buffer[self.core.output_map[name]]
        }
    };
}

/// Run all steps unconditionally (no clean checks).
#[inline]
fn eval_all_steps(core: &mut KernelCore) {
    for step in &core.steps {
        for (i, &s) in step.input_slots.iter().enumerate() {
            core.gather_buf[i] = core.buffer[s];
        }
        (step.op)(
            &core.gather_buf[..step.input_slots.len()],
            &mut core.scatter_buf[..step.output_slots.len()],
        );
        for (i, &s) in step.output_slots.iter().enumerate() {
            core.buffer[s] = core.scatter_buf[i];
        }
    }
}

// ═══════════════════════════════════════════════════════════════
// Raw: no provenance, no cone guard. Eval runs all steps.
// ═══════════════════════════════════════════════════════════════

pub struct CompiledKernelRaw {
    core: KernelCore,
}

impl CompiledKernelRaw {
    pub(crate) fn new(
        coord_count: usize,
        total_slots: usize,
        steps: Vec<(CompiledU64Op, Vec<usize>, Vec<usize>)>,
        output_map: HashMap<String, usize>,
    ) -> Self {
        Self { core: build_core(coord_count, total_slots, steps, output_map) }
    }

    #[inline]
    pub fn eval(&mut self, coords: &[u64]) {
        self.core.buffer[..self.core.coord_count.min(coords.len())]
            .copy_from_slice(&coords[..self.core.coord_count.min(coords.len())]);
        eval_all_steps(&mut self.core);
    }

    /// Eval + return a specific slot. No cone guard — always evaluates.
    #[inline]
    pub fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
        self.eval(coords);
        self.core.buffer[slot]
    }

    kernel_accessors!();
}

// ═══════════════════════════════════════════════════════════════
// Push: per-node dirty skip, no cone guard.
// set_inputs marks dependents dirty. eval skips clean steps.
// ═══════════════════════════════════════════════════════════════

pub struct CompiledKernelPush {
    core: KernelCore,
    node_clean: Vec<bool>,
    input_dependents: Vec<Vec<usize>>,
}

impl CompiledKernelPush {
    pub(crate) fn new(
        coord_count: usize,
        total_slots: usize,
        steps: Vec<(CompiledU64Op, Vec<usize>, Vec<usize>)>,
        output_map: HashMap<String, usize>,
        input_dependents: Vec<Vec<usize>>,
    ) -> Self {
        let step_count = steps.len();
        Self {
            core: build_core(coord_count, total_slots, steps, output_map),
            node_clean: vec![false; step_count],
            input_dependents,
        }
    }

    #[inline]
    fn set_inputs(&mut self, coords: &[u64]) {
        for i in 0..coords.len().min(self.core.coord_count) {
            if self.core.buffer[i] != coords[i] {
                self.core.buffer[i] = coords[i];
                if i < self.input_dependents.len() {
                    for &step_idx in &self.input_dependents[i] {
                        self.node_clean[step_idx] = false;
                    }
                }
            }
        }
    }

    #[inline]
    pub fn eval(&mut self, coords: &[u64]) {
        self.set_inputs(coords);
        for (step_idx, step) in self.core.steps.iter().enumerate() {
            if self.node_clean[step_idx] { continue; }
            for (i, &s) in step.input_slots.iter().enumerate() {
                self.core.gather_buf[i] = self.core.buffer[s];
            }
            (step.op)(
                &self.core.gather_buf[..step.input_slots.len()],
                &mut self.core.scatter_buf[..step.output_slots.len()],
            );
            for (i, &s) in step.output_slots.iter().enumerate() {
                self.core.buffer[s] = self.core.scatter_buf[i];
            }
            self.node_clean[step_idx] = true;
        }
    }

    /// Eval + return a specific slot. No cone guard — always enters eval loop.
    #[inline]
    pub fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
        self.eval(coords);
        self.core.buffer[slot]
    }

    kernel_accessors!();
}

// ═══════════════════════════════════════════════════════════════
// Pull: cone guard only, no per-node skip.
// set_inputs tracks changed_mask. eval_for_slot checks cone
// then runs ALL steps if dirty.
// ═══════════════════════════════════════════════════════════════

pub struct CompiledKernelPull {
    core: KernelCore,
    slot_provenance: Vec<u64>,
    changed_mask: u64,
}

impl CompiledKernelPull {
    pub(crate) fn new(
        coord_count: usize,
        total_slots: usize,
        steps: Vec<(CompiledU64Op, Vec<usize>, Vec<usize>)>,
        output_map: HashMap<String, usize>,
        input_dependents: &[Vec<usize>],
    ) -> Self {
        let core = build_core(coord_count, total_slots, steps, output_map);
        let slot_provenance = compute_slot_provenance(
            coord_count, total_slots, input_dependents, &core.steps);
        Self {
            core,
            slot_provenance,
            changed_mask: u64::MAX, // all dirty initially
        }
    }

    /// Track which inputs changed (for cone guard). Does NOT mark
    /// individual nodes dirty — there is no per-node clean state.
    #[inline]
    fn set_inputs(&mut self, coords: &[u64]) {
        self.changed_mask = 0;
        for i in 0..coords.len().min(self.core.coord_count) {
            if self.core.buffer[i] != coords[i] {
                self.core.buffer[i] = coords[i];
                self.changed_mask |= 1u64 << i;
            }
        }
    }

    /// Evaluate eagerly (no cone guard). Runs all steps.
    #[inline]
    pub fn eval(&mut self, coords: &[u64]) {
        self.set_inputs(coords);
        eval_all_steps(&mut self.core);
    }

    /// Cone guard: if the output's cone is clean, skip eval entirely.
    /// Otherwise run ALL steps (no per-node skip).
    #[inline]
    pub fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
        self.set_inputs(coords);
        if slot < self.slot_provenance.len() {
            if self.slot_provenance[slot] & self.changed_mask == 0 {
                return self.core.buffer[slot];
            }
        }
        eval_all_steps(&mut self.core);
        self.core.buffer[slot]
    }

    kernel_accessors!();
}

// ═══════════════════════════════════════════════════════════════
// PushPull: push-side per-node skip + pull-side cone guard.
// Full optimization.
// ═══════════════════════════════════════════════════════════════

pub struct CompiledKernelPushPull {
    core: KernelCore,
    node_clean: Vec<bool>,
    input_dependents: Vec<Vec<usize>>,
    slot_provenance: Vec<u64>,
    changed_mask: u64,
}

impl CompiledKernelPushPull {
    pub(crate) fn new(
        coord_count: usize,
        total_slots: usize,
        steps: Vec<(CompiledU64Op, Vec<usize>, Vec<usize>)>,
        output_map: HashMap<String, usize>,
        input_dependents: Vec<Vec<usize>>,
    ) -> Self {
        let step_count = steps.len();
        let core = build_core(coord_count, total_slots, steps, output_map);
        let slot_provenance = compute_slot_provenance(
            coord_count, total_slots, &input_dependents, &core.steps);
        Self {
            core,
            node_clean: vec![false; step_count],
            input_dependents,
            slot_provenance,
            changed_mask: u64::MAX,
        }
    }

    #[inline]
    fn set_inputs(&mut self, coords: &[u64]) {
        self.changed_mask = 0;
        for i in 0..coords.len().min(self.core.coord_count) {
            if self.core.buffer[i] != coords[i] {
                self.core.buffer[i] = coords[i];
                self.changed_mask |= 1u64 << i;
                if i < self.input_dependents.len() {
                    for &step_idx in &self.input_dependents[i] {
                        self.node_clean[step_idx] = false;
                    }
                }
            }
        }
    }

    /// Eval with push-side skip (no cone guard).
    #[inline]
    pub fn eval(&mut self, coords: &[u64]) {
        self.set_inputs(coords);
        for (step_idx, step) in self.core.steps.iter().enumerate() {
            if self.node_clean[step_idx] { continue; }
            for (i, &s) in step.input_slots.iter().enumerate() {
                self.core.gather_buf[i] = self.core.buffer[s];
            }
            (step.op)(
                &self.core.gather_buf[..step.input_slots.len()],
                &mut self.core.scatter_buf[..step.output_slots.len()],
            );
            for (i, &s) in step.output_slots.iter().enumerate() {
                self.core.buffer[s] = self.core.scatter_buf[i];
            }
            self.node_clean[step_idx] = true;
        }
    }

    /// Cone guard + push-side skip: the full optimization.
    #[inline]
    pub fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
        self.set_inputs(coords);
        if slot < self.slot_provenance.len() {
            if self.slot_provenance[slot] & self.changed_mask == 0 {
                return self.core.buffer[slot];
            }
        }
        for (step_idx, step) in self.core.steps.iter().enumerate() {
            if self.node_clean[step_idx] { continue; }
            for (i, &s) in step.input_slots.iter().enumerate() {
                self.core.gather_buf[i] = self.core.buffer[s];
            }
            (step.op)(
                &self.core.gather_buf[..step.input_slots.len()],
                &mut self.core.scatter_buf[..step.output_slots.len()],
            );
            for (i, &s) in step.output_slots.iter().enumerate() {
                self.core.buffer[s] = self.core.scatter_buf[i];
            }
            self.node_clean[step_idx] = true;
        }
        self.core.buffer[slot]
    }

    kernel_accessors!();
}