-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcpu_bus.rs
More file actions
2574 lines (2406 loc) · 86.6 KB
/
cpu_bus.rs
File metadata and controls
2574 lines (2406 loc) · 86.6 KB
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
use crate::PiCcsError;
use neo_ccs::{CcsMatrix, CcsStructure, CeClaim, Mat};
use neo_math::{F, K};
use neo_memory::cpu::{
build_bus_layout_for_instances_with_shout_shapes_and_twist_lanes, BusLayout, ShoutInstanceShape,
};
use neo_memory::riscv::lookups::{PROG_ID, REG_ID};
use neo_memory::riscv::trace::{
riscv_is_decode_lookup_table_id, riscv_trace_is_width_lookup_table_id, riscv_trace_lookup_n_vals_for_table_id,
rv32_trace_cpu_cols, rv64_trace_cpu_cols,
};
use neo_memory::sparse_time::SparseIdxVec;
use neo_memory::witness::{LutInstance, MemInstance, StepInstanceBundle, StepWitnessBundle};
use neo_params::NeoParams;
use p3_field::PrimeCharacteristicRing;
use std::collections::{BTreeMap, HashMap, HashSet};
pub(crate) trait BusStepView<Cmt> {
fn m_in(&self) -> usize;
fn public_x(&self) -> &[F];
fn lut_insts_len(&self) -> usize;
fn mem_insts_len(&self) -> usize;
fn lut_inst(&self, idx: usize) -> &LutInstance<Cmt, F>;
fn mem_inst(&self, idx: usize) -> &MemInstance<Cmt, F>;
fn time_t(&self) -> usize {
0
}
fn time_cpu_cols_len(&self) -> usize {
0
}
fn time_mem_cols_len(&self) -> usize {
0
}
}
impl<Cmt, KK> BusStepView<Cmt> for StepWitnessBundle<Cmt, F, KK> {
fn m_in(&self) -> usize {
self.mcs.0.m_in
}
fn public_x(&self) -> &[F] {
&self.mcs.0.x
}
fn lut_insts_len(&self) -> usize {
self.lut_instances.len()
}
fn mem_insts_len(&self) -> usize {
self.mem_instances.len()
}
fn lut_inst(&self, idx: usize) -> &LutInstance<Cmt, F> {
&self.lut_instances[idx].0
}
fn mem_inst(&self, idx: usize) -> &MemInstance<Cmt, F> {
&self.mem_instances[idx].0
}
fn time_t(&self) -> usize {
self.time_columns.t
}
fn time_cpu_cols_len(&self) -> usize {
self.time_columns.cpu_cols.len()
}
fn time_mem_cols_len(&self) -> usize {
self.time_columns.mem_cols.len()
}
}
impl<Cmt, KK> BusStepView<Cmt> for StepInstanceBundle<Cmt, F, KK> {
fn m_in(&self) -> usize {
self.mcs_inst.m_in
}
fn public_x(&self) -> &[F] {
&self.mcs_inst.x
}
fn lut_insts_len(&self) -> usize {
self.lut_insts.len()
}
fn mem_insts_len(&self) -> usize {
self.mem_insts.len()
}
fn lut_inst(&self, idx: usize) -> &LutInstance<Cmt, F> {
&self.lut_insts[idx]
}
fn mem_inst(&self, idx: usize) -> &MemInstance<Cmt, F> {
&self.mem_insts[idx]
}
fn time_t(&self) -> usize {
self.time_columns.t
}
fn time_cpu_cols_len(&self) -> usize {
self.time_columns.cpu_cols.len()
}
fn time_mem_cols_len(&self) -> usize {
self.time_columns.mem_cols.len()
}
}
fn infer_chunk_size_from_steps<Cmt, S: BusStepView<Cmt>>(steps: &[S]) -> Result<usize, PiCcsError> {
let mut max_steps = 0usize;
for step in steps {
for i in 0..step.lut_insts_len() {
max_steps = max_steps.max(step.lut_inst(i).steps);
}
for i in 0..step.mem_insts_len() {
max_steps = max_steps.max(step.mem_inst(i).steps);
}
}
if max_steps == 0 {
// No instances => no bus; chunk_size is irrelevant but must be >=1 for layout helpers.
return Ok(1);
}
Ok(max_steps)
}
fn infer_bus_layout_for_steps<Cmt, S: BusStepView<Cmt>>(
s: &CcsStructure<F>,
steps: &[S],
) -> Result<BusLayout, PiCcsError> {
if steps.is_empty() {
return Err(PiCcsError::InvalidInput("no steps".into()));
}
let m_in = steps[0].m_in();
for (i, step) in steps.iter().enumerate() {
let cur_m_in = step.m_in();
if cur_m_in != m_in {
return Err(PiCcsError::InvalidInput(format!(
"m_in mismatch across steps (step 0 has {m_in}, step {i} has {cur_m_in})"
)));
}
}
let chunk_size = infer_chunk_size_from_steps(steps)?;
let base_shout_ell_addrs: Vec<usize> = (0..steps[0].lut_insts_len())
.map(|i| {
let inst = steps[0].lut_inst(i);
inst.d * inst.ell
})
.collect();
let base_shout_lanes: Vec<usize> = (0..steps[0].lut_insts_len())
.map(|i| {
let inst = steps[0].lut_inst(i);
inst.lanes
})
.collect();
let base_shout_n_vals: Vec<usize> = (0..steps[0].lut_insts_len())
.map(|i| riscv_trace_lookup_n_vals_for_table_id(steps[0].lut_inst(i).table_id))
.collect();
let base_shout_addr_groups: Vec<Option<u64>> = (0..steps[0].lut_insts_len())
.map(|i| steps[0].lut_inst(i).addr_group)
.collect();
let base_shout_selector_groups: Vec<Option<u64>> = (0..steps[0].lut_insts_len())
.map(|i| steps[0].lut_inst(i).selector_group)
.collect();
let base_twist_ell_addrs: Vec<usize> = (0..steps[0].mem_insts_len())
.map(|i| {
let inst = steps[0].mem_inst(i);
inst.d * inst.ell
})
.collect();
let base_twist_lanes: Vec<usize> = (0..steps[0].mem_insts_len())
.map(|i| {
let inst = steps[0].mem_inst(i);
inst.lanes
})
.collect();
for (i, step) in steps.iter().enumerate().skip(1) {
let cur_shout: Vec<usize> = (0..step.lut_insts_len())
.map(|j| {
let inst = step.lut_inst(j);
inst.d * inst.ell
})
.collect();
let cur_shout_lanes: Vec<usize> = (0..step.lut_insts_len())
.map(|j| {
let inst = step.lut_inst(j);
inst.lanes
})
.collect();
let cur_shout_n_vals: Vec<usize> = (0..step.lut_insts_len())
.map(|j| riscv_trace_lookup_n_vals_for_table_id(step.lut_inst(j).table_id))
.collect();
let cur_shout_addr_groups: Vec<Option<u64>> = (0..step.lut_insts_len())
.map(|j| step.lut_inst(j).addr_group)
.collect();
let cur_shout_selector_groups: Vec<Option<u64>> = (0..step.lut_insts_len())
.map(|j| step.lut_inst(j).selector_group)
.collect();
let cur_twist: Vec<usize> = (0..step.mem_insts_len())
.map(|j| {
let inst = step.mem_inst(j);
inst.d * inst.ell
})
.collect();
let cur_twist_lanes: Vec<usize> = (0..step.mem_insts_len())
.map(|j| {
let inst = step.mem_inst(j);
inst.lanes
})
.collect();
if cur_shout != base_shout_ell_addrs
|| cur_shout_lanes != base_shout_lanes
|| cur_shout_n_vals != base_shout_n_vals
|| cur_shout_addr_groups != base_shout_addr_groups
|| cur_shout_selector_groups != base_shout_selector_groups
|| cur_twist != base_twist_ell_addrs
|| cur_twist_lanes != base_twist_lanes
{
return Err(PiCcsError::InvalidInput(format!(
"shared CPU bus layout mismatch across steps (step 0 vs step {i})"
)));
}
}
let shout_shapes = base_shout_ell_addrs
.iter()
.copied()
.zip(base_shout_lanes.iter().copied())
.zip(base_shout_n_vals.iter().copied())
.zip(base_shout_addr_groups.iter().copied())
.zip(base_shout_selector_groups.iter().copied())
.map(
|((((ell_addr, lanes), n_vals), addr_group), selector_group)| ShoutInstanceShape {
ell_addr,
lanes,
n_vals,
addr_group,
selector_group,
},
);
let twist_ell_addrs_and_lanes = base_twist_ell_addrs
.iter()
.copied()
.zip(base_twist_lanes.iter().copied())
.map(|(ell_addr, lanes)| (ell_addr, lanes));
let uniform_width_matches_ccs = m_in
.checked_add(steps[0].time_cpu_cols_len())
.and_then(|v| v.checked_add(steps[0].time_mem_cols_len()))
.map_or(false, |uniform_m| uniform_m == s.m);
let use_time_columns = uniform_width_matches_ccs
&& steps[0].time_t() == chunk_size
&& steps[0].time_mem_cols_len() > 0
&& steps.iter().all(|step| {
step.time_t() == chunk_size
&& step.time_mem_cols_len() == steps[0].time_mem_cols_len()
&& step.time_cpu_cols_len() == steps[0].time_cpu_cols_len()
});
let m_virtual = if use_time_columns {
let cpu_region = steps[0]
.time_cpu_cols_len()
.checked_mul(chunk_size)
.ok_or_else(|| PiCcsError::InvalidInput("time cpu_cols*chunk_size overflow".into()))?;
let mem_region = steps[0]
.time_mem_cols_len()
.checked_mul(chunk_size)
.ok_or_else(|| PiCcsError::InvalidInput("time mem_cols*chunk_size overflow".into()))?;
m_in.checked_add(cpu_region)
.and_then(|v| v.checked_add(mem_region))
.ok_or_else(|| PiCcsError::InvalidInput("time virtual m overflow".into()))?
} else {
s.m
};
let layout = build_bus_layout_for_instances_with_shout_shapes_and_twist_lanes(
m_virtual,
m_in,
chunk_size,
shout_shapes,
twist_ell_addrs_and_lanes,
)
.map_err(PiCcsError::InvalidInput)?;
if use_time_columns && layout.bus_cols != steps[0].time_mem_cols_len() {
return Err(PiCcsError::InvalidInput(format!(
"time mem column count mismatch: layout.bus_cols={} vs time_columns.mem_cols={}",
layout.bus_cols,
steps[0].time_mem_cols_len()
)));
}
// If there are no bus columns (no Twist/Shout instances), Route A doesn't use the bus time rows.
// Allow small CCS instances (including m_in == n) in this case.
if layout.bus_cols == 0 {
return Ok(layout);
}
if m_in
.checked_add(layout.chunk_size)
.ok_or_else(|| PiCcsError::InvalidInput("m_in + chunk_size overflow".into()))?
> s.n
{
return Err(PiCcsError::InvalidInput(format!(
"bus time rows out of range: m_in({m_in}) + chunk_size({}) > n({})",
layout.chunk_size, s.n
)));
}
Ok(layout)
}
pub(crate) fn prepare_ccs_for_shared_cpu_bus_steps<'a, Cmt, S: BusStepView<Cmt>>(
s0: &'a CcsStructure<F>,
steps: &[S],
) -> Result<(&'a CcsStructure<F>, BusLayout), PiCcsError> {
let bus = infer_bus_layout_for_steps(s0, steps)?;
let m_in = steps.first().map(|s| s.m_in()).unwrap_or(0usize);
let uniform_width_matches_ccs = steps.first().and_then(|step0| {
m_in.checked_add(step0.time_cpu_cols_len())
.and_then(|v| v.checked_add(step0.time_mem_cols_len()))
}) == Some(s0.m);
let has_physical_bus_refs = ccs_references_any_bus_cols(s0, &bus);
let using_time_columns = !steps.is_empty()
&& steps[0].time_t() == bus.chunk_size
&& steps[0].time_mem_cols_len() > 0
&& steps.iter().all(|step| {
step.time_t() == bus.chunk_size
&& step.time_mem_cols_len() == steps[0].time_mem_cols_len()
&& step.time_cpu_cols_len() == steps[0].time_cpu_cols_len()
});
let rv32_trace_cpu_cols = rv32_trace_cpu_cols();
let rv64_trace_cpu_cols = rv64_trace_cpu_cols();
let canonical_trace_mode = !steps.is_empty()
&& m_in == 5
&& matches!(steps[0].time_cpu_cols_len(), n if n == rv32_trace_cpu_cols || n == rv64_trace_cpu_cols);
let route_a_uniform_mode = using_time_columns && uniform_width_matches_ccs && canonical_trace_mode;
if route_a_uniform_mode && !has_physical_bus_refs {
// Only the canonical RV32/RV64 trace-wiring paths are allowed to satisfy shared-bus
// linkage purely through committed time columns. Ad hoc test bundles may also synthesize
// `time_columns`, but those columns are not authoritative and must still satisfy the
// physical-tail guardrails below.
return Ok((s0, bus));
}
let padding_rows = ensure_ccs_has_shared_bus_padding_for_steps(s0, &bus, steps)?;
ensure_ccs_binds_shared_bus_for_steps(s0, &bus, &padding_rows, steps)?;
// Performance: do NOT materialize bus copyout matrices into the CCS. Instead, we append the
// corresponding ME openings directly from the witness (see `append_bus_openings_to_me_*`).
Ok((s0, bus))
}
#[inline]
fn chi_for_row_index(r: &[K], idx: usize) -> K {
// Multilinear basis polynomial χ_r(idx) where idx is interpreted in little-endian bits:
// χ_r(idx) = ∏_i (idx_i ? r_i : (1 - r_i)).
let mut acc = K::ONE;
for (bit, &ri) in r.iter().enumerate() {
let is_one = ((idx >> bit) & 1) == 1;
acc *= if is_one { ri } else { K::ONE - ri };
}
acc
}
#[inline]
fn precompute_contiguous_time_weights(
r: &[K],
start_row: usize,
len: usize,
n_pad: usize,
) -> Result<Vec<K>, PiCcsError> {
if len == 0 {
return Ok(Vec::new());
}
let end_row = start_row
.checked_add(len)
.ok_or_else(|| PiCcsError::InvalidInput("time-weight range overflow".into()))?;
if end_row > n_pad {
return Err(PiCcsError::InvalidInput(format!(
"time-weight range out of bounds (start_row={}, len={}, n_pad={})",
start_row, len, n_pad
)));
}
// For large contiguous windows, build χ_r over the full boolean domain once and slice.
// This avoids repeated per-index basis recomputation in hot Route-A paths.
const FULL_CHI_MAX_PAD: usize = 1 << 20;
let naive_ops = len.saturating_mul(r.len().max(1));
let use_full_table = len >= 1024 && n_pad <= FULL_CHI_MAX_PAD && naive_ops >= n_pad;
if use_full_table {
let mut chi = Vec::with_capacity(n_pad);
chi.push(K::ONE);
for &ri in r {
let one_minus_ri = K::ONE - ri;
let cur_len = chi.len();
chi.reserve(cur_len);
for i in 0..cur_len {
let v = chi[i];
chi[i] = v * one_minus_ri;
chi.push(v * ri);
}
}
return Ok(chi[start_row..start_row + len].to_vec());
}
let mut out = Vec::with_capacity(len);
for off in 0..len {
out.push(chi_for_row_index(r, start_row + off));
}
Ok(out)
}
pub(crate) fn point_covers_bus_time_rows(bus: &BusLayout, point: &[K]) -> Result<bool, PiCcsError> {
if bus.bus_cols == 0 {
return Ok(true);
}
let n_pad = 1usize
.checked_shl(point.len() as u32)
.ok_or_else(|| PiCcsError::InvalidInput("2^ell_n overflow".into()))?;
let start_row = bus.time_index(0);
let end_row = start_row
.checked_add(bus.chunk_size)
.ok_or_else(|| PiCcsError::InvalidInput("bus time row range overflow".into()))?;
Ok(end_row <= n_pad)
}
pub(crate) fn append_bus_openings_to_me_instance<Cmt>(
params: &NeoParams,
bus: &BusLayout,
core_t: usize,
Z: &Mat<F>,
me: &mut CeClaim<Cmt, F, K>,
) -> Result<(), PiCcsError>
where
Cmt: Clone,
{
if bus.bus_cols == 0 {
return Ok(());
}
let want_len = core_t
.checked_add(bus.bus_cols)
.ok_or_else(|| PiCcsError::InvalidInput("core_t + bus_cols overflow".into()))?;
let y_pad = (params.d as usize).next_power_of_two();
let expected_cols = bus.m.div_ceil(neo_math::D);
if Z.cols() != expected_cols {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require packed witness width (Z.cols()={}, expected ceil(bus.m/D)={} for bus.m={})",
Z.cols(),
expected_cols,
bus.m
)));
}
// Idempotent append: allow callers to call this once; reject unexpected shapes.
if me.y_ring.len() >= want_len && me.ct.len() >= want_len && me.y_ring.len() == me.ct.len() {
return Ok(());
}
if me.y_ring.len() != core_t || me.ct.len() != core_t {
return Err(PiCcsError::InvalidInput(format!(
"bus openings expect ME y/ct to start at core_t (y.len()={}, ct.len()={}, core_t={})",
me.y_ring.len(),
me.ct.len(),
core_t
)));
}
let d = neo_math::D;
if y_pad < d {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require y_pad >= D (y_pad={y_pad}, D={d})"
)));
}
if Z.rows() != d {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require Z.rows()==D (got {}, want {})",
Z.rows(),
d
)));
}
if me.m_in != bus.m_in {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require ME.m_in==bus.m_in (got {}, want {})",
me.m_in, bus.m_in
)));
}
let n_pad = 1usize
.checked_shl(me.r.len() as u32)
.ok_or_else(|| PiCcsError::InvalidInput("2^ell_n overflow".into()))?;
let start_row = bus.time_index(0);
for j in 0..bus.chunk_size {
let row = bus.time_index(j);
if row >= n_pad {
return Err(PiCcsError::InvalidInput(format!(
"bus time_index({j})={row} out of range for ell_n={} (n_pad={})",
me.r.len(),
n_pad
)));
}
if row != start_row + j {
return Err(PiCcsError::InvalidInput(format!(
"bus time_index must be contiguous: time_index({j})={row}, expected {}",
start_row + j
)));
}
}
if start_row
.checked_add(bus.chunk_size)
.map_or(true, |end| end > n_pad)
{
return Err(PiCcsError::InvalidInput(format!(
"bus time row range out of bounds: start_row={} chunk_size={} n_pad={}",
start_row, bus.chunk_size, n_pad
)));
}
if core_t < me.ct.len() {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require core_t >= ME core ct len (core_t={}, ct.len()={})",
core_t,
me.ct.len(),
)));
}
let aux_base = core_t
.checked_sub(me.ct.len())
.ok_or_else(|| PiCcsError::InvalidInput("core_t underflow for bus aux base".into()))?;
// Idempotent append: allow callers to call this once; reject unexpected aux lengths.
let want_aux_len = aux_base
.checked_add(bus.bus_cols)
.ok_or_else(|| PiCcsError::InvalidInput("aux_base + bus_cols overflow".into()))?;
if me.aux_openings.len() >= want_aux_len {
return Ok(());
}
if me.aux_openings.len() != aux_base {
return Err(PiCcsError::InvalidInput(format!(
"bus openings expect ME aux_openings to start at aux_base (aux_openings.len()={}, aux_base={})",
me.aux_openings.len(),
aux_base
)));
}
for (j, row) in me.y_ring.iter().enumerate() {
if row.len() != y_pad {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require ME.y_ring[{j}].len()==y_pad (got {}, want {})",
row.len(),
y_pad
)));
}
}
// Precompute χ_r(time_index(j)) weights for the bus time rows.
let time_weights = precompute_contiguous_time_weights(&me.r, start_row, bus.chunk_size, n_pad)?;
let weighted_rows: Vec<(usize, K)> = time_weights
.into_iter()
.enumerate()
.filter_map(|(j, w)| (w != K::ZERO).then_some((j, w)))
.collect();
// Decode once into logical witness coordinates so openings are layout-agnostic.
let z_logical = decode_cpu_z_to_k(params, Z, bus.m)?;
// Append bus openings in canonical col_id order so `bus_y_base = ct.len() - bus_cols`
// remains valid.
for col_id in 0..bus.bus_cols {
let col_base = bus
.bus_base
.checked_add(
col_id
.checked_mul(bus.chunk_size)
.ok_or_else(|| PiCcsError::InvalidInput("bus col_id * chunk_size overflow".into()))?,
)
.ok_or_else(|| PiCcsError::InvalidInput("bus col_base overflow".into()))?;
let mut y_scalar = K::ZERO;
for &(j, w) in weighted_rows.iter() {
let idx = col_base
.checked_add(j)
.ok_or_else(|| PiCcsError::InvalidInput("bus cell index overflow".into()))?;
let v = z_logical.get(idx).copied().ok_or_else(|| {
PiCcsError::InvalidInput(format!(
"bus openings: logical index out of range (idx={idx}, m={})",
z_logical.len()
))
})?;
y_scalar += w * v;
}
me.aux_openings.push(y_scalar);
}
Ok(())
}
pub(crate) fn shared_bus_openings_from_time_columns_at_point(
bus: &BusLayout,
mem_cols: &[Vec<F>],
point: &[K],
label: &str,
) -> Result<BTreeMap<usize, K>, PiCcsError> {
if bus.bus_cols == 0 {
return Ok(BTreeMap::new());
}
if mem_cols.len() != bus.bus_cols {
return Err(PiCcsError::InvalidInput(format!(
"{label}: mem_cols.len()={} != bus.bus_cols={}",
mem_cols.len(),
bus.bus_cols
)));
}
if point.is_empty() {
return Err(PiCcsError::InvalidInput(format!("{label}: point must be non-empty")));
}
let n_pad = 1usize
.checked_shl(point.len() as u32)
.ok_or_else(|| PiCcsError::InvalidInput(format!("{label}: 2^ell_n overflow")))?;
let start_row = bus.time_index(0);
for j in 0..bus.chunk_size {
let row = bus.time_index(j);
if row >= n_pad {
return Err(PiCcsError::InvalidInput(format!(
"{label}: bus time row index out of range: t={row} >= 2^ell_n={n_pad}"
)));
}
if row != start_row + j {
return Err(PiCcsError::InvalidInput(format!(
"{label}: bus time_index must be contiguous: time_index({j})={row}, expected {}",
start_row + j
)));
}
}
if start_row
.checked_add(bus.chunk_size)
.map_or(true, |end| end > n_pad)
{
return Err(PiCcsError::InvalidInput(format!(
"{label}: bus time row range out of bounds: start_row={} chunk_size={} n_pad={}",
start_row, bus.chunk_size, n_pad
)));
}
let time_weights = precompute_contiguous_time_weights(point, start_row, bus.chunk_size, n_pad)?;
let weighted_rows: Vec<(usize, K)> = time_weights
.into_iter()
.enumerate()
.filter_map(|(j, w)| (w != K::ZERO).then_some((j, w)))
.collect();
let mut out = BTreeMap::new();
for col_id in 0..bus.bus_cols {
let vals = mem_cols
.get(col_id)
.ok_or_else(|| PiCcsError::InvalidInput(format!("{label}: missing mem column {col_id}")))?;
if vals.len() != bus.chunk_size {
return Err(PiCcsError::InvalidInput(format!(
"{label}: time mem column length mismatch for bus col_id={col_id}: len={}, chunk_size={}",
vals.len(),
bus.chunk_size
)));
}
let mut eval = K::ZERO;
for &(j, w) in weighted_rows.iter() {
eval += w * K::from(vals[j]);
}
out.insert(col_id, eval);
}
Ok(out)
}
pub(crate) fn time_columns_openings_from_time_columns_at_point(
m_in: usize,
t_len: usize,
cpu_cols: &[Vec<F>],
col_ids: &[usize],
point: &[K],
label: &str,
) -> Result<BTreeMap<usize, K>, PiCcsError> {
if t_len == 0 {
return Err(PiCcsError::InvalidInput(format!("{label}: t_len must be non-zero")));
}
if point.is_empty() {
return Err(PiCcsError::InvalidInput(format!("{label}: point must be non-empty")));
}
let n_pad = 1usize
.checked_shl(point.len() as u32)
.ok_or_else(|| PiCcsError::InvalidInput(format!("{label}: 2^ell_n overflow")))?;
if m_in.checked_add(t_len).map_or(true, |end| end > n_pad) {
return Err(PiCcsError::InvalidInput(format!(
"{label}: time row range out of bounds: m_in={} t_len={} n_pad={}",
m_in, t_len, n_pad
)));
}
let time_weights = precompute_contiguous_time_weights(point, m_in, t_len, n_pad)?;
let weighted_rows: Vec<(usize, K)> = time_weights
.into_iter()
.enumerate()
.filter_map(|(j, w)| (w != K::ZERO).then_some((j, w)))
.collect();
let mut out = BTreeMap::new();
for &col_id in col_ids {
let vals = cpu_cols.get(col_id).ok_or_else(|| {
PiCcsError::InvalidInput(format!(
"{label}: trace col_id {} out of range for cpu_cols.len()={}",
col_id,
cpu_cols.len()
))
})?;
if vals.len() != t_len {
return Err(PiCcsError::InvalidInput(format!(
"{label}: time cpu column length mismatch for col_id={col_id}: len={}, t_len={t_len}",
vals.len()
)));
}
let mut eval = K::ZERO;
for &(j, w) in weighted_rows.iter() {
eval += w * K::from(vals[j]);
}
out.insert(col_id, eval);
}
Ok(out)
}
pub(crate) fn append_bus_openings_to_me_instance_from_time_columns<Cmt>(
params: &NeoParams,
bus: &BusLayout,
core_t: usize,
mem_cols: &[Vec<F>],
me: &mut CeClaim<Cmt, F, K>,
) -> Result<(), PiCcsError>
where
Cmt: Clone,
{
if bus.bus_cols == 0 {
return Ok(());
}
if mem_cols.len() != bus.bus_cols {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require mem_cols.len()==bus.bus_cols (got {}, want {})",
mem_cols.len(),
bus.bus_cols
)));
}
let y_pad = (params.d as usize).next_power_of_two();
let d = neo_math::D;
if y_pad < d {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require y_pad >= D (y_pad={y_pad}, D={d})"
)));
}
let n_pad = 1usize
.checked_shl(me.r.len() as u32)
.ok_or_else(|| PiCcsError::InvalidInput("2^ell_n overflow".into()))?;
let start_row = bus.time_index(0);
for j in 0..bus.chunk_size {
let row = bus.time_index(j);
if row >= n_pad {
return Err(PiCcsError::InvalidInput(format!(
"bus time row index out of range: t={row} >= 2^ell_n={n_pad}"
)));
}
if row != start_row + j {
return Err(PiCcsError::InvalidInput(format!(
"bus time_index must be contiguous: time_index({j})={row}, expected {}",
start_row + j
)));
}
}
if start_row
.checked_add(bus.chunk_size)
.map_or(true, |end| end > n_pad)
{
return Err(PiCcsError::InvalidInput(format!(
"bus time row range out of bounds: start_row={} chunk_size={} n_pad={}",
start_row, bus.chunk_size, n_pad
)));
}
let want_len = core_t
.checked_add(bus.bus_cols)
.ok_or_else(|| PiCcsError::InvalidInput("core_t + bus_cols overflow".into()))?;
if me.y_ring.len() == want_len && me.ct.len() == want_len {
return Ok(());
}
if me.y_ring.len() != core_t || me.ct.len() != core_t {
return Err(PiCcsError::InvalidInput(format!(
"bus openings expect ME y/ct to start at core_t (y.len()={}, ct.len()={}, core_t={})",
me.y_ring.len(),
me.ct.len(),
core_t
)));
}
for (j, row) in me.y_ring.iter().enumerate() {
if row.len() != y_pad {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require ME.y_ring[{j}].len()==y_pad (got {}, want {})",
row.len(),
y_pad
)));
}
}
let time_weights = precompute_contiguous_time_weights(&me.r, start_row, bus.chunk_size, n_pad)?;
let weighted_rows: Vec<(usize, K)> = time_weights
.into_iter()
.enumerate()
.filter_map(|(j, w)| (w != K::ZERO).then_some((j, w)))
.collect();
let bK = K::from(F::from_u64(params.b as u64));
let mut pow_b = Vec::with_capacity(d);
let mut cur = K::ONE;
for _ in 0..d {
pow_b.push(cur);
cur *= bK;
}
for col_id in 0..bus.bus_cols {
let vals = mem_cols
.get(col_id)
.ok_or_else(|| PiCcsError::InvalidInput(format!("missing mem column {col_id} for bus openings")))?;
if vals.len() != bus.chunk_size {
return Err(PiCcsError::InvalidInput(format!(
"time mem column length mismatch for bus col_id={col_id}: len={}, chunk_size={}",
vals.len(),
bus.chunk_size
)));
}
let mut y_row = vec![K::ZERO; y_pad];
let mut acc = K::ZERO;
for &(j, w) in weighted_rows.iter() {
acc += w * K::from(vals[j]);
}
y_row[0] = acc;
let y_scalar = acc * pow_b[0];
me.y_ring.push(y_row);
me.ct.push(y_scalar);
}
Ok(())
}
pub(crate) fn append_zero_bus_openings_to_me_instance<Cmt>(
params: &NeoParams,
bus: &BusLayout,
core_t: usize,
me: &mut CeClaim<Cmt, F, K>,
) -> Result<(), PiCcsError>
where
Cmt: Clone,
{
if bus.bus_cols == 0 {
return Ok(());
}
let y_pad = (params.d as usize).next_power_of_two();
let d = neo_math::D;
if y_pad < d {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require y_pad >= D (y_pad={y_pad}, D={d})"
)));
}
let want_len = core_t
.checked_add(bus.bus_cols)
.ok_or_else(|| PiCcsError::InvalidInput("core_t + bus_cols overflow".into()))?;
if me.y_ring.len() == want_len && me.ct.len() == want_len {
return Ok(());
}
if me.y_ring.len() != core_t || me.ct.len() != core_t {
return Err(PiCcsError::InvalidInput(format!(
"bus openings expect ME y/ct to start at core_t (y.len()={}, ct.len()={}, core_t={})",
me.y_ring.len(),
me.ct.len(),
core_t
)));
}
for (j, row) in me.y_ring.iter().enumerate() {
if row.len() != y_pad {
return Err(PiCcsError::InvalidInput(format!(
"bus openings require ME.y_ring[{j}].len()==y_pad (got {}, want {})",
row.len(),
y_pad
)));
}
}
for _ in 0..bus.bus_cols {
me.y_ring.push(vec![K::ZERO; y_pad]);
me.ct.push(K::ZERO);
}
Ok(())
}
pub(crate) fn append_zero_time_openings_to_me_instance<Cmt>(
params: &NeoParams,
num_openings: usize,
core_t: usize,
me: &mut CeClaim<Cmt, F, K>,
) -> Result<(), PiCcsError>
where
Cmt: Clone,
{
if num_openings == 0 {
return Ok(());
}
let y_pad = (params.d as usize).next_power_of_two();
let d = neo_math::D;
if y_pad < d {
return Err(PiCcsError::InvalidInput(format!(
"time openings require y_pad >= D (y_pad={y_pad}, D={d})"
)));
}
let want_len = core_t
.checked_add(num_openings)
.ok_or_else(|| PiCcsError::InvalidInput("core_t + num_openings overflow".into()))?;
if me.y_ring.len() == want_len && me.ct.len() == want_len {
return Ok(());
}
if me.y_ring.len() != core_t || me.ct.len() != core_t {
return Err(PiCcsError::InvalidInput(format!(
"time openings expect ME y/ct to start at core_t (y.len()={}, ct.len()={}, core_t={})",
me.y_ring.len(),
me.ct.len(),
core_t
)));
}
for (j, row) in me.y_ring.iter().enumerate() {
if row.len() != y_pad {
return Err(PiCcsError::InvalidInput(format!(
"time openings require ME.y_ring[{j}].len()==y_pad (got {}, want {})",
row.len(),
y_pad
)));
}
}
for _ in 0..num_openings {
me.y_ring.push(vec![K::ZERO; y_pad]);
me.ct.push(K::ZERO);
}
Ok(())
}
pub(crate) fn append_time_columns_openings_to_me_instance<Cmt>(
params: &NeoParams,
m_in: usize,
t_len: usize,
cpu_cols: &[Vec<F>],
cols: &[usize],
core_t: usize,
me: &mut CeClaim<Cmt, F, K>,
) -> Result<(), PiCcsError>
where
Cmt: Clone,
{
append_time_columns_openings_to_me_instance_with_row_base(params, m_in, m_in, t_len, cpu_cols, cols, core_t, me)
}
pub(crate) fn append_time_columns_openings_to_me_instance_with_row_base<Cmt>(
params: &NeoParams,
m_in: usize,
row_base: usize,
t_len: usize,
cpu_cols: &[Vec<F>],
cols: &[usize],
core_t: usize,
me: &mut CeClaim<Cmt, F, K>,
) -> Result<(), PiCcsError>
where
Cmt: Clone,
{
if cols.is_empty() {
return Ok(());
}
if t_len == 0 {
return Err(PiCcsError::InvalidInput("time openings require t_len >= 1".into()));
}
let y_pad = (params.d as usize).next_power_of_two();
let d = neo_math::D;
if y_pad < d {
return Err(PiCcsError::InvalidInput(format!(
"time openings require y_pad >= D (y_pad={y_pad}, D={d})"
)));
}
if me.m_in != m_in {
return Err(PiCcsError::InvalidInput(format!(
"time openings require ME.m_in==m_in (got {}, want {})",
me.m_in, m_in
)));
}
if me.r.is_empty() {
return Err(PiCcsError::InvalidInput("time openings require non-empty ME.r".into()));
}
let n_pad = 1usize