Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
c105f9d
Move JAX cuDNN attention to Python graphs and add FP8 support
vcherepanov-nv Oct 11, 2026
4b40acd
Port PyTorch cuDNN attention to the Python frontend
vcherepanov-nv Oct 11, 2026
0c3ef6b
Merge branches 'py-jax' and 'py-pyt' into py-all
vcherepanov-nv Oct 11, 2026
78565fc
Share cuDNN Python attention graph builders across frontends
vcherepanov-nv Oct 11, 2026
f564a84
Fix cuDNN attention workspace, compile probe, and JAX dependencies
vcherepanov-nv Oct 15, 2026
e50b3cf
Fix score-mod callback caching and SM12x attention layouts
vcherepanov-nv Oct 15, 2026
00ac7cf
Align attention statistics metadata across SM12x variants
vcherepanov-nv Oct 15, 2026
56606d2
Merge main into py-all
vcherepanov-nv Oct 16, 2026
13141e3
Fix cuDNN attention support guards and output initialization
vcherepanov-nv Oct 19, 2026
4a70c52
Merge branch 'main' into py-all
vcherepanov-nv Oct 20, 2026
e9e9b8c
Fix build tools imports in JAX dependency tests
vcherepanov-nv Oct 20, 2026
9e0f6e7
Skip deterministic cuDNN execution tests below SM90
vcherepanov-nv Oct 20, 2026
01ffce2
Share MXFP8 attention preparation rules across frontends
vcherepanov-nv Oct 20, 2026
da5c011
Add dense MXFP8 attention to JAX
vcherepanov-nv Oct 20, 2026
a32c9fa
Extend JAX MXFP8 attention layouts and feature coverage
vcherepanov-nv Oct 20, 2026
950cf8d
Reuse prequantized MXFP8 operands in JAX attention
vcherepanov-nv Oct 20, 2026
f5efdfc
Enable packed and prequantized MXFP8 context parallelism
vcherepanov-nv Oct 20, 2026
88fd9d2
Skip unsupported JAX cuDNN attention test configurations
vcherepanov-nv Oct 21, 2026
6bb6482
Require precompiled cuDNN plans during JAX graph deserialization
vcherepanov-nv Oct 27, 2026
710e419
Temporarily disable FROST plans in JAX cuDNN attention
vcherepanov-nv Oct 27, 2026
070c008
Fix PyTorch fused attention precision and inference dropout
vcherepanov-nv Oct 29, 2026
5ab71e0
Fix SBHD paged-cache dimensions in PyTorch attention
vcherepanov-nv Oct 29, 2026
569e9d3
Merge main into py-all
vcherepanov-nv Oct 30, 2026
cad3188
Fall back from fused attention when the cuDNN frontend is unavailable
vcherepanov-nv Oct 30, 2026
ff6d4a0
Cache the fused attention cache-diagnostics level
vcherepanov-nv Oct 30, 2026
8ee7f42
Propagate fused attention setup errors again
vcherepanov-nv Oct 30, 2026
4db3a2a
Merge branch 'main' into py-all
vcherepanov-nv Nov 5, 2026
5b5cf2d
Fix FP8 attention test backward mode isolation
vcherepanov-nv Nov 5, 2026
6737567
Fix host scalar lifetime in JAX cuDNN graph execution
vcherepanov-nv Nov 5, 2026
a2596ce
Fix JAX attention documentation formatting
vcherepanov-nv Nov 6, 2026
0054179
Merge branch 'main' into py-all
vcherepanov-nv Nov 6, 2026
b175ee4
Merge main into py-all
vcherepanov-nv Nov 10, 2026
8598bcd
Simplify cuDNN attention documentation
vcherepanov-nv Nov 10, 2026
a93a55f
Match common attention batch bucketing
vcherepanov-nv Nov 11, 2026
dd4457a
Remove JAX attention cache size limits
vcherepanov-nv Nov 11, 2026
c0890e2
Address PyTorch cuDNN attention review feedback
vcherepanov-nv Nov 11, 2026
5213d19
Retire the legacy PyTorch fused attention wrapper
vcherepanov-nv Nov 11, 2026
5c21002
Address straightforward PyTorch attention review feedback
vcherepanov-nv Nov 11, 2026
5344e71
Remove redundant attention metadata tests
vcherepanov-nv Nov 11, 2026
6727540
Fix JAX cuDNN support checks and reuse common handles
vcherepanov-nv Nov 11, 2026
303d618
Replace the JAX backend binding with a Python enum
vcherepanov-nv Nov 11, 2026
e396500
Support both O precisions in JAX FP8 backward
vcherepanov-nv Nov 11, 2026
d5fdde2
Match main cuDNN attention heuristic selection
vcherepanov-nv Nov 11, 2026
509322f
Group cuDNN attention dispatch and rename MXFP8 helpers
vcherepanov-nv Nov 11, 2026
c290457
Match fused attention bias query and runtime descriptors
vcherepanov-nv Nov 11, 2026
b65fd23
Remove MXFP8 support-surface and scale-byte tests
vcherepanov-nv Nov 12, 2026
9231140
Remove the empty ragged-capacity descriptor test
vcherepanov-nv Nov 12, 2026
b52a40c
Group JAX distributed attention tests
vcherepanov-nv Nov 12, 2026
06536d6
Share cuDNN attention caches across SDPA paths
vcherepanov-nv Nov 12, 2026
d1249bf
Consolidate JAX FP8 attention numerical tests
vcherepanov-nv Nov 12, 2026
bd81acc
Merge main into py-all
vcherepanov-nv Nov 12, 2026
9080bdd
Skip the bias graph cache test in deterministic mode
vcherepanov-nv Nov 12, 2026
303ab18
Fix architecture assumptions in PyTorch attention tests
vcherepanov-nv Nov 12, 2026
b9315cf
Remove JAX build dependency metadata tests
vcherepanov-nv Nov 12, 2026
3bdbc83
Reuse shared graph attributes in JAX Flex Attention
vcherepanov-nv Nov 12, 2026
b8b8b6b
Add Flex Attention cache diagnostics
vcherepanov-nv Nov 12, 2026
c689b37
Merge branch 'main' into py-all
vcherepanov-nv Nov 12, 2026
8ad4833
Fix attention test backend availability checks
vcherepanov-nv Nov 13, 2026
8a11276
Disable autograd in KV-cache inference tests
vcherepanov-nv Nov 14, 2026
6753a87
Remove current-scaled FP8 attention from JAX
vcherepanov-nv Nov 17, 2026
35f763b
Address cuDNN attention review feedback
vcherepanov-nv Nov 20, 2026
aa420fc
Merge branch 'main' into py-all
vcherepanov-nv Nov 20, 2026
5b4995f
Allocate the cuDNN attention scale on the CPU
vcherepanov-nv Nov 20, 2026
86c867a
Clarify MXFP8 dispatch and remove the Frontend 1.29 guard
vcherepanov-nv Nov 20, 2026
8b98fbc
Rename the shared attention tensor spec helper
vcherepanov-nv Nov 20, 2026
799ee8f
Align cuDNN attention and MXFP8 helper names
vcherepanov-nv Nov 21, 2026
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
14 changes: 13 additions & 1 deletion build_tools/jax.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

import os
import warnings
from importlib.metadata import PackageNotFoundError, version as distribution_version
from pathlib import Path
from packaging import version

import setuptools

Expand All @@ -26,7 +28,17 @@

def install_requirements() -> List[str]:
"""Install dependencies for TE/JAX extensions."""
return ["jax>=0.5.3", "flax>=0.7.1", "nvidia-cudnn-frontend>=1.31.0", "triton"]
# Python serializes graphs for C++ built with headers from this distribution.
# Keep the runtime serializer at the exact version used by this build.
try:
frontend_version = distribution_version("nvidia-cudnn-frontend")
except PackageNotFoundError as exc:
raise RuntimeError(
"Building TE/JAX requires nvidia-cudnn-frontend>=1.31.0 to be installed."
) from exc
if version.parse(frontend_version) < version.parse("1.31.0"):
raise RuntimeError("Building TE/JAX requires nvidia-cudnn-frontend>=1.31.0.")
return ["jax>=0.5.3", "flax>=0.7.1", f"nvidia-cudnn-frontend=={frontend_version}", "triton"]


def test_requirements() -> List[str]:
Expand Down
8 changes: 8 additions & 0 deletions docs/api/c/fused_attn.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,12 @@
fused_attn.h
============

.. deprecated:: 2.22

The C fused-attention execution and support-query APIs, including their v2
variants, configuration and parameter accessors, and C++ parameter wrappers,
will be removed in the next major release. Use
:class:`transformer_engine.pytorch.DotProductAttention` or
:func:`transformer_engine.jax.attention.fused_attn` instead.

.. doxygenfile:: fused_attn.h
1 change: 0 additions & 1 deletion docs/api/jax.rst
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ Modules

.. autoapifunction:: transformer_engine.jax.flax.extend_logical_axis_rules


Mixture of Experts
------------------
Router, routing kernels, and grouped dense for MoE layers. See
Expand Down
10 changes: 7 additions & 3 deletions docs/envvars.rst
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ backend-selection overview.

:Type: ``int`` (0, 1 or 2), optionally followed by ``:<ranks>``
:Default: ``0``
:Description: Log FusedAttention graph cache activity to stderr, prefixed with ``[FUSED-ATTN-CACHE]``. ``1`` prints an end-of-run summary of the cache counters and the mean time of each cuDNN build stage. ``2`` additionally traces every event as it happens: each graph built, each graph cuDNN accepts and the cache keeps, each lookup and whether it hit or missed, each first execution that compiles kernels, and each execution. When the launcher exports a rank, only rank 0 logs; append ``:<ranks>`` to override, as in ``1:all`` for level 1 on every rank or ``2:0,3`` for level 2 on ranks 0 and 3.
:Description: Log FusedAttention graph cache activity to stderr, prefixed with ``[FUSED-ATTN-CACHE]``. ``1`` prints a summary of cache counters and build timings at process exit. ``2`` also prints individual events. Ordinary SDPA and Flex Attention contribute to the same per-framework summary; Flex Attention uses the ``f16`` forward/backward counters. Uncacheable callbacks report graph construction and compilation without cache hits, misses, or insertions. At both levels, JAX diagnostics describe graph construction and caching during tracing, rather than each execution of a compiled function. When the launcher exports a rank, only rank 0 logs; append ``:<ranks>`` to override, as in ``1:all`` for level 1 on every rank or ``2:0,3`` for level 2 on ranks 0 and 3.

.. envvar:: NVTE_ALLOW_NONDETERMINISTIC_ALGO

Expand Down Expand Up @@ -282,13 +282,17 @@ FP8 Configuration

:Type: ``int`` (0 or 1)
:Default: ``1``
:Description: Enable FP8 in the backward pass of DotProductAttention. ``1`` = FP8 forward and backward, ``0`` = FP8 forward and FP16/BF16 backward.
:Description: When FP8 attention is enabled in PyTorch or JAX, control whether the backward pass also uses FP8. ``1`` = FP8 forward and backward, ``0`` = FP8 forward and FP16/BF16 backward.

.. envvar:: NVTE_DPA_FP8CS_O_in_F16

:Type: ``int`` (0 or 1)
:Default: ``1``
:Description: For Float8CurrentScaling in DotProductAttention, use FP16/BF16 for the output tensor in the backward pass. ``1`` = use F16/BF16 output in backward, ``0`` = use FP8 output in backward.
:Description: For current-scaled FP8 attention in PyTorch, control the precision
of the forward output tensor consumed by the backward pass. ``1`` = use FP16/BF16
output in backward, ``0`` = quantize it to FP8. This option does not affect MXFP8
attention or FP16/BF16 backward selected with ``NVTE_FP8_DPA_BWD=0``. JAX attention
does not support current tensor scaling and ignores this option.

.. envvar:: NVTE_DPA_FP8_RECIPE

Expand Down
28 changes: 23 additions & 5 deletions docs/examples/jax/attention.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ Transformer Engine's JAX attention APIs support self-attention and
cross-attention with MHA, GQA, and MQA. Inputs can use standard BSHD or packed
THD layouts, with Q/K/V supplied separately or in packed forms.

Common options include causal and padding masks, bias, dropout, sliding-window
attention (SWA), attention sinks, and experimental ``score_mod`` callbacks for
FlexAttention-style customization. The API also supports different Q/K and V
head dimensions, as used by the attention operation after the projection
stages in DeepSeek-style MLA.
Common options include causal and padding masks, bias (including ALiBi),
dropout, sliding-window attention (SWA), attention sinks, and experimental
``score_mod`` callbacks for FlexAttention-style customization. The API also
supports different Q/K and V head dimensions, as used by the attention
operation after the projection stages in DeepSeek-style MLA.

Reusing the same dropout key repeats the mask, including during forward
recomputation.

Comment thread
vcherepanov-nv marked this conversation as resolved.
Resolved
For long contexts, selected BSHD and THD configurations support context
parallelism with Ring or AllGather collectives. Exact fused-kernel availability
Expand All @@ -24,6 +27,21 @@ see the `JAX DotProductAttention API reference
full interface. Choose the tutorial that matches how the sequence dimension is
distributed in your model.

FP8 attention
--------------

The Flax ``DotProductAttention``, ``MultiHeadAttention``, and
``TransformerLayer`` modules support two ``fp8`` settings. Use ``fp8=False``
for FP16/BF16 attention or ``fp8="mxfp8"`` for block-scaled MXFP8 attention.

With MXFP8, ``fused_attn`` and Flax ``DotProductAttention`` can also take
prequantized MXFP8 operands through ``quantized_qkv`` alongside the original
FP16/BF16 Q/K/V. The output and Q/K/V gradients retain the model dtype.

:envvar:`NVTE_FP8_DPA_BWD` controls whether the backward pass also uses FP8.
Availability depends on the GPU, installed cuDNN version, and attention
configuration.

`← Back to the JAX integration overview <../te_jax_integration.html>`_

Pick a tutorial
Expand Down
5 changes: 5 additions & 0 deletions docs/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ Prerequisites
4. `cuDNN 9.12 <https://developer.nvidia.com/cudnn>`__ or later.
5. `cuDNN Frontend 1.31.0 <https://pypi.org/project/nvidia-cudnn-frontend/>`__ or later.

PyTorch and JAX cuDNN attention require ``nvidia-cudnn-frontend`` version
1.31.0 or later. JAX builds pin the runtime dependency to the frontend version
used for the build headers. The JAX extension and frontend Python package must
use matching versions; rebuild the extension after upgrading that package.

Comment thread
vcherepanov-nv marked this conversation as resolved.
Resolved
If the CUDA Toolkit headers are not available at runtime in a standard
installation path, e.g. within `CUDA_HOME`, set
`NVTE_CUDA_INCLUDE_PATH` in the environment.
Expand Down
3 changes: 2 additions & 1 deletion docs/release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

## Fixed Issues

-
- PyTorch fused-attention backend selection checks backward support when gradients are needed,
including in evaluation mode.

## Breaking Changes in This Release

Expand Down
49 changes: 49 additions & 0 deletions tests/cpp/operator/test_splits_to_offsets.cu
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,59 @@
#include <gtest/gtest.h>

#include <transformer_engine/transformer_engine.h>
#include <transformer_engine/utils.h>
#include "../test_common.h"

class SplitsToOffsetsTestSuite : public ::testing::TestWithParam<std::tuple<size_t, int64_t>> {};

TEST(SequenceLengthsTest, ConvertAndPad) {
using namespace transformer_engine;
for (const size_t batch : {0, 3, 129, 513}) {
for (const size_t padding : {0, 7}) {
const size_t capacity = batch + padding;
SCOPED_TRACE(::testing::Message() << "batch=" << batch << ", capacity=" << capacity);
test::Tensor cu_q("cu_q", std::vector<size_t>{batch + 1}, DType::kInt32);
test::Tensor cu_kv("cu_kv", std::vector<size_t>{batch + 1}, DType::kInt32);
test::Tensor seq_q("seq_q", std::vector<size_t>{capacity}, DType::kInt32);
test::Tensor seq_kv("seq_kv", std::vector<size_t>{capacity}, DType::kInt32);
auto *q = cu_q.rowwise_cpu_dptr<int32_t>();
auto *kv = cu_kv.rowwise_cpu_dptr<int32_t>();
q[0] = kv[0] = 0;
for (size_t i = 0; i < batch; ++i) {
q[i + 1] = q[i] + i % 7;
kv[i + 1] = kv[i] + i % 11;
}
cu_q.from_cpu();
cu_kv.from_cpu();
nvte_cu_seqlens_to_actual_seqlens(cu_q.data(), cu_kv.data(), seq_q.data(), seq_kv.data(),
nullptr);
seq_q.to_cpu();
seq_kv.to_cpu();
for (size_t i = 0; i < capacity; ++i) {
EXPECT_EQ(seq_q.rowwise_cpu_dptr<int32_t>()[i], i < batch ? i % 7 : 0);
EXPECT_EQ(seq_kv.rowwise_cpu_dptr<int32_t>()[i], i < batch ? i % 11 : 0);
}
}
}
}

TEST(SequenceLengthsTest, RejectInvalidMetadata) {
using namespace transformer_engine;
test::Tensor cu("cu", std::vector<size_t>{3}, DType::kInt32);
test::Tensor lengths("lengths", std::vector<size_t>{2}, DType::kInt32);
test::Tensor small("small", std::vector<size_t>{1}, DType::kInt32);
test::Tensor wrong_type("wrong_type", std::vector<size_t>{2}, DType::kInt64);
test::Tensor wrong_rank("wrong_rank", std::vector<size_t>{1, 2}, DType::kInt32);
EXPECT_ANY_THROW(nvte_cu_seqlens_to_actual_seqlens(cu.data(), small.data(), lengths.data(),
lengths.data(), nullptr));
EXPECT_ANY_THROW(nvte_cu_seqlens_to_actual_seqlens(cu.data(), cu.data(), small.data(),
small.data(), nullptr));
EXPECT_ANY_THROW(nvte_cu_seqlens_to_actual_seqlens(cu.data(), cu.data(), wrong_type.data(),
wrong_type.data(), nullptr));
EXPECT_ANY_THROW(nvte_cu_seqlens_to_actual_seqlens(cu.data(), cu.data(), wrong_rank.data(),
wrong_rank.data(), nullptr));
}

TEST_P(SplitsToOffsetsTestSuite, TestSplitsToOffsets) {
const size_t num_tensors = std::get<0>(GetParam());
const int64_t logical_last_dim = std::get<1>(GetParam());
Expand Down
165 changes: 165 additions & 0 deletions tests/jax/test_distributed_fused_attn.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import pytest
import jax
import jax.numpy as jnp
import numpy as np
from jax.sharding import Mesh, NamedSharding, PartitionSpec
from jax import random
from distributed_test_base import (
generate_configs,
Expand All @@ -21,10 +23,21 @@
ScoreModFusedAttnRunner,
_has_cudnn_frontend_python,
)
from test_mxfp8_attention import (
_attention as _mxfp8_attention,
_reference as _mxfp8_reference,
_require_mxfp8,
_pack as _pack_mxfp8,
_unpack as _unpack_mxfp8,
)
from utils import pytest_parametrize_wrapper
from transformer_engine.jax import autocast
from transformer_engine.jax.sharding import MeshResource, global_shard_guard
from transformer_engine_jax import get_cudnn_version, get_device_compute_capability
from transformer_engine.jax.attention import (
is_fused_attn_kernel_available,
fused_attn,
quantize_attention_qkv,
AttnBiasType,
AttnMaskType,
AttnSoftmaxType,
Expand Down Expand Up @@ -919,3 +932,155 @@ def test(self, cp_size, shape, qkv_format, reorder_strategy, stripe_size):
inversed = inverse(reordered, reorder_strategy, cp_size, seq_dim, stripe_size)

assert jnp.array_equal(inversed, ref)


@pytest.mark.parametrize("strategy", [CPStrategy.ALL_GATHER, CPStrategy.RING])
def test_cudnn_python_context_parallel(strategy):
"""Two-device context parallel attention agrees with FP32 forward and backward."""
if jax.local_device_count() < 2:
pytest.skip("Context parallel attention requires two GPUs.")
mesh = Mesh(np.asarray(jax.local_devices()[:2]), ("cp",))
sharding = NamedSharding(mesh, PartitionSpec(None, "cp", None, None))
q = jnp.full((2, 256, 2, 64), 0.5, jnp.bfloat16)
v = jnp.zeros_like(q).at[:, ::2, :, 0].set(1.0)
arrays = tuple(jax.device_put(value, sharding) for value in (q, q, v))

def attention(arrays):
return fused_attn(
arrays,
None,
None,
None,
attn_bias_type=AttnBiasType.NO_BIAS,
attn_mask_type=AttnMaskType.NO_MASK,
qkv_layout=QKVLayout.BSHD_BSHD_BSHD,
softmax_type=AttnSoftmaxType.VANILLA_SOFTMAX,
scaling_factor=0.125,
dropout_probability=0.0,
is_training=True,
context_parallel_axis="cp",
context_parallel_strategy=strategy,
)

def reference(arrays):
query, key, value = (tensor.astype(jnp.float32) for tensor in arrays)
scores = jnp.einsum("bqhd,bkhd->bhqk", query, key) * 0.125
return jnp.einsum("bhqk,bkhd->bqhd", jax.nn.softmax(scores, axis=-1), value)

expected = jax.jit(reference)(arrays)
expected_grads = jax.jit(jax.grad(lambda xs: jnp.sum(reference(xs))))(arrays)
with mesh, autocast(mesh_resource=MeshResource(cp_resource="cp")):
actual = jax.jit(attention)(arrays)
actual_grads = jax.jit(jax.grad(lambda xs: jnp.sum(attention(xs))))(arrays)
np.testing.assert_allclose(actual, expected, rtol=5e-3, atol=5e-3)
for actual, expected in zip(actual_grads, expected_grads):
np.testing.assert_allclose(actual, expected, rtol=1e-2, atol=1e-2)


@pytest.mark.parametrize("axis", ("dp", "tp", "replica"))
def test_mxfp8_prequantized_sharding(axis):
"""Per-head scale packing happens after data/tensor parallel partitioning."""
_require_mxfp8()
if jax.local_device_count() < 2:
pytest.skip("Requires two GPUs for attention sharding")
mesh = jax.sharding.Mesh(np.array(jax.local_devices()[:2]), (axis,))
spec = (
(axis, None, None, None)
if axis == "dp"
else (None, None, axis, None) if axis == "tp" else ()
)
sharding = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec(*spec))
q = jnp.full((2, 128, 4, 64), 0.5, jnp.bfloat16)
kv = q[:, :, :2]
v = jnp.zeros_like(kv).at[:, ::2, :, 0].set(1.0)
inputs = (q, kv, v)
loss = lambda xs: _mxfp8_attention(xs, quantized_qkv=quantize_attention_qkv(xs)).sum()
expected = jax.jit(jax.value_and_grad(loss))(inputs)
resource = MeshResource() if axis == "replica" else MeshResource(**{axis + "_resource": axis})
with jax.set_mesh(mesh), global_shard_guard(resource):
actual = jax.jit(jax.value_and_grad(loss), in_shardings=((sharding,) * 3,))(inputs)
for value, ref in zip(jax.tree.leaves(actual), jax.tree.leaves(expected)):
np.testing.assert_array_equal(value, ref)


@pytest.mark.parametrize("strategy", (CPStrategy.ALL_GATHER, CPStrategy.RING))
@pytest.mark.parametrize(
"kind,cp_size,fp8_backward,layout,prequantized",
[
("dense", 2, False, QKVLayout.BSHD_BSHD_BSHD, False),
("dense", 4, True, QKVLayout.BSHD_BSHD_BSHD, False),
("causal", 2, True, QKVLayout.BSHD_BSHD_BSHD, False),
("causal", 4, False, QKVLayout.BSHD_BSHD_BSHD, False),
("balanced_causal", 2, False, QKVLayout.BSHD_BSHD_BSHD, False),
("balanced_causal", 4, True, QKVLayout.BSHD_BSHD_BSHD, False),
("dense", 2, True, QKVLayout.BS3HD, False),
("dense", 2, True, QKVLayout.BSHD_BS2HD, False),
("dense", 2, True, QKVLayout.BS3HD, True),
("dense", 2, True, QKVLayout.BSHD_BS2HD, True),
("dense", 2, True, QKVLayout.BSHD_BSHD_BSHD, True),
],
)
def test_mxfp8_context_parallel(
strategy, kind, cp_size, fp8_backward, layout, prequantized, monkeypatch
):
"""CP masks, load balancing and packed/supplied inputs agree with global FP32 attention."""
from transformer_engine.jax.cpp_extensions.attention import reorder_causal_dual_chunk_swap

_require_mxfp8()
if jax.local_device_count() < cp_size:
pytest.skip(f"Requires {cp_size} GPUs for context parallelism")
monkeypatch.setenv("NVTE_FP8_DPA_BWD", "1" if fp8_backward else "0")
mesh = jax.sharding.Mesh(np.asarray(jax.local_devices()[:cp_size]), ("cp",))
sharding = jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec(None, "cp", None, None))
length = 256 * cp_size
rng = np.random.default_rng(42)
q = jnp.asarray(rng.choice([-0.5, 0.5], (1, length, 4, 64)), jnp.bfloat16)
kv_shape = q.shape if layout.is_qkvpacked() else (1, length, 2, 64)
k = jnp.asarray(rng.choice([-0.5, 0.5], kv_shape), q.dtype)
v = jnp.asarray(rng.choice([-1.0, 1.0], kv_shape), q.dtype)
# Nonuniform rank-local keys and values expose missing communication and reordering.
amplitude = jnp.exp2((jnp.arange(length) // 128) % 4 - 2).astype(q.dtype)
k *= amplitude[None, :, None, None]
v *= amplitude[None, :, None, None]
weight = jnp.asarray(rng.choice([-1.0, 1.0], q.shape), q.dtype)
inputs = _pack_mxfp8((q, k, v), layout)
balanced = kind == "balanced_causal"
causal = kind != "dense"
mask = (
jnp.arange(length)[None, :, None] >= jnp.arange(length)[None, None, :] if causal else None
)
reference = lambda xs: _mxfp8_reference(_unpack_mxfp8(xs, layout), mask)
expected = jax.jit(reference)(inputs)
ref_grads = jax.jit(jax.grad(lambda xs: (reference(xs) * weight).sum()))(inputs)
reorder = lambda x, reverse: reorder_causal_dual_chunk_swap(x, cp_size, 1, reverse)
local_weight = reorder(weight, False) if balanced else weight
if balanced:
inputs = tuple(reorder(x, False) for x in inputs)

def attention(xs):
supplied = quantize_attention_qkv(_unpack_mxfp8(xs, layout)) if prequantized else None
return _mxfp8_attention(
xs,
qkv_layout=layout,
quantized_qkv=supplied,
attn_mask_type=AttnMaskType.CAUSAL_MASK if causal else AttnMaskType.NO_MASK,
context_parallel_axis="cp",
context_parallel_strategy=strategy,
context_parallel_causal_load_balanced=balanced,
)

with jax.set_mesh(mesh), global_shard_guard(MeshResource(cp_resource="cp")):
actual = jax.jit(attention, in_shardings=((sharding,) * len(inputs),))(inputs)
grads = jax.jit(
jax.grad(lambda xs: (attention(xs) * local_weight).sum()),
in_shardings=((sharding,) * len(inputs),),
)(inputs)
if balanced:
actual = reorder(actual, True)
grads = tuple(reorder(x, True) for x in grads)
relative_error = lambda a, b: float(
jnp.linalg.norm(a.astype(jnp.float32) - b) / jnp.linalg.norm(b)
)
assert relative_error(actual, expected) < 0.04
for grad, ref in zip(grads, ref_grads):
assert relative_error(grad, ref) < 0.08
Loading
Loading