From 26b44676716bc82af280f1243d36dce4df57c63b Mon Sep 17 00:00:00 2001 From: Vedaanta Agarwalla Date: Fri, 21 Aug 2026 00:40:06 -0700 Subject: [PATCH] sdpa: require FP32 Stats and default an unset Stats dtype to FP32 The SDPA kernels always compute and store Stats (logsumexp) as FP32, 4 bytes per row. A graph that declared Stats with a narrower dtype -- explicitly, or implicitly by leaving it unset with a non-FP32 io_data_type (fill_from_context assigned the io dtype) -- built and executed fine, and the kernel then wrote FP32 rows past the end of the buffer the caller sized from the declared dtype: silent corruption of adjacent allocations, illegal memory accesses, or kernel launch failures, depending on what the stray writes hit. - Graph::sdpa_internal sets the Stats output dtype to FLOAT at creation, so no later fill can assign the io dtype. - SDPANodeBase::infer_properties_node defaults a still-unset Stats dtype to FLOAT (direct node-construction paths). - SDPANodeBase::post_validate_node rejects an explicitly non-FP32 Stats with GRAPH_NOT_SUPPORTED instead of corrupting memory at execute. - The python IR layer (nodes.py) applies the same FP32 default for SDPA/SDPA_FP8/SDPA_MXFP8 Stats before its generic io-dtype fill. Root-caused from a customer workload where an fp16 Stats buffer half the required size was overwritten by batch >= 1 stats rows, corrupting whichever allocation happened to be adjacent. Co-Authored-By: Claude Fable 5 --- include/cudnn_frontend/graph_interface.h | 3 + .../node/scaled_dot_product_flash_attention.h | 22 ++++- python/cudnn/nodes.py | 10 +++ test/python/test_sdpa_stats_fp32_required.py | 89 +++++++++++++++++++ 4 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 test/python/test_sdpa_stats_fp32_required.py diff --git a/include/cudnn_frontend/graph_interface.h b/include/cudnn_frontend/graph_interface.h index c0a203f991..1b85aacf81 100644 --- a/include/cudnn_frontend/graph_interface.h +++ b/include/cudnn_frontend/graph_interface.h @@ -381,6 +381,9 @@ class Graph : public ICudnn, public INode { if (attributes.generate_stats == true) { sdpa_outputs.Stats = attributes.outputs[SDPA_attributes::output_names::Stats] = output_tensor(attributes.name + "::Stats"); + // Stats is always computed and stored in FP32; setting it at creation keeps + // fill_from_context from assigning the (possibly narrower) io data type. + sdpa_outputs.Stats->set_data_type(DataType_t::FLOAT); } // Dropout mask dump (created conditionally based on dropout parameters) diff --git a/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h b/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h index 75a69c9a2c..39cc9c77d5 100644 --- a/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h +++ b/include/cudnn_frontend/node/scaled_dot_product_flash_attention.h @@ -446,6 +446,13 @@ class SDPANodeBase : public NodeCRTP { auto stats = attributes.outputs.at(output_names::Stats); auto stats_dim = stats->get_dim(); + // Stats is always computed and stored in FP32, regardless of the io data type. + // Default an unset data type here instead of fill_from_context, which would + // wrongly assign the io data type. + if (stats->get_data_type() == DataType_t::NOT_SET) { + stats->set_data_type(DataType_t::FLOAT); + } + if (stats_dim.empty()) { // Fill properties of virtual tensors auto const& p_dim = attributes.inputs[input_names::Q]->get_dim(); @@ -498,11 +505,22 @@ class SDPANodeBase : public NodeCRTP { CUDNN_FE_VALIDATE_STRIDE(output_names::O, attributes.outputs); + auto const& stats_out = attributes.outputs.find(output_names::Stats); + bool const has_stats = (stats_out != attributes.outputs.end()) && (stats_out->second != nullptr); + + // Stats is always computed and stored in FP32. A narrower declared type makes the kernel + // write FP32 values past the end of the user's buffer (silent corruption / IMA), so + // reject it loudly here. An unset data type is allowed: shape inference defaults it to + // FP32 (see infer_properties_node) rather than letting fill_from_context assign the io + // data type. + RETURN_CUDNN_FRONTEND_ERROR_IF(has_stats && stats_out->second->get_data_type() != DataType_t::FLOAT && + stats_out->second->get_data_type() != DataType_t::NOT_SET, + error_code_t::GRAPH_NOT_SUPPORTED, + "The Stats output of sdpa must be an FP32 tensor."); + // Non-ragged Stats layouts other than packed BHSD are not correctly supported prior to 9.26.0. // Runs post shape inference so that an unset Stats layout (always inferred as packed BHSD) // is not rejected. - auto const& stats_out = attributes.outputs.find(output_names::Stats); - bool const has_stats = (stats_out != attributes.outputs.end()) && (stats_out->second != nullptr); if (has_stats && !stats_out->second->get_ragged_offset() && detail::get_backend_version() < 92600) { auto const& stats_dim = stats_out->second->get_dim(); auto const& stats_stride = stats_out->second->get_stride(); diff --git a/python/cudnn/nodes.py b/python/cudnn/nodes.py index 9b407604bc..cfc62cd28d 100644 --- a/python/cudnn/nodes.py +++ b/python/cudnn/nodes.py @@ -56,6 +56,16 @@ def validate(self) -> None: def infer_properties(self, context: "GraphContext") -> None: """Infer unset tensor properties from context and inputs.""" + # SDPA Stats is always computed and stored in FP32, so an unset dtype must + # not inherit a narrower io dtype: the kernel would write 4-byte rows past + # the end of a buffer the caller sized from the declared dtype. + if self.node_type in (NodeType.SDPA, NodeType.SDPA_FP8, NodeType.SDPA_MXFP8): + stats = self.outputs.get("Stats") + if stats is not None and stats.data_type is None: + from ._compiled_module import data_type as _cudnn_data_type + + stats.data_type = _cudnn_data_type.FLOAT + # Fill data types from context for tensor in self.inputs.values(): if tensor and tensor.data_type is None: diff --git a/test/python/test_sdpa_stats_fp32_required.py b/test/python/test_sdpa_stats_fp32_required.py new file mode 100644 index 0000000000..f073ef1f02 --- /dev/null +++ b/test/python/test_sdpa_stats_fp32_required.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Regression test: the SDPA Stats output must be declared FP32. + +The SDPA kernels always compute and store Stats (logsumexp) as FP32, 4 bytes +per row. A graph that declared Stats with a narrower dtype -- either explicitly +or implicitly, by leaving it unset with a non-FP32 ``io_data_type`` -- would +previously build fine and then write FP32 values into a buffer the caller sized +for the narrower dtype, running past its end (silent corruption of adjacent +allocations, illegal memory accesses, or kernel launch failures). + +Now: an unset Stats dtype is inferred as FP32 at shape inference, and an +explicitly non-FP32 Stats dtype is rejected at ``validate()``. +""" + +import cudnn +import pytest +import torch + +pytestmark = pytest.mark.L0 + +_DTYPE = { + torch.float32: cudnn.data_type.FLOAT, + torch.float16: cudnn.data_type.HALF, + torch.bfloat16: cudnn.data_type.BFLOAT16, +} + + +def _build_sdpa_with_stats(io_dtype, stats_dtype): + """Build an SDPA graph with generate_stats=True through validate(). + + ``stats_dtype`` of None leaves the Stats dtype unset, mimicking callers + that rely on inference; the returned stats tensor lets the caller assert + what was inferred. + """ + b, h, s, d = 2, 4, 128, 64 + + graph = cudnn.pygraph( + io_data_type=_DTYPE[io_dtype], + intermediate_data_type=cudnn.data_type.FLOAT, + compute_data_type=cudnn.data_type.FLOAT, + ) + dim = [b, h, s, d] + stride = [h * s * d, s * d, d, 1] + q = graph.tensor(name="q", dim=dim, stride=stride, data_type=_DTYPE[io_dtype]) + k = graph.tensor(name="k", dim=dim, stride=stride, data_type=_DTYPE[io_dtype]) + v = graph.tensor(name="v", dim=dim, stride=stride, data_type=_DTYPE[io_dtype]) + o, stats = graph.sdpa( + name="sdpa", + q=q, + k=k, + v=v, + generate_stats=True, + attn_scale=1.0 / (d**0.5), + ) + o.set_output(True).set_dim(dim).set_stride(stride).set_data_type(_DTYPE[io_dtype]) + stats.set_output(True).set_dim([b, h, s, 1]).set_stride([h * s, s, 1, 1]) + if stats_dtype is not None: + stats.set_data_type(_DTYPE[stats_dtype]) + + graph.validate() + return stats + + +@pytest.mark.parametrize("io_dtype", [torch.float16, torch.bfloat16]) +@pytest.mark.parametrize("stats_dtype", [torch.float16, torch.bfloat16]) +def test_non_fp32_stats_rejected(io_dtype, stats_dtype): + """An explicitly non-FP32 Stats output is rejected at validate(), before + any kernel can write FP32 rows past the end of an undersized buffer.""" + with pytest.raises( + cudnn.cudnnGraphNotSupportedError, match="Stats output of sdpa must be an FP32" + ): + _build_sdpa_with_stats(io_dtype, stats_dtype) + + +@pytest.mark.parametrize("io_dtype", [torch.float16, torch.bfloat16]) +def test_unset_stats_dtype_inferred_fp32(io_dtype): + """An unset Stats dtype must be inferred as FP32, not the io dtype: it is + what tells callers (via the graph/tensor introspection) how large a buffer + to bind, so inheriting a 2-byte io dtype would halve the expected size.""" + stats = _build_sdpa_with_stats(io_dtype, None) + assert stats.get_data_type() == cudnn.data_type.FLOAT + + +def test_fp32_stats_accepted(): + """The required FP32 declaration itself must not be over-rejected.""" + stats = _build_sdpa_with_stats(torch.float16, torch.float32) + assert stats.get_data_type() == cudnn.data_type.FLOAT