Skip to main content

spatialrust_gpu/image/
histogram.rs

1//! Exact, bounded two-pass histograms of resident u8 image channels.
2
3mod cdf;
4
5pub(crate) use cdf::CdfPipeline;
6pub use cdf::{histogram_cdf_gpu, histogram_cdf_gpu_profiled, GpuImageCdf};
7
8use bytemuck::{Pod, Zeroable};
9use spatialrust_core::{SpatialError, SpatialResult};
10use std::sync::OnceLock;
11use wgpu::util::DeviceExt;
12
13use super::gpu_image::runtime_device_key;
14#[cfg(not(target_arch = "wasm32"))]
15use super::gpu_image::with_staging_bytes;
16use super::{GpuImage, GpuImageReceipt};
17use crate::{scratch::ScratchBuffers, GpuStageProfiler, WgpuRuntime};
18
19const BINS: u32 = 256;
20const HISTOGRAM_BYTES: u64 = BINS as u64 * 4;
21const MAX_GROUPS: u32 = 256;
22const REPLICATED_MIN_PIXELS: u32 = 4 * 1024 * 1024;
23const REPLICATED_MAX_PIXELS: u32 = 8 * 1024 * 1024;
24const REPLICATED_WORKGROUP_BYTES: u32 = 8 * 257 * 4;
25
26#[repr(C)]
27#[derive(Clone, Copy, Pod, Zeroable)]
28struct Params {
29    width: u32,
30    height: u32,
31    channel: u32,
32    groups: u32,
33}
34
35const SHADER: &str = r#"
36struct Params { width: u32, height: u32, channel: u32, groups: u32, };
37@group(0) @binding(0) var<uniform> params: Params;
38@group(0) @binding(1) var pixels: texture_2d<u32>;
39@group(0) @binding(2) var<storage, read_write> partials: array<u32>;
40@group(0) @binding(3) var<storage, read_write> output: array<u32>;
41var<workgroup> local_bins: array<atomic<u32>, 256>;
42
43@compute @workgroup_size(256)
44fn histogram_partials(
45    @builtin(local_invocation_index) lane: u32,
46    @builtin(workgroup_id) group: vec3<u32>,
47) {
48    atomicStore(&local_bins[lane], 0u);
49    workgroupBarrier();
50    let total = params.width * params.height;
51    let stride = params.groups * 256u;
52    var index = group.x * 256u + lane;
53    loop {
54        if (index >= total) { break; }
55        let xy = vec2<i32>(i32(index % params.width), i32(index / params.width));
56        let value = textureLoad(pixels, xy, 0)[params.channel];
57        atomicAdd(&local_bins[value], 1u);
58        // Prevent u32 wrapping even at the maximum accepted pixel count.
59        if (total - index <= stride) { break; }
60        index += stride;
61    }
62    workgroupBarrier();
63    // Every entry is overwritten, including zero bins in recycled scratch.
64    partials[group.x * 256u + lane] = atomicLoad(&local_bins[lane]);
65}
66
67@compute @workgroup_size(256)
68fn histogram_reduce(@builtin(local_invocation_index) bin: u32) {
69    var count = 0u;
70    for (var group = 0u; group < params.groups; group++) {
71        count += partials[group * 256u + bin];
72    }
73    output[bin] = count;
74}
75"#;
76
77pub(crate) struct HistogramPipelines {
78    layout: wgpu::BindGroupLayout,
79    partials: wgpu::ComputePipeline,
80    reduce: wgpu::ComputePipeline,
81    replicated: OnceLock<wgpu::ComputePipeline>,
82}
83
84impl HistogramPipelines {
85    fn replicated_partials(&self, device: &wgpu::Device) -> &wgpu::ComputePipeline {
86        self.replicated.get_or_init(|| {
87            let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
88                label: Some("gpu-image-histogram-replicated-shader"),
89                source: wgpu::ShaderSource::Wgsl(include_str!("histogram/replicated.wgsl").into()),
90            });
91            let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
92                label: Some("gpu-image-histogram-replicated-layout"),
93                bind_group_layouts: &[&self.layout],
94                push_constant_ranges: &[],
95            });
96            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
97                label: Some("gpu-image-histogram-replicated-partials"),
98                layout: Some(&layout),
99                module: &shader,
100                entry_point: Some("histogram_partials"),
101                compilation_options: Default::default(),
102                cache: None,
103            })
104        })
105    }
106}
107
108fn create_pipelines(device: &wgpu::Device) -> HistogramPipelines {
109    let buffer = |binding, ty| wgpu::BindGroupLayoutEntry {
110        binding,
111        visibility: wgpu::ShaderStages::COMPUTE,
112        ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None },
113        count: None,
114    };
115    let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
116        label: Some("gpu-image-histogram-layout"),
117        entries: &[
118            buffer(0, wgpu::BufferBindingType::Uniform),
119            wgpu::BindGroupLayoutEntry {
120                binding: 1,
121                visibility: wgpu::ShaderStages::COMPUTE,
122                ty: wgpu::BindingType::Texture {
123                    sample_type: wgpu::TextureSampleType::Uint,
124                    view_dimension: wgpu::TextureViewDimension::D2,
125                    multisampled: false,
126                },
127                count: None,
128            },
129            buffer(2, wgpu::BufferBindingType::Storage { read_only: false }),
130            buffer(3, wgpu::BufferBindingType::Storage { read_only: false }),
131        ],
132    });
133    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
134        label: Some("gpu-image-histogram-shader"),
135        source: wgpu::ShaderSource::Wgsl(SHADER.into()),
136    });
137    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
138        label: Some("gpu-image-histogram-pipeline-layout"),
139        bind_group_layouts: &[&layout],
140        push_constant_ranges: &[],
141    });
142    let pipeline = |entry| {
143        device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
144            label: Some(entry),
145            layout: Some(&pipeline_layout),
146            module: &shader,
147            entry_point: Some(entry),
148            compilation_options: wgpu::PipelineCompilationOptions::default(),
149            cache: None,
150        })
151    };
152    HistogramPipelines {
153        partials: pipeline("histogram_partials"),
154        reduce: pipeline("histogram_reduce"),
155        replicated: OnceLock::new(),
156        layout,
157    }
158}
159
160pub(super) struct DispatchPlan {
161    pixels: u32,
162    groups: u32,
163    partial_bytes: u64,
164}
165
166fn use_replicated(plan: &DispatchPlan, limits: &wgpu::Limits) -> bool {
167    plan.pixels >= REPLICATED_MIN_PIXELS
168        && plan.pixels <= REPLICATED_MAX_PIXELS
169        && limits.max_compute_workgroup_storage_size >= REPLICATED_WORKGROUP_BYTES
170}
171
172pub(super) fn dispatch_plan(
173    width: u32,
174    height: u32,
175    limits: &wgpu::Limits,
176) -> SpatialResult<DispatchPlan> {
177    let pixels = u64::from(width) * u64::from(height);
178    if pixels == 0 || pixels > u64::from(u32::MAX) {
179        return Err(invalid("GPU histogram requires 1..=u32::MAX pixels"));
180    }
181    if limits.max_compute_invocations_per_workgroup < BINS
182        || limits.max_compute_workgroup_size_x < BINS
183        || u64::from(limits.max_compute_workgroup_storage_size) < HISTOGRAM_BYTES
184        || limits.max_storage_buffers_per_shader_stage < 2
185    {
186        return Err(invalid(
187            "GPU histogram requires 256 lanes, 1 KiB workgroup storage and two storage buffers",
188        ));
189    }
190    let binding_groups =
191        limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size))
192            / HISTOGRAM_BYTES;
193    let groups = pixels
194        .div_ceil(u64::from(BINS))
195        .min(u64::from(MAX_GROUPS))
196        .min(u64::from(limits.max_compute_workgroups_per_dimension))
197        .min(binding_groups) as u32;
198    if groups == 0 {
199        return Err(invalid("GPU histogram device limits cannot hold one 256-bin histogram"));
200    }
201    Ok(DispatchPlan {
202        pixels: pixels as u32,
203        groups,
204        partial_bytes: u64::from(groups) * HISTOGRAM_BYTES,
205    })
206}
207
208/// Resident exact 256-bin u32 counts for one logical u8 image channel.
209///
210/// Construction performs two compute passes without host readback. Input is
211/// limited to u32::MAX pixels so every bin and their sum are exactly representable.
212/// A live result is never recycled implicitly; call `recycle` when finished.
213pub struct GpuImageHistogram {
214    buffer: wgpu::Buffer,
215    device_key: std::sync::Arc<()>,
216    pixel_count: u32,
217    channel: u32,
218    receipt: GpuImageReceipt,
219}
220
221impl GpuImageHistogram {
222    /// Returns the source pixel count (also the sum of all bins).
223    #[must_use]
224    pub const fn pixel_count(&self) -> u32 {
225        self.pixel_count
226    }
227
228    /// Returns the selected logical channel, without implicit luma conversion.
229    #[must_use]
230    pub const fn channel(&self) -> u32 {
231        self.channel
232    }
233
234    /// Returns cumulative source transfers and histogram device-stage writes.
235    #[must_use]
236    pub const fn receipt(&self) -> &GpuImageReceipt {
237        &self.receipt
238    }
239
240    /// Explicitly synchronizes and reads exactly 1,024 bin bytes on native hosts.
241    /// Each successful call adds another 1,024 bytes to the transfer receipt.
242    #[cfg(not(target_arch = "wasm32"))]
243    pub fn readback_u32(&mut self, runtime: &WgpuRuntime) -> SpatialResult<[u32; 256]> {
244        self.validate_runtime(runtime)?;
245        let result = readback_bins_u32(runtime, &self.buffer)?;
246        self.receipt.record_device_to_host(HISTOGRAM_BYTES, "readback_histogram_u32");
247        Ok(result)
248    }
249
250    /// Returns bin storage to its runtime's bounded buffer pool after submission.
251    /// A different runtime discards this result instead of contaminating its pool.
252    pub fn recycle(self, runtime: &WgpuRuntime) {
253        if self.validate_runtime(runtime).is_ok() {
254            runtime.recycle_storage(HISTOGRAM_BYTES, self.buffer);
255        }
256    }
257
258    fn validate_runtime(&self, runtime: &WgpuRuntime) -> SpatialResult<()> {
259        if !std::sync::Arc::ptr_eq(&self.device_key, &runtime_device_key(runtime)) {
260            return Err(invalid("GPU histogram belongs to a different runtime device"));
261        }
262        Ok(())
263    }
264}
265
266#[cfg(not(target_arch = "wasm32"))]
267fn readback_bins_u32(runtime: &WgpuRuntime, buffer: &wgpu::Buffer) -> SpatialResult<[u32; 256]> {
268    let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
269        label: Some("gpu-image-histogram-readback"),
270        size: HISTOGRAM_BYTES,
271        usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
272        mapped_at_creation: false,
273    });
274    let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
275        label: Some("gpu-image-histogram-readback-encoder"),
276    });
277    encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, HISTOGRAM_BYTES);
278    runtime.queue().submit(Some(encoder.finish()));
279    with_staging_bytes(runtime.device(), &staging, HISTOGRAM_BYTES as usize, |bytes| {
280        let mut result = [0; 256];
281        for (count, bytes) in result.iter_mut().zip(bytes.chunks_exact(4)) {
282            *count = u32::from_le_bytes(bytes.try_into().expect("four-byte histogram count"));
283        }
284        result
285    })
286}
287
288/// Counts one logical channel (0..source.channels()) without leaving the GPU.
289///
290/// Uses at most 256 workgroups, 256 KiB private pooled partials and a 1 KiB
291/// resident output. Every scratch/output bin is overwritten before reuse.
292/// Images with 4..=8 Mi pixels use eight local counter replicas when shared
293/// memory permits; other calls retain the original kernel.
294/// Apply `rgb_to_gray_gpu` first when a luma histogram is desired.
295pub fn histogram_u8_gpu(
296    runtime: &WgpuRuntime,
297    source: &GpuImage,
298    channel: u32,
299) -> SpatialResult<GpuImageHistogram> {
300    histogram_with_profiler(runtime, source, channel, None)
301}
302
303/// Counts a resident channel while recording two optional GPU pass timestamps.
304/// Requires two unused profiler stages on the same runtime before allocating work.
305pub fn histogram_u8_gpu_profiled(
306    runtime: &WgpuRuntime,
307    source: &GpuImage,
308    channel: u32,
309    profiler: &mut GpuStageProfiler,
310) -> SpatialResult<GpuImageHistogram> {
311    profiler.validate(runtime, 2)?;
312    let result = histogram_with_profiler(runtime, source, channel, Some(profiler));
313    profiler.finish_recording(&result);
314    result
315}
316
317fn histogram_with_profiler(
318    runtime: &WgpuRuntime,
319    source: &GpuImage,
320    channel: u32,
321    mut profiler: Option<&mut GpuStageProfiler>,
322) -> SpatialResult<GpuImageHistogram> {
323    source.validate_runtime(runtime)?;
324    if channel >= source.channels() {
325        return Err(invalid("GPU histogram channel is outside the logical image channels"));
326    }
327    let limits = runtime.device().limits();
328    let plan = dispatch_plan(source.width(), source.height(), &limits)?;
329    let params =
330        Params { width: source.width(), height: source.height(), channel, groups: plan.groups };
331    let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
332        label: Some("gpu-image-histogram-params"),
333        contents: bytemuck::bytes_of(&params),
334        usage: wgpu::BufferUsages::UNIFORM,
335    });
336    let pipelines =
337        runtime.image_histogram_pipelines.get_or_init(|| create_pipelines(runtime.device()));
338    let partial_pipeline = if use_replicated(&plan, &limits) {
339        pipelines.replicated_partials(runtime.device())
340    } else {
341        &pipelines.partials
342    };
343    let mut scratch = ScratchBuffers::new(runtime);
344    let partials = scratch.acquire("gpu-image-histogram-partials", plan.partial_bytes);
345    let output = runtime.buffer_pool().acquire_storage(
346        runtime,
347        "gpu-image-histogram-output",
348        HISTOGRAM_BYTES,
349    );
350    let source_view = source.view();
351    let bind_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
352        label: Some("gpu-image-histogram-bind-group"),
353        layout: &pipelines.layout,
354        entries: &[
355            wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
356            wgpu::BindGroupEntry {
357                binding: 1,
358                resource: wgpu::BindingResource::TextureView(&source_view),
359            },
360            wgpu::BindGroupEntry { binding: 2, resource: partials.as_entire_binding() },
361            wgpu::BindGroupEntry { binding: 3, resource: output.as_entire_binding() },
362        ],
363    });
364    let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
365        label: Some("gpu-image-histogram-encoder"),
366    });
367    for (pipeline, stage, groups) in [
368        (partial_pipeline, "histogram_u8_partials_gpu", plan.groups),
369        (&pipelines.reduce, "histogram_u8_reduce_gpu", 1),
370    ] {
371        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
372            label: Some(stage),
373            timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
374        });
375        pass.set_pipeline(pipeline);
376        pass.set_bind_group(0, &bind_group, &[]);
377        pass.dispatch_workgroups(groups, 1, 1);
378    }
379    scratch.submit_and_recycle(encoder);
380    let mut receipt = source.receipt().clone();
381    receipt.record_gpu_to_gpu(plan.partial_bytes, "histogram_u8_partials_gpu");
382    receipt.record_gpu_to_gpu(HISTOGRAM_BYTES, "histogram_u8_reduce_gpu");
383    Ok(GpuImageHistogram {
384        buffer: output,
385        device_key: runtime_device_key(runtime),
386        pixel_count: plan.pixels,
387        channel,
388        receipt,
389    })
390}
391
392fn invalid(message: &str) -> SpatialError {
393    SpatialError::InvalidArgument(message.to_owned())
394}
395
396#[cfg(all(test, not(target_arch = "wasm32")))]
397#[path = "histogram_experiment_execution.rs"]
398mod experiment;
399
400#[cfg(all(test, not(target_arch = "wasm32")))]
401#[path = "histogram_replica_tests.rs"]
402mod replica_tests;
403
404#[cfg(all(test, not(target_arch = "wasm32")))]
405#[path = "histogram_replica_benchmark.rs"]
406mod replica_benchmark;
407
408#[cfg(all(test, not(target_arch = "wasm32")))]
409mod tests {
410    use super::*;
411    use spatialrust_image::{Image, ImageRegion, ImageView};
412
413    #[test]
414    fn plan_checks_counter_overflow_and_bounds_scratch_and_device_dispatch() {
415        let limits = wgpu::Limits::default();
416        for (width, height) in [(1, 1), (257, 1), (3840, 2160), (u32::MAX, 1)] {
417            let plan = dispatch_plan(width, height, &limits).unwrap();
418            assert_eq!(u64::from(plan.pixels), u64::from(width) * u64::from(height));
419            assert!((1..=256).contains(&plan.groups));
420            assert!(plan.partial_bytes <= 256 * 1024);
421        }
422        for (width, height) in [(0, 1), (1, 0), (65_536, 65_536), (u32::MAX, 2)] {
423            assert!(dispatch_plan(width, height, &limits).is_err());
424        }
425        let mut bounded = limits.clone();
426        bounded.max_compute_workgroups_per_dimension = 3;
427        bounded.max_storage_buffer_binding_size = 2 * 1024;
428        assert_eq!(dispatch_plan(3840, 2160, &bounded).unwrap().groups, 2);
429        bounded.max_storage_buffer_binding_size = 1024;
430        assert_eq!(dispatch_plan(3840, 2160, &bounded).unwrap().groups, 1);
431        for field in 0..6 {
432            let mut invalid = limits.clone();
433            match field {
434                0 => invalid.max_compute_invocations_per_workgroup = 255,
435                1 => invalid.max_compute_workgroup_size_x = 255,
436                2 => invalid.max_compute_workgroup_storage_size = 1023,
437                3 => invalid.max_storage_buffer_binding_size = 1023,
438                4 => invalid.max_compute_workgroups_per_dimension = 0,
439                _ => invalid.max_storage_buffers_per_shader_stage = 1,
440            }
441            assert!(dispatch_plan(17, 19, &invalid).is_err());
442        }
443    }
444
445    #[test]
446    fn packed_histograms_match_exact_counts_across_lanes_grid_stride_and_hot_bins() {
447        let runtime = WgpuRuntime::new_headless().unwrap();
448        for (width, height) in
449            [(1, 1), (255, 1), (256, 1), (257, 1), (1, 257), (257, 257), (1001, 1003)]
450        {
451            for pattern in [0, 1, 2] {
452                let data: Vec<_> = (0..width * height)
453                    .map(|i| match pattern {
454                        0 => 255,
455                        1 => 0,
456                        _ => ((i * 37 + i / 257) % 256) as u8,
457                    })
458                    .collect();
459                let mut expected = [0u32; 256];
460                for &value in &data {
461                    expected[value as usize] += 1;
462                }
463                let image = Image::<u8, 1>::try_new(width, height, data).unwrap();
464                let uploaded = GpuImage::upload_u8(&runtime, image.view()).unwrap();
465                let mut result = histogram_u8_gpu(&runtime, &uploaded, 0).unwrap();
466                assert_eq!(result.pixel_count(), (width * height) as u32);
467                assert_eq!(result.channel(), 0);
468                assert_eq!(result.receipt().device_to_host_bytes(), 0);
469                assert_eq!(result.readback_u32(&runtime).unwrap(), expected);
470                assert_eq!(result.receipt().device_to_host_bytes(), 1024);
471                result.recycle(&runtime);
472                uploaded.recycle(&runtime);
473            }
474        }
475        assert_eq!(runtime.initialized_image_pipeline_count(), 1);
476    }
477
478    fn check_roi<const C: usize>(runtime: &WgpuRuntime) {
479        let stride = 21 * C + 13;
480        let mut data = vec![255; 23 * stride];
481        for y in 0..23 {
482            for x in 0..21 {
483                for channel in 0..C {
484                    data[y * stride + x * C + channel] =
485                        ((x * 17 + y * 31 + channel * 53) % 251) as u8;
486                }
487            }
488        }
489        let roi = ImageView::<u8, C>::new(21, 23, stride, &data)
490            .unwrap()
491            .subview(ImageRegion::new(3, 2, 17, 19))
492            .unwrap();
493        let uploaded = GpuImage::upload_u8(runtime, roi).unwrap();
494        for channel in 0..C {
495            let mut expected = [0u32; 256];
496            for y in 0..roi.height() {
497                for pixel in roi.row(y).unwrap().chunks_exact(C) {
498                    expected[pixel[channel] as usize] += 1;
499                }
500            }
501            let mut result = histogram_u8_gpu(runtime, &uploaded, channel as u32).unwrap();
502            result.receipt().validate_resident_chain(17 * 19 * 4).unwrap();
503            assert_eq!(result.readback_u32(runtime).unwrap(), expected);
504            assert_eq!(result.readback_u32(runtime).unwrap(), expected);
505            assert_eq!(result.receipt().device_to_host_bytes(), 2048);
506            assert!(result.receipt().validate_resident_chain(17 * 19 * 4).is_err());
507            assert_eq!(result.receipt().gpu_to_gpu_bytes(), 2 * 1024 + 1024);
508            result.recycle(runtime);
509        }
510        let before = runtime.buffer_pool().stats();
511        assert!(histogram_u8_gpu(runtime, &uploaded, C as u32).is_err());
512        assert!(histogram_u8_gpu(runtime, &uploaded, u32::MAX).is_err());
513        assert_eq!(runtime.buffer_pool().stats(), before);
514        uploaded.recycle(runtime);
515    }
516
517    #[test]
518    fn all_logical_channels_ignore_roi_padding_and_record_only_explicit_bin_readbacks() {
519        let runtime = WgpuRuntime::new_headless().unwrap();
520        check_roi::<1>(&runtime);
521        check_roi::<2>(&runtime);
522        check_roi::<3>(&runtime);
523        check_roi::<4>(&runtime);
524    }
525
526    #[test]
527    fn live_results_survive_scratch_reuse_pool_clears_and_runtime_moves() {
528        let boxed = Box::new(WgpuRuntime::new_headless().unwrap());
529        let image = Image::<u8, 1>::try_new(257, 257, vec![73; 257 * 257]).unwrap();
530        let uploaded = GpuImage::upload_u8(&boxed, image.view()).unwrap();
531        let mut first = histogram_u8_gpu(&boxed, &uploaded, 0).unwrap();
532        let runtime = *boxed;
533        for value in [0, 255, 42, 73] {
534            let image = Image::<u8, 1>::try_new(257, 257, vec![value; 257 * 257]).unwrap();
535            let source = GpuImage::upload_u8(&runtime, image.view()).unwrap();
536            let mut result = histogram_u8_gpu(&runtime, &source, 0).unwrap();
537            let bins = result.readback_u32(&runtime).unwrap();
538            assert_eq!(bins[value as usize], 257 * 257);
539            assert_eq!(bins.iter().sum::<u32>(), 257 * 257);
540            result.recycle(&runtime);
541            source.recycle(&runtime);
542        }
543        let scratch = runtime.scratch_buffer_pool_stats();
544        let buffers = runtime.buffer_pool().stats();
545        for _ in 0..5 {
546            histogram_u8_gpu(&runtime, &uploaded, 0).unwrap().recycle(&runtime);
547        }
548        assert_eq!(runtime.scratch_buffer_pool_stats().allocation_count, scratch.allocation_count);
549        assert_eq!(runtime.buffer_pool().stats().allocation_count, buffers.allocation_count);
550        assert_eq!(runtime.scratch_buffer_pool_stats().reuse_count - scratch.reuse_count, 5);
551        runtime.set_scratch_buffer_pool_budget(0);
552        runtime.buffer_pool().set_budget(0);
553        let expected = {
554            let mut bins = [0; 256];
555            bins[73] = 257 * 257;
556            bins
557        };
558        assert_eq!(first.readback_u32(&runtime).unwrap(), expected);
559        first.recycle(&runtime);
560        assert_eq!(runtime.buffer_pool().stats().cached_bytes, 0);
561        uploaded.recycle(&runtime);
562    }
563
564    #[test]
565    fn foreign_devices_reject_sources_results_and_recycling_without_pool_changes() {
566        let first = WgpuRuntime::new_headless().unwrap();
567        let other = WgpuRuntime::new_headless().unwrap();
568        let image = Image::<u8, 1>::try_new(1, 1, vec![19]).unwrap();
569        let source = GpuImage::upload_u8(&first, image.view()).unwrap();
570        let mut result = histogram_u8_gpu(&first, &source, 0).unwrap();
571        assert!(histogram_u8_gpu(&other, &source, 0).is_err());
572        assert!(result.readback_u32(&other).is_err());
573        assert_eq!(result.receipt().device_to_host_bytes(), 0);
574        result.recycle(&other);
575        assert_eq!(other.buffer_pool().stats().cached_bytes, 0);
576        assert_eq!(other.scratch_buffer_pool_stats().allocation_count, 0);
577        assert_eq!(other.initialized_image_pipeline_count(), 0);
578        source.recycle(&first);
579    }
580
581    #[test]
582    fn concurrent_histograms_keep_live_outputs_and_private_scratch_separate() {
583        let runtime = WgpuRuntime::new_headless().unwrap();
584        std::thread::scope(|scope| {
585            let mut handles = Vec::new();
586            for value in [0u8, 19, 73, 255] {
587                let runtime = &runtime;
588                handles.push(scope.spawn(move || {
589                    let image = Image::<u8, 1>::try_new(257, 257, vec![value; 257 * 257]).unwrap();
590                    let source = GpuImage::upload_u8(runtime, image.view()).unwrap();
591                    let mut outputs = Vec::new();
592                    for _ in 0..3 {
593                        outputs.push(histogram_u8_gpu(runtime, &source, 0).unwrap());
594                    }
595                    for mut output in outputs {
596                        let bins = output.readback_u32(runtime).unwrap();
597                        assert_eq!(bins[value as usize], 257 * 257);
598                        assert_eq!(bins.iter().sum::<u32>(), 257 * 257);
599                        output.recycle(runtime);
600                    }
601                    source.recycle(runtime);
602                }));
603            }
604            for handle in handles {
605                handle.join().unwrap();
606            }
607        });
608        assert!(runtime.scratch_buffer_pool_stats().cached_bytes <= 64 * 1024 * 1024);
609        assert_eq!(runtime.initialized_image_pipeline_count(), 1);
610    }
611}