From ca177b24610408ea81c0efe26226db0d53c6e441 Mon Sep 17 00:00:00 2001 From: Justin Chu Date: Tue, 24 Nov 2026 08:44:49 -0800 Subject: [PATCH] Support FLOAT64 in CUDA AffineGrid Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../src/kernels/affine_grid.rs | 130 ++++++++++----- .../src/kernels/data_transform.rs | 149 +++++++++++++----- .../src/kernels/standard_claims.rs | 2 +- .../tests/cuda_parity_batch10_gpu.rs | 70 ++++++++ docs/execution/CUDA_COVERAGE.md | 2 +- 5 files changed, 270 insertions(+), 83 deletions(-) diff --git a/crates/onnx-runtime-ep-cpu/src/kernels/affine_grid.rs b/crates/onnx-runtime-ep-cpu/src/kernels/affine_grid.rs index 6979ee9e97..45a43ff507 100644 --- a/crates/onnx-runtime-ep-cpu/src/kernels/affine_grid.rs +++ b/crates/onnx-runtime-ep-cpu/src/kernels/affine_grid.rs @@ -1,10 +1,12 @@ //! `AffineGrid` sampling-grid generation. +use std::ops::{Add, Div, Mul, Sub}; + use onnx_runtime_ep_api::{EpError, Kernel, KernelFactory, Result, TensorMut, TensorView}; -use onnx_runtime_ir::{Attribute, Node}; +use onnx_runtime_ir::{Attribute, DataType, Node}; use super::{check_arity, to_dense_i64}; -use crate::dtype::{to_dense_f32_widen, write_dense_f32_narrow}; +use crate::dtype::{to_dense, to_dense_f32_widen, write_dense, write_dense_f32_narrow}; pub struct AffineGridKernel { align_corners: bool, @@ -24,16 +26,61 @@ impl KernelFactory for AffineGridFactory { } } -fn coordinate(index: usize, extent: usize, align_corners: bool) -> f32 { - if align_corners { - if extent <= 1 { - 0.0 +fn sampling_grid( + theta: &[T], + batch: usize, + dims: &[usize], + align_corners: bool, + cast: impl Fn(usize) -> T, +) -> Vec +where + T: Copy + Add + Sub + Mul + Div, +{ + if batch == 0 || dims.contains(&0) { + return Vec::new(); + } + let coordinate = |index, extent| { + if align_corners { + if extent <= 1 { + cast(0) + } else { + cast(2) * cast(index) / cast(extent - 1) - cast(1) + } } else { - 2.0 * index as f32 / (extent - 1) as f32 - 1.0 + (cast(2) * cast(index) + cast(1)) / cast(extent) - cast(1) + } + }; + let mut out = Vec::with_capacity(batch * dims.len() * dims.iter().product::()); + if let &[height, width] = dims { + for n in 0..batch { + let t = &theta[n * 6..n * 6 + 6]; + for y in 0..height { + let y = coordinate(y, height); + for x in 0..width { + let x = coordinate(x, width); + out.push(t[0] * x + t[1] * y + t[2]); + out.push(t[3] * x + t[4] * y + t[5]); + } + } + } + } else if let &[depth, height, width] = dims { + for n in 0..batch { + let t = &theta[n * 12..n * 12 + 12]; + for z in 0..depth { + let z = coordinate(z, depth); + for y in 0..height { + let y = coordinate(y, height); + for x in 0..width { + let x = coordinate(x, width); + out.push(t[0] * x + t[1] * y + t[2] * z + t[3]); + out.push(t[4] * x + t[5] * y + t[6] * z + t[7]); + out.push(t[8] * x + t[9] * y + t[10] * z + t[11]); + } + } + } } - } else { - (2.0 * index as f32 + 1.0) / extent as f32 - 1.0 } + out } impl Kernel for AffineGridKernel { @@ -79,39 +126,13 @@ impl Kernel for AffineGridKernel { ))); } - let theta = to_dense_f32_widen("AffineGrid", &inputs[0])?; - let mut out = Vec::with_capacity(expected_shape.iter().product()); - if spatial_rank == 2 { - let (height, width) = (dims[0], dims[1]); - for n in 0..batch { - let t = &theta[n * 6..n * 6 + 6]; - for y in 0..height { - let y = coordinate(y, height, self.align_corners); - for x in 0..width { - let x = coordinate(x, width, self.align_corners); - out.push(t[0] * x + t[1] * y + t[2]); - out.push(t[3] * x + t[4] * y + t[5]); - } - } - } - } else { - let (depth, height, width) = (dims[0], dims[1], dims[2]); - for n in 0..batch { - let t = &theta[n * 12..n * 12 + 12]; - for z in 0..depth { - let z = coordinate(z, depth, self.align_corners); - for y in 0..height { - let y = coordinate(y, height, self.align_corners); - for x in 0..width { - let x = coordinate(x, width, self.align_corners); - out.push(t[0] * x + t[1] * y + t[2] * z + t[3]); - out.push(t[4] * x + t[5] * y + t[6] * z + t[7]); - out.push(t[8] * x + t[9] * y + t[10] * z + t[11]); - } - } - } - } + if inputs[0].dtype == DataType::Float64 { + let theta = to_dense::(&inputs[0])?; + let out = sampling_grid(&theta, batch, &dims, self.align_corners, |i| i as f64); + return write_dense(&mut outputs[0], &out); } + let theta = to_dense_f32_widen("AffineGrid", &inputs[0])?; + let out = sampling_grid(&theta, batch, &dims, self.align_corners, |i| i as f32); write_dense_f32_narrow("AffineGrid", &mut outputs[0], &out) } @@ -125,6 +146,33 @@ mod tests { use super::*; use crate::kernels::testutil::Owned; + #[test] + fn affine_grid_f64_preserves_double_precision() { + let scale = 1.0 + 2f64.powi(-30); + let theta = Owned::f64(&[1, 2, 3], &[scale, 0., 0., 0., 1., scale]); + let size = Owned::i64(&[4], &[1, 1, 1, 3]); + let mut out = Owned::zeros(DataType::Float64, &[1, 1, 3, 2]); + AffineGridKernel { + align_corners: false, + } + .execute(&[theta.view(), size.view()], &mut [out.view_mut()]) + .unwrap(); + let expected = [ + -scale * (2.0 / 3.0), + scale, + 0.0, + scale, + scale * (2.0 / 3.0), + scale, + ]; + for (index, (got, expected)) in out.to_f64().into_iter().zip(expected).enumerate() { + assert!( + (got - expected).abs() <= 1e-14, + "AffineGrid FLOAT64 output {index}: got {got}, expected {expected}" + ); + } + } + #[test] fn affine_grid_bf16_matches_widened_f32_reference() { let theta_vals = [1.0f32, 0.25, -0.5, 0.1, 1.0, 0.75]; diff --git a/crates/onnx-runtime-ep-cuda/src/kernels/data_transform.rs b/crates/onnx-runtime-ep-cuda/src/kernels/data_transform.rs index 5a0349e71b..ceceb46257 100644 --- a/crates/onnx-runtime-ep-cuda/src/kernels/data_transform.rs +++ b/crates/onnx-runtime-ep-cuda/src/kernels/data_transform.rs @@ -51,29 +51,52 @@ extern "C" __global__ void compress_bytes( } } -__device__ __forceinline__ float load_grid_value( +template +__device__ __forceinline__ T load_grid_value( + const void* values, int dtype, unsigned long long index); + +template <> +__device__ __forceinline__ float load_grid_value( const void* values, int dtype, unsigned long long index) { if (dtype == 0) return ((const float*)values)[index]; if (dtype == 1) return __half2float(((const __half*)values)[index]); return __bfloat162float(((const __nv_bfloat16*)values)[index]); } +template <> +__device__ __forceinline__ double load_grid_value( + const void* values, int, unsigned long long index) { + return ((const double*)values)[index]; +} + +template __device__ __forceinline__ void store_grid_value( + void* values, int dtype, unsigned long long index, T value); + +template <> +__device__ __forceinline__ void store_grid_value( void* values, int dtype, unsigned long long index, float value) { if (dtype == 0) ((float*)values)[index] = value; else if (dtype == 1) ((__half*)values)[index] = __float2half_rn(value); else ((__nv_bfloat16*)values)[index] = __float2bfloat16_rn(value); } -__device__ __forceinline__ float grid_coordinate( +template <> +__device__ __forceinline__ void store_grid_value( + void* values, int, unsigned long long index, double value) { + ((double*)values)[index] = value; +} + +template +__device__ __forceinline__ T grid_coordinate( unsigned long long index, unsigned long long extent, int align_corners) { if (align_corners) - return extent <= 1 ? 0.0f - : 2.0f * (float)index / (float)(extent - 1) - 1.0f; - return (2.0f * (float)index + 1.0f) / (float)extent - 1.0f; + return extent <= 1 ? T(0) : T(2) * T(index) / T(extent - 1) - T(1); + return (T(2) * T(index) + T(1)) / T(extent) - T(1); } -extern "C" __global__ void affine_grid_2d( +template +__device__ __forceinline__ void affine_grid_2d_impl( const void* theta, void* output, unsigned long long points, unsigned long long height, unsigned long long width, int dtype, int align_corners) { @@ -81,21 +104,22 @@ extern "C" __global__ void affine_grid_2d( point < points; point += (unsigned long long)gridDim.x * blockDim.x) { const unsigned long long batch_index = point / (height * width); const unsigned long long spatial = point % (height * width); - const float y = grid_coordinate(spatial / width, height, align_corners); - const float x = grid_coordinate(spatial % width, width, align_corners); + const T y = grid_coordinate(spatial / width, height, align_corners); + const T x = grid_coordinate(spatial % width, width, align_corners); const unsigned long long theta_base = batch_index * 6; store_grid_value(output, dtype, point * 2, - load_grid_value(theta, dtype, theta_base) * x - + load_grid_value(theta, dtype, theta_base + 1) * y - + load_grid_value(theta, dtype, theta_base + 2)); + load_grid_value(theta, dtype, theta_base) * x + + load_grid_value(theta, dtype, theta_base + 1) * y + + load_grid_value(theta, dtype, theta_base + 2)); store_grid_value(output, dtype, point * 2 + 1, - load_grid_value(theta, dtype, theta_base + 3) * x - + load_grid_value(theta, dtype, theta_base + 4) * y - + load_grid_value(theta, dtype, theta_base + 5)); + load_grid_value(theta, dtype, theta_base + 3) * x + + load_grid_value(theta, dtype, theta_base + 4) * y + + load_grid_value(theta, dtype, theta_base + 5)); } } -extern "C" __global__ void affine_grid_3d( +template +__device__ __forceinline__ void affine_grid_3d_impl( const void* theta, void* output, unsigned long long points, unsigned long long depth, unsigned long long height, unsigned long long width, int dtype, int align_corners) { @@ -105,21 +129,48 @@ extern "C" __global__ void affine_grid_3d( const unsigned long long batch_index = point / spatial_size; const unsigned long long spatial = point % spatial_size; const unsigned long long plane = height * width; - const float z = grid_coordinate(spatial / plane, depth, align_corners); + const T z = grid_coordinate(spatial / plane, depth, align_corners); const unsigned long long within_plane = spatial % plane; - const float y = grid_coordinate(within_plane / width, height, align_corners); - const float x = grid_coordinate(within_plane % width, width, align_corners); + const T y = grid_coordinate(within_plane / width, height, align_corners); + const T x = grid_coordinate(within_plane % width, width, align_corners); const unsigned long long theta_base = batch_index * 12; for (unsigned long long component = 0; component < 3; ++component) { const unsigned long long base = theta_base + component * 4; store_grid_value(output, dtype, point * 3 + component, - load_grid_value(theta, dtype, base) * x - + load_grid_value(theta, dtype, base + 1) * y - + load_grid_value(theta, dtype, base + 2) * z - + load_grid_value(theta, dtype, base + 3)); + load_grid_value(theta, dtype, base) * x + + load_grid_value(theta, dtype, base + 1) * y + + load_grid_value(theta, dtype, base + 2) * z + + load_grid_value(theta, dtype, base + 3)); } } } + +extern "C" __global__ void affine_grid_2d( + const void* theta, void* output, unsigned long long points, + unsigned long long height, unsigned long long width, + int dtype, int align_corners) { + affine_grid_2d_impl(theta, output, points, height, width, dtype, align_corners); +} + +extern "C" __global__ void affine_grid_3d( + const void* theta, void* output, unsigned long long points, + unsigned long long depth, unsigned long long height, + unsigned long long width, int dtype, int align_corners) { + affine_grid_3d_impl(theta, output, points, depth, height, width, dtype, align_corners); +} + +extern "C" __global__ void affine_grid_2d_f64( + const void* theta, void* output, unsigned long long points, + unsigned long long height, unsigned long long width, int align_corners) { + affine_grid_2d_impl(theta, output, points, height, width, 0, align_corners); +} + +extern "C" __global__ void affine_grid_3d_f64( + const void* theta, void* output, unsigned long long points, + unsigned long long depth, unsigned long long height, + unsigned long long width, int align_corners) { + affine_grid_3d_impl(theta, output, points, depth, height, width, 0, align_corners); +} "#; pub struct CompressFactory { @@ -264,6 +315,32 @@ struct AffineGridKernel { runtime: Arc, } +pub(super) enum AffineGridDtype { + F32Accum(i32), + F64, +} + +impl AffineGridDtype { + pub(super) fn from_theta(dtype: DataType) -> std::result::Result { + match dtype { + DataType::Float32 => Ok(Self::F32Accum(0)), + DataType::Float16 => Ok(Self::F32Accum(1)), + DataType::BFloat16 => Ok(Self::F32Accum(2)), + DataType::Float64 => Ok(Self::F64), + other => Err(format!( + "AffineGrid theta dtype {other:?} unsupported; expected Float32, Float16, BFloat16, or Float64" + )), + } + } + + fn symbols(&self) -> (&'static str, &'static str) { + match self { + Self::F32Accum(_) => ("affine_grid_2d", "affine_grid_3d"), + Self::F64 => ("affine_grid_2d_f64", "affine_grid_3d_f64"), + } + } +} + impl Kernel for AffineGridKernel { fn execute(&self, inputs: &[TensorView], outputs: &mut [TensorMut]) -> Result<()> { if inputs.len() != 2 || outputs.len() != 1 { @@ -294,19 +371,11 @@ impl Kernel for AffineGridKernel { "AffineGrid requires contiguous theta/size/output, Int64 size, and matching float dtypes", )); } - let dtype = match theta.dtype { - DataType::Float32 => 0i32, - DataType::Float16 => 1, - DataType::BFloat16 => 2, - other => { - return Err(not_implemented(format!( - "AffineGrid theta dtype {other:?} (supported: Float32, Float16, BFloat16)" - ))); - } - }; - if dtype != 0 { + let dtype = AffineGridDtype::from_theta(theta.dtype).map_err(not_implemented)?; + if matches!(dtype, AffineGridDtype::F32Accum(1 | 2)) { self.runtime.require_nvrtc_half_headers("AffineGrid")?; } + let (stem_2d, stem_3d) = dtype.symbols(); let batch = theta.shape[0]; let expected = if spatial_rank == 2 { output.shape.len() == 4 && output.shape[0] == batch && output.shape[3] == 2 @@ -327,7 +396,7 @@ impl Kernel for AffineGridKernel { batch .saturating_mul(output.shape[1]) .saturating_mul(output.shape[2]) as u64, - "affine_grid_2d", + stem_2d, ) } else { ( @@ -338,7 +407,7 @@ impl Kernel for AffineGridKernel { .saturating_mul(output.shape[1]) .saturating_mul(output.shape[2]) .saturating_mul(output.shape[3]) as u64, - "affine_grid_3d", + stem_3d, ) }; if points == 0 { @@ -358,11 +427,11 @@ impl Kernel for AffineGridKernel { if spatial_rank == 3 { builder.arg(&depth); } - builder - .arg(&height) - .arg(&width) - .arg(&dtype) - .arg(&align_corners); + builder.arg(&height).arg(&width); + if let AffineGridDtype::F32Accum(ref storage) = dtype { + builder.arg(storage); + } + builder.arg(&align_corners); unsafe { builder.launch(LaunchConfig { grid_dim: (points.div_ceil(BLOCK as u64).clamp(1, 65_535) as u32, 1, 1), diff --git a/crates/onnx-runtime-ep-cuda/src/kernels/standard_claims.rs b/crates/onnx-runtime-ep-cuda/src/kernels/standard_claims.rs index 43e327f7ba..79e776e9bd 100644 --- a/crates/onnx-runtime-ep-cuda/src/kernels/standard_claims.rs +++ b/crates/onnx-runtime-ep-cuda/src/kernels/standard_claims.rs @@ -96,7 +96,7 @@ const CUDA_FLOAT_DTYPES: &[DataType] = &[DataType::Float32, DataType::Float16, D fn affine_grid(node: &Node, input_dtypes: &[DataType]) -> Result<(), String> { required_arity(node, input_dtypes, 2, 1, 1)?; - require_one_of(input_dtypes, 0, CUDA_FLOAT_DTYPES, "theta")?; + super::data_transform::AffineGridDtype::from_theta(input_dtypes[0])?; require_dtype(input_dtypes, 1, DataType::Int64, "size")?; bool_attribute(node, "align_corners") } diff --git a/crates/onnx-runtime-ep-cuda/tests/cuda_parity_batch10_gpu.rs b/crates/onnx-runtime-ep-cuda/tests/cuda_parity_batch10_gpu.rs index 26dec2f64a..23930a5e52 100644 --- a/crates/onnx-runtime-ep-cuda/tests/cuda_parity_batch10_gpu.rs +++ b/crates/onnx-runtime-ep-cuda/tests/cuda_parity_batch10_gpu.rs @@ -38,6 +38,76 @@ fn assert_float_outputs(label: &str, dtype: DataType, cuda: &[Vec], cpu: &[V ); } +#[cfg_attr( + not(feature = "gpu-tests"), + ignore = "requires CUDA device; enable the gpu-tests feature on a CUDA runner" +)] +#[test] +fn affine_grid_f64_matches_cpu_and_preserves_double_precision() { + let ep = require_cuda(); + let dtype = DataType::Float64; + // The scale rounds to 1.0 in f32; non-dyadic coordinates also expose f32 intermediates. + let delta = 2f64.powi(-30); + let scale = 1.0 + delta; + for (align_corners, xs, zs) in [ + (0, [-2.0 / 3.0, 0.0, 2.0 / 3.0], [-0.5, 0.5]), + (1, [-1.0, 0.0, 1.0], [-1.0, 1.0]), + ] { + let attrs = [("align_corners", Attribute::Int(align_corners))]; + let expected_2d: Vec = xs.iter().flat_map(|&x| [scale * x, scale]).collect(); + let expected_3d: Vec = zs + .iter() + .flat_map(|&z| { + xs.into_iter() + .flat_map(move |x| [scale * x + z, z + scale, x - z + delta]) + }) + .collect(); + for (theta_shape, theta, size, output_shape, expected) in [ + ( + vec![1, 2, 3], + vec![scale, 0.25, 0.0, 0.0, 1.0, scale], + vec![1i64, 1, 1, 3], + vec![1, 1, 3, 2], + expected_2d, + ), + ( + vec![1, 3, 4], + vec![ + scale, 0.25, 1.0, 0.0, 0.0, 1.0, 1.0, scale, 1.0, 0.5, -1.0, delta, + ], + vec![1, 1, 2, 1, 3], + vec![1, 2, 1, 3, 3], + expected_3d, + ), + ] { + let inputs = [ + input(dtype, &theta_shape, &theta), + input(DataType::Int64, &[size.len()], &size), + ]; + let outputs = [(dtype, output_shape)]; + let cuda = run_cuda(&ep, "AffineGrid", "", 20, &inputs, &outputs, &attrs); + let cpu = run_cpu("AffineGrid", "", 20, &inputs, &outputs, &attrs); + assert_eq!(cuda[0].len(), expected.len() * size_of::()); + assert_eq!(cpu[0].len(), cuda[0].len()); + for (index, ((cuda, cpu), expected)) in cuda[0] + .chunks_exact(size_of::()) + .zip(cpu[0].chunks_exact(size_of::())) + .zip(expected) + .enumerate() + { + let cuda = f64::from_ne_bytes(cuda.try_into().unwrap()); + let cpu = f64::from_ne_bytes(cpu.try_into().unwrap()); + assert!( + (cuda - expected).abs() <= 1e-14 + && (cpu - expected).abs() <= 1e-14 + && (cuda - cpu).abs() <= 1e-14, + "AffineGrid {theta_shape:?}, align_corners={align_corners}, index {index}: CUDA {cuda}, CPU {cpu}, expected {expected}" + ); + } + } + } +} + #[cfg_attr( not(feature = "gpu-tests"), ignore = "requires CUDA device; enable the gpu-tests feature on a CUDA runner" diff --git a/docs/execution/CUDA_COVERAGE.md b/docs/execution/CUDA_COVERAGE.md index 6fb08e6ef4..b9820384ae 100644 --- a/docs/execution/CUDA_COVERAGE.md +++ b/docs/execution/CUDA_COVERAGE.md @@ -252,7 +252,7 @@ not yet wired) ยท **๐Ÿ”ฌ custom** (needs a fused NVRTC/CUTLASS kernel). | `GatherND` | `` | โœ… | **NVRTC-custom** | Dtype-agnostic indexed copy with Int64 indices (Int32 since opset 29), negative index wrapping, arbitrary tuple depth, and `batch_dims`; eager execution validates indices before launch and graph capture uses the device error latch (`structural.rs`). | | `SpaceToDepth` | `` | โœ… | **NVRTC-custom** | Dtype-agnostic NCHW spatial-block rearrangement with runtime `blocksize`, including multi-channel and empty-batch tensors (`structural.rs`). | | `EyeLike` | `` | โœ… | **NVRTC-custom** | Rank-2 identity-like construction with positive/negative diagonal offsets and the full CPU numeric/bool dtype set, including dtype override (`structural.rs`). | -| `AffineGrid` | `` | โœ… | **NVRTC-custom** | Two- and three-dimensional sampling-grid construction for f32/f16/bf16 theta, including `align_corners` and singleton spatial dimensions (`data_transform.rs`). | +| `AffineGrid` | `` | โœ… | **NVRTC-custom** | Two- and three-dimensional sampling-grid construction for f32/f16/bf16/f64 theta, including `align_corners` and singleton spatial dimensions; f64 uses native double arithmetic (`data_transform.rs`). | | `Compress` | `` | โœ… | **NVRTC-custom** | Dtype-agnostic fixed-width selection with omitted-axis flattening, positive/negative axes, and short conditions (`data_transform.rs`). | | `DynamicQuantizeLinear` | `` | โœ… | **NVRTC-custom** | Float32 per-tensor dynamic uint8 quantization; one block derives min/max, scale, and ties-to-even zero point before quantizing (`quantization.rs`). | | `Pad` | `` | โœ… | **NVRTC-custom** | Dtype-agnostic constant/reflect/edge/wrap padding, negative-pad cropping, and opset-18 subset/negative axes (`pad.rs`). |