Skip to content

fix(megatron): cast get_cp_local_num_tokens to torch.int for Megatron int32 token accumulator - #290

Open
ZiyiTsang wants to merge 1 commit into
redai-studio:mainfrom
ZiyiTsang:fix/cp-num-tokens-int
Open

fix(megatron): cast get_cp_local_num_tokens to torch.int for Megatron int32 token accumulator#290
ZiyiTsang wants to merge 1 commit into
redai-studio:mainfrom
ZiyiTsang:fix/cp-num-tokens-int

Conversation

@ZiyiTsang

Copy link
Copy Markdown

Why

Megatron pipeline schedules accumulate the per-token loss normalizer on an int tensor:

  • megatron/core/pipeline_parallel/schedules.pytotal_num_tokens = torch.zeros([], dtype=torch.int) (lines 256/652/1144/2363)
  • Relax own relax/backends/megatron/streaming_schedules.py:106,295 uses the same int accumulator

get_cp_local_num_tokens returned float32 (aggregated loss_mask.sum()), so every training run with --calculate-per-token-loss crashes at step 0 on the first total_num_tokens += num_tokens:

RuntimeError: result type Float can't be cast to the desired output type Int

17/30 example launchers enable --calculate-per-token-loss (all six sdpo launchers, most OPD/agentic recipes, rloo, mini_swe, nemo_gym).

How

Cast the three return paths of get_cp_local_num_tokens to torch.int so the value handed to forward_backward_* matches the accumulator dtype. Non-per-token-loss paths are unaffected (their normalizer is torch.tensor(1)), and mixing the int32 scalar into log_values still produces identical float32 metrics.

Testing

  • pytest tests/backends/megatron/test_rloo_policy_loss_dispatch.py tests/backends/megatron/test_rloo_cp_reduction.py passes on CPU.
  • test_rloo_policy_loss_dispatch now compares the normalizer dtype-safely and pins normalizer.dtype == torch.int as the regression contract (the dtype-strict torch.allclose would otherwise fail after this fix).

Relates to #285 (touches the same function cp_size == 1 branch).

Both branches (cp_size == 1 and cp_size > 1) returned float32
(loss_mask.sum()), crashing every --calculate-per-token-loss
training run at step 0: Megatron schedules.py accumulates
`total_num_tokens += num_tokens` on an int tensor, so a float
input raises "Result type Float can't be cast to the desired
output type Int". Match the accumulator dtype, and compare the
normalizer dtype-safely in the rloo dispatch test while pinning
the int contract.
Copilot AI lite review requested due to automatic review settings August 27, 2026 16:31

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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