Skip to main content

polydat_nodes/
vector_math.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Element-wise vector math nodes (type_system_alignment.md §8.2).
5//!
6//! These are the first compute-shaped (rather than I/O-shaped)
7//! consumers of the typed-vector family: perturbing query vectors,
8//! computing ground-truth distances in evaluations, normalizing
9//! embeddings. On `jit` builds the f32 hot loops execute through
10//! the cranelift-SIMD kernels (`compile::jit::simd` — F32X4
11//! chunked with scalar tails); without `jit`, or if host ISA
12//! construction fails, the scalar reference loops below run
13//! instead. SIMD accumulation reassociates float addition, so dot
14//! products may differ from the scalar reference in the final
15//! ulps — both orders are equally valid IEEE 754 sums.
16//!
17//! Length mismatches panic with both lengths named: silently
18//! truncating to the shorter operand would corrupt distance
19//! semantics ("never ignore silently").
20
21use polydat::ast::PortType;
22use polydat::dsl::registry::{Overload, OverloadForm};
23pub use polydat::numeric::vector::{
24    add_f32, add_f32_into, check_lens, cosine_f32, dot_f32, dot_scalar, hash_vec_into, l2sq_f32,
25    l2sq_scalar, lid_mle_of, norm_f32_into, scale_f32, scale_f32_into, xxhash3_vec_into,
26};
27
28// ── Library nodes ──────────────────────────────────────────────
29//
30// Each node over vector operands has an f32 and an f64 form, and its
31// unsuffixed name is an overload of the two
32// (`polydat::dsl::registry::Overload`): a call builds the form its
33// operands' types agree with, and operands agreeing with neither reach
34// the f32 form through the assembler's adapters, as the unsuffixed
35// name did before it had an f64 form.
36
37/// `vec_add_f32(a, b)` — element-wise sum of two f32 vectors.
38/// Panics when the lengths differ.
39#[polydat::polydat_node(category = Arithmetic)]
40fn vec_add_f32(a: &[f32], b: &[f32]) -> Vec<f32> {
41    check_lens("vec_add_f32", a.len(), b.len());
42    add_f32(a, b)
43}
44
45/// `vec_add_f64(a, b)` — element-wise sum of two f64 vectors.
46/// Panics when the lengths differ.
47#[polydat::polydat_node(category = Arithmetic)]
48fn vec_add_f64(a: &[f64], b: &[f64]) -> Vec<f64> {
49    check_lens("vec_add_f64", a.len(), b.len());
50    a.iter().zip(b).map(|(x, y)| x + y).collect()
51}
52
53/// `vec_scale_f32(a, k)` — multiply every element of an f32 vector by
54/// scalar `k` (applied at f32 precision).
55#[polydat::polydat_node(category = Arithmetic)]
56fn vec_scale_f32(a: &[f32], k: f64) -> Vec<f32> {
57    scale_f32(a, k as f32)
58}
59
60/// `vec_scale_f64(a, k)` — multiply every element of an f64 vector by
61/// scalar `k`.
62#[polydat::polydat_node(category = Arithmetic)]
63fn vec_scale_f64(a: &[f64], k: f64) -> Vec<f64> {
64    a.iter().map(|x| x * k).collect()
65}
66
67// ── Distances ──────────────────────────────────────────────────
68
69/// `vec_dot_f32(a, b)` — dot product of two f32 vectors, widened to
70/// f64 on the output wire. Panics when the lengths differ.
71#[polydat::polydat_node(category = Arithmetic)]
72fn vec_dot_f32(a: &[f32], b: &[f32]) -> f64 {
73    check_lens("vec_dot_f32", a.len(), b.len());
74    dot_f32(a, b) as f64
75}
76
77/// `vec_dot_f64(a, b)` — dot product of two f64 vectors. Panics when
78/// the lengths differ.
79#[polydat::polydat_node(category = Arithmetic)]
80fn vec_dot_f64(a: &[f64], b: &[f64]) -> f64 {
81    check_lens("vec_dot_f64", a.len(), b.len());
82    a.iter().zip(b).map(|(x, y)| x * y).sum()
83}
84
85/// `vec_l2_f32(a, b)` — Euclidean (L2) distance between two f32
86/// vectors. Panics when the lengths differ.
87#[polydat::polydat_node(category = Arithmetic)]
88fn vec_l2_f32(a: &[f32], b: &[f32]) -> f64 {
89    check_lens("vec_l2_f32", a.len(), b.len());
90    (l2sq_f32(a, b) as f64).sqrt()
91}
92
93/// `vec_l2_f64(a, b)` — Euclidean (L2) distance between two f64
94/// vectors. Panics when the lengths differ.
95#[polydat::polydat_node(category = Arithmetic)]
96fn vec_l2_f64(a: &[f64], b: &[f64]) -> f64 {
97    check_lens("vec_l2_f64", a.len(), b.len());
98    a.iter()
99        .zip(b)
100        .map(|(x, y)| (x - y) * (x - y))
101        .sum::<f64>()
102        .sqrt()
103}
104
105/// `vec_cosine_f32(a, b)` — cosine similarity of two f32 vectors:
106/// `dot(a,b) / (|a| * |b|)`. Returns 0.0 when either vector has
107/// zero magnitude (the conventional degenerate-case value: no
108/// direction, no similarity). Panics when the lengths differ.
109#[polydat::polydat_node(category = Arithmetic)]
110fn vec_cosine_f32(a: &[f32], b: &[f32]) -> f64 {
111    check_lens("vec_cosine_f32", a.len(), b.len());
112    cosine_f32(a, b)
113}
114
115/// `vec_cosine_f64(a, b)` — cosine similarity of two f64 vectors:
116/// `dot(a,b) / (|a| * |b|)`, and 0.0 when either vector has zero
117/// magnitude, as `vec_cosine_f32` answers. Panics when the lengths
118/// differ.
119#[polydat::polydat_node(category = Arithmetic)]
120fn vec_cosine_f64(a: &[f64], b: &[f64]) -> f64 {
121    check_lens("vec_cosine_f64", a.len(), b.len());
122    let (dot, aa, bb) = dot_and_squares(a, b);
123    if aa == 0.0 || bb == 0.0 {
124        0.0
125    } else {
126        dot / (aa.sqrt() * bb.sqrt())
127    }
128}
129
130/// `vec_distance_f32(metric, a, b)` — the distance between two f32
131/// vectors as a dataset's ground truth records it, accumulated in
132/// f64. Smaller is closer under every metric:
133///
134/// - `EUCLIDEAN`: squared Euclidean distance (the square root is
135///   monotonic, so ground truth leaves it out);
136/// - `COSINE`: `1 − a·b / (|a|·|b|)`, and `1.0` when either operand
137///   has zero length;
138/// - `DOT_PRODUCT`: `−a·b`, so a larger inner product is closer;
139/// - `MANHATTAN`: `Σ|aᵢ − bᵢ|`.
140///
141/// `metric` is a name as `dataset_distance_function` returns it, so a
142/// host recomputes a stored neighbor distance with
143/// `vec_distance(dataset_distance_function(group), query, base)`.
144/// Any other name panics naming it, as do differing lengths: a
145/// distance under a guessed metric would make every comparison
146/// against the stored one meaningless.
147#[polydat::polydat_node(category = Arithmetic)]
148fn vec_distance_f32(metric: &str, a: &[f32], b: &[f32]) -> f64 {
149    ground_truth_distance("vec_distance_f32", metric, a, b)
150}
151
152/// `vec_distance_f64(metric, a, b)` — the distance between two f64
153/// vectors as a dataset's ground truth records it, under the metrics
154/// and conventions of `vec_distance_f32`.
155#[polydat::polydat_node(category = Arithmetic)]
156fn vec_distance_f64(metric: &str, a: &[f64], b: &[f64]) -> f64 {
157    ground_truth_distance("vec_distance_f64", metric, a, b)
158}
159
160/// The distance `metric` puts between `a` and `b`, smaller being
161/// closer, accumulated in f64: the body of the `vec_distance` forms,
162/// which `node` names in a panic.
163fn ground_truth_distance<T: Copy + Into<f64>>(node: &str, metric: &str, a: &[T], b: &[T]) -> f64 {
164    check_lens(node, a.len(), b.len());
165    let pairs = || a.iter().zip(b).map(|(x, y)| ((*x).into(), (*y).into()));
166    match metric {
167        "EUCLIDEAN" => pairs().map(|(x, y): (f64, f64)| (x - y) * (x - y)).sum(),
168        "COSINE" => {
169            let (dot, aa, bb) = dot_and_squares(a, b);
170            if aa == 0.0 || bb == 0.0 {
171                1.0
172            } else {
173                1.0 - dot / (aa.sqrt() * bb.sqrt())
174            }
175        }
176        "DOT_PRODUCT" => -pairs().map(|(x, y): (f64, f64)| x * y).sum::<f64>(),
177        "MANHATTAN" => pairs().map(|(x, y): (f64, f64)| (x - y).abs()).sum(),
178        other => panic!(
179            "{node}: unknown metric {other:?}; expected EUCLIDEAN, COSINE, DOT_PRODUCT or MANHATTAN"
180        ),
181    }
182}
183
184/// `(a·b, a·a, b·b)` accumulated in f64, for the cosine forms.
185fn dot_and_squares<T: Copy + Into<f64>>(a: &[T], b: &[T]) -> (f64, f64, f64) {
186    a.iter()
187        .zip(b)
188        .map(|(x, y)| ((*x).into(), (*y).into()))
189        .fold((0.0, 0.0, 0.0), |(d, aa, bb), (x, y): (f64, f64)| {
190            (d + x * y, aa + x * x, bb + y * y)
191        })
192}
193
194/// The overload `name` of an f32 form and an f64 form, each with the
195/// wire types it takes.
196macro_rules! float_overload {
197    ($name:literal: [$($w32:ident),*] => $f32:literal, [$($w64:ident),*] => $f64:literal) => {
198        polydat::inventory::submit! {
199            Overload {
200                name: $name,
201                forms: &[
202                    OverloadForm { wires: &[$(PortType::$w32),*], func: $f32 },
203                    OverloadForm { wires: &[$(PortType::$w64),*], func: $f64 },
204                ],
205            }
206        }
207    };
208}
209
210float_overload!("vec_add": [VecF32, VecF32] => "vec_add_f32", [VecF64, VecF64] => "vec_add_f64");
211float_overload!("vec_scale": [VecF32, F64] => "vec_scale_f32", [VecF64, F64] => "vec_scale_f64");
212float_overload!("vec_norm": [VecF32] => "vec_norm_f32", [VecF64] => "vec_norm_f64");
213float_overload!("vec_dot": [VecF32, VecF32] => "vec_dot_f32", [VecF64, VecF64] => "vec_dot_f64");
214float_overload!("vec_l2": [VecF32, VecF32] => "vec_l2_f32", [VecF64, VecF64] => "vec_l2_f64");
215float_overload!("vec_cosine": [VecF32, VecF32] => "vec_cosine_f32", [VecF64, VecF64] => "vec_cosine_f64");
216float_overload!(
217    "vec_distance": [Str, VecF32, VecF32] => "vec_distance_f32",
218    [Str, VecF64, VecF64] => "vec_distance_f64"
219);
220
221/// `vec_norm_f32(a)` — scale an f32 vector to unit L2 magnitude.
222/// A zero vector passes through unchanged (there is no direction
223/// to normalize onto, and emitting NaNs would poison downstream
224/// distance math silently).
225#[polydat::polydat_node(category = Arithmetic)]
226fn vec_norm_f32(a: &[f32]) -> Vec<f32> {
227    let mut out = Vec::new();
228    norm_f32_into(a, &mut out);
229    out
230}
231
232/// `vec_norm_f64(a)` — scale an f64 vector to unit L2 magnitude, a
233/// zero vector passing through unchanged as `vec_norm_f32` passes it.
234#[polydat::polydat_node(category = Arithmetic)]
235fn vec_norm_f64(a: &[f64]) -> Vec<f64> {
236    let mag = a.iter().map(|x| x * x).sum::<f64>().sqrt();
237    if mag == 0.0 {
238        a.to_vec()
239    } else {
240        a.iter().map(|x| x / mag).collect()
241    }
242}
243
244/// `lid_mle(distances, k)` — Levina–Bickel maximum-likelihood estimate of
245/// the **local intrinsic dimensionality** at one query point, from its
246/// sorted ground-truth nearest-neighbor distances.
247///
248/// Given ascending distances `r_1 ≤ … ≤ r_k` to the `k` nearest neighbors,
249///
250/// ```text
251///     d̂ = m / Σ_{j=1..m} ln(r_k / r_j)        (m = number of valid terms)
252/// ```
253///
254/// the standard MLE (Levina & Bickel, NIPS 2004) with `r_k` as the cutoff
255/// radius. `k` is clamped to the available length. Terms with a
256/// non-positive `r_j` (exact duplicates / self-matches at distance 0, where
257/// `ln(r_k/r_j)` is undefined) are skipped — the conventional handling.
258/// Returns `0.0` for a degenerate query (fewer than one valid term, or a
259/// non-positive log-sum, e.g. all-duplicate neighbors) so the caller can
260/// filter it out of the aggregate.
261///
262/// Reporting the *distribution* of this per-query estimate (mean / p50 /
263/// p90) characterizes both the intrinsic dimension and its heterogeneity —
264/// the quantity that governs whether a 1-D locality ordering can work (a
265/// low, tight LID favors it; a high or skewed LID does not).
266///
267/// ASSUMES `distances` are true metric distances in ascending order (the
268/// dataset's `neighbor_distances` / `filtered_neighbor_distances` facet).
269/// If that facet stores *squared* distances the estimate is scaled by ½
270/// (double it); if it stores *similarities* (higher = closer) the result is
271/// meaningless — validate against the dataset's metric first.
272#[polydat::polydat_node(category = Arithmetic)]
273fn lid_mle(distances: &[f32], k: f64) -> f64 {
274    lid_mle_of(distances, k)
275}
276
277/// `hash_vec(seed, dim)` — deterministic synthetic f32 vector:
278/// element `i` is the SplitMix64 hash of `(seed, i)` mapped into
279/// `[-1, 1)`. The canonical generator for synthetic embeddings —
280/// equal seeds always produce the identical vector, so dataset-
281/// free vector workloads stay replayable. Pairs with `vec_norm`
282/// for unit vectors.
283#[polydat::polydat_node(category = Hashing)]
284fn hash_vec(seed: u64, dim: u64) -> Vec<f32> {
285    let mut out = Vec::new();
286    hash_vec_into(seed, dim, &mut out);
287    out
288}
289
290/// `xxhash3_vec(seed, dim)` — deterministic synthetic f32 vector using xxHash3.
291#[polydat::polydat_node(category = Hashing)]
292fn xxhash3_vec(seed: u64, dim: u64) -> Vec<f32> {
293    let mut out = Vec::new();
294    xxhash3_vec_into(seed, dim, &mut out);
295    out
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use polydat::ast::{PolydatNode, SliceArc, Value};
302
303    fn vecv(v: Vec<f32>) -> Value {
304        Value::VecF32(SliceArc::from_vec(v))
305    }
306
307    fn test_vec(n: usize, seed: u64) -> Vec<f32> {
308        (0..n)
309            .map(|i| {
310                let h = xxhash_rust::xxh3::xxh3_64(&(seed ^ i as u64).to_le_bytes());
311                (h as f64 / u64::MAX as f64 * 2.0 - 1.0) as f32
312            })
313            .collect()
314    }
315
316    fn eval2<N: PolydatNode>(node: &N, a: Vec<f32>, b: Vec<f32>) -> Value {
317        let mut out = [Value::None];
318        node.eval(&[vecv(a), vecv(b)], &mut out);
319        out[0].clone()
320    }
321
322    #[test]
323    fn vec_math_matches_scalar_reference() {
324        // 1029 = 257 SIMD chunks + 1 tail element.
325        let a = test_vec(1029, 1);
326        let b = test_vec(1029, 2);
327
328        let dot = eval2(&VecDotF32::new(), a.clone(), b.clone()).as_f64();
329        let dot_ref = dot_scalar(&a, &b) as f64;
330        assert!((dot - dot_ref).abs() / dot_ref.abs().max(1e-6) < 1e-4);
331
332        let l2 = eval2(&VecL2F32::new(), a.clone(), b.clone()).as_f64();
333        let l2_ref = (l2sq_scalar(&a, &b) as f64).sqrt();
334        assert!((l2 - l2_ref).abs() / l2_ref.max(1e-6) < 1e-4);
335
336        let sum = eval2(&VecAddF32::new(), a.clone(), b.clone());
337        let sum = sum.as_vec_f32();
338        for i in 0..a.len() {
339            assert_eq!(sum[i], a[i] + b[i], "vec_add lane {i}");
340        }
341
342        let cos_self = eval2(&VecCosineF32::new(), a.clone(), a.clone()).as_f64();
343        assert!((cos_self - 1.0).abs() < 1e-4, "self-cosine = {cos_self}");
344    }
345
346    fn vecd(v: Vec<f32>) -> Value {
347        Value::VecF64(SliceArc::from_vec(v.into_iter().map(f64::from).collect()))
348    }
349
350    /// `node` over `a` and `b` as f32 vectors and as f64 vectors: the two
351    /// forms of one distance, with any leading wires in `lead`.
352    fn both_forms<N32: PolydatNode, N64: PolydatNode>(
353        f32_form: &N32,
354        f64_form: &N64,
355        lead: &[Value],
356        a: Vec<f32>,
357        b: Vec<f32>,
358    ) -> (f64, f64) {
359        let eval = |node: &dyn PolydatNode, a: Value, b: Value| {
360            let mut ins = lead.to_vec();
361            ins.extend([a, b]);
362            let mut out = [Value::None];
363            node.eval(&ins, &mut out);
364            out[0].as_f64()
365        };
366        (
367            eval(f32_form, vecv(a.clone()), vecv(b.clone())),
368            eval(f64_form, vecd(a), vecd(b)),
369        )
370    }
371
372    /// The f64 forms compute what the f32 forms do, on vectors whose
373    /// products and sums are exact in both widths.
374    #[test]
375    fn the_f64_forms_agree_with_the_f32_forms() {
376        let (a, b) = (vec![1.0, 2.0, 3.0], vec![4.0, -2.0, 2.0]);
377        let (d32, d64) = both_forms(
378            &VecDotF32::new(),
379            &VecDotF64::new(),
380            &[],
381            a.clone(),
382            b.clone(),
383        );
384        assert_eq!((d32, d64), (6.0, 6.0));
385        let (l32, l64) = both_forms(
386            &VecL2F32::new(),
387            &VecL2F64::new(),
388            &[],
389            a.clone(),
390            b.clone(),
391        );
392        assert_eq!((l32, l64), (26f64.sqrt(), 26f64.sqrt()));
393        let (c32, c64) = both_forms(
394            &VecCosineF32::new(),
395            &VecCosineF64::new(),
396            &[],
397            vec![3.0, 4.0],
398            vec![4.0, 3.0],
399        );
400        assert_eq!((c32, c64), (24.0 / 25.0, 24.0 / 25.0));
401        let (z32, z64) = both_forms(
402            &VecCosineF32::new(),
403            &VecCosineF64::new(),
404            &[],
405            vec![0.0, 0.0],
406            vec![4.0, 3.0],
407        );
408        assert_eq!((z32, z64), (0.0, 0.0));
409    }
410
411    /// `vec_distance` under `metric` in both forms, which must agree.
412    fn distance(metric: &str, a: Vec<f32>, b: Vec<f32>) -> f64 {
413        let (d32, d64) = both_forms(
414            &VecDistanceF32::new(),
415            &VecDistanceF64::new(),
416            &[Value::Str(metric.into())],
417            a,
418            b,
419        );
420        assert_eq!(d32, d64, "{metric}: the f32 and f64 forms differ");
421        d32
422    }
423
424    /// Each metric in the ground-truth convention, smaller is closer,
425    /// on vectors whose distances are exact in binary.
426    #[test]
427    fn vec_distance_follows_the_ground_truth_convention() {
428        let (a, b) = (vec![1.0, 2.0, 0.0], vec![4.0, -2.0, 0.0]);
429        assert_eq!(distance("EUCLIDEAN", a.clone(), b.clone()), 25.0);
430        assert_eq!(distance("MANHATTAN", a.clone(), b.clone()), 7.0);
431        assert_eq!(
432            distance("DOT_PRODUCT", vec![1.0, 2.0], vec![3.0, 4.0]),
433            -11.0
434        );
435        assert_eq!(
436            distance("COSINE", vec![3.0, 4.0], vec![4.0, 3.0]),
437            1.0 - 24.0 / 25.0
438        );
439        assert_eq!(distance("COSINE", vec![0.0, 0.0], vec![4.0, 3.0]), 1.0);
440        // An f32 sift-scale distance is exact: integer coordinates.
441        assert_eq!(
442            distance("EUCLIDEAN", vec![0.0; 2], vec![200.0, 207.0]),
443            82849.0
444        );
445    }
446
447    #[test]
448    #[should_panic(expected = "unknown metric \"euclidean\"")]
449    fn vec_distance_refuses_an_unknown_metric() {
450        distance("euclidean", vec![1.0], vec![2.0]);
451    }
452
453    #[test]
454    fn vec_scale_and_norm() {
455        let a = test_vec(37, 3);
456        let mut out = [Value::None];
457        VecScaleF32::new().eval(&[vecv(a.clone()), Value::F64(2.0)], &mut out);
458        let scaled = out[0].as_vec_f32();
459        for i in 0..a.len() {
460            assert_eq!(scaled[i], a[i] * 2.0, "vec_scale lane {i}");
461        }
462
463        let mut out = [Value::None];
464        VecNormF32::new().eval(&[vecv(a.clone())], &mut out);
465        let unit = out[0].as_vec_f32().to_vec();
466        let mag = (dot_scalar(&unit, &unit) as f64).sqrt();
467        assert!((mag - 1.0).abs() < 1e-4, "norm magnitude = {mag}");
468
469        // Zero vector passes through unchanged.
470        let mut out = [Value::None];
471        VecNormF32::new().eval(&[vecv(vec![0.0; 4])], &mut out);
472        assert_eq!(out[0].as_vec_f32(), &[0.0, 0.0, 0.0, 0.0]);
473    }
474
475    #[test]
476    fn lid_mle_matches_closed_form_and_handles_degenerate() {
477        // r_j = e^{j}, j=0..9 → ln(r_k/r_j) = 9-j; Σ_{j=0}^{8}(9-j)=45,
478        // 9 valid terms → d̂ = 9/45 = 0.2. Deterministic arithmetic check.
479        let dists: Vec<f32> = (0..10).map(|j| (j as f32).exp()).collect();
480        let mut out = [Value::None];
481        LidMle::new().eval(&[vecv(dists), Value::F64(10.0)], &mut out);
482        assert!(
483            (out[0].as_f64() - 0.2).abs() < 1e-4,
484            "got {}",
485            out[0].as_f64()
486        );
487
488        // Fewer than 2 distances → degenerate → 0.0.
489        let mut out = [Value::None];
490        LidMle::new().eval(&[vecv(vec![1.0]), Value::F64(10.0)], &mut out);
491        assert_eq!(out[0].as_f64(), 0.0);
492
493        // All-zero (duplicate) neighbors, r_k = 0 → degenerate → 0.0.
494        let mut out = [Value::None];
495        LidMle::new().eval(&[vecv(vec![0.0, 0.0, 0.0]), Value::F64(3.0)], &mut out);
496        assert_eq!(out[0].as_f64(), 0.0);
497
498        // Zero-distance self-match at r_1 is skipped, not fatal: distances
499        // [0, e, e^2] with k=3 → r_k=e^2 (ln=2), only r_2=e (ln=1) valid →
500        // 1 term, logsum=1 → d̂ = 1.0.
501        let mut out = [Value::None];
502        let d: Vec<f32> = vec![
503            0.0,
504            std::f32::consts::E,
505            std::f32::consts::E * std::f32::consts::E,
506        ];
507        LidMle::new().eval(&[vecv(d), Value::F64(3.0)], &mut out);
508        assert!(
509            (out[0].as_f64() - 1.0).abs() < 1e-4,
510            "got {}",
511            out[0].as_f64()
512        );
513    }
514
515    #[test]
516    fn hash_vec_is_deterministic_and_seed_sensitive() {
517        let mut out = [Value::None];
518        HashVec::new().eval(&[Value::U64(7), Value::U64(16)], &mut out);
519        let v1 = out[0].as_vec_f32().to_vec();
520        let mut out = [Value::None];
521        HashVec::new().eval(&[Value::U64(7), Value::U64(16)], &mut out);
522        assert_eq!(v1, out[0].as_vec_f32(), "same seed must reproduce");
523        let mut out = [Value::None];
524        HashVec::new().eval(&[Value::U64(8), Value::U64(16)], &mut out);
525        assert_ne!(v1, out[0].as_vec_f32(), "different seed must differ");
526        assert_eq!(v1.len(), 16);
527        assert!(v1.iter().all(|x| (-1.0..1.0).contains(x)));
528    }
529
530    /// §8.4 layer 3 end-to-end: a vector dataflow (synthetic
531    /// producer → element-wise math → horizontal reduce) rides
532    /// compiled kernels via the (ptr, len) slot protocol with
533    /// kernel-owned scratch, and must match typed eval. The same
534    /// flow through the hybrid kernel runs the scalar segments as
535    /// native JIT and the slice ops as slot closures (whose
536    /// bodies already execute the cranelift-SIMD kernels).
537    #[test]
538    fn vec_flow_rides_compiled_kernels() {
539        let src = r#"
540            input cycle: u64
541            a := hash_vec(cycle, 37)
542            b := hash_vec(hash(cycle), 37)
543            s := vec_add(a, b)
544            out := vec_dot(s, b)
545        "#;
546        let mut p1 = polydat::dsl::compile_polydat(src).unwrap();
547
548        let asm = polydat::dsl::compile::compile_polydat_to_assembler(src).unwrap();
549        let mut p2 = asm
550            .compile_slots(polydat_core::Engine::Closures(
551                polydat_core::Provenance::Raw,
552            ))
553            .expect("slice-bearing nodes are P2-eligible via compiled_slot");
554
555        for cycle in [0u64, 7, 0xFEED] {
556            p1.set_inputs(&[cycle]);
557            let want = p1.pull("out").as_f64();
558            let slot = p2.resolve_output("out").unwrap();
559            let got = f64::from_bits(p2.eval_for_slot(&[cycle], slot));
560            assert_eq!(got, want, "P2 vec flow mismatch at cycle={cycle}");
561        }
562
563        #[cfg(feature = "jit")]
564        {
565            let asm = polydat::dsl::compile::compile_polydat_to_assembler(src).unwrap();
566            let mut hy = asm
567                .compile_slots(polydat_core::Engine::Native(
568                    polydat_core::Provenance::PushPull,
569                ))
570                .unwrap();
571            for cycle in [0u64, 7, 0xFEED] {
572                p1.set_inputs(&[cycle]);
573                let want = p1.pull("out").as_f64();
574                let slot = hy.resolve_output("out").unwrap();
575                hy.eval_at(&[cycle]);
576                let got = f64::from_bits(hy.get_slot(slot));
577                assert_eq!(got, want, "hybrid vec flow mismatch at cycle={cycle}");
578            }
579        }
580    }
581
582    /// Scratch reuse: re-evaluating the same compiled kernel must
583    /// republish coherent (ptr, len) views even as vector contents
584    /// change cycle to cycle.
585    #[test]
586    fn vec_scratch_reuses_across_evals() {
587        let src = r#"
588            input cycle: u64
589            a := hash_vec(cycle, 16)
590            out := vec_l2(a, vec_scale(a, 2.0))
591        "#;
592        let mut p1 = polydat::dsl::compile_polydat(src).unwrap();
593        let asm = polydat::dsl::compile::compile_polydat_to_assembler(src).unwrap();
594        let mut p2 = asm
595            .compile_slots(polydat_core::Engine::Closures(
596                polydat_core::Provenance::Raw,
597            ))
598            .expect("P2-eligible");
599        let slot = p2.resolve_output("out").unwrap();
600        // Interleave cycles so stale-scratch bugs would surface as
601        // cross-cycle contamination.
602        for cycle in [1u64, 9, 1, 42, 9, 1] {
603            p1.set_inputs(&[cycle]);
604            let want = p1.pull("out").as_f64();
605            let got = f64::from_bits(p2.eval_for_slot(&[cycle], slot));
606            assert_eq!(got, want, "scratch reuse mismatch at cycle={cycle}");
607        }
608    }
609
610    #[test]
611    fn vec_length_mismatch_panics() {
612        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
613            let mut out = [Value::None];
614            VecDotF32::new().eval(&[vecv(vec![1.0]), vecv(vec![1.0, 2.0])], &mut out);
615        }));
616        assert!(r.is_err(), "vec_dot_f32 accepted mismatched lengths");
617    }
618}