1use 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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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
160fn 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
184fn 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
194macro_rules! float_overload {
197 ($name:literal: [$($w32:ident),*] => $f32:literal, [$($w64:ident),*] => $f64:literal) => {
198 polydat::inventory::submit! {
199 Overload::new(
200 $name,
201 &[
202 OverloadForm::new(&[$(PortType::$w32),*], $f32),
203 OverloadForm::new(&[$(PortType::$w64),*], $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#[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#[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#[polydat::polydat_node(category = Arithmetic)]
273fn lid_mle(distances: &[f32], k: f64) -> f64 {
274 lid_mle_of(distances, k)
275}
276
277#[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#[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 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 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 #[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 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 #[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 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 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 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 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 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 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 #[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 #[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 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}