bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 45쪽
column.
```rust theme={null}
struct RangeCheckColumn {
pub log_size: u32,
}
#[allow(dead_code)]
impl RangeCheckColumn {
pub fn new(log_size: u32) -> Self {
Self { log_size }
}
pub fn gen_column(&self) -> CircleEvaluation<SimdBackend, M31, BitReversedOrder> {
let col = BaseColumn::from_iter((0..(1 << self.log_size)).map(|i| M31::from(i)));
CircleEvaluation::new(CanonicCoset::new(self.log_size).circle_domain(), col)
}
pub fn id(&self) -> PreProcessedColumnId {
PreProcessedColumnId {
id: format!("range_check_{}_bits", self.log_size),
}
}
}
```
First, we need to create the range-check column as a preprocessed column. This should look familiar to the code from the previous section.
```rust theme={null}
fn gen_trace(log_size: u32) -> Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>> {
// Create a table with random values
let mut rng = rand::thread_rng();
let lookup_col_1 =
BaseColumn::from_iter((0..(1 << log_size)).map(|_| M31::from(rng.gen_range(0..16))));
let lookup_col_2 =
BaseColumn::from_iter((0..(1 << log_size)).map(|_| M31::from(rng.gen_range(0..16))));
let mut multiplicity_col = BaseColumn::zeros(1 << log_size);
lookup_col_1
.as_slice()
.iter()
.chain(lookup_col_2.as_slice().iter())
.for_each(|value| {
let index = value.0 as usize;
multiplicity_col.set(index, multiplicity_col.at(index) + M31::from(1));
});
// Convert table to trace polynomials
let domain = CanonicCoset::new(log_size).circle_domain();
vec![
lookup_col_1.clone(),
lookup_col_2.clone(),
multiplicity_col.clone(),
]
.into_iter()
.map(|col| CircleEvaluation::new(domain, col))
.collect()
}
```
Next, we create the original trace columns. The first two columns are random values in the range $[0, 15]$, and the third column contains the counts of the values in the range-check column.
```rust theme={null}
relation!(SmallerThan16Elements, 1);
fn gen_logup_trace(
range_log_size: u32,
log_size: u32,
range_check_col: &BaseColumn,
lookup_col_1: &BaseColumn,
lookup_col_2: &BaseColumn,
multiplicity_col: &BaseColumn,
lookup_elements: &SmallerThan16Elements,
) -> (
Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>>,
SecureField,
) {
let mut logup_gen = LogupTraceGenerator::new(range_log_size);
let mut col_gen = logup_gen.new_col();
for simd_row in 0..(1 << (range_log_size - LOG_N_LANES)) {
let numerator: PackedSecureField = PackedSecureField::from(multiplicity_col.data[simd_row]);
let denom: PackedSecureField = lookup_elements.combine(&[range_check_col.data[simd_row]]);
col_gen.write_frac(simd_row, -numerator, denom);
}
col_gen.finalize_col();
let mut col_gen = logup_gen.new_col();
for simd_row in 0..(1 << (log_size - LOG_N_LANES)) {
let lookup_col_1_val: PackedSecureField =
lookup_elements.combine(&[lookup_col_1.data[simd_row]]);
let lookup_col_2_val: PackedSecureField =
lookup_elements.combine(&[lookup_col_2.data[simd_row]]);
// 1 / denom1 + 1 / denom2 = (denom1 + denom2) / (denom1 * denom2)
let numerator = lookup_col_1_val + lookup_col_2_val;
let denom = lookup_col_1_val * lookup_col_2_val;
col_gen.write_frac(simd_row, numerator, denom);
}
col_gen.finalize_col();
logup_gen.finalize_last()
}
fn main() {
...
// Draw random elements to use when creating the random linear combination of lookup values in the LogUp columns
let lookup_elements = SmallerThan16Elements::draw(channel);
// Create and commit to the LogUp columns
let (logup_cols, claimed_sum) = gen_logup_trace(
range_log_size,
log_num_rows,
&range_check_col,
&trace[0],
&trace[1],
&trace[2],
&lookup_elements,
);
...
}
```
Now we need to create the LogUp columns.
First, note that we are creating a `SmallerThan16Elements` instance using the macro `relation!`. This macro creates an API for performing random linear combinations. Under the hood, it creates two random values $z, \alpha$ that can create a random linear combination of an arbitrary number of elements. In our case, we only need to combine one value (value in $[0,15]$), which is why we pass in `1` to the macro.
Inside `gen_logup_trace`, we create a `LogupTraceGenerator` instance. This is a helper class that allows us to create LogUp columns. Every time we create a new column, we need to call `new_col()` on the `LogupTraceGenerator` instance.
You may notice that we are iterating over `BaseColumn` in chunks of 16, or `1 << LOG_N_LANES` values. This is because we are using the `SimdBackend`, which runs 16 lanes simultaneously, so we need to preserve this structure. The `Packed` in `PackedSecureField` means that it packs 16 values into a single value.
You may also notice that we are using a `SecureField` instead of just the `Field`. This is because the random value we created by `SmallerThan16Elements` lies in the degree-4 extension field $\mathbb{F}_{p^4}$. This is necessary for the security of the protocol and interested readers can refer to the [Mersenne Primes](../../how-it-works/mersenne-prime) section for more details.
Once we set the fractions for each `simd_row`, we need to call `finalize_col()` to finalize the column. This process modifies the LogUp columns from individual fractions to cumulative sums of the fractions as shown in [Figure 2](#figure-2).
<div>
<img alt="" />
*Figure 2: Finalizing each LogUp column*
</div>
Finally, we need to call `finalize_last()` on the `LogupTraceGenerator` instance to finalize the LogUp columns, which will return the LogUp columns as well as the sum of the fractions in the LogUp columns.
```rust theme={null}
struct TestEval {
range_check_id: PreProcessedColumnId,
log_size: u32,
lookup_elements: SmallerThan16Elements,
}
impl FrameworkEval for TestEval {
fn log_size(&self) -> u32 {
self.log_size
}
fn max_constraint_log_degree_bound(&self) -> u32 {
self.log_size + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR
}
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let range_check_col = eval.get_preprocessed_column(self.range_check_id.clone());
let lookup_col_1 = eval.next_trace_mask();
let lookup_col_2 = eval.next_trace_mask();
let multiplicity_col = eval.next_trace_mask();
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
-E::EF::from(multiplicity_col),
&[range_check_col],
));
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
E::EF::one(),
&[lookup_col_1],
));
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
E::EF::one(),
&[lookup_col_2],
));
eval.finalize_logup_batched(&vec![0, 1, 1]);
eval
}
}
```
The last piece of the puzzle is to create the constraints. We use the same `TestEval` struct as in the previous sections, but the `evaluate` function will look slightly different. Instead of calling `add_constraint` on the `EvalAtRow` instance, we will call `add_to_relation`, which recreates the fractions that we added in the LogUp columns using values in the range-check, lookup, and multiplicity columns.
Once we add the fractions as constraints, we call the `finalize_logup_batched` function, which indicates how we want to batch the fractions. In our case, we added 3 fractions but want to create batches where the last two fractions are batched together, so we pass in `&vec![0, 1, 1]`.
```rust theme={null}
// Verify
assert_eq!(claimed_sum, SecureField::zero());
let channel = &mut Blake2sChannel::default();
let commitment_scheme = &mut CommitmentSchemeVerifier::<Blake2sMerkleChannel>::new(config);
let sizes = component.trace_log_degree_bounds();
commitment_scheme.commit(proof.commitments[0], &sizes[0], channel);
channel.mix_u64((log_num_rows) as u64);
commitment_scheme.commit(proof.commitments[1], &sizes[1], channel);
commitment_scheme.commit(proof.commitments[2], &sizes[2], channel);
verify(&[&component], channel, commitment_scheme, proof).unwrap();
```
When we verify the proof, as promised, we check that the `claimed_sum`, which is the sum of the fractions in the LogUp columns, is 0.
And that's it! We have successfully created a static lookup for a range-check.
<Tip>
**How many fractions can we batch together?**
This depends on how we set the `max_constraint_log_degree_bound` function, as discussed in this [note](../writing-a-simple-air/constraints-over-trace-polynomials.md#max_constraint_log_degree_bound). More specifically, we can batch up to exactly the blowup factor.
e.g.
* `self.log_size + 1` -> 2 fractions
* `self.log_size + 2` -> 4 fractions
* `self.log_size + 3` -> 8 fractions
* `self.log_size + 4` -> 16 fractions
* ...
</Tip>
<Note>
Note that unlike what [Figure 1](#figure-1) shows, the size of the range column and the range-checked columns do not have to be the same. As we will learn in the [Components](../components/index) section, we can create separate components for the range-check and the range-checked columns to support such cases.
</Note>
# Committing to the Trace Polynomials
Source: https://docs.starknet.io/learn/S-two-book/air-development/writing-a-simple-air/committing-to-the-trace-polynomials
<div>
<img alt="" />
*Figure 1: Prover workflow: Commitment*
</div>
Now that we have created the trace polynomials, we need to commit to them.
As we can see in [Figure 1](#figure-1), S-two commits to the trace polynomials by first expanding the trace polynomials (i.e. adding more evaluations) and then committing to the expanded evaluations using a Merkle tree. The rate of expansion (commonly referred to as the *blowup factor*) is a parameter of the FRI protocol and for the purposes of this tutorial, we will use the default value.
```rust theme={null}
const LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR: u32 = 1;
fn main() {
// --snip--
// Config for FRI and PoW
let config = PcsConfig::default();
// Precompute twiddles for evaluating and interpolating the trace
let twiddles = SimdBackend::precompute_twiddles(
CanonicCoset::new(
log_num_rows + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR + config.fri_config.log_blowup_factor,
)
.circle_domain()
.half_coset,
);
// Create the channel and commitment scheme
let channel = &mut Blake2sChannel::default();
let mut commitment_scheme =
CommitmentSchemeProver::<SimdBackend, Blake2sMerkleChannel>::new(config, &twiddles);
// Commit to the preprocessed trace
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(vec![]);
tree_builder.commit(channel);
// Commit to the size of the trace
channel.mix_u64(log_num_rows as u64);
// Commit to the original trace
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(trace);
tree_builder.commit(channel);
}
```
We begin with some setup. First, we create a default `PcsConfig` instance, which sets the values for the FRI and PoW operations. Setting non-default values is related to the security of the proof, which is outside the scope of this tutorial.
Next, we precompute twiddles, which are factors multiplied during FFT for a particular domain. Notice that the log size of the domain is set to `log_num_rows + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR + config.fri_config.log_blowup_factor`, which is the max log size of the domain that is needed throughout the proving process. For committing to the trace polynomial, we only need to add `config.fri_config.log_blowup_factor` but as we will see in the next section, we also need to commit to a polynomial of a higher degree, which is the reason we also add `LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR`.
The final setup is creating a commitment scheme and a channel. The commitment scheme will be used to commit to the trace polynomials as Merkle trees, while the channel will be used to keep a running hash of all data in the proving process (i.e. transcript of the proof). This is part of the Fiat-Shamir transformation, which derives randomness safely in a non-interactive setting. Here, we use the `Blake2sChannel` and `Blake2sMerkleChannel` for the channel and commitment scheme, respectively, but we can also use the `Poseidon252Channel` and `Poseidon252MerkleChannel` pair.
Now that we have our setup, we can commit to the trace polynomials. But before we do so, we need to first commit to an empty vector called a *preprocessed trace*, which doesn't do anything but is required by S-two. Then, we need to commit to the size of the trace, which is another vital part that the prover should not be able to cheat on. After doing so, we can finally commit to the original trace polynomials.
Now that we have committed to the trace polynomials, we can move on to how we can create constraints over the trace polynomials!
# Evaluating Constraints Over Trace Polynomials
Source: https://docs.starknet.io/learn/S-two-book/air-development/writing-a-simple-air/constraints-over-trace-polynomials
<div>
<img alt="" />
*Figure 1: Prover workflow: Constraints*
</div>
## Proving Spreadsheet Functions
When we want to perform computations over the cells in a spreadsheet, we don't want to manually fill in the computed values. Instead, we leverage spreadsheet functions to autofill cells based on a given computation.
We can do the same thing with our table, except in addition to autofilling cells, we can also create a constraint that the result was computed correctly. Remember that the purpose of using a proof system is that the verifier can verify a computation was executed correctly without having to execute it themselves? Well, that's exactly why we need to create a constraint.
Now let's say we want to add a new column `C` to our spreadsheet that computes the product of the previous columns plus the first column. We can set `C1` as `A1 * B1 + A1` as in [Figure 2](#figure-2). The corresponding constraint is expressed as `C1 = A1 * B1 + A1`. However, we use an alternate representation `A1 * B1 + A1 - C1 = 0` because we can only enforce constraints stating that an expression should equal zero. Generalizing this constraint to the whole column, we get `col1_row1 * col2_row1 + col1_row1 - col3_row1 = 0`.
<div>
<img alt="" />
*Figure 2: Proving spreadsheet functions as constraints*
</div>
## Identical Constraints Every Row
Obviously, as can be seen in [Figure 2](#figure-2), our new constraint is satisfied for every row in the table. This means that we can substitute creating a constraint for each row with a single constraint over the columns, i.e. the trace polynomials.
Thus, `col1_row1 * col2_row1 + col1_row1 - col3_row1 = 0` becomes:
$$
f_1(x,y) \cdot f_2(x,y) + f_1(x,y) - f_3(x,y) = 0
$$
<Info>
The idea that all rows must have the same constraint may seem restrictive, compared to say a spreadsheet where we can define different functions for different rows. However, we will show in later sections how to handle such use-cases.
(Spoiler alert: it involves selectors and components)
</Info>
## Composition Polynomial
We will now give a name to the polynomial that expresses the constraint: a **composition polynomial**.
$$
C(x,y) = f_1(x,y) \cdot f_2(x,y) + f_1(x,y) - f_3(x,y)
$$
Basically, in order to prove that the constraints are satisfied, we need to show that the composition polynomial evaluates to 0 over the original domain (i.e. the domain of size the number of rows in the table).
But first, as can be seen in the upper part of [Figure 1](#figure-1), we need to expand the evaluations of the trace polynomials by a factor of 2. This is because when you multiply two trace polynomials of degree `n-1` (where `n` is the number of rows) to compute the constraint polynomial, the degree of the constraint polynomial will be the sum of the degrees of the trace polynomials, which is `2n-2`. To adjust for this increase in degree, we double the number of evaluations.
Once we have the expanded evaluations, we can evaluate the composition polynomial $C(x,y)$. Since we need to do a FRI operation on the composition polynomial as well, we expand the evaluations again by a factor of 2 and commit to them as a merkle tree. This part corresponds to the bottom part of [Figure 1](#figure-1).
## Implementation
Let's see how this is implemented in the code.
```rust theme={null}
struct TestEval {
log_size: u32,
}
impl FrameworkEval for TestEval {
fn log_size(&self) -> u32 {
self.log_size
}
fn max_constraint_log_degree_bound(&self) -> u32 {
self.log_size + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR
}
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let col_1 = eval.next_trace_mask();
let col_2 = eval.next_trace_mask();
let col_3 = eval.next_trace_mask();
eval.add_constraint(col_1.clone() * col_2.clone() + col_1.clone() - col_3.clone());
eval
}
}
fn main() {
// --snip--
let mut col_3 = BaseColumn::zeros(num_rows);
col_3.set(0, col_1.at(0) * col_2.at(0) + col_1.at(0));
col_3.set(1, col_1.at(1) * col_2.at(1) + col_1.at(1));
// Convert table to trace polynomials
let domain = CanonicCoset::new(log_num_rows).circle_domain();
let trace: ColumnVec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>> =
vec![col_1, col_2, col_3]
.into_iter()
.map(|col| CircleEvaluation::new(domain, col))
.collect();
// --snip--
// Create a component
let _component = FrameworkComponent::<TestEval>::new(
&mut TraceLocationAllocator::default(),
TestEval {
log_size: log_num_rows,
},
QM31::zero(),
);
}
```
First, we add a new column `col_3` that contains the result of the computation: `col_1 * col_2 + col_1`. Note that all the columns are padded with 0 to a length of 16 via `BaseColumn::zeros(num_rows)` and we got lucky because this satisfies our constraint (i.e. `0 * 0 + 0 - 0 = 0`), so we don't need to modify the constraint.
Then, to create a constraint over the trace polynomials, we first create a `TestEval` struct that implements the `FrameworkEval` trait. Then, we add our constraint logic in the `FrameworkEval::evaluate` function. Note that this function is called for every row in the table, so we only need to define the constraint once.
Inside `FrameworkEval::evaluate`, we call `eval.next_trace_mask()` consecutively three times, retrieving the cell values of all three columns (see [Figure 3](#figure-3) below for a visual representation). Once we retrieve all three column values, we add a constraint of the form `col_1 * col_2 + col_1 - col_3`, which should equal 0. Note that `FrameworkEval::evaluate` will be called for every row in the table.
<div>
<img alt="" />
*Figure 3: Evaluate function*
</div>
We also need to implement `FrameworkEval::max_constraint_log_degree_bound(&self)` for `FrameworkEval`. As mentioned in the [Composition Polynomial section](#composition-polynomial), we need to expand the trace polynomial evaluations because the degree of our composition polynomial is higher than that of the trace polynomial. Expanding it by `LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR=1` is sufficient for our example as the total degree of the highest degree term $f_1(x,y) \cdot f_2(x,y)$ is 2, so we return `self.log_size + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR`. For those who are interested in how to set this value in general, we leave a detailed note below.
<Tip>
**What value to set for `max_constraint_log_degree_bound(&self)`?**
`self.log_size + max(1, ceil(log2(max_degree - 1)))`, where `max_degree` is the maximum total degree of all defined constraint polynomials. For example, the `max_degree` of constraint $f_1(x,y) \cdot f_2(x,y) = 0$ is 2, while that of $f_1(x,y) \cdot f_1(x,y) \cdot f_2(x,y) \cdot f_3(x,y) = 0$ is 4.
e.g.
* degree 1 - 3: `self.log_size + 1`
* degree 4 - 5: `self.log_size + 2`
* degree 6 - 9: `self.log_size + 3`
* degree 10 - 17: `self.log_size + 4`
* ...
</Tip>
<Note>
Now that we know the degree of the composition polynomial, we can now why we need to set the `log_size` of the domain to `log_num_rows + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR + config.fri_config.log_blowup_factor` when precomputing twiddles in the following code:
</Note>
```rust theme={null}
// Precompute twiddles for evaluating and interpolating the trace
let twiddles = SimdBackend::precompute_twiddles(
CanonicCoset::new(
log_num_rows + LOG_CONSTRAINT_EVAL프로젝트로 돌아가기