Repository navigation
add dummy-ema-optimizer for model averaing - #3985
Conversation
|
|
| except Exception: | ||
| return False | ||
|
|
||
| def _maybe_exclude_missing_ema( |
There was a problem hiding this comment.
its mainly for BP and deal with edge case.
people may resume or doing continue training where EMA weights is missing there
There was a problem hiding this comment.
Can we just use this exclude_from_loading flag https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/checkpointer/base.py#L315
| all_params: list[nn.Parameter] = [] | ||
| for model in model_parts: | ||
| named_params = [ | ||
| (name, p) for name, p in model.named_parameters() if p.requires_grad |
There was a problem hiding this comment.
for now, only learnable params will be included in EMA
| """First training step (matching Trainer.step) at which EMA tracking | ||
| begins. Intentionally decoupled from the LR scheduler's WSD phases.""" | ||
|
|
||
| step_bias: int = 0 |
There was a problem hiding this comment.
we need this because for mid-train, continues trainig or any cases people reset training step to 1, but LR scheduler or EMA scheduler is kept.
| recent half_life_fraction share of steps dominant. Default 0.05 | ||
| matches the common decay = 2 ** (-20 / t) rule of thumb.""" | ||
|
|
||
| start_step: int = 0 |
There was a problem hiding this comment.
i think this will be less used, mainly to offer the options to avoid code-start case..
| for deliberately renumbering Trainer.step (e.g. a new training phase) | ||
| while wanting the EMA to keep aging as if uninterrupted.""" | ||
|
|
||
| update_every_n_steps: int = 1 |
There was a problem hiding this comment.
i think this will be also less used.. i think cost of per-step update is ok.. but we can offer that options anyhow
| # registered; EMAOptimizersContainer internally no-ops everything | ||
| # when config.ema_weights.enable is False. | ||
| self.ema_optimizer = config.ema_weights.build(model_parts=self.model_parts) | ||
| self.optimizers.register_step_post_hook( |
There was a problem hiding this comment.
i think we can also to explicitly call self.ema_optimizer.step() after optimizers.step,
in later case better add a stream check to make sure ema update always happend after optimizer update done?
There was a problem hiding this comment.
what can be off-stream / async? I had thought they would happen on the same main stream.
There was a problem hiding this comment.
current version has no "async".
" I had thought they would happen on the same main stream."
yes, by default i think it will be executed afteroptmizer.stepdone.
There might be an exception is if we want to have better CPU-offload/fetch -> we need to create stream -> we may want to explicitly wait main stream is done.
i think my original comment may not be related. doing eithter explicitly self.ema_optimizer.step() or post hook should work
There was a problem hiding this comment.
let's just call self.ema.step()
| self._offload_stream = torch.cuda.Stream() | ||
| for ema_opt in self.optimizers: | ||
| for st in ema_opt.state.values(): | ||
| st["ema_params"] = st["ema_params"].cpu().pin_memory() |
There was a problem hiding this comment.
Is EMA CPU offload currently expected to work with FSDP2? _init_cpu_offload() appears to call .pin_memory() directly on a DTensor, which raises NYI: aten._pin_memory.default.
There was a problem hiding this comment.
from my local test it works good. (cpu offload is more or less like adamw offload, i add pin memory and stream to make offload works better on GH/GB)
There was a problem hiding this comment.
Thanks. We used this PR to validate EMA for our work and encountered an issue with FSDP2 CPU offload. After FSDP2 is applied, the EMA states are DTensors. Since .cpu() still returns a DTensor, the subsequent .pin_memory() call fails in our environment with NYI: aten._pin_memory.default.
The PyTorch source at our commit 7661cd9c6b841b62b7f411aa52ec51f05457263b also indicates this limitation: torch/distributed/tensor/parallel/fsdp.py, line 110 states, ignore memory_format and pin_memory as those are not supported by DT.
Is the current implementation expected to support FSDP2 CPU offload when the EMA states are DTensors, or could this behavior depend on the PyTorch build?
There was a problem hiding this comment.
thanks! ok that's interesting, i will do more test later today and update you later
If DTensor really not gonna work, the minimal fix is to add Dtensor > Tensor convert on saving and dtensor reaload on loading.
There was a problem hiding this comment.
you are right. i fixed it by explicitly apply Dtensor -> Tensor converting
There was a problem hiding this comment.
Sorry, I missed your earlier reply. Thanks for getting back to me. btw, do you have an estimated timeline for merging PR #3985? No worries if there isn’t an update yet.
There was a problem hiding this comment.
i am not sure on my side, mainly up to PR review.
I have tested it on 30b model on 512 gpus for ~500B tokens and it seems works ok for me (but without cpu-offload)
tianyu-l
left a comment
There was a problem hiding this comment.
Probably because I don't have a good mental model, I found the logic around two things not clear:
- Checkpointing. Could you describe the concrete requirements around checkpoint save & load, HF conversion expectation, and downstream eval? I only know that people may want ema'ed checkpoints for eval, but there're many other aspects -- e.g. should we allow loading a checkpoint with / without ema?
- Offloading. When exactly would offloading and unloading happen? Would any thing happen in async way?
| aten._pin_memory.default), so pin just the local shard.""" | ||
| return self._local_view(tensor).cpu().pin_memory() | ||
|
|
||
| def _materialize_dtensor( |
There was a problem hiding this comment.
What gap does DTensor have so that we need the back-and-forth conversion here?
There was a problem hiding this comment.
as @NaDongsfd mentioned above, DTensor does not have/support _pin_memory, so if one need CPU-Offload, we need extra convert there
There was a problem hiding this comment.
i add todo about dtensor's to local function
| # registered; EMAOptimizersContainer internally no-ops everything | ||
| # when config.ema_weights.enable is False. | ||
| self.ema_optimizer = config.ema_weights.build(model_parts=self.model_parts) | ||
| self.optimizers.register_step_post_hook( |
There was a problem hiding this comment.
what can be off-stream / async? I had thought they would happen on the same main stream.
| begin = time.monotonic() | ||
|
|
||
| states = self._states_to_load(model_only) | ||
| needs_ema_reseed = not model_only and self._maybe_exclude_missing_ema( |
There was a problem hiding this comment.
if i remember correctly, there is an edge case in my test.
train model with this PR, with EMA OFF, the CKPT will have states[EMA_OPTIMIZER] but its empty.
If we resume training with that CKPT, with EMA ON, dcp_load will try to read states[EMA_OPTIMIZER] and believe the CKPT do have data there, and it casuses problem because the CKPT comes from runs without EMA.
So if we need to clean the empty dict of states[EMA_OPTIMIZER] for dcp_load, then, create states[EMA_OPTIMIZER] equals to "main" model weights for cold-start
There was a problem hiding this comment.
hmmm maybe we can make "EMA_OPTIMIZER" optional in state? if there is ema checkpoint, we load it, otherwise; it will be marked as None or sth?
There was a problem hiding this comment.
hmmm maybe we can make "EMA_OPTIMIZER" optional in state? if there is ema checkpoint, we load it, otherwise; it will be marked as None or sth?
conceptually yes... just need to do lots of patch...
There was a problem hiding this comment.
done, its optional now.
For HF conversion & Eval, by default it only convert "main" weights (act like no EMA), and optionally to convert both "main" weights and "EMA" weights when For checkpoint save/load, as it is like a StatefulOptimizer, the EMA state will be saved just like model weights and optimizer states, and async checkpoint et al works well and out-of-box. (i tested 30b model on up 1024 gpus with HSDP, async ckpt works well). For sure, all DCP checkpoints now will be larger. It will be complicated to have EMA but load a CKPT without EMA weights, so we need to copy mater weights to init the EMA weights, and some corner cases like this
For now, this PR only do memory offload. so in training, the EMA copy of weights can be on CPU RAM, and after optimizer step, EMA weights are load to GPU and do update, and then offload to CPU RAM again. this is avoid put EMA resident on GPU RAM to save space. we can off course move EMA update to CPU as well. |
| _EMA_STATE_SUFFIX = ".ema_params" | ||
|
|
||
|
|
||
| class ParallelFileSystemReader(FileSystemReader): |
There was a problem hiding this comment.
this helper is used to speed up DCP -> Convert (i can open separate PR for this if you want).
I dont know how people usually run convert to HF. i usually run it on single cpu node, therefore when i convert DCP from actual runs (for example 30b on 1k gpus) it takes ages to load the data. and we can make this faster by just using more cpu cores
There was a problem hiding this comment.
Curious, is there any specific tasks you wanted to evaluate with huggingface format?
FYI there is this draft pr that allows you to evaluate lm-harness with a torchtitan DCP format without converting to huggingface format: EleutherAI/lm-evaluation-harness#3948
There was a problem hiding this comment.
thanks a lot, thats a good idea to use DCP for eval.
i think HF format is not just for "eval", for example for us, we want to build open source model and we wish to release all (intermedia) checkpoints like olmo or other projects. so make other people can also access the model in easy way.
(and for now our eval run on top of VLLM, its decoupled with torch-titan for now. it prefer to read HF format of checkpoint)
There was a problem hiding this comment.
i see, thanks for explaining
There was a problem hiding this comment.
Let's separate changes in this file in a separate PR.
ruisizhang123
left a comment
There was a problem hiding this comment.
Thanks for adding EMA! have a few questions and comments.
| _EMA_STATE_SUFFIX = ".ema_params" | ||
|
|
||
|
|
||
| class ParallelFileSystemReader(FileSystemReader): |
There was a problem hiding this comment.
Curious, is there any specific tasks you wanted to evaluate with huggingface format?
FYI there is this draft pr that allows you to evaluate lm-harness with a torchtitan DCP format without converting to huggingface format: EleutherAI/lm-evaluation-harness#3948
| states (Dict[str, Any]): The states that need to be saved, other than the | ||
| previous 4 components. | ||
| previous 5 components. |
There was a problem hiding this comment.
why it changed to 5 here?
There was a problem hiding this comment.
before:
self.states.update(
{
MODEL: ModelWrapper(model_parts),
OPTIMIZER: optimizers,
DATALOADER: dataloader,
LR_SCHEDULER: lr_schedulers,
}
)
and now one more EMA_OPTIMIZER: ema_optimizer state, so its 5.
| ): | ||
| params = [p for p in model.parameters() if p.requires_grad] | ||
| if not params: | ||
| continue |
There was a problem hiding this comment.
I feel like buffers like expert bias things should also be EMA'ed. However, they seemed to be missing from this update, since it's only calling parameters()
There was a problem hiding this comment.
good question, i am fine to include it, or make it optional.
TBH i dont know what is the right way. because e.g. people dont do expert_bias_update_coeff scheduler or don't decay the coeff. in this sense we may not need it. (EMA + constant LR ≈ LR decay scheduler and if we don't need decay we may not needs RMA)
There was a problem hiding this comment.
Maybe we can have an optional ema_buffer key in optimizer, and have some customized regex function if user wants to apply ema_buffer to a subset of buffers. wdyt?
There was a problem hiding this comment.
i am fine for this, will add it
| begin = time.monotonic() | ||
|
|
||
| states = self._states_to_load(model_only) | ||
| needs_ema_reseed = not model_only and self._maybe_exclude_missing_ema( |
There was a problem hiding this comment.
hmmm maybe we can make "EMA_OPTIMIZER" optional in state? if there is ema checkpoint, we load it, otherwise; it will be marked as None or sth?
|
@rakkit would you like to follow up or would you like us to take over? |
|
sry for late reply.... i did not see notification from GitHub so i did not realize you have comments on it |
| except Exception: | ||
| return False | ||
|
|
||
| def _maybe_exclude_missing_ema( |
There was a problem hiding this comment.
Can we just use this exclude_from_loading flag https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/checkpointer/base.py#L315
| loss_fn: BaseLoss | ||
| optimizers: OptimizersContainer | ||
| lr_schedulers: LRSchedulersContainer | ||
| ema_optimizer: EMAOptimizersContainer |
There was a problem hiding this comment.
| ema_optimizer: EMAOptimizersContainer | |
| ema: EMA |
| # registered; EMAOptimizersContainer internally no-ops everything | ||
| # when config.ema_weights.enable is False. | ||
| self.ema_optimizer = config.ema_weights.build(model_parts=self.model_parts) | ||
| self.optimizers.register_step_post_hook( |
There was a problem hiding this comment.
let's just call self.ema.step()
There was a problem hiding this comment.
For checkpoint save/load, as it is like a StatefulOptimizer, the EMA state will be saved just like model weights and optimizer states, and async checkpoint et al works well and out-of-box. (i tested 30b model on up 1024 gpus with HSDP, async ckpt works well). For sure, all DCP checkpoints now will be larger.
Let's support this first.
It will be complicated to have EMA but load a CKPT without EMA weights, so we need to copy mater weights to init the EMA weights, and some corner cases like this
I think it'd be fine? We just don't skip loading ema weights, and start to accumulate ema values using the current main weights.
For HF conversion & Eval, by default it only convert "main" weights (act like no EMA), and optionally to convert both "main" weights and "EMA" weights when --ema_output is given so to get two HF ckpts.
For using ema to do checkpoint eval, in this PR I'd suggest
- we don't support "cleanly saving an ema checkpoint to do eval"
- and instead user can have an offline script to convert current "mixed main + ema" DCP checkpoint into an ema-only model checkpoint
And let's worry about that in next PRs.
| _EMA_STATE_SUFFIX = ".ema_params" | ||
|
|
||
|
|
||
| class ParallelFileSystemReader(FileSystemReader): |
There was a problem hiding this comment.
Let's separate changes in this file in a separate PR.
|
@rakkit would you like to follow up? |
|
most of comments adressed, thx for feedback.
|
| if not model_only and EMA in self.exclude_from_loading and EMA in self.states: | ||
| self.states[EMA].load_state_dict({}) |
There was a problem hiding this comment.
oh I see. Even if the checkpoint has no EMA states, and we specify EMA as being excluded from loading, we still have to init EMA states using loaded model states.
| # via the same exclude_from_loading a caller uses for any other | ||
| # optional state -- reseed it from the just-loaded model weights | ||
| # rather than leaving it at its pre-load (fresh-init) values. | ||
| if not model_only and EMA in self.exclude_from_loading and EMA in self.states: |
There was a problem hiding this comment.
Why conditioning on model_only? e.g. when loading from HuggingFace format, it will be model_only, but it doesn't mean we shouldn't set initial EMA states to be model states.
There was a problem hiding this comment.
Given how close they are, can we put this under components/optimizer/?
|
@claude review the latest commit and my latest comments |
|
Claude finished @tianyu-l's task in 5m 9s —— View job Review: latest commit (
|
Co-authored-by: AWWWOLF<[email protected]> # message auto-generated for no-merge-commit merge: !615 merge feat/ema-weights-3985 into master [feat] backport TorchTitan EMA weights (#3985) with Ascend offload fixes Created-by: ZHANGJIAOGOU Commit-by: AWWWOLF Merged-by: cann-robot Description: ## 描述 本 PR 回移 [TorchTitan #3985](pytorch/torchtitan#3985) 的 EMA weights,并做 Ascend / NPU 适配。改动只在 `torchtitan_npu/patches/torchtitan`(目录与上游对齐),不改 `extension/`、`override/`、`config/configs.py`。 `torchtitan_npu` 启动时先导入 `patches`,再加载 NPU Config / TrainerEx,因此后续类会继承本补丁替换后的 `Trainer` / `CheckpointManager`。 ### 主要实现 1. **`EMAOptimizersContainer`**(`patches/torchtitan/components/ema.py`) 在线维护模型权重 EMA,复用 `OptimizersContainer` 的 FQN 扁平化与可 reshard 的 `state_dict` / `load_state_dict`。 - 固定 `decay`,或 `decay=None` 时按 `half_life_fraction` 动态 decay - `start_step` / `step_bias` / `update_every_n_steps` - `offload_to_cpu`:pinned CPU + 异步 stream(NPU 侧含 0-numel shard 跳过、checkpoint 时按 param shell materialize) - `Config.__post_init__` 校验非法 `decay` / `half_life_fraction` / `update_every_n_steps` 2. **`EMATrainer`**(`patches/torchtitan/trainer.py`) - `Config` 新增 `ema_weights`(默认 `enable=False`) - `apply()`:`torchtitan.trainer.Trainer = EMATrainer` - NPU `TrainerEx` / `TrainerConfig` 随后定义,自动带上该字段和 CLI(`--ema-weights.*`) - `__init__`:`enable=False` 直接返回,不建 container、不挂 hook、不写 checkpoint state - `enable=True`:`super()` 完成 `model_parts` / optimizer / checkpointer 后,执行 `ema_weights.build` → optimizer step hook → `checkpointer.register_ema_optimizer` 三处共用同一 EMA 实例。当前 pin 的 `checkpointer.load()` 在 `train()` 中,登记早于 load。 3. **`EMACheckpointManager`**(`patches/torchtitan/components/checkpoint.py`) - 继承 `CheckpointManager`,**不**声明嵌套 `Config`(`exact=True` 的 NPU override 目标类身份不变) - `apply()`:`CheckpointManager = EMACheckpointManager`,并同步 `Config._owner` - 之后定义的 `NPUCheckpointManager` / `NPUVirtualCheckpointManager` 通过 MRO 继承 EMA 能力 - `register_ema_optimizer`:仅在 `checkpoint.enable` 时写入 `states["ema_optimizer"]` - 续训:盘上无 EMA 时从已加载模型 reseed;`model-only` / HF initial-load 后同样 reseed(不从 flatten FQN 猜 `"model"` key) 4. **HF 导出**(`patches/torchtitan/scripts/checkpoint_conversion/convert_to_hf.py`) `--ema_output` 可额外导出 EMA 权重。这是 backport 入口,不是稳定公共 API;上游 `torchtitan.tools` 尚未接该参数。空 DCP plan 直接返回完成 Future,避免 `max_workers=0`。 5. **不支持的 recipe** `GraphTrainer`、`FaultTolerantTrainer` 等自定义 `__init__` 的 trainer **不在支持范围**(见 patches README)。NPU config manager 仍会把它们转成标准 `TrainerConfig`;请勿与 `--ema-weights.enable` 组合使用。 6. **DT** `tests/unit_tests/ema/test_ema_initial_load.py`:算法、disable 路径、checkpoint 登记、model-only / 缺 EMA reseed、NPU manager MRO、空 DCP plan。 上游 #3985 合入且 torchtitan pin 升级后,删除本目录对应补丁。 ## 类型 - [ ] Bug 修复 - [x] 新功能 - [ ] 重构 - [ ] 构建过程或辅助工具 - [x] 文档内容更新 ## Checklist - [x] 代码遵循项目代码风格 - [x] 已自行测试 - [x] 已更新文档(`patches/torchtitan/README.md`) - [x] 标题已使用类型标签 ## 如何测试 ```bash PYTHONPATH=/path/to/torchtitan \ TORCH_DEVICE_BACKEND_AUTOLOAD=0 \ python3 -m pytest -v --tb=short \ tests/unit_tests/ema/test_ema_initial_load.py ``` 功能训练(DeepSeek-V4 8P 示例): ```bash # 在原 recipe 上增加: --ema-weights.enable --ema-weights.decay 0.999 # 或省略,走 half-life 动态 decay --ema-weights.offload-to-cpu # 可选 --checkpoint.enable # 末步也要完整 EMA state 时: --checkpoint.no-last-save-model-only ``` HF 导出: ```bash python torchtitan_npu/patches/torchtitan/scripts/checkpoint_conversion/convert_to_hf.py \ <dcp_dir> <model_hf_dir> \ --ema_output <ema_hf_dir> \ --model_name torchtitan_npu.models.deepseek_v4 \ --model_flavor ... ``` ## 测试结果(摘要) DT:`tests/unit_tests/ema/test_ema_initial_load.py` 覆盖算法、opt-in 默认路径、登记/reseed、NPU checkpoint 组合。 DeepSeek-V4 8P 实机(flash 43L / 16E,`MATRIX_STEPS=4`)此前已验证: | # | 项 | 结果 | | --- | --- | --- | | 1 | CLI / 参数校验 | PASS | | 2 | `enable=false` 默认路径无 EMA state | PASS | | 3 | Fixed decay + trajectory oracle | PASS | | 4 | Dynamic half-life | PASS | | 5 | schedule(start / cadence / bias) | PASS | | 6 | 8P device EMA + DCP `ema_optimizer.*` | PASS | | 7 | CPU offload 与 device 数值一致,显存下降 | PASS | | 8 | EMA HF 导出与 model HF key 一致、权重有真实差异 | PASS | `enable=false` 时不创建 EMA optimizer,checkpoint 无额外 EMA key。需要持久化时必须 `--checkpoint.enable`。 ## (上一轮修改)如何测试 执行: ```bash PYTHONPATH=/tmp/torchtitan \ TORCH_DEVICE_BACKEND_AUTOLOAD=0 \ python3 -m pytest -v --tb=short \ tests/unit_tests/ema/test_ema_initial_load.py ``` ## 最新一轮测试结果 针对之前提出的 **EMA 参数没有被充分使能、缺少较完整功能验证** 的意见,本次基于 ```bash id="b28e4e" examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh ``` 补充进行了 DeepSeek-V4 **8P NPU 实机验证**。 本轮验证重点不再只是确认“EMA 开启后可以训练”,而是进一步检查: - EMA 参数是否能够正确接入 Trainer 配置并进入实际执行路径; - fixed decay / dynamic decay / schedule 等配置是否真正改变 EMA 行为; - EMA 在真实 DeepSeek-V4 8P NPU 场景中是否正常工作; - CPU offload 是否保持与 device EMA 一致的数值语义; - EMA checkpoint 是否能够生成独立的 HF EMA 权重; - EMA 配置隔离及参数合法性检查是否正常工作。 测试环境: ```text id="ef696e" DeepSeek-V4 flash 43L / 16E NPU: 8P MATRIX_STEPS=4 MATRIX_SEQ_LEN=2048 MATRIX_GBS=64 ``` ## ST 总览  | # | 验证项 | 主要配置 / 方法 | 结果 | 已证明内容 | |---:|---|---|:---:|---| | 1 | EMA Config / 参数校验 | CLI binding + N0–N4 | **PASS** | Trainer 初始化阶段 EMA 参数绑定、默认值、配置隔离和范围校验正常 | | 2 | EMA disabled baseline | `enable=false` | **PASS** | EMA 保持 opt-in;关闭后不创建 EMA optimizer/state,原训练路径正常 | | 3 | Fixed decay | `decay=0.5` | **PASS** | fixed-decay 路径在 8P NPU 训练中生效,并通过 EMA trajectory oracle | | 4 | Dynamic half-life | `decay=None`, `half_life_fraction=0.5` | **PASS** | dynamic decay 路径生效,half-life 参数实际参与 EMA 计算 | | 5 | EMA schedule | start / cadence / bias | **PASS** | EMA 更新/跳过时机、`num_updates` 与 decay 能按照 schedule 工作 | | 6 | 8P device EMA | device-resident EMA + oracle | **PASS** | EMA state 在真实 DeepSeek-V4 8P NPU Trainer 中正常创建、更新和保存 | | 7 | CPU offload | `offload_to_cpu=true` | **PASS** | offload 与 device EMA 数值探针对比通过,并观察到 NPU 显存下降 | | 8 | EMA HF export | model HF + EMA HF | **PASS** | 成功生成独立 EMA HF 权重文件,且内容不是普通 model 权重复制 | --- ## 1. Trainer 初始化及 EMA 配置校验 `verify_cli_matrix.py` 验证结果: ```text id="46b263" PASS config_binding_and_defaults PASS N0_standard_recipe_rejects_ema PASS N1_value_error PASS N2_value_error PASS N3_value_error PASS N4_value_error PASS verify_cli_matrix CLI_RC=0 ```  该结果证明: - EMA Config 已成功接入对应 Trainer 配置; - EMA 参数默认值和 CLI binding 正常; - 普通非 NPU EMA recipe 不会意外接受 EMA 参数; - 超出 EMA 配置约束的参数会在训练启动前被正确拒绝,而不是被静默忽略。 同时 TrainerEx 接线单测: ```text id="2c89e0" 3 passed in 2.14s ```  覆盖了 EMA Config 接线、disabled path、enable wiring order 以及 Trainer 初始化相关逻辑。 --- ## 2. EMA disabled baseline 关闭 EMA 时: ```text id="8674cb" PASS ```  验证结果表明: ```text id="75efeb" ema_weights.enable=false ``` 时不会创建 `ema_optimizer`,checkpoint 中也不会产生额外 EMA state,因此本次 EMA 功能保持 opt-in,不影响默认训练路径。 --- ## 3. Fixed decay 配置: ```bash id="c02051" --ema-weights.enable --ema-weights.decay 0.5 ``` 结果: ```text id="50d370" PASS ```  该 Case 在真实 DeepSeek-V4 8P NPU 训练中进入 fixed-decay 路径,并由 `verify_ema_trajectory.py` 对 EMA tensor trajectory 进行 oracle 校验。 因此可以确认 `decay` 参数不是只完成 CLI 解析,而是实际影响 EMA 更新: ```text id="ca246a" EMA_t = 0.5 * EMA_(t-1) + 0.5 * W_t ``` --- ## 4. Dynamic half-life 配置: ```bash id="b303c0" --ema-weights.enable --ema-weights.half-life-fraction 0.5 ``` 且不设置 fixed `decay`。 结果: ```text id="5071e0" PASS ```  该测试验证 dynamic half-life EMA 能够在真实 8P 训练中正常执行,并通过对应 oracle。 因此当前 fixed decay 和 dynamic half-life 两条 EMA decay 路径均已得到验证。 --- ## 5. EMA schedule EMA schedule Case 结果: ```text id="f76b72" PASS ```  测试过程中观察到: ```text id="3af9c8" step2: skip step3/4: fire num_updates / decay follow expected schedule ``` 说明 EMA 的更新时机不是固定每 step 无条件执行,相关 schedule 配置已经能够实际控制 EMA update,并且 `num_updates` / decay 与预期调度一致。 --- ## 6. DeepSeek-V4 8P device EMA 8P device-resident EMA: ```text id="a2f09c" PASS ``` 实际训练过程中: - EMA state 正常生成; - checkpoint 中能够检查到 `ema_params`; - EMA trajectory oracle 校验通过; - 8P device-resident EMA 可以正常保存。 因此可以确认 EMA 已经真正接入 **DeepSeek-V4 8P NPU Trainer runtime**,而不是仅在配置层或 standalone 测试中工作。 EMA 算法单元测试同时通过: ```text id="c00113" 5 passed ALGO_RC=0 ```  --- ## 7. NPU CPU offload CPU-offload 配置: ```bash id="82c052" --ema-weights.enable --ema-weights.decay 0.5 --ema-weights.offload-to-cpu ``` 结果: ```text id="772e95" PASS ```  其中 `ema_offload_probe` 与相同 `decay=0.5` 的 device EMA final state 对比: ```text id="12967f" PASS ``` 即: ```text id="02e7bb" device EMA ≈ CPU-offload EMA ``` 说明 CPU offload 改变的是 EMA state 的存储与搬运位置,并没有改变 EMA 数学结果。 同时在运行过程中实际观察到: | 模式 | 观测 NPU memory | |---|---:| | Device EMA | ≈ 51.10 GiB | | CPU-offload EMA(step1) | ≈ 39.40–39.60 GiB | 因此在功能正确性之外,也观察到了 offload 后明显的 NPU memory 降低。 显存数据会受到 allocator cache 和临时 scratch 影响,因此这里将其作为 offload 功能效果证据,而不把某个固定下降比例作为 correctnes See merge request: cann/torchtitan-npu!615
|
thanks a lot, i will fix. (It so annoying i cannot see github notification for no reason, but thanks a lot for your time and quick review) |
|
fixed first bug claude pointed, and rebased to latest commits. the checkpoint build now needs to take |
There was a problem hiding this comment.
could you rebase? I think RL trainer would benefit from this field, too, if we put EMA in TrainingEngine
|
thx. rebased and did few more round of checks. after rebase, ema build is log now under and, again, as I also rewrote the PR message, includes claude summarized few edge-cases |
|
i also bring EMA weights -> HF convert scripts back, the args is mirror of DCP->HF. its much clean than put eveything into one. Also i just realized, torchtitan by default have |
|
@rakkit Seems CI failures are real. Also sorry need to rebase again. |
|
rebased to |
This is a follow-up of #3985. It allows EMA to keep track of multiple copies by having a mixture of `decays` and `half_life_fractions` as the input list. As a results, we can now support both decay mode and half_life_fractions mode. It still maintains one `ema` checkpoint key. Each tensor's state now holds one copy per entry, flattened by DCP to `ema.state.<fqn>.ema_params.<ema_key>`. The decays and half-life fractions are flattened into one list of copies, and each copy is updated independently on the same firing. The CPU-offload path is unchanged; it runs once per copy on the same side stream.
* [data] Keep Hugging Face streaming state opaque to DCP (#5017)
Fixes #4991
## Summary
`GrainDataLoader.state_dict()` stores the nested object from
`iterator.get_state()` under the data-parallel rank key. Distributed
checkpoint flattens that tree and requires the flattened keys to match
at save and load.
With `HuggingFaceStreamingSource`, `examples_iterable.previous_state` is
`None` on a freshly built loader and a dict after iteration. A
checkpoint saved after iteration therefore has no leaf
`dataloader.dp_rank_0...hf.examples_iterable.previous_state`, while
`dcp.load` builds its plan from a new loader that still has that key.
Load planning raises `CheckpointException` (`Missing key in checkpoint
state_dict: ...previous_state`) before `GrainDataLoader.load_state_dict`
runs. Direct `state_dict()` / `load_state_dict()` round trips never hit
this.
That key change is inside the Hugging Face dataset state.
`_HuggingFaceCursorIterator.get_state` stores
`pickle.dumps(self._dataset.state_dict())` under `hf`, and `set_state`
unpickles that bytes leaf before `load_state_dict`. `epoch` stays a
plain field. The rest of the Grain tree stays nested, so other data
sources can still be resharded. `GrainDataLoader` stays on checkpoint
version 1 and still rejects a different data-parallel degree.
## Test plan
- [ ] `pytest tests/unit_tests/cpu/test_dataset_checkpointing.py`
- [ ] `pytest tests/unit_tests/cpu/components/data/test_grain_data.py`
* [ROCm][CI] Regenerate mi350x loss baselines after torch nightly bump (#5062)
## Summary
ROCm model tests loss assertion have been red from today after the CI's
unpinned torch install moved from `dev20261004` to `dev20261005`. I
believe CUDA is also failing on the same test. This regenerates all
affected mi350x loss files.
* [dist_moe] Defer optional backend imports (#5066)
The Dist-MoE integration imported the standalone backend while defining
its module and config types. This made otherwise generic TorchTitan
imports fail once another feature referenced the integration classes.
Especially problematic for defining relations for transforms #4995,
#5007.
Route backend symbol access through a cached lazy module. Postponed
annotations and deferred MXFP8 defaults keep the integration importable,
while selecting Dist-MoE still reports the focused installation error
and preserves failures from dependencies inside an installed backend.
Test Plan: taskset -c 0-7 pytest
tests/unit_tests/cpu/test_optional_imports.py
tests/unit_tests/cpu/test_transforms.py
tests/unit_tests/cpu/test_dist_moe.py -q -k 'not
runtime_passes_per_slot_capacity_to_annex and not
dist_moe_671b_recipe_topology'
Test Plan: env SKIP=pyrefly-check pre-commit run --files
tests/unit_tests/cpu/test_optional_imports.py
torchtitan/models/common/dist_moe/_optional.py
torchtitan/models/common/dist_moe/mxfp8.py
torchtitan/models/common/dist_moe/routed_experts.py
torchtitan/models/common/dist_moe/runtime.py
torchtitan/config/transform/dist_moe.py
* [FSDP] enable apply_fsdp_to_decoder to configure MixedPrecisionPolicy param_dtype_override_fn (#5068)
Allow passing into `apply_fsdp_to_decoder` the `param_dtype_override_fn`
option for `MixedPrecisionPolicy`.
* LoRA for BF16 DistMoE (#4995)
Adds support for LoRA BF16 DistMoE.
`DistMoeRoutedExperts._weight_operands` returns the weights matrices
`w13_EFD, w2_EDF` used to make the DistMoE kernel call.
LoRA overrides `_weight_operands` to add the LoRA matrices to `w13_EFD,
w2_EDF` before returning.
This does not support MXFP8 DistMoE. It would be quite tricky to
implement.
## Some caveats
- `DistMoeTransform -> LoRATransform (for GroupedLinear w13, w2)` would
not error but result in no op. Would it be worth to error out by
checking the parent? It wouldn't be too clean.
- In `transform/lora.py`, `LoRATransform.run_after` registers
`DistMoeRoutedExpert` which requires importing `dist_moe` which is an
optional package dependency. Similar for `common/lora.py`
- Should we just set `LoRATransform.run_after` inside
`transform/dist_moe.py` and move the DistMoE LoRA to DistMoE files?
- This also raises a question on how to do #5007 nicely.
## Test Plan
One node, 4 GB300 GPU DP shard 4, EP 2, LoRA rank 8, alpha 16
Deepseek v3 debug model on DistMoE LoRA compared to LoRA on
`GroupedLinear` on `w13, w2` with all to all backend.
| Metric | Step 1 | Step 100 | Mean absolute difference | RMSE | Maximum
absolute difference |
|---|---:|---:|---:|---:|---:|
| Loss, all-to-all | 8.217248 | 4.354145 | — | — | — |
| Loss, DistMoE | 8.217256 | 4.347911 | 0.002922 | 0.005632 | 0.030035 |
| Grad norm, all-to-all | 0.00892750 | 0.12869738 | — | — | — |
| Grad norm, DistMoE | 0.00892772 | 0.12781706 | 0.005116 | 0.013849 |
0.098999 |
<img width="1120" height="409" alt="Screenshot 2026-10-03 at 3 46 52 PM"
src="https://github.com/user-attachments/assets/3aa077ce-f666-424e-ba3e-6ef818aa8459"
/>
* Bump attn-gym to 0.0.16 (#5069)
attn-gym 0.0.16 removes `T` from the GDN local-dV kernel's autotune key
(meta-pytorch/attention-gym#625). That kernel takes no `T` argument, and
Triton 3.9 validates autotune keys when the decorator runs, so fused GDN
backward raised on Triton 3.9 with 0.0.15. The release changes no
dependency pins.
Before publishing, the attn-gym release workflow tested the built wheel
on Modal B200 (296 passed, 0 failed, 5 skipped).
* [graph_trainer] Split graph_builder.py by execution path (#5000)
Regenerated on current `main` (the earlier version predated #4999,
#5001, #5003, #5035, #5038 and the Dist-MoE adapter #4541, which all
touched `graph_builder.py`).
## Why
`graph_builder.py` had grown to ~2650 lines mixing the stage-graph
provider, shared helpers, SPMD graph construction (with and without
gradient accumulation), and PP stage graph construction. Splitting it
along the execution paths (SPMD / PP) makes each path readable on its
own.
## What
| File | Contents |
|---|---|
| `graph_builder.py` (~290 lines) | `GraphExecutionPlan`, placement
types, `GraphTrainerStageGraphProvider`, the provider's Dist-MoE slot
lookup |
| `graph_builder_utils.py` (~310) | `GraphTrainerConfigView`, FSDP
bucketing helpers, graph execute/pack/compile helpers shared by both
paths |
| `spmd_graph_builder.py` (~360) | joint-graph tracing shared by both
SPMD paths; SPMD without gradient accumulation executor and builder |
| `spmd_gradient_accumulation_graph_builder.py` (~810) | SPMD with
gradient accumulation: first / middle / last graphs, their executor,
accumulation, edge-graph bucketing |
| `graph_pp/pp_graph_builder.py` (~1020) | PP stage graphs,
partitioning, overlap graphs, the Dist-MoE activation-slot rewrite used
by PP stages |
**Pure code move.** All 45 top-level definitions are AST-identical to
`main` (checked by script), except:
- `spmd_graph_builder.py` imports `GraphExecutionPlan` under
`TYPE_CHECKING` and quotes its annotations, to avoid an import cycle
with `graph_builder.py`.
- Each file has only the imports it uses, its own `logger`, and keeps
`graph_builder.py`'s `from __future__ import annotations` (needed for
the `TYPE_CHECKING`-only Dist-MoE annotations).
Callers (`pipeline.py`, `precompile_main.py`, tests) and `mock.patch`
targets are updated to the new modules.
**Second commit** moves the SPMD gradient-accumulation code out of
`spmd_graph_builder.py` (it was ~70% of that file), so the simple SPMD
path reads on its own. The only non-move change is the dispatch:
`_build_fwd_bwd_graphs` used to trace and then branch on
`plan.has_gradient_accumulation`; its tracing becomes
`_trace_spmd_stage_graph` (shared), `_build_fwd_bwd_graphs` builds only
SPMD without gradient accumulation, the new
`_build_gradient_accumulation_fwd_bwd_graphs` builds the GA path, and
`GraphTrainerStageGraphProvider` picks between them as it already does
for PP. The new module imports from `spmd_graph_builder.py`, not the
reverse.
## Tests
- `test_graph_pp_runner.py`, `test_graph_pp_passes.py`,
`test_trace_module.py`: 169 passed, 4 skipped, 2 failed. Both failures
reproduce on unmodified `main`:
- `test_dist_moe_slot_is_an_explicit_stage_graph_input`: `dist_moe`
package not installed locally.
- `test_initializes_one_stage_pipeline_runtime`: its `SimpleNamespace`
config lacks the new `dist_moe` field read at `trainer.py:108`.
- Bitwise-identical loss and grad_norm vs. `main`, 10 steps, `seed=42`,
`deterministic=True` (`scripts/loss_compare.py --assert-equal`): SPMD GA
first/last (FSDP=4), SPMD GA without FSDP (1 GPU), SPMD without GA
(FSDP=4).
- `precompile_main` / `trainer` import check passes.
- pre-commit clean.
* [config] Centralize built-in transform relations (#5007)
## Summary
Consolidate `run_after` and `conflicts_with` relation into one file,
rather than scattered for each transform.
This makes the import logic simpler and also less brain power to reason
about composability.
`run_after` is modeled by a direct graph `PRECEDES` with an edge `(a,
b)` meaning `a` must be applied before `b`.
`conflicts_with` is modeled by an undirected graph `CONFLICTS` with an
edge `{a, b}` meaning `a` and `b` cannot be applied together.
`PRECEDES` does not necessarily have to be a DAG (although I would
believe a set of reasonable transforms would keep it a DAG), but only
the induced subgraph on the user chosen valid set of transforms without
conflict should be a DAG.
## Not sure about this part but Codex insists
External users who implement their own transform outside of torchtitan
library should still be able to specify these relations,
so the class owned `run_after` and `conflicts_with` should be preserved?
* Always run Flux after the integration suite (#4850)
Flux always runs after run_tests on the fake-PG job and the real-PG
models job, including when run_tests failed. The job still fails if
either suite failed. Flux flavors also finish the rest of the suite
after a failure, same as run_tests. The features job still does not run
Flux.
---------
Co-authored-by: Cursor <[email protected]>
* [qwen3.5] Compile the shared expert's sigmoid gate (#5079)
Qwen3.5's MoE shared expert ends with an eager `sigmoid(gate) * out`
over `[T, 2048]`. This PR compiles it as the `shared_expert_gate` region
and turns it on in the Qwen3.5 defaults.
Kernel time, gate `[T, 1]` x out `[T, 2048]` bf16, eager -> region:
```text
H100 GB300
fwd+bwd T=16k 314 -> 153 us 202 -> 51 us
fwd+bwd T=64k 1214 -> 621 us 757 -> 193 us
fwd T=2k 11.7 -> 4.5 us 10.6 -> 5.7 us
fwd T=1 3.3 -> 1.1 us 3.6 -> 1.1 us
```
2 MoE layers of Qwen3.5-35B-A3B (GDN + attention), 16k tokens, fwd+bwd,
default regions on:
```text
H100 no AC 66.09 -> 65.81 ms SelectiveAC 83.10 -> 82.89 ms peak memory unchanged
GB300 no AC 28.11 -> 27.79 ms SelectiveAC 37.89 -> 37.34 ms
```
- Accuracy vs fp64 (16k, output and grads): rel L2 4.1e-3 eager, 1.7e-3
region. The region keeps the sigmoid in fp32; eager rounds it to bf16.
- `batch_invariant=True`, like `swiglu`: forward and grads are bitwise
equal when the batch is split (halves, uneven splits, single tokens).
- Recompiles: 3 graphs for train T = 16k, 8k, 2k plus no_grad 16k, 2k,
and 3 for the generator's CUDA graph sizes 2048 ... 1.
**Test plan**
- `tests/unit_tests/gpu/test_sigmoid_gate.py`: matches an fp32
reference; batch invariant.
- H100 with torch 2.15.0.dev20261004+cu132. The GB300 numbers are from
an earlier main (torch 2.15.0.dev20260926).
Co-authored-by: Felipe Mello <[email protected]>
* [CP][Attn] Delegate attention metadata ownership to attention backends (#4897)
## Summary
- Store model-level attention metadata by attention backend class, so
mixed
models can carry independent metadata for each backend.
- Let each inner-attention backend build its own metadata, and select
that
metadata before invoking each transformer layer.
- Rename `VarlenMetadata` to `VarlenAttentionMetadata` and preserve
backend-owned CP metadata preparation.
## Known limitation
Attention metadata is keyed by backend class. If the same backend class
is
configured differently across layers, metadata is currently built once
using
the first encountered configuration. Existing model configurations are
not
affected.
## Testing
- `SKIP=pyrefly-check pre-commit run --all-files`
- Targeted Pyrefly check of the common attention, CP, transform, and
validation
modules (0 errors)
- `pytest -q
torchtitan/experiments/graph_trainer/tests/test_simple_fsdp.py
tests/unit_tests/cpu/test_context_parallel_validation.py
tests/unit_tests/cpu/test_cp_attention.py
torchtitan/experiments/transformers_modeling_backend/tests/test_hf_build_forward_inputs.py
-k 'not test_every_cp_recipe_passes_the_gate'` (58 passed, 1 deselected,
2 subtests passed)
Rebased without conflicts onto `a3ffc9482` (PR head `e9136ed2c`), then
repeated the pre-commit and targeted CPU tests above successfully.
Retested PR commit `9acf7ac45` against parent commit `0b7536202`.
Deterministic parent-vs-PR comparisons used `seed=42` and 10 training
steps.
All used a shared seed checkpoint except the Transformers backend row,
which
used identical deterministic initialization. Values were read at full
precision from TensorBoard.
| Configuration | GPUs | Loss diff | Grad norm diff |
| --- | ---: | ---: | ---: |
| Llama 3 all-gather CP | 4 | 0 at every step | 0 at every step |
| Llama 3 Ulysses CP | 2 | 0 at every step | 0 at every step |
| Flux HSDP 2x2 + CP=2 with validation | 8 | 0 at every step | 0 at
every step |
| DeepSeek V3 MoE FSDP2 + TP2 + CP2 + EP8 | 8 | 0 at every step | 0 at
every step |
| Qwen3 MoE param groups FSDP2 + TP2 + CP2 + EP8 | 8 | 0 at every step |
0 at every step |
| Transformers backend MoE FSDP + TP + EP + CP (PTRR) | 8 | 0 at every
step | 0 at every step |
The GraphTrainer numerics CI currently reports a small Llama 3 mismatch
at
step 2. A control run from the rebased parent `0b7536202`, without this
PR,
reproduces the exact same values (`7.747598648071289` vs.
`7.747601509094238`), so this failure is not introduced by this PR.
* [optim] Hold the final LR when training runs past lr_scheduler.total_steps (#5057)
`lr_scheduler.total_steps` decouples the LR schedule from
`training.steps`. When it is smaller than `training.steps`, the steps
after the schedule ends keep extrapolating the decay, because `progress`
in `linear_warmup_stable_decay` is never capped at 1:
- linear and sqrt decay go below `min_lr_factor` and then negative
- cosine decay climbs back up toward the peak LR
- with `decay_ratio=0.0` (no decay phase), the first step past the
schedule fails `assert decay_steps != 0`
LR used at steps 1..10 with `training.steps=10`,
`lr_scheduler.total_steps=6`, `warmup_steps=2`, `min_lr_factor=0.1`,
base LR 1.0 (main at d09c6f5):
```
linear [0.5, 1.0, 1.0, 0.775, 0.55, 0.325, 0.1, -0.125, -0.35, -0.575]
sqrt [0.5, 1.0, 1.0, 0.55, 0.3636, 0.2206, 0.1, -0.0062, -0.1023, -0.1906]
cosine [0.5, 1.0, 1.0, 0.8682, 0.55, 0.2318, 0.1, 0.2318, 0.55, 0.8682]
linear, decay_ratio=0.0: 1.0 for steps 2..7, then AssertionError: decay_steps must not be zero to reach this branch
```
### Change
- Clamp the step at the top of the schedule function to the schedule's
last step, so steps past `total_steps` hold its final LR (`min_lr_factor
* lr` here). This covers warmup, stable and decay alike, including
`decay_ratio=0.0`.
- Warn in `build()` when `total_steps < training.steps`, and say on the
`total_steps` field that the LR is held at its final value for the
remaining steps.
With this change all four cases above hold at 0.1 (or 1.0 for
`decay_ratio=0.0`) from step 7 on. Runs where `total_steps` is unset or
at least `training.steps` are unchanged, since the clamp never applies
there.
### Test plan
New `test_steps_beyond_total_steps_hold_final_lr` in
`tests/unit_tests/cpu/test_lr_scheduler.py` covers the four cases above:
from the schedule's last step on the LR equals the final value, and the
steps inside the schedule match a schedule built without `total_steps`.
Its four subtests fail on main and pass with this change.
Run locally (macOS, CPU):
```
pytest tests/unit_tests/cpu/test_lr_scheduler.py tests/unit_tests/cpu/test_optim.py \
tests/unit_tests/cpu/test_checkpoint.py tests/unit_tests/cpu/test_trainer.py
124 passed, 21 subtests passed
```
`pre-commit run --files` on both files passes; `pyrefly check` (0.45.1)
reports the same result on this branch and on main.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
* ChunkedLossWrapper: free each chunk's logits before its backward (#5082)
**TLDR:** `ChunkedLossWrapper` now frees each chunk's logits before that
chunk's backward. Peak memory drops by 0.58-1.16 GiB for Qwen3-8B;
results are bitwise identical and speed is unchanged.
**Problem**
1. `ChunkedLossWrapper` runs lm_head + loss on one chunk, then
`chunk_loss.backward()`.
2. The `logits` variable keeps that chunk's `[T, V]` logits alive
through the backward, which doesn't need them.
3. So each backward holds one extra buffer: 1.16 GiB per 2048-token
Qwen3-8B chunk with fp32 logits, 0.58 GiB with bf16.
**Solution:** `del logits` right after the loss call.
**Results**
Qwen3-8B head, 16384 tokens in 8 chunks, H100, peak memory during the
call:
```text
CastLinear head (fp32 logits) 8.46 -> 7.30 GiB eager and compiled CE
bf16 Linear head 5.47 -> 4.89 GiB eager CE
3.78 -> 3.20 GiB compiled CE
```
Loss, dX and dW are bitwise identical. Speed is unchanged: paired over 8
rounds, within ±0.8 ms of a ~250 ms call.
**Test plan**
- Re-checked on current main (H100, torch 2.15.0.dev20261004): same
savings, bitwise identical loss, dX and dW.
- CPU `test_loss`, `test_lora`, `test_override` and graph_trainer
`test_chunked_loss`: 89 passed.
NOTE: measured on H100; needs retesting on Blackwell.
Co-authored-by: Felipe Mello <[email protected]>
* [docs] Correct stale README launch commands (#5078)
## Summary
Four README commands named modules, configs, or an entrypoint that do
not resolve. tianyu-l asked to land these doc fixes in one PR and to
drop the README guard tests, so #5075, #5076, and #5077 are folded in
here. No unit test is added.
- DeepSeek-V3 16B. `torchtitan_recipes.models.deepseek_v3` defines
`deepseek_v3_671b` and the two 671B Dist-MoE recipes. `deepseek_v3_16b`
lives in `torchtitan_recipes.tests.models.deepseek_v3`, next to
`deepseek_v3_debugmodel`, and does not require Dist-MoE. The 16B command
now uses that tests module. The 671B command stays
`MODULE=torchtitan_recipes.models.deepseek_v3 CONFIG=deepseek_v3_671b`.
- GraphTrainer DeepSeek. `graph_trainer_deepseek_v3_16b` is not defined.
The production module `torchtitan_recipes.graph_trainer.deepseek_v3`
provides `graph_trainer_deepseek_v3_671b_dist_moe_bf16` and the MXFP8
variant. The quick start now runs the BF16 671B Dist-MoE recipe, next to
the production Llama3 and Qwen3 commands. The heading says 671B
Dist-MoE. The 16B name exists only as
`graph_trainer_deepseek_v3_16b_dist_moe_bf16` under
`torchtitan_recipes.tests.graph_trainer`, and that recipe requires
Dist-MoE.
- NVFP4 Llama 3 8B. `Trainer.Config` has no `optimizer` field. The
learning rate is `config.optim.optimizer.optimizers[0].lr`
(`Optim.Config.optimizer` is an `OptimizersContainer.Config`, and that
config's `optimizers` list holds the AdamW config).
`config.optimizer.optimizers[0].lr` raises AttributeError.
- Search-R1. `python torchtitan/rl/train.py` inserts the script
directory `torchtitan/rl` at `sys.path[0]` and does not put the repo
root on `sys.path`, so `import torchtitan` fails unless the package is
installed. `python -m torchtitan.rl.train` puts the current directory on
`sys.path`. `--module` and `--config` are unchanged. The Results
permalinks `e28796e0` and `4b183e3a` stay as historical links.
## Test plan
- [ ] Docs only. The four commands name callables and an entrypoint that
exist on this branch. No unit test is added.
* [CP] Support Kimi K3 KDA CP (#4639)
## Summary
This PR replaces #4500 so the branch can participate in GitHub's native
PR
stacks.
Enable context parallelism for Kimi K3's hybrid KDA/MLA decoder and
multimodal input path.
- KDA layers use Attention Gym's native context-parallel implementation.
Each
rank keeps its local sequence fragments while exchanging the
short-convolution
history and composing the recurrent state from preceding fragments.
- MLA layers can use all-gather K/V CP with contiguous or headtail
partitions,
or Ulysses CP with contiguous partitions.
- Multimodal preprocessing shards token-aligned vision-bank indices with
the
token IDs, allowing each rank to map replicated vision-encoder outputs
to its
local placeholders.
KDA and MLA reuse the same TorchTitan CP mesh. The all-gather
configuration
supports contiguous and headtail partitions across the hybrid model; the
Ulysses configuration requires contiguous partitioning.
## Implementation
The integration follows Attention Gym's [delta-rule context-parallel
example](https://github.com/meta-pytorch/attention-gym/blob/main/examples/linear/delta_rule_context_parallel.py).
The KDA path separates its local stages so the CP adapter can replace
only the
distributed operations while sharing projection, normalization, gating,
and
output logic with the non-CP path. Attention Gym provides:
- `context_parallel_conv_history` for convolution halo exchange; and
- `context_parallel_kda` for recurrent-state summary composition and the
local
KDA computation.
TorchTitan builds an Attention Gym routing plan that matches its
contiguous or
headtail token assignment and passes the per-batch routing through every
KDA
layer.
## Limitations
- KDA CP currently supports contiguous and headtail partitions; PTRR is
not
supported.
- Ulysses MLA requires contiguous partitioning; it does not support
headtail.
- Current TorchTitan partitioning requires equal-sized fragments, where
`T` is
the token count and `C` is the CP degree:
- contiguous: `T % C == 0`
- headtail: `T % (2 * C) == 0`
This is a limitation of the current PyTorch/TorchTitan equal-sized
sharder,
not Attention Gym; Attention Gym routing accepts arbitrary fragment
ranges.
- Kimi K3 sample packing is not yet supported. Routing currently models
the
batch as one global sequence.
## Tests
**CP=1 regression check**
| Step | Before PR loss (CP=1) | This PR loss (CP=1) | Diff | Before PR
grad norm (CP=1) | This PR grad norm (CP=1) | Diff |
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | `8.084497` | `8.084497` | `0.000%` | `2.531250` | `2.531250` |
`0.000%` |
| 10 | `3.574754` | `3.574754` | `0.000%` | `2.562500` | `2.562500` |
`0.000%` |
| 100 | `3.089925` | `3.089925` | `0.000%` | `5.156250` | `5.156250` |
`0.000%` |
**CP=2 loss vs. the before-PR CP=1 baseline**
| Step | Before PR (CP=1) | This PR all-gather (CP=2) | Diff | This PR
Ulysses (CP=2) | Diff |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | `8.084497` | `8.084440` | `0.001%` | `8.084446` | `0.001%` |
| 10 | `3.574754` | `3.576608` | `0.052%` | `3.571825` | `0.082%` |
| 100 | `3.089925` | `3.060069` | `0.966%` | `3.051986` | `1.228%` |
**CP=2 grad norm vs. the before-PR CP=1 baseline**
| Step | Before PR (CP=1) | This PR all-gather (CP=2) | Diff | This PR
Ulysses (CP=2) | Diff |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | `2.531250` | `2.531250` | `0.000%` | `2.531250` | `0.000%` |
| 10 | `2.562500` | `2.562500` | `0.000%` | `2.546875` | `0.610%` |
| 100 | `5.156250` | `5.062500` | `1.818%` | `5.031250` | `2.424%` |
* [1/3] [graph_trainer] Extract FSDP split-pad-cat together with reduce_grad chains (#5058)
FSDP reduce grad chains can contain split-pad-cat before reduce_grad.
We should extract them into REDUCE_GRAD to not execute it in the
middle-repeated microbatch no unshard , no reduce logic.
This PRs includes split-pad-cat into those chains.
Before:
# Every microbatch
cast_grad = grad.to(reduce_dtype)
chunks = torch.split(cast_grad, ...)
padded = torch.nn.functional.pad(chunks[-1], ...)
packed_grad = torch.cat((*chunks[:-1], padded))
grad_accumulator.add_(packed_grad)
# Final reduce_grad
reduced_grad = reduce_scatter_tensor(grad_accumulator, ...)
We follow SimpleFSDP annotations to include them.
cast_grad is left in grad computation, to keep it before grad
accumulation.
To have:
grad_accum = cast_bf16(g0) ... cast_bf16(gN).
This matches eager grad accumulation.
After:
# Every microbatch
cast_grad = grad.to(reduce_dtype)
grad_accumulator.add_(cast_grad)
# Final reduce_grad
chunks = torch.split(grad_accumulator, ...)
padded = torch.nn.functional.pad(chunks[-1], ...)
packed_grad = torch.cat((*chunks[:-1], padded))
reduced_grad = reduce_scatter_tensor(packed_grad, ...)
* [2/3] [graph_trainer] Fuse WGrad accumulation through views (#5059)
Depends on #5058.
Matmul often followed by view operations.
We need to handle this to do WGrad accumulation.
We fuse grad accumulation before this view op.
Before:
grad_2d = mm(lhs, rhs)
grad_3d = grad_2d.reshape(1, 3, 2)
result = accumulator_3d.add_(grad_3d)
When the path contains only single-user storage aliases, view the
accumulator in the producer shape and let the GEMM accumulate directly
into its storage.
After:
accumulator_2d = accumulator_3d.view(3, 2)
grad_2d = addmm_(accumulator_2d, lhs, rhs)
result = grad_2d.reshape(1, 3, 2)
* [3/3] [graph_trainer] Bucket routed experts by parent scope (#5067)
## Stack
1. #5058
2. #5059
3. This PR
## Summary
Bucket the routed-expert `w13` and `w2` FSDP collectives using their
captured parent scope, `layers.N.moe.routed_experts`.
The traced collective nodes are annotated with the parent scope, while
the bucket plan previously named the `w13` and `w2` child scopes. Those
entries therefore did not match the captured nodes, leaving two
routed-expert buckets per MoE layer. Using the parent scope combines
them into one bucket.
## 256-GPU result
DeepSeek V3 671B DistMoE on 256 GB300 GPUs:
- Cat-fix-only GraphTrainer: 5,670.50 tokens/s/GPU
- GraphTrainer with parent-scope bucketing: 5,830.50 tokens/s/GPU
- Improvement: +2.82%
- Same-cluster eager baseline: 5,822.00 tokens/s/GPU
- GraphTrainer versus eager: +0.15%
- Peak memory: 249.38 GiB versus 265.08 GiB eager
The profile shows all-gathers and reduce-scatters decreasing from 179 to
121 each, removing exactly one of each from all 58 MoE layers. The
experimental dense-overlap scheduler was disabled, so it did not
contribute to this result.
* [rl] Fix RL CPU unit tests resolving a month-old torch nightly (#5083)
## Why
RL CPU Unit Tests is red on `main` and on every PR that runs it. Four
test modules fail at collection:
```
ERROR tests/rl/unit_tests/cpu/test_alphabet_sort.py
ERROR tests/rl/unit_tests/cpu/test_verifiers_example.py
ERROR tests/rl/unit_tests/cpu/test_vllm_registry.py
ERROR tests/rl/unit_tests/cpu/test_vllm_wrapper.py
E ImportError: cannot import name 'analyze_pipeline_activation_liveness' from 'torch.distributed.pipelining'
```
The cause is the torch the job ends up with. The CPU job resolves `torch
2.15.0.dev20260830` + `vllm 1.0.0.dev20260830`, while the RL GPU jobs in
the same run get `20261005` for both. The CPU job installs the Verifiers
example requirements first and then passes them as a `--constraint` to
the nightly install:
- `verifiers==0.3.1` requires `mcp>=1.24.0,<2`.
- vLLM nightlies since about 2026-10-01 require `mcp>=2.0.0,<3.0.0`.
uv therefore falls back to the newest vLLM that accepts mcp 1.x
(`1.0.0.dev20260830`), which pins a torch from the same day. That torch
predates `analyze_pipeline_activation_liveness`, which `dist_moe`
started importing in #4541.
To reproduce, force a current vLLM next to the Verifiers requirements:
```
$ uv pip compile in.txt --prerelease allow ... # vllm>=1.0.0.dev20261001, verifiers==0.3.1
× No solution found when resolving dependencies:
╰─▶ Because vllm>=1.0.0.dev20261001+cu132 depends on mcp>=2.0.0,<3.0.0 [...]
And because you require mcp>=1.24.0,<2, we can conclude that your
requirements are unsatisfiable.
```
## What
- Install torch/torchvision/vLLM nightlies the same way the RL GPU jobs
do (no Verifiers constraint), then run the CPU suite. The plain DAPO
example requirements
(`torchtitan/rl/examples/dapo_math/requirements.txt`, i.e.
`math-verify==0.9.0` for `test_dapo_math.py`) are still installed first
and passed as a constraint. They resolve fine with the current
nightlies.
- After that, install the Verifiers requirements with the installed
torch/torchvision/vLLM versions as constraints, and run
`test_verifiers.py` and `test_verifiers_example.py`. Verifiers only
changes its own dependencies: uv swaps `mcp` 2.x -> 1.30.0 and
`websockets` 17.1 -> 16.1.1 and leaves the nightlies alone.
- Add `pytest.importorskip("verifiers")` to `test_verifiers.py`, the
same guard `test_verifiers_example.py` already has, so the first run
skips it instead of failing at collection.
- Drop the `mcp>=1.24.0,<2` line from `dapo_math/requirements.txt`. It
only existed to constrain the nightly install, and `verifiers==0.3.1`
already requires the same bound.
## Tests
Run locally with torch `2.15.0.dev20260926` and vLLM `1.0.0.dev20260926`
(mcp 2.2.0):
- First run, without Verifiers: `pytest tests/rl/unit_tests/cpu` gives
474 passed, 6 skipped. That includes the three non-Verifiers modules
above; both Verifiers files skip with "could not import 'verifiers'".
- Second run, with `verifiers==0.3.1` installed on top:
`test_verifiers.py` and `test_verifiers_example.py` give 11 passed, and
vLLM still imports with mcp 1.30.0.
- Dry run of the new `uv pip install -r .../requirements.txt
--constraint <nightly pins>` against that env: it installs 19 packages,
changes only `mcp` and `websockets`, and leaves torch/torchvision/vLLM
untouched.
- `uv pip compile` of the nightlies plus `math-verify==0.9.0` resolves
to torch/vLLM `20261005`.
- CI on the first commit picked up torch/vLLM `20261005`, but
`test_dapo_math.py` failed to collect because `math_verify` was missing.
That's fixed by the DAPO requirements step above.
## Follow-up
Outside CI, the Verifiers example still can't share an environment with
current vLLM nightlies, since `verifiers==0.3.1` needs `mcp<2`. The
`verifiers` 0.3.2 dev releases move to `mcp==2.0.0`, but they also
require `renderers>=0.1.12.dev2`, while torchtitan pins
`renderers==0.1.11`. Bumping `verifiers` makes sense once a 0.3.2
release is out.
* [rl] Keep only the NCCL env vars batch invariance needs (#5081)
## Why
`set_batch_invariance` copied all ten NCCL env vars from vLLM's
`override_envs_for_invariance()`, without saying why each one is there.
Most of them are either no-ops or redundant. One isn't an NCCL variable
at all, and one has an invalid value. One of the redundant ones
(`NCCL_NVLS_ENABLE=0`) also turns off NVLS for FSDP
all-gather/reduce-scatter in every batch-invariant training run.
Batch invariance only needs the cross-rank reduction to sum each element
in the same order regardless of message size (that is, token count). The
TP all-reduce is the only collective in a batch-invariant forward that
reduces across ranks: the RL controller rejects sequence parallel, and
FSDP reduce-scatter only runs in backward.
## What
Keep two vars:
- `NCCL_ALGO=allreduce:tree`: tree sums each element along one fixed
tree for every message size. Ring's order depends on how the message is
chunked. Pinning the all-reduce to tree also rules out NVLS and CollNet
for it.
- `NCCL_MAX_NCHANNELS=1`: NCCL builds two inter-node trees and
alternates channels between them (`connectTrees` in
`src/graph/connect.cc`). With several channels, which tree reduces a
given element depends on the message size. With one channel there is
only one tree.
Drop eight vars:
| Var | Why it can go (NCCL 2.30 source) |
|---|---|
| `NCCL_P2P_NET_DISABLE=1` | Not an NCCL variable. |
| `NCCL_NTHREADS=1` | Not a multiple of 32, so `getNthreads`
(`src/graph/tuning.cc`) rejects it as invalid and uses the max thread
count. |
| `NCCL_LAUNCH_MODE=GROUP` | Only toggles a launch barrier for grouped
launches (`src/group.cc`); arithmetic is unchanged. |
| `NCCL_SOCKET_NTHREADS=1` | Helper threads for the socket transport;
only moves bytes. |
| `NCCL_PROTO=Simple` | Simple, LL, and LL128 all sum in the order
`((own + child0) + child1) + child2`, so the protocol doesn't change the
result. |
| `NCCL_MIN_NCHANNELS=1` | No effect once the max is 1. |
| `NCCL_NVLS_ENABLE=0`, `NCCL_COLLNET_ENABLE=0` | Already ruled out for
the all-reduce by `NCCL_ALGO=allreduce:tree`. |
`torchtitan/rl/docs/bitwise_parity.md` is updated to match.
## Tests
Setup: torch 2.15 nightly (cu130), NCCL 2.30.7, vLLM 1.0.0.dev20260926,
a single node with 7x H100.
**1. NCCL all-reduce probe.** Each rank all-reduces bf16 `[num_tokens,
4096]` for `num_tokens` in {1, 2, 7, 33, 128, 511, 2048, 8191, 32768}.
Row `r` holds the same input for every `num_tokens`, and the check is
whether row `r` of the output is bitwise identical across all sizes.
| Env | TP=2 | TP=4 | TP=7 |
|---|---|---|---|
| none (NCCL default) | invariant | **variant** | **variant** |
| all 10 vars (before) | invariant | invariant | invariant |
| `ALGO` + `MAX_NCHANNELS` (after) | invariant | invariant | invariant |
| `ALGO` only | invariant | invariant | invariant |
| `MAX_NCHANNELS` + `PROTO`, no `ALGO` | invariant | **variant** |
invariant |
TP=2 is always invariant, because summing two operands gives the same
result in either order. The existing TP=2 parity recipes therefore can't
catch a cross-rank reduction-order bug.
**2. End-to-end bitwise parity at TP=4.** `TestBitwiseParityVarlen`
(Qwen3-0.6B) with trainer and generator TP set to 4:
- With this PR: 3/3 pass (`test_batch_invariance`,
`test_trainer_vs_vllm_prefill`, `test_vllm_decode_vs_prefill`).
- Negative control, same run with `NCCL_ALGO` removed: all 3 fail
(max_delta 2.4e-2, 7.4e-2, and 7.0e-3). The test does detect the
all-reduce algorithm.
**Not tested:** multi-node. Keeping `NCCL_MAX_NCHANNELS=1` and dropping
`NCCL_PROTO` are both based on reading the NCCL source, not on a
multi-node run.
<details>
<summary>NCCL probe script</summary>
```python
import os
import torch
import torch.distributed as dist
HIDDEN = 4096
NUM_TOKENS = [1, 2, 7, 33, 128, 511, 2048, 8191, 32768]
dist.init_process_group("nccl")
rank = dist.get_rank()
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
gen = torch.Generator(device="cuda").manual_seed(1234 + rank)
base = torch.randn(max(NUM_TOKENS), HIDDEN, generator=gen, device="cuda").to(torch.bfloat16)
results = {}
for n in NUM_TOKENS:
x = base[:n].clone()
dist.all_reduce(x)
results[n] = x
ref = results[max(NUM_TOKENS)]
mismatched = [n for n in NUM_TOKENS if not torch.equal(results[n], ref[:n])]
if rank == 0:
print("invariant" if not mismatched else f"variant at {mismatched}")
dist.destroy_process_group()
```
Run with `torchrun --standalone --nproc_per_node=<TP> probe.py` under
each env setting.
</details>
* Add precomputed routing for weight sync (#5061)
<!-- forkstack:stack:start -->
---
Stack (top to bottom):
- -> #5061 Add precomputed routing for weight sync
---
<!-- forkstack:stack:end -->
Integrate Titan to optionally use the new locally cached routing plan.
Currently, we look up and creating the routing plan every time weights
need to be pulled on the generator. This change speeds up weight
transfer by dispatching the requests faster. This also unblocks features
in Titan e.g. pipeline parallel that need merged state_dict's from
multiple trainers and dtype conversion inside torchstore.
# API Changes
- Pass an enum to `ts.initialize()` that initializes torchstore in the
new mode - a lightweight API that spawns ts actors
- Have Titan explicitly initialize ts client with `ts.client(role=...)`
- this tells ts who stores the data and who needs to get the data
# How it works
There is some metadata exchange that happens lazily on the first
`get_state_dict` and `put_state_dict`
### First `put_state_dict`
The trainer ts clients send state dict metadata to a coordinator
### First `get_state_dict`
The generator ts clients
- Wait for all trainers to register their metadata with the coordinator
- Build and cache a routing plan after they get all the metadata from
trainers
Co-authored-by: Tushar Jain <[email protected]>
* Make AllToAll dispatch and combine single remat regions (#4958)
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4893
* #5070
* __->__ #4958
Human note
----------
* With EP > 1, the all-to-all dispatcher declares two remat regions,
`dispatch` and `combine`. The previous regions covered only the
all-to-all collectives; these also cover the processing around them.
* With EP = 1 there is no communication, so dispatch and combine are not
regions; they are always recomputed.
* The combine now multiplies the bf16 expert outputs by the fp32 router
scores instead of casting them to fp32 first. The product is still
computed in fp32, but the multiply now saves the bf16 input for backward
instead of an fp32 copy. This is unrelated to remat but lands in the
same commit.
Agent note
----------
Before, the split sync ran as a bare op, so it replayed in every
backward
(one host sync per MoE layer) even with `ep_communication` saved. The
operator-level SelectiveAC avoided this by always saving CUDA -> CPU
copies;
a saved `dispatch` region gives a torch_remat policy the same behavior.
The
pins on the all-to-all outputs and on the w2 output are gone, since
those
tensors are now region inputs or outputs: when w2 and the combine are
both
saved, the w2 output is no longer kept.
Regions return only tensors, so the splits come back as CPU tensors and
the
pre-permute shape is derived from them; TorchAO's padded `_unpermute`
allocates and strips its sentinel row itself. Without EP there is no
communication, so the local dispatch and combine stay bare. Bare readers
of
the routed-expert outputs (the dtype cast and postprocess after w2, the
local
scatter-add, the TP zero-fill, the shared-expert add, and the
DeepEP/HybridEP
kernels) call `recompute_needs_tensor` before they read.
The combine also multiplies the bf16 expert outputs by the float32
router
scores directly instead of casting them to float32 first. Type promotion
still
computes the product in float32, but the multiply now saves the bf16
output for
backward rather than a float32 copy twice its size. The local,
all-to-all, and
TorchAO EP=1 combines share `_score_and_scatter_add`. Losses are bitwise
identical; on qwen3 MoE (30B-A3B width, 4 layers, TP2 EP2) activation
memory
without AC drops from 6.5 GiB to 5.5 GiB (256 MiB per layer).
* Fix per-depth MTP loss normalization (#5055)
## Summary
- compute distinct per-depth loss-token and routing-token counts in the
data pipeline, with MTP depth synchronized into dataloader/batcher
config
- carry local counts on microbatches; standard trainers only
accumulate/reduce them, while the RL batcher supplies global counts
- normalize every MTP objective and MoE auxiliary loss with its matching
denominator across packed-sequence and padding boundaries
- forward the optional auxiliary-loss denominator uniformly through
dense and MoE transformer blocks
## Testing
- 252 focused model, loss, MoE, trainer, and config CPU tests
- 179 focused data, trainer, validation, and Flux CPU tests
- 4x H100 real FSDP run, 10 steps: identical loss/grad norm across
ranks, loss 10.50247 -> 5.14992
- 4x H100 real TP+CP MTP integration run, 10 steps
- `pre-commit run --all-files` (all gates except local Pyrefly, whose
installed PyTorch lacks current nightly APIs)
* Fix MXFP8 DCP checkpoint serialization (#5094)
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #5094
MXFP8Linear installs _LinearShardedTensorWithMXFP8Compute as its
nn.Parameter. DCP plans it as an ordinary tensor entry, but when writing
it
asks the tensor for its data through __get_tensor_shard__, and
_ShardedFSDPTensor does not implement that hook. DCP therefore writes
the
wrapper itself, and torch.save pickles the wrapper class along with the
plain high-precision shard it holds in _tensor. The read then fails,
since
torch.load runs under weights_only=True:
_pickle.UnpicklingError: Weights only load failed.
WeightsUnpickler error: Unsupported global: GLOBAL
torchtitan.quantization.mxfp8.tensor._LinearShardedTensorWithMXFP8Compute
was not an allowed global by default
Saving succeeds, so this surfaces only on resume. Any MXFP8 run that
resumes from a DCP checkpoint is affected. #4203 added both the class
and
the parameter wrap.
_ShardedFSDPTensor already documents itself as "the nn.Parameter the
optimizer updates and the checkpoint stores", and quantized operands are
rebuilt per unshard by _build_operands, never checkpointed. So _tensor
is
the shard DCP should persist: high-precision data, byte-identical to
what
an unconverted model writes, and loadable by a model built without the
converter. Under FSDP the parameter is a DTensor, whose
__get_tensor_shard__ forwards to its local tensor's hook.
The test clears torch.serialization's safe globals around the save and
load, so the load fails if the wrapper class is pickled into the
checkpoint even when another import has allowlisted it.
Verified on 2 nodes: save at step 2, resume at step 6. Also verified at
671B on 16 nodes, where the MXFP8 attention arm resumed with no
UnpicklingError.
Co-Authored-By: Claude Opus 5 <[email protected]>
* Save trailing adds so replay skips them (#5070)
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4893
* __->__ #5070
`torch.utils.checkpoint` stops replay once every tensor saved under the
checkpoint has been recomputed, so it never reruns the trailing ops of a
block
that save nothing. `remat.checkpoint` replays the whole block, so the
bare
end-of-block residual add and the shared-expert add replayed, and their
`recompute_needs_tensor` markers kept their inputs (e.g. the MoE combine
output
and the shared-expert output) alive from the forward until replay.
Make these adds fixed `recompute=False` regions (`ffn_residual`,
`moe.shared_add`) and drop the markers. A saved add keeps nothing
resident
because it saves nothing for backward, its inputs need no persisting,
and
replay skips it, matching checkpoint early stop. Trailing ops that save
what
they produce, such as Muse Glimmer's `post_ffn_norm`, stay bare.
With every region saved (RegionAC `*`), activation memory drops from
8.18 to
7.93 GiB on qwen3 MoE (30B-A3B width, 4 layers, FSDP4 + EP4) and from
9.11 to
8.67 GiB on DeepSeek V3 16B (same setup), one tensor per layer plus one
more
per layer with shared experts, at the same step time; losses are bitwise
identical.
* [1/2] [graph_trainer] Support MTP in single-stage schedules (#5091)
MTP preprocessing returns `(main, mtp)` tuples for both model inputs and
labels. The single-stage GraphTrainer path still asserted that each
value was one tensor, so it rejected a valid MTP batch before tracing.
This removes that single-tensor restriction and lets the existing
runtime carry the tuple structure unchanged:
```text
preprocess -> ((tokens, mtp_tokens), (labels, mtp_labels), kwargs)
```
* Support multiple EMA copies (#5074)
This is a follow-up of https://github.com/pytorch/torchtitan/pull/3985.
It allows EMA to keep track of multiple copies by having a mixture of
`decays` and `half_life_fractions` as the input list. As a results, we
can now support both decay mode and half_life_fractions mode.
It still maintains one `ema` checkpoint key. Each tensor's state now
holds one copy per entry, flattened by DCP to
`ema.state.<fqn>.ema_params.<ema_key>`. The decays and half-life
fractions are flattened into one list of copies, and each copy is
updated independently on the same firing. The CPU-offload path is
unchanged; it runs once per copy on the same side stream.
* [debug] Save the device-mesh layout with `debug.save_parallelism_file` (#5045)
## Parallelism Layout Debug File
Add a new debug option, `config.debug.save_parallelism_file`, which is
**disabled by default**.
When enabled, rank 0 writes a JSON file to `<dump_folder>/<file>`
describing how `ParallelismContext.build_mesh` laid out the world:
```json
{
"world_size": 8,
"degrees": {
"pp": 1,
"dp_replicate": 1,
"dp_shard": 8,
"cp": 1,
"tp": 1,
"ep": 4
},
"ranks": [
{"host": "node-a", "local_rank": 0, "global_rank": 0},
...
{"host": "node-a", "local_rank": 3, "global_rank": 7}
],
"meshes": {
"dense": {
"axis_names": ["pp", "dp_replicate", "dp_shard", "cp", "tp"],
"mesh": [...]
},
"sparse": {
"axis_names": ["pp", "dp_replicate", "edp_shard", "ep"],
"mesh": [[[[0, 1, 2, 3], [4, 5, 6, 7]]]]
}
}
}
```
The option is wired into **Trainer**, the **TorchFT trainer**, and the
**RL trainer**
### Why
`debug.save_config_file` records the **requested** parallelism degrees,
but it does not capture the **resulting rank and mesh layout** produced
by `ParallelismContext.build_mesh`.
This debug file makes the actual layout inspectable. In particular, it
provides an easy way to verify that **expert parallelism (EP) is placed
intra-node**, which is important in setups where communication across
nodes is significantly slower than communication within a node.
* [rl] Fix loss_token_counts asserts in test_async_controller (#5100)
**TLDR:** RL CPU Unit Tests have been red on main since ed35bdaed. This
fixes the two broken asserts in `test_async_controller.py`.
**Problem**
1. ed35bdaed changed two asserts to
`torch.testing.assert_close(microbatch.loss_token_counts,
torch.tensor(N))`.
2. The file never imports `torch`, so both tests fail with `NameError:
name 'torch' is not defined`.
3. With the import added, they still fail: `torch.Size([1]) !=
torch.Size([])`.
4. `get_mtp_token_counts` returns one count per depth, so with no MTP
layers `loss_token_counts` has shape `(1,)`.
**Solution**
1. Add `import torch`.
2. Compare against `torch.tensor([8])` and `torch.tensor([3])`.
**Test plan**
```
pytest -q tests/rl/unit_tests/cpu/test_async_controller.py
before: test_batcher_uses_flat_rank_capacity_and_reports_padding, test_flat_rank_packing_preserves_padding_mask -> NameError
after: 32 passed
```
NOTE: I deselected `test_controller_config_maybe_log` locally because my
env has an older torchstore (no `RankRole`). It passes in CI.
Co-authored-by: Felipe Mello <[email protected]>
* [Data] Add tool call capability for ChatProcessor (#5098)
Add tool support for multiturn SFT chat data as mentioned by
https://github.com/pytorch/torchtitan/pull/2769#issuecomment-5654985510
## Summary
- Add an optional `tools_fn` to `ChatProcessor.Config`.
- Pass per-sample tool definitions to `renderer`-based chat processing.
## Test Plan
python -m unittest tests.unit_tests.cpu.test_chat_dataset
18 tests passed.
* Add HiMidLoLinear for the LM head and router gate; delete CastLinear and RouterGateLinear (#4923)
**Update after review 5** (rebased on main):
- Renamed `FP32OutputLinear` to `HiMidLoLinear`
(`torchtitan/models/common/hi_mid_lo_linear.py`), after the hi, mid and
lo pieces of its backward. `LMHeadFP32OutputConverter` keeps its name:
it exists for the fp32 logits.
- The split's custom op is gone. graph_trainer runs with local_compile
regions off, so it never traces the compiled split. The op also hid the
split from Inductor when it compiles the whole backward (graph_trainer's
full mode, an outer `torch.compile`), where dropping the
`.to(bf16).float()` round trip zeroes every piece after the first. The
split now upcasts its pieces with an integer shift, which leaves no
round trip to drop, so `emulate_precision_casts` is gone too. Run
uncompiled (graph_trainer's regional mode), the layer's backward is 5-7%
slower; graph_trainer's full mode gets faster (LM-head forward +
backward 20.5 -> 16.5 ms, H100).
- The region is `fp32_to_bf16_split`, and the split's argument is
`tensor`.
- `backward_mode: Literal["hi_mid", "hi_mid_lo"]`, default "hi_mid",
named after the pieces (the 2-piece split is hi + mid); the router gates
set "hi_mid_lo".
- RL loss reference, steps 3-10: the LM head's grad_weight is now fp32,
where `CastLinear` rounded it to bf16, and FSDP2 in recent torch
nightlies keeps it, so the rollouts diverge from step 3.
- Docstrings: why chunking the grad_input sum helps when the GEMM
already accumulates in fp32, and when our pieces equal cuBLAS BF16x9's
a0, a1, a2 bit for bit.
**Update after review 4**:
- `FP32OutputLinear` moved to
`torchtitan/models/common/fp32_output_linear.py`.
- `higher_precision_bwd` -> `backward_mode: Literal["bf16x2",
"bf16x3"]`, default "bf16x2"; the router gates set "bf16x3".
- The split rounds each piece with `.to(torch.bfloat16)`, ties to even:
cuBLAS BF16x9's a0, a1, a2 without their scales. It is compiled with
`emulate_precision_casts`, so it matches eager bit for bit, with the
same errors as before and faster than the integer bit ops it replaces.
- The split is the `fp32_output_split` local_compile region. The LM-head
converter and the models with FP32OutputLinear routers turn it on. It
uses `dynamic=True`, so at most 4 graphs.
- NOTE: the split timings in the docstrings and the tables below are
being regenerated on GB300.
**Update after review 3** (rebased on main):
- Every piece is rounded to nearest instead of truncated: LM-head
grad_weight error 1.6e-5 -> 8.4e-6, router grad_input 4.9e-6 -> 2.4e-6
(2 pieces, GB300).
- `exact_grad_output_split` -> `higher_precision_bwd`, default False;
the router gates set it to True.
- The backward has one function per layout, and the split runs as one
compiled kernel behind a custom op
(`torchtitan::split_into_bf16_pieces`).
- NOTE: CI compares golden losses exactly, so the MoE goldens need
regenerating from this PR's CI run.
TLDR:
(Check the tables below)
- We want some layers to be computed in Fp32, e.g. lm_head and router
gate
- For the head, we use CastLinear, which sets weight.to(fp32) every
forward
- The weight is a huge matrix (248k vocab for Qwen3.5), so each forward
copies it to fp32 and runs a slow fp32 GEMM
- BF16x9 (the trainer's fp32 matmul emulation) is faster, but still slow
- TF32 is faster, but imprecise
- This PR instead does `torch.mm(out_dtype=float32)`, which does the
GEMM in bf16, but accumulates in fp32 (check the table).
- This is already what `RouterGateLinear` does
- However, in this PR we improved the backward by running only 2 out of
the 9 GEMMs: fwd/bwd go from 55.7 ms (`RouterGateLinear`'s BF16x9
backward) to 18.9 ms, or 18.0 ms compiled
- We deleted `CastLinear` and `RouterGateLinear`, and unified the code
under `HiMidLoLinear`
- The router splits grad_output into 3 bf16 pieces (exact), the LM head
into 2; see "2 vs 3 pieces" below
### Controlled results
1x GB300, the real Qwen3.5-27B lm_head weight (vocab 248320, hidden
5120) and hidden states from 2048 tokens of text. Tokens are sampled
from the model's fp64 distribution, like the generator samples them.
Logprob error is the mean |error| of the sampled token's logprob vs
fp64.
Inference, LM head alone, per call
```
1 seq (us) 16 seq (us) logprob |err|
upcast + IEEE GEMM (generator before) 1850 2720 8.9e-06
upcast + BF16x9 GEMM 1850 2720 2.2e-06
upcast + TF32 GEMM 1868 1815 1.9e-05
bf16 GEMM, fp32 out (this PR) 362 368 1.0e-05
bf16 GEMM, bf16 out (bf16 head) 360 364 1.7e-02
```
Training, one 2048-token chunk of `ChunkedLossWrapper` (forward + CE +
backward). Gradient errors are vs exact fp64 gradients; rounding those
to bf16 alone gives 1.66e-03 (`dh`) and 1.65e-03 (`dW`).
```
ms logprob |err| dh err dW err
upcast + IEEE GEMM 229.5 8.9e-06 1.66e-03 1.65e-03
upcast + BF16x9 GEMM (trainer before) 77.5 2.2e-06 1.66e-03 1.65e-03
upcast + TF32 GEMM 20.3 1.9e-05 1.71e-03 1.66e-03
bf16 GEMM, fp32 out, BF16x9 bwd (router) 55.7 1.0e-05 1.66e-03 1.65e-03
bf16 GEMM, fp32 out, bf16 bwd (megatron) 12.0 1.0e-05 2.23e-03 2.13e-03
bf16 GEMM, fp32 out, hi+mid bwd (this PR) 18.9 1.0e-05 1.69e-03 1.65e-03
bf16 GEMM, fp32 out, hi+mid bwd, fp32 .grad 18.5 1.0e-05 1.69e-03 2.78e-05
bf16 GEMM, bf16 out (bf16 head) 12.3 1.7e-02 1.14e-02 1.24e-02
(compile) bf16 GEMM, fp32 out, BF16x9 bwd (router) 53.4 1.0e-05 1.66e-03 1.65e-03
(compile) bf16 GEMM, fp32 out, bf16 bwd (megatron) 10.0 1.0e-05 2.23e-03 2.13e-03
(compile) bf16 GEMM, fp32 out, hi+mid bwd (this PR) 18.0 1.0e-05 1.69e-03 1.65e-03
```
### Validation
Qwen3-30B-A3B, 2 nodes x 4 GB300 (PP2 x DP4, EP4, HybridEP + CUDA
graphs, no AC), random init, c4, 1M tokens/step, 100 and 300 steps,
seeds 42 / 777 (each cell is `seed 42 / seed 777`). tps is the median
over steps 21-300.
**fp32 lm_head, old vs new**
| run | lm_head | gate bwd | MFU | tps/GPU | vs old | lm_head-stage mem
| loss@300 |
|---|---|---|---:|---:|---:|---:|---:|
| `main_head-fp32cast_gate-old` | fp32 (`CastLinear`) | old (BF16x9) |
15.3 / 15.2% | 13,686 / 13,606 | | 149.4 GiB | 6.145 / 6.228 |
| `pr_head-fp32_gate-new` | fp32 (`HiMidLoLinear`) | new (hi+mid) | 18.8
/ 18.6% | 16,822 / 16,684 | +22.9 / +22.6% | 148.7 GiB | 6.164 / 5.997 |
Seed 777
<img width="1413" height="306" alt="image"
src="https://github.com/user-attachments/assets/17f39a77-8e97-4d5e-8d17-e46c4112e5b4"
/>
Seed 42
<img width="1178" height="305" alt="image"
src="https://github.com/user-attachments/assets/d7890cba-d6ed-465d-9048-b9534d700d25"
/>
**Router gate backward, old vs new (bf16 lm_head)**
| run | lm_head | gate bwd | MFU | tps/GPU | vs old | lm_head-stage mem
| loss@300 |
|---|---|---|---:|---:|---:|---:|---:|
| `main_head-bf16_gate-old` | bf16 | old (BF16x9) | 19.4 / 19.4% |
17,410 / 17,409 | | 148.0 GiB | 6.128 / 6.119 |
| `pr_head-bf16_gate-new` | bf16 | new (hi+mid) | 19.6 / 19.5% | 17,516
/ 17,492 | +0.6 / +0.5% | 148.0 GiB | 6.180 / 6.019 |
Seed 777
<img width="1421" height="312" alt="image"
src="https://github.com/user-attachments/assets/4fe1e18d-8444-4d1a-b3af-f0d72107c516"
/>
Seed 42
<img width="1179" height="310" alt="image"
src="https://github.com/user-attachments/assets/f77a3b94-6fa6-4595-bce5-7d4b4f96674b"
/>
- tps moves at most 0.8% between seeds for the same run.
- Loss is worse on the 100 step run, maybe due to an unlucky peak? 300
step looks fine and better.
## How the backward trick works
More details in the docstring
### 2 vs 3 pieces of grad_output
`backward_mode` ("hi_mid_lo" for routers, "hi_mid" for the LM head)
splits the fp32 grad_output into 3 bf16 pieces (exact) instead of 2 (~16
bits):
- **Router** (grad_input sums over its experts): the split sets the
error, so a 3rd piece cuts it ~7x for a small op.
- **LM head** (sums over the vocab): tensor-core accumulation sets the
error, so a 3rd piece doesn't help and costs ~1.5x backward.
`LMHeadFP32OutputConverter` defaults it to "hi_mid" (configurable).
Relative error vs fp64, and backward time as a multiple of a bf16
Linear's (GB300; Qwen3-8B LM head on 2048 tokens; a 2048 -> 128 router,
errors on 16k tokens, times on 64k). Same table as the docstring:
```
relative error backward time
grad_input grad_weight eager compiled
LM head (bf16 backward: 2.8 ms)
bf16 grad_output 1.5e-3 1.3e-3 1.0x 1.0x
2 pieces (default) 2.1e-4 8.4e-6 2.4x 2.5x
3 pieces 2.1e-4 8.6e-6 3.6x 3.8x
fp32 matmul (IEEE) 7.9e-5 2.3e-6 26.2x 27.4x
router (bf16 backward: 0.24 ms)
bf16 grad_output 1.7e-3 1.2e-3 1.0x 1.0x
2 pieces 2.4e-6 2.9e-6 2.2x 1.6x
3 pieces (routers) 3.5e-7 2.1e-6 2.8x 1.7x
fp32 matmul (IEEE) 5.1e-8 2.9e-7 5.1x 4.5x
```
NOTE: the validation runs above predate review 3: 2 truncated pieces for
the head and the router, an eager split, and a bf16 `grad_weight`. In
the Controlled results, grad_weight is bf16 except in the fp32 `.grad`
row; the table above keeps it in fp32.
## Q&A
- **Why not keep the router's BF16x9 backward?** Same gradients (`dh`
1.66e-03 vs 1.69e-03, `dW` equal), but 2.9x slower eager (55.7 vs 18.9
ms per chunk) and 3.0x compiled (53.4 vs 18.0 ms).
- **Does the router get the same gradient error with this?** Yes.
Qwen3.5-35B-A3B router shape (2048 -> 256 experts, 40 layers, 64k
tokens, GB300), with 3 pieces: grad_input error 1.66e-03 for both,
100.0% of grad_input elements bitwise equal, GPU time 44.6 -> 15.8 ms.
grad_weight now stays fp32: 1.66e-03 -> 8.1e-06. So `RouterGateLinear`
is replaced, not just the LM head.
## Code changes
- `HiMidLoLinear(Linear)`, in `hi_mid_lo_linear.py`, replaces
`CastLinear` and `RouterGateLinear`. bf16 operands on CUDA take the
bf16-GEMM path (see the docstring). CPU and fp32 or mixed dtypes upcast
to fp32, as `RouterGateLinear` did; batch-invariant mode also upcasts
(see the last bullet).
- The backward has one function per layout (wide, e.g. an LM head;
narrow, e.g. a router). The grad_output split is the
`fp32_to_bf16_split` local_compile region; it upcasts its pieces with an
integer shift, so no compiler can drop its `.to(bf16).float()` round
trip. The router gates set `backward_mode="hi_mid_lo"` explicitly.
- `LMHeadFP32OutputConverter` (replacing `LMHeadCastConverter`) swaps
the `lm_head` config to `HiMidLoLinear.Config`. Quantization rejects the
class through its allowlist, as it did `CastLinear` and
`RouterGateLinear`.
- Every RL config with a plain `Linear` head now uses
`LMHeadFP32OutputConverter`; the GPT-OSS, Qwen3 MoE, Qwen3-30B-A3B and
search_r1 configs didn't before. Muse Glimmer's head is a
`SoftCappedLinear` and is unchanged.
- Removed `enable_fp32_matmul_emulation_with_bf16x9` (the global
`fp32_precision = "bfx9"`, added for `RouterGateLinear`). After this PR
it only affected fp32-weight training and DeepSeek V4's mHC fp32
`F.linear`, on Blackwell.
- `grad_weight` now comes back in fp32; `grad_input` is still rounded
once to bf16. FSDP2 keeps it in torch nightlies since 2026-10-02, so the
LM head (eager in `ChunkedLossWrapper`) gets an fp32 `dW`: 2.5e-06 error
vs fp64, against the 1.66e-03 bf16 floor (H100, 2 GPUs, toy shape).
Compiled code still rounds it to bf16 (an open PyTorch fix). On older
torch, autograd casts it back to bf16: same bits as before, +0.6 ms per
Qwen3-8B head chunk on GB300.
- Behavior changes for MoE: router gradients change slightly (3 bf16
pieces instead of BF16x9: closer to fp32, not bitwise), and in
batch-invariant mode the router now computes with fp32 inputs through
`batch_invariant_ops` (Triton runs them in TF32) instead of cuBLAS's
`out_dtype` GEMM, which is not batch-invariant.
---------
Co-authored-by: Felipe Mello <[email protected]>
* [RL] Run the vLLM engine on its own thread, fed by a thread-safe inbox (#5029)
**For reviewers**: *I carefully made the change incrementally through
the list of commits. So if you find the whole PR is too confusing to
review, I strongly suggest to go through the changes commit by commit.*
Right now everything in VLLMGenerator runs on one event loop, including
`_engine_loop()`, which does most of the work. We notice
`LLMEngine.step()` used in the loop could be a long blocking call (e.g.
~30ms). As a result, the Monarch actor can't take in requests while the
engine steps.
This PR moves the engine loop to its dedicate thread. The endpoints stay
on the actor's event loop, and reach the engine loop only through a
thread-safe inbox and the `concurrent.futures.Future` replies it
resolves. After the move, the actor can keeps taking calls while the
engine loop executes long blocking calls such as `LLMEngine.step()`.
The data flow looks the the following. For states crossing the thread
boundaries, it uses 2 mechanisms:
* endpoint -> engine loop: `EngineLoopInbox`
* engine loop -> endpoint: `concurrent.futures.Future`
```
actor thread (actor's event loop) | vllm-engine thread (its own event
loop)
|
generate / pull_model_state_dict |
reply = concurrent.futures.Future() |
inbox.put(message) ----------------------> asyncio.Queue (owned by this
loop)
with lock: raise if closed | |
call_soon_threadsafe(put_nowait) | v
returns at once, even mid-step | _decide_next_action
await wrap_future(reply) | idle: await get(); then drain
^ | CloseRequest -> CLOSE
| | reply.set_running_or_notify_cancel()
| | False (cancelled on inbox): skip
| | True: register reply with dispatcher
| | |
| | v
| | LoopDecision ---- gloo ----> other ranks
| | |
| | v
| | engine.step() burst (blocks only this thread)
| | |
+------ call_soon_threadsafe ------------ reply.set_result(completion)
|
close |
inbox.close(CloseRequest()) -------------> queued behind earlier puts;
later puts raise
await wrap_future(engine_loop_future) <--- _engine_loop exits; its
finally releases
| the dispatcher, renderer and engine
```
## Performance
Stress test of the final commit on Monarch 0.6.0 and 8x H100: 2
generators x TP4, 512 requests per wave (256 per generator), one cold
wave then 5 warm waves per `max_tokens`, 2 runs per arm interleaved with
control. Mean time for a warm wave to finish:
| max_tokens | control | this PR |
| ---: | ---: | ---: |
| 48 | 2.76 s | 1.46 s (-47%) |
| 256 | 6.04 s | 5.27 s (-13%) |
| 1024 | 21.98 s | 21.15 s (-4%) |
In a warm wave, each generator's rank 0 now starts all 256 of its
`generate` calls within 83-117 ms, against 2.26-2.55 s on control. That
saves 0.8-1.3 s per wave, so the gain is largest for short generations.
* [checkpoint] Parallelize Hugging Face checkpoint loading (#5087)
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ #5087
The reader otherwise loads each shard serially. Two workers overlap
reads while limiting storage and CPU pressure.
- Use two workers for unquantized readers by default.
- Allow callers to override the thread count.
- Preserve existing quantized reader defaults.
- Reuse the shared reader in model adapters and conversion tooling.
- Cover default and overridden thread counts.
Test Plan:
- pytest -q tests/unit_tests/cpu/test_state_dict_adapter.py -x
- pytest -q
test/distributed/checkpoint/test_hf_safetensor_e2e.py::TestSingleRankSaveLoad::test_load_with_multiple_threads
- Full formatting, lint, spelling, link, and Pyrefly checks pass.
* [LoRA] Target modules by FQN (#5095)
Addresses
https://github.com/pytorch/torchtitan/pull/4995#discussion_r4175611437
Also addresses
https://github.com/pytorch/torchtitan/pull/4995#discussion_r4181602839
since `handler` interface is gone.
## Summary
HuggingFace
[link](https://huggingface.co/docs/diffusers/en/training/lora) and
Megatron
[link](https://docs.nvidia.com/nemo/automodel/latest/recipes-e2e-examples/sft-peft)
target LoRA modules by FQN.
This PR lets the user only specify the FQN, and the transform handles
applying the correct LoRA for different kinds of modules, including
`Linear`, `GroupedLinear`, `DistMoeRoutedExperts`.
Only complication is the `DistMoeRoutedExperts` because the previous
implementation assumed both `w13` and `w2` are targeted, but this one
allows one to target only one of them.
- traverse the modules from bottom up (child -> parent)
- apply `GroupedLinear` or `Linear` LoRA for targeted modules
- when we reach `DistMoeRoutedExperts` and it has child `w13` or `w2`
that is already LoRA transformed, edit `_weight_operands` to return the
LoRA weight summed matrix.
* Add TITAN_LOG_LEVEL var for the logger. (#5089)
Currently, all logs at the `DEBUG` level are silently dropped, with no
way to access them.
This PR introduces the `TITAN_LOG_LEVEL` environment variable to control
the logging level. It defaults to `INFO`; setting it to `DEBUG` enables
access to debug logs.
* [compile] Gated activations: unbind gate/up inside the compiled region (#5086)
**TLDR:** SwiGLU, SiTUGLU and GPT-OSS SwiGLU now take `w13`'s fused
`gate_up` tensor and unbind it inside their compiled region, and the
`FusedSwiGLU` kernel takes it too. This removes an eager copy from their
backward: Qwen3.5-4B FFN fwd+bwd 10.99 -> 10…
add EMA implement for #3982
What it is
EMAsubclassesOptimizersContainerand behaves like a gradient-free pseudo-optimizer:it holds one
ema_paramstensor per tracked tensor and updates them in place after eachreal optimizer step.
Two decay formulas:
ema = decay * ema + (1 - decay) * paramdecay = 2 ** (-1 / (half_life_fraction * num_updates)), i.e.roughly 5% tail averaging (reference)
How to use
in Config
or from CLI
convert EMA weights to HF checkpoint
which takes the same arguments as
convert_to_hf.py.Buffers. MoE's
expert_bias_Eis aregister_bufferupdated by a non-gradientload-balancing heuristic, so it is not a parameter and would not be tracked by EMA. To expliclty include them, we could set
buffer_patterns=["expert_bias_E$"]folds it into the same"ema"key.
CPU offload.
offload_to_cpuruns the update on a side stream with an H2D/D2Hpipeline. Scratch is carved from a single flat buffer and reused chunk by chunk, so GPU
scratch stays bounded instead of growing to 1x parameter memory.
Edge cases and semantics (some edge cases from claude, summarized by claude)
These are the cases worth reviewing; most of the non-obvious code is here.
The decay schedule has to survive a resume.
num_updatesis stateless, so derived from the trainerstep, not kept as a counter. Only
ema_paramsare checkpointed, so a stored counter wouldrestart at 0 after a resume, making
decay ~ 2**-20and overwriting the restored averagewith the current weights on the very first firing.
Turning EMA on mid-run. An existing checkpoint has no
"ema"key, so the load failsuntil you exclude it once:
The EMA then cold-starts from the just-loaded weights.
Model-only loads. An HF safetensors load or an
initial_load_pathwarm start neverrestores EMA state, so it reseeds from the loaded weights the same way. Conversely,
resuming with EMA disabled against a checkpoint that has EMA data is fine: the key is
simply never requested.
The final checkpoint has no EMA state.
last_save_model_onlydefaults toTrue, sothe last-step checkpoint is model weights only. Export the EMA from an interval
checkpoint, or set
last_save_model_only=False. -> maybe we should fix this?Fused parameters. EMA state is keyed by
named_parameters()FQNs, which for fusedmodules differ from the model state-dict keys the save hooks split them into
(
qkv_linear.wqkv->wq/wk/wv,feed_forward.w13->w1/w3). One checkpointtherefore holds
ema.state.<fused fqn>.ema_paramsnext to model keys...wq.weight. Thatis the same contract optimizer state already follows. The conversion script overlays
through the module rather than the dict for this reason — writing EMA values into a
state-dict-keyed dict would add unmatched keys that
to_hfsilently drops, exporting thetrained weights instead.
Tensors EMA does not track. Only parameters with
requires_gradare tracked, plus thebuffers matched by
buffer_patterns. Everything else — frozen parameters, unmatchedbuffers — is exported from the trained weights, so the HF result is a complete, loadable
checkpoint rather than one with missing keys. The conversion script tracks exactly the
FQNs the checkpoint holds, so a run that froze some parameters converts correctly.
The tracked set is fixed at construction. State is keyed by tensor identity, so
unfreezing a parameter, or replacing a parameter or buffer, after the EMA is built raises a
clear error instead of a bare
KeyError. Freezing a parameter afterwards is fine; it juststops being averaged.
DTensor and pinned memory. DTensor has no
pin_memory()(NYI:aten._pin_memory.default), so the offload path pins the local shard and rewraps it aroundthe parameter's live sharding at save/load time. There is a TODO for this, including the
process-group-restore concern.