Debian Codegraph @

examples/torch_native_parallelism/nd_parallel_trainer.py

raw
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 import argparse
15
16 import torch
17 from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
18
19 from accelerate.utils import ParallelismConfig
20 from utils import get_dataset
21
22
23 MODEL_ID = "NousResearch/Hermes-3-Llama-3.1-8B"
24
25
26 def parse_args():
27 parser = argparse.ArgumentParser()
28 parser.add_argument("--sequence-length", type=int, default=4096)
29 parser.add_argument("--checkpoint-frequency", type=int, default=100)
30 parser.add_argument("--model-name", type=str, default=MODEL_ID)
31 parser.add_argument("--save-dir", type=str, default=f"./accelerate-nd-parallel-{MODEL_ID.split('/')[-1]}")
32 parser.add_argument("--device-type", type=str, default="auto")
33 return parser.parse_args()
34
35
36 def main():
37 # If ParallelismConfig is not initialized with __init__, it reads from env vars
38 # which were set by using config
39 pc = ParallelismConfig()
40 args = parse_args()
41
42 if args.device_type == "auto":
43 args.device_type = torch.accelerator.current_accelerator().type
44
45 model_kwargs = {}
46 if pc.tp_enabled:
47 model_kwargs["tp_plan"] = "auto"
48 model_kwargs["device_mesh"] = pc.build_device_mesh(args.device_type)
49
50 tokenizer = AutoTokenizer.from_pretrained(args.model_name)
51 model = AutoModelForCausalLM.from_pretrained(args.model_name, use_cache=False, **model_kwargs)
52
53 if tokenizer.pad_token is None:
54 tokenizer.pad_token = tokenizer.eos_token
55
56 packed_dataset = get_dataset(tokenizer, args.sequence_length)
57
58 training_args = TrainingArguments(
59 output_dir=args.save_dir,
60 parallelism_config=pc,
61 num_train_epochs=1,
62 per_device_train_batch_size=1,
63 logging_steps=5,
64 save_steps=args.checkpoint_frequency,
65 learning_rate=5e-5,
66 remove_unused_columns=False,
67 bf16=True,
68 )
69
70 trainer = Trainer(
71 model=model,
72 args=training_args,
73 processing_class=tokenizer,
74 train_dataset=packed_dataset,
75 )
76
77 trainer.train()
78 trainer.save_model()
79
80
81 if __name__ == "__main__":
82 main()