This repository was archived by the owner on Apr 18, 2025. It is now read-only.
forked from privacy-scaling-explorations/zkevm-circuits
-
Notifications
You must be signed in to change notification settings - Fork 390
/
Copy pathfse.rs
1972 lines (1805 loc) · 89.1 KB
/
fse.rs
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 gadgets::{
is_equal::{IsEqualChip, IsEqualConfig, IsEqualInstruction},
util::{and, not, select, Expr},
};
use halo2_proofs::{
circuit::{Layouter, Value},
halo2curves::bn256::Fr,
plonk::{Advice, Column, ConstraintSystem, Error, Expression, Fixed, VirtualCells},
poly::Rotation,
};
use itertools::Itertools;
use zkevm_circuits::{
evm_circuit::{BaseConstraintBuilder, ConstrainBuilderCommon},
table::{BitwiseOp, BitwiseOpTable, LookupTable, Pow2Table, RangeTable, U8Table},
};
use crate::aggregation::{
decoder::{
tables::{FixedLookupTag, FixedTable},
witgen::FseTableKind,
FseAuxiliaryTableData,
},
util::BooleanAdvice,
};
const N_ROWS_PER_FSE: usize = 1 << 10;
/// The FSE table verifies that given the symbols and the states allocated to those symbols, the
/// baseline and number of bits (nb) are assigned correctly to them.
///
/// The FSE table's layout is setup in a specific order, so that we cannot specify multiple FSE
/// table's of the same kind at the same block index. Every block has 3 FSE tables, namely for
/// Literal Length (LLT), Match Offset (MOT) and Match Length (MLT). They appear in the below
/// order:
///
/// - block_idx=1, table_kind=LLT
/// - block_idx=1, table_kind=MOT
/// - block_idx=1, table_kind=MLT
/// - block_idx=2, table_kind=LLT
/// - ... and so on
///
/// Each table spans over a maximum of 1024 rows, and the start of an FSE table is marked by the
/// fixed column ``q_start``. Upon finishing the FSE table, remaining rows are marked with the
/// ``is_padding`` column.
///
/// Each table begins with symbols that have a "less than 1" probability, whereby the state
/// allocated to them is at the end of the table (highest state) and retreating. For example, if
/// the symbol=3 has a normalised probability of prob==-1, then it is allocated the state 0x3f (63)
/// in an FSE table of accuracy_log=6. For subsequent symbols that have a prob>1, the state=0x3f is
/// skipped and we continue the same computation for the next successive state:
///
/// - state' == state'' & (table_size - 1)
/// - state'' == state + (table_size >> 3) + (table_size >> 1) + 3
///
/// where state' signifies the next state.
///
/// We cannot anticipate how many times we end up on such a "skipped" (or pre-allocated) state
/// while computing the states for a symbol, so we mark such rows with the boolean column
/// ``is_skipped_state``. On these rows, the ``state`` should have been taken by a
/// ``is_prob_less_than1`` symbol that reads AL number of bits at a baseline of 0x00.
///
/// | State | Symbol | is_prob_less_than1 |
/// |-------|--------|--------------------|
/// | 0 | 0 | 0 | <- q_first
/// |-------|--------|--------------------|
/// | 0x3f | 3 | 1 | <- q_start
/// | 0x3e | 4 | 1 |
/// | 0x00 | 0 | 0 |
/// | ... | 0 | 0 |
/// | 0x1d | 0 | 0 |
/// | 0x03 | 1 -> | 0 |
/// | 0x0c | 1 -> | 0 |
/// | 0x11 | 1 -> | 0 |
/// | 0x15 | 1 -> | 0 |
/// | 0x1a | 1 -> | 0 |
/// | 0x1e | 1 -> | 0 |
/// | 0x08 | 2 | 0 |
/// | ... | ... | 0 |
/// | 0x09 | 6 | 0 |
/// | 0x00 | 0 | 0 | <- is_padding
/// | ... | ... | 0 | <- is_padding
/// | 0x00 | 0 | 0 | <- is_padding
/// |-------|--------|--------------------|
/// | ... | ... | ... | <- q_start
/// |-------|--------|--------------------|
///
/// For more details, refer the [FSE reconstruction][doclink] section.
///
/// [doclink]: https://nigeltao.github.io/blog/2022/zstandard-part-5-fse.html#fse-reconstruction
#[derive(Clone, Debug)]
pub struct FseTable<const L: usize, const R: usize> {
/// The helper table to validate that the (baseline, nb) were assigned correctly to each state.
sorted_table: FseSortedStatesTable,
/// A boolean to mark whether this row represents a symbol with probability "less than 1".
is_prob_less_than1: BooleanAdvice,
/// Boolean column to mark whether the row is a padded row.
is_padding: BooleanAdvice,
/// Helper column for (table_size >> 1).
table_size_rs_1: Column<Advice>,
/// Helper column for (table_size >> 3).
table_size_rs_3: Column<Advice>,
/// Incremental index given to a state, idx in 1..=table_size.
idx: Column<Advice>,
/// The FSE symbol, starting at symbol=0.
symbol: Column<Advice>,
/// Boolean column to tell us when symbol is changing.
is_new_symbol: BooleanAdvice,
/// Represents the number of times this symbol appears in the FSE table. This value does not
/// change while the symbol in the table remains the same.
symbol_count: Column<Advice>,
/// An accumulator that resets to 1 each time we encounter a new symbol in the FSE table.
/// It increments while the symbol remains the same if we are not skipping the state. When we
/// encounter a new symbol, we validate that on the previous row, symbol_count equaled
/// symbol_count_acc.
symbol_count_acc: Column<Advice>,
/// The state in FSE. In the Auxiliary table, it does not increment by 1. Instead, it follows:
///
/// - state'' == state + table_size_rs_1 + table_size_rs_3 + 3
/// - state' == state'' & (table_size - 1)
///
/// where state' is the next row's state.
state: Column<Advice>,
/// Boolean column to mark if the computed state must be "skipped" because it was
/// pre-allocated to one of the symbols with a "less than 1" probability.
is_skipped_state: BooleanAdvice,
/// The assigned baseline for this state.
baseline: Column<Advice>,
/// The number of bits to read from bitstream when at this state.
nb: Column<Advice>,
/// Boolean advice to trigger the FSE state transition check.
enable_lookup: BooleanAdvice,
}
#[cfg(feature = "soundness-tests")]
use halo2_proofs::circuit::AssignedCell;
#[cfg(feature = "soundness-tests")]
#[derive(Debug)]
pub struct AssignedFseTableRow {
pub is_prob_less_than1: AssignedCell<Fr, Fr>,
pub is_padding: AssignedCell<Fr, Fr>,
pub table_size_rs_1: AssignedCell<Fr, Fr>,
pub table_size_rs_3: AssignedCell<Fr, Fr>,
pub idx: AssignedCell<Fr, Fr>,
pub symbol: AssignedCell<Fr, Fr>,
pub is_new_symbol: AssignedCell<Fr, Fr>,
pub symbol_count: AssignedCell<Fr, Fr>,
pub symbol_count_acc: AssignedCell<Fr, Fr>,
pub state: AssignedCell<Fr, Fr>,
pub is_skipped_state: AssignedCell<Fr, Fr>,
pub baseline: AssignedCell<Fr, Fr>,
pub nb: AssignedCell<Fr, Fr>,
}
#[cfg(feature = "soundness-tests")]
#[derive(Debug)]
pub struct AssignedFseSortedTableRow {
pub block_idx: AssignedCell<Fr, Fr>,
pub table_kind: AssignedCell<Fr, Fr>,
pub table_size: AssignedCell<Fr, Fr>,
pub is_predefined: AssignedCell<Fr, Fr>,
pub symbol: AssignedCell<Fr, Fr>,
pub is_new_symbol: AssignedCell<Fr, Fr>,
pub symbol_count: AssignedCell<Fr, Fr>,
pub symbol_count_acc: AssignedCell<Fr, Fr>,
pub state: AssignedCell<Fr, Fr>,
pub nb: AssignedCell<Fr, Fr>,
pub baseline: AssignedCell<Fr, Fr>,
pub last_baseline: AssignedCell<Fr, Fr>,
pub baseline_mark: AssignedCell<Fr, Fr>,
pub spot: AssignedCell<Fr, Fr>,
pub smallest_spot: AssignedCell<Fr, Fr>,
pub spot_acc: AssignedCell<Fr, Fr>,
}
#[cfg(feature = "soundness-tests")]
pub(crate) type AssignedFseTableRows = Vec<AssignedFseTableRow>;
#[cfg(feature = "soundness-tests")]
pub(crate) type AssignedFseSortedTableRows = Vec<AssignedFseSortedTableRow>;
#[cfg(feature = "soundness-tests")]
pub(crate) type AssignedFse = (AssignedFseTableRows, AssignedFseSortedTableRows);
#[cfg(not(feature = "soundness-tests"))]
pub(crate) type AssignedFse = ();
impl<const L: usize, const R: usize> FseTable<L, R> {
/// Configure the FSE table.
#[allow(clippy::too_many_arguments)]
pub fn configure(
meta: &mut ConstraintSystem<Fr>,
q_enable: Column<Fixed>,
fixed_table: &FixedTable,
u8_table: U8Table,
range8_table: RangeTable<8>,
range512_table: RangeTable<512>,
pow2_table: Pow2Table<20>,
bitwise_op_table: BitwiseOpTable<1, L, R>,
) -> Self {
// Auxiliary table to validate that (baseline, nb) were assigned correctly to the states
// allocated to a symbol.
let sorted_table =
FseSortedStatesTable::configure(meta, q_enable, pow2_table, u8_table, range512_table);
let config = Self {
sorted_table,
is_prob_less_than1: BooleanAdvice::construct(meta, |meta| {
meta.query_fixed(q_enable, Rotation::cur())
}),
is_padding: BooleanAdvice::construct(meta, |meta| {
meta.query_fixed(q_enable, Rotation::cur())
}),
table_size_rs_1: meta.advice_column(),
table_size_rs_3: meta.advice_column(),
idx: meta.advice_column(),
symbol: meta.advice_column(),
is_new_symbol: BooleanAdvice::construct(meta, |meta| {
meta.query_fixed(q_enable, Rotation::cur())
}),
symbol_count: meta.advice_column(),
symbol_count_acc: meta.advice_column(),
state: meta.advice_column(),
is_skipped_state: BooleanAdvice::construct(meta, |meta| {
meta.query_fixed(q_enable, Rotation::cur())
}),
baseline: meta.advice_column(),
nb: meta.advice_column(),
enable_lookup: BooleanAdvice::construct(meta, |meta| {
meta.query_fixed(q_enable, Rotation::cur())
}),
};
// Check that on the starting row of each FSE table, i.e. q_start=true:
// - table_size_rs_3 == table_size >> 3.
meta.lookup("FseTable: table_size >> 3", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
meta.query_fixed(config.sorted_table.q_start, Rotation::cur()),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let range_value = meta.query_advice(config.sorted_table.table_size, Rotation::cur())
- (meta.query_advice(config.table_size_rs_3, Rotation::cur()) * 8.expr());
vec![(condition * range_value, range8_table.into())]
});
// Every FSE symbol is a byte.
meta.lookup("FseTable: symbol in [0, 256)", |meta| {
let condition = meta.query_fixed(q_enable, Rotation::cur());
vec![(
condition * meta.query_advice(config.symbol, Rotation::cur()),
u8_table.into(),
)]
});
// Check that on the starting row of every FSE table, i.e. q_start=true:
//
// - tuple (block_idx::prev, block_idx::cur, table_kind::prev, table_kind::cur)
//
// is in fact a valid transition. All valid transitions are provided in the fixed-table
// RomFseTableTransition.
meta.lookup_any(
"FseTable: start row (ROM block_idx and table_kind transition)",
|meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
meta.query_fixed(config.sorted_table.q_start, Rotation::cur()),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let (block_idx_prev, block_idx_curr, table_kind_prev, table_kind_curr) = (
meta.query_advice(config.sorted_table.block_idx, Rotation::prev()),
meta.query_advice(config.sorted_table.block_idx, Rotation::cur()),
meta.query_advice(config.sorted_table.table_kind, Rotation::prev()),
meta.query_advice(config.sorted_table.table_kind, Rotation::cur()),
);
[
FixedLookupTag::FseTableTransition.expr(),
block_idx_prev,
block_idx_curr,
table_kind_prev,
table_kind_curr,
0.expr(), // unused
0.expr(), // unused
]
.into_iter()
.zip_eq(fixed_table.table_exprs(meta))
.map(|(arg, table)| (condition.expr() * arg, table))
.collect()
},
);
// The starting row of every FSE table, i.e. q_start=true.
meta.create_gate("FseTable: start row", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
meta.query_fixed(config.sorted_table.q_start, Rotation::cur()),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let mut cb = BaseConstraintBuilder::default();
let is_prob_less_than1 = config.is_prob_less_than1.expr_at(meta, Rotation::cur());
// 1. If we start with a symbol that has prob "less than 1"
cb.condition(is_prob_less_than1.expr(), |cb| {
cb.require_equal(
"prob=-1: state inits at table_size - 1",
meta.query_advice(config.state, Rotation::cur()),
meta.query_advice(config.sorted_table.table_size, Rotation::cur()) - 1.expr(),
);
});
// 2. If no symbol has a prob "less than 1"
cb.condition(not::expr(is_prob_less_than1), |cb| {
cb.require_zero(
"state inits at 0",
meta.query_advice(config.state, Rotation::cur()),
);
});
cb.require_equal(
"idx == 1",
meta.query_advice(config.idx, Rotation::cur()),
1.expr(),
);
// table_size_rs_1 == table_size >> 1.
cb.require_boolean(
"table_size >> 1",
meta.query_advice(config.sorted_table.table_size, Rotation::cur())
- (meta.query_advice(config.table_size_rs_1, Rotation::cur()) * 2.expr()),
);
// The start row is a new symbol.
cb.require_equal(
"is_new_symbol==true",
config.is_new_symbol.expr_at(meta, Rotation::cur()),
1.expr(),
);
cb.gate(condition)
});
// For every symbol that has a normalised probability prob=-1.
meta.lookup_any("FseTable: all symbols with prob=-1 (nb==AL)", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
config.is_prob_less_than1.expr_at(meta, Rotation::cur()),
]);
// for a symbol with prob=-1, we do a full state reset, i.e.
// read nb=AL bits, i.e. 1 << nb == table_size.
[
meta.query_advice(config.nb, Rotation::cur()),
meta.query_advice(config.sorted_table.table_size, Rotation::cur()),
]
.into_iter()
.zip_eq(pow2_table.table_exprs(meta))
.map(|(arg, table)| (condition.expr() * arg, table))
.collect()
});
// For every symbol that has a normalised probability prob=-1.
meta.create_gate("FseTable: all symbols with prob=-1", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
config.is_prob_less_than1.expr_at(meta, Rotation::cur()),
]);
let mut cb = BaseConstraintBuilder::default();
// Each such row is a new symbol.
cb.require_equal(
"prob=-1: is_new_symbol==true",
config.is_new_symbol.expr_at(meta, Rotation::cur()),
1.expr(),
);
// prob=-1 indicates a baseline==0x00.
cb.require_zero(
"prob=-1: baseline==0x00",
meta.query_advice(config.baseline, Rotation::cur()),
);
// prob=-1 symbol cannot be padding.
cb.require_zero(
"prob=-1: is_padding==false",
config.is_padding.expr_at(meta, Rotation::cur()),
);
// prob=-1 symbol is not a skipped state.
cb.require_zero(
"prob=-1: is_skipped_state=false",
config.is_skipped_state.expr_at(meta, Rotation::cur()),
);
cb.gate(condition)
});
// Symbols with prob=-1 are in increasing order.
meta.lookup(
"FseTable: subsequent symbols with prob=-1 (symbol increasing)",
|meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(meta.query_fixed(config.sorted_table.q_start, Rotation::cur())),
config.is_prob_less_than1.expr_at(meta, Rotation::cur()),
]);
// Symbols with prob=-1 are assigned cells from the end (state==table_size-1) and
// retreating. However those symbols are processed in natural order, i.e. symbols
// are in increasing order.
//
// - symbol::cur - symbol::prev > 0
//
// We check that (symbol - symbol_prev - 1) lies in the [0, 256) range.
let (symbol_curr, symbol_prev) = (
meta.query_advice(config.symbol, Rotation::cur()),
meta.query_advice(config.symbol, Rotation::prev()),
);
let delta = symbol_curr - symbol_prev - 1.expr();
vec![(condition * delta, u8_table.into())]
},
);
// Symbols with prob=-1 are assigned states from the end and retreating.
meta.create_gate(
"FseTable: subsequent symbols with prob=-1 (state retreating)",
|meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(meta.query_fixed(config.sorted_table.q_start, Rotation::cur())),
config.is_prob_less_than1.expr_at(meta, Rotation::cur()),
]);
let mut cb = BaseConstraintBuilder::default();
// While prob=-1, state is retreating, i.e. decrements by 1.
cb.require_equal(
"state == state::prev - 1",
meta.query_advice(config.state, Rotation::cur()),
meta.query_advice(config.state, Rotation::prev()) - 1.expr(),
);
cb.gate(condition)
},
);
// Symbols with prob>=1 are also in increasing order. We skip this check if this is the
// first symbol with prob>=1.
meta.lookup(
"FseTable: symbols with prob>=1 (symbol increasing)",
|meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(meta.query_fixed(config.sorted_table.q_start, Rotation::cur())),
not::expr(config.is_prob_less_than1.expr_at(meta, Rotation::prev())),
config.is_new_symbol.expr_at(meta, Rotation::cur()),
]);
// Whenever we move to a new symbol (is_new_symbol=true), excluding the first symbol
// with prob>=1, the symbol is increasing.
//
// - symbol::cur - symbol::prev > 0
//
// We check that (symbol - symbol_prev - 1) lies in the [0, 256) range.
let (symbol_curr, symbol_prev) = (
meta.query_advice(config.symbol, Rotation::cur()),
meta.query_advice(config.symbol, Rotation::prev()),
);
let delta = symbol_curr - symbol_prev - 1.expr();
vec![(condition * delta, u8_table.into())]
},
);
// Symbols with prob>=1 continue the same symbol if not a new symbol.
meta.create_gate("FseTable: symbols with prob>=1", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(meta.query_fixed(config.sorted_table.q_first, Rotation::cur())),
not::expr(meta.query_fixed(config.sorted_table.q_start, Rotation::cur())),
not::expr(config.is_prob_less_than1.expr_at(meta, Rotation::cur())),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let mut cb = BaseConstraintBuilder::default();
// When we are not seeing a new symbol, make sure the symbol is equal to the symbol on
// the previous row.
let is_not_new_symbol = not::expr(config.is_new_symbol.expr_at(meta, Rotation::cur()));
cb.condition(is_not_new_symbol, |cb| {
cb.require_equal(
"prob>=1: same symbol",
meta.query_advice(config.symbol, Rotation::cur()),
meta.query_advice(config.symbol, Rotation::prev()),
);
});
// is the first symbol if:
// - prev row was prob=-1
let is_first_symbol = config.is_prob_less_than1.expr_at(meta, Rotation::prev());
cb.condition(is_first_symbol, |cb| {
cb.require_zero(
"first symbol (prob >= 1): state == 0",
meta.query_advice(config.state, Rotation::cur()),
);
});
cb.gate(condition)
});
// All rows in an instance of FSE table, except the starting row (q_start=true).
meta.create_gate("FseTable: every FSE table (except q_start=1)", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(meta.query_fixed(config.sorted_table.q_first, Rotation::cur())),
not::expr(meta.query_fixed(config.sorted_table.q_start, Rotation::cur())),
]);
let mut cb = BaseConstraintBuilder::default();
// FSE table's columns that remain unchanged.
for column in [config.table_size_rs_1, config.table_size_rs_3] {
cb.require_equal(
"FseTable: columns that remain unchanged",
meta.query_advice(column, Rotation::cur()),
meta.query_advice(column, Rotation::prev()),
);
}
// The symbols with prob "less than 1" are assigned at the starting rows of the FSE
// table with maximum (and retreating) state values.
let (is_prob_less_than1_prev, is_prob_less_than1_curr) = (
config.is_prob_less_than1.expr_at(meta, Rotation::prev()),
config.is_prob_less_than1.expr_at(meta, Rotation::cur()),
);
let delta = is_prob_less_than1_prev - is_prob_less_than1_curr.expr();
cb.require_boolean("prob=-1 symbols occur in the start of the layout", delta);
// Once we enter padding territory, we stay in padding territory, i.e.
// is_padding transitions from 0 -> 1 only once.
let (is_padding_curr, is_padding_prev) = (
config.is_padding.expr_at(meta, Rotation::cur()),
config.is_padding.expr_at(meta, Rotation::prev()),
);
let is_padding_delta = is_padding_curr.expr() - is_padding_prev.expr();
cb.require_boolean("is_padding_delta is boolean", is_padding_delta);
// If we are not in the padding region and don't skip state on this row, then this is a
// new state in the FSE table, i.e. idx increments.
let is_skipped_state = config.is_skipped_state.expr_at(meta, Rotation::cur());
cb.require_equal(
"idx increments in non-padding region if we don't skip state",
meta.query_advice(config.idx, Rotation::cur()),
select::expr(
and::expr([
not::expr(is_padding_curr.expr()),
not::expr(is_skipped_state),
]),
meta.query_advice(config.idx, Rotation::prev()) + 1.expr(),
meta.query_advice(config.idx, Rotation::prev()),
),
);
// If we are entering the padding region on this row, the idx on the previous row must
// equal the table size, i.e. all states must be generated.
cb.condition(
and::expr([not::expr(is_padding_prev), is_padding_curr]),
|cb| {
cb.require_equal(
"idx == table_size on the last state",
meta.query_advice(config.idx, Rotation::prev()),
meta.query_advice(config.sorted_table.table_size, Rotation::prev()),
);
},
);
cb.gate(condition)
});
// A state is skipped only if that state was pre-allocated to a symbol with prob=-1.
meta.lookup_any("FseTable: skipped state", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
config.is_skipped_state.expr_at(meta, Rotation::cur()),
]);
// A state can be skipped only if it was pre-allocated to a symbol with prob=-1. So we
// check that there exists a row with the same block_idx, table_kind and the skipped
// state with a prob=-1.
let fse_table_exprs = [
meta.query_advice(config.sorted_table.block_idx, Rotation::cur()),
meta.query_advice(config.sorted_table.table_kind, Rotation::cur()),
meta.query_advice(config.state, Rotation::cur()),
config.is_prob_less_than1.expr_at(meta, Rotation::cur()),
];
[
meta.query_advice(config.sorted_table.block_idx, Rotation::cur()),
meta.query_advice(config.sorted_table.table_kind, Rotation::cur()),
meta.query_advice(config.state, Rotation::cur()),
1.expr(), // prob=-1
]
.into_iter()
.zip_eq(fse_table_exprs)
.map(|(arg, table)| (condition.expr() * arg, table))
.collect()
});
// For every symbol with prob>=1 and a valid state allocated, we check that the baseline
// and nb fields were assigned correctly.
meta.lookup_any(
"FseTable: assigned state (baseline, nb) validation",
|meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(config.is_prob_less_than1.expr_at(meta, Rotation::cur())),
not::expr(config.is_skipped_state.expr_at(meta, Rotation::cur())),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let (block_idx, table_kind, table_size, state, symbol, symbol_count, baseline, nb) = (
meta.query_advice(config.sorted_table.block_idx, Rotation::cur()),
meta.query_advice(config.sorted_table.table_kind, Rotation::cur()),
meta.query_advice(config.sorted_table.table_size, Rotation::cur()),
meta.query_advice(config.state, Rotation::cur()),
meta.query_advice(config.symbol, Rotation::cur()),
meta.query_advice(config.symbol_count, Rotation::cur()),
meta.query_advice(config.baseline, Rotation::cur()),
meta.query_advice(config.nb, Rotation::cur()),
);
[
block_idx,
table_kind,
table_size,
symbol,
symbol_count,
state,
baseline,
nb,
0.expr(),
]
.into_iter()
.zip_eq(config.sorted_table.table_exprs(meta))
.map(|(arg, table)| (condition.expr() * arg, table))
.collect()
},
);
// For predefined FSE tables, we must validate against the ROM predefined table fields for
// every state in the FSE table.
meta.lookup_any("FseTable: predefined table validation", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
config
.sorted_table
.is_predefined
.expr_at(meta, Rotation::cur()),
not::expr(config.is_skipped_state.expr_at(meta, Rotation::cur())),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let (table_kind, table_size, state, symbol, baseline, nb) = (
meta.query_advice(config.sorted_table.table_kind, Rotation::cur()),
meta.query_advice(config.sorted_table.table_size, Rotation::cur()),
meta.query_advice(config.state, Rotation::cur()),
meta.query_advice(config.symbol, Rotation::cur()),
meta.query_advice(config.baseline, Rotation::cur()),
meta.query_advice(config.nb, Rotation::cur()),
);
[
FixedLookupTag::PredefinedFse.expr(),
table_kind,
table_size,
state,
symbol,
baseline,
nb,
]
.into_iter()
.zip_eq(fixed_table.table_exprs(meta))
.map(|(arg, table)| (condition.expr() * arg, table))
.collect()
});
// For every new symbol detected.
meta.create_gate("FseTable: new symbol", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
config.is_new_symbol.expr_at(meta, Rotation::cur()),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let mut cb = BaseConstraintBuilder::default();
// We first do validations for the previous symbol.
//
// - symbol_count_acc accumulated to symbol_count.
//
// This is also expected to pass on the starting row of each FSE table, since the
// previous row is either q_first=true or is_padding=true, where in both
// cases we expect:
// - symbol_count == symbol_count_acc == 0.
cb.require_equal(
"symbol_count == symbol_count_acc",
meta.query_advice(config.symbol_count, Rotation::prev()),
meta.query_advice(config.symbol_count_acc, Rotation::prev()),
);
// The symbol_count_acc inits at 1.
cb.require_equal(
"symbol_count_acc inits at 1 if not skipped state",
meta.query_advice(config.symbol_count_acc, Rotation::cur()),
not::expr(config.is_skipped_state.expr_at(meta, Rotation::cur())),
);
cb.gate(condition)
});
// Whenever we continue allocating states to the same symbol.
meta.create_gate("FseTable: same symbol, transitioned state", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
not::expr(meta.query_fixed(config.sorted_table.q_first, Rotation::cur())),
not::expr(config.is_new_symbol.expr_at(meta, Rotation::cur())),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]);
let mut cb = BaseConstraintBuilder::default();
// While we allocate more states to the same symbol:
//
// - symbol_count does not change
cb.require_equal(
"if symbol continues: symbol_count unchanged",
meta.query_advice(config.symbol_count, Rotation::cur()),
meta.query_advice(config.symbol_count, Rotation::prev()),
);
// symbol count accumulator increments if the state is not skipped.
cb.require_equal(
"symbol_count_acc increments if state not skipped",
meta.query_advice(config.symbol_count_acc, Rotation::cur()),
select::expr(
config.is_skipped_state.expr_at(meta, Rotation::cur()),
meta.query_advice(config.symbol_count_acc, Rotation::prev()),
meta.query_advice(config.symbol_count_acc, Rotation::prev()) + 1.expr(),
),
);
cb.gate(condition)
});
meta.create_gate("FseTable: enable state transition lookup", |meta| {
let condition = meta.query_fixed(q_enable, Rotation::cur());
let mut cb = BaseConstraintBuilder::default();
cb.require_equal(
"enable_lookup for state transition?",
config.enable_lookup.expr_at(meta, Rotation::cur()),
and::expr([
not::expr(meta.query_fixed(config.sorted_table.q_first, Rotation::cur())),
not::expr(meta.query_fixed(config.sorted_table.q_start, Rotation::cur())),
not::expr(config.is_prob_less_than1.expr_at(meta, Rotation::cur())),
not::expr(config.is_prob_less_than1.expr_at(meta, Rotation::prev())),
not::expr(config.is_padding.expr_at(meta, Rotation::cur())),
]),
);
cb.gate(condition)
});
// Constraint for state' calculation. We wish to constrain:
//
// - state' == state'' & (table_size - 1)
// - state'' == state + (table_size >> 3) + (table_size >> 1) + 3
meta.lookup_any("FseTable: state transition", |meta| {
let condition = and::expr([
meta.query_fixed(q_enable, Rotation::cur()),
config.enable_lookup.expr_at(meta, Rotation::cur()),
]);
let state_prime = meta.query_advice(config.state, Rotation::cur());
let state_prime_prime = meta.query_advice(config.state, Rotation::prev())
+ meta.query_advice(config.table_size_rs_3, Rotation::cur())
+ meta.query_advice(config.table_size_rs_1, Rotation::cur())
+ 3.expr();
let table_size_minus_one =
meta.query_advice(config.sorted_table.table_size, Rotation::cur()) - 1.expr();
[
BitwiseOp::AND.expr(), // op
state_prime_prime, // operand1
table_size_minus_one, // operand2
state_prime, // result
]
.into_iter()
.zip_eq(bitwise_op_table.table_exprs(meta))
.map(|(arg, table)| (condition.expr() * arg, table))
.collect()
});
debug_assert!(meta.degree() <= 9);
debug_assert!(meta.clone().chunk_lookups().degree() <= 9);
config
}
/// Assign the FSE table.
pub fn assign(
&self,
layouter: &mut impl Layouter<Fr>,
data: &[FseAuxiliaryTableData],
n_enabled: usize,
) -> Result<AssignedFse, Error> {
layouter.assign_region(
|| "FseTable",
|mut region| {
region.assign_fixed(
|| "q_first",
self.sorted_table.q_first,
0,
|| Value::known(Fr::one()),
)?;
// Both tables should skip the first row
let mut fse_offset: usize = 1;
let mut sorted_offset: usize = 1;
#[cfg(feature = "soundness-tests")]
let mut assigned_fse_table_rows = Vec::with_capacity(n_enabled);
#[cfg(feature = "soundness-tests")]
let mut assigned_fse_sorted_table_rows = Vec::with_capacity(n_enabled);
for i in (1..n_enabled).step_by(N_ROWS_PER_FSE) {
region.assign_fixed(
|| "q_start",
self.sorted_table.q_start,
i,
|| Value::known(Fr::one()),
)?;
}
for table in data.iter() {
// reserve enough rows to accommodate skipped states Assign q_start
let target_end_offset = fse_offset + N_ROWS_PER_FSE;
let states_to_symbol = table.parse_state_table();
let mut state_idx: usize = 0;
let mut first_regular_prob = true;
// Assign the symbols with negative normalised probability
let tail_states_count = table
.normalised_probs
.iter()
.filter(|(&_sym, &w)| w < 0)
.count();
if tail_states_count > 0 {
for state in ((table.table_size - tail_states_count as u64)
..=(table.table_size - 1))
.rev()
{
state_idx += 1;
let _state = region.assign_advice(
|| "state",
self.state,
fse_offset,
|| Value::known(Fr::from(state)),
)?;
let _idx = region.assign_advice(
|| "idx",
self.idx,
fse_offset,
|| Value::known(Fr::from(state_idx as u64)),
)?;
let _symbol = region.assign_advice(
|| "symbol",
self.symbol,
fse_offset,
|| {
Value::known(Fr::from(
states_to_symbol.get(&state).expect("state exists").0,
))
},
)?;
let _baseline = region.assign_advice(
|| "baseline",
self.baseline,
fse_offset,
|| {
Value::known(Fr::from(
states_to_symbol.get(&state).expect("state exists").1,
))
},
)?;
let _nb = region.assign_advice(
|| "nb",
self.nb,
fse_offset,
|| {
Value::known(Fr::from(
states_to_symbol.get(&state).expect("state exists").2,
))
},
)?;
let _is_new_symbol = region.assign_advice(
|| "is_new_symbol",
self.is_new_symbol.column,
fse_offset,
|| Value::known(Fr::one()),
)?;
let _is_prob_less_than1 = region.assign_advice(
|| "is_prob_less_than1",
self.is_prob_less_than1.column,
fse_offset,
|| Value::known(Fr::one()),
)?;
let _is_skipped_state = region.assign_advice(
|| "is_skipped_state",
self.is_skipped_state.column,
fse_offset,
|| Value::known(Fr::zero()),
)?;
let _symbol_count = region.assign_advice(
|| "symbol_count",
self.symbol_count,
fse_offset,
|| Value::known(Fr::one()),
)?;
let _symbol_count_acc = region.assign_advice(
|| "symbol_count_acc",
self.symbol_count_acc,
fse_offset,
|| Value::known(Fr::one()),
)?;
let _table_size_rs_1 = region.assign_advice(
|| "table_size_rs_1",
self.table_size_rs_1,
fse_offset,
|| Value::known(Fr::from(table.table_size >> 1)),
)?;
let _table_size_rs_3 = region.assign_advice(
|| "table_size_rs_3",
self.table_size_rs_3,
fse_offset,
|| Value::known(Fr::from(table.table_size >> 3)),
)?;
let _is_padding = region.assign_advice(
|| "is_padding",
self.is_padding.column,
fse_offset,
|| Value::known(Fr::zero()),
)?;
region.assign_advice(
|| "enable_lookup",
self.enable_lookup.column,
fse_offset,
|| Value::known(Fr::zero()),
)?;
#[cfg(feature = "soundness-tests")]
assigned_fse_table_rows.push(AssignedFseTableRow {
is_prob_less_than1: _is_prob_less_than1,
is_padding: _is_padding,
table_size_rs_1: _table_size_rs_1,
table_size_rs_3: _table_size_rs_3,
idx: _idx,
symbol: _symbol,
is_new_symbol: _is_new_symbol,
symbol_count: _symbol_count,
symbol_count_acc: _symbol_count_acc,
state: _state,
is_skipped_state: _is_skipped_state,
baseline: _baseline,
nb: _nb,
});
fse_offset += 1;
}
}
// Assign the symbols with positive probability in fse table
let regular_symbols = table
.normalised_probs
.clone()
.into_iter()
.filter(|(_sym, w)| *w > 0)
.collect::<Vec<(u64, i32)>>();
for (sym, _c) in regular_symbols.clone().into_iter() {
let mut sym_acc: usize = 0;
let sym_rows = table.sym_to_states.get(&sym).expect("symbol exists.");
let sym_count = sym_rows.iter().filter(|r| !r.is_state_skipped).count();