| 1 |
# Copyright 2025 The HuggingFace Inc. team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
""" |
| 16 |
Minimal example of training with FP8 precision using FSDP2 via Accelerate. |
| 17 |
This example demonstrates how to use torchao's Float8LinearConfig with Accelerate's AORecipeKwargs. |
| 18 |
""" |
| 19 |
|
| 20 |
import argparse |
| 21 |
|
| 22 |
import torch |
| 23 |
from torch.utils.data import DataLoader |
| 24 |
from torchao.float8 import Float8LinearConfig |
| 25 |
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer |
| 26 |
|
| 27 |
from accelerate import Accelerator |
| 28 |
from accelerate.utils import AORecipeKwargs, FullyShardedDataParallelPlugin, TorchDynamoPlugin, set_seed |
| 29 |
from utils import PerformanceTracker, create_collate_fn, get_dataset, get_model_flops_per_token |
| 30 |
|
| 31 |
|
| 32 |
WARMUP_STEPS = 10 |
| 33 |
|
| 34 |
MODEL_ID = "NousResearch/Hermes-3-Llama-3.1-8B" |
| 35 |
|
| 36 |
|
| 37 |
def parse_args(): |
| 38 |
parser = argparse.ArgumentParser() |
| 39 |
|
| 40 |
parser.add_argument("--sequence-length", type=int, default=8192, help="Sequence length for the dataset") |
| 41 |
parser.add_argument("--num-steps", type=int, default=1000, help="Number of steps to train for") |
| 42 |
parser.add_argument("--precision", type=str, default="fp8", choices=["fp8", "bf16"], help="Precision to train in") |
| 43 |
parser.add_argument("--log-with", type=str, default="wandb", help="Log with wandb or tensorboard") |
| 44 |
|
| 45 |
return parser.parse_args() |
| 46 |
|
| 47 |
|
| 48 |
def main(): |
| 49 |
""" |
| 50 |
Main function to train the model. |
| 51 |
""" |
| 52 |
set_seed(42) |
| 53 |
|
| 54 |
args = parse_args() |
| 55 |
|
| 56 |
fsdp2_plugin = FullyShardedDataParallelPlugin( |
| 57 |
fsdp_version=2, |
| 58 |
cpu_ram_efficient_loading=False, # CPU RAM efficient loading CANNOT work with fp8 torchao |
| 59 |
auto_wrap_policy="transformer_based_wrap", |
| 60 |
transformer_cls_names_to_wrap=["LlamaDecoderLayer"], |
| 61 |
) |
| 62 |
fsdp2_plugin.set_mixed_precision(args.precision) |
| 63 |
|
| 64 |
dynamo_plugin = TorchDynamoPlugin( |
| 65 |
backend="inductor", |
| 66 |
use_regional_compilation=True, # We use regional compilation to compile the model way faster |
| 67 |
) |
| 68 |
|
| 69 |
fp8_config = Float8LinearConfig( |
| 70 |
enable_fsdp_float8_all_gather=True, # extra saving by gathering parameters in fp8 and upcasting after |
| 71 |
) |
| 72 |
|
| 73 |
kwargs = [] |
| 74 |
if args.precision == "fp8": |
| 75 |
kwargs = [AORecipeKwargs(config=fp8_config)] |
| 76 |
|
| 77 |
accelerator = Accelerator( |
| 78 |
fsdp_plugin=fsdp2_plugin, |
| 79 |
dynamo_plugin=dynamo_plugin, |
| 80 |
kwargs_handlers=kwargs, |
| 81 |
log_with=args.log_with, |
| 82 |
) |
| 83 |
accelerator.init_trackers( |
| 84 |
project_name="FSDP2_torchao_fp8", |
| 85 |
config={"sequence_length": args.sequence_length, "num_steps": args.num_steps}, |
| 86 |
) |
| 87 |
|
| 88 |
model = AutoModelForCausalLM.from_config( |
| 89 |
AutoConfig.from_pretrained(MODEL_ID, use_cache=False), |
| 90 |
torch_dtype=torch.bfloat16, |
| 91 |
) |
| 92 |
|
| 93 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) |
| 94 |
if tokenizer.pad_token is None: |
| 95 |
tokenizer.pad_token = tokenizer.eos_token |
| 96 |
|
| 97 |
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5) |
| 98 |
dataset = get_dataset(tokenizer, args.sequence_length, accelerator) |
| 99 |
dataloader = DataLoader(dataset, batch_size=1, collate_fn=create_collate_fn()) |
| 100 |
|
| 101 |
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) |
| 102 |
accelerator.wait_for_everyone() |
| 103 |
|
| 104 |
model.train() |
| 105 |
|
| 106 |
total_num_steps = min(args.num_steps, len(dataloader)) |
| 107 |
model_flops_per_token = get_model_flops_per_token(model, args.sequence_length) |
| 108 |
performance_tracker = PerformanceTracker(warmup_steps=5) |
| 109 |
|
| 110 |
for step, batch in enumerate(dataloader): |
| 111 |
if step >= total_num_steps: |
| 112 |
break |
| 113 |
|
| 114 |
outputs = model(**batch) |
| 115 |
loss = outputs.loss |
| 116 |
|
| 117 |
accelerator.backward(loss) |
| 118 |
optimizer.step() |
| 119 |
optimizer.zero_grad() |
| 120 |
metrics = performance_tracker.step(batch["input_ids"].shape[1], model_flops_per_token) |
| 121 |
|
| 122 |
print_msg = f"Step {step}/{total_num_steps}, Loss: {loss.item():.4f}" |
| 123 |
if "warmup_completed" in metrics: |
| 124 |
accelerator.print("Warm up completed! Starting training") |
| 125 |
elif metrics: |
| 126 |
print_msg += performance_tracker.get_print_message(metrics) |
| 127 |
|
| 128 |
if step % 10 == 0 or step == total_num_steps - 1: |
| 129 |
accelerator.print(print_msg) |
| 130 |
|
| 131 |
accelerator.log(metrics) |
| 132 |
|
| 133 |
accelerator.wait_for_everyone() |
| 134 |
accelerator.end_training() |
| 135 |
accelerator.print("Training completed!") |
| 136 |
|
| 137 |
|
| 138 |
if __name__ == "__main__": |
| 139 |
main() |