| 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 |
Example of training with ND parallel using accelerate's ParallelismConfig |
| 17 |
""" |
| 18 |
|
| 19 |
import argparse |
| 20 |
import warnings |
| 21 |
|
| 22 |
import torch |
| 23 |
import torch.distributed as dist |
| 24 |
from torch.utils.data import DataLoader |
| 25 |
from transformers import AutoModelForCausalLM |
| 26 |
|
| 27 |
from accelerate import Accelerator |
| 28 |
from accelerate.parallelism_config import ParallelismConfig |
| 29 |
from accelerate.utils import FullyShardedDataParallelPlugin, set_seed |
| 30 |
from utils import ( |
| 31 |
PerformanceTracker, |
| 32 |
create_collate_fn, |
| 33 |
get_dataset, |
| 34 |
get_model_flops_per_token, |
| 35 |
setup_tokenizer, |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
MODEL_ID = "NousResearch/Hermes-3-Llama-3.1-8B" |
| 40 |
|
| 41 |
|
| 42 |
def parse_args(): |
| 43 |
parser = argparse.ArgumentParser() |
| 44 |
parser.add_argument("--dp-replicate-size", type=int, default=1) |
| 45 |
parser.add_argument("--dp-shard-size", type=int, default=1) |
| 46 |
parser.add_argument("--tp-size", type=int, default=1) |
| 47 |
parser.add_argument("--cp-size", type=int, default=1) |
| 48 |
parser.add_argument("--sequence-length", type=int, default=1024) |
| 49 |
parser.add_argument("--num-steps", type=int, default=1000) |
| 50 |
parser.add_argument("--save-dir", type=str, default="./outputs") |
| 51 |
parser.add_argument("--checkpoint-frequency", type=int, default=100) |
| 52 |
parser.add_argument("--model-name", type=str, default=MODEL_ID) |
| 53 |
|
| 54 |
return parser.parse_args() |
| 55 |
|
| 56 |
|
| 57 |
def forward(model, batch, optimizer, accelerator: Accelerator): |
| 58 |
batch["position_ids"] = torch.arange(0, batch["input_ids"].size(1), device=batch["input_ids"].device).unsqueeze(0) |
| 59 |
# We need both labels and shift_labels, as the loss computation in the model is hidden behind `if labels is not None`, but the loss computation |
| 60 |
# itself prioritzes shift_labels (if provided) which are the correct ones (due to labels being wrong if cp enabled) |
| 61 |
buffers = [batch["input_ids"], batch["shift_labels"], batch["labels"], batch["position_ids"]] |
| 62 |
with accelerator.maybe_context_parallel( |
| 63 |
buffers=buffers, buffer_seq_dims=[1, 1, 1, 1], no_restore_buffers=set(buffers) |
| 64 |
): |
| 65 |
# To get the proper loss value, we need to average across devices that are participating in data parallel/context parallel training |
| 66 |
# As for DP we have a different batch on each device and for CP we essentially have a different part of sequences on each device |
| 67 |
# I.e. with causal modelling and seq_len 1024, this dimension becomes another batch dimension of sorts |
| 68 |
loss_reduce_grp = ( |
| 69 |
accelerator.torch_device_mesh["dp_cp"].get_group() |
| 70 |
if accelerator.parallelism_config.dp_cp_dim_names |
| 71 |
else None |
| 72 |
) |
| 73 |
outputs = model(**batch) |
| 74 |
loss = outputs.loss |
| 75 |
accelerator.backward(loss) |
| 76 |
optimizer.step() |
| 77 |
optimizer.zero_grad(set_to_none=False) |
| 78 |
dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=loss_reduce_grp) |
| 79 |
|
| 80 |
return loss |
| 81 |
|
| 82 |
|
| 83 |
def train(args): |
| 84 |
parallelism_config = ParallelismConfig( |
| 85 |
dp_replicate_size=args.dp_replicate_size, |
| 86 |
dp_shard_size=args.dp_shard_size, |
| 87 |
tp_size=args.tp_size, |
| 88 |
cp_size=args.cp_size, |
| 89 |
) |
| 90 |
|
| 91 |
# FSDP needs extra configuration, so we properly shard the model |
| 92 |
fsdp2_plugin = None |
| 93 |
if parallelism_config.dp_shard_enabled or parallelism_config.cp_enabled: |
| 94 |
fsdp2_plugin = FullyShardedDataParallelPlugin( |
| 95 |
fsdp_version=2, |
| 96 |
auto_wrap_policy="transformer_based_wrap", |
| 97 |
transformer_cls_names_to_wrap=["LlamaDecoderLayer"], |
| 98 |
state_dict_type="SHARDED_STATE_DICT", |
| 99 |
) |
| 100 |
|
| 101 |
accelerator = Accelerator( |
| 102 |
log_with=["wandb"], mixed_precision="bf16", parallelism_config=parallelism_config, fsdp_plugin=fsdp2_plugin |
| 103 |
) |
| 104 |
accelerator.init_trackers("nd_parallel_training") |
| 105 |
|
| 106 |
# If TP was enabled, we need to tell transformers to prepare the model for us |
| 107 |
model_kwargs = ( |
| 108 |
{"tp_size": args.tp_size, "tp_plan": "auto", "device_mesh": accelerator.torch_device_mesh} |
| 109 |
if args.tp_size > 1 |
| 110 |
else {} |
| 111 |
) |
| 112 |
model = AutoModelForCausalLM.from_pretrained( |
| 113 |
args.model_name, |
| 114 |
torch_dtype=torch.bfloat16, |
| 115 |
use_cache=False, |
| 116 |
**model_kwargs, |
| 117 |
) |
| 118 |
tokenizer = setup_tokenizer(args.model_name) |
| 119 |
optimizer = torch.optim.SGD(model.parameters(), lr=1e-5) |
| 120 |
dataset = get_dataset(tokenizer, args.sequence_length, accelerator) |
| 121 |
dataloader = DataLoader(dataset, batch_size=1, collate_fn=create_collate_fn()) |
| 122 |
|
| 123 |
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) |
| 124 |
|
| 125 |
total_num_steps = min(args.num_steps, len(dataloader)) |
| 126 |
performance_tracker = PerformanceTracker(warmup_steps=5) |
| 127 |
model_flops_per_token = get_model_flops_per_token(model, args.sequence_length) |
| 128 |
|
| 129 |
accelerator.print("Starting training...") |
| 130 |
for step, batch in enumerate(dataloader): |
| 131 |
if step >= total_num_steps: |
| 132 |
break |
| 133 |
|
| 134 |
loss = forward(model, batch, optimizer, accelerator) |
| 135 |
|
| 136 |
# We report TPS per device, so we divide by the number of devices in the non-data parallel dimension |
| 137 |
metrics = performance_tracker.step( |
| 138 |
batch["input_ids"].shape[1] / parallelism_config.non_data_parallel_size, model_flops_per_token |
| 139 |
) |
| 140 |
|
| 141 |
print_msg = f"Step {step}/{total_num_steps}, Loss: {loss.item():.4f}" |
| 142 |
if "warmup_completed" in metrics: |
| 143 |
accelerator.print("Warm up completed! Starting performance tracking...") |
| 144 |
elif metrics: |
| 145 |
print_msg += performance_tracker.get_print_message(metrics, with_memory=True) |
| 146 |
|
| 147 |
if step % 10 == 0 or step == total_num_steps - 1: |
| 148 |
accelerator.print(print_msg) |
| 149 |
|
| 150 |
if step % args.checkpoint_frequency == 0 and step > 0 and parallelism_config.dp_shard_enabled: |
| 151 |
accelerator.print(f"Saving checkpoint at step {step}...") |
| 152 |
accelerator.save_state(args.save_dir + f"/checkpoint-{step}") |
| 153 |
|
| 154 |
accelerator.log({"loss": loss.item()}) |
| 155 |
|
| 156 |
accelerator.print("Training completed!") |
| 157 |
|
| 158 |
model.save_pretrained(args.save_dir + f"/{args.model_name}") |
| 159 |
accelerator.print(f"Model saved to {args.save_dir}/{args.model_name}") |
| 160 |
accelerator.end_training() |
| 161 |
|
| 162 |
|
| 163 |
if __name__ == "__main__": |
| 164 |
set_seed(42) |
| 165 |
args = parse_args() |
| 166 |
if args.dp_shard_size == 1 and args.tp_size > 1: |
| 167 |
# We currently don't support saving with `save_state` when using only |
| 168 |
# tensor parallelism, fsdp must be enabled |
| 169 |
warnings.warn( |
| 170 |
"Accelerator.save_state() is not yet supported with pure tensor parallel training. Training will work, but intermediate checkpoints will not be saved." |
| 171 |
) |
| 172 |
train(args) |