Fix EAGLE TTT attention-mask reuse across sequence lengths (#3230)

### What does this PR do?

Type of change: Bug fix.

EAGLE caches training-time-test attention masks by TTT step. When a
later batch has a different sequence length, the cached mask has the
previous shape and SDPA fails with a tensor-size mismatch.

Invalidate the cache when sequence length, device, mask dtype or
attention backend changes. Masks are still reused across TTT steps and
batches with the same context. Only the current context is retained, so
changing lengths does not accumulate old masks. Batch size is not part
of the context because these masks broadcast across the batch dimension.
Use the current draft input tensor's dtype and device for both cache
lookup and mask construction. This avoids stale config dtypes after a
checkpoint save or dtype conversion and places Flex masks with the draft
inputs.

### Usage

No configuration changes. This fixes EAGLE training that receives
different sequence lengths between batches.

### Testing

- A tiny converted EAGLE3 model runs real CPU SDPA forward/backward at
lengths 8, 4 and 8, including consecutive same-length batches with
different batch sizes. The test checks mask shapes, bounded retention
and reuse across batches.
- Saving a native checkpoint between identical batches preserves
projected logits, loss, trainable gradients and cached masks. Later
length and attention-backend changes rebuild the mask correctly.
- The dtype case saves BF16, converts to FP32, then runs real SDPA with
and without CPU autocast. It checks that dtype changes rebuild masks.
- The device case places the first base parameter on meta while the
draft remains on CPU and checks that Flex mask tensors use the draft
device.
- Both regression cases fail before the follow-up fix and pass with it
(PyTorch 2.13.0, Transformers 5.18.0).
- Scoped pre-commit checks pass, including Ruff, mypy and Bandit.

### Before your PR is "Ready for review"

- Is this change backward compatible?: ✅ No configuration or
checkpoint-format change.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in CONTRIBUTING.md?: N/A.
- Did you write any new necessary tests?: ✅ One offline regression.
- Did you update Changelog?: N/A. Focused bug fix.
- Did you get Claude approval on this PR?: ❌ Pending.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Attention masks are now cached separately for different sequence
lengths, devices, data types, and attention implementations. Switching
context clears cached masks, and newly created masks use the active
device and data type.
* **Tests**
* Added checks for mask reuse and rebuilding across batch sizes,
sequence lengths, and data types, as well as mask shape and
flex-attention mask creation.
* Added checks that cached masks and training outputs remain intact
after saving a checkpoint.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Sandeep Agrawal <sandeepa@nvidia.com>
This commit is contained in:
Sandeep Agrawal
2026-11-06 16:34:56 +08:00
committed by GitHub
parent 77ef48794f
commit 09a14b9ae8
2 changed files with 146 additions and 13 deletions
+26 -13
View File
@@ -425,12 +425,21 @@ class HFEagleModel(EagleModel):
self._activate_torch_compile()
self._cached_attn_blk_masks = {}
self._cached_attn_blk_mask_context = None
def _get_ttt_attention_mask(self, batch_size, seq_length, ttt_step):
def _get_ttt_attention_mask(self, batch_size, seq_length, ttt_step, *, device, dtype):
context = (seq_length, device, dtype, self.eagle_config._attn_implementation)
if context != self._cached_attn_blk_mask_context:
self._cached_attn_blk_masks.clear()
self._cached_attn_blk_mask_context = context
# compile and cached flex attention masks in first call
if ttt_step not in self._cached_attn_blk_masks:
self._cached_attn_blk_masks.update(
{ttt_step: self._compute_ttt_attention_mask(batch_size, seq_length, ttt_step)}
{
ttt_step: self._compute_ttt_attention_mask(
batch_size, seq_length, ttt_step, device=device, dtype=dtype
)
}
)
return self._cached_attn_blk_masks[ttt_step]
@@ -547,20 +556,18 @@ class HFEagleModel(EagleModel):
)
def _compute_ttt_attention_mask(
self, batch_size, seq_length, ttt_step
self, batch_size, seq_length, ttt_step, *, device, dtype
) -> BlockMask | torch.Tensor:
"""Return TTT attention_mask tensor of type BlockMask or Tensor depends on eagle attn impl."""
msk_func = get_ttt_msk_func(seq_length, ttt_step)
dtype = (
getattr(self._base_llm_config, "dtype", None)
or self.eagle_module.layers[0].input_layernorm.weight.dtype
)
dtypemin = torch.finfo(dtype).min
q_len = seq_length
kv_len = seq_length * (1 + ttt_step)
if self.eagle_config._attn_implementation == "flex_attention":
# Return block mask for flex attention
block_mask = create_block_mask(msk_func, B=None, H=None, Q_LEN=q_len, KV_LEN=kv_len)
block_mask = create_block_mask(
msk_func, B=None, H=None, Q_LEN=q_len, KV_LEN=kv_len, device=device
)
return block_mask
else:
# Return tensor mask for non-flex attention
@@ -569,10 +576,10 @@ class HFEagleModel(EagleModel):
None,
torch.arange(q_len).view(1, 1, q_len, 1),
torch.arange(kv_len).view(1, 1, 1, kv_len),
).to(self.device)
tensor_mask = torch.full_like(
tensor_mask, 0, dtype=dtype, device=self.device
).masked_fill(~tensor_mask, dtypemin)
).to(device)
tensor_mask = torch.full_like(tensor_mask, 0, dtype=dtype, device=device).masked_fill(
~tensor_mask, dtypemin
)
return tensor_mask
@@ -767,7 +774,13 @@ class HFEagleModel(EagleModel):
eagle_attention_mask = (
eagle_attn_mask_0
if self.eagle_mix_hidden_states or ttt_step == 0
else self._get_ttt_attention_mask(b, seq_length, ttt_step)
else self._get_ttt_attention_mask(
b,
seq_length,
ttt_step,
device=eagle_input_hiddens.device,
dtype=eagle_input_hiddens.dtype,
)
)
# Under CP the dense mask is unused and fatal (plain tensor vs DTensor scores);
# causal masking comes from is_causal and TTT masking from the ring-attention patch.
@@ -0,0 +1,120 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# 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.
"""Tests for cached EAGLE training-time attention masks."""
from copy import deepcopy
import pytest
import torch
from _test_utils.torch.transformers_models import get_tiny_llama
from torch.nn.attention.flex_attention import BlockMask
import modelopt.torch.speculative as mtsp
from modelopt.torch.speculative.config import EAGLE3_DEFAULT_CFG
@pytest.mark.parametrize("context_change", ["dtype", "device"])
def test_ttt_attention_mask_cache_with_variable_lengths(tmp_path, context_change):
"""Reuse masks across batches and checkpoint saves, rebuilding when context changes."""
model = get_tiny_llama(dtype=torch.float32)
config = deepcopy(EAGLE3_DEFAULT_CFG["config"])
config["eagle_architecture_config"].update(
draft_vocab_size=model.config.vocab_size,
intermediate_size=32,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=8,
)
config.update(eagle_ttt_steps=3, eagle_use_torch_compile=False)
mtsp.convert(model, mode=[("eagle", config)])
model.train()
projected_logits = []
handle = model._base_model_lm_head.register_forward_hook(
lambda _module, _inputs, logits: projected_logits.append(logits.detach().clone())
)
previous_masks = None
previous_length = None
for batch_size, seq_length in ((1, 8), (2, 8), (2, 4), (1, 8)):
input_ids = torch.randint(0, model.config.vocab_size, (batch_size, seq_length))
output = model(input_ids=input_ids, labels=input_ids)
assert torch.isfinite(output.loss)
output.loss.backward()
if previous_masks is None:
masks_before_save = dict(model._cached_attn_blk_masks)
expected_logits = list(projected_logits)
projected_logits.clear()
expected_gradients = {
name: parameter.grad.clone()
for name, parameter in model.named_parameters()
if parameter.grad is not None
}
model.zero_grad(set_to_none=True)
model.save_pretrained(tmp_path)
restored_output = model(input_ids=input_ids, labels=input_ids)
assert all(
model._cached_attn_blk_masks[step] is mask
for step, mask in masks_before_save.items()
)
torch.testing.assert_close(projected_logits, expected_logits)
torch.testing.assert_close(restored_output.loss, output.loss)
restored_output.loss.backward()
for name, parameter in model.named_parameters():
if name in expected_gradients:
torch.testing.assert_close(parameter.grad, expected_gradients[name])
model.zero_grad(set_to_none=True)
assert len(model._cached_attn_blk_masks) == 2
for step in (1, 2):
mask = model._get_ttt_attention_mask(
batch_size, seq_length, step, device=input_ids.device, dtype=torch.float32
)
assert mask.shape == (1, 1, seq_length, seq_length * (step + 1))
assert (
model._get_ttt_attention_mask(
batch_size, seq_length, step, device=input_ids.device, dtype=torch.float32
)
is mask
)
if previous_length == seq_length:
assert mask is previous_masks[step]
previous_masks = dict(model._cached_attn_blk_masks)
previous_length = seq_length
projected_logits.clear()
handle.remove()
if context_change == "dtype":
model.bfloat16()
model.save_pretrained(tmp_path)
model.float()
input_ids = torch.randint(0, model.config.vocab_size, (1, 8))
with torch.autocast("cpu", dtype=torch.bfloat16):
assert torch.isfinite(model(input_ids=input_ids, labels=input_ids).loss)
masks_before_cast = dict(model._cached_attn_blk_masks)
assert all(mask.dtype == torch.bfloat16 for mask in masks_before_cast.values())
assert torch.isfinite(model(input_ids=input_ids, labels=input_ids).loss)
assert all(
mask.dtype == torch.float32 and mask is not masks_before_cast[step]
for step, mask in model._cached_attn_blk_masks.items()
)
else:
# A split base must not place draft masks on its first parameter's device.
model.get_input_embeddings().to("meta")
model.eagle_config._attn_implementation = "flex_attention"
block_mask = model._get_ttt_attention_mask(
1, 8, 1, device=input_ids.device, dtype=torch.float32
)
assert isinstance(block_mask, BlockMask)
assert block_mask.kv_num_blocks.device == model.eagle_module.fc.weight.device