Skip to main content

spatialrust_gpu/image/
ai_tensor.rs

1//! Device-resident planar floating-point tensors packed from GPU images.
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use wgpu::util::DeviceExt;
6
7use super::gpu_image::{runtime_device_key, with_staging_bytes, GpuImage, GpuImageReceipt};
8use crate::WgpuRuntime;
9
10const WORKGROUP_X: u32 = 16;
11const WORKGROUP_Y: u32 = 16;
12
13#[derive(Clone, Copy, Debug)]
14struct AiPackPlan {
15    byte_len: u64,
16    groups: [u32; 3],
17}
18
19fn pack_plan(
20    width: u32,
21    height: u32,
22    channels: u32,
23    limits: &wgpu::Limits,
24) -> SpatialResult<AiPackPlan> {
25    let invalid = || {
26        SpatialError::InvalidArgument(
27        "GPU AI packing requires positive dimensions, supported channels and buffer/compute/index limits".to_owned(),
28    )
29    };
30    let pixels = u64::from(width) * u64::from(height);
31    if width == 0
32        || height == 0
33        || !(1..=4).contains(&channels)
34        || width > limits.max_texture_dimension_2d
35        || height > limits.max_texture_dimension_2d
36        || width > i32::MAX as u32
37        || height > i32::MAX as u32
38        || pixels > u64::from(u32::MAX)
39        || limits.max_compute_invocations_per_workgroup < WORKGROUP_X * WORKGROUP_Y
40        || limits.max_compute_workgroup_size_x < WORKGROUP_X
41        || limits.max_compute_workgroup_size_y < WORKGROUP_Y
42        || limits.max_compute_workgroup_size_z == 0
43        || width.div_ceil(WORKGROUP_X) > limits.max_compute_workgroups_per_dimension
44        || height.div_ceil(WORKGROUP_Y) > limits.max_compute_workgroups_per_dimension
45        || limits.max_sampled_textures_per_shader_stage == 0
46        || limits.max_storage_buffers_per_shader_stage == 0
47        || limits.max_uniform_buffers_per_shader_stage == 0
48        || limits.max_uniform_buffer_binding_size < std::mem::size_of::<AiPackParams>() as u32
49        || limits.max_buffer_size < std::mem::size_of::<AiPackParams>() as u64
50        || limits.max_bind_groups == 0
51        || limits.max_bindings_per_bind_group < 3
52    {
53        return Err(invalid());
54    }
55    let elements = pixels
56        .checked_mul(u64::from(channels))
57        .filter(|&n| n <= u64::from(u32::MAX))
58        .ok_or_else(invalid)?;
59    let byte_len = elements.checked_mul(4).ok_or_else(invalid)?;
60    if byte_len > limits.max_buffer_size
61        || byte_len > u64::from(limits.max_storage_buffer_binding_size)
62    {
63        return Err(invalid());
64    }
65    Ok(AiPackPlan {
66        byte_len,
67        groups: [width.div_ceil(WORKGROUP_X), height.div_ceil(WORKGROUP_Y), 1],
68    })
69}
70
71const SHADER: &str = r#"
72struct Params {
73    width: u32,
74    height: u32,
75    channels: u32,
76    _pad: u32,
77    scale: f32,
78    mean0: f32,
79    mean1: f32,
80    mean2: f32,
81    mean3: f32,
82    std0: f32,
83    std1: f32,
84    std2: f32,
85    std3: f32,
86    _tail0: f32,
87    _tail1: f32,
88    _tail2: f32,
89}
90@group(0) @binding(0) var<uniform> params: Params;
91@group(0) @binding(1) var source_px: texture_2d<u32>;
92@group(0) @binding(2) var<storage, read_write> output: array<f32>;
93
94@compute @workgroup_size(16, 16)
95fn pack_ai_chw(@builtin(global_invocation_id) gid: vec3<u32>) {
96    if (gid.x >= params.width || gid.y >= params.height) { return; }
97    let pixel = textureLoad(source_px, vec2<i32>(gid.xy), 0);
98    let values = vec4<f32>(pixel);
99    let means = vec4<f32>(params.mean0, params.mean1, params.mean2, params.mean3);
100    let stds = vec4<f32>(params.std0, params.std1, params.std2, params.std3);
101    let index = gid.y * params.width + gid.x;
102    let plane = params.width * params.height;
103    for (var channel = 0u; channel < params.channels; channel++) {
104        output[channel * plane + index] = (values[channel] * params.scale - means[channel]) / stds[channel];
105    }
106}
107"#;
108
109#[repr(C)]
110#[derive(Clone, Copy, Pod, Zeroable)]
111struct AiPackParams {
112    width: u32,
113    height: u32,
114    channels: u32,
115    _pad: u32,
116    scale: f32,
117    mean: [f32; 4],
118    std: [f32; 4],
119    _tail: [f32; 3],
120}
121
122pub(crate) struct AiPackPipeline {
123    layout: wgpu::BindGroupLayout,
124    pipeline: wgpu::ComputePipeline,
125}
126
127pub(crate) fn create_ai_pack_pipeline(device: &wgpu::Device) -> AiPackPipeline {
128    let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
129        label: Some("gpu-ai-pack-bgl"),
130        entries: &[
131            wgpu::BindGroupLayoutEntry {
132                binding: 0,
133                visibility: wgpu::ShaderStages::COMPUTE,
134                ty: wgpu::BindingType::Buffer {
135                    ty: wgpu::BufferBindingType::Uniform,
136                    has_dynamic_offset: false,
137                    min_binding_size: None,
138                },
139                count: None,
140            },
141            wgpu::BindGroupLayoutEntry {
142                binding: 1,
143                visibility: wgpu::ShaderStages::COMPUTE,
144                ty: wgpu::BindingType::Texture {
145                    sample_type: wgpu::TextureSampleType::Uint,
146                    view_dimension: wgpu::TextureViewDimension::D2,
147                    multisampled: false,
148                },
149                count: None,
150            },
151            wgpu::BindGroupLayoutEntry {
152                binding: 2,
153                visibility: wgpu::ShaderStages::COMPUTE,
154                ty: wgpu::BindingType::Buffer {
155                    ty: wgpu::BufferBindingType::Storage { read_only: false },
156                    has_dynamic_offset: false,
157                    min_binding_size: None,
158                },
159                count: None,
160            },
161        ],
162    });
163    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
164        label: Some("gpu-ai-pack-shader"),
165        source: wgpu::ShaderSource::Wgsl(SHADER.into()),
166    });
167    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
168        label: Some("gpu-ai-pack-layout"),
169        bind_group_layouts: &[&layout],
170        push_constant_ranges: &[],
171    });
172    let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
173        label: Some("gpu-ai-pack-pipeline"),
174        layout: Some(&pipeline_layout),
175        module: &shader,
176        entry_point: Some("pack_ai_chw"),
177        compilation_options: wgpu::PipelineCompilationOptions::default(),
178        cache: None,
179    });
180    AiPackPipeline { layout, pipeline }
181}
182
183/// Device-resident planar `f32` tensor with explicit optional readback.
184pub struct GpuAiTensor {
185    buffer: wgpu::Buffer,
186    width: u32,
187    height: u32,
188    channels: u32,
189    byte_len: u64,
190    device_key: std::sync::Arc<()>,
191    receipt: GpuImageReceipt,
192}
193
194impl GpuAiTensor {
195    /// Returns tensor dimensions as CHW.
196    #[must_use]
197    pub const fn shape(&self) -> [u32; 3] {
198        [self.channels, self.height, self.width]
199    }
200
201    /// Returns cumulative transfer and stage accounting.
202    #[must_use]
203    pub const fn receipt(&self) -> &GpuImageReceipt {
204        &self.receipt
205    }
206
207    /// Explicitly reads planar values back to host memory.
208    /// Decodes mapped staging directly into the owned output without an
209    /// intermediate host byte vector; the mapping is released before return.
210    pub fn readback_f32(&mut self, runtime: &WgpuRuntime) -> SpatialResult<Vec<f32>> {
211        if !std::sync::Arc::ptr_eq(&self.device_key, &runtime_device_key(runtime)) {
212            return Err(SpatialError::InvalidArgument(
213                "GpuAiTensor belongs to a different runtime device".to_owned(),
214            ));
215        }
216        let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
217            label: Some("gpu-ai-tensor-readback"),
218            size: self.byte_len,
219            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
220            mapped_at_creation: false,
221        });
222        let mut encoder =
223            runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
224                label: Some("gpu-ai-tensor-readback-encoder"),
225            });
226        encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, self.byte_len);
227        runtime.queue().submit(Some(encoder.finish()));
228        with_staging_bytes(runtime.device(), &staging, self.byte_len as usize, |bytes| {
229            self.receipt.record_device_to_host(self.byte_len, "readback_ai_chw_f32");
230            bytes
231                .chunks_exact(std::mem::size_of::<f32>())
232                .map(|chunk| f32::from_ne_bytes(chunk.try_into().expect("four-byte f32 chunk")))
233                .collect()
234        })
235    }
236
237    /// Returns tensor storage to the runtime pool.
238    pub fn recycle(self, runtime: &WgpuRuntime) {
239        if std::sync::Arc::ptr_eq(&self.device_key, &runtime_device_key(runtime)) {
240            runtime.recycle_storage(self.byte_len, self.buffer);
241        }
242    }
243}
244
245/// Packs a resident image into normalized planar CHW `f32` storage.
246///
247/// Runtime, index, dispatch, binding and output-buffer limits are checked
248/// before allocation or pipeline setup; valid shader math remains unchanged.
249pub fn pack_ai_chw_gpu(
250    runtime: &WgpuRuntime,
251    source: &GpuImage,
252    scale: f32,
253    mean: [f32; 4],
254    std: [f32; 4],
255) -> SpatialResult<GpuAiTensor> {
256    pack_ai_chw_gpu_with_profiler(runtime, source, scale, mean, std, None)
257}
258
259pub(crate) fn pack_ai_chw_gpu_with_profiler(
260    runtime: &WgpuRuntime,
261    source: &GpuImage,
262    scale: f32,
263    mean: [f32; 4],
264    std: [f32; 4],
265    profiler: Option<&mut crate::GpuStageProfiler>,
266) -> SpatialResult<GpuAiTensor> {
267    source.validate_runtime(runtime)?;
268    if !scale.is_finite()
269        || mean.iter().any(|value| !value.is_finite())
270        || std.iter().any(|value| !value.is_finite() || *value == 0.0)
271    {
272        return Err(SpatialError::InvalidArgument(
273            "AI packing scale/mean/std must be finite and std non-zero".to_owned(),
274        ));
275    }
276    let plan =
277        pack_plan(source.width(), source.height(), source.channels(), &runtime.device().limits())?;
278    if let Some(profiler) = &profiler {
279        profiler.validate(runtime, 1)?;
280    }
281    let cache =
282        runtime.image_ai_pack_pipeline.get_or_init(|| create_ai_pack_pipeline(runtime.device()));
283    pack_dispatch(runtime, source, scale, mean, std, plan, cache, &cache.pipeline, profiler)
284}
285
286#[allow(clippy::too_many_arguments)]
287fn pack_dispatch(
288    runtime: &WgpuRuntime,
289    source: &GpuImage,
290    scale: f32,
291    mean: [f32; 4],
292    std: [f32; 4],
293    plan: AiPackPlan,
294    cache: &AiPackPipeline,
295    pipeline: &wgpu::ComputePipeline,
296    mut profiler: Option<&mut crate::GpuStageProfiler>,
297) -> SpatialResult<GpuAiTensor> {
298    let byte_len = plan.byte_len;
299    let output = runtime.buffer_pool().acquire_storage(runtime, "gpu-ai-chw-output", byte_len);
300    let params = AiPackParams {
301        width: source.width(),
302        height: source.height(),
303        channels: source.channels(),
304        _pad: 0,
305        scale,
306        mean,
307        std,
308        _tail: [0.0; 3],
309    };
310    let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
311        label: Some("gpu-ai-pack-params"),
312        contents: bytemuck::bytes_of(&params),
313        usage: wgpu::BufferUsages::UNIFORM,
314    });
315    let source_view = source.view();
316    let bind_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
317        label: Some("gpu-ai-pack-bg"),
318        layout: &cache.layout,
319        entries: &[
320            wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
321            wgpu::BindGroupEntry {
322                binding: 1,
323                resource: wgpu::BindingResource::TextureView(&source_view),
324            },
325            wgpu::BindGroupEntry { binding: 2, resource: output.as_entire_binding() },
326        ],
327    });
328    let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
329        label: Some("gpu-ai-pack-encoder"),
330    });
331    {
332        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
333            label: Some("pack_ai_chw_gpu"),
334            timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, "pack_ai_chw_gpu"),
335        });
336        pass.set_pipeline(pipeline);
337        pass.set_bind_group(0, &bind_group, &[]);
338        pass.dispatch_workgroups(plan.groups[0], plan.groups[1], plan.groups[2]);
339    }
340    runtime.queue().submit(Some(encoder.finish()));
341    let mut receipt = source.receipt().clone();
342    receipt.record_gpu_to_gpu(byte_len, "pack_ai_chw_gpu");
343    Ok(GpuAiTensor {
344        buffer: output,
345        width: source.width(),
346        height: source.height(),
347        channels: source.channels(),
348        byte_len,
349        device_key: runtime_device_key(runtime),
350        receipt,
351    })
352}
353
354#[cfg(all(test, not(target_arch = "wasm32")))]
355#[path = "ai_pack_tests.rs"]
356mod tests;
357
358#[cfg(all(test, not(target_arch = "wasm32")))]
359#[path = "ai_readback_tests.rs"]
360mod readback_tests;