This repository was archived by the owner on Sep 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathwitness.rs
More file actions
1754 lines (1568 loc) · 54.3 KB
/
Copy pathwitness.rs
File metadata and controls
1754 lines (1568 loc) · 54.3 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
// Copyright 2025 Irreducible Inc.
use std::{
cell::{Ref, RefCell, RefMut},
iter,
ops::{Deref, DerefMut},
slice,
sync::Arc,
};
use binius_compute::alloc::{ComputeAllocator, HostBumpAllocator};
use binius_core::witness::{MultilinearExtensionIndex, MultilinearWitness};
use binius_fast_compute::arith_circuit::ArithCircuitPoly;
use binius_field::{
ExtensionField, PackedExtension, PackedField, PackedFieldIndexable, PackedSubfield, TowerField,
arch::OptimalUnderlier,
as_packed_field::PackedType,
packed::{get_packed_slice, set_packed_slice},
};
use binius_math::{
ArithCircuit, CompositionPoly, MultilinearExtension, MultilinearPoly, RowsBatchRef,
};
use binius_maybe_rayon::prelude::*;
use binius_utils::checked_arithmetics::checked_log_2;
use bytemuck::{Pod, must_cast_slice, must_cast_slice_mut, zeroed_vec};
use either::Either;
use getset::CopyGetters;
use itertools::Itertools;
use super::{
ColumnDef, ColumnId, ColumnInfo, ConstraintSystem, Expr,
column::{Col, ColumnShape},
constraint_system::OracleMapping,
error::Error,
table::{self, Table, TableId},
types::{B1, B8, B16, B32, B64, B128},
};
use crate::builder::multi_iter::MultiIterator;
/// Holds witness column data for all tables in a constraint system, indexed by column ID.
///
/// The struct has two lifetimes: `'cs` is the lifetime of the constraint system, and `'alloc` is
/// the lifetime of the bump allocator. The reason these must be separate is that the witness index
/// gets converted into a multilinear extension index, which maintains references to the data
/// allocated by the allocator, but does not need to maintain a reference to the constraint system,
/// which can then be dropped.
pub struct WitnessIndex<'cs, 'alloc, P = PackedType<OptimalUnderlier, B128>>
where
P: PackedField,
P::Scalar: TowerField,
{
cs: &'cs ConstraintSystem<P::Scalar>,
allocator: &'alloc HostBumpAllocator<'alloc, P>,
/// Each entry is Left if the index hasn't been initialized & filled, and Right if it has.
tables: Vec<Either<&'cs Table<P::Scalar>, TableWitnessIndex<'cs, 'alloc, P>>>,
}
impl<'cs, 'alloc, F: TowerField, P: PackedField<Scalar = F>> WitnessIndex<'cs, 'alloc, P> {
/// Creates and allocates the witness index for a constraint system.
pub fn new(
cs: &'cs ConstraintSystem<F>,
allocator: &'alloc HostBumpAllocator<'alloc, P>,
) -> Self {
Self {
cs,
allocator,
tables: cs.tables.iter().map(Either::Left).collect(),
}
}
pub fn init_table(
&mut self,
table_id: TableId,
size: usize,
) -> Result<&mut TableWitnessIndex<'cs, 'alloc, P>, Error> {
match self.tables.get_mut(table_id) {
Some(entry) => match entry {
Either::Left(table) => {
if size == 0 {
Err(Error::EmptyTable { table_id })
} else {
let table_witness = TableWitnessIndex::new(self.allocator, table, size)?;
*entry = Either::Right(table_witness);
let Either::Right(table_witness) = entry else {
unreachable!("entry is assigned to this pattern on the previous line")
};
Ok(table_witness)
}
}
Either::Right(_) => Err(Error::TableIndexAlreadyInitialized { table_id }),
},
None => Err(Error::MissingTable { table_id }),
}
}
pub fn get_table(
&mut self,
table_id: TableId,
) -> Option<&mut TableWitnessIndex<'cs, 'alloc, P>> {
self.tables.get_mut(table_id).and_then(|table| match table {
Either::Left(_) => None,
Either::Right(index) => Some(index),
})
}
pub fn fill_table_sequential<T: TableFiller<P>>(
&mut self,
filler: &T,
rows: &[T::Event],
) -> Result<(), Error> {
self.init_and_fill_table(
filler.id(),
|table_witness, rows| table_witness.fill_sequential(filler, rows),
rows,
)
}
pub fn fill_table_parallel<T>(&mut self, filler: &T, rows: &[T::Event]) -> Result<(), Error>
where
T: TableFiller<P> + Sync,
T::Event: Sync,
{
self.init_and_fill_table(
filler.id(),
|table_witness, rows| table_witness.fill_parallel(filler, rows),
rows,
)
}
fn init_and_fill_table<Event>(
&mut self,
table_id: TableId,
fill: impl FnOnce(&mut TableWitnessIndex<'cs, 'alloc, P>, &[Event]) -> Result<(), Error>,
rows: &[Event],
) -> Result<(), Error> {
match self.tables.get_mut(table_id) {
Some(entry) => match entry {
Either::Right(witness) => fill(witness, rows),
Either::Left(table) => {
if rows.is_empty() {
Ok(())
} else {
let mut table_witness =
TableWitnessIndex::new(self.allocator, table, rows.len())?;
fill(&mut table_witness, rows)?;
*entry = Either::Right(table_witness);
Ok(())
}
}
},
None => Err(Error::MissingTable { table_id }),
}
}
/// Returns the sizes of all tables in the witness, indexed by table ID.
pub fn table_sizes(&self) -> Vec<usize> {
self.tables
.iter()
.map(|entry| match entry {
Either::Left(_) => 0,
Either::Right(index) => index.size(),
})
.collect()
}
fn mk_column_witness<'a>(
log_capacity: usize,
shape: ColumnShape,
data: &'a [P],
) -> MultilinearWitness<'a, P>
where
P: PackedExtension<B1>
+ PackedExtension<B8>
+ PackedExtension<B16>
+ PackedExtension<B32>
+ PackedExtension<B64>
+ PackedExtension<B128>,
{
let n_vars = log_capacity + shape.log_values_per_row;
let underlier_count =
1 << (n_vars + shape.tower_height).saturating_sub(P::LOG_WIDTH + F::TOWER_LEVEL);
multilin_poly_from_underlier_data(&data[..underlier_count], n_vars, shape.tower_height)
}
/// Converts this witness into binius_core's [`MultilinearExtensionIndex`].
///
/// Note that this function must be called only after the [`ConstraintSystem::compile`].
pub fn into_multilinear_extension_index(self) -> MultilinearExtensionIndex<'alloc, P>
where
P: PackedExtension<B1>
+ PackedExtension<B8>
+ PackedExtension<B16>
+ PackedExtension<B32>
+ PackedExtension<B64>
+ PackedExtension<B128>,
{
let oracle_lookup = self.cs.oracle_lookup();
let mut index = MultilinearExtensionIndex::new();
for table_witness in self.tables {
let Either::Right(table_witness) = table_witness else {
continue;
};
let cols = immutable_witness_index_columns(table_witness.cols);
// Here our objective is to add a witness for every oracle the table has created.
//
// There are some tricky parts that is worth keeping in mind:
//
// 1. Some oracles share witnesses, e.g. packed column has the same witness as the
// column that it packs. Despite that they cannot share the underlying witness
// polynomial because of the difference in n_vars.
//
// 2. Similarly, the constant column creates two oracles: the original constant and the
// the user-visible one, repeating column. Instead of making the user to fill both
// witnesses, we fill the original constant oracle with the truncated version of the
// repeating column.
//
for col in cols.into_iter() {
let oracle_mapping = *oracle_lookup.lookup(col.column_id);
match oracle_mapping {
OracleMapping::Regular(oracle_id) => index
.update_multilin_poly([(
oracle_id,
Self::mk_column_witness(
table_witness.log_capacity,
col.shape,
col.data,
),
)])
.unwrap(),
OracleMapping::TransparentCompound {
original,
repeating,
} => {
// Create a single row poly witness for the original oracle and the
// repeating version of that for the repeating oracle.
let original_witness = Self::mk_column_witness(0, col.shape, col.data);
let repeating_witness = Self::mk_column_witness(
table_witness.log_capacity,
col.shape,
col.data,
);
index
.update_multilin_poly([
(original, original_witness),
(repeating, repeating_witness),
])
.unwrap();
}
}
}
}
index
}
}
impl<'cs, 'alloc, P> WitnessIndex<'cs, 'alloc, P>
where
P: PackedField<Scalar: TowerField>
+ PackedExtension<B1>
+ PackedExtension<B8>
+ PackedExtension<B16>
+ PackedExtension<B32>
+ PackedExtension<B64>
+ PackedExtension<B128>,
{
/// Automatically populate the witness data for all the constant columns in all the tables with
/// a [`TableWitnessIndex<P>`].
pub fn fill_constant_cols(&mut self) -> Result<(), Error> {
for table in self.tables.iter_mut() {
match table.as_mut() {
Either::Left(_) => (),
// If we have witness index data, populate the witness
Either::Right(table_witness_index) => {
let table = table_witness_index.table();
let segment = table_witness_index.full_segment();
for col in table.columns.iter() {
if let ColumnDef::Constant { data, .. } = &col.col {
let mut witness_data = segment.get_dyn_mut(col.id)?;
let len = witness_data.size();
for (i, scalar) in data.iter().cycle().take(len).enumerate() {
witness_data.set(i, *scalar)?
}
}
}
}
}
}
Ok(())
}
}
fn multilin_poly_from_underlier_data<P>(
data: &[P],
n_vars: usize,
tower_height: usize,
) -> Arc<dyn MultilinearPoly<P> + Send + Sync + '_>
where
P: PackedExtension<B1>
+ PackedExtension<B8>
+ PackedExtension<B16>
+ PackedExtension<B32>
+ PackedExtension<B64>
+ PackedExtension<B128>,
{
match tower_height {
0 => MultilinearExtension::new(n_vars, PackedExtension::<B1>::cast_bases(data))
.unwrap()
.specialize_arc_dyn(),
3 => MultilinearExtension::new(n_vars, PackedExtension::<B8>::cast_bases(data))
.unwrap()
.specialize_arc_dyn(),
4 => MultilinearExtension::new(n_vars, PackedExtension::<B16>::cast_bases(data))
.unwrap()
.specialize_arc_dyn(),
5 => MultilinearExtension::new(n_vars, PackedExtension::<B32>::cast_bases(data))
.unwrap()
.specialize_arc_dyn(),
6 => MultilinearExtension::new(n_vars, PackedExtension::<B64>::cast_bases(data))
.unwrap()
.specialize_arc_dyn(),
7 => MultilinearExtension::new(n_vars, PackedExtension::<B128>::cast_bases(data))
.unwrap()
.specialize_arc_dyn(),
_ => {
panic!("Unsupported tower height: {tower_height}");
}
}
}
/// Holds witness column data for a table, indexed by column index.
#[derive(Debug, CopyGetters)]
pub struct TableWitnessIndex<'cs, 'alloc, P = PackedType<OptimalUnderlier, B128>>
where
P: PackedField,
P::Scalar: TowerField,
{
#[get_copy = "pub"]
table: &'cs Table<P::Scalar>,
cols: Vec<WitnessIndexColumn<'alloc, P>>,
/// The number of table events that the index should contain.
#[get_copy = "pub"]
size: usize,
#[get_copy = "pub"]
log_capacity: usize,
/// Binary logarithm of the mininimum segment size.
///
/// This is the minimum number of logical rows that can be put into one segment during
/// iteration. It is the maximum number of logical rows occupied by a single underlier.
#[get_copy = "pub"]
min_log_segment_size: usize,
}
#[derive(Debug)]
pub struct WitnessIndexColumn<'a, P: PackedField> {
shape: ColumnShape,
data: WitnessDataMut<'a, P>,
column_id: ColumnId,
}
#[derive(Debug, Clone)]
enum WitnessColumnInfo<T> {
Owned(T),
/// This column is same as the column stored in `cols[.0]`.
SameAsIndex(usize),
}
type WitnessDataMut<'a, P> = WitnessColumnInfo<&'a mut [P]>;
impl<'a, P: PackedField> WitnessDataMut<'a, P> {
pub fn new_owned(allocator: &'a HostBumpAllocator<'a, P>, log_underlier_count: usize) -> Self {
let slice = allocator
.alloc(1 << log_underlier_count)
.expect("failed to allocate witness data slice");
Self::Owned(slice)
}
}
type RefCellData<'a, P> = WitnessColumnInfo<RefCell<&'a mut [P]>>;
#[derive(Debug)]
struct ImmutableWitnessIndexColumn<'a, P: PackedField> {
shape: ColumnShape,
data: &'a [P],
column_id: ColumnId,
}
/// Converts the vector of witness columns into immutable references to column data that may be
/// shared.
fn immutable_witness_index_columns<P: PackedField>(
cols: Vec<WitnessIndexColumn<P>>,
) -> Vec<ImmutableWitnessIndexColumn<P>> {
let mut result = Vec::<ImmutableWitnessIndexColumn<_>>::with_capacity(cols.len());
for col in cols {
result.push(ImmutableWitnessIndexColumn {
shape: col.shape,
data: match col.data {
WitnessDataMut::Owned(data) => data,
WitnessDataMut::SameAsIndex(index) => result[index].data,
},
column_id: col.column_id,
});
}
result
}
impl<'cs, 'alloc, F: TowerField, P: PackedField<Scalar = F>> TableWitnessIndex<'cs, 'alloc, P> {
pub(crate) fn new(
allocator: &'alloc HostBumpAllocator<'alloc, P>,
table: &'cs Table<F>,
size: usize,
) -> Result<Self, Error> {
if size == 0 {
return Err(Error::EmptyTable {
table_id: table.id(),
});
}
let log_capacity = table::log_capacity(size);
let packed_elem_log_bits = P::LOG_WIDTH + F::TOWER_LEVEL;
let mut cols = Vec::with_capacity(table.columns.len());
for ColumnInfo { id, col, shape, .. } in &table.columns {
let data: WitnessDataMut<P> = if let ColumnDef::Packed { col: source, .. } = col {
// Packed column reuses the witness of the one it is based on.
WitnessDataMut::SameAsIndex(source.table_index.0)
} else {
// Everything else has it's own column.
WitnessDataMut::new_owned(
allocator,
(shape.log_cell_size() + log_capacity).saturating_sub(packed_elem_log_bits),
)
};
cols.push(WitnessIndexColumn {
shape: *shape,
data,
column_id: *id,
});
}
// The minimum segment size is chosen such that the segment of each column is at least one
// underlier in size.
let min_log_segment_size = packed_elem_log_bits
- table
.columns
.iter()
.map(|col| col.shape.log_cell_size())
.fold(packed_elem_log_bits, |a, b| a.min(b));
// But, in case the minimum segment size is larger than the capacity, we lower it so the
// caller can get the full witness index in one segment. This is OK because the extra field
// elements in the smallest columns are just padding.
let min_log_segment_size = min_log_segment_size.min(log_capacity);
Ok(Self {
table,
cols,
size,
log_capacity,
min_log_segment_size,
})
}
pub fn table_id(&self) -> TableId {
self.table.id
}
pub fn capacity(&self) -> usize {
1 << self.log_capacity
}
/// Returns a witness index segment covering the entire table.
pub fn full_segment(&mut self) -> TableWitnessSegment<P> {
let cols = self
.cols
.iter_mut()
.map(|col| match &mut col.data {
WitnessDataMut::SameAsIndex(id) => RefCellData::SameAsIndex(*id),
WitnessDataMut::Owned(data) => RefCellData::Owned(RefCell::new(data)),
})
.collect();
TableWitnessSegment {
table: self.table,
cols,
log_size: self.log_capacity,
index: 0,
}
}
/// Fill a full table witness index using the given row data.
///
/// This function iterates through witness segments sequentially in a single thread.
pub fn fill_sequential<T: TableFiller<P>>(
&mut self,
table: &T,
rows: &[T::Event],
) -> Result<(), Error> {
let log_size = self.optimal_segment_size_heuristic();
self.fill_sequential_with_segment_size(table, rows, log_size)
}
/// Fill a full table witness index using the given row data.
///
/// This function iterates through witness segments in parallel in multiple threads.
pub fn fill_parallel<T>(&mut self, table: &T, rows: &[T::Event]) -> Result<(), Error>
where
T: TableFiller<P> + Sync,
T::Event: Sync,
{
let log_size = self.optimal_segment_size_heuristic();
self.fill_parallel_with_segment_size(table, rows, log_size)
}
fn optimal_segment_size_heuristic(&self) -> usize {
// As a heuristic, choose log_size so that the median column segment size is 4 KiB.
const TARGET_SEGMENT_LOG_BITS: usize = 12 + 3;
let n_cols = self.table.columns.len();
let median_col_log_bits = self
.table
.columns
.iter()
.map(|col| col.shape.log_cell_size())
.sorted()
.nth(n_cols / 2)
.unwrap_or_default();
TARGET_SEGMENT_LOG_BITS.saturating_sub(median_col_log_bits)
}
/// Fill a full table witness index using the given row data.
///
/// This function iterates through witness segments sequentially in a single thread.
pub fn fill_sequential_with_segment_size<T: TableFiller<P>>(
&mut self,
table: &T,
rows: &[T::Event],
log_size: usize,
) -> Result<(), Error> {
if rows.len() != self.size {
return Err(Error::IncorrectNumberOfTableEvents {
expected: self.size,
actual: rows.len(),
});
}
let mut segmented_view = TableWitnessSegmentedView::new(self, log_size);
// Overwrite log_size because it may need to get clamped.
let log_size = segmented_view.log_segment_size;
let segment_size = 1 << log_size;
// rows.len() equals self.size and self.size is check to be non-zero in the constructor
debug_assert_ne!(rows.len(), 0);
// number of chunks is rounded up
let n_chunks = (rows.len() - 1) / segment_size + 1;
let (full_chunk_segments, mut rest_segments) = segmented_view.split_at(n_chunks - 1);
// Fill segments of the table with full chunks
full_chunk_segments
.into_iter()
// by taking n_chunks - 1, we guarantee that all row chunks are full
.zip(rows.chunks(segment_size).take(n_chunks - 1))
.try_for_each(|(mut witness_segment, row_chunk)| {
table
.fill(row_chunk, &mut witness_segment)
.map_err(Error::TableFill)
})?;
// Fill the last segment. There may not be enough events to match the size of the segment,
// which is a pre-condition for TableFiller::fill. In that case, we clone the last event to
// pad the row_chunk. Since it's a clone, the filled witness should satisfy all row-wise
// constraints as long as all the given events do.
let row_chunk = &rows[(n_chunks - 1) * segment_size..];
let mut padded_row_chunk = Vec::new();
let row_chunk = if row_chunk.len() != segment_size {
padded_row_chunk.reserve(segment_size);
padded_row_chunk.extend_from_slice(row_chunk);
let last_event = row_chunk
.last()
.expect("row_chunk must be non-empty because of how n_chunk is calculated")
.clone();
padded_row_chunk.resize(segment_size, last_event);
&padded_row_chunk
} else {
row_chunk
};
let (partial_chunk_segments, rest_segments) = rest_segments.split_at(1);
let mut partial_chunk_segment_iter = partial_chunk_segments.into_iter();
let mut witness_segment = partial_chunk_segment_iter.next().expect(
"segmented_view.split_at called with 1 must return a view with exactly one segment",
);
table
.fill(row_chunk, &mut witness_segment)
.map_err(Error::TableFill)?;
assert!(partial_chunk_segment_iter.next().is_none());
// Finally, copy the last filled segment to the remaining segments. This should satisfy all
// row-wise constraints if the last segment does.
let last_segment_cols = witness_segment
.cols
.iter_mut()
.map(|col| match col {
RefCellData::Owned(data) => WitnessColumnInfo::Owned(data.get_mut()),
RefCellData::SameAsIndex(idx) => WitnessColumnInfo::SameAsIndex(*idx),
})
.collect::<Vec<_>>();
rest_segments.into_iter().for_each(|mut segment| {
for (dst_col, src_col) in iter::zip(&mut segment.cols, &last_segment_cols) {
if let (RefCellData::Owned(dst), WitnessColumnInfo::Owned(src)) = (dst_col, src_col)
{
dst.get_mut().copy_from_slice(src)
}
}
});
Ok(())
}
/// Fill a full table witness index using the given row data.
///
/// This function iterates through witness segments in parallel in multiple threads.
pub fn fill_parallel_with_segment_size<T>(
&mut self,
table: &T,
rows: &[T::Event],
log_size: usize,
) -> Result<(), Error>
where
T: TableFiller<P> + Sync,
T::Event: Sync,
{
if rows.len() != self.size {
return Err(Error::IncorrectNumberOfTableEvents {
expected: self.size,
actual: rows.len(),
});
}
// This implementation duplicates a lot of code with `fill_sequential_with_segment_size`.
// We could either refactor to deduplicate or just remove `fill_sequential` once this
// method is more battle-tested.
let mut segmented_view = TableWitnessSegmentedView::new(self, log_size);
// Overwrite log_size because it may need to get clamped.
let log_size = segmented_view.log_segment_size;
let segment_size = 1 << log_size;
// rows.len() equals self.size and self.size is check to be non-zero in the constructor
debug_assert_ne!(rows.len(), 0);
// number of chunks is rounded up
let n_chunks = (rows.len() - 1) / segment_size + 1;
let (full_chunk_segments, mut rest_segments) = segmented_view.split_at(n_chunks - 1);
// Fill segments of the table with full chunks
full_chunk_segments
.into_par_iter()
// by taking n_chunks - 1, we guarantee that all row chunks are full
.zip(rows.par_chunks(segment_size).take(n_chunks - 1))
.try_for_each(|(mut witness_segment, row_chunk)| {
table
.fill(row_chunk, &mut witness_segment)
.map_err(Error::TableFill)
})?;
// Fill the last segment. There may not be enough events to match the size of the segment,
// which is a pre-condition for TableFiller::fill. In that case, we clone the last event to
// pad the row_chunk. Since it's a clone, the filled witness should satisfy all row-wise
// constraints as long as all the given events do.
let row_chunk = &rows[(n_chunks - 1) * segment_size..];
let mut padded_row_chunk = Vec::new();
let row_chunk = if row_chunk.len() != segment_size {
padded_row_chunk.reserve(segment_size);
padded_row_chunk.extend_from_slice(row_chunk);
let last_event = row_chunk
.last()
.expect("row_chunk must be non-empty because of how n_chunk is calculated")
.clone();
padded_row_chunk.resize(segment_size, last_event);
&padded_row_chunk
} else {
row_chunk
};
let (partial_chunk_segments, rest_segments) = rest_segments.split_at(1);
let mut partial_chunk_segment_iter = partial_chunk_segments.into_iter();
let mut witness_segment = partial_chunk_segment_iter.next().expect(
"segmented_view.split_at called with 1 must return a view with exactly one segment",
);
table
.fill(row_chunk, &mut witness_segment)
.map_err(Error::TableFill)?;
assert!(partial_chunk_segment_iter.next().is_none());
// Finally, copy the last filled segment to the remaining segments. This should satisfy all
// row-wise constraints if the last segment does.
let last_segment_cols = witness_segment
.cols
.iter_mut()
.map(|col| match col {
RefCellData::Owned(data) => WitnessColumnInfo::Owned(data.get_mut()),
RefCellData::SameAsIndex(idx) => WitnessColumnInfo::SameAsIndex(*idx),
})
.collect::<Vec<_>>();
rest_segments.into_par_iter().for_each(|mut segment| {
for (dst_col, src_col) in iter::zip(&mut segment.cols, &last_segment_cols) {
if let (RefCellData::Owned(dst), WitnessColumnInfo::Owned(src)) = (dst_col, src_col)
{
dst.get_mut().copy_from_slice(src)
}
}
});
Ok(())
}
/// Returns an iterator over segments of witness index rows.
///
/// This method clamps the segment size, requested as `log_size`, to a minimum of
/// `self.min_log_segment_size()` and a maximum of `self.log_capacity()`. The actual segment
/// size can be queried on the items yielded by the iterator.
pub fn segments(&mut self, log_size: usize) -> impl Iterator<Item = TableWitnessSegment<P>> {
TableWitnessSegmentedView::new(self, log_size).into_iter()
}
pub fn par_segments(
&mut self,
log_size: usize,
) -> impl IndexedParallelIterator<Item = TableWitnessSegment<'_, P>> {
TableWitnessSegmentedView::new(self, log_size).into_par_iter()
}
}
/// A view over a table witness that splits the table into segments.
///
/// The purpose of this struct is to implement the `split_at` method, which safely splits the view
/// of the table witness vertically. This aids in the implementation of `fill_sequential` and
/// `fill_parallel`.
#[derive(Debug)]
struct TableWitnessSegmentedView<'a, P = PackedType<OptimalUnderlier, B128>>
where
P: PackedField,
P::Scalar: TowerField,
{
table: &'a Table<P::Scalar>,
cols: Vec<WitnessColumnInfo<(&'a mut [P], usize)>>,
log_segment_size: usize,
start_index: usize,
n_segments: usize,
}
impl<'a, F: TowerField, P: PackedField<Scalar = F>> TableWitnessSegmentedView<'a, P> {
fn new(witness: &'a mut TableWitnessIndex<P>, log_segment_size: usize) -> Self {
// Clamp the segment size.
let log_segment_size = log_segment_size
.min(witness.log_capacity)
.max(witness.min_log_segment_size);
let cols = witness
.cols
.iter_mut()
.map(|col| match &mut col.data {
WitnessColumnInfo::Owned(data) => {
let chunk_size = (log_segment_size + col.shape.log_cell_size())
.saturating_sub(P::LOG_WIDTH + F::TOWER_LEVEL);
WitnessColumnInfo::Owned((&mut **data, 1 << chunk_size))
}
WitnessColumnInfo::SameAsIndex(id) => WitnessColumnInfo::SameAsIndex(*id),
})
.collect::<Vec<_>>();
Self {
table: witness.table,
cols,
log_segment_size,
start_index: 0,
n_segments: 1 << (witness.log_capacity - log_segment_size),
}
}
fn split_at(
&mut self,
index: usize,
) -> (TableWitnessSegmentedView<P>, TableWitnessSegmentedView<P>) {
assert!(index <= self.n_segments);
let (cols_0, cols_1) = self
.cols
.iter_mut()
.map(|col| match col {
WitnessColumnInfo::Owned((data, chunk_size)) => {
let (data_0, data_1) = data.split_at_mut(*chunk_size * index);
(
WitnessColumnInfo::Owned((data_0, *chunk_size)),
WitnessColumnInfo::Owned((data_1, *chunk_size)),
)
}
WitnessColumnInfo::SameAsIndex(id) => {
(WitnessColumnInfo::SameAsIndex(*id), WitnessColumnInfo::SameAsIndex(*id))
}
})
.unzip();
(
TableWitnessSegmentedView {
table: self.table,
cols: cols_0,
log_segment_size: self.log_segment_size,
start_index: self.start_index,
n_segments: index,
},
TableWitnessSegmentedView {
table: self.table,
cols: cols_1,
log_segment_size: self.log_segment_size,
start_index: self.start_index + index,
n_segments: self.n_segments - index,
},
)
}
fn into_iter(self) -> impl Iterator<Item = TableWitnessSegment<'a, P>> {
let TableWitnessSegmentedView {
table,
cols,
log_segment_size,
start_index,
n_segments,
} = self;
if n_segments == 0 {
itertools::Either::Left(iter::empty())
} else {
let iter = MultiIterator::new(
cols.into_iter()
.map(|col| match col {
WitnessColumnInfo::Owned((data, chunk_size)) => itertools::Either::Left(
data.chunks_mut(chunk_size)
.map(|chunk| RefCellData::Owned(RefCell::new(chunk))),
),
WitnessColumnInfo::SameAsIndex(id) => itertools::Either::Right(
iter::repeat_n(id, n_segments).map(RefCellData::SameAsIndex),
),
})
.collect(),
)
.enumerate()
.map(move |(index, cols)| TableWitnessSegment {
table,
cols,
log_size: log_segment_size,
index: start_index + index,
});
itertools::Either::Right(iter)
}
}
fn into_par_iter(self) -> impl IndexedParallelIterator<Item = TableWitnessSegment<'a, P>> {
let TableWitnessSegmentedView {
table,
cols,
log_segment_size,
start_index,
n_segments,
} = self;
// This implementation uses unsafe code to iterate the segments of the view. A fully safe
// implementation is also possible, which would look similar to that of
// `rayon::slice::ChunksMut`. That just requires more code and doesn't seem justified.
// TODO: clippy error (clippy::mut_from_ref): mutable borrow from immutable input(s)
#[allow(clippy::mut_from_ref)]
unsafe fn cast_slice_ref_to_mut<T>(slice: &[T]) -> &mut [T] {
unsafe { slice::from_raw_parts_mut(slice.as_ptr() as *mut T, slice.len()) }
}
// Convert cols with mutable references into cols with const refs so that they can be
// cloned. Within the loop, we unsafely cast back to mut refs.
let cols = cols
.into_iter()
.map(|col| -> WitnessColumnInfo<(&'a [P], usize)> {
match col {
WitnessColumnInfo::Owned((data, chunk_size)) => {
WitnessColumnInfo::Owned((data, chunk_size))
}
WitnessColumnInfo::SameAsIndex(id) => WitnessColumnInfo::SameAsIndex(id),
}
})
.collect::<Vec<_>>();
(0..n_segments).into_par_iter().map(move |i| {
let col_strides = cols
.iter()
.map(|col| match col {
WitnessColumnInfo::SameAsIndex(id) => RefCellData::SameAsIndex(*id),
WitnessColumnInfo::Owned((data, chunk_size)) => {
RefCellData::Owned(RefCell::new(unsafe {
// Safety: The function borrows self mutably, so we have mutable access
// to all columns and thus none can be borrowed by anyone else. The
// loop is constructed to borrow disjoint segments of each column -- if
// this loop were transposed, we would use `chunks_mut`.
cast_slice_ref_to_mut(&data[i * chunk_size..(i + 1) * chunk_size])
}))
}
})
.collect();
TableWitnessSegment {
table,
cols: col_strides,
log_size: log_segment_size,
index: start_index + i,
}
})
}
}
/// A vertical segment of a table witness index.
///
/// This provides runtime-checked access to slices of the witness columns. This is used separately
/// from [`TableWitnessIndex`] so that witness population can be parallelized over segments.
#[derive(Debug, CopyGetters)]
pub struct TableWitnessSegment<'a, P = PackedType<OptimalUnderlier, B128>>
where
P: PackedField,
P::Scalar: TowerField,
{
table: &'a Table<P::Scalar>,
/// Stores the actual data for the witness columns.
///
/// The order of the columns corresponds to the same order as defined in the table.
cols: Vec<RefCellData<'a, P>>,
#[get_copy = "pub"]
log_size: usize,
/// The index of the segment in the segmented table witness.
#[get_copy = "pub"]
index: usize,
}
impl<'a, F: TowerField, P: PackedField<Scalar = F>> TableWitnessSegment<'a, P> {
pub fn get<FSub: TowerField, const V: usize>(
&self,
col: Col<FSub, V>,
) -> Result<Ref<[PackedSubfield<P, FSub>]>, Error>
where
P: PackedExtension<FSub>,
{
if col.table_id != self.table.id() {
return Err(Error::TableMismatch {
column_table_id: col.table_id,
witness_table_id: self.table.id(),
});
}
let col = self
.get_col_data(col.id())
.ok_or_else(|| Error::MissingColumn(col.id()))?;
let col_ref = col.try_borrow().map_err(|e| Error::WitnessBorrow { column_id: col.id(), source: e })?;
Ok(Ref::map(col_ref, |packed| PackedExtension::cast_bases(packed)))
}
pub fn get_mut<FSub: TowerField, const V: usize>(
&self,
col: Col<FSub, V>,
) -> Result<RefMut<[PackedSubfield<P, FSub>]>, Error>
where
P: PackedExtension<FSub>,
F: ExtensionField<FSub>,
{
if col.table_id != self.table.id() {
return Err(Error::TableMismatch {
column_table_id: col.table_id,
witness_table_id: self.table.id(),
});
}
let col = self
.get_col_data(col.id())
.ok_or_else(|| Error::MissingColumn(col.id()))?;
let col_ref = col.try_borrow_mut().map_err(|e| Error::WitnessBorrowMut { column_id: col.id(), source: e })?;
Ok(RefMut::map(col_ref, |packed| PackedExtension::cast_bases_mut(packed)))
}
pub fn get_scalars<FSub: TowerField, const V: usize>(
&self,
col: Col<FSub, V>,
) -> Result<Ref<[FSub]>, Error>
where
P: PackedExtension<FSub>,
F: ExtensionField<FSub>,
PackedSubfield<P, FSub>: PackedFieldIndexable,
{
self.get(col)
.map(|packed| Ref::map(packed, <PackedSubfield<P, FSub>>::unpack_scalars))