Skip to content

Add Tokamax ring MHA attention for TPU#4266

Open
huytransformer wants to merge 4 commits into
AI-Hypercomputer:mainfrom
huytransformer:htn/tokamax-ring-tpu
Open

Add Tokamax ring MHA attention for TPU#4266
huytransformer wants to merge 4 commits into
AI-Hypercomputer:mainfrom
huytransformer:htn/tokamax-ring-tpu

Conversation

@huytransformer

@huytransformer huytransformer commented Jun 25, 2026

Copy link
Copy Markdown
Collaborator

Description

Adds TPU support for context_parallel_strategy=ring in Flash attention using Tokamax Splash.

The ring path keeps Q sequence-sharded, rotates K/V blocks across the context axis, and combines the partial attention results using online softmax. This PR uses the Tokamax Splash components and includes the MaxText integration, config validation, and sharding checks.

Sequence packing and CP load balancing are not enabled in this PR.

Tests

Ran:

python3 -m pytest tests/unit/tokamax_ring_attention_test.py
python3 -m pytest tests/unit/tokamax_splash_attention_mask_test.py
python3 -m pytest tests/unit/configs_value_test.py -k tpu_tokamax_ring
python3 -m pytest tests/unit/attention_test.py -k tpu_flash_attention_ring_context_parallel

Checklist

Before submitting this PR, please make sure (put X in square brackets):

  • I have performed a self-review of my code. For an optional AI review, add the gemini-review label.
  • I have necessary comments in my code, particularly in hard-to-understand areas.
  • I have run end-to-end tests tests and provided workload links above if applicable.
  • I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in our documentation.

# Conflicts:
#	src/maxtext/layers/attention_op.py
if keys["use_qk_clip"]:
raise ValueError("TPU Tokamax ring attention does not support QK-Clip statistics yet.")
if keys["enable_dropout"] and keys["dropout_rate"] > 0.0:
raise ValueError("TPU Tokamax ring attention does not support dropout yet.")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pyconfig_deprecated.py is no longer in use.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

if self.use_qk_clip:
raise ValueError("TPU Tokamax ring attention does not support QK-Clip statistics yet.")
if self.enable_dropout and self.dropout_rate > 0.0:
raise ValueError("TPU Tokamax ring attention does not support dropout yet.")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a great, exhaustive list of early stopping conditions (we need more of this!). As a quick refactoring idea: what do you think about mapping these out in a dictionary instead of using a long chain of if statements?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a neat idea.
I saw people mostly use if....raise individually in this file so I didn't bring in more abstractions. I will make changes though if you insist but it's a P2 for now : )

indexer_mask=indexer_mask,
use_ragged_attention=use_ragged_attention,
record_max_logits=record_max_logits,
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move the validation logic to initi of the module

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed

Comment thread src/maxtext/layers/attention_op.py Outdated
axis_names_kv=axis_names_kv,
dkv_dim_q=3,
dkv_dim_kv=3,
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move validation logic to init instead of call

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed

Comment thread src/maxtext/layers/attention_op.py
Comment thread tests/unit/attention_test.py Outdated
mha_generic_flash_cp_output = jax.device_get(mha_generic_flash_cp_output)

self.assertTrue(
jax.numpy.allclose(mha_generic_output, mha_generic_flash_cp_output, rtol=1e-01, atol=1e-01, equal_nan=False),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are 1e-01 the best we can do? maybe try using dtype=float32 and see if we can reduce them

@huytransformer huytransformer Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1e-1 was due to following other similar instances for comparing cross kernels. Some examples: attention_test.py line 674 (dot_product vs flash), 881 (dot_product vs flash_cp) , 1872 (MLA CP dot_product vs flash+cp).

Edited:
This is the best we can go afaik

# Forward
rtol=1e-2, atol=1e-2
# Backward
rtol=1e-2, atol=1e-7

Comment thread .pre-commit-config.yaml Outdated
hooks:
- id: pyink
exclude: src/maxtext/input_pipeline/protos/
exclude: src/maxtext/input_pipeline/protos/|src/maxtext/kernels/tokamax_splash_attention/(base|ring_attention_kernel|splash_attention_kernel|splash_attention_mask|splash_attention_mask_info)\.py

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not necessary, please do not change this file

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

Comment thread codecov.yml Outdated
- "src/maxtext/kernels/tokamax_splash_attention/ring_attention_kernel.py"
- "src/maxtext/kernels/tokamax_splash_attention/splash_attention_kernel.py"
- "src/maxtext/kernels/tokamax_splash_attention/splash_attention_mask.py"
- "src/maxtext/kernels/tokamax_splash_attention/splash_attention_mask_info.py"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why making this change?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just wanted codecov to ignore the bulk from tokamax but ya we don't have to touch this

from maxtext.kernels.attention import tokamax_ring_attention


class TokamaxRingAttentionTest(absltest.TestCase):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think many of these tests are ran on CPU instead of TPU. For shape checks we could use AOT instead of real runs. We could chat more about details.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for TPU previously we only had forward test and I added backward test.

@huytransformer huytransformer requested a review from xibinliu as a code owner July 9, 2026 17:14
@huytransformer huytransformer force-pushed the htn/tokamax-ring-tpu branch 3 times, most recently from 45e5f89 to 37b508c Compare July 10, 2026 21:30
)
if context_parallel_size > 1 and self.context_parallel_strategy.lower() == "ring":
if "gpu" not in self.hardware:
context_parallel_strategy = self.context_parallel_strategy.lower()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: alternatively we can create Enum for context parallel strategy, e.g. in https://github.com/AI-Hypercomputer/maxtext/blob/main/src/maxtext/common/common_types.py, to avoid mis-spell.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that would touch several paths so perhaps a separate PR?

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tokamax ring attention helpers."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add references in tokamax

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

# limitations under the License.
"""Tokamax SplashAttention runtime.

These modules are adapted from OpenXLA Tokamax SplashAttention.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

provide link

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this file necessary to clone? Looks like it is mask-unrelated? I am inclined to minimize cloning as much as possible.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll respond below

return f"splash_{attention_type}_{phase}{segments}{residuals}"


# Splash attention implementation

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

emmm empty?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not empty. I didn't change anything about this part from tokamax 0.0.12. It just means it owns the stuff below

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this file necessary to clone?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll respond below

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this file necessary to clone?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll respond below

@NuojCheng NuojCheng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM. I am a little scared by the scale of cloned codes. I have two suggestions on editing the PR description:

  1. Please specify reasons why cloning tokamax ring/splash and making local changes are necessary;
  2. Please provide example maxtext command for running ring attention, with performance comparison, see example description of PR#2783, also add link to your doc.

@NuojCheng NuojCheng changed the title Add Tokamax ring attention for TPU Add Tokamax ring MLA attention for TPU Jul 10, 2026
@NuojCheng NuojCheng changed the title Add Tokamax ring MLA attention for TPU Add Tokamax ring MHA attention for TPU Jul 10, 2026
…kamax-ring-tpu

# Conflicts:
#	src/maxtext/configs/pyconfig_deprecated.py
#	src/maxtext/layers/attention_op.py
#	tests/unit/configs_value_test.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants