Skip to content

Commit

Permalink
Fix DummyProofGenerator serialization (0xPolygonZero#1634)
Browse files Browse the repository at this point in the history
* Fix dummy generator serialization

* Tweak

* Update CODEOWNERS
  • Loading branch information
fengzhizi319 committed Nov 3, 2024
1 parent ae6eb60 commit 9a2df3f
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 14 deletions.
34 changes: 29 additions & 5 deletions field/src/polynomial/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ pub struct PolynomialValues<F: Field> {
}

impl<F: Field> PolynomialValues<F> {
//创建一个新的 PolynomialValues 实例,并检查向量的长度是否为 2 的幂
pub fn new(values: Vec<F>) -> Self {
// Check that a subgroup exists of this size, which should be a power of two.
debug_assert!(log2_strict(values.len()) <= F::TWO_ADICITY);
PolynomialValues { values }
}

//创建一个所有值都相同的多项式
pub fn constant(value: F, len: usize) -> Self {
Self::new(vec![value; len])
}
Expand All @@ -44,6 +46,7 @@ impl<F: Field> PolynomialValues<F> {
}

/// Returns the polynomial whole value is one at the given index, and zero elsewhere.
/// 创建一个在特定索引处为一,其余为零的多项式
pub fn selector(len: usize, index: usize) -> Self {
let mut result = Self::zero(len);
result.values[index] = F::ONE;
Expand All @@ -55,11 +58,13 @@ impl<F: Field> PolynomialValues<F> {
self.values.len()
}

//对多项式进行逆快速傅里叶变换,返回系数形式的多项式
pub fn ifft(self) -> PolynomialCoeffs<F> {
ifft(self)
}

/// Returns the polynomial whose evaluation on the coset `shift*H` is `self`.
/// 对多项式进行逆快速傅里叶变换,并将其扩展到一个又陪集子群上
pub fn coset_ifft(self, shift: F) -> PolynomialCoeffs<F> {
let mut shifted_coeffs = self.ifft();
shifted_coeffs
Expand All @@ -72,16 +77,19 @@ impl<F: Field> PolynomialValues<F> {
shifted_coeffs
}

//对多个多项式进行低度扩展
pub fn lde_multiple(polys: Vec<Self>, rate_bits: usize) -> Vec<Self> {
polys.into_iter().map(|p| p.lde(rate_bits)).collect()
}

//对多项式进行低度扩展
pub fn lde(self, rate_bits: usize) -> Self {
let coeffs = ifft(self).lde(rate_bits);
fft_with_options(coeffs, Some(rate_bits), None)
}

/// Low-degree extend `Self` (seen as evaluations over the subgroup) onto a coset.
/// 将多项式扩展到一个余子群
pub fn lde_onto_coset(self, rate_bits: usize) -> Self {
let coeffs = ifft(self).lde(rate_bits);
coeffs.coset_fft_with_options(F::coset_shift(), Some(rate_bits), None)
Expand All @@ -96,6 +104,7 @@ impl<F: Field> PolynomialValues<F> {
}

/// Adds `rhs * rhs_weight` to `self`. Assumes `self.len() == rhs.len()`.
/// rhs 乘以 rhs_weight 后加到当前多项式上
pub fn add_assign_scaled(&mut self, rhs: &Self, rhs_weight: F) {
self.values
.iter_mut()
Expand All @@ -116,7 +125,7 @@ impl<F: Field> From<Vec<F>> for PolynomialValues<F> {
pub struct PolynomialCoeffs<F: Field> {
pub coeffs: Vec<F>,
}

//PolynomialCoeffs是一个表示多项式系数形式的结构体。系数形式意味着多项式的值是通过其系数来表示的。
impl<F: Field> PolynomialCoeffs<F> {
pub fn new(coeffs: Vec<F>) -> Self {
PolynomialCoeffs { coeffs }
Expand All @@ -141,17 +150,20 @@ impl<F: Field> PolynomialCoeffs<F> {
self.coeffs.len()
}

//返回多项式长度的对数
pub fn log_len(&self) -> usize {
log2_strict(self.len())
}

//将多项式分块
pub fn chunks(&self, chunk_size: usize) -> Vec<Self> {
self.coeffs
.chunks(chunk_size)
.map(|chunk| PolynomialCoeffs::new(chunk.to_vec()))
.collect()
}

//在点 x 处评估多项式,返回多项式在 x 处的值
pub fn eval(&self, x: F) -> F {
self.coeffs
.iter()
Expand All @@ -160,6 +172,7 @@ impl<F: Field> PolynomialCoeffs<F> {
}

/// Evaluate the polynomial at a point given its powers. The first power is the point itself, not 1.
/// 在给定点的幂处评估多项式,返回多项式在给定点的值
pub fn eval_with_powers(&self, powers: &[F]) -> F {
debug_assert_eq!(self.coeffs.len(), powers.len() + 1);
let acc = self.coeffs[0];
Expand All @@ -169,14 +182,16 @@ impl<F: Field> PolynomialCoeffs<F> {
.fold(acc, |acc, (&x, &c)| acc + c * x)
}


//在基域点 x 处评估多项式
pub fn eval_base<const D: usize>(&self, x: F::BaseField) -> F
where
F: FieldExtension<D>,
{
self.coeffs
.iter()
.rev()
.fold(F::ZERO, |acc, &c| acc.scalar_mul(x) + c)
.iter() // 迭代多项式的系数
.rev() // 反转迭代顺序,从最高次项开始
.fold(F::ZERO, |acc, &c| acc.scalar_mul(x) + c) // 使用折叠操作计算多项式的值
}

/// Evaluate the polynomial at a point given its powers. The first power is the point itself, not 1.
Expand Down Expand Up @@ -218,12 +233,14 @@ impl<F: Field> PolynomialCoeffs<F> {
}

/// Removes any leading zero coefficients.
/// 移除多项式的前导零系数
pub fn trim(&mut self) {
self.coeffs.truncate(self.degree_plus_one());
}

/// Removes some leading zero coefficients, such that a desired length is reached. Fails if a
/// nonzero coefficient is encountered before then.
/// 将多项式修剪到指定长度
pub fn trim_to_len(&mut self, len: usize) -> Result<()> {
ensure!(self.len() >= len);
ensure!(self.coeffs[len..].iter().all(F::is_zero));
Expand All @@ -232,6 +249,7 @@ impl<F: Field> PolynomialCoeffs<F> {
}

/// Removes any leading zero coefficients.
/// 返回移除前导零系数后的多项式
pub fn trimmed(&self) -> Self {
let coeffs = self.coeffs[..self.degree_plus_one()].to_vec();
Self { coeffs }
Expand All @@ -245,7 +263,7 @@ impl<F: Field> PolynomialCoeffs<F> {
.map_or(0, |i| i + 1)
}

/// Leading coefficient.
/// Leading coefficient.返回多项式的首项系数
pub fn lead(&self) -> F {
self.coeffs
.iter()
Expand All @@ -255,6 +273,7 @@ impl<F: Field> PolynomialCoeffs<F> {
}

/// Reverse the order of the coefficients, not taking into account the leading zero coefficients.
/// 返回系数顺序反转的多项式
pub(crate) fn rev(&self) -> Self {
Self::new(self.trimmed().coeffs.into_iter().rev().collect())
}
Expand All @@ -263,6 +282,7 @@ impl<F: Field> PolynomialCoeffs<F> {
fft(self)
}

//带选项的快速傅里叶变换
pub fn fft_with_options(
self,
zero_factor: Option<usize>,
Expand All @@ -277,6 +297,7 @@ impl<F: Field> PolynomialCoeffs<F> {
}

/// Returns the evaluation of the polynomial on the coset `shift*H`.
/// 带选项的余子群快速傅里叶变换
pub fn coset_fft_with_options(
&self,
shift: F,
Expand All @@ -292,13 +313,16 @@ impl<F: Field> PolynomialCoeffs<F> {
modified_poly.fft_with_options(zero_factor, root_table)
}

//将多项式转换为扩展域
pub fn to_extension<const D: usize>(&self) -> PolynomialCoeffs<F::Extension>
where
F: Extendable<D>,
{
PolynomialCoeffs::new(self.coeffs.iter().map(|&c| c.into()).collect())
}


//将多项式与扩展域元素相乘
pub fn mul_extension<const D: usize>(&self, rhs: F::Extension) -> PolynomialCoeffs<F::Extension>
where
F: Extendable<D>,
Expand Down
18 changes: 17 additions & 1 deletion plonky2/examples/fibonacci.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,25 @@ fn main() -> Result<()> {
let initial_b = builder.add_virtual_target();
let mut prev_target = initial_a;
let mut cur_target = initial_b;
for i in 0..99 {
for i in 0..40 {
println!("{}", i,);
println!("begin prev_target:{:?}", prev_target);
println!("begin cur_target:{:?}", cur_target);


let temp = builder.add(prev_target, cur_target);
if i==21 {
println!("-----------------------");
}
// println!("after prev_target:{:?}", prev_target);
// println!("after cur_target:{:?}", cur_target);
// println!("after output:{:?}", temp);
// println!("gate_instances{:?}", builder.gate_instances);
// println!("copy_constraints{:?}", builder.copy_constraints);
//println!("current_slots{:?}", builder.current_slots);
// println!("gates{:?}", builder.gates);
//println!("base_arithmetic_results{:?}", builder.base_arithmetic_results);

prev_target = cur_target;
cur_target = temp;
}
Expand Down
7 changes: 7 additions & 0 deletions plonky2/src/gadgets/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,15 @@ impl<F: RichField + Extendable<D>, const D: usize> CircuitBuilder<F, D> {
multiplicand_1,
addend,
};
//self.base_arithmetic_result是一个哈希表,用于缓存已经计算过的算术操作及其结果。
if let Some(&result) = self.base_arithmetic_results.get(&operation) {
return result;
}

// Otherwise, we must actually perform the operation using an ArithmeticExtensionGate slot.
let result = self.add_base_arithmetic_operation(operation);
self.base_arithmetic_results.insert(operation, result);
println!("base_arithmetic_results: {:?}", self.base_arithmetic_results);
result
}

Expand All @@ -97,8 +99,11 @@ impl<F: RichField + Extendable<D>, const D: usize> CircuitBuilder<F, D> {
let wires_addend = Target::wire(gate, ArithmeticGate::wire_ith_addend(i));

self.connect(operation.multiplicand_0, wires_multiplicand_0);
//println!("self.copy_constraints: {:?}", self.copy_constraints);
self.connect(operation.multiplicand_1, wires_multiplicand_1);
//println!("self.copy_constraints: {:?}", self.copy_constraints);
self.connect(operation.addend, wires_addend);
//println!("self.copy_constraints: {:?}", self.copy_constraints);

Target::wire(gate, ArithmeticGate::wire_ith_output(i))
}
Expand Down Expand Up @@ -193,6 +198,8 @@ impl<F: RichField + Extendable<D>, const D: usize> CircuitBuilder<F, D> {
pub fn add(&mut self, x: Target, y: Target) -> Target {
let one = self.one();
// x + y = 1 * x * 1 + 1 * y
//const_0 * multiplicand_0 * multiplicand_1 + const_1 * addend`
// const_0 = 1, const_1 = 1, multiplicand_0 = x, multiplicand_1 = 1, addend = y
self.arithmetic(F::ONE, F::ONE, x, one, y)
}

Expand Down
18 changes: 13 additions & 5 deletions plonky2/src/gates/arithmetic_base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@ use crate::util::serialization::{Buffer, IoResult, Read, Write};

/// A gate which can perform a weighted multiply-add, i.e. `result = c0.x.y + c1.z`. If the config
/// has enough routed wires, it can support several such operations in one gate.
/// ArithmeticGate 是一个在电路中执行加权乘加操作的门。它可以执行如下操作:result = c0.x.y + c1.z,
/// 其中 c0 和 c1 是常数,x、y 和 z 是输入。这个门可以在一个门中支持多个这样的操作,具体取决于配置
#[derive(Debug, Clone)]
pub struct ArithmeticGate {
/// Number of arithmetic operations performed by an arithmetic gate.
/// num_ops: 表示一个 ArithmeticGate 可以执行的算术操作的数量。
pub num_ops: usize,
}

Expand All @@ -41,10 +44,12 @@ impl ArithmeticGate {
}

/// Determine the maximum number of operations that can fit in one gate for the given config.
/// 确定在给定配置下一个门中可以容纳的最大操作数
pub(crate) const fn num_ops(config: &CircuitConfig) -> usize {
let wires_per_op = 4;
config.num_routed_wires / wires_per_op
}
///返回第 i 个操作的乘数、加数和输出的线索引。每个操作占用4个字段,所以要乘以4
pub(crate) const fn wire_ith_multiplicand_0(i: usize) -> usize {
4 * i
Expand Down Expand Up @@ -74,7 +79,9 @@ impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for ArithmeticGate
Ok(Self { num_ops })
}

//eval_unfiltered 的方法,用于评估 ArithmeticGate 的约束条件
fn eval_unfiltered(&self, vars: EvaluationVars<F, D>) -> Vec<F::Extension> {
//从 vars 中提取局部常量 const_0 和 const_1
let const_0 = vars.local_constants[0];
let const_1 = vars.local_constants[1];

Expand Down Expand Up @@ -131,6 +138,7 @@ impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for ArithmeticGate
constraints
}

/// ArithmeticGate 的每个算术操作生成一个见证生成器,并将这些生成器收集到一个向量中返回。
fn generators(&self, row: usize, local_constants: &[F]) -> Vec<WitnessGeneratorRef<F, D>> {
(0..self.num_ops)
.map(|i| {
Expand All @@ -141,7 +149,7 @@ impl<F: RichField + Extendable<D>, const D: usize> Gate<F, D> for ArithmeticGate
const_1: local_constants[1],
i,
}
.adapter(),
.adapter(),
)
})
.collect()
Expand Down Expand Up @@ -194,7 +202,7 @@ pub struct ArithmeticBaseGenerator<F: RichField + Extendable<D>, const D: usize>
}

impl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F, D>
for ArithmeticBaseGenerator<F, D>
for ArithmeticBaseGenerator<F, D>
{
fn id(&self) -> String {
"ArithmeticBaseGenerator".to_string()
Expand All @@ -206,9 +214,9 @@ impl<F: RichField + Extendable<D>, const D: usize> SimpleGenerator<F, D>
ArithmeticGate::wire_ith_multiplicand_1(self.i),
ArithmeticGate::wire_ith_addend(self.i),
]
.iter()
.map(|&i| Target::wire(self.row, i))
.collect()
.iter()
.map(|&i| Target::wire(self.row, i))
.collect()
}

fn run_once(
Expand Down
Loading

0 comments on commit 9a2df3f

Please sign in to comment.