Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is_prime on sp1 #814

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ceno_host/tests/test_elf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ fn test_bubble_sorting() -> Result<()> {

let all_messages = messages_to_strings(&ceno_host::run(
CENO_PLATFORM,
ceno_examples::bubble_sorting,
ceno_examples::quadratic_sorting,
&hints,
));
for msg in &all_messages {
Expand Down
12 changes: 12 additions & 0 deletions ceno_zkvm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ serde_json.workspace = true

base64 = "0.22"
ceno_emul = { path = "../ceno_emul" }
ceno-examples = { path = "../examples-builder" }
ceno_host = { path = "../ceno_host" }

ff_ext = { path = "../ff_ext" }
mpcs = { path = "../mpcs" }
multilinear_extensions = { version = "0", path = "../multilinear_extensions" }
Expand Down Expand Up @@ -50,6 +53,7 @@ criterion.workspace = true
pprof2.workspace = true
proptest.workspace = true


[build-dependencies]
glob = "0.3"

Expand All @@ -70,3 +74,11 @@ name = "fibonacci"
[[bench]]
harness = false
name = "fibonacci_witness"

[[bench]]
harness = false
name = "quadratic_sorting"

[[bench]]
harness = false
name = "is_prime"
76 changes: 76 additions & 0 deletions ceno_zkvm/benches/is_prime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
use std::time::Duration;

use ceno_emul::{Platform, Program};
use ceno_host::CenoStdin;
use ceno_zkvm::{
self,
e2e::{Checkpoint, Preset, run_e2e_with_checkpoint, setup_platform},
};
use criterion::*;

use goldilocks::GoldilocksExt2;
use mpcs::BasefoldDefault;

criterion_group! {
name = is_prime;
config = Criterion::default().warm_up_time(Duration::from_millis(5000));
targets = is_prime_1
}

criterion_main!(is_prime);

const NUM_SAMPLES: usize = 10;
type Pcs = BasefoldDefault<E>;
type E = GoldilocksExt2;

// Relevant init data for fibonacci run
fn setup() -> (Program, Platform) {
let stack_size = 32768;
let heap_size = 2097152;
let pub_io_size = 16;
let program = Program::load_elf(ceno_examples::is_prime, u32::MAX).unwrap();
let platform = setup_platform(Preset::Ceno, &program, stack_size, heap_size, pub_io_size);
(program, platform)
}

fn is_prime_1(c: &mut Criterion) {
let (program, platform) = setup();

for n in [100u32, 10000u32, 50000u32] {
let max_steps = usize::MAX;
let mut hints = CenoStdin::default();
_ = hints.write(&n);
let hints: Vec<u32> = (&hints).into();

let mut group = c.benchmark_group(format!("is_prime_{}", max_steps));
group.sample_size(NUM_SAMPLES);

// Benchmark the proving time
group.bench_function(
BenchmarkId::new("is_prime", format!("is_prime_n={}", n)),
|b| {
b.iter_custom(|iters| {
let mut time = Duration::new(0, 0);

for _ in 0..iters {
let (_, prove) = run_e2e_with_checkpoint::<E, Pcs>(
program.clone(),
platform.clone(),
hints.clone(),
max_steps,
Checkpoint::PrepE2EProving,
);
let instant = std::time::Instant::now();
prove();
time += instant.elapsed();
}
time
});
},
);

group.finish();
}

type E = GoldilocksExt2;
}
78 changes: 78 additions & 0 deletions ceno_zkvm/benches/quadratic_sorting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use std::time::Duration;

use ceno_emul::{Platform, Program};
use ceno_host::CenoStdin;
use ceno_zkvm::{
self,
e2e::{Checkpoint, Preset, run_e2e_with_checkpoint, setup_platform},
};
use criterion::*;

use goldilocks::GoldilocksExt2;
use mpcs::BasefoldDefault;

criterion_group! {
name = quadratic_sorting;
config = Criterion::default().warm_up_time(Duration::from_millis(5000));
targets = quadratic_sorting_1
}

criterion_main!(quadratic_sorting);

const NUM_SAMPLES: usize = 10;
type Pcs = BasefoldDefault<E>;
type E = GoldilocksExt2;

// Relevant init data for fibonacci run
fn setup() -> (Program, Platform) {
let stack_size = 32768;
let heap_size = 2097152;
let pub_io_size = 16;

let program = Program::load_elf(ceno_examples::quadratic_sorting, u32::MAX).unwrap();
let platform = setup_platform(Preset::Ceno, &program, stack_size, heap_size, pub_io_size);
(program, platform)
}

fn quadratic_sorting_1(c: &mut Criterion) {
let (program, platform) = setup();
use rand::{Rng, SeedableRng};
let mut rng = rand::rngs::StdRng::seed_from_u64(42);

for n in [100, 500] {
let max_steps = usize::MAX;
let mut hints = CenoStdin::default();
_ = hints.write(&(0..n).map(|_| rng.gen::<u32>()).collect::<Vec<_>>());
let hints: Vec<u32> = (&hints).into();

let mut group = c.benchmark_group(format!("quadratic_sorting"));
group.sample_size(NUM_SAMPLES);

// Benchmark the proving time
group.bench_function(
BenchmarkId::new("quadratic_sorting", format!("n = {}", n)),
|b| {
b.iter_custom(|iters| {
let mut time = Duration::new(0, 0);
for _ in 0..iters {
let (_, prove) = run_e2e_with_checkpoint::<E, Pcs>(
program.clone(),
platform.clone(),
hints.clone(),
max_steps,
Checkpoint::PrepE2EProving,
);
let instant = std::time::Instant::now();
prove();
time += instant.elapsed();
}
time
});
},
);

group.finish();
}

type E = GoldilocksExt2;
}
12 changes: 10 additions & 2 deletions ceno_zkvm/src/bin/e2e.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use ceno_emul::{IterAddresses, Program, WORD_SIZE, Word};
use ceno_host::CenoStdin;
use ceno_zkvm::{
e2e::{Checkpoint, Preset, run_e2e_with_checkpoint, setup_platform},
with_panic_hook,
Expand Down Expand Up @@ -44,6 +45,9 @@ struct Args {
#[arg(long)]
hints: Option<String>,

#[arg(long, default_value = "100")]
n: u32,

/// Stack size in bytes.
#[arg(long, default_value = "32768")]
stack_size: u32,
Expand Down Expand Up @@ -97,7 +101,8 @@ fn main() {
.init();

tracing::info!("Loading ELF file: {}", &args.elf);
let elf_bytes = fs::read(&args.elf).expect("read elf file");
// let elf_bytes = fs::read(&args.elf).expect("read elf file");
let elf_bytes = ceno_examples::is_prime;
let program = Program::load_elf(&elf_bytes, u32::MAX).unwrap();
let platform = setup_platform(
args.platform,
Expand All @@ -114,7 +119,10 @@ fn main() {
);

tracing::info!("Loading hints file: {:?}", args.hints);
let hints = memory_from_file(&args.hints);
// let hints = memory_from_file(&args.hints);
let mut hints = CenoStdin::default();
_ = hints.write(&args.n);
let hints: Vec<u32> = (&hints).into();
assert!(
hints.len() <= platform.hints.iter_addresses().len(),
"hints must fit in {} bytes",
Expand Down
4 changes: 2 additions & 2 deletions ceno_zkvm/src/e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ fn emulate_program(
}
})
.collect_vec();
debug_memory_ranges(&vm, &mem_final);
// debug_memory_ranges(&vm, &mem_final);

// Find the final public IO cycles.
let io_final = io_init
Expand Down Expand Up @@ -443,7 +443,7 @@ pub fn run_e2e_with_checkpoint<

// Emulate program
let emul_result = emulate_program(program.clone(), max_steps, init_full_mem, &platform, hints);

println!("Cycles: {:?}", emul_result.all_records.len());
// Clone some emul_result fields before consuming
let pi = emul_result.pi.clone();
let exit_code = emul_result.exit_code;
Expand Down
3 changes: 2 additions & 1 deletion examples-builder/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ const EXAMPLES: &[&str] = &[
"hints",
"sorting",
"median",
"bubble_sorting",
"quadratic_sorting",
"hashing",
"is_prime",
];
const CARGO_MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");

Expand Down
32 changes: 32 additions & 0 deletions examples/examples/is_prime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
extern crate ceno_rt;
use ceno_rt::println;
use core::fmt::Write;
use rkyv::Archived;

fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
let mut i = 2;
while i * i <= n {
if n % i == 0 {
return false;
}
i += 1;
}

return true;
}

fn main() {
let n: &Archived<u32> = ceno_rt::read();
let mut cnt_primes = 0;

for i in 0..=n.into() {
cnt_primes += is_prime(i) as u32;
}

if cnt_primes > 1000 * 1000 {
panic!();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ fn main() {
let mut scratch = input.to_vec();
sort(&mut scratch);
// Print any output you feel like, eg the first element of the sorted vector:
println!("{}", scratch[0]);
// println!("{}", scratch[0]);
}
5 changes: 5 additions & 0 deletions is_prime/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# 'mock' for generating mock proofs locally, 'local' for generating proofs locally, 'network' for generating proofs using the proving network.
SP1_PROVER=local
# If using the proving network, set to your whitelisted private key. For more information, see:
# https://docs.succinct.xyz/prover-network/setup.html#key-setup
SP1_PRIVATE_KEY=
40 changes: 40 additions & 0 deletions is_prime/.github/workflows/foundry-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Foundry Test

on:
workflow_dispatch:
push:
branches: [ main ]
pull_request:

env:
FOUNDRY_PROFILE: ci

jobs:
check:
strategy:
fail-fast: true

name: Foundry project
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive

- name: Install Foundry
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly

- name: Run Forge build
run: |
cd contracts
forge --version
forge build --sizes
id: build

- name: Run Forge tests
run: |
cd contracts
forge test -vvv
id: test
39 changes: 39 additions & 0 deletions is_prime/.github/workflows/prove.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Build Program

on:
workflow_dispatch:
push:
branches: [main]
pull_request:

env:
FOUNDRY_PROFILE: ci

jobs:
check:
strategy:
fail-fast: true

name: Build
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v4
with:
submodules: recursive

- name: Install rust toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: 1.81.0

- name: Install SP1 toolchain
run: |
curl -L https://sp1.succinct.xyz | bash
~/.sp1/bin/sp1up
~/.sp1/bin/cargo-prove prove --version

- name: Build SP1 program
run: |
cd program
~/.sp1/bin/cargo-prove prove build
Loading
Loading