Repository navigation
Description
Describe the bug
In TemplatedRingAttention, each rank all-gathers K/V and loops over the chunks of the other ranks, but it passes the same attn_mask to every iteration (forward, backward). The context-parallel hooks shard the mask along the key sequence together with the inputs, so the mask a rank holds describes its own keys. From the second iteration on, the keys come from another rank but the mask does not. Padded keys of the other rank are attended to, and valid keys of the other rank are masked out when the local chunk has padding.
This affects every model that passes a key mask under ring_degree > 1. I saw it with QwenImage (encoder_hidden_states_mask) and LTX (encoder_attention_mask) whenever the text has padding; without padding the outputs match.
Suggested change
Gather the per-rank masks once and pick the mask of the rank whose K/V is used in each iteration, in forward and backward:
@@ class TemplatedRingAttention.forward
kv_buffer = kv_buffer.chunk(world_size)
+ ctx.ring_masks = None
+ if attn_mask is not None:
+ masks = funcol.all_gather_tensor(attn_mask.contiguous(), gather_dim=0, group=ring_mesh.get_group())
+ ctx.ring_masks = masks.chunk(world_size)
for i in range(world_size):
+ if ctx.ring_masks is not None:
+ attn_mask = ctx.ring_masks[(rank + i) % world_size]
if i > 0:
kv = kv_buffer[next_rank]
@@ class TemplatedRingAttention.backward
for i in range(world_size):
+ if ctx.ring_masks is not None:
+ ctx.attn_mask = ctx.ring_masks[(rank + i) % world_size]
if i > 0:
kv = kv_buffer[next_rank]The backward part matters for training: backward_op reads ctx.attn_mask. With a float64 CPU attention backend that returns LSE (written for testing, since the native backend does not return LSE), this change makes the QwenImage and LTX outputs and all parameter gradients bit-identical to the single-process run with 3 padded text tokens.
Reproduction
A simple check: values at masked text positions must not change the output. The script below changes only those values and measures the relative change of the output. QwenImage transformer with the test config, bf16, _native_cudnn, 2 GPUs (torchrun --nproc_per_node=2 ring_mask.py):
import torch, torch.distributed as dist
from diffusers import QwenImageTransformer2DModel, ContextParallelConfig
dist.init_process_group("nccl")
rank = dist.get_rank(); torch.cuda.set_device(rank); dev = torch.device("cuda", rank)
torch.manual_seed(0)
model = QwenImageTransformer2DModel(patch_size=2, in_channels=16, out_channels=4, num_layers=2,
attention_head_dim=16, num_attention_heads=4, joint_attention_dim=16, guidance_embeds=False,
axes_dims_rope=(8, 4, 4)).to(dev, torch.bfloat16).eval()
model.set_attention_backend("_native_cudnn")
g = torch.Generator().manual_seed(0)
latents = torch.randn(1, 16, 16, generator=g).to(dev, torch.bfloat16)
text = torch.randn(1, 8, 16, generator=g)
mask = torch.ones(1, 8, dtype=torch.bool); mask[0, 5:] = False # last 3 text tokens are padding
other = text.clone(); other[0, 5:] = 10 * torch.randn(3, 16, generator=g) # differs only where masked
def run(t):
with torch.no_grad():
return model(hidden_states=latents, encoder_hidden_states=t.to(dev, torch.bfloat16),
encoder_hidden_states_mask=mask.to(dev), timestep=torch.tensor([1.0], device=dev),
img_shapes=[(1, 4, 4)], return_dict=False)[0].float()
def report(name):
a, b = run(text), run(other)
if rank == 0:
print(f"{name}: output change from masked tokens = {((a - b).norm() / a.norm()).item():.3e}")
report("single GPU ")
model.enable_parallelism(config=ContextParallelConfig(ring_degree=2))
report("ring_degree=2")
dist.destroy_process_group()On cuDNN the mask is also dropped by #14342, so the table separates the two (the last column is the same script with ulysses_degree=2):
| code | single GPU | ring_degree=2 |
ulysses_degree=2 |
|---|---|---|---|
| main (f982295) | 0 | 1.32e-2 | 3.78e-2 |
| main + #14349 | 0 | 8.32e-3 | 0 |
| main + #14349 + suggested change | 0 | 0 | 0 |
With #14349, Ulysses is fixed and ring still leaks; with the suggested change as well, ring is exact too.
Context
With pretrained LTX-Video (1.92B), 161 frames at 512×704, 50 steps, ring_degree=2, the decoded video differs from the single-GPU video by 76% relative RMS, and composition and camera motion visibly change. With the change it differs by 0.04%. For this comparison both sides used the same float32 attention implementation, so the cuDNN issue above does not enter.
Logs
System Info
diffusers main f982295, torch 2.12.0+cu130, cuDNN 9.20, 2× NVIDIA RTX PRO 6000 Blackwell, Linux.
Activity