Repository navigation
Conversation
…tives Signed-off-by: Jacob Schneider-Martin <[email protected]>
Signed-off-by: Jacob Schneider-Martin <[email protected]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5a8b4a67b4
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if global_chunk_size % sp_size != 0: | ||
| raise ValueError(f"FPDT chunk size must be divisible by the sequence parallel size {geometry}") | ||
|
|
||
| padding = (-global_seq_len) % global_chunk_size |
There was a problem hiding this comment.
Document the FPDT padding and loss-mask contract
FPDT_InputConstruct now turns previously rejected lengths into padded batches, but the shipped FPDT tutorial (docs/_tutorials/ulysses-offload.md) still only describes fixed chunks and never states that callers must pass and use the returned loss mask, reject attention masks, or normalize by the SP-global weight sum. External Megatron users can therefore enable the new path yet include fake labels or mis-normalize ranks with no valid tokens; document this contract where FPDT is configured.
AGENTS.md reference: AGENTS.md:L71-L71
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Have now added the padding contract to the FPDT tutorial and constructor docstring in a170cbbc.
| labels = append_zeros(labels) | ||
| loss_mask = append_zeros(loss_mask) |
There was a problem hiding this comment.
Keep padded losses finite before zero-weighting
When an auto-padded position assigns class 0 a probability that underflows to zero (for example, its logit is roughly 104 or more below the maximum), FPDT_LogitsLoss.forward computes softmax(...).log() and returns +inf; the intended (losses * loss_mask).sum() then evaluates inf * 0 as NaN. Thus an otherwise finite model can report a NaN loss for an unaligned sequence even though padded gradients are masked; make the padded loss finite (for example via log_softmax or an honored ignore mask) rather than relying on a zero multiplier.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is true, but it seems the softmax().log() issue is pre-existing? Happy to include a fix here if the reviewers prefer, otherwise it could be added as a second PR. For now, I've just included it as a limitation in the PR.
There was a problem hiding this comment.
You are right, the instability of softmax().log() is a pre-existing issue. I opened #9068 to address it.
On the other hand, padding could cause the same issue when the padded positions return +inf. I think it would be good to show an example to zero loss values the padded positions (See the inline comment).
There was a problem hiding this comment.
Makes sense, just added the safe-masking example. Have referenced #9068 in the PR body now too.
Signed-off-by: Jacob Schneider-Martin <[email protected]>
tohtana
left a comment
There was a problem hiding this comment.
Hi @jschneider-canva,
Thank you for your contribution! The code change looks good to me, but could we show an example to zero loss values at padded positions? I left a comment in the new tutorial section you added.
I also found we could improve the stability of logits loss by using log_softmax and opened #9068.
|
|
||
| When padding is needed, supply a `loss_mask` and set `attention_mask=None`. Causal attention prevents real tokens from attending to the appended tail, so padding cannot affect their outputs. Aligned inputs retain their existing behavior. | ||
|
|
||
| Use the reordered loss mask returned by `FPDT_InputConstruct.generate()`, keeping it aligned with the loss layout. `FPDT_LogitsLoss` returns globally gathered losses in SP-rank order with shape `[sequence, batch]`; the returned mask already covers the global sequence in the same order with shape `[batch, sequence]`. Compute `(losses * loss_mask.t()).sum() / loss_mask.sum()`. This normalizes by the SP-global valid loss-weight sum even when one rank has no valid tokens; the returned mask needs no further all-reduce. |
There was a problem hiding this comment.
losses * loss_mask.t()
If a padded token has an infinite loss, multiplying it by its zero weight gives NaN, and the mean loss becomes NaN as well. Could we add an example showing how to set the loss at masked positions to zero before multiplying by the weights?
# Losses are [sequence, batch]. The last position is padding for both samples.
losses = torch.tensor([[1., 2.],
[3., 4.],
[5., 6.],
[float("inf"), float("inf")]])
# FPDT returns the mask in [batch, sequence] order.
loss_mask = torch.tensor([[1., 1., 1., 0.],
[1., 1., 1., 0.]])
weights = loss_mask.t()
losses = losses.masked_fill(weights == 0, 0.0)
mean_loss = (losses * weights).sum() / weights.sum()This gives 21 / 6 = 3.5, the mean over the six real tokens.
There was a problem hiding this comment.
Thanks for the review - I've added that example in f24d695d, zeroing out masked losses before applying the weights. Checked it on CPU with infinite padded losses and fractional weights, and verified the masked gradients are zero.
Signed-off-by: Jacob Schneider-Martin <[email protected]>
tohtana
left a comment
There was a problem hiding this comment.
Thank you for the update! Looks good to me.
Problem
DistributedAttentionassumes equal sequence lengths across sequence-parallel ranks. Unequal shards can hang, abort, or silently corrupt results, depending on backend and version (#7384, #8351). A two-GPU reproduction hangs without a mask or fails with a callback shape error when masked.Separately,
FPDT_InputConstructrejects sequence lengths that do not fill its global chunks, requiring callers to pad manually.#7868 proposed zero-padding Q/K/V inside attention. In a five-token reproduction, that produced maximum absolute errors of 0.24 in outputs and 0.32 in Q gradients against an unpadded reference, and unmasked zero keys still receive softmax probability.
Approach
Report unequal shards as an error before generic attention data exchange and pad FPDT inputs under its causal contract.
DistributedAttention(..., validate_shards=True). The enabled check gathers Q/K/V sequence lengths across the SP group and raisesValueErroron every participating rank before attention data exchange. Q and K/V may differ from each other; each must agree across ranks. Validation defaults off.0, zero loss weights, and continued position IDs. Padding requiresloss_maskandattention_mask=None. The padding and normalization contract is documented in the FPDT tutorial and constructor docstring.DistributedAttentionfromdeepspeed.sequence; keep_SeqAllToAllprivate.Outputs and gradients were verified against an unpadded reference within numerical tolerances.
Enable validation consistently across all SP ranks - this adds one metadata all-gather and host synchronization per forward. Generic-attention callers still own the padding and masks.
For FPDT, apply the returned loss mask and normalize by the SP-global sum of loss weights.
PKUWZP’s review items on #7868
Nonemasks when padding is required; preserve aligned pass-through.DistributedAttentiononly.Testing
137 passed, zero skips across the FPDT constructor, Ulysses, and ALST files on four H200s. The six affected rejection cases passed again on two H200s after test deduplication.
Coverage includes:
Environment: Python 3.11.10, Torch 2.11.0+cu128, CUDA 12.8, FA2 2.8.3, pytest 8.3.5, NVIDIA driver 590.48.01.
New numerical coverage uses FP32 SDPA for Ulysses and FP16/SP2/zero dropout for FPDT.
Test commands
The pre-existing
softmax().log()instability is being addressed separately in #9068. This PR documents zeroing losses at zero-weight positions before weighting, avoidinginf * 0 = NaNfor masked tokens.Duplicate Work
Addresses #7384 and picks up the remaining work from #7868.
#8351 proposed the local divisibility assertion, this PR adds cross-rank validation and FPDT padding. The sibling ALST data-loader adapter already rejects non-divisible lengths and is unchanged. Our pre-submission search found no other open implementation of this approach.
Builds on @harshang03’s proposal and @PKUWZP’s review of #7868.
AI assistance was used for implementation, testing, review, and preparation of this PR.