Skip to content

Commit 14ec3e3

Browse files
JulianGCalderonAlon-TiyuvalswOmriEshhar1
authored
Add dynamic layout basic support (#1824)
* Fix Zero segment location. * Fixed has_zero_segment naming * Fix prover input. * Fixed version reading when no version is supplied * Added change to changelog. * fix test_from_serializable() * fix panic_impl error * fix cairo version * Add dummy changelog * Pin wasm-bindgen * Register change in CHANGELOG * Update Cargo.lock * Remove changes from CHANGELOG * Add argument parsing for layout params file * Add dynamic support (no implement) * Add cairo_layout_params_file.example.json * Implement dynamic layout creation * Update CHANGELOG * Add cli dynamic support for cairo 1 * Make wasm compatible * Use public_memory_fraction = 4 vy default * Deserialize bool from int * Add comparison with python-vm (failing) * Rebuild .rs files in makefile * Use 8 as dynamic public_memory_fraction The same value is used in python-vm * Use None ratio for dynamic unused builtins * Add rangecheck96 to private inputs * Make dyn py files depend on params_file * Use cpu_component_step=1 by default * Fix typo in private inputs * Add range check value to air private input test * Fix zero segment location * Use zero builtin instead of None * Add debug scripts * Remove dup makefile recipes * remove outdated test * Enable ensure-no_std on test * Fix tests * Add correct test * Rename tset * Add comment * Add debugging document * Update cairo layout params file * Remove duplicated range check * Remove dup * Remove debugging and scrippts (moveed to another branch) * Add comment * Add tests * Add dynamic test to cairo-vm-cli * Add parse test * Remove compare all dynamic * Add script for comparing with dynamic layouts * Add tests to workflow * Delete logic changes They are going to be moved to another branch * Delete more logic changes * Update rust.yml * Rename compare_outputs_dynamic_layout.sh to compare_outputs_dynamic_layouts.sh * Update test script * Add more tests * Rename parameter for clarity * Enable mod builtin only on feature with dynamic layout * Remove debug assert * Refactor errors into variants * Fix failing test * Move cairo_layout_params_file to test folder * Document cairo_layout_param_file in the README.md * Fix clippy warning * Use mod_builtin feature in tests --------- Co-authored-by: Alon Titelman <[email protected]> Co-authored-by: Yuval Goldberg <[email protected]> Co-authored-by: Omri Eshhar <[email protected]>
1 parent 63b4a55 commit 14ec3e3

File tree

22 files changed

+744
-58
lines changed

22 files changed

+744
-58
lines changed

.github/workflows/rust.yml

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -725,6 +725,45 @@ jobs:
725725
- name: Run script
726726
run: ./vm/src/tests/compare_factorial_outputs_all_layouts.sh
727727

728+
compare-outputs-dynamic-layouts:
729+
name: Compare outputs with dynamic layouts
730+
needs: [ build-programs, build-release ]
731+
runs-on: ubuntu-22.04
732+
steps:
733+
- name: Checkout
734+
uses: actions/checkout@v3
735+
736+
- name: Python3 Build
737+
uses: actions/setup-python@v4
738+
with:
739+
python-version: '3.9'
740+
cache: 'pip'
741+
742+
- name: Install cairo-lang and deps
743+
run: pip install -r requirements.txt
744+
745+
- name: Fetch release binary
746+
uses: actions/cache/restore@v3
747+
with:
748+
key: cli-bin-rel-${{ github.sha }}
749+
path: target/release/cairo-vm-cli
750+
fail-on-cache-miss: true
751+
752+
- uses: actions/download-artifact@master
753+
with:
754+
name: proof_programs
755+
path: cairo_programs/proof_programs/
756+
757+
- name: Fetch programs
758+
uses: actions/cache/restore@v3
759+
with:
760+
path: ${{ env.CAIRO_PROGRAMS_PATH }}
761+
key: cairo_proof_programs-cache-${{ hashFiles('cairo_programs/**/*.cairo', 'examples/wasm-demo/src/array_sum.cairo') }}
762+
fail-on-cache-miss: true
763+
764+
- name: Run script
765+
run: ./vm/src/tests/compare_outputs_dynamic_layouts.sh
766+
728767
compare-run-from-cairo-pie-all-outputs:
729768
name: Compare all outputs from running Cairo PIEs
730769
needs: [ build-programs, build-release, run-cairo-release ]

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,5 @@ cairo-vm-cli/air_input.pub
2626
ensure-no_std/Cargo.lock
2727
cairo_programs/proof_programs/*.cairo
2828

29+
!cairo_layout_params_file.json
2930
!vm/src/tests/cairo_pie_test_output.json

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
#### Upcoming Changes
44

5+
* feat(BREAKING): [#1824](https://github.com/lambdaclass/cairo-vm/pull/1824):
6+
* Add support for dynamic layout
7+
* CLI change(BREAKING): The flag `cairo_layout_params_file` must be specified when using dynamic layout.
8+
* Signature change(BREAKING): Both `CairoRunner::new` and `CairoRunner::new_v2` now receive an `Option<CairoLayoutParams>`, used only with dynamic layout.
9+
510
* chore: bump pip `cairo-lang` 0.13.2 [#1827](https://github.com/lambdaclass/cairo-vm/pull/1827)
611

712
* chore: bump `cairo-lang-` dependencies to 2.8.0 [#1833](https://github.com/lambdaclass/cairo-vm/pull/1833/files)

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,8 @@ The cairo-vm-cli supports the following optional arguments:
182182

183183
- `run_from_cairo_pie`: Runs a Cairo PIE instead of a compiled json file. The name of the file will be the first argument received by the CLI (as if it were to run a normal compiled program). Can only be used if proof_mode is not enabled.
184184

185+
- `cairo_layout_params_file`: Only used with dynamic layout. Receives the name of a json file with the dynamic layout parameters.
186+
185187
For example, to obtain the air public inputs from a fibonacci program run, we can run :
186188

187189
```bash

bench/criterion_benchmark.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ fn build_many_runners(c: &mut Criterion) {
3030
CairoRunner::new(
3131
black_box(&program),
3232
black_box(LayoutName::starknet_with_keccak),
33+
black_box(None),
3334
black_box(false),
3435
black_box(false),
3536
)
@@ -45,7 +46,16 @@ fn load_program_data(c: &mut Criterion) {
4546
let program = Program::from_bytes(program.as_slice(), Some("main")).unwrap();
4647
c.bench_function("initialize", |b| {
4748
b.iter_batched(
48-
|| CairoRunner::new(&program, LayoutName::starknet_with_keccak, false, false).unwrap(),
49+
|| {
50+
CairoRunner::new(
51+
&program,
52+
LayoutName::starknet_with_keccak,
53+
None,
54+
false,
55+
false,
56+
)
57+
.unwrap()
58+
},
4959
|mut runner| _ = black_box(runner.initialize(false).unwrap()),
5060
BatchSize::SmallInput,
5161
)

bench/iai_benchmark.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ fn build_runner() {
3434
let runner = CairoRunner::new(
3535
black_box(&program),
3636
LayoutName::starknet_with_keccak,
37+
None,
3738
false,
3839
false,
3940
)
@@ -47,7 +48,14 @@ fn build_runner_helper() -> CairoRunner {
4748
//Picked the biggest one at the time of writing
4849
let program = include_bytes!("../cairo_programs/benchmarks/keccak_integration_benchmark.json");
4950
let program = Program::from_bytes(program.as_slice(), Some("main")).unwrap();
50-
CairoRunner::new(&program, LayoutName::starknet_with_keccak, false, false).unwrap()
51+
CairoRunner::new(
52+
&program,
53+
LayoutName::starknet_with_keccak,
54+
None,
55+
false,
56+
false,
57+
)
58+
.unwrap()
5159
}
5260

5361
#[inline(never)]

cairo-vm-cli/src/main.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use cairo_vm::cairo_run::{self, EncodeTraceError};
66
use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::BuiltinHintProcessor;
77
#[cfg(feature = "with_tracer")]
88
use cairo_vm::serde::deserialize_program::DebugInfo;
9+
use cairo_vm::types::layout::CairoLayoutParams;
910
use cairo_vm::types::layout_name::LayoutName;
1011
use cairo_vm::vm::errors::cairo_run_errors::CairoRunError;
1112
use cairo_vm::vm::errors::trace_errors::TraceError;
@@ -43,8 +44,13 @@ struct Args {
4344
entrypoint: String,
4445
#[structopt(long = "memory_file")]
4546
memory_file: Option<PathBuf>,
47+
/// When using dynamic layout, it's parameters must be specified through a layout params file.
4648
#[clap(long = "layout", default_value = "plain", value_enum)]
4749
layout: LayoutName,
50+
/// Required when using with dynamic layout.
51+
/// Ignored otherwise.
52+
#[clap(long = "cairo_layout_params_file", required_if_eq("layout", "dynamic"))]
53+
cairo_layout_params_file: Option<PathBuf>,
4854
#[structopt(long = "proof_mode")]
4955
proof_mode: bool,
5056
#[structopt(long = "secure_run")]
@@ -162,6 +168,11 @@ fn run(args: impl Iterator<Item = String>) -> Result<(), Error> {
162168

163169
let trace_enabled = args.trace_file.is_some() || args.air_public_input.is_some();
164170

171+
let cairo_layout_params = match args.cairo_layout_params_file {
172+
Some(file) => Some(CairoLayoutParams::from_file(&file)?),
173+
None => None,
174+
};
175+
165176
let cairo_run_config = cairo_run::CairoRunConfig {
166177
entrypoint: &args.entrypoint,
167178
trace_enabled,
@@ -170,6 +181,7 @@ fn run(args: impl Iterator<Item = String>) -> Result<(), Error> {
170181
proof_mode: args.proof_mode,
171182
secure_run: args.secure_run,
172183
allow_missing_builtins: args.allow_missing_builtins,
184+
dynamic_layout_params: cairo_layout_params,
173185
..Default::default()
174186
};
175187

@@ -405,6 +417,19 @@ mod tests {
405417
assert_matches!(run(args), Err(Error::Runner(_)));
406418
}
407419

420+
#[test]
421+
fn test_run_dynamic_params() {
422+
let mut args = vec!["cairo-vm-cli".to_string()];
423+
args.extend_from_slice(&["--layout".to_string(), "dynamic".to_string()]);
424+
args.extend_from_slice(&[
425+
"--cairo_layout_params_file".to_string(),
426+
"../vm/src/tests/cairo_layout_params_file.json".to_string(),
427+
]);
428+
args.push("../cairo_programs/proof_programs/fibonacci.json".to_string());
429+
430+
assert_matches!(run(args.into_iter()), Ok(_));
431+
}
432+
408433
//Since the functionality here is trivial, I just call the function
409434
//to fool Codecov.
410435
#[test]

cairo1-run/src/cairo_run.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@ use cairo_vm::{
3838
math_utils::signed_felt,
3939
serde::deserialize_program::{ApTracking, FlowTrackingData, HintParams, ReferenceManager},
4040
types::{
41-
builtin_name::BuiltinName, layout_name::LayoutName, program::Program,
42-
relocatable::MaybeRelocatable,
41+
builtin_name::BuiltinName, layout::CairoLayoutParams, layout_name::LayoutName,
42+
program::Program, relocatable::MaybeRelocatable,
4343
},
4444
vm::{
4545
errors::{runner_errors::RunnerError, vm_errors::VirtualMachineError},
@@ -86,6 +86,7 @@ pub struct Cairo1RunConfig<'a> {
8686
pub relocate_mem: bool,
8787
/// Cairo layout chosen for the run
8888
pub layout: LayoutName,
89+
pub dynamic_layout_params: Option<CairoLayoutParams>,
8990
/// Run in proof_mode
9091
pub proof_mode: bool,
9192
/// Should be true if either air_public_input or cairo_pie_output are needed
@@ -106,6 +107,7 @@ impl Default for Cairo1RunConfig<'_> {
106107
proof_mode: false,
107108
finalize_builtins: false,
108109
append_return_values: false,
110+
dynamic_layout_params: None,
109111
}
110112
}
111113
}
@@ -248,6 +250,7 @@ pub fn cairo_run_program(
248250
let mut runner = CairoRunner::new_v2(
249251
&program,
250252
cairo_run_config.layout,
253+
cairo_run_config.dynamic_layout_params.clone(),
251254
runner_mode,
252255
cairo_run_config.trace_enabled,
253256
)?;

cairo1-run/src/main.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use cairo1_run::{cairo_run_program, Cairo1RunConfig, FuncArg};
44
use cairo_lang_compiler::{
55
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
66
};
7+
use cairo_vm::types::layout::CairoLayoutParams;
78
use cairo_vm::{
89
air_public_input::PublicInputError, types::layout_name::LayoutName,
910
vm::errors::trace_errors::TraceError, Felt252,
@@ -24,8 +25,13 @@ struct Args {
2425
trace_file: Option<PathBuf>,
2526
#[structopt(long = "memory_file")]
2627
memory_file: Option<PathBuf>,
28+
/// When using dynamic layout, it's parameters must be specified through a layout params file.
2729
#[clap(long = "layout", default_value = "plain", value_enum)]
2830
layout: LayoutName,
31+
/// Required when using with dynamic layout.
32+
/// Ignored otherwise.
33+
#[clap(long = "cairo_layout_params_file", required_if_eq("layout", "dynamic"))]
34+
cairo_layout_params_file: Option<PathBuf>,
2935
#[clap(long = "proof_mode", value_parser)]
3036
proof_mode: bool,
3137
#[clap(long = "air_public_input", requires = "proof_mode")]
@@ -153,6 +159,11 @@ fn run(args: impl Iterator<Item = String>) -> Result<Option<String>, Error> {
153159
args.args = process_args(&std::fs::read_to_string(filename)?).unwrap();
154160
}
155161

162+
let cairo_layout_params = match args.cairo_layout_params_file {
163+
Some(file) => Some(CairoLayoutParams::from_file(&file)?),
164+
None => None,
165+
};
166+
156167
let cairo_run_config = Cairo1RunConfig {
157168
proof_mode: args.proof_mode,
158169
serialize_output: args.print_output,
@@ -162,6 +173,7 @@ fn run(args: impl Iterator<Item = String>) -> Result<Option<String>, Error> {
162173
args: &args.args.0,
163174
finalize_builtins: args.air_public_input.is_some() || args.cairo_pie_output.is_some(),
164175
append_return_values: args.append_return_values,
176+
dynamic_layout_params: cairo_layout_params,
165177
};
166178

167179
// Try to parse the file as a sierra program
@@ -478,6 +490,19 @@ mod tests {
478490
assert_matches!(run(args), Ok(Some(res)) if res == expected_output, "Program {} failed with flags {}", program, extra_flags.concat());
479491
}
480492

493+
#[test]
494+
fn test_run_dynamic_params() {
495+
let mut args = vec!["cairo1-run".to_string()];
496+
args.extend_from_slice(&["--layout".to_string(), "dynamic".to_string()]);
497+
args.extend_from_slice(&[
498+
"--cairo_layout_params_file".to_string(),
499+
"../vm/src/tests/cairo_layout_params_file.json".to_string(),
500+
]);
501+
args.push("../cairo_programs/cairo-1-programs/fibonacci.cairo".to_string());
502+
503+
assert_matches!(run(args.into_iter()), Ok(_));
504+
}
505+
481506
// these tests are separated so as to run them without --append_return_values and --proof_mode options
482507
// since they require to use the squashed version of felt252
483508
#[rstest]

fuzzer/Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)