oarust 0.14.0

GPU-first semantic computing engine written in Rust
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=crypto_ntt.json schema_version=1 generator_version=64
// schema_sha256=7c4fa9a7775bc4e482550c6d15fd3d9506d13e51a23259023f87fe2db4c2f2a4
use super::config::{NttRepresentation, power_mod};
use crate::crypto::ntt::NttConfig;
use crate::{
	DType, Engine, Error, Matrix, OpAttribute, Result,
	runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
};

/// Reusable device twiddles and checked public field metadata.
///
/// This value retains its originating Engine through its Matrix allocations.
/// It has no independent execution owner and exposes no mutable twiddle storage.
#[derive(Clone)]
pub struct NttParameters {
	config: NttConfig,
	forward: Matrix,
	inverse: Matrix,
	forward_scalar: Option<Matrix>,
	inverse_scalar: Option<Matrix>,
	negative_inverse: u32,
	r2: u64,
	inverse_length: u64,
}

impl NttParameters {
	/// Checked public field configuration.
	pub const fn config(&self) -> &NttConfig {
		&self.config
	}
}

/// Prepare forward/inverse Montgomery twiddles on the supplied Engine.
///
/// # Errors
/// Rejects allocation, queried workgroup limits, ABI or recording failures.
pub fn prepare(engine: &Engine, config: &NttConfig) -> Result<NttParameters> {
	let engine = engine.handle();
	let modulus = config.modulus;
	let root = config.root;
	let one = ((1_u128 << 64) % u128::from(modulus)) as u64;
	let r2 = ((u128::from(one) * u128::from(one)) % u128::from(modulus)) as u64;
	let root_montgomery = ((u128::from(root) * u128::from(one)) % u128::from(modulus)) as u64;
	let inverse_root = power_mod(root, modulus - 2, modulus);
	let inverse_root_montgomery =
		((u128::from(inverse_root) * u128::from(one)) % u128::from(modulus)) as u64;
	let inverse_length = ((u128::from(power_mod(config.length as u64, modulus - 2, modulus))
		* u128::from(one))
		% u128::from(modulus)) as u64;
	let mut inverse = 1_u32;
	for _ in 0..5 {
		inverse = inverse.wrapping_mul(2_u32.wrapping_sub((modulus as u32).wrapping_mul(inverse)));
	}
	let negative_inverse = inverse.wrapping_neg();
	let count = (config.length / 2) as u32;
	let groups = engine.linear_dispatch_grid(count, 128)?;
	let forward = Matrix::allocate_output(
		&engine,
		vec![config.length / 2, 2],
		config.length,
		DType::U32,
	)?;
	let inverse = Matrix::allocate_output(
		&engine,
		vec![config.length / 2, 2],
		config.length,
		DType::U32,
	)?;
	let kernel = KernelId::CryptographyNttTwiddlesU32;
	let buffers = [
		BufferBinding::write(forward.storage()),
		BufferBinding::write(inverse.storage()),
	];
	let push_constants = [
		PushConstant::U32(count),
		PushConstant::U32(groups[0] * 128),
		PushConstant::U32(modulus as u32),
		PushConstant::U32((modulus >> 32) as u32),
		PushConstant::U32(negative_inverse),
		PushConstant::U32(root_montgomery as u32),
		PushConstant::U32((root_montgomery >> 32) as u32),
		PushConstant::U32(inverse_root_montgomery as u32),
		PushConstant::U32((inverse_root_montgomery >> 32) as u32),
		PushConstant::U32(one as u32),
		PushConstant::U32((one >> 32) as u32),
	];
	let attributes = [
		OpAttribute::UnsignedInteger {
			name: "modulus".into(),
			value: modulus,
		},
		OpAttribute::UnsignedInteger {
			name: "length".into(),
			value: config.length as u64,
		},
	];
	engine.record_semantic(
		ComputeDispatch {
			kernel,
			buffers: &buffers,
			push_constants: &push_constants,
			workgroups: groups,
			indirect: None,
		},
		SemanticDispatch {
			contract: crate::core::operation::crypto::ntt::NTT_TWIDDLES,
			inputs: &[],
			outputs: &[&forward, &inverse],
			attributes: &attributes,
		},
	)?;
	// Scalar R = 2^32 twiddles are generated only when prime31 arithmetic can
	// represent the field; scalar-storage transforms check table presence.
	let (forward_scalar, inverse_scalar) = if modulus < (1_u64 << 31) {
		let one_scalar = ((1_u128 << 32) % u128::from(modulus)) as u32;
		let root_scalar = ((u128::from(root) * u128::from(one_scalar)) % u128::from(modulus)) as u32;
		let inverse_root_scalar =
			((u128::from(inverse_root) * u128::from(one_scalar)) % u128::from(modulus)) as u32;
		let forward_scalar = Matrix::allocate_output(
			&engine,
			vec![config.length / 2],
			config.length / 2,
			DType::U32,
		)?;
		let inverse_scalar = Matrix::allocate_output(
			&engine,
			vec![config.length / 2],
			config.length / 2,
			DType::U32,
		)?;
		let kernel = KernelId::CryptographyNttTwiddlesScalarU32;
		let buffers = [
			BufferBinding::write(forward_scalar.storage()),
			BufferBinding::write(inverse_scalar.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(modulus as u32),
			PushConstant::U32(negative_inverse),
			PushConstant::U32(root_scalar),
			PushConstant::U32(inverse_root_scalar),
			PushConstant::U32(one_scalar),
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_TWIDDLES,
				inputs: &[],
				outputs: &[&forward_scalar, &inverse_scalar],
				attributes: &attributes,
			},
		)?;
		(Some(forward_scalar), Some(inverse_scalar))
	} else {
		(None, None)
	};
	Ok(NttParameters {
		config: config.clone(),
		forward,
		inverse,
		forward_scalar,
		inverse_scalar,
		negative_inverse,
		r2,
		inverse_length,
	})
}

/// Compute a natural-order forward cyclic NTT, preserving field representation.
///
/// Records staged GPU work with two reusable private buffers. It performs no
/// tensor host reads, waits or per-stage host initialization.
///
/// # Errors
/// Rejects dtype, shape, ownership, address limits, allocation or recording failures.
pub fn forward(input: &Matrix, parameters: &NttParameters) -> Result<Matrix> {
	let config = &parameters.config;
	let scalar = input.shape().len() == 2;
	if input.dtype() != DType::U32
		|| !input
			.engine_handle()
			.same_as(parameters.forward.engine_handle())
		|| (scalar && input.shape()[1] != config.length)
		|| (!scalar && (input.shape().len() != 3 || input.shape()[1..] != [config.length, 2]))
	{
		return Err(Error::invalid_argument(
			"NTT requires matching-owner U32 [batch, length] scalar or [batch, length, 2] paired coefficients",
		));
	}
	let elements = input.num_elements();
	let bytes = elements
		.checked_mul(4)
		.ok_or_else(|| Error::invalid_argument("NTT input byte extent overflows usize"))?;
	u32::try_from(bytes).map_err(|_| Error::invalid_argument("NTT input byte extent exceeds u32"))?;
	let count = u32::try_from(elements / if scalar { 1 } else { 2 })
		.map_err(|_| Error::invalid_argument("NTT coefficient count exceeds u32"))?;
	let engine = input.engine_handle();
	let first = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
	if count == 0 {
		return Ok(first);
	}
	let modulus = config.modulus;
	let montgomery = u32::from(config.representation == NttRepresentation::Montgomery);
	let shared_bytes = engine.compute_shared_memory_bytes() as usize;
	if scalar {
		// Scalar storage halves coefficient footprint but admits only fields whose
		// modulus fits prime31 Montgomery arithmetic (R = 2^32, p < 2^31).
		let Some(twiddles) = parameters.forward_scalar.as_ref() else {
			return Err(Error::invalid_argument(
				"Scalar NTT storage requires a prepared modulus below 2^31",
			));
		};
		let cooperative = [
			(256, KernelId::CryptographyNttCooperativeScalar256U32),
			(1024, KernelId::CryptographyNttCooperativeScalar1024U32),
			(4096, KernelId::CryptographyNttCooperativeScalar4096U32),
			(8192, KernelId::CryptographyNttCooperativeScalar8192U32),
		]
		.into_iter()
		.find(|(capacity, _)| config.length <= *capacity && capacity * 4 <= shared_bytes);
		let Some((_, kernel)) = cooperative else {
			return Err(Error::invalid_argument(
				"Scalar NTT length exceeds the shared-memory provider capacity; use paired-word storage",
			));
		};
		let modulus32 = modulus as u32;
		let r2_scalar = ((1_u128 << 64) % u128::from(modulus)) as u32;
		let normalization = ((1_u128 << 32) % u128::from(modulus)) as u32;
		let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
		let buffers = [
			BufferBinding::read(input.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(first.storage()),
		];
		let push_constants = [
			PushConstant::U32(input.shape()[0] as u32),
			PushConstant::U32(groups[0]),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(config.length.trailing_zeros()),
			PushConstant::U32(modulus32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(r2_scalar),
			PushConstant::U32(normalization),
			PushConstant::U32(montgomery),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 0,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
				inputs: &[input, twiddles],
				outputs: &[&first],
				attributes: &attributes,
			},
		)?;
		return Ok(first);
	}
	let twiddles = &parameters.forward;
	let normalization = ((1_u128 << 64) % u128::from(modulus)) as u64;
	let cooperative = [
		(256, KernelId::CryptographyNttCooperative256U32),
		(1024, KernelId::CryptographyNttCooperative1024U32),
		(4096, KernelId::CryptographyNttCooperative4096U32),
		(8192, KernelId::CryptographyNttCooperative8192U32),
	]
	.into_iter()
	.find(|(capacity, _)| config.length <= *capacity && capacity * 8 <= shared_bytes);
	if let Some((_, kernel)) = cooperative {
		let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
		let buffers = [
			BufferBinding::read(input.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(first.storage()),
		];
		let push_constants = [
			PushConstant::U32(input.shape()[0] as u32),
			PushConstant::U32(groups[0]),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(config.length.trailing_zeros()),
			PushConstant::U32(modulus as u32),
			PushConstant::U32((modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(parameters.r2 as u32),
			PushConstant::U32((parameters.r2 >> 32) as u32),
			PushConstant::U32(normalization as u32),
			PushConstant::U32((normalization >> 32) as u32),
			PushConstant::U32(montgomery),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 0,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
				inputs: &[input, twiddles],
				outputs: &[&first],
				attributes: &attributes,
			},
		)?;
		return Ok(first);
	}
	let second = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
	let groups = engine.linear_dispatch_grid(count, 128)?;
	let kernel = KernelId::CryptographyNttReorderU32;
	let buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(first.storage()),
	];
	let push_constants = [
		PushConstant::U32(count),
		PushConstant::U32(groups[0] * 128),
		PushConstant::U32(config.length as u32),
		PushConstant::U32(config.length.trailing_zeros()),
		PushConstant::U32(modulus as u32),
		PushConstant::U32((modulus >> 32) as u32),
		PushConstant::U32(parameters.negative_inverse),
		PushConstant::U32(parameters.r2 as u32),
		PushConstant::U32((parameters.r2 >> 32) as u32),
		PushConstant::U32(montgomery),
	];
	let attributes = [
		OpAttribute::UnsignedInteger {
			name: "modulus".into(),
			value: modulus,
		},
		OpAttribute::UnsignedInteger {
			name: "length".into(),
			value: config.length as u64,
		},
		OpAttribute::UnsignedInteger {
			name: "montgomery".into(),
			value: u64::from(montgomery),
		},
	];
	engine.record_semantic(
		ComputeDispatch {
			kernel,
			buffers: &buffers,
			push_constants: &push_constants,
			workgroups: groups,
			indirect: None,
		},
		SemanticDispatch {
			contract: crate::core::operation::crypto::ntt::NTT_REORDER,
			inputs: &[input],
			outputs: &[&first],
			attributes: &attributes,
		},
	)?;
	let mut current = first.clone();
	// The fused tile provider performs every butterfly whose span fits one
	// shared-memory tile in a single pass; larger spans keep the staged route.
	let fused = [
		(8192, KernelId::CryptographyNttStageFused8192U32),
		(4096, KernelId::CryptographyNttStageFused4096U32),
		(1024, KernelId::CryptographyNttStageFused1024U32),
		(256, KernelId::CryptographyNttStageFused256U32),
	]
	.into_iter()
	.find(|(capacity, _)| *capacity < config.length && capacity * 8 <= shared_bytes);
	let mut completed_stages = 0u32;
	if let Some((capacity, kernel)) = fused {
		let tiles = count / capacity as u32;
		let groups = engine.linear_dispatch_grid(tiles, 1)?;
		let output = second.reshape_semantic_output(input.shape().to_vec())?;
		let buffers = [
			BufferBinding::read(current.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(tiles),
			PushConstant::U32(groups[0]),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(modulus as u32),
			PushConstant::U32((modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 0,
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_STAGE_FUSED,
				inputs: &[&current, twiddles],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		current = output;
		completed_stages = capacity.trailing_zeros();
	}
	let mut current_is_second = fused.is_some();
	let groups = engine.linear_dispatch_grid(count / 2, 128)?;
	for stage in (completed_stages + 1)..=config.length.trailing_zeros() {
		let span = 1_u32 << stage;
		// These two allocations are private to this operation. A fresh semantic
		// output reuses retired stage storage; exact buffer hazards order writes.
		let target = if current_is_second { &first } else { &second };
		let output = target.reshape_semantic_output(input.shape().to_vec())?;
		let kernel = KernelId::CryptographyNttStageU32;
		let buffers = [
			BufferBinding::read(current.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count / 2),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(span),
			PushConstant::U32(modulus as u32),
			PushConstant::U32((modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(normalization as u32),
			PushConstant::U32((normalization >> 32) as u32),
			PushConstant::U32(montgomery),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "span".into(),
				value: u64::from(span),
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 0,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_STAGE,
				inputs: &[&current, twiddles],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		current = output;
		current_is_second = !current_is_second;
	}
	Ok(current)
}

/// Compute a natural-order inverse cyclic NTT, preserving field representation.
///
/// Records staged GPU work with two reusable private buffers. It performs no
/// tensor host reads, waits or per-stage host initialization.
///
/// # Errors
/// Rejects dtype, shape, ownership, address limits, allocation or recording failures.
pub fn inverse(input: &Matrix, parameters: &NttParameters) -> Result<Matrix> {
	let config = &parameters.config;
	let scalar = input.shape().len() == 2;
	if input.dtype() != DType::U32
		|| !input
			.engine_handle()
			.same_as(parameters.forward.engine_handle())
		|| (scalar && input.shape()[1] != config.length)
		|| (!scalar && (input.shape().len() != 3 || input.shape()[1..] != [config.length, 2]))
	{
		return Err(Error::invalid_argument(
			"NTT requires matching-owner U32 [batch, length] scalar or [batch, length, 2] paired coefficients",
		));
	}
	let elements = input.num_elements();
	let bytes = elements
		.checked_mul(4)
		.ok_or_else(|| Error::invalid_argument("NTT input byte extent overflows usize"))?;
	u32::try_from(bytes).map_err(|_| Error::invalid_argument("NTT input byte extent exceeds u32"))?;
	let count = u32::try_from(elements / if scalar { 1 } else { 2 })
		.map_err(|_| Error::invalid_argument("NTT coefficient count exceeds u32"))?;
	let engine = input.engine_handle();
	let first = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
	if count == 0 {
		return Ok(first);
	}
	let modulus = config.modulus;
	let montgomery = u32::from(config.representation == NttRepresentation::Montgomery);
	let shared_bytes = engine.compute_shared_memory_bytes() as usize;
	if scalar {
		// Scalar storage halves coefficient footprint but admits only fields whose
		// modulus fits prime31 Montgomery arithmetic (R = 2^32, p < 2^31).
		let Some(twiddles) = parameters.inverse_scalar.as_ref() else {
			return Err(Error::invalid_argument(
				"Scalar NTT storage requires a prepared modulus below 2^31",
			));
		};
		let cooperative = [
			(256, KernelId::CryptographyNttCooperativeScalar256U32),
			(1024, KernelId::CryptographyNttCooperativeScalar1024U32),
			(4096, KernelId::CryptographyNttCooperativeScalar4096U32),
			(8192, KernelId::CryptographyNttCooperativeScalar8192U32),
		]
		.into_iter()
		.find(|(capacity, _)| config.length <= *capacity && capacity * 4 <= shared_bytes);
		let Some((_, kernel)) = cooperative else {
			return Err(Error::invalid_argument(
				"Scalar NTT length exceeds the shared-memory provider capacity; use paired-word storage",
			));
		};
		let modulus32 = modulus as u32;
		let r2_scalar = ((1_u128 << 64) % u128::from(modulus)) as u32;
		let normalization = ((u128::from(power_mod(config.length as u64, modulus - 2, modulus))
			* (1_u128 << 32))
			% u128::from(modulus)) as u32;
		let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
		let buffers = [
			BufferBinding::read(input.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(first.storage()),
		];
		let push_constants = [
			PushConstant::U32(input.shape()[0] as u32),
			PushConstant::U32(groups[0]),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(config.length.trailing_zeros()),
			PushConstant::U32(modulus32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(r2_scalar),
			PushConstant::U32(normalization),
			PushConstant::U32(montgomery),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 1,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
				inputs: &[input, twiddles],
				outputs: &[&first],
				attributes: &attributes,
			},
		)?;
		return Ok(first);
	}
	let twiddles = &parameters.inverse;
	let normalization = parameters.inverse_length;
	let cooperative = [
		(256, KernelId::CryptographyNttCooperative256U32),
		(1024, KernelId::CryptographyNttCooperative1024U32),
		(4096, KernelId::CryptographyNttCooperative4096U32),
		(8192, KernelId::CryptographyNttCooperative8192U32),
	]
	.into_iter()
	.find(|(capacity, _)| config.length <= *capacity && capacity * 8 <= shared_bytes);
	if let Some((_, kernel)) = cooperative {
		let groups = engine.linear_dispatch_grid(input.shape()[0] as u32, 1)?;
		let buffers = [
			BufferBinding::read(input.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(first.storage()),
		];
		let push_constants = [
			PushConstant::U32(input.shape()[0] as u32),
			PushConstant::U32(groups[0]),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(config.length.trailing_zeros()),
			PushConstant::U32(modulus as u32),
			PushConstant::U32((modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(parameters.r2 as u32),
			PushConstant::U32((parameters.r2 >> 32) as u32),
			PushConstant::U32(normalization as u32),
			PushConstant::U32((normalization >> 32) as u32),
			PushConstant::U32(montgomery),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 1,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_TRANSFORM,
				inputs: &[input, twiddles],
				outputs: &[&first],
				attributes: &attributes,
			},
		)?;
		return Ok(first);
	}
	let second = Matrix::allocate_output(engine, input.shape().to_vec(), elements, DType::U32)?;
	let groups = engine.linear_dispatch_grid(count, 128)?;
	let kernel = KernelId::CryptographyNttReorderU32;
	let buffers = [
		BufferBinding::read(input.storage()),
		BufferBinding::write(first.storage()),
	];
	let push_constants = [
		PushConstant::U32(count),
		PushConstant::U32(groups[0] * 128),
		PushConstant::U32(config.length as u32),
		PushConstant::U32(config.length.trailing_zeros()),
		PushConstant::U32(modulus as u32),
		PushConstant::U32((modulus >> 32) as u32),
		PushConstant::U32(parameters.negative_inverse),
		PushConstant::U32(parameters.r2 as u32),
		PushConstant::U32((parameters.r2 >> 32) as u32),
		PushConstant::U32(montgomery),
	];
	let attributes = [
		OpAttribute::UnsignedInteger {
			name: "modulus".into(),
			value: modulus,
		},
		OpAttribute::UnsignedInteger {
			name: "length".into(),
			value: config.length as u64,
		},
		OpAttribute::UnsignedInteger {
			name: "montgomery".into(),
			value: u64::from(montgomery),
		},
	];
	engine.record_semantic(
		ComputeDispatch {
			kernel,
			buffers: &buffers,
			push_constants: &push_constants,
			workgroups: groups,
			indirect: None,
		},
		SemanticDispatch {
			contract: crate::core::operation::crypto::ntt::NTT_REORDER,
			inputs: &[input],
			outputs: &[&first],
			attributes: &attributes,
		},
	)?;
	let mut current = first.clone();
	// The fused tile provider performs every butterfly whose span fits one
	// shared-memory tile in a single pass; larger spans keep the staged route.
	let fused = [
		(8192, KernelId::CryptographyNttStageFused8192U32),
		(4096, KernelId::CryptographyNttStageFused4096U32),
		(1024, KernelId::CryptographyNttStageFused1024U32),
		(256, KernelId::CryptographyNttStageFused256U32),
	]
	.into_iter()
	.find(|(capacity, _)| *capacity < config.length && capacity * 8 <= shared_bytes);
	let mut completed_stages = 0u32;
	if let Some((capacity, kernel)) = fused {
		let tiles = count / capacity as u32;
		let groups = engine.linear_dispatch_grid(tiles, 1)?;
		let output = second.reshape_semantic_output(input.shape().to_vec())?;
		let buffers = [
			BufferBinding::read(current.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(tiles),
			PushConstant::U32(groups[0]),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(modulus as u32),
			PushConstant::U32((modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 1,
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_STAGE_FUSED,
				inputs: &[&current, twiddles],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		current = output;
		completed_stages = capacity.trailing_zeros();
	}
	let mut current_is_second = fused.is_some();
	let groups = engine.linear_dispatch_grid(count / 2, 128)?;
	for stage in (completed_stages + 1)..=config.length.trailing_zeros() {
		let span = 1_u32 << stage;
		// These two allocations are private to this operation. A fresh semantic
		// output reuses retired stage storage; exact buffer hazards order writes.
		let target = if current_is_second { &first } else { &second };
		let output = target.reshape_semantic_output(input.shape().to_vec())?;
		let kernel = KernelId::CryptographyNttStageU32;
		let buffers = [
			BufferBinding::read(current.storage()),
			BufferBinding::read(twiddles.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count / 2),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(config.length as u32),
			PushConstant::U32(span),
			PushConstant::U32(modulus as u32),
			PushConstant::U32((modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(normalization as u32),
			PushConstant::U32((normalization >> 32) as u32),
			PushConstant::U32(montgomery),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "span".into(),
				value: u64::from(span),
			},
			OpAttribute::UnsignedInteger {
				name: "inverse".into(),
				value: 1,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_STAGE,
				inputs: &[&current, twiddles],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		current = output;
		current_is_second = !current_is_second;
	}
	Ok(current)
}

/// Multiply pointwise in the configured prime field, preserving representation.
///
/// # Errors
/// Rejects dtype, shape, ownership, address limits, allocation or recording failures.
pub fn pointwise_multiply(
	left: &Matrix,
	right: &Matrix,
	parameters: &NttParameters,
) -> Result<Matrix> {
	let config = &parameters.config;
	let scalar = left.shape().len() == 2;
	if left.dtype() != DType::U32
		|| right.dtype() != DType::U32
		|| right.shape() != left.shape()
		|| !left.engine_handle().same_as(right.engine_handle())
		|| !left
			.engine_handle()
			.same_as(parameters.forward.engine_handle())
		|| (scalar && left.shape()[1] != config.length)
		|| (!scalar && (left.shape().len() != 3 || left.shape()[1..] != [config.length, 2]))
	{
		return Err(Error::invalid_argument(
			"NTT pointwise multiplication requires matching-owner U32 rows in one coefficient layout",
		));
	}
	let elements = left.num_elements();
	let bytes = elements
		.checked_mul(4)
		.ok_or_else(|| Error::invalid_argument("NTT byte extent overflows usize"))?;
	u32::try_from(bytes).map_err(|_| Error::invalid_argument("NTT byte extent exceeds u32"))?;
	let count = u32::try_from(elements / if scalar { 1 } else { 2 })
		.map_err(|_| Error::invalid_argument("NTT coefficient count exceeds u32"))?;
	let engine = left.engine_handle();
	let output = Matrix::allocate_output(engine, left.shape().to_vec(), elements, DType::U32)?;
	if count != 0 && scalar {
		if parameters.forward_scalar.is_none() {
			return Err(Error::invalid_argument(
				"Scalar NTT storage requires a prepared modulus below 2^31",
			));
		}
		let groups = engine.linear_dispatch_grid(count, 128)?;
		let kernel = KernelId::CryptographyNttPointwiseScalarU32;
		let buffers = [
			BufferBinding::read(left.storage()),
			BufferBinding::read(right.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(config.modulus as u32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(((1_u128 << 64) % u128::from(config.modulus)) as u32),
			PushConstant::U32(u32::from(
				config.representation == NttRepresentation::Montgomery,
			)),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: config.modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(config.representation == NttRepresentation::Montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_POINTWISE,
				inputs: &[left, right],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		return Ok(output);
	}
	if count != 0 {
		let groups = engine.linear_dispatch_grid(count, 128)?;
		let kernel = KernelId::CryptographyNttPointwiseU32;
		let buffers = [
			BufferBinding::read(left.storage()),
			BufferBinding::read(right.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(config.modulus as u32),
			PushConstant::U32((config.modulus >> 32) as u32),
			PushConstant::U32(parameters.negative_inverse),
			PushConstant::U32(parameters.r2 as u32),
			PushConstant::U32((parameters.r2 >> 32) as u32),
			PushConstant::U32(u32::from(
				config.representation == NttRepresentation::Montgomery,
			)),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "modulus".into(),
				value: config.modulus,
			},
			OpAttribute::UnsignedInteger {
				name: "length".into(),
				value: config.length as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "montgomery".into(),
				value: u64::from(config.representation == NttRepresentation::Montgomery),
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
				indirect: None,
			},
			SemanticDispatch {
				contract: crate::core::operation::crypto::ntt::NTT_POINTWISE,
				inputs: &[left, right],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
	}
	Ok(output)
}