openvm_rv32im_circuit/branch_lt/
cuda.rs

1use std::{mem::size_of, sync::Arc};
2
3use derive_new::new;
4use openvm_circuit::{arch::DenseRecordArena, utils::next_power_of_two_or_zero};
5use openvm_circuit_primitives::{
6    bitwise_op_lookup::BitwiseOperationLookupChipGPU, var_range::VariableRangeCheckerChipGPU, Chip,
7};
8use openvm_cuda_backend::{base::DeviceMatrix, prelude::F, GpuBackend};
9use openvm_cuda_common::copy::MemCopyH2D;
10use openvm_stark_backend::prover::AirProvingContext;
11
12use crate::{
13    adapters::{
14        Rv32BranchAdapterCols, Rv32BranchAdapterRecord, RV32_CELL_BITS, RV32_REGISTER_NUM_LIMBS,
15    },
16    cuda_abi::branch_lt_cuda::tracegen,
17    BranchLessThanCoreCols, BranchLessThanCoreRecord,
18};
19
20#[derive(new)]
21pub struct Rv32BranchLessThanChipGpu {
22    pub range_checker: Arc<VariableRangeCheckerChipGPU>,
23    pub bitwise_lookup: Arc<BitwiseOperationLookupChipGPU<RV32_CELL_BITS>>,
24    pub timestamp_max_bits: usize,
25}
26
27impl Chip<DenseRecordArena, GpuBackend> for Rv32BranchLessThanChipGpu {
28    fn generate_proving_ctx(&self, arena: DenseRecordArena) -> AirProvingContext<GpuBackend> {
29        const RECORD_SIZE: usize = size_of::<(
30            Rv32BranchAdapterRecord,
31            BranchLessThanCoreRecord<RV32_REGISTER_NUM_LIMBS, RV32_CELL_BITS>,
32        )>();
33        let records = arena.allocated();
34        if records.is_empty() {
35            return AirProvingContext::simple_no_pis(DeviceMatrix::dummy());
36        }
37        debug_assert_eq!(records.len() % RECORD_SIZE, 0);
38
39        let trace_width =
40            BranchLessThanCoreCols::<F, RV32_REGISTER_NUM_LIMBS, RV32_CELL_BITS>::width()
41                + Rv32BranchAdapterCols::<F>::width();
42        let trace_height = next_power_of_two_or_zero(records.len() / RECORD_SIZE);
43        let device_ctx = &self.range_checker.device_ctx;
44
45        let d_records = tracing::info_span!("trace_gen.h2d_records")
46            .in_scope(|| records.to_device_on(device_ctx))
47            .unwrap();
48        let d_trace = DeviceMatrix::<F>::with_capacity_on(trace_height, trace_width, device_ctx);
49
50        unsafe {
51            tracegen(
52                d_trace.buffer(),
53                trace_height,
54                &d_records,
55                &self.range_checker.count,
56                &self.bitwise_lookup.count,
57                RV32_CELL_BITS,
58                self.timestamp_max_bits as u32,
59                device_ctx.stream.as_raw(),
60            )
61            .unwrap();
62        }
63        AirProvingContext::simple_no_pis(d_trace)
64    }
65}