Compare commits
10 Commits
439e23fdba
...
df3ae8a5f0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df3ae8a5f0 | ||
|
|
bf03420686 | ||
|
|
164ab81e27 | ||
|
|
78ba56ce80 | ||
|
|
009bb0b2a8 | ||
|
|
59b841e3cb | ||
|
|
7ef2344cd4 | ||
|
|
d855aead9e | ||
|
|
e82c719f31 | ||
|
|
a727b986cb |
203
LICENSE
Normal file
203
LICENSE
Normal file
@ -0,0 +1,203 @@
|
||||
Copyright 2024- The Hugging Face team. All rights reserved.
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
48
README.md
48
README.md
@ -1,10 +1,16 @@
|
||||
# picotron
|
||||
In the spirit of [NanoGPT](https://github.com/karpathy/nanoGPT), we created Picotron: The minimalist & most-hackable repository for pre-training Llama-like models with [4D Parallelism](https://arxiv.org/abs/2407.21783) (Data, Tensor, Pipeline, Context parallel). It is designed with simplicity and **educational** purposes in mind, making it an excellent tool for learning and experimentation.
|
||||
|
||||

|
||||
- The code itself is simple and readable: `train.py`, `model.py` and `[data|tensor|pipeline|context]_parallel.py` are all under **300** lines of code.
|
||||
|
||||
- The minimalist & most-hackable repository for pre-training Llama-like models with 4D Parallelism (Data, Tensor, Pipeline, Context parallel). It is a rewrite of [Megatron-LM](https://github.com/NVIDIA/Megatron-LM) for educational purpose. The code itself is plain and readable: **train.py, model.py and \[data|tensor|pipeline|context\]_parallel.py are all < 300 LOC**.
|
||||
- Performance is not the best but still under active development. We observed 38% MFU on a LLaMA-2-7B model using 64 H100 GPUs and nearly 50% MFU on the SmolLM-1.7B model with 8 H100 GPUs. Benchmarks will come soon
|
||||
|
||||
- Performance is not yet in okay-ish but this is under active development.
|
||||
# Tutorial videos
|
||||
|
||||
- A step by step tutorial on how to build Picotron distributed training framework form scratch:
|
||||
- [Picotron tutorial (playlist)](https://www.youtube.com/playlist?list=PL-_armZiJvAnhcRr6yTJ0__f3Oi-LLi9S) 🎬
|
||||
- [Picotron tutorial (codebase)](https://github.com/huggingface/picotron_tutorial) 👷🏻♂️
|
||||
|
||||
# Install
|
||||
|
||||
@ -13,32 +19,34 @@ pip install -e .
|
||||
```
|
||||
|
||||
# Quick start
|
||||
- Get a HF token [here](https://huggingface.co/settings/tokens) to download models from HuggingFace
|
||||
|
||||
- GPU
|
||||
```sh
|
||||
# DP=8
|
||||
python create_config.py --out_dir tmp --exp_name llama-1B --dp 8 --model_name HuggingFaceTB/SmolLM-1.7B --num_hidden_layers 15 --grad_acc_steps 32 --mbs 4 --seq_len 1024 --hf_token <HF_TOKEN>
|
||||
```sh
|
||||
# To create a config file in json format under tmp by default
|
||||
python create_config.py --out_dir tmp --exp_name llama-1B --dp 8 --model_name HuggingFaceTB/SmolLM-1.7B --num_hidden_layers 15 --grad_acc_steps 32 --mbs 4 --seq_len 1024 --hf_token <HF_TOKEN>
|
||||
|
||||
# Locally
|
||||
torchrun --nproc_per_node 8 train.py --config tmp/llama-1B/config.json
|
||||
# Locally
|
||||
torchrun --nproc_per_node 8 train.py --config tmp/llama-1B/config.json
|
||||
|
||||
# 3D Parallelism
|
||||
python create_config.py --out_dir tmp --dp 4 --tp 2 --pp 2 --pp_engine 1f1b --exp_name llama-7B --model_name meta-llama/Llama-2-7b-hf --grad_acc_steps 32 --mbs 4 --seq_len 1024 --hf_token <HF_TOKEN>
|
||||
# 3D Parallelism
|
||||
python create_config.py --out_dir tmp --dp 4 --tp 2 --pp 2 --pp_engine 1f1b --exp_name llama-7B --model_name meta-llama/Llama-2-7b-hf --grad_acc_steps 32 --mbs 4 --seq_len 1024 --hf_token <HF_TOKEN>
|
||||
|
||||
# Slurm
|
||||
python submit_slurm_jobs.py --inp_dir tmp/llama-7B --qos high --hf_token <HF_TOKEN>
|
||||
```
|
||||
# Slurm
|
||||
python submit_slurm_jobs.py --inp_dir tmp/llama-7B --qos high --hf_token <HF_TOKEN>
|
||||
```
|
||||
|
||||
- CPU (expect it to be slow)
|
||||
```sh
|
||||
# 3D Parallelism on CPU
|
||||
python create_config.py --out_dir tmp --exp_name llama-1B-cpu --dp 2 --tp 2 --pp 2 --pp_engine 1f1b --model_name HuggingFaceTB/SmolLM-1.7B --num_hidden_layers 5 --grad_acc_steps 2 --mbs 4 --seq_len 128 --hf_token <HF_TOKEN> --use_cpu
|
||||
|
||||
```sh
|
||||
# 3D Parallelism on CPU
|
||||
python create_config.py --out_dir tmp --exp_name llama-1B-cpu --dp 2 --tp 2 --pp 2 --pp_engine 1f1b --model_name HuggingFaceTB/SmolLM-1.7B --num_hidden_layers 5 --grad_acc_steps 2 --mbs 4 --seq_len 128 --hf_token <HF_TOKEN> --use_cpu
|
||||
|
||||
# Locally
|
||||
torchrun --nproc_per_node 8 train.py --config tmp/llama-1B-cpu/config.json
|
||||
```
|
||||
# Locally
|
||||
torchrun --nproc_per_node 8 train.py --config tmp/llama-1B-cpu/config.json
|
||||
```
|
||||
|
||||
# Acknowledgements
|
||||
|
||||
- [Megatron-LM](https://github.com/NVIDIA/Megatron-LM)
|
||||
- [Megatron-LM](https://github.com/NVIDIA/Megatron-LM)
|
||||
- [FairScale](https://github.com/facebookresearch/fairscale)
|
||||
- [LitGPT](https://github.com/Lightning-AI/lit-gpt)
|
||||
|
||||
@ -52,7 +52,7 @@ def init_model_with_materialized_weights(model, model_config, save_dir):
|
||||
initialization_manager = InitializationManager(model, model_config)
|
||||
layer_names = initialization_manager.get_layer_names_in_sft_format()
|
||||
|
||||
print(f"Rank {pgm.process_group_manager.global_rank} responsible for {len(layer_names)} layers")
|
||||
# print(f"Rank {pgm.process_group_manager.global_rank} responsible for {len(layer_names)} layers")
|
||||
|
||||
if len(layer_names) == 0:
|
||||
raise Exception("Some ranks has no layers. There are too many ranks and not enough layers to distribute.")
|
||||
|
||||
@ -18,7 +18,7 @@ class MicroBatchDataLoader(DataLoader):
|
||||
self.num_global_micro_batches = self.global_batch_size // self.micro_batch_size
|
||||
|
||||
self.seq_length_per_gpu = seq_length // pgm.process_group_manager.cp_world_size
|
||||
self.dataset = load_dataset(dataset_name, split=split)
|
||||
self.dataset = load_dataset(dataset_name, split=split, name=subset_name)
|
||||
|
||||
if pgm.process_group_manager.global_rank == 0:
|
||||
print(f"rank {pgm.process_group_manager.global_rank}: Creating tokenizer")
|
||||
|
||||
@ -8,6 +8,11 @@ from picotron.data_parallel.bucket import BucketManager
|
||||
import picotron.process_group_manager as pgm
|
||||
|
||||
class DataParallelNaive(nn.Module):
|
||||
"""
|
||||
Naive Data Parallelism. Not used in practice. But it is a good starting point to understand how data parallelism works.
|
||||
It implements a simple all-reduce operation to synchronize gradients across multiple processes.
|
||||
And `no_sync` context manager to disable gradient synchronization.
|
||||
"""
|
||||
def __init__(self, module):
|
||||
"""
|
||||
Initializes the DataParallel wrapper for a given module.
|
||||
@ -55,6 +60,9 @@ class DataParallelNaive(nn.Module):
|
||||
self.require_backward_grad_sync = True
|
||||
|
||||
class DataParallelBucket(nn.Module):
|
||||
"""
|
||||
Data Parallelism with gradient grouped into buckets to reduce the communication overhead.
|
||||
"""
|
||||
def __init__(self, module, bucket_cap_mb=25, grad_type = torch.float32):
|
||||
"""
|
||||
Initialize the DataParallelBucket module.
|
||||
|
||||
@ -16,8 +16,27 @@ def split_tensor_along_last_dim(tensor, num_partitions):
|
||||
last_dim_size = tensor.size()[last_dim] // num_partitions
|
||||
return torch.split(tensor, last_dim_size, dim=last_dim)
|
||||
|
||||
class CopyToModelParallelRegion(torch.autograd.Function):
|
||||
"""
|
||||
Copy in forward pass, all-reduce in backward pass.
|
||||
This is the `f` function in the paper: https://arxiv.org/abs/1909.08053
|
||||
"""
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
if pgm.process_group_manager.tp_world_size == 1:
|
||||
return grad_output
|
||||
dist.all_reduce(grad_output, op=dist.ReduceOp.SUM, group=pgm.process_group_manager.tp_group)
|
||||
return grad_output
|
||||
|
||||
class ReduceFromModelParallelRegion(torch.autograd.Function):
|
||||
"""All-reduce in forward pass, identity in backward pass."""
|
||||
"""
|
||||
All-reduce in forward pass, identity in backward pass.
|
||||
This is the `g` function in the paper: https://arxiv.org/abs/1909.08053
|
||||
"""
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
if pgm.process_group_manager.tp_world_size == 1:
|
||||
@ -52,27 +71,6 @@ class GatherFromModelParallelRegion(torch.autograd.Function):
|
||||
chunks = split_tensor_along_last_dim(grad_output, pgm.process_group_manager.tp_world_size)
|
||||
return chunks[pgm.process_group_manager.tp_rank].contiguous()
|
||||
|
||||
class CopyToModelParallelRegion(torch.autograd.Function):
|
||||
"""Copy in forward pass, all-reduce in backward pass."""
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
if pgm.process_group_manager.tp_world_size == 1:
|
||||
return grad_output
|
||||
dist.all_reduce(grad_output, op=dist.ReduceOp.SUM, group=pgm.process_group_manager.tp_group)
|
||||
return grad_output
|
||||
|
||||
def linear_with_all_reduce(x, weight, bias):
|
||||
input_parallel = CopyToModelParallelRegion.apply(x)
|
||||
output = F.linear(input_parallel, weight, bias) # XW_i^T + b, output is Y_i
|
||||
return output
|
||||
|
||||
def linear_with_async_all_reduce(x, weight, bias):
|
||||
return LinearWithAsyncAllReduce.apply(x, weight, bias)
|
||||
|
||||
class LinearWithAsyncAllReduce(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, input_, weight, bias):
|
||||
@ -100,4 +98,12 @@ class LinearWithAsyncAllReduce(torch.autograd.Function):
|
||||
grad_weight = grad_output.t() @ input_ # (out_size, b*s) @ (b*s, input_size) -> (out_size, input_size)
|
||||
grad_bias = grad_output.sum(0) if ctx.use_bias else None
|
||||
input_gradient_all_reduce_handle.wait()
|
||||
return grad_input, grad_weight, grad_bias
|
||||
return grad_input, grad_weight, grad_bias
|
||||
|
||||
def linear_with_all_reduce(x, weight, bias):
|
||||
input_parallel = CopyToModelParallelRegion.apply(x)
|
||||
output = F.linear(input_parallel, weight, bias) # XW_i^T + b, output is Y_i
|
||||
return output
|
||||
|
||||
def linear_with_async_all_reduce(x, weight, bias):
|
||||
return LinearWithAsyncAllReduce.apply(x, weight, bias)
|
||||
@ -52,7 +52,6 @@ def get_num_params(model):
|
||||
For DP: Parameters are replicated, so only count once
|
||||
|
||||
Note:
|
||||
LayerNorm: Split across TP ranks for sequence parallelism
|
||||
FSDP: Parameters are sharded across data parallel ranks
|
||||
"""
|
||||
tp_world_size = pgm.process_group_manager.tp_world_size
|
||||
@ -86,4 +85,11 @@ def assert_no_meta_tensors(model):
|
||||
if buffer.device == torch.device("meta"):
|
||||
meta_tensors.append(f"Buffer '{name}' with shape {buffer.shape}")
|
||||
|
||||
assert len(meta_tensors) == 0, f"Found {len(meta_tensors)} meta tensors:\n" + "\n".join(meta_tensors)
|
||||
assert len(meta_tensors) == 0, f"Found {len(meta_tensors)} meta tensors:\n" + "\n".join(meta_tensors)
|
||||
|
||||
def average_loss_across_dp_cp_ranks(loss, device):
|
||||
reduced_loss = torch.tensor([loss if loss is not None else 0.0], dtype=torch.float32, device=device)
|
||||
if pgm.process_group_manager.pp_is_last_stage:
|
||||
dist.all_reduce(reduced_loss, op=dist.ReduceOp.SUM, group=pgm.process_group_manager.cp_dp_group)
|
||||
reduced_loss /= pgm.process_group_manager.cp_dp_world_size
|
||||
return reduced_loss.item()
|
||||
29
train.py
29
train.py
@ -1,10 +1,6 @@
|
||||
"""Training script for LLaMA model.
|
||||
CUDA_DEVICE_MAX_CONNECTIONS=1 torchrun --nproc_per_node 1 --master_addr localhost --master_port 25500 train.py --config tmp/dummy/360M_131K.json
|
||||
CUDA_DEVICE_MAX_CONNECTIONS=1 torchrun --nproc_per_node 2 --master_addr localhost --master_port 25500 train.py --config tmp/dummy/360M_131K.json
|
||||
CUDA_DEVICE_MAX_CONNECTIONS=1 torchrun --nproc_per_node 4 --master_addr localhost --master_port 25500 train.py --config tmp/dummy/llama2_7b_benchmark.json
|
||||
CUDA_DEVICE_MAX_CONNECTIONS=1 torchrun --nproc_per_node 8 --master_addr localhost --master_port 25500 train.py --config tmp/dummy/360M_131K.json
|
||||
CUDA_DEVICE_MAX_CONNECTIONS=1 debugpy-run -p 5678 -m torch.distributed.run -- --nproc_per_node=2 --nnodes=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:29400 train.py --config tmp/dummy/360M_131K.json
|
||||
#VERBOSE=0 torchrun --nproc_per_node 4 --master_addr localhost --master_port 25500 train.py --pp_size 2 --dp_size 2
|
||||
CUDA_DEVICE_MAX_CONNECTIONS=1 debugpy-run -p 5678 -m torch.distributed.run -- --nproc_per_node=4 --nnodes=1 --rdzv_backend=c10d --rdzv_endpoint=localhost:29400 train.py --config tmp/dummy/llama2_7b_benchmark.json
|
||||
"""
|
||||
import os
|
||||
import inspect
|
||||
@ -20,7 +16,7 @@ from transformers import AutoConfig
|
||||
from picotron.context_parallel.context_parallel import apply_context_parallel
|
||||
from picotron.tensor_parallel.tensor_parallel import apply_tensor_parallel
|
||||
import picotron.process_group_manager as pgm
|
||||
from picotron.utils import set_all_seed, print, to_readable_format, get_mfu, get_num_params
|
||||
from picotron.utils import average_loss_across_dp_cp_ranks, set_all_seed, print, to_readable_format, get_mfu, get_num_params
|
||||
from picotron.checkpoint import CheckpointManager
|
||||
from picotron.checkpoint import init_model_with_dematerialized_weights, init_model_with_materialized_weights
|
||||
from picotron.data import MicroBatchDataLoader
|
||||
@ -111,8 +107,9 @@ if __name__ == "__main__":
|
||||
device=device,
|
||||
num_workers=config["dataset"]["num_workers"],
|
||||
num_proc=config["dataset"]["num_proc"],
|
||||
num_samples=config["training"]["num_samples"],
|
||||
subset_name=config["dataset"]["subset_name"],
|
||||
num_samples=config["training"].get("num_samples", None),
|
||||
subset_name=config["dataset"].get("subset_name", None),
|
||||
split=config["dataset"].get("split", "train")
|
||||
)
|
||||
|
||||
dist.barrier()
|
||||
@ -146,9 +143,10 @@ if __name__ == "__main__":
|
||||
if pgm.process_group_manager.global_rank == 0:
|
||||
print(f"rank {pgm.process_group_manager.global_rank}: Creating model config")
|
||||
model_config = AutoConfig.from_pretrained(config["model"]["name"])
|
||||
model_config.num_hidden_layers = config["model"]["num_hidden_layers"]
|
||||
model_config.num_attention_heads = config["model"]["num_attention_heads"]
|
||||
model_config.num_key_value_heads = config["model"]["num_key_value_heads"]
|
||||
# twist the model structure if specified in the config file
|
||||
model_config.num_hidden_layers = model_config.num_hidden_layers if "num_hidden_layers" not in config["model"] else config["model"]["num_hidden_layers"]
|
||||
model_config.num_attention_heads = model_config.num_attention_heads if "num_attention_heads" not in config["model"] else config["model"]["num_attention_heads"]
|
||||
model_config.num_key_value_heads = model_config.num_key_value_heads if "num_key_value_heads" not in config["model"] else config["model"]["num_key_value_heads"]
|
||||
model_config.max_position_embeddings = config["training"]["seq_length"]
|
||||
objects = [model_config]
|
||||
else:
|
||||
@ -208,13 +206,6 @@ if __name__ == "__main__":
|
||||
step, trained_tokens = checkpoint_manager.load_checkpoint(model, optimizer, config["checkpoint"]["load_path"])
|
||||
|
||||
dist.barrier()
|
||||
|
||||
def _all_reduce_loss_across_dp_cp_ranks(loss, device):
|
||||
reduced_loss = torch.tensor([loss if loss is not None else 0.0], dtype=torch.float32, device=device)
|
||||
if pgm.process_group_manager.pp_is_last_stage:
|
||||
dist.all_reduce(reduced_loss, op=dist.ReduceOp.SUM, group=pgm.process_group_manager.cp_dp_group)
|
||||
reduced_loss /= pgm.process_group_manager.cp_dp_world_size
|
||||
return reduced_loss.item()
|
||||
|
||||
while config["training"]["max_tokens"] is None or trained_tokens < config["training"]["max_tokens"]:
|
||||
step_start_time = time.time()
|
||||
@ -230,7 +221,7 @@ if __name__ == "__main__":
|
||||
else:
|
||||
loss = train_step(model, data_loader, device)
|
||||
|
||||
loss = _all_reduce_loss_across_dp_cp_ranks(loss, device)
|
||||
loss = average_loss_across_dp_cp_ranks(loss, device)
|
||||
|
||||
optimizer.step()
|
||||
trained_tokens += tokens_per_step
|
||||
|
||||
Loading…
Reference in New Issue
Block a user