Skip to main content

spatialrust_gpu/image/histogram/
cdf.rs

1//! Exact inclusive cumulative counts from an owned resident histogram.
2
3use spatialrust_core::{SpatialError, SpatialResult};
4
5use super::{GpuImageHistogram, HISTOGRAM_BYTES};
6use crate::image::gpu_image::runtime_device_key;
7use crate::image::GpuImageReceipt;
8use crate::{GpuStageProfiler, WgpuRuntime};
9
10const SHADER: &str = r#"
11@group(0) @binding(0) var<storage, read> bins: array<u32>;
12@group(0) @binding(1) var<storage, read_write> cumulative: array<u32>;
13var<workgroup> tree: array<u32, 256>;
14
15// The same work-efficient tree scan used by point-cloud compaction, specialized
16// to exactly one full block. The original count turns exclusive into inclusive.
17@compute @workgroup_size(256)
18fn histogram_cdf(@builtin(local_invocation_index) lane: u32) {
19    let value = bins[lane];
20    tree[lane] = value;
21    workgroupBarrier();
22    for (var stride = 1u; stride < 256u; stride *= 2u) {
23        let slot = (lane + 1u) * stride * 2u - 1u;
24        if slot < 256u { tree[slot] += tree[slot - stride]; }
25        workgroupBarrier();
26    }
27    if lane == 0u { tree[255u] = 0u; }
28    workgroupBarrier();
29    for (var stride = 128u; stride > 0u; stride /= 2u) {
30        let slot = (lane + 1u) * stride * 2u - 1u;
31        if slot < 256u {
32            let left = tree[slot - stride];
33            tree[slot - stride] = tree[slot];
34            tree[slot] += left;
35        }
36        workgroupBarrier();
37    }
38    // All output bins are overwritten, including leading zero counts.
39    cumulative[lane] = tree[lane] + value;
40}
41"#;
42
43pub(crate) struct CdfPipeline {
44    layout: wgpu::BindGroupLayout,
45    pipeline: wgpu::ComputePipeline,
46}
47
48impl CdfPipeline {
49    fn new(device: &wgpu::Device) -> Self {
50        let entry = |binding, read_only| wgpu::BindGroupLayoutEntry {
51            binding,
52            visibility: wgpu::ShaderStages::COMPUTE,
53            ty: wgpu::BindingType::Buffer {
54                ty: wgpu::BufferBindingType::Storage { read_only },
55                has_dynamic_offset: false,
56                min_binding_size: std::num::NonZeroU64::new(HISTOGRAM_BYTES),
57            },
58            count: None,
59        };
60        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
61            label: Some("gpu-image-cdf-layout"),
62            entries: &[entry(0, true), entry(1, false)],
63        });
64        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
65            label: Some("gpu-image-cdf-shader"),
66            source: wgpu::ShaderSource::Wgsl(SHADER.into()),
67        });
68        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
69            label: Some("gpu-image-cdf-pipeline-layout"),
70            bind_group_layouts: &[&layout],
71            push_constant_ranges: &[],
72        });
73        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
74            label: Some("gpu-image-cdf-pipeline"),
75            layout: Some(&pipeline_layout),
76            module: &shader,
77            entry_point: Some("histogram_cdf"),
78            compilation_options: wgpu::PipelineCompilationOptions::default(),
79            cache: None,
80        });
81        Self { layout, pipeline }
82    }
83}
84
85fn validate_limits(limits: &wgpu::Limits) -> SpatialResult<()> {
86    if limits.max_compute_invocations_per_workgroup < 256
87        || limits.max_compute_workgroup_size_x < 256
88        || u64::from(limits.max_compute_workgroup_storage_size) < HISTOGRAM_BYTES
89        || limits.max_storage_buffers_per_shader_stage < 2
90        || limits.max_compute_workgroups_per_dimension == 0
91        || limits.max_buffer_size < HISTOGRAM_BYTES
92        || u64::from(limits.max_storage_buffer_binding_size) < HISTOGRAM_BYTES
93    {
94        return Err(invalid(
95            "GPU CDF requires 256 lanes, 1 KiB local storage and two 1 KiB buffers",
96        ));
97    }
98    Ok(())
99}
100
101/// Resident inclusive u32 cumulative counts for all 256 image byte values.
102///
103/// Entry `i` counts source pixels whose selected channel is at most `i`.
104/// Counts are exact, monotonically nondecreasing, and entry 255 equals
105/// `pixel_count()`. This is an unnormalized CDF; no float conversion or rounding
106/// occurs. The result owns independent 1 KiB storage and never recycles implicitly.
107pub struct GpuImageCdf {
108    buffer: wgpu::Buffer,
109    device_key: std::sync::Arc<()>,
110    pixel_count: u32,
111    channel: u32,
112    receipt: GpuImageReceipt,
113}
114
115impl GpuImageCdf {
116    pub(in crate::image) const fn buffer(&self) -> &wgpu::Buffer {
117        &self.buffer
118    }
119
120    /// Returns the source pixel count, also the final cumulative count.
121    #[must_use]
122    pub const fn pixel_count(&self) -> u32 {
123        self.pixel_count
124    }
125
126    /// Returns the source histogram's logical channel.
127    #[must_use]
128    pub const fn channel(&self) -> u32 {
129        self.channel
130    }
131
132    /// Returns cumulative source transfers plus the 1 KiB CDF stage write.
133    #[must_use]
134    pub const fn receipt(&self) -> &GpuImageReceipt {
135        &self.receipt
136    }
137
138    /// Explicitly synchronizes and reads 1,024 cumulative-count bytes natively.
139    /// Each successful call adds 1,024 bytes to the cumulative transfer receipt.
140    #[cfg(not(target_arch = "wasm32"))]
141    pub fn readback_u32(&mut self, runtime: &WgpuRuntime) -> SpatialResult<[u32; 256]> {
142        self.validate_runtime(runtime)?;
143        let counts = super::readback_bins_u32(runtime, &self.buffer)?;
144        self.receipt.record_device_to_host(HISTOGRAM_BYTES, "readback_cdf_u32");
145        Ok(counts)
146    }
147
148    /// Returns output storage to its original runtime's bounded buffer pool.
149    /// A foreign runtime discards this result instead of receiving its storage.
150    pub fn recycle(self, runtime: &WgpuRuntime) {
151        if self.validate_runtime(runtime).is_ok() {
152            runtime.recycle_storage(HISTOGRAM_BYTES, self.buffer);
153        }
154    }
155
156    fn validate_runtime(&self, runtime: &WgpuRuntime) -> SpatialResult<()> {
157        if !std::sync::Arc::ptr_eq(&self.device_key, &runtime_device_key(runtime)) {
158            return Err(invalid("GPU CDF belongs to a different runtime device"));
159        }
160        Ok(())
161    }
162}
163
164/// Computes exact inclusive cumulative counts without downloading source bins.
165///
166/// One 256-lane pass uses 1 KiB workgroup-local memory and writes a separate
167/// 1 KiB resident result. Source bins stay unchanged. The source may be recycled
168/// after this call returns; its reads have already been submitted in queue order.
169pub fn histogram_cdf_gpu(
170    runtime: &WgpuRuntime,
171    source: &GpuImageHistogram,
172) -> SpatialResult<GpuImageCdf> {
173    cdf_with_profiler(runtime, source, None)
174}
175
176/// Computes cumulative counts while recording one optional GPU pass timestamp.
177/// Requires one unused profiler stage on the original runtime before allocation.
178pub fn histogram_cdf_gpu_profiled(
179    runtime: &WgpuRuntime,
180    source: &GpuImageHistogram,
181    profiler: &mut GpuStageProfiler,
182) -> SpatialResult<GpuImageCdf> {
183    profiler.validate(runtime, 1)?;
184    let result = cdf_with_profiler(runtime, source, Some(profiler));
185    profiler.finish_recording(&result);
186    result
187}
188
189fn cdf_with_profiler(
190    runtime: &WgpuRuntime,
191    source: &GpuImageHistogram,
192    mut profiler: Option<&mut GpuStageProfiler>,
193) -> SpatialResult<GpuImageCdf> {
194    source.validate_runtime(runtime)?;
195    validate_limits(&runtime.device().limits())?;
196    let pipelines = runtime.image_cdf_pipeline.get_or_init(|| CdfPipeline::new(runtime.device()));
197    let output =
198        runtime.buffer_pool().acquire_storage(runtime, "gpu-image-cdf-output", HISTOGRAM_BYTES);
199    let bind_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
200        label: Some("gpu-image-cdf-bind-group"),
201        layout: &pipelines.layout,
202        entries: &[
203            wgpu::BindGroupEntry { binding: 0, resource: source.buffer.as_entire_binding() },
204            wgpu::BindGroupEntry { binding: 1, resource: output.as_entire_binding() },
205        ],
206    });
207    let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
208        label: Some("gpu-image-cdf-encoder"),
209    });
210    {
211        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
212            label: Some("histogram_cdf_u32_gpu"),
213            timestamp_writes: crate::profiling::timestamp_writes(
214                &mut profiler,
215                "histogram_cdf_u32_gpu",
216            ),
217        });
218        pass.set_pipeline(&pipelines.pipeline);
219        pass.set_bind_group(0, &bind_group, &[]);
220        pass.dispatch_workgroups(1, 1, 1);
221    }
222    runtime.queue().submit(Some(encoder.finish()));
223    let mut receipt = source.receipt().clone();
224    receipt.record_gpu_to_gpu(HISTOGRAM_BYTES, "histogram_cdf_u32_gpu");
225    Ok(GpuImageCdf {
226        buffer: output,
227        device_key: runtime_device_key(runtime),
228        pixel_count: source.pixel_count(),
229        channel: source.channel(),
230        receipt,
231    })
232}
233
234fn invalid(message: &str) -> SpatialError {
235    SpatialError::InvalidArgument(message.to_owned())
236}
237
238#[cfg(all(test, not(target_arch = "wasm32")))]
239#[path = "mapped_readback_tests.rs"]
240mod mapped_readback_tests;
241
242#[cfg(all(test, not(target_arch = "wasm32")))]
243mod tests {
244    use super::*;
245    use crate::image::{histogram_u8_gpu, GpuImage};
246    use spatialrust_image::Image;
247
248    #[test]
249    fn cdf_requires_bounded_scan_limits() {
250        let limits = wgpu::Limits::default();
251        validate_limits(&limits).unwrap();
252        for field in 0..7 {
253            let mut invalid = limits.clone();
254            match field {
255                0 => invalid.max_compute_invocations_per_workgroup = 255,
256                1 => invalid.max_compute_workgroup_size_x = 255,
257                2 => invalid.max_compute_workgroup_storage_size = 1023,
258                3 => invalid.max_storage_buffers_per_shader_stage = 1,
259                4 => invalid.max_compute_workgroups_per_dimension = 0,
260                5 => invalid.max_buffer_size = 1023,
261                _ => invalid.max_storage_buffer_binding_size = 1023,
262            }
263            assert!(validate_limits(&invalid).is_err());
264        }
265    }
266
267    fn reference(bins: &[u32; 256]) -> [u32; 256] {
268        let mut total = 0u64;
269        std::array::from_fn(|i| {
270            total += u64::from(bins[i]);
271            u32::try_from(total).unwrap()
272        })
273    }
274
275    // Test-only resident input avoids allocating a u32::MAX-pixel texture.
276    fn synthetic(runtime: &WgpuRuntime, bins: &[u32; 256]) -> GpuImageHistogram {
277        let pixel_count = reference(bins)[255];
278        let buffer =
279            runtime.buffer_pool().acquire_storage(runtime, "cdf-test-bins", HISTOGRAM_BYTES);
280        runtime.queue().write_buffer(&buffer, 0, bytemuck::cast_slice(bins));
281        let mut receipt = GpuImageReceipt::default();
282        receipt.record_host_to_device(HISTOGRAM_BYTES, "cdf_test_upload");
283        GpuImageHistogram {
284            buffer,
285            device_key: runtime_device_key(runtime),
286            pixel_count,
287            channel: 0,
288            receipt,
289        }
290    }
291
292    #[test]
293    fn scan_is_exact_through_u32_max_and_preserves_source_bins() {
294        let runtime = WgpuRuntime::new_headless().unwrap();
295        let mut cases = vec![std::array::from_fn(|i| (i * i + 3) as u32)];
296        for (slot, count) in
297            [(0, 1), (127, 19), (255, 257), (0, u32::MAX), (127, u32::MAX), (255, u32::MAX)]
298        {
299            let mut bins = [0; 256];
300            bins[slot] = count;
301            cases.push(bins);
302        }
303        let mut split = [0; 256];
304        split[0] = u32::MAX - 1;
305        split[255] = 1;
306        cases.push(split);
307        cases.push(std::array::from_fn(|i| if i == 255 { 16_777_470 } else { 16_777_215 }));
308        for bins in cases {
309            let mut source = synthetic(&runtime, &bins);
310            let mut result = histogram_cdf_gpu(&runtime, &source).unwrap();
311            let expected = reference(&bins);
312            result.receipt().validate_resident_chain(HISTOGRAM_BYTES).unwrap();
313            assert_eq!(result.readback_u32(&runtime).unwrap(), expected);
314            assert_eq!(result.readback_u32(&runtime).unwrap(), expected);
315            assert_eq!(result.pixel_count(), expected[255]);
316            assert_eq!(result.channel(), 0);
317            assert_eq!(result.receipt().device_to_host_bytes(), 2048);
318            assert_eq!(result.receipt().gpu_to_gpu_bytes(), 1024);
319            assert_eq!(result.receipt().stages().last(), Some(&"readback_cdf_u32"));
320            assert!(expected.windows(2).all(|pair| pair[0] <= pair[1]));
321            assert_eq!(source.readback_u32(&runtime).unwrap(), bins);
322            source.recycle(&runtime);
323            result.recycle(&runtime);
324        }
325        assert_eq!(runtime.initialized_image_pipeline_count(), 1);
326        assert_eq!(runtime.scratch_buffer_pool_stats().allocation_count, 0);
327    }
328
329    #[test]
330    fn live_cdfs_survive_source_recycling_output_reuse_and_runtime_moves() {
331        let boxed = Box::new(WgpuRuntime::new_headless().unwrap());
332        let mut bins = [0; 256];
333        bins[42] = 65_537;
334        let source = synthetic(&boxed, &bins);
335        let mut retained = histogram_cdf_gpu(&boxed, &source).unwrap();
336        source.recycle(&boxed);
337        let runtime = *boxed;
338        for value in [255, 0, 127, 255] {
339            let mut replacement = [0; 256];
340            replacement[value] = 9;
341            let source = synthetic(&runtime, &replacement);
342            let mut result = histogram_cdf_gpu(&runtime, &source).unwrap();
343            source.recycle(&runtime);
344            assert_eq!(result.readback_u32(&runtime).unwrap(), reference(&replacement));
345            result.recycle(&runtime);
346        }
347        let source = synthetic(&runtime, &bins);
348        let before = runtime.buffer_pool().stats();
349        for _ in 0..5 {
350            histogram_cdf_gpu(&runtime, &source).unwrap().recycle(&runtime);
351        }
352        assert_eq!(runtime.buffer_pool().stats().allocation_count, before.allocation_count);
353        assert_eq!(runtime.buffer_pool().stats().reuse_count - before.reuse_count, 5);
354        runtime.buffer_pool().set_budget(0);
355        runtime.clear_scratch_buffer_pool();
356        assert_eq!(retained.readback_u32(&runtime).unwrap(), reference(&bins));
357        retained.recycle(&runtime);
358        source.recycle(&runtime);
359        assert_eq!(runtime.buffer_pool().stats().cached_bytes, 0);
360    }
361
362    #[test]
363    fn foreign_sources_readbacks_and_recycling_fail_without_work_allocation() {
364        let runtime = WgpuRuntime::new_headless().unwrap();
365        let other = WgpuRuntime::new_headless().unwrap();
366        let mut bins = [0; 256];
367        bins[19] = 1;
368        let source = synthetic(&runtime, &bins);
369        let mut result = histogram_cdf_gpu(&runtime, &source).unwrap();
370        assert!(histogram_cdf_gpu(&other, &source).is_err());
371        assert!(result.readback_u32(&other).is_err());
372        assert_eq!(result.receipt().device_to_host_bytes(), 0);
373        result.recycle(&other);
374        assert_eq!(other.buffer_pool().stats().allocation_count, 0);
375        assert_eq!(other.buffer_pool().stats().cached_bytes, 0);
376        assert_eq!(other.initialized_image_pipeline_count(), 0);
377        source.recycle(&runtime);
378    }
379
380    #[test]
381    fn shared_histogram_supports_concurrent_independent_cdfs() {
382        let runtime = WgpuRuntime::new_headless().unwrap();
383        let image =
384            Image::<u8, 1>::try_new(257, 129, (0..257 * 129).map(|i| (i % 251) as u8).collect())
385                .unwrap();
386        let uploaded = GpuImage::upload_u8(&runtime, image.view()).unwrap();
387        let mut bins = [0; 256];
388        for &value in image.as_slice() {
389            bins[value as usize] += 1;
390        }
391        let source = histogram_u8_gpu(&runtime, &uploaded, 0).unwrap();
392        let outputs = std::thread::scope(|scope| {
393            let handles: Vec<_> = (0..4)
394                .map(|_| {
395                    scope.spawn(|| {
396                        (0..3)
397                            .map(|_| histogram_cdf_gpu(&runtime, &source).unwrap())
398                            .collect::<Vec<_>>()
399                    })
400                })
401                .collect();
402            handles.into_iter().flat_map(|handle| handle.join().unwrap()).collect::<Vec<_>>()
403        });
404        source.recycle(&runtime);
405        uploaded.recycle(&runtime);
406        for mut output in outputs {
407            assert_eq!(output.readback_u32(&runtime).unwrap(), reference(&bins));
408            output.recycle(&runtime);
409        }
410        assert_eq!(runtime.initialized_image_pipeline_count(), 2);
411        let stats = runtime.buffer_pool().stats();
412        assert!(stats.cached_bytes <= stats.budget_bytes);
413    }
414}