ColossalAI icon indicating copy to clipboard operation
ColossalAI copied to clipboard

[BUG]: bf16 training does not resume exactly: fp32 master weights are rebuilt from bf16 weights on load

Open JazyJiang opened this issue 1 month ago • 0 comments

Is there an existing issue for this bug?

  • [x] I have searched the existing issues

The bug has not been fixed in the latest main branch

  • [x] I have checked the latest main branch

Do you feel comfortable sharing a concise (minimal) script that reproduces the error? :)

Yes, I will share a minimal reproducible script.

🐛 Describe the bug

With precision="bf16", a run resumed from a checkpoint does not continue the uninterrupted run. After one step past the checkpoint, every weight tensor differs, by up to the last bf16 bit (3.9e-3). With fp32 the same script gives identical weights. This affects LowLevelZeroPlugin (stage 1 and 2, 1 and 2 GPUs) and HybridParallelPlugin(tp_size=1, pp_size=1).

Cause. The fp32 master weights are not saved. On load, they are rebuilt from the bf16 working weights, so their low bits are lost and later updates round differently:

Megatron-LM, for comparison, saves the fp32 parameters along with the optimizer state and restores them when it loads the optimizer. A possible fix is to do the same: save the master weights in save_optimizer, and in load_optimizer overwrite the master weights that load_model rebuilt. A checkpoint without them would keep today's behaviour.

Reproduction (1 GPU):

# torchrun --nproc_per_node=1 bf16_resume.py {low_level_zero,hybrid_parallel} {bf16,fp32}
import sys
import tempfile

import torch
from transformers import LlamaConfig, LlamaForCausalLM

import colossalai
from colossalai.booster import Booster
from colossalai.booster.plugin import HybridParallelPlugin, LowLevelZeroPlugin

colossalai.launch_from_torch()
PLUGINS = {
    "low_level_zero": lambda precision: LowLevelZeroPlugin(stage=2, precision=precision),
    "hybrid_parallel": lambda precision: HybridParallelPlugin(tp_size=1, pp_size=1, precision=precision),
}
config = LlamaConfig(hidden_size=64, intermediate_size=128, num_hidden_layers=2, num_attention_heads=4, vocab_size=128)


def build():
    torch.manual_seed(0)
    model = LlamaForCausalLM(config)
    booster = Booster(plugin=PLUGINS[sys.argv[1]](sys.argv[2]))
    model, optimizer, *_ = booster.boost(model, torch.optim.AdamW(model.parameters(), lr=1e-3))
    return booster, model, optimizer


def train_step(booster, model, optimizer, step):
    torch.manual_seed(100 + step)
    ids = torch.randint(0, 128, (2, 16), device="cuda")
    loss = model(input_ids=ids, labels=ids).loss
    booster.backward(loss, optimizer)
    optimizer.step()
    optimizer.zero_grad()


def weights(model):
    return {k: v.detach().float().clone() for k, v in model.unwrap().state_dict().items()}


with tempfile.TemporaryDirectory() as ckpt:
    booster, model, optimizer = build()
    for step in range(2):
        train_step(booster, model, optimizer, step)
    booster.save_model(model, f"{ckpt}/model")
    booster.save_optimizer(optimizer, f"{ckpt}/optimizer")
    train_step(booster, model, optimizer, 2)
    uninterrupted = weights(model)

    booster, model, optimizer = build()
    booster.load_model(model, f"{ckpt}/model")
    booster.load_optimizer(optimizer, f"{ckpt}/optimizer")
    train_step(booster, model, optimizer, 2)
    resumed = weights(model)

diff = {k: (uninterrupted[k] - resumed[k]).abs().max().item() for k in uninterrupted}
print(f"{sys.argv[1]} {sys.argv[2]}: {sum(d > 0 for d in diff.values())}/{len(diff)} tensors differ, max abs diff {max(diff.values()):.3e}")

Output:

low_level_zero fp32: 0/21 tensors differ, max abs diff 0.000e+00
low_level_zero bf16: 21/21 tensors differ, max abs diff 3.906e-03
hybrid_parallel fp32: 0/21 tensors differ, max abs diff 0.000e+00
hybrid_parallel bf16: 21/21 tensors differ, max abs diff 3.906e-03

Environment

  • ColossalAI: main at d414d565
  • PyTorch 2.13.0+cu130, CUDA 13.0, transformers 5.17.0, Python 3.10.12
  • 1× NVIDIA H20, driver 595.71.05

JazyJiang avatar Nov 03 '26 06:11 JazyJiang