Skip to main content

ab_proof_of_space_gpu/
host.rs

1#[cfg(all(test, not(miri)))]
2mod tests;
3
4use crate::shader::constants::{
5    MAX_BUCKET_SIZE, NUM_BUCKETS, NUM_MATCH_BUCKETS, NUM_S_BUCKETS, REDUCED_MATCHES_COUNT,
6    TABLE_1_SIZE,
7};
8use crate::shader::find_matches_and_compute_f7::{NUM_ELEMENTS_PER_S_BUCKET, ProofTargets};
9use crate::shader::find_proofs::ProofsHost;
10use crate::shader::types::{Metadata, Position, PositionR};
11use crate::shader::{compute_f1, find_proofs, select_shader_features_limits};
12use ab_chacha8::{ChaCha8Block, ChaCha8State, block_to_bytes};
13use ab_core_primitives::pieces::{PieceOffset, Record};
14use ab_core_primitives::pos::{PosProof, PosSeed};
15use ab_core_primitives::sectors::SectorId;
16use ab_erasure_coding::ErasureCoding;
17use ab_farmer_components::plotting::RecordsEncoder;
18use ab_farmer_components::sector::{FoundProofs, SectorContentsMap};
19use ab_proof_of_space::PosProofs;
20use async_lock::Mutex as AsyncMutex;
21use futures::stream::FuturesOrdered;
22use futures::{StreamExt, TryStreamExt};
23use parking_lot::Mutex;
24use rayon::prelude::*;
25use rayon::{ThreadPool, ThreadPoolBuilder};
26use std::num::NonZeroU8;
27use std::simd::Simd;
28use std::sync::atomic::{AtomicBool, Ordering};
29use std::{fmt, iter};
30use tracing::{debug, warn};
31use triomphe::Arc;
32use wgpu::{
33    AdapterInfo, Backend, BackendOptions, Backends, BindGroup, BindGroupDescriptor, BindGroupEntry,
34    BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingType, Buffer, BufferAddress,
35    BufferAsyncError, BufferBindingType, BufferDescriptor, BufferUsages, CommandEncoderDescriptor,
36    ComputePassDescriptor, ComputePipeline, ComputePipelineDescriptor, DeviceDescriptor,
37    DeviceType, Instance, InstanceDescriptor, InstanceFlags, MapMode, MapRangeError,
38    MemoryBudgetThresholds, PipelineCompilationOptions, PipelineLayoutDescriptor, PollError,
39    PollType, Queue, RequestDeviceError, ShaderModule, ShaderRuntimeChecks, ShaderStages,
40};
41
42/// Proof creation error
43#[derive(Debug, thiserror::Error)]
44enum RecordEncodingError {
45    /// Too many records
46    #[error("Too many records: {0}")]
47    TooManyRecords(usize),
48    /// Proof creation failed previously and the device is now considered broken
49    #[error("Proof creation failed previously and the device is now considered broken")]
50    DeviceBroken,
51    /// Failed to map buffer
52    #[error("Failed to map buffer: {0}")]
53    BufferMapping(#[from] BufferAsyncError),
54    /// Failed to get mapped buffer range
55    #[error("Failed to get mapped buffer range: {0}")]
56    MapRangeError(#[from] MapRangeError),
57    /// Poll error
58    #[error("Poll error: {0}")]
59    DevicePoll(#[from] PollError),
60}
61
62struct ProofsHostWrapper<'a> {
63    proofs: &'a ProofsHost,
64    proofs_host: &'a Buffer,
65}
66
67impl Drop for ProofsHostWrapper<'_> {
68    fn drop(&mut self) {
69        self.proofs_host.unmap();
70    }
71}
72
73/// Wrapper data structure encapsulating a single compatible device
74#[derive(Clone)]
75pub struct Device {
76    id: u32,
77    devices: Vec<(wgpu::Device, Queue, ShaderModule)>,
78    adapter_info: AdapterInfo,
79}
80
81impl fmt::Debug for Device {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.debug_struct("Device")
84            .field("id", &self.id)
85            .field("name", &self.adapter_info.name)
86            .field("device_type", &self.adapter_info.device_type)
87            .field("driver", &self.adapter_info.driver)
88            .field("driver_info", &self.adapter_info.driver_info)
89            .field("backend", &self.adapter_info.backend)
90            .finish_non_exhaustive()
91    }
92}
93
94impl Device {
95    /// Returns [`Device`] for each available device
96    pub async fn enumerate<NOQ>(number_of_queues: NOQ) -> Vec<Self>
97    where
98        NOQ: Fn(DeviceType) -> NonZeroU8,
99    {
100        let backends = Backends::from_env().unwrap_or(Backends::METAL | Backends::VULKAN);
101        let instance = Instance::new(InstanceDescriptor {
102            backends,
103            flags: if cfg!(debug_assertions) {
104                InstanceFlags::debugging().with_env()
105            } else {
106                InstanceFlags::from_env_or_default()
107            },
108            memory_budget_thresholds: MemoryBudgetThresholds::default(),
109            backend_options: BackendOptions::from_env_or_default(),
110            display: None,
111        });
112
113        let adapters = instance.enumerate_adapters(backends).await;
114        let number_of_queues = &number_of_queues;
115
116        adapters
117            .into_iter()
118            .zip(0..)
119            .map(|(adapter, id)| async move {
120                let adapter_info = adapter.get_info();
121
122                let (shader, required_features, required_limits) =
123                    if let Some((shader, required_features, required_limits)) =
124                        select_shader_features_limits(&adapter)
125                    {
126                        debug!(
127                            %id,
128                            adapter_info = ?adapter_info,
129                            "Compatible adapter found"
130                        );
131
132                        (shader, required_features, required_limits)
133                    } else {
134                        debug!(
135                            %id,
136                            adapter_info = ?adapter_info,
137                            "Incompatible adapter found"
138                        );
139
140                        return None;
141                    };
142
143                // TODO: creation of multiple devices is a workaround for lack of support for
144                //  multiple queues: https://github.com/gfx-rs/wgpu/issues/1066
145                let devices = iter::repeat_with(|| async {
146                    let (device, queue) = adapter
147                        .request_device(&DeviceDescriptor {
148                            label: None,
149                            required_features,
150                            required_limits: required_limits.clone(),
151                            ..DeviceDescriptor::default()
152                        })
153                        .await
154                        .inspect_err(|error| {
155                            warn!(%id, ?adapter_info, %error, "Failed to request the device");
156                        })?;
157                    let module = if cfg!(debug_assertions) {
158                        device.create_shader_module(shader.clone())
159                    } else {
160                        // SAFETY: The shader is trusted, individual tests include correctness
161                        // checks and debug builds of this crate too only release version skips
162                        // checks for better runtime performance
163                        unsafe {
164                            device.create_shader_module_trusted(
165                                shader.clone(),
166                                ShaderRuntimeChecks::unchecked(),
167                            )
168                        }
169                    };
170
171                    Ok::<_, RequestDeviceError>((device, queue, module))
172                })
173                .take(usize::from(
174                    number_of_queues(adapter_info.device_type).get(),
175                ))
176                .collect::<FuturesOrdered<_>>()
177                .try_collect::<Vec<_>>()
178                .await
179                .ok()?;
180
181                Some(Self {
182                    id,
183                    devices,
184                    adapter_info,
185                })
186            })
187            .collect::<FuturesOrdered<_>>()
188            .filter_map(|device| async move { device })
189            .collect()
190            .await
191    }
192
193    /// Gpu ID
194    pub fn id(&self) -> u32 {
195        self.id
196    }
197
198    /// Device name
199    pub fn name(&self) -> &str {
200        &self.adapter_info.name
201    }
202
203    /// Device type
204    pub fn device_type(&self) -> DeviceType {
205        self.adapter_info.device_type
206    }
207
208    /// Driver
209    pub fn driver(&self) -> &str {
210        &self.adapter_info.driver
211    }
212
213    /// Driver info
214    pub fn driver_info(&self) -> &str {
215        &self.adapter_info.driver_info
216    }
217
218    /// Backend
219    pub fn backend(&self) -> Backend {
220        self.adapter_info.backend
221    }
222
223    pub fn instantiate(
224        &self,
225        erasure_coding: ErasureCoding,
226        global_mutex: Arc<AsyncMutex<()>>,
227    ) -> anyhow::Result<GpuRecordsEncoder> {
228        GpuRecordsEncoder::new(
229            self.id,
230            self.devices.clone(),
231            self.adapter_info.clone(),
232            erasure_coding,
233            global_mutex,
234        )
235    }
236}
237
238pub struct GpuRecordsEncoder {
239    id: u32,
240    /// Encoder instances with a buffer for parity chunks of the record they are encoding, which is
241    /// allocated just once since every record overwrites all parity chunks
242    instances: Vec<Mutex<(GpuRecordsEncoderInstance, Box<Record>)>>,
243    thread_pool: ThreadPool,
244    adapter_info: AdapterInfo,
245    erasure_coding: ErasureCoding,
246    global_mutex: Arc<AsyncMutex<()>>,
247}
248
249impl fmt::Debug for GpuRecordsEncoder {
250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251        f.debug_struct("GpuRecordsEncoder")
252            .field("id", &self.id)
253            .field("name", &self.adapter_info.name)
254            .field("device_type", &self.adapter_info.device_type)
255            .field("driver", &self.adapter_info.driver)
256            .field("driver_info", &self.adapter_info.driver_info)
257            .field("backend", &self.adapter_info.backend)
258            .finish_non_exhaustive()
259    }
260}
261
262impl RecordsEncoder for GpuRecordsEncoder {
263    // TODO: Run more than one encoding per device concurrently
264    fn encode_records(
265        &mut self,
266        sector_id: &SectorId,
267        records: &mut [Record],
268        abort_early: &AtomicBool,
269    ) -> anyhow::Result<SectorContentsMap> {
270        let mut sector_contents_map = SectorContentsMap::new(
271            u16::try_from(records.len())
272                .map_err(|_error| RecordEncodingError::TooManyRecords(records.len()))?,
273        );
274
275        let maybe_error = self.thread_pool.install(|| {
276            records
277                .par_iter_mut()
278                .zip(sector_contents_map.iter_record_chunks_used_mut())
279                .enumerate()
280                .find_map_any(|(piece_offset, (record, record_chunks_used))| {
281                    // Take mutex briefly to make sure encoding is allowed right now
282                    self.global_mutex.lock_blocking();
283
284                    let thread_index = rayon::current_thread_index().unwrap_or_default();
285                    let mut instance = self.instances[thread_index]
286                        .try_lock()
287                        .expect("1:1 mapping between threads and devices; qed");
288                    let (encoder_instance, parity_record_chunks) = &mut *instance;
289
290                    // TODO: Do erasure coding on the GPU
291                    // Erasure code source record chunks
292                    self.erasure_coding
293                        .extend(record, parity_record_chunks)
294                        .expect("Statically guaranteed valid inputs; qed");
295
296                    if abort_early.load(Ordering::Relaxed) {
297                        return None;
298                    }
299                    let seed =
300                        sector_id.derive_evaluation_seed(PieceOffset::from(piece_offset as u16));
301                    let proofs = match encoder_instance.create_proofs(&seed) {
302                        Ok(proofs) => proofs,
303                        Err(error) => {
304                            return Some(error);
305                        }
306                    };
307                    let proofs = proofs.proofs;
308
309                    encode_record(
310                        record,
311                        parity_record_chunks,
312                        &proofs.found_proofs,
313                        &proofs.proofs,
314                        record_chunks_used,
315                    );
316
317                    None
318                })
319        });
320
321        if let Some(error) = maybe_error {
322            return Err(error.into());
323        }
324
325        Ok(sector_contents_map)
326    }
327}
328
329/// Encode record chunks with proofs created on the GPU and store which s-buckets were used.
330///
331/// The GPU creates proofs for all s-buckets that have them, the first [`Record::NUM_CHUNKS`] are
332/// used. Very rarely there are fewer, then the first s-buckets without a proof are used with
333/// [`PosProofs::PLACEHOLDER_PROOF`] instead, the same way as on CPU.
334// TODO: Record encoding on the GPU
335fn encode_record(
336    record: &mut Record,
337    parity_record_chunks: &Record,
338    found_proofs: &FoundProofs,
339    proofs: &[PosProof; NUM_S_BUCKETS],
340    record_chunks_used: &mut FoundProofs,
341) {
342    let num_found_proofs = found_proofs
343        .iter()
344        .map(|&found_proofs| found_proofs.count_ones() as usize)
345        .sum::<usize>();
346    let mut num_placeholder_proofs = Record::NUM_CHUNKS.saturating_sub(num_found_proofs);
347
348    *record_chunks_used = *found_proofs;
349
350    let mut num_used_proofs = 0_usize;
351    for (s_buckets, record_chunks_used) in (0..Record::NUM_S_BUCKETS)
352        .array_chunks::<{ u8::BITS as usize }>()
353        .zip(record_chunks_used)
354    {
355        for (proof_offset, s_bucket) in s_buckets.into_iter().enumerate() {
356            if num_used_proofs == Record::NUM_CHUNKS {
357                // Enough proofs collected, clear the rest of the bits
358                *record_chunks_used &= u8::MAX.unbounded_shr(u8::BITS - proof_offset as u32);
359                break;
360            }
361
362            let proof_hash = if (*record_chunks_used & (1 << proof_offset)) != 0 {
363                proofs[s_bucket].hash()
364            } else if let Some(remaining) = num_placeholder_proofs.checked_sub(1) {
365                num_placeholder_proofs = remaining;
366                *record_chunks_used |= 1 << proof_offset;
367                PosProof::from(PosProofs::PLACEHOLDER_PROOF).hash()
368            } else {
369                continue;
370            };
371
372            let record_chunk = if s_bucket < Record::NUM_CHUNKS {
373                record[s_bucket]
374            } else {
375                parity_record_chunks[s_bucket - Record::NUM_CHUNKS]
376            };
377
378            record[num_used_proofs] =
379                (Simd::from(record_chunk) ^ Simd::from(*proof_hash)).to_array();
380            num_used_proofs += 1;
381        }
382    }
383}
384
385impl GpuRecordsEncoder {
386    fn new(
387        id: u32,
388        devices: Vec<(wgpu::Device, Queue, ShaderModule)>,
389        adapter_info: AdapterInfo,
390        erasure_coding: ErasureCoding,
391        global_mutex: Arc<AsyncMutex<()>>,
392    ) -> anyhow::Result<Self> {
393        let thread_pool = ThreadPoolBuilder::new()
394            .thread_name(move |thread_index| format!("pos-gpu-{id}.{thread_index}"))
395            .num_threads(devices.len())
396            .build()?;
397
398        Ok(Self {
399            id,
400            instances: devices
401                .into_iter()
402                .map(|(device, queue, module)| {
403                    Mutex::new((
404                        GpuRecordsEncoderInstance::new(device, queue, module),
405                        Record::new_boxed(),
406                    ))
407                })
408                .collect(),
409            thread_pool,
410            adapter_info,
411            erasure_coding,
412            global_mutex,
413        })
414    }
415}
416
417struct GpuRecordsEncoderInstance {
418    device: wgpu::Device,
419    queue: Queue,
420    mapping_error: Arc<Mutex<Option<BufferAsyncError>>>,
421    tainted: bool,
422    initial_state_host: Buffer,
423    initial_state_gpu: Buffer,
424    proofs_host: Buffer,
425    proofs_gpu: Buffer,
426    bind_group_compute_f1: BindGroup,
427    compute_pipeline_compute_f1: ComputePipeline,
428    bind_group_sort_buckets_a: BindGroup,
429    compute_pipeline_sort_buckets_a: ComputePipeline,
430    bind_group_sort_buckets_b: BindGroup,
431    compute_pipeline_sort_buckets_b: ComputePipeline,
432    bind_group_find_matches_and_compute_f2: BindGroup,
433    compute_pipeline_find_matches_and_compute_f2: ComputePipeline,
434    bind_group_find_matches_and_compute_f3: BindGroup,
435    compute_pipeline_find_matches_and_compute_f3: ComputePipeline,
436    bind_group_find_matches_and_compute_f4: BindGroup,
437    compute_pipeline_find_matches_and_compute_f4: ComputePipeline,
438    bind_group_find_matches_and_compute_f5: BindGroup,
439    compute_pipeline_find_matches_and_compute_f5: ComputePipeline,
440    bind_group_find_matches_and_compute_f6: BindGroup,
441    compute_pipeline_find_matches_and_compute_f6: ComputePipeline,
442    bind_group_find_matches_and_compute_f7: BindGroup,
443    compute_pipeline_find_matches_and_compute_f7: ComputePipeline,
444    bind_group_find_proofs: BindGroup,
445    compute_pipeline_find_proofs: ComputePipeline,
446}
447
448impl GpuRecordsEncoderInstance {
449    fn new(device: wgpu::Device, queue: Queue, module: ShaderModule) -> Self {
450        let initial_state_host = device.create_buffer(&BufferDescriptor {
451            label: Some("initial_state_host"),
452            size: size_of::<ChaCha8Block>() as BufferAddress,
453            usage: BufferUsages::MAP_WRITE | BufferUsages::COPY_SRC,
454            mapped_at_creation: true,
455        });
456
457        let initial_state_gpu = device.create_buffer(&BufferDescriptor {
458            label: Some("initial_state_gpu"),
459            size: initial_state_host.size(),
460            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
461            mapped_at_creation: false,
462        });
463
464        let bucket_sizes_gpu_buffer_size = size_of::<[u32; NUM_BUCKETS]>() as BufferAddress;
465        let table_6_proof_targets_sizes_gpu_buffer_size =
466            size_of::<[u32; NUM_S_BUCKETS]>() as BufferAddress;
467        // TODO: Sizes are excessive, for `bucket_sizes_gpu` are less than `u16` and could use SWAR
468        //  approach for storing bucket sizes. Similarly, `table_6_proof_targets_sizes_gpu` sizes
469        //  are less than `u8` and could use SWAR too with even higher compression ratio
470        let bucket_sizes_gpu = device.create_buffer(&BufferDescriptor {
471            label: Some("bucket_sizes_gpu"),
472            size: bucket_sizes_gpu_buffer_size.max(table_6_proof_targets_sizes_gpu_buffer_size),
473            usage: BufferUsages::STORAGE,
474            mapped_at_creation: false,
475        });
476        // Reuse the same buffer as `bucket_sizes_gpu`, they are not overlapping in use
477        let table_6_proof_targets_sizes_gpu = bucket_sizes_gpu.clone();
478
479        let buckets_a_gpu = device.create_buffer(&BufferDescriptor {
480            label: Some("buckets_a_gpu"),
481            size: size_of::<[[PositionR; MAX_BUCKET_SIZE]; NUM_BUCKETS]>() as BufferAddress,
482            usage: BufferUsages::STORAGE,
483            mapped_at_creation: false,
484        });
485
486        let buckets_b_gpu = device.create_buffer(&BufferDescriptor {
487            label: Some("buckets_b_gpu"),
488            size: buckets_a_gpu.size(),
489            usage: BufferUsages::STORAGE,
490            mapped_at_creation: false,
491        });
492
493        let positions_f2_gpu = device.create_buffer(&BufferDescriptor {
494            label: Some("positions_f2_gpu"),
495            size: size_of::<[[[Position; 2]; REDUCED_MATCHES_COUNT]; NUM_MATCH_BUCKETS]>()
496                as BufferAddress,
497            usage: BufferUsages::STORAGE,
498            mapped_at_creation: false,
499        });
500
501        let positions_f3_gpu = device.create_buffer(&BufferDescriptor {
502            label: Some("positions_f3_gpu"),
503            size: positions_f2_gpu.size(),
504            usage: BufferUsages::STORAGE,
505            mapped_at_creation: false,
506        });
507
508        let positions_f4_gpu = device.create_buffer(&BufferDescriptor {
509            label: Some("positions_f4_gpu"),
510            size: positions_f2_gpu.size(),
511            usage: BufferUsages::STORAGE,
512            mapped_at_creation: false,
513        });
514
515        let positions_f5_gpu = device.create_buffer(&BufferDescriptor {
516            label: Some("positions_f5_gpu"),
517            size: positions_f2_gpu.size(),
518            usage: BufferUsages::STORAGE,
519            mapped_at_creation: false,
520        });
521
522        let positions_f6_gpu = device.create_buffer(&BufferDescriptor {
523            label: Some("positions_f6_gpu"),
524            size: positions_f2_gpu.size(),
525            usage: BufferUsages::STORAGE,
526            mapped_at_creation: false,
527        });
528
529        let metadatas_gpu_buffer_size =
530            size_of::<[[Metadata; REDUCED_MATCHES_COUNT]; NUM_MATCH_BUCKETS]>() as BufferAddress;
531        let table_6_proof_targets_gpu_buffer_size = size_of::<
532            [[ProofTargets; NUM_ELEMENTS_PER_S_BUCKET]; NUM_S_BUCKETS],
533        >() as BufferAddress;
534        let metadatas_a_gpu = device.create_buffer(&BufferDescriptor {
535            label: Some("metadatas_a_gpu"),
536            size: metadatas_gpu_buffer_size.max(table_6_proof_targets_gpu_buffer_size),
537            usage: BufferUsages::STORAGE,
538            mapped_at_creation: false,
539        });
540        // Reuse the same buffer as `metadatas_a_gpu`, they are not overlapping in use
541        let table_6_proof_targets_gpu = metadatas_a_gpu.clone();
542
543        let metadatas_b_gpu = device.create_buffer(&BufferDescriptor {
544            label: Some("metadatas_b_gpu"),
545            size: metadatas_gpu_buffer_size,
546            usage: BufferUsages::STORAGE,
547            mapped_at_creation: false,
548        });
549
550        let proofs_host = device.create_buffer(&BufferDescriptor {
551            label: Some("proofs_host"),
552            size: size_of::<ProofsHost>() as BufferAddress,
553            usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST,
554            mapped_at_creation: false,
555        });
556
557        let proofs_gpu = device.create_buffer(&BufferDescriptor {
558            label: Some("proofs_gpu"),
559            size: proofs_host.size(),
560            usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
561            mapped_at_creation: false,
562        });
563
564        let (bind_group_compute_f1, compute_pipeline_compute_f1) =
565            bind_group_and_pipeline_compute_f1(
566                &device,
567                &module,
568                &initial_state_gpu,
569                &bucket_sizes_gpu,
570                &buckets_a_gpu,
571            );
572        let (bind_group_sort_buckets_a, compute_pipeline_sort_buckets_a) =
573            bind_group_and_pipeline_sort_buckets(
574                &device,
575                &module,
576                &bucket_sizes_gpu,
577                &buckets_a_gpu,
578            );
579
580        let (bind_group_sort_buckets_b, compute_pipeline_sort_buckets_b) =
581            bind_group_and_pipeline_sort_buckets(
582                &device,
583                &module,
584                &bucket_sizes_gpu,
585                &buckets_b_gpu,
586            );
587
588        let (bind_group_find_matches_and_compute_f2, compute_pipeline_find_matches_and_compute_f2) =
589            bind_group_and_pipeline_find_matches_and_compute_f2(
590                &device,
591                &module,
592                &buckets_a_gpu,
593                &bucket_sizes_gpu,
594                &buckets_b_gpu,
595                &positions_f2_gpu,
596                &metadatas_b_gpu,
597            );
598
599        let (bind_group_find_matches_and_compute_f3, compute_pipeline_find_matches_and_compute_f3) =
600            bind_group_and_pipeline_find_matches_and_compute_fn::<3>(
601                &device,
602                &module,
603                &buckets_b_gpu,
604                &metadatas_b_gpu,
605                &bucket_sizes_gpu,
606                &buckets_a_gpu,
607                &positions_f3_gpu,
608                &metadatas_a_gpu,
609            );
610
611        let (bind_group_find_matches_and_compute_f4, compute_pipeline_find_matches_and_compute_f4) =
612            bind_group_and_pipeline_find_matches_and_compute_fn::<4>(
613                &device,
614                &module,
615                &buckets_a_gpu,
616                &metadatas_a_gpu,
617                &bucket_sizes_gpu,
618                &buckets_b_gpu,
619                &positions_f4_gpu,
620                &metadatas_b_gpu,
621            );
622
623        let (bind_group_find_matches_and_compute_f5, compute_pipeline_find_matches_and_compute_f5) =
624            bind_group_and_pipeline_find_matches_and_compute_fn::<5>(
625                &device,
626                &module,
627                &buckets_b_gpu,
628                &metadatas_b_gpu,
629                &bucket_sizes_gpu,
630                &buckets_a_gpu,
631                &positions_f5_gpu,
632                &metadatas_a_gpu,
633            );
634
635        let (bind_group_find_matches_and_compute_f6, compute_pipeline_find_matches_and_compute_f6) =
636            bind_group_and_pipeline_find_matches_and_compute_fn::<6>(
637                &device,
638                &module,
639                &buckets_a_gpu,
640                &metadatas_a_gpu,
641                &bucket_sizes_gpu,
642                &buckets_b_gpu,
643                &positions_f6_gpu,
644                &metadatas_b_gpu,
645            );
646
647        let (bind_group_find_matches_and_compute_f7, compute_pipeline_find_matches_and_compute_f7) =
648            bind_group_and_pipeline_find_matches_and_compute_f7(
649                &device,
650                &module,
651                &buckets_b_gpu,
652                &metadatas_b_gpu,
653                &table_6_proof_targets_sizes_gpu,
654                &table_6_proof_targets_gpu,
655            );
656
657        let (bind_group_find_proofs, compute_pipeline_find_proofs) =
658            bind_group_and_pipeline_find_proofs(
659                &device,
660                &module,
661                &positions_f2_gpu,
662                &positions_f3_gpu,
663                &positions_f4_gpu,
664                &positions_f5_gpu,
665                &positions_f6_gpu,
666                &table_6_proof_targets_sizes_gpu,
667                &table_6_proof_targets_gpu,
668                &proofs_gpu,
669            );
670
671        Self {
672            device,
673            queue,
674            mapping_error: Arc::new(Mutex::new(None)),
675            tainted: false,
676            initial_state_host,
677            initial_state_gpu,
678            proofs_host,
679            proofs_gpu,
680            bind_group_compute_f1,
681            compute_pipeline_compute_f1,
682            bind_group_sort_buckets_a,
683            compute_pipeline_sort_buckets_a,
684            bind_group_sort_buckets_b,
685            compute_pipeline_sort_buckets_b,
686            bind_group_find_matches_and_compute_f2,
687            compute_pipeline_find_matches_and_compute_f2,
688            bind_group_find_matches_and_compute_f3,
689            compute_pipeline_find_matches_and_compute_f3,
690            bind_group_find_matches_and_compute_f4,
691            compute_pipeline_find_matches_and_compute_f4,
692            bind_group_find_matches_and_compute_f5,
693            compute_pipeline_find_matches_and_compute_f5,
694            bind_group_find_matches_and_compute_f6,
695            compute_pipeline_find_matches_and_compute_f6,
696            bind_group_find_matches_and_compute_f7,
697            compute_pipeline_find_matches_and_compute_f7,
698            bind_group_find_proofs,
699            compute_pipeline_find_proofs,
700        }
701    }
702
703    fn create_proofs(
704        &mut self,
705        seed: &PosSeed,
706    ) -> Result<ProofsHostWrapper<'_>, RecordEncodingError> {
707        if self.tainted {
708            return Err(RecordEncodingError::DeviceBroken);
709        }
710        self.tainted = true;
711
712        let mut encoder = self
713            .device
714            .create_command_encoder(&CommandEncoderDescriptor {
715                label: Some("create_proofs"),
716            });
717
718        // Mapped initially and re-mapped at the end of the computation
719        self.initial_state_host
720            .get_mapped_range_mut(..)?
721            .copy_from_slice(&block_to_bytes(
722                &ChaCha8State::init(seed, &[0; _]).to_repr(),
723            ));
724        self.initial_state_host.unmap();
725
726        encoder.copy_buffer_to_buffer(
727            &self.initial_state_host,
728            0,
729            &self.initial_state_gpu,
730            0,
731            self.initial_state_host.size(),
732        );
733
734        {
735            let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor {
736                label: Some("create_proofs"),
737                timestamp_writes: None,
738            });
739
740            cpass.set_bind_group(0, &self.bind_group_compute_f1, &[]);
741            cpass.set_pipeline(&self.compute_pipeline_compute_f1);
742            cpass.dispatch_workgroups(
743                TABLE_1_SIZE
744                    .div_ceil(compute_f1::WORKGROUP_SIZE * compute_f1::ELEMENTS_PER_INVOCATION),
745                1,
746                1,
747            );
748
749            cpass.set_bind_group(0, &self.bind_group_sort_buckets_a, &[]);
750            cpass.set_pipeline(&self.compute_pipeline_sort_buckets_a);
751            cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1);
752
753            cpass.set_bind_group(0, &self.bind_group_find_matches_and_compute_f2, &[]);
754            cpass.set_pipeline(&self.compute_pipeline_find_matches_and_compute_f2);
755            cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1);
756
757            cpass.set_bind_group(0, &self.bind_group_sort_buckets_b, &[]);
758            cpass.set_pipeline(&self.compute_pipeline_sort_buckets_b);
759            cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1);
760
761            cpass.set_bind_group(0, &self.bind_group_find_matches_and_compute_f3, &[]);
762            cpass.set_pipeline(&self.compute_pipeline_find_matches_and_compute_f3);
763            cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1);
764
765            cpass.set_bind_group(0, &self.bind_group_sort_buckets_a, &[]);
766            cpass.set_pipeline(&self.compute_pipeline_sort_buckets_a);
767            cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1);
768
769            cpass.set_bind_group(0, &self.bind_group_find_matches_and_compute_f4, &[]);
770            cpass.set_pipeline(&self.compute_pipeline_find_matches_and_compute_f4);
771            cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1);
772
773            cpass.set_bind_group(0, &self.bind_group_sort_buckets_b, &[]);
774            cpass.set_pipeline(&self.compute_pipeline_sort_buckets_b);
775            cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1);
776
777            cpass.set_bind_group(0, &self.bind_group_find_matches_and_compute_f5, &[]);
778            cpass.set_pipeline(&self.compute_pipeline_find_matches_and_compute_f5);
779            cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1);
780
781            cpass.set_bind_group(0, &self.bind_group_sort_buckets_a, &[]);
782            cpass.set_pipeline(&self.compute_pipeline_sort_buckets_a);
783            cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1);
784
785            cpass.set_bind_group(0, &self.bind_group_find_matches_and_compute_f6, &[]);
786            cpass.set_pipeline(&self.compute_pipeline_find_matches_and_compute_f6);
787            cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1);
788
789            cpass.set_bind_group(0, &self.bind_group_sort_buckets_b, &[]);
790            cpass.set_pipeline(&self.compute_pipeline_sort_buckets_b);
791            cpass.dispatch_workgroups(NUM_BUCKETS as u32, 1, 1);
792
793            cpass.set_bind_group(0, &self.bind_group_find_matches_and_compute_f7, &[]);
794            cpass.set_pipeline(&self.compute_pipeline_find_matches_and_compute_f7);
795            cpass.dispatch_workgroups(NUM_MATCH_BUCKETS as u32, 1, 1);
796
797            cpass.set_bind_group(0, &self.bind_group_find_proofs, &[]);
798            cpass.set_pipeline(&self.compute_pipeline_find_proofs);
799            cpass.dispatch_workgroups(NUM_S_BUCKETS as u32 / find_proofs::WORKGROUP_SIZE, 1, 1);
800        }
801
802        encoder.copy_buffer_to_buffer(
803            &self.proofs_gpu,
804            0,
805            &self.proofs_host,
806            0,
807            self.proofs_host.size(),
808        );
809
810        // Map initial state for writes for the next iteration
811        encoder.map_buffer_on_submit(&self.initial_state_host, MapMode::Write, .., {
812            let mapping_error = Arc::clone(&self.mapping_error);
813
814            move |r| {
815                if let Err(error) = r {
816                    mapping_error.lock().replace(error);
817                }
818            }
819        });
820        encoder.map_buffer_on_submit(&self.proofs_host, MapMode::Read, .., {
821            let mapping_error = Arc::clone(&self.mapping_error);
822
823            move |r| {
824                if let Err(error) = r {
825                    mapping_error.lock().replace(error);
826                }
827            }
828        });
829
830        let submission_index = self.queue.submit([encoder.finish()]);
831
832        self.device.poll(PollType::Wait {
833            submission_index,
834            timeout: None,
835        })?;
836
837        if let Some(error) = self.mapping_error.lock().take() {
838            return Err(RecordEncodingError::BufferMapping(error));
839        }
840
841        let proofs = {
842            let proofs_host_ptr = self
843                .proofs_host
844                .get_mapped_range(..)?
845                .as_ptr()
846                .cast::<ProofsHost>();
847            // SAFETY: Initialized on the GPU
848            unsafe { &*proofs_host_ptr }
849        };
850
851        self.tainted = false;
852
853        Ok(ProofsHostWrapper {
854            proofs,
855            proofs_host: &self.proofs_host,
856        })
857    }
858}
859
860fn bind_group_and_pipeline_compute_f1(
861    device: &wgpu::Device,
862    module: &ShaderModule,
863    initial_state_gpu: &Buffer,
864    bucket_sizes_gpu: &Buffer,
865    buckets_gpu: &Buffer,
866) -> (BindGroup, ComputePipeline) {
867    let bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
868        label: Some("compute_f1"),
869        entries: &[
870            BindGroupLayoutEntry {
871                binding: 0,
872                count: None,
873                visibility: ShaderStages::COMPUTE,
874                ty: BindingType::Buffer {
875                    has_dynamic_offset: false,
876                    min_binding_size: None,
877                    ty: BufferBindingType::Uniform,
878                },
879            },
880            BindGroupLayoutEntry {
881                binding: 1,
882                count: None,
883                visibility: ShaderStages::COMPUTE,
884                ty: BindingType::Buffer {
885                    has_dynamic_offset: false,
886                    min_binding_size: None,
887                    ty: BufferBindingType::Storage { read_only: false },
888                },
889            },
890            BindGroupLayoutEntry {
891                binding: 2,
892                count: None,
893                visibility: ShaderStages::COMPUTE,
894                ty: BindingType::Buffer {
895                    has_dynamic_offset: false,
896                    min_binding_size: None,
897                    ty: BufferBindingType::Storage { read_only: false },
898                },
899            },
900        ],
901    });
902
903    let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
904        label: Some("compute_f1"),
905        bind_group_layouts: &[Some(&bind_group_layout)],
906        immediate_size: 0,
907    });
908
909    let compute_pipeline = device.create_compute_pipeline(&ComputePipelineDescriptor {
910        compilation_options: PipelineCompilationOptions {
911            constants: &[],
912            zero_initialize_workgroup_memory: false,
913        },
914        cache: None,
915        label: Some("compute_f1"),
916        layout: Some(&pipeline_layout),
917        module,
918        entry_point: Some("compute_f1"),
919    });
920
921    let bind_group = device.create_bind_group(&BindGroupDescriptor {
922        label: Some("compute_f1"),
923        layout: &bind_group_layout,
924        entries: &[
925            BindGroupEntry {
926                binding: 0,
927                resource: initial_state_gpu.as_entire_binding(),
928            },
929            BindGroupEntry {
930                binding: 1,
931                resource: bucket_sizes_gpu.as_entire_binding(),
932            },
933            BindGroupEntry {
934                binding: 2,
935                resource: buckets_gpu.as_entire_binding(),
936            },
937        ],
938    });
939
940    (bind_group, compute_pipeline)
941}
942
943fn bind_group_and_pipeline_sort_buckets(
944    device: &wgpu::Device,
945    module: &ShaderModule,
946    bucket_sizes_gpu: &Buffer,
947    buckets_gpu: &Buffer,
948) -> (BindGroup, ComputePipeline) {
949    let bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
950        label: Some("sort_buckets"),
951        entries: &[
952            BindGroupLayoutEntry {
953                binding: 0,
954                count: None,
955                visibility: ShaderStages::COMPUTE,
956                ty: BindingType::Buffer {
957                    has_dynamic_offset: false,
958                    min_binding_size: None,
959                    ty: BufferBindingType::Storage { read_only: false },
960                },
961            },
962            BindGroupLayoutEntry {
963                binding: 1,
964                count: None,
965                visibility: ShaderStages::COMPUTE,
966                ty: BindingType::Buffer {
967                    has_dynamic_offset: false,
968                    min_binding_size: None,
969                    ty: BufferBindingType::Storage { read_only: false },
970                },
971            },
972        ],
973    });
974
975    let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
976        label: Some("sort_buckets"),
977        bind_group_layouts: &[Some(&bind_group_layout)],
978        immediate_size: 0,
979    });
980
981    let compute_pipeline = device.create_compute_pipeline(&ComputePipelineDescriptor {
982        compilation_options: PipelineCompilationOptions {
983            constants: &[],
984            zero_initialize_workgroup_memory: false,
985        },
986        cache: None,
987        label: Some("sort_buckets"),
988        layout: Some(&pipeline_layout),
989        module,
990        entry_point: Some("sort_buckets"),
991    });
992
993    let bind_group = device.create_bind_group(&BindGroupDescriptor {
994        label: Some("sort_buckets"),
995        layout: &bind_group_layout,
996        entries: &[
997            BindGroupEntry {
998                binding: 0,
999                resource: bucket_sizes_gpu.as_entire_binding(),
1000            },
1001            BindGroupEntry {
1002                binding: 1,
1003                resource: buckets_gpu.as_entire_binding(),
1004            },
1005        ],
1006    });
1007
1008    (bind_group, compute_pipeline)
1009}
1010
1011fn bind_group_and_pipeline_find_matches_and_compute_f2(
1012    device: &wgpu::Device,
1013    module: &ShaderModule,
1014    parent_buckets_gpu: &Buffer,
1015    bucket_sizes_gpu: &Buffer,
1016    buckets_gpu: &Buffer,
1017    positions_gpu: &Buffer,
1018    metadatas_gpu: &Buffer,
1019) -> (BindGroup, ComputePipeline) {
1020    let bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
1021        label: Some("find_matches_and_compute_f2"),
1022        entries: &[
1023            BindGroupLayoutEntry {
1024                binding: 0,
1025                count: None,
1026                visibility: ShaderStages::COMPUTE,
1027                ty: BindingType::Buffer {
1028                    has_dynamic_offset: false,
1029                    min_binding_size: None,
1030                    ty: BufferBindingType::Storage { read_only: true },
1031                },
1032            },
1033            BindGroupLayoutEntry {
1034                binding: 1,
1035                count: None,
1036                visibility: ShaderStages::COMPUTE,
1037                ty: BindingType::Buffer {
1038                    has_dynamic_offset: false,
1039                    min_binding_size: None,
1040                    ty: BufferBindingType::Storage { read_only: false },
1041                },
1042            },
1043            BindGroupLayoutEntry {
1044                binding: 2,
1045                count: None,
1046                visibility: ShaderStages::COMPUTE,
1047                ty: BindingType::Buffer {
1048                    has_dynamic_offset: false,
1049                    min_binding_size: None,
1050                    ty: BufferBindingType::Storage { read_only: false },
1051                },
1052            },
1053            BindGroupLayoutEntry {
1054                binding: 3,
1055                count: None,
1056                visibility: ShaderStages::COMPUTE,
1057                ty: BindingType::Buffer {
1058                    has_dynamic_offset: false,
1059                    min_binding_size: None,
1060                    ty: BufferBindingType::Storage { read_only: false },
1061                },
1062            },
1063            BindGroupLayoutEntry {
1064                binding: 4,
1065                count: None,
1066                visibility: ShaderStages::COMPUTE,
1067                ty: BindingType::Buffer {
1068                    has_dynamic_offset: false,
1069                    min_binding_size: None,
1070                    ty: BufferBindingType::Storage { read_only: false },
1071                },
1072            },
1073        ],
1074    });
1075
1076    let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
1077        label: Some("find_matches_and_compute_f2"),
1078        bind_group_layouts: &[Some(&bind_group_layout)],
1079        immediate_size: 0,
1080    });
1081
1082    let compute_pipeline = device.create_compute_pipeline(&ComputePipelineDescriptor {
1083        compilation_options: PipelineCompilationOptions {
1084            constants: &[],
1085            zero_initialize_workgroup_memory: true,
1086        },
1087        cache: None,
1088        label: Some("find_matches_and_compute_f2"),
1089        layout: Some(&pipeline_layout),
1090        module,
1091        entry_point: Some("find_matches_and_compute_f2"),
1092    });
1093
1094    let bind_group = device.create_bind_group(&BindGroupDescriptor {
1095        label: Some("find_matches_and_compute_f2"),
1096        layout: &bind_group_layout,
1097        entries: &[
1098            BindGroupEntry {
1099                binding: 0,
1100                resource: parent_buckets_gpu.as_entire_binding(),
1101            },
1102            BindGroupEntry {
1103                binding: 1,
1104                resource: bucket_sizes_gpu.as_entire_binding(),
1105            },
1106            BindGroupEntry {
1107                binding: 2,
1108                resource: buckets_gpu.as_entire_binding(),
1109            },
1110            BindGroupEntry {
1111                binding: 3,
1112                resource: positions_gpu.as_entire_binding(),
1113            },
1114            BindGroupEntry {
1115                binding: 4,
1116                resource: metadatas_gpu.as_entire_binding(),
1117            },
1118        ],
1119    });
1120
1121    (bind_group, compute_pipeline)
1122}
1123
1124#[expect(
1125    clippy::too_many_arguments,
1126    reason = "Both I/O and Vulkan stuff together take a lot of arguments"
1127)]
1128fn bind_group_and_pipeline_find_matches_and_compute_fn<const TABLE_NUMBER: u8>(
1129    device: &wgpu::Device,
1130    module: &ShaderModule,
1131    parent_buckets_gpu: &Buffer,
1132    parent_metadatas_gpu: &Buffer,
1133    bucket_sizes_gpu: &Buffer,
1134    buckets_gpu: &Buffer,
1135    positions_gpu: &Buffer,
1136    metadatas_gpu: &Buffer,
1137) -> (BindGroup, ComputePipeline) {
1138    let label = format!("find_matches_and_compute_f{TABLE_NUMBER}");
1139    let bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
1140        label: Some(&label),
1141        entries: &[
1142            BindGroupLayoutEntry {
1143                binding: 0,
1144                count: None,
1145                visibility: ShaderStages::COMPUTE,
1146                ty: BindingType::Buffer {
1147                    has_dynamic_offset: false,
1148                    min_binding_size: None,
1149                    ty: BufferBindingType::Storage { read_only: true },
1150                },
1151            },
1152            BindGroupLayoutEntry {
1153                binding: 1,
1154                count: None,
1155                visibility: ShaderStages::COMPUTE,
1156                ty: BindingType::Buffer {
1157                    has_dynamic_offset: false,
1158                    min_binding_size: None,
1159                    ty: BufferBindingType::Storage { read_only: true },
1160                },
1161            },
1162            BindGroupLayoutEntry {
1163                binding: 2,
1164                count: None,
1165                visibility: ShaderStages::COMPUTE,
1166                ty: BindingType::Buffer {
1167                    has_dynamic_offset: false,
1168                    min_binding_size: None,
1169                    ty: BufferBindingType::Storage { read_only: false },
1170                },
1171            },
1172            BindGroupLayoutEntry {
1173                binding: 3,
1174                count: None,
1175                visibility: ShaderStages::COMPUTE,
1176                ty: BindingType::Buffer {
1177                    has_dynamic_offset: false,
1178                    min_binding_size: None,
1179                    ty: BufferBindingType::Storage { read_only: false },
1180                },
1181            },
1182            BindGroupLayoutEntry {
1183                binding: 4,
1184                count: None,
1185                visibility: ShaderStages::COMPUTE,
1186                ty: BindingType::Buffer {
1187                    has_dynamic_offset: false,
1188                    min_binding_size: None,
1189                    ty: BufferBindingType::Storage { read_only: false },
1190                },
1191            },
1192            BindGroupLayoutEntry {
1193                binding: 5,
1194                count: None,
1195                visibility: ShaderStages::COMPUTE,
1196                ty: BindingType::Buffer {
1197                    has_dynamic_offset: false,
1198                    min_binding_size: None,
1199                    ty: BufferBindingType::Storage { read_only: false },
1200                },
1201            },
1202        ],
1203    });
1204
1205    let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
1206        label: Some(&label),
1207        bind_group_layouts: &[Some(&bind_group_layout)],
1208        immediate_size: 0,
1209    });
1210
1211    let compute_pipeline = device.create_compute_pipeline(&ComputePipelineDescriptor {
1212        compilation_options: PipelineCompilationOptions {
1213            constants: &[],
1214            zero_initialize_workgroup_memory: true,
1215        },
1216        cache: None,
1217        label: Some(&label),
1218        layout: Some(&pipeline_layout),
1219        module,
1220        entry_point: Some(&format!("find_matches_and_compute_f{TABLE_NUMBER}")),
1221    });
1222
1223    let bind_group = device.create_bind_group(&BindGroupDescriptor {
1224        label: Some(&label),
1225        layout: &bind_group_layout,
1226        entries: &[
1227            BindGroupEntry {
1228                binding: 0,
1229                resource: parent_buckets_gpu.as_entire_binding(),
1230            },
1231            BindGroupEntry {
1232                binding: 1,
1233                resource: parent_metadatas_gpu.as_entire_binding(),
1234            },
1235            BindGroupEntry {
1236                binding: 2,
1237                resource: bucket_sizes_gpu.as_entire_binding(),
1238            },
1239            BindGroupEntry {
1240                binding: 3,
1241                resource: buckets_gpu.as_entire_binding(),
1242            },
1243            BindGroupEntry {
1244                binding: 4,
1245                resource: positions_gpu.as_entire_binding(),
1246            },
1247            BindGroupEntry {
1248                binding: 5,
1249                resource: metadatas_gpu.as_entire_binding(),
1250            },
1251        ],
1252    });
1253
1254    (bind_group, compute_pipeline)
1255}
1256
1257fn bind_group_and_pipeline_find_matches_and_compute_f7(
1258    device: &wgpu::Device,
1259    module: &ShaderModule,
1260    parent_buckets_gpu: &Buffer,
1261    parent_metadatas_gpu: &Buffer,
1262    table_6_proof_targets_sizes_gpu: &Buffer,
1263    table_6_proof_targets_gpu: &Buffer,
1264) -> (BindGroup, ComputePipeline) {
1265    let bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
1266        label: Some("find_matches_and_compute_f7"),
1267        entries: &[
1268            BindGroupLayoutEntry {
1269                binding: 0,
1270                count: None,
1271                visibility: ShaderStages::COMPUTE,
1272                ty: BindingType::Buffer {
1273                    has_dynamic_offset: false,
1274                    min_binding_size: None,
1275                    ty: BufferBindingType::Storage { read_only: true },
1276                },
1277            },
1278            BindGroupLayoutEntry {
1279                binding: 1,
1280                count: None,
1281                visibility: ShaderStages::COMPUTE,
1282                ty: BindingType::Buffer {
1283                    has_dynamic_offset: false,
1284                    min_binding_size: None,
1285                    ty: BufferBindingType::Storage { read_only: true },
1286                },
1287            },
1288            BindGroupLayoutEntry {
1289                binding: 2,
1290                count: None,
1291                visibility: ShaderStages::COMPUTE,
1292                ty: BindingType::Buffer {
1293                    has_dynamic_offset: false,
1294                    min_binding_size: None,
1295                    ty: BufferBindingType::Storage { read_only: false },
1296                },
1297            },
1298            BindGroupLayoutEntry {
1299                binding: 3,
1300                count: None,
1301                visibility: ShaderStages::COMPUTE,
1302                ty: BindingType::Buffer {
1303                    has_dynamic_offset: false,
1304                    min_binding_size: None,
1305                    ty: BufferBindingType::Storage { read_only: false },
1306                },
1307            },
1308        ],
1309    });
1310
1311    let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
1312        label: Some("find_matches_and_compute_f7"),
1313        bind_group_layouts: &[Some(&bind_group_layout)],
1314        immediate_size: 0,
1315    });
1316
1317    let compute_pipeline = device.create_compute_pipeline(&ComputePipelineDescriptor {
1318        compilation_options: PipelineCompilationOptions {
1319            constants: &[],
1320            zero_initialize_workgroup_memory: true,
1321        },
1322        cache: None,
1323        label: Some("find_matches_and_compute_f7"),
1324        layout: Some(&pipeline_layout),
1325        module,
1326        entry_point: Some("find_matches_and_compute_f7"),
1327    });
1328
1329    let bind_group = device.create_bind_group(&BindGroupDescriptor {
1330        label: Some("find_matches_and_compute_f7"),
1331        layout: &bind_group_layout,
1332        entries: &[
1333            BindGroupEntry {
1334                binding: 0,
1335                resource: parent_buckets_gpu.as_entire_binding(),
1336            },
1337            BindGroupEntry {
1338                binding: 1,
1339                resource: parent_metadatas_gpu.as_entire_binding(),
1340            },
1341            BindGroupEntry {
1342                binding: 2,
1343                resource: table_6_proof_targets_sizes_gpu.as_entire_binding(),
1344            },
1345            BindGroupEntry {
1346                binding: 3,
1347                resource: table_6_proof_targets_gpu.as_entire_binding(),
1348            },
1349        ],
1350    });
1351
1352    (bind_group, compute_pipeline)
1353}
1354
1355#[expect(
1356    clippy::too_many_arguments,
1357    reason = "Both I/O and Vulkan stuff together take a lot of arguments"
1358)]
1359fn bind_group_and_pipeline_find_proofs(
1360    device: &wgpu::Device,
1361    module: &ShaderModule,
1362    table_2_positions_gpu: &Buffer,
1363    table_3_positions_gpu: &Buffer,
1364    table_4_positions_gpu: &Buffer,
1365    table_5_positions_gpu: &Buffer,
1366    table_6_positions_gpu: &Buffer,
1367    bucket_sizes_gpu: &Buffer,
1368    buckets_gpu: &Buffer,
1369    proofs_gpu: &Buffer,
1370) -> (BindGroup, ComputePipeline) {
1371    let bind_group_layout = device.create_bind_group_layout(&BindGroupLayoutDescriptor {
1372        label: Some("find_proofs"),
1373        entries: &[
1374            BindGroupLayoutEntry {
1375                binding: 0,
1376                count: None,
1377                visibility: ShaderStages::COMPUTE,
1378                ty: BindingType::Buffer {
1379                    has_dynamic_offset: false,
1380                    min_binding_size: None,
1381                    ty: BufferBindingType::Storage { read_only: true },
1382                },
1383            },
1384            BindGroupLayoutEntry {
1385                binding: 1,
1386                count: None,
1387                visibility: ShaderStages::COMPUTE,
1388                ty: BindingType::Buffer {
1389                    has_dynamic_offset: false,
1390                    min_binding_size: None,
1391                    ty: BufferBindingType::Storage { read_only: true },
1392                },
1393            },
1394            BindGroupLayoutEntry {
1395                binding: 2,
1396                count: None,
1397                visibility: ShaderStages::COMPUTE,
1398                ty: BindingType::Buffer {
1399                    has_dynamic_offset: false,
1400                    min_binding_size: None,
1401                    ty: BufferBindingType::Storage { read_only: true },
1402                },
1403            },
1404            BindGroupLayoutEntry {
1405                binding: 3,
1406                count: None,
1407                visibility: ShaderStages::COMPUTE,
1408                ty: BindingType::Buffer {
1409                    has_dynamic_offset: false,
1410                    min_binding_size: None,
1411                    ty: BufferBindingType::Storage { read_only: true },
1412                },
1413            },
1414            BindGroupLayoutEntry {
1415                binding: 4,
1416                count: None,
1417                visibility: ShaderStages::COMPUTE,
1418                ty: BindingType::Buffer {
1419                    has_dynamic_offset: false,
1420                    min_binding_size: None,
1421                    ty: BufferBindingType::Storage { read_only: true },
1422                },
1423            },
1424            BindGroupLayoutEntry {
1425                binding: 5,
1426                count: None,
1427                visibility: ShaderStages::COMPUTE,
1428                ty: BindingType::Buffer {
1429                    has_dynamic_offset: false,
1430                    min_binding_size: None,
1431                    ty: BufferBindingType::Storage { read_only: false },
1432                },
1433            },
1434            BindGroupLayoutEntry {
1435                binding: 6,
1436                count: None,
1437                visibility: ShaderStages::COMPUTE,
1438                ty: BindingType::Buffer {
1439                    has_dynamic_offset: false,
1440                    min_binding_size: None,
1441                    ty: BufferBindingType::Storage { read_only: true },
1442                },
1443            },
1444            BindGroupLayoutEntry {
1445                binding: 7,
1446                count: None,
1447                visibility: ShaderStages::COMPUTE,
1448                ty: BindingType::Buffer {
1449                    has_dynamic_offset: false,
1450                    min_binding_size: None,
1451                    ty: BufferBindingType::Storage { read_only: false },
1452                },
1453            },
1454        ],
1455    });
1456
1457    let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
1458        label: Some("find_proofs"),
1459        bind_group_layouts: &[Some(&bind_group_layout)],
1460        immediate_size: 0,
1461    });
1462
1463    let compute_pipeline = device.create_compute_pipeline(&ComputePipelineDescriptor {
1464        compilation_options: PipelineCompilationOptions {
1465            constants: &[],
1466            zero_initialize_workgroup_memory: false,
1467        },
1468        cache: None,
1469        label: Some("find_proofs"),
1470        layout: Some(&pipeline_layout),
1471        module,
1472        entry_point: Some("find_proofs"),
1473    });
1474
1475    let bind_group = device.create_bind_group(&BindGroupDescriptor {
1476        label: Some("find_proofs"),
1477        layout: &bind_group_layout,
1478        entries: &[
1479            BindGroupEntry {
1480                binding: 0,
1481                resource: table_2_positions_gpu.as_entire_binding(),
1482            },
1483            BindGroupEntry {
1484                binding: 1,
1485                resource: table_3_positions_gpu.as_entire_binding(),
1486            },
1487            BindGroupEntry {
1488                binding: 2,
1489                resource: table_4_positions_gpu.as_entire_binding(),
1490            },
1491            BindGroupEntry {
1492                binding: 3,
1493                resource: table_5_positions_gpu.as_entire_binding(),
1494            },
1495            BindGroupEntry {
1496                binding: 4,
1497                resource: table_6_positions_gpu.as_entire_binding(),
1498            },
1499            BindGroupEntry {
1500                binding: 5,
1501                resource: bucket_sizes_gpu.as_entire_binding(),
1502            },
1503            BindGroupEntry {
1504                binding: 6,
1505                resource: buckets_gpu.as_entire_binding(),
1506            },
1507            BindGroupEntry {
1508                binding: 7,
1509                resource: proofs_gpu.as_entire_binding(),
1510            },
1511        ],
1512    });
1513
1514    (bind_group, compute_pipeline)
1515}