Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions include/cudnn_frontend/graph_interface.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
22 changes: 20 additions & 2 deletions include/cudnn_frontend/node/scaled_dot_product_flash_attention.h
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,13 @@ class SDPANodeBase : public NodeCRTP<DerivedT> {
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();
Expand Down Expand Up @@ -498,11 +505,22 @@ class SDPANodeBase : public NodeCRTP<DerivedT> {

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();
Expand Down
10 changes: 10 additions & 0 deletions python/cudnn/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
89 changes: 89 additions & 0 deletions test/python/test_sdpa_stats_fp32_required.py
Original file line number Diff line number Diff line change
@@ -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