Starknet 백서

Starknet

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 51쪽

'_N(F) = F[x]^{ \leq N/2 - 1} + Y \cdot F[x]^{ \leq N/2 - 1}$ where $F[x]^{ \leq N/2 - 1}$ represents polynomials of degree at most $N/2 - 1$ with coefficients in $F$. Similarly, we can represent the space $L_N(F)$ as: $L_N(F) = F[x]^{ \leq N/2} + Y \cdot F[x]^{ \leq N/2 - 1}$ Thus the space $L'_N(F)$ does not include the monomial $X^{N/2}$, which lies in the space $L_N(F)$. Therefore, $L_N(F) = L'_N(F) + \langle X^{N/2} \rangle$ Since the space spanned by $X^{N/2}$ is same as the space spanned by the vanishing polynomial $v_n(x)$ which has degree $deg(v_n) = 2^{n-1} =N/2$, we can also write: $L_N(F) = L'_N(F) + \langle v_n \rangle$ A consequence of this dimension gap is that we cannot interpolate some polynomials over the circle i.e. those with $X^{N/2}$. We will address how this dimension gap is handled within the FRI protocol in the upcoming sections. # Introduction Source: https://docs.starknet.io/learn/S-two-book/how-it-works/circle-fft/index > This section introduces the Circle FFT algorithm, used to interpolate bivariate polynomials over the circle domain using a divide-and-conquer approach. This section is organized as follows: * **[Algorithm](/learn/S-two-book/how-it-works/circle-fft/algorithm)**: Overview of the Circle FFT algorithm with concrete examples showing the three-step interpolation process. * **[Twiddles](/learn/S-two-book/how-it-works/circle-fft/twiddles)**: Precomputation and storage of twiddle values required for efficient FFT operations. * **[Interpolate](/learn/S-two-book/how-it-works/circle-fft/interpolation)**: Detailed implementation walkthrough of the interpolation function with code breakdown. * **[Basis and Dimension Gap](/learn/S-two-book/how-it-works/circle-fft/basis)**: FFT basis for Circle FFT and analysis of the dimension gap in circle polynomial spaces. # Interpolation Source: https://docs.starknet.io/learn/S-two-book/how-it-works/circle-fft/interpolation This section covers the implementation of the `interpolate` function step by step. The function takes as input a `CircleEvaluation` and a `TwiddleTree` and outputs a `CirclePoly`. The circle FFT algorithm changes the order of the input. Since the `CircleEvaluation` is in `BitReversedOrder`, the output coefficients of the `CirclePoly` will be in `NaturalOrder`. The complete implementation of the `interpolate` function is shown below: ```rust theme={null} fn interpolate( eval: CircleEvaluation<Self, BaseField, BitReversedOrder>, twiddles: &TwiddleTree<Self>, ) -> CirclePoly<Self> { assert!(eval.domain.half_coset.is_doubling_of(twiddles.root_coset)); let mut values = eval.values; if eval.domain.log_size() == 1 { let y = eval.domain.half_coset.initial.y; let n = BaseField::from(2); let yn_inv = (y * n).inverse(); let y_inv = yn_inv * n; let n_inv = yn_inv * y; let (mut v0, mut v1) = (values[0], values[1]); ibutterfly(&mut v0, &mut v1, y_inv); return CirclePoly::new(vec![v0 * n_inv, v1 * n_inv]); } if eval.domain.log_size() == 2 { let CirclePoint { x, y } = eval.domain.half_coset.initial; let n = BaseField::from(4); let xyn_inv = (x * y * n).inverse(); let x_inv = xyn_inv * y * n; let y_inv = xyn_inv * x * n; let n_inv = xyn_inv * x * y; let (mut v0, mut v1, mut v2, mut v3) = (values[0], values[1], values[2], values[3]); ibutterfly(&mut v0, &mut v1, y_inv); ibutterfly(&mut v2, &mut v3, -y_inv); ibutterfly(&mut v0, &mut v2, x_inv); ibutterfly(&mut v1, &mut v3, x_inv); return CirclePoly::new(vec![v0 * n_inv, v1 * n_inv, v2 * n_inv, v3 * n_inv]); } let line_twiddles = domain_line_twiddles_from_tree(eval.domain, &twiddles.itwiddles); let circle_twiddles = circle_twiddles_from_line_twiddles(line_twiddles[0]); for (h, t) in circle_twiddles.enumerate() { fft_layer_loop(&mut values, 0, h, t, ibutterfly); } for (layer, layer_twiddles) in line_twiddles.into_iter().enumerate() { for (h, &t) in layer_twiddles.iter().enumerate() { fft_layer_loop(&mut values, layer + 1, h, t, ibutterfly); } } // Divide all values by 2^log_size. let inv = BaseField::from_u32_unchecked(eval.domain.size() as u32).inverse(); for val in &mut values { *val *= inv; } CirclePoly::new(values) } ``` The function includes hardcoded implementations for circle domains of small sizes for efficiency. Lets breakdown the function step by step. 1. **Compute Twiddles:** Given the `TwiddleTree`, the function computes the line twiddles and circle twiddles. * The `circle_twiddles` are twiddles required at the first layer where all points are projected to the $x$-axis. These correspond to the $y$-coordinate points in the half coset. * The `line_twiddles` are twiddles required to compute FFT at the subsequent recursive layers where the squaring map $\pi$ is used as the 2-to-1 map. > For the example of the [half coset](/learn/S-two-book/how-it-works/circle-fft/twiddles#fig-half-coset), there are three FFT layers: one layer with the projection map $\pi_x$ and two recursive layers with the squaring map $\pi$. > > The `line_twiddles` for the two recursive layers are computed using the inverse twiddles $[a^{-1}, b^{-1}, \pi(a)^{-1}, 1]$. For the first recursive layer, the twiddles are the inverse of the $x$-coordinates: $[a^{-1}, b^{-1}]$. For the second recursive layer, the twiddles are the inverse of the square of the $x$-coordinates: $[\pi(a)^{-1}]$. Thus for this example, the `line_twiddles` are $[[a^{-1}, b^{-1}], [\pi(a)^{-1}]]$. The `circle_twiddles` are computed using the first recursive layer `line_twiddles`. They are equal to the inverse of the $y$-coordinates of the half coset. > For this example, they take the values $[b^{-1}, -b^{-1}, -a^{-1}, a^{-1}]$. 2. **Apply FFT Layers:** With the twiddles for each layer computed, the FFT algorithm is applied first using the projection map $\pi_x$ and `circle_twiddles`, then using the squaring map $\pi$ and the `line_twiddles`. This process uses two key functions: * **`fft_layer_loop`**: Applies butterfly operations across a specific layer of the FFT. The key inputs are the values array, layer parameters, twiddle factor, and the butterfly function to apply. It iterates through pairs of elements in the values array at the appropriate indices and applies the butterfly operation with the twiddle factor. * **`ibutterfly`**: Performs the inverse butterfly operation on a pair of elements from the values array. This is the fundamental operation that transforms the values during interpolation. 3. **Scale and Output:** Finally, the `values` are scaled by dividing by the domain size, and the `CirclePoly` is output. This completes the description of the `interpolate` function. The `evaluate` function follows a similar approach, applying the same components in reverse order to convert from coefficient representation back to point-value representation. In the next section, we will explore the FFT basis underlying the Circle FFT algorithm. # Twiddles Source: https://docs.starknet.io/learn/S-two-book/how-it-works/circle-fft/twiddles This section provides a detailed look at how twiddles are computed and stored in S-two. <Callout type="info"> As discussed earlier, S-two has two main backend implementations: `CpuBackend` and `SimdBackend`. Each backend implements the `PolyOps` trait, which provides core polynomial operations such as interpolation, evaluation and twiddle precomputation. Here and in the following sections on Circle FFT, we will explore how these functions are implemented for the `CpuBackend`. </Callout> ## Twiddle Tree The twiddles are stored using the `TwiddleTree` struct implemented as follows: ```rust theme={null} pub struct TwiddleTree<B: PolyOps> { pub root_coset: Coset, // TODO(shahars): Represent a slice, and grabbing, in a generic way pub twiddles: B::Twiddles, pub itwiddles: B::Twiddles, } ``` For `CpuBackend`, `B::Twiddles` is a vector of `BaseField` elements. Here, `root_coset` is the half coset $q + \langle g_{n-1} \rangle$ of our circle domain $D_n$. As we have seen in the earlier section, for interpolation we divide by twiddles or multiply by inverse twiddles. In the evaluation algorithm, we multiply by twiddles. Thus we store both `twiddles` and their inverses `itwiddles`. Now we will understand how the twiddle tree is computed using an example. Consider the following half coset $q + \langle g_2 \rangle$ of a circle domain $D_3$. <div> <img alt="" /> *Figure 1: Half Coset of size 4* </div> The `TwiddleTree` is constructed by the `precompute_twiddles` function, which takes the half coset as input and produces the twiddles needed to perform FFT over the corresponding circle domain. It is implemented as follows: ```rust theme={null} fn precompute_twiddles(coset: Coset) -> TwiddleTree<Self> { const CHUNK_LOG_SIZE: usize = 12; const CHUNK_SIZE: usize = 1 << CHUNK_LOG_SIZE; let root_coset = coset; let twiddles = slow_precompute_twiddles(coset); // Inverse twiddles. // Fallback to the non-chunked version if the domain is not big enough. if CHUNK_SIZE > root_coset.size() { let itwiddles = twiddles.iter().map(|&t| t.inverse()).collect(); return TwiddleTree { root_coset, twiddles, itwiddles, }; } let mut itwiddles = vec![BaseField::zero(); twiddles.len()]; twiddles .array_chunks::<CHUNK_SIZE>() .zip(itwiddles.array_chunks_mut::<CHUNK_SIZE>()) .for_each(|(src, dst)| { batch_inverse_in_place(src, dst); }); TwiddleTree { root_coset, twiddles, itwiddles, } } ``` As shown above, it first computes `twiddles` using the function `slow_precompute_twiddles` then computes their inverses `itwiddles` using batch inversion and finally stores them in the `TwiddleTree` along with the `root_coset` which is the input half coset. Now let us look into the function `slow_precompute_twiddles`. ```rust theme={null} pub fn slow_precompute_twiddles(mut coset: Coset) -> Vec<BaseField> { let mut twiddles = Vec::with_capacity(coset.size()); for _ in 0..coset.log_size() { let i0 = twiddles.len(); twiddles.extend( coset .iter() .take(coset.size() / 2) .map(|p| p.x) .collect::<Vec<_>>(), ); bit_reverse(&mut twiddles[i0..]); coset = coset.double(); } // Pad with an arbitrary value to make the length a power of 2. twiddles.push(1.into()); twiddles } ``` The above function computes the twiddles required to compute FFT over the line (i.e. the recursive layer FFT, after projecting to the $x$-axis). For the example in the figure with the half coset points $[(a, b), (b, -a), (-a, -b), (-b, a)]$, this function will output $[a, b, \pi(a), 1]$. Thus, for the half coset in the figure, the `precompute_twiddles` will output `TwiddleTree` with `twiddles` as $[a, b, \pi(a), 1]$ and `itwiddles` as $[a^{-1}, b^{-1}, \pi(a)^{-1}, 1]$. The `twiddles` will be used for the evaluation algorithm and `itwiddles` will be used for the interpolation algorithm. In the next section, we will bring together everything we've covered so far on Circle FFT to examine the implementation of the interpolation algorithm. # FRI Prover Source: https://docs.starknet.io/learn/S-two-book/how-it-works/circle-fri/fri_prover In this section, we examine the FRI prover implementation, beginning with the FRI protocol configuration. ## FRI Protocol Configuration We configure the FRI protocol using the following parameters: * Log of blowup factor $\beta$ * Log of last layer degree bound (determines the number of rounds $r$ in the FRI protocol) * Number of queries $s$ made by the verifier in the query phase It is implemented as follows: ```rust theme={null} pub struct FriConfig { pub log_blowup_factor: u32, pub log_last_layer_degree_bound: u32, pub n_queries: usize, // TODO(andrew): fold_steps. } ``` We calculate the security bits of our protocol as follows: ```rust theme={null} pub const fn security_bits(&self) -> u32 { self.log_blowup_factor * self.n_queries as u32 } ``` This is as we discussed in the [Security Analysis section](/learn/S-two-book/how-it-works/circle-fri/overview#security-analysis). ## Proving Let us look into how the FRI prover struct is implemented. ```rust theme={null} pub struct FriProver<'a, B: FriOps + MerkleOps<MC::H>, MC: MerkleChannel> { config: FriConfig, first_layer: FriFirstLayerProver<'a, B, MC::H>, inner_layers: Vec<FriInnerLayerProver<B, MC::H>>, last_layer_poly: LinePoly, } ``` Here, `FriOps` is a trait which implements functionality for the commit phase of FRI, such as folding the evaluations, and `MerkleOps` is the trait used in the [Merkle commitment scheme](/learn/S-two-book/how-it-works/vcs/hash_functions#merkleops-trait). The generic `B` refers to a specific backend, for example either `CpuBackend` or `SimdBackend`, which implements the `FriOps` and `MerkleOps` traits. We described [FRI](/learn/S-two-book/how-it-works/circle-fri/overview#protocol) as an interactive protocol between the prover and the verifier. To make the protocol non-interactive, we use the [Fiat-Shamir transform](https://en.wikipedia.org/wiki/Fiat%E2%80%93Shamir_heuristic), where both the prover and verifier use a channel to hash the transcript and generate random challenges. These functionalities are defined by the `MerkleChannel` trait. In the non-interactive protocol, oracles to functions are replaced by Merkle commitments to their evaluations, and queries to the oracle by the verifier are replaced by Merkle decommitments, which the prover appends to the channel. The `FRIProver` struct is composed of several layers. Each layer contains a Merkle tree that commits to the evaluations of a polynomial for that layer. The main components are: **• `config`**: The `FriConfig` discussed in the previous section, which holds protocol parameters. **• `first_layer`**: The first layer of the FRI protocol, containing the commitment to the initial set of columns. ```rust theme={null} struct FriFirstLayerProver<'a, B: FriOps + MerkleOps<H>, H: MerkleHasher> { columns: &'a [SecureEvaluation<B, BitReversedOrder>], merkle_tree: MerkleProver<B, H>, } ``` For example, the `columns` are the array of evaluations $[h_{0}, h_{1}, h_{2}]$, and `merkle_tree` commits to $h_{0} \in F^{H_0}$, $h_{1} \in F^{H_1}$, and $h_{2} \in F^{H_2}$ using a single Merkle tree. **• `inner_layers`**: The inner layers of FRI, each representing a folding round and its corresponding Merkle commitment. ```rust theme={null} struct FriInnerLayerProver<B: FriOps + MerkleOps<H>, H: MerkleHasher> { evaluation: LineEvaluation<B>, merkle_tree: MerkleProver<B, H>, } ``` In our example, there are two FRI inner layers: the first contains evaluations of $g_0$ over the "line" domain $F^{I_0}$ with a Merkle commitment to $g_0$, and the second contains evaluations of $g_1$ over $F^{I_1}$ with its Merkle commitment. **• `last_layer_poly`**: The last layer polynomial, which the prover sends in clear to the verifier. ```rust theme={null} pub struct LinePoly { /// Coefficients of the polynomial in [`line_ifft`] algorithm's basis. /// /// The coefficients are stored in bit-reversed order. #[allow(rustdoc::private_intra_doc_links)] coeffs: Vec<SecureField>, /// The number of coefficients stored as `log2(len(coeffs))`. log_size: u32, } ``` For our example, this is the polynomial $g_2$ in coefficient representation. ### Commitment The `commit` function corresponds to the commitment phase of our protocol and outputs the `FriProver` struct. This function handles multiple mixed-degree polynomials, each evaluated over domains of different sizes. We will now give a high-level overview of the function as it is implemented in Stwo. ```rust theme={null} pub fn commit( channel: &mut MC::C, config: FriConfig, columns: &'a [SecureEvaluation<B, BitReversedOrder>], twiddles: &TwiddleTree<B>, ) -> Self { assert!(!columns.is_empty(), "no columns"); assert!(columns.iter().all(|e| e.domain.is_canonic()), "not canonic"); assert!( columns .iter() .tuple_windows() .all(|(a, b)| a.len() > b.len()), "column sizes not decreasing" ); let first_layer = Self::commit_first_layer(channel, columns); let (inner_layers, last_layer_evaluation) = Self::commit_inner_layers(channel, config, columns, twiddles); let last_layer_poly = Self::commit_last_layer(channel, config, last_layer_evaluation); Self { config, first_layer, inner_layers, last_layer_poly, } } ``` It takes the following inputs: * `channel`: The Merkle channel used for the Fiat-Shamir transform to generate random challenges and maintain the transcript. * `config`: The `FriConfig` containing protocol parameters. * `columns`: The array of evaluations of the functions. For our example, this will contain $[h_0, h_1, h_2]$ over their respective domains $[H_0, H_1, H_2]$. * `twiddles`: The [precomputed twiddle](/learn/S-two-book/how-it-works/circle-fft/twiddles#twiddle-tree) values needed for folding. The commitment phase consists of the following steps, corresponding to the protocol rounds described in the [overview](/learn/S-two-book/how-it-works/circle-fri/overview#protocol): 1. **First Layer Commitment** (`commit_first_layer`): * Takes the input functions $[h_0, h_1, h_2]$ and creates a Merkle commitment to all of them using a single Merkle tree. * Commits to the root of the Merkle tree by appending it to the channel as part of the transcript. * Returns the `FriFirstLayerProver` containing the columns and their Merkle commitment. 2. **Inner Layers Commitment** (`commit_inner_layers`): * Performs the folding rounds as described in the protocol. * In each round $i$: * Decomposes the previous round "line" polynomial $g_{i-1}$ into $g_{i-1, 0}$ and $g_{i-1, 1}$. * Decomposes the current round "circle" polynomial $h_i$ into $h_{i, 0}$ and $h_{i, 1}$. * Receives random challenge $\lambda_i$ from the channel. * Folds the decomposed functions to compute $g_i$ over domain $I_i$. * Creates Merkle commitment to $g_i$ and adds the root of the Merkle tree to the channel. * For our example with $r=2$, this creates two inner layers containing $g_0$ and $g_1$. * Returns the following two objects: * Two `FriInnerLayerProver` corresponding to $g_0$ and $g_1$. * Final `last_layer_evaluation`, i.e., evaluations of $g_2$ over the domain $I_2$. 3. **Last Layer Commitment** (`commit_last_layer`): * Takes the final evaluation $g_r$ (which will be sent to the verifier in clear). * Interpolates it to coefficient form and appends the coefficients into the channel as protocol transcript. * For our example, this converts $g_2 \in F^{I_2}$ to polynomial coefficient representation. * Returns the `last_layer_poly`. The function then constructs and returns the complete `FriProver` struct containing all layers, which will be used later for decommitment during the query phase. ### Decommitment Now we will look at the decommit function. It is implemented as follows: ```rust theme={null} pub fn decommit(self, channel: &mut MC::C) -> (FriProof<MC::H>, BTreeMap<u32, Vec<usize>>) { let max_column_log_size = self.first_layer.max_column_log_size(); let queries = Queries::generate(channel, max_column_log_size, self.config.n_queries); let column_log_sizes = self.first_layer.column_log_sizes(); let query_positions_by_log_size = get_query_positions_by_log_size(&queries, column_log_sizes); let proof = self.decommit_on_queries(&queries); (proof, query_positions_by_log_size) } ``` It takes the following input: 1. `self`: The `FriProver` containing the Merkle tree commitments to all the FRI layers. 2. `channel`: The Fiat-Shamir channel used to hash the transcript and generate the random query points. Let us walk through the function step by step. 1. **Setup Query Generation**: Use the Fiat-Shamir channel to generate `n_queries` random positions on the maximum domain. 2. **Map Query Positions by Domain Size**: The function `get_query_positions_by_log_size` takes `queries` and `column_log_sizes` as input and maps each domain size to its respective query position in the column. 3. **Generate Proof**: The function `decommi
프로젝트로 돌아가기