Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +6 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/LICENSE +21 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/README.md +509 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-1/.metadata +3 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-1/__0_0.distcp +3 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-4/.metadata +3 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-4/__0_0.distcp +3 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-40/.metadata +3 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-40/__0_0.distcp +3 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/config.json +46 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/140M_lact_swiglu_nh4_fwlow_rank_momentum.json +33 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/760M_lact_swiglu_nh4_fwlow_rank_momentum_muon.json +33 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/delta_net_1B.json +29 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/delta_net_340M.json +26 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gated_deltanet_1B.json +22 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gated_deltanet_340M.json +22 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gla_340M.json +24 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gla_7B.json +25 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gsa_340M.json +29 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/hgrn2_340M.json +20 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba2_1B.json +32 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba2_340M.json +32 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba_1B.json +30 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba_340M.json +30 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/samba_1B.json +52 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/sba_340m.json +18 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/transformer_1B.json +22 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/transformer_340M.json +18 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/transformer_7B.json +21 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/download.py +4 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__init__.py +1 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/__init__.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/__init__.cpython-39.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/config_manager.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/data.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/train.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/__init__.py +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/__pycache__/__init__.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/__pycache__/checkpoint.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/checkpoint.py +59 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/config_manager.py +911 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/data.py +756 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__init__.py +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__pycache__/__init__.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__pycache__/parallelize_fla.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__pycache__/pipeline_fla.cpython-311.pyc +0 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/activation_offloading.py +447 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/fla.toml +67 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/parallelize_fla.py +550 -0
- batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/pipeline_fla.py +162 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-1/.metadata filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-1/__0_0.distcp filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-4/.metadata filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-4/__0_0.distcp filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-40/.metadata filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-40/__0_0.distcp filter=lfs diff=lfs merge=lfs -text
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2023-2025 Songlin Yang, Yu Zhang
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/README.md
ADDED
|
@@ -0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
| 1 |
+
<div align="center">
|
| 2 |
+
|
| 3 |
+
# 🔥 Flame: Flash Language Modeling Made Easy
|
| 4 |
+
|
| 5 |
+
</div>
|
| 6 |
+
|
| 7 |
+
Welcome to 🔥 `flame`, a minimal and efficient framework built on `torchtitan` for language models with blazing efficiency.
|
| 8 |
+
|
| 9 |
+
**Feature Highlights:**
|
| 10 |
+
|
| 11 |
+
- 🚀 Minimal, easy-to-use, extensible training framework
|
| 12 |
+
- 🤗 Seamless integration with `fla` and `transformers`
|
| 13 |
+
- 🔄 Zero-cost data preprocessing: online tokenization, dataset shuffling, and multiple datasets support
|
| 14 |
+
- 🔮 4D parallelism (coming soon)
|
| 15 |
+
|
| 16 |
+
## Setup
|
| 17 |
+
|
| 18 |
+
To get started, clone the `flame` repository and install the required dependencies:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
git clone https://github.com/fla-org/flame.git
|
| 22 |
+
cd flame
|
| 23 |
+
pip install .
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Install the latest version of fla
|
| 27 |
+
```
|
| 28 |
+
pip uninstall flash-linear-attention && pip install -U --no-use-pep517 git+https://github.com/fla-org/flash-linear-attention
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
[Important] Install specific version of torchtitan
|
| 32 |
+
```
|
| 33 |
+
pip install git+https://github.com/pytorch/torchtitan.git@5e2033c
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
## Dataset Preparation
|
| 38 |
+
To download the dataset to your local disk, create a new Python file with the following content and execute it:
|
| 39 |
+
|
| 40 |
+
```py
|
| 41 |
+
from datasets import load_dataset
|
| 42 |
+
|
| 43 |
+
# load fineweb-edu with parallel processing
|
| 44 |
+
dataset = load_dataset("HuggingFaceFW/fineweb-edu", name="default", num_proc=64, cache_dir="/your/cache/path")
|
| 45 |
+
|
| 46 |
+
# or load a subset with roughly 100B tokens, suitable for small- or medium-sized experiments
|
| 47 |
+
dataset = load_dataset("HuggingFaceFW/fineweb-edu", name="sample-100BT", num_proc=64, cache_dir="/your/cache/path")
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Training Recipes
|
| 51 |
+
|
| 52 |
+
Here's an example of training a 340M FLA Transformer model with a LLaMA-like architecture from scratch on a 100BT subset of the Fineweb-edu corpus ~~in streaming mode~~. (Do not use streaming mode if you are concerned about resuming training.)
|
| 53 |
+
|
| 54 |
+
> [!WARNING]
|
| 55 |
+
> If the dataset is not downloaded beforehand, the streaming mode will attempt to fetch it from a remote server and download it on-the-fly, which can be highly unstable during training due to network issues.
|
| 56 |
+
> For stable training, ensure the dataset is downloaded locally (see [**Dataset Preparation**](#dataset-preparation)). Otherwise, we assume you are only testing the new corpus.
|
| 57 |
+
|
| 58 |
+
```sh
|
| 59 |
+
bash train.sh \
|
| 60 |
+
--job.config_file flame/models/fla.toml \
|
| 61 |
+
--job.dump_folder exp/transformer-340M-4K-10B/batch1.seqlen65536.context4096.warmup1024.update1.steps20480.lr1e-3.cosine \
|
| 62 |
+
--model.config configs/transformer_340M.json \
|
| 63 |
+
--model.tokenizer_path fla-hub/transformer-1.3B-100B \
|
| 64 |
+
--optimizer.name AdamW \
|
| 65 |
+
--optimizer.eps 1e-15 \
|
| 66 |
+
--optimizer.lr 1e-3 \
|
| 67 |
+
--lr_scheduler.warmup_steps 1024 \
|
| 68 |
+
--lr_scheduler.lr_min 0.1 \
|
| 69 |
+
--lr_scheduler.decay_type cosine \
|
| 70 |
+
--training.batch_size 1 \
|
| 71 |
+
--training.seq_len 65536 \
|
| 72 |
+
--training.context_len 4096 \
|
| 73 |
+
--training.varlen \
|
| 74 |
+
--training.gradient_accumulation_steps 1 \
|
| 75 |
+
--training.steps 20480 \
|
| 76 |
+
--training.max_norm 1.0 \
|
| 77 |
+
--training.skip_nan_inf \
|
| 78 |
+
--training.dataset HuggingFaceFW/fineweb-edu \
|
| 79 |
+
--training.dataset_name sample-100BT \
|
| 80 |
+
--training.dataset_split train \
|
| 81 |
+
--training.num_workers 32 \
|
| 82 |
+
--training.prefetch_factor 2 \
|
| 83 |
+
--training.seed 42 \
|
| 84 |
+
--training.compile \
|
| 85 |
+
--checkpoint.interval 2048 \
|
| 86 |
+
--checkpoint.load_step -1 \
|
| 87 |
+
--checkpoint.keep_latest_k 2 \
|
| 88 |
+
--metrics.log_freq 1
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
You can specify the number of GPUs by setting the environment variable `NGPU`, which defaults to 8.
|
| 92 |
+
**For single-GPU debugging, set `NGPU=1`.**
|
| 93 |
+
|
| 94 |
+
We provide several [config files](https://github.com/fla-org/flame/tree/main/configs) for different models.
|
| 95 |
+
By default, the learning rate is set to 1e-3 with a cosine scheduler. Other schedulers, such as WSD (wsd), are also supported.
|
| 96 |
+
|
| 97 |
+
**Key parameters:**
|
| 98 |
+
- `--lr_scheduler.decay_ratio`: The proportion of the steps allocated to the decay phase. The learning rate will remain stable after the warmup period and only start decaying during the last `decay_ratio` portion of the total training steps, which is known as the Warmup-Stable-Decay (WSD) schedule.
|
| 99 |
+
- `--lr_scheduler.warmup_steps`: The number of steps for the learning rate warmup phase.
|
| 100 |
+
- `--training.steps`: Total number of training steps.
|
| 101 |
+
- `--training.batch_size`: Batch size per device, must be 1 if `--training.varlen` is set.
|
| 102 |
+
- `--training.seq_len`: The length of each sequence in the batch, which is concatenated from multiple samples.
|
| 103 |
+
- `--training.context_len`: The max allowed length of a sample. For non-varlen mode, this is equivalent to `seq_len`.
|
| 104 |
+
- `--training.varlen`: Whether to conduct variable-length sequence training.
|
| 105 |
+
- `--training.gradient_accumulation_steps`: Number of gradient accumulation steps.
|
| 106 |
+
|
| 107 |
+
> [!WARNING]
|
| 108 |
+
> The total number of tokens processed per batch, referred to as `global_batch_size`, is calculated as batch_size × gradient_accumulation_steps × num_gpus.
|
| 109 |
+
> Each step processes `global_batch_size * seq_len` tokens.
|
| 110 |
+
> Monitor the value of `global_batch_size`, `warmup_steps`, and `steps` carefully when modifying any of the hyperparameters!
|
| 111 |
+
|
| 112 |
+
For a detailed explanation of all parameters, run:
|
| 113 |
+
|
| 114 |
+
```sh
|
| 115 |
+
bash train.sh -h
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
<details>
|
| 119 |
+
<summary>Usage</summary>
|
| 120 |
+
|
| 121 |
+
```py
|
| 122 |
+
options:
|
| 123 |
+
-h, --help show this help message and exit
|
| 124 |
+
--job.config_file JOB.CONFIG_FILE
|
| 125 |
+
Job config file
|
| 126 |
+
--job.dump_folder JOB.DUMP_FOLDER
|
| 127 |
+
Folder to dump job outputs
|
| 128 |
+
--job.description JOB.DESCRIPTION
|
| 129 |
+
Description of the job
|
| 130 |
+
--job.use_for_integration_test
|
| 131 |
+
Add this config to the integration test suite
|
| 132 |
+
--job.print_args Print the args to terminal
|
| 133 |
+
--model.config MODEL.CONFIG
|
| 134 |
+
Path to the model config
|
| 135 |
+
--model.norm_type MODEL.NORM_TYPE
|
| 136 |
+
Type of layer normalization to use [layernorm,
|
| 137 |
+
np_layernorm, rmsnorm, fused_rmsnorm]
|
| 138 |
+
--model.tokenizer_path MODEL.TOKENIZER_PATH
|
| 139 |
+
Tokenizer path
|
| 140 |
+
--profiling.enable_profiling
|
| 141 |
+
Whether to enable pytorch profiler
|
| 142 |
+
--profiling.save_traces_folder PROFILING.SAVE_TRACES_FOLDER
|
| 143 |
+
Trace files location
|
| 144 |
+
--profiling.profile_freq PROFILING.PROFILE_FREQ
|
| 145 |
+
How often to collect profiler traces, in iterations
|
| 146 |
+
--profiling.enable_memory_snapshot
|
| 147 |
+
Whether to dump memory snapshot
|
| 148 |
+
--profiling.save_memory_snapshot_folder PROFILING.SAVE_MEMORY_SNAPSHOT_FOLDER
|
| 149 |
+
Memeory snapshot files location
|
| 150 |
+
--optimizer.name OPTIMIZER.NAME
|
| 151 |
+
Optimizer to use
|
| 152 |
+
--optimizer.eps OPTIMIZER.EPS
|
| 153 |
+
Epsilon value for the optimizer.
|
| 154 |
+
--optimizer.fused Whether the fused implementation(CUDA only) is used.
|
| 155 |
+
--optimizer.scheduler {wsd,cosine,linear}
|
| 156 |
+
Scheduler to use. Currently supported: wsd, cosine,
|
| 157 |
+
and linear.
|
| 158 |
+
--optimizer.lr OPTIMIZER.LR
|
| 159 |
+
Learning rate to use
|
| 160 |
+
--optimizer.min_lr_ratio OPTIMIZER.MIN_LR_RATIO
|
| 161 |
+
Min lr ratio for lr scheduler
|
| 162 |
+
--optimizer.early_step_in_backward
|
| 163 |
+
Whether to apply optimizer in the backward. Caution,
|
| 164 |
+
optimizer_in_backward is not compatible with gradients
|
| 165 |
+
clipping, users should not call
|
| 166 |
+
register_post_accumulate_grad_hook after the optimizer
|
| 167 |
+
is built.
|
| 168 |
+
--training.batch_size TRAINING.BATCH_SIZE
|
| 169 |
+
Batch size
|
| 170 |
+
--training.seq_len TRAINING.SEQ_LEN
|
| 171 |
+
Sequence length
|
| 172 |
+
--training.context_len TRAINING.CONTEXT_LEN
|
| 173 |
+
Max length allowed for each sequence
|
| 174 |
+
--training.varlen Whether to take sequences of variable length as input
|
| 175 |
+
--training.warmup_steps TRAINING.WARMUP_STEPS
|
| 176 |
+
Steps for lr scheduler warmup, normally 1/5 of
|
| 177 |
+
--training.steps
|
| 178 |
+
--training.gradient_accumulation_steps TRAINING.GRADIENT_ACCUMULATION_STEPS
|
| 179 |
+
Number of steps to accumulate gradients before
|
| 180 |
+
updating parameters
|
| 181 |
+
--training.steps TRAINING.STEPS
|
| 182 |
+
How many train steps to run
|
| 183 |
+
--training.max_norm TRAINING.MAX_NORM
|
| 184 |
+
Max norm for gradient clipping
|
| 185 |
+
--training.skip_nan_inf
|
| 186 |
+
Skip batch updates when NaN or INF gradients are
|
| 187 |
+
encountered during training
|
| 188 |
+
--training.dataset TRAINING.DATASET
|
| 189 |
+
Dataset to use, with comma separated values
|
| 190 |
+
--training.dataset_name TRAINING.DATASET_NAME
|
| 191 |
+
The name of the dataset config, with comma separated
|
| 192 |
+
values if provided
|
| 193 |
+
--training.dataset_split TRAINING.DATASET_SPLIT
|
| 194 |
+
Dataset split to use, with comma separated values if
|
| 195 |
+
provided
|
| 196 |
+
--training.data_dir TRAINING.DATA_DIR
|
| 197 |
+
Data dirs to use, with comma separated values if
|
| 198 |
+
provided
|
| 199 |
+
--training.data_files TRAINING.DATA_FILES
|
| 200 |
+
Data files to use, with comma separated values if
|
| 201 |
+
provided
|
| 202 |
+
--training.data_probs TRAINING.DATA_PROBS
|
| 203 |
+
Data sampling probabilities, with comma separated
|
| 204 |
+
values if provided
|
| 205 |
+
--training.streaming Whether to load dataset in streaming mode, used for
|
| 206 |
+
huge dataset
|
| 207 |
+
--training.num_workers TRAINING.NUM_WORKERS
|
| 208 |
+
Number of subprocesses to use for data loading. 0
|
| 209 |
+
means that the data will be loaded in the main
|
| 210 |
+
process.
|
| 211 |
+
--training.prefetch_factor TRAINING.PREFETCH_FACTOR
|
| 212 |
+
Number of batches loaded in advance by each worker.2
|
| 213 |
+
means there will be a total of 2 * num_workers batches
|
| 214 |
+
prefetched across all workers.
|
| 215 |
+
--training.data_parallel_replicate_degree TRAINING.DATA_PARALLEL_REPLICATE_DEGREE
|
| 216 |
+
The `data_parallel_replicate_degree` argument
|
| 217 |
+
specifies the degree of data parallelism for weight
|
| 218 |
+
replication. When this value is greater than 1,
|
| 219 |
+
weights will be replicated across
|
| 220 |
+
`data_parallel_replicate_degree` ranks. If
|
| 221 |
+
`data_parallel_shard_degree` is also greater than 1,
|
| 222 |
+
the parallelism method used is HSDP (Hybrid Sharded
|
| 223 |
+
Data Parallelism). Otherwise, the parallelism method
|
| 224 |
+
used is DDP (Distributed Data Parallelism). 1 means
|
| 225 |
+
disabled.
|
| 226 |
+
--training.data_parallel_shard_degree TRAINING.DATA_PARALLEL_SHARD_DEGREE
|
| 227 |
+
The `data_parallel_shard_degree` argument specifies
|
| 228 |
+
the degree of data parallelism for weight sharding.
|
| 229 |
+
When this value is greater than 1, weights will be
|
| 230 |
+
sharded across `data_parallel_shard_degree` ranks. If
|
| 231 |
+
`data_parallel_replicate_degree` is also greater than
|
| 232 |
+
1, the parallelism method used is HSDP (Hybrid Sharded
|
| 233 |
+
Data Parallelism). Otherwise, the parallelism method
|
| 234 |
+
used is FSDP (Fully Sharded Data Parallelism). -1
|
| 235 |
+
means leftover ranks will be used (After
|
| 236 |
+
DP_REPLICATE/SP/PP). Note that only
|
| 237 |
+
`data_parallel_shard_degree` can be negative. 1 means
|
| 238 |
+
disabled.
|
| 239 |
+
--training.enable_cpu_offload
|
| 240 |
+
Whether to apply CPU offloading of parameters,
|
| 241 |
+
gradients, and optimizer states in FSDP
|
| 242 |
+
--training.tensor_parallel_degree TRAINING.TENSOR_PARALLEL_DEGREE
|
| 243 |
+
Tensor Parallelism degree. 1 means disabled.
|
| 244 |
+
--training.disable_loss_parallel
|
| 245 |
+
Whether to apply loss parallel when sequence parallel
|
| 246 |
+
is enabled
|
| 247 |
+
--training.mixed_precision_param {bfloat16,float32}
|
| 248 |
+
torch dtype to use for parameters when applying mixed
|
| 249 |
+
precision via FSDP. This feature only takes effect
|
| 250 |
+
when data_parallel_shard_degree > 1
|
| 251 |
+
--training.mixed_precision_reduce {float32}
|
| 252 |
+
torch dtype to use for reductions when applying mixed
|
| 253 |
+
precision via FSDP. This feature only takes effect
|
| 254 |
+
when data_parallel_shard_degree > 1
|
| 255 |
+
--training.compile Whether to compile the model
|
| 256 |
+
--training.gc_freq TRAINING.GC_FREQ
|
| 257 |
+
Python garbage control scheduling interval, in steps
|
| 258 |
+
--training.seed TRAINING.SEED
|
| 259 |
+
Choose the base RNG seed used for training
|
| 260 |
+
--training.deterministic
|
| 261 |
+
Use deterministic algorithms wherever possible, may be
|
| 262 |
+
slower
|
| 263 |
+
--metrics.log_freq METRICS.LOG_FREQ
|
| 264 |
+
How often to log metrics to TensorBoard, in iterations
|
| 265 |
+
--metrics.enable_tensorboard
|
| 266 |
+
Whether to log metrics to TensorBoard
|
| 267 |
+
--metrics.disable_color_printing
|
| 268 |
+
Whether to disable color printing in logs
|
| 269 |
+
--metrics.save_tb_folder METRICS.SAVE_TB_FOLDER
|
| 270 |
+
Folder to dump TensorBoard states
|
| 271 |
+
--metrics.rank_0_only
|
| 272 |
+
Whether to save TensorBoard metrics only for rank 0 or
|
| 273 |
+
for all ranks. When pipeline_parallel_degree is > 1,
|
| 274 |
+
this option uses the 0th rank of the last stage
|
| 275 |
+
pipeline group, which is the only stage that computes
|
| 276 |
+
loss metrics.
|
| 277 |
+
--metrics.enable_wandb
|
| 278 |
+
Whether to log metrics to Weights & Biases
|
| 279 |
+
--experimental.enable_async_tensor_parallel
|
| 280 |
+
Whether to apply async tensor parallel (currently only
|
| 281 |
+
effective when compile is enabled)
|
| 282 |
+
--experimental.pipeline_parallel_degree EXPERIMENTAL.PIPELINE_PARALLEL_DEGREE
|
| 283 |
+
Pipeline Parallelism degree, or number of ranks. 1
|
| 284 |
+
means disabled. If using looped schedules, this still
|
| 285 |
+
specifies the number of physical ranks, not the number
|
| 286 |
+
of stages. Stages per rank are inferred from split
|
| 287 |
+
points degree, and schedule.
|
| 288 |
+
--experimental.pipeline_parallel_split_points EXPERIMENTAL.PIPELINE_PARALLEL_SPLIT_POINTS [EXPERIMENTAL.PIPELINE_PARALLEL_SPLIT_POINTS ...]
|
| 289 |
+
Specify comma-separated names of modules to use as the
|
| 290 |
+
beginning of a split point. e.g. "layers.0,layers.2"
|
| 291 |
+
will cause the model to be split into 3 stages, the
|
| 292 |
+
first containing all the layers up to layers.0, the
|
| 293 |
+
second containing layers.0 and up to layers.2, the
|
| 294 |
+
third containing layers.2 and all the remaining
|
| 295 |
+
layers. Note: fully-automated splitting may be enabled
|
| 296 |
+
in the future, but currently the split points must be
|
| 297 |
+
specified manually.
|
| 298 |
+
--experimental.pipeline_parallel_schedule EXPERIMENTAL.PIPELINE_PARALLEL_SCHEDULE
|
| 299 |
+
Specify the Pipeline Parallel schedule to use. The
|
| 300 |
+
supported schedules are: https://github.com/pytorch/py
|
| 301 |
+
torch/blob/de4c2a3b4e89d96334dc678d1c3f2ae51a6630a0/to
|
| 302 |
+
rch/distributed/pipelining/schedules.py#L2161. The
|
| 303 |
+
schedule must be compatible with the split points and
|
| 304 |
+
stages_per_rank. Looped schedules (e.g.
|
| 305 |
+
Interleaved1F1B) require specifying
|
| 306 |
+
pipeline_parallel_degree = number of ranks, and
|
| 307 |
+
split_points = number of stages - 1
|
| 308 |
+
--experimental.pipeline_parallel_schedule_csv EXPERIMENTAL.PIPELINE_PARALLEL_SCHEDULE_CSV
|
| 309 |
+
Specify the path to the pipeline parallel schedule csv
|
| 310 |
+
file to use. The pipeline_parallel_schedule argument
|
| 311 |
+
must be either PipelineScheduleSingle,
|
| 312 |
+
PipelineScheduleMulti, or _PipelineScheduleRuntime.
|
| 313 |
+
--experimental.pipeline_parallel_microbatches EXPERIMENTAL.PIPELINE_PARALLEL_MICROBATCHES
|
| 314 |
+
How many microbatches to split the global training
|
| 315 |
+
batch into when using pipeline parallelism. The global
|
| 316 |
+
training batch size must be evenly divisible by the
|
| 317 |
+
number of microbatches. The default value will be the
|
| 318 |
+
number of pipeline stages, if unspecified.
|
| 319 |
+
--experimental.enable_compiled_autograd
|
| 320 |
+
Enable CompiledAutograd to compile the backward.
|
| 321 |
+
--experimental.context_parallel_degree EXPERIMENTAL.CONTEXT_PARALLEL_DEGREE
|
| 322 |
+
Context parallelism degree. 1 means disabled.
|
| 323 |
+
--experimental.context_parallel_rotate_method EXPERIMENTAL.CONTEXT_PARALLEL_ROTATE_METHOD
|
| 324 |
+
The collective to use in context parallel SDPA for kv
|
| 325 |
+
shards exchange. 'allgather' means to all-gather all
|
| 326 |
+
kv shards on ranks after the first sub-SDPA
|
| 327 |
+
computation, 'alltoall' means to all-to-all shuffle
|
| 328 |
+
the kv shards. The default value is 'allgather'.
|
| 329 |
+
--checkpoint.enable_checkpoint
|
| 330 |
+
Whether to enable checkpoint
|
| 331 |
+
--checkpoint.folder CHECKPOINT.FOLDER
|
| 332 |
+
The folder to store the checkpoints. When
|
| 333 |
+
enable_checkpoint is set to true, checkpoints will be
|
| 334 |
+
in {--job.dump_folder}/{--checkpoint.folder}.
|
| 335 |
+
--checkpoint.interval_type CHECKPOINT.INTERVAL_TYPE
|
| 336 |
+
Checkpointing interval unit of measurement ['step',
|
| 337 |
+
'seconds']
|
| 338 |
+
--checkpoint.interval CHECKPOINT.INTERVAL
|
| 339 |
+
Checkpointing interval, in steps or seconds depending
|
| 340 |
+
on --checkpoint.interval_type
|
| 341 |
+
--checkpoint.model_weights_only
|
| 342 |
+
When model_weights_only=True, only model weights will
|
| 343 |
+
be saved at the end of training. With this,
|
| 344 |
+
checkpoints can be loaded using `torch.load(...,
|
| 345 |
+
weights_only=True)` after conversion. When
|
| 346 |
+
model_weights_only=False, the full checkpoint will be
|
| 347 |
+
saved. A full checkpoint includes model, optimizer and
|
| 348 |
+
train_state, which can be used to resume training. The
|
| 349 |
+
default value is false.
|
| 350 |
+
--checkpoint.export_dtype {float16,bfloat16,float32}
|
| 351 |
+
Converts to the specified precision when training
|
| 352 |
+
completes and model_weights_only=true. Currently
|
| 353 |
+
supports float32, float16, and bfloat16. The default
|
| 354 |
+
value is float32.
|
| 355 |
+
--checkpoint.create_seed_checkpoint
|
| 356 |
+
Initializes the full model without applying
|
| 357 |
+
parallelisms, and then saves it as a seed checkpoint.
|
| 358 |
+
Note: requires user to call train.py without
|
| 359 |
+
specifying any parallelisms, e.g. NGPU=1. Could be
|
| 360 |
+
implemented as a separate script, but this way shares
|
| 361 |
+
more code.
|
| 362 |
+
--checkpoint.async_mode CHECKPOINT.ASYNC_MODE
|
| 363 |
+
Which async checkpoint mode to use. Currently there
|
| 364 |
+
are 3 different modes. 1. "disabled": synchronized
|
| 365 |
+
checkpointing will be used. 2. "async":
|
| 366 |
+
torch.distributed.checkpoint.async_save will be used.
|
| 367 |
+
1. "async_with_pinned_mem": this option utilizes a
|
| 368 |
+
dedicated pinned memory space and creates a separate
|
| 369 |
+
process for faster GPU->CPU transfer performance and
|
| 370 |
+
eliminating GIL contention. The cost is increased CPU
|
| 371 |
+
memory usage. If insufficient CPU memory is available,
|
| 372 |
+
performance may degrade due to memory paging. For most
|
| 373 |
+
users, "async" should suffice as the performance
|
| 374 |
+
overhead is typically small (on the order of tens of
|
| 375 |
+
seconds) compared to checkpointing frequency. This
|
| 376 |
+
mode can be employed to pursue near-zero checkpointing
|
| 377 |
+
times (e.g., < 1 second) given appropriate hardware
|
| 378 |
+
support such as ample CPU memory and fast PCIe.
|
| 379 |
+
"disabled" is the default mode.
|
| 380 |
+
--checkpoint.keep_latest_k CHECKPOINT.KEEP_LATEST_K
|
| 381 |
+
Keeps only the latest k checkpoints, and purging older
|
| 382 |
+
ones. If 0, keep all checkpoints. 0 is the default
|
| 383 |
+
value.
|
| 384 |
+
--checkpoint.load_step CHECKPOINT.LOAD_STEP
|
| 385 |
+
Load the checkpoint at the specified step. If -1, load
|
| 386 |
+
the latest checkpoint.
|
| 387 |
+
--float8.enable_float8_linear
|
| 388 |
+
If true, swaps `torch.nn.Linear` with `Float8Linear`.
|
| 389 |
+
This feature requires you to install 'torchao' which
|
| 390 |
+
can be found here: https://github.com/pytorch/ao
|
| 391 |
+
--float8.enable_fsdp_float8_all_gather
|
| 392 |
+
Whether enable float8 all-gather in FSDP
|
| 393 |
+
--float8.precompute_float8_dynamic_scale_for_fsdp
|
| 394 |
+
Whether precompute float8 scales dynamically for FSDP
|
| 395 |
+
--float8.scaling_type_input {dynamic,delayed}
|
| 396 |
+
float8 scaling for input, dynamic (default) or delayed
|
| 397 |
+
--float8.scaling_type_weight FLOAT8.SCALING_TYPE_WEIGHT
|
| 398 |
+
float8 scaling for input, dynamic (default) or delayed
|
| 399 |
+
--float8.scaling_type_grad_output FLOAT8.SCALING_TYPE_GRAD_OUTPUT
|
| 400 |
+
float8 scaling for input, dynamic (default) or delayed
|
| 401 |
+
--comm.init_timeout_seconds COMM.INIT_TIMEOUT_SECONDS
|
| 402 |
+
Timeout for communication operations, during
|
| 403 |
+
initialization and first train step.
|
| 404 |
+
--comm.train_timeout_seconds COMM.TRAIN_TIMEOUT_SECONDS
|
| 405 |
+
Timeout for communication operations after the first
|
| 406 |
+
train step -- usually a tighter bound than during
|
| 407 |
+
initialization.
|
| 408 |
+
--comm.trace_buf_size COMM.TRACE_BUF_SIZE
|
| 409 |
+
Flight recorder ring buffer size, >0 means recording
|
| 410 |
+
by default, 0 means disabled
|
| 411 |
+
--memory_estimation.enabled
|
| 412 |
+
Whether to estimate memory usage for FSDP
|
| 413 |
+
--memory_estimation.disable_fake_mode
|
| 414 |
+
Whether to estimate memory under FakeTensorMode
|
| 415 |
+
```
|
| 416 |
+
</details>
|
| 417 |
+
|
| 418 |
+
### Training with `torch.compile`
|
| 419 |
+
|
| 420 |
+
Starting from `torch 2.0`, `torch.compile` has been introduced as a new feature to seamlessly accelerate training processes.
|
| 421 |
+
In `flame`, one can simply enable `torch.compile` by adding `--training.compile` flag to your training script.
|
| 422 |
+
|
| 423 |
+
However, `fla` has integrated numerous fused kernels for acceleration, which may potentially conflict with `torch.compile`.
|
| 424 |
+
We are actively working on resolving these issues to make compilation transparent to users.
|
| 425 |
+
In the meantime, please ensure you are using the latest dependencies.
|
| 426 |
+
|
| 427 |
+
Specifically, **we recommend using `torch>=2.6` and `triton>=3.0`**.
|
| 428 |
+
|
| 429 |
+
### Training with multiple datasets
|
| 430 |
+
|
| 431 |
+
If you wish to train a model with all-round capabilities (e.g., code, math, and multilingual ability), it's necessary to train on multiple datasets.
|
| 432 |
+
`flame` allows training with multiple datasets easily.
|
| 433 |
+
For example, you can specify the following arguments to train on 6 datasets with different proportions:
|
| 434 |
+
|
| 435 |
+
```sh
|
| 436 |
+
--training.dataset HuggingFaceFW/fineweb-edu,opencsg/Fineweb-Edu-Chinese-V2.1,OpenCoder-LLM/opc-fineweb-code-corpus,math-ai/AutoMathText,EleutherAI/proof-pile-2,OpenCoder-LLM/opc-fineweb-math-corpus \
|
| 437 |
+
--training.data_probs 0.6,0.15,0.15,0.014,0.058,0.028 \
|
| 438 |
+
```
|
| 439 |
+
|
| 440 |
+
### ~Finalizing training~
|
| 441 |
+
|
| 442 |
+
> [!NOTE]
|
| 443 |
+
> We have done this conversion automatically in the training script since our latest updates.
|
| 444 |
+
|
| 445 |
+
Once training is complete, you may want to convert the distributed checkpoints (DCPs) into the 🤗 format for broader use.
|
| 446 |
+
To facilitate this, we provide a straightforward conversion script:
|
| 447 |
+
|
| 448 |
+
```sh
|
| 449 |
+
python -m flame.utils.convert_dcp_to_hf --path <path_to_model> --step <step> --config <path_to_config> --tokenizer <path_to_tokenizer>
|
| 450 |
+
```
|
| 451 |
+
After this, your model will be in the 🤗 format, ready to be shared or deployed.
|
| 452 |
+
You can then easily publish your model using the `huggingface_hub` for wider accessibility.
|
| 453 |
+
|
| 454 |
+
### Continual training
|
| 455 |
+
|
| 456 |
+
If you wish to build upon a strong pre-trained model (in 🤗 format) and continue training, we also offer a script to convert the 🤗 format model back into DCP format.
|
| 457 |
+
This allows you to seamlessly resume training with `flame`.
|
| 458 |
+
```sh
|
| 459 |
+
python -m flame.utils.convert_hf_to_dcp --model <path_to_hf> --checkpoint <path_to_dcp/checkpoint/step-0>
|
| 460 |
+
```
|
| 461 |
+
Here, `<path_to_dcp>` is the directory where your distributed checkpoints will be stored.
|
| 462 |
+
The checkpoint is intentionally saved at `<step-0>` within the checkpoint folder to ensure it is loadable by `flame` during the initial training step, similar to how a seed checkpoint is handled.
|
| 463 |
+
|
| 464 |
+
Once the conversion is complete, you can proceed with training using `flame` as usual, continuing from where the pretrained model left off.
|
| 465 |
+
|
| 466 |
+
## Multi-node training
|
| 467 |
+
|
| 468 |
+
If you have access to multi-node GPUs, consider leveraging them for optimal performance.
|
| 469 |
+
This process is straightforward and well-documented in the PyTorch [docs](https://pytorch.org/docs/stable/elastic/run.html).
|
| 470 |
+
|
| 471 |
+
To set up multi-node training:
|
| 472 |
+
* Set the environment variables `MASTER_ADDR=<ip>` and `MASTER_PORT=<port>` before running the training script across all nodes.
|
| 473 |
+
* If you're using a job scheduler like Slurm, it will handle these variables for you.
|
| 474 |
+
|
| 475 |
+
`torchtitan` provides a [Slurm script](https://github.com/pytorch/torchtitan/blob/main/multinode_trainer.slurm) for multi-node training, which you can use as a reference or starting point.
|
| 476 |
+
|
| 477 |
+
## Custom models
|
| 478 |
+
|
| 479 |
+
`flame` supports custom model architectures through seamless integration with the Hugging Face `transformers` library. To add your own model:
|
| 480 |
+
|
| 481 |
+
1. Create a new model directory under `custom_models/` (see `custom_models/sba` for a complete example)
|
| 482 |
+
2. Implement your model classes and configuration:
|
| 483 |
+
- Define a config class inheriting from `PretrainedConfig` (see `custom_models/sba/config_sba.py` for an example)
|
| 484 |
+
- Create model classes inheriting from `PreTrainedModel` (see `custom_models/sba/modeling_sba.py` for an example)
|
| 485 |
+
3. Register your models in `__init__.py`:
|
| 486 |
+
- Import your model classes and config classes
|
| 487 |
+
- Register your models with the `AutoModelForCausalLM`, `AutoModel` and `AutoConfig` classes (see `custom_models/sba/__init__.py` for an example)
|
| 488 |
+
4. Create a config file for your custom model, just need to specify the `model_type` to the one you just named for your custom model (example: `configs/sba_340m.json`).
|
| 489 |
+
5. Training is extremely simple, you can just use the `flame.train.py` script to train your custom model.
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
## Citation
|
| 498 |
+
|
| 499 |
+
If you find `flame` helpful for your work, please consider citing it.
|
| 500 |
+
|
| 501 |
+
```bib
|
| 502 |
+
@software{yang2025flame,
|
| 503 |
+
title = {Flame: Flash Language Modeling Made Easy},
|
| 504 |
+
author = {Zhang, Yu and Yang, Songlin},
|
| 505 |
+
url = {https://github.com/fla-org/flame},
|
| 506 |
+
month = jan,
|
| 507 |
+
year = {2025}
|
| 508 |
+
}
|
| 509 |
+
```
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-1/.metadata
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c946323a1df9a30227efd61a82718c546cb5f16bec1dd24bf6c70412048308c0
|
| 3 |
+
size 1193269
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-1/__0_0.distcp
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:387d32504a9e5dc3ceba1fdb9a8c3d9e84d364642e92b12008864a96b2821e05
|
| 3 |
+
size 976615997
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-4/.metadata
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f246156eb0e8acaf48deafbab27f8d208aaacd4e57aadd19443e2dcf0aaddce2
|
| 3 |
+
size 1193269
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-4/__0_0.distcp
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8949f5e1e1955ddd6193947c4ec64b4dd73415560db4ebd59a367e9194bb7d80
|
| 3 |
+
size 976615997
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-40/.metadata
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3aafe92c2fa7422b644be3bdb5afc0d0d79f6a94bc3a460a1d9beca6f710966
|
| 3 |
+
size 1193270
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/checkpoint/step-40/__0_0.distcp
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ce7b4e8ae76093bc29dbbd4a33adfcd5f5aa9518a7fe55f221598aebc2cded47
|
| 3 |
+
size 976615997
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/config.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"LaCTForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attn_qk_norm": false,
|
| 7 |
+
"bos_token_id": 1,
|
| 8 |
+
"elementwise_affine": true,
|
| 9 |
+
"eos_token_id": 2,
|
| 10 |
+
"fuse_cross_entropy": true,
|
| 11 |
+
"fuse_norm": true,
|
| 12 |
+
"fuse_swiglu": true,
|
| 13 |
+
"fw_init_gain": 0.5,
|
| 14 |
+
"hidden_act": "swish",
|
| 15 |
+
"hidden_ratio": 4,
|
| 16 |
+
"hidden_size": 768,
|
| 17 |
+
"initializer_range": 0.02,
|
| 18 |
+
"inter_multi": 1,
|
| 19 |
+
"intermediate_size": null,
|
| 20 |
+
"lact_chunk_size": 2048,
|
| 21 |
+
"last_layer_fuse_norm": true,
|
| 22 |
+
"learnable_ttt_scale": true,
|
| 23 |
+
"lr_dim": 1,
|
| 24 |
+
"lr_parameterization": "mamba",
|
| 25 |
+
"max_position_embeddings": 32768,
|
| 26 |
+
"model_type": "lact_swiglu",
|
| 27 |
+
"norm_eps": 1e-06,
|
| 28 |
+
"num_attn_heads": 24,
|
| 29 |
+
"num_hidden_layers": 12,
|
| 30 |
+
"num_lact_heads": 4,
|
| 31 |
+
"qkv_bias": false,
|
| 32 |
+
"qkv_silu": true,
|
| 33 |
+
"rope_theta": 1000000,
|
| 34 |
+
"tie_word_embeddings": false,
|
| 35 |
+
"torch_dtype": "bfloat16",
|
| 36 |
+
"transformers_version": "4.53.2",
|
| 37 |
+
"ttt_loss_type": "dot_product",
|
| 38 |
+
"ttt_nope": false,
|
| 39 |
+
"ttt_prenorm": false,
|
| 40 |
+
"use_cache": true,
|
| 41 |
+
"use_momentum": true,
|
| 42 |
+
"use_muon": false,
|
| 43 |
+
"vocab_size": 32000,
|
| 44 |
+
"w0_w2_low_rank": 32,
|
| 45 |
+
"window_size": 2048
|
| 46 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/140M_lact_swiglu_nh4_fwlow_rank_momentum.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"fuse_cross_entropy": true,
|
| 6 |
+
"fuse_norm": true,
|
| 7 |
+
"hidden_act": "swish",
|
| 8 |
+
"hidden_size": 768,
|
| 9 |
+
"num_attn_heads": 24,
|
| 10 |
+
"num_hidden_layers": 12,
|
| 11 |
+
"initializer_range": 0.02,
|
| 12 |
+
"max_position_embeddings": 32768,
|
| 13 |
+
"model_type": "lact_swiglu",
|
| 14 |
+
"num_lact_heads": 4,
|
| 15 |
+
"inter_multi": 1,
|
| 16 |
+
"qkv_bias": false,
|
| 17 |
+
"attn_qk_norm": false,
|
| 18 |
+
"qkv_silu": true,
|
| 19 |
+
"lact_chunk_size": 2048,
|
| 20 |
+
"window_size": 2048,
|
| 21 |
+
"use_muon": false,
|
| 22 |
+
"lr_dim": 1,
|
| 23 |
+
"lr_parameterization": "mamba",
|
| 24 |
+
"learnable_ttt_scale": true,
|
| 25 |
+
"w0_w2_low_rank": 32,
|
| 26 |
+
"fw_init_gain": 0.5,
|
| 27 |
+
"use_momentum": true,
|
| 28 |
+
"rope_theta": 1000000,
|
| 29 |
+
"norm_eps": 1e-06,
|
| 30 |
+
"tie_word_embeddings": false,
|
| 31 |
+
"use_cache": true,
|
| 32 |
+
"vocab_size": 32000
|
| 33 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/760M_lact_swiglu_nh4_fwlow_rank_momentum_muon.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"fuse_cross_entropy": true,
|
| 6 |
+
"fuse_norm": true,
|
| 7 |
+
"hidden_act": "swish",
|
| 8 |
+
"hidden_size": 384,
|
| 9 |
+
"num_attn_heads": 24,
|
| 10 |
+
"num_hidden_layers": 2,
|
| 11 |
+
"initializer_range": 0.02,
|
| 12 |
+
"max_position_embeddings": 32768,
|
| 13 |
+
"model_type": "lact_swiglu",
|
| 14 |
+
"num_lact_heads": 4,
|
| 15 |
+
"inter_multi": 1,
|
| 16 |
+
"qkv_bias": false,
|
| 17 |
+
"attn_qk_norm": false,
|
| 18 |
+
"qkv_silu": true,
|
| 19 |
+
"lact_chunk_size": 2048,
|
| 20 |
+
"window_size": 2048,
|
| 21 |
+
"use_muon": true,
|
| 22 |
+
"lr_dim": 1,
|
| 23 |
+
"lr_parameterization": "mamba",
|
| 24 |
+
"learnable_ttt_scale": true,
|
| 25 |
+
"w0_w2_low_rank": 32,
|
| 26 |
+
"fw_init_gain": 0.5,
|
| 27 |
+
"use_momentum": true,
|
| 28 |
+
"rope_theta": 1000000,
|
| 29 |
+
"norm_eps": 1e-06,
|
| 30 |
+
"tie_word_embeddings": false,
|
| 31 |
+
"use_cache": true,
|
| 32 |
+
"vocab_size": 32000
|
| 33 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/delta_net_1B.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn": null,
|
| 3 |
+
"attn_mode": "chunk",
|
| 4 |
+
"bos_token_id": 1,
|
| 5 |
+
"conv_size": 4,
|
| 6 |
+
"eos_token_id": 2,
|
| 7 |
+
"expand_k": 1,
|
| 8 |
+
"expand_v": 1,
|
| 9 |
+
"fuse_cross_entropy": true,
|
| 10 |
+
"fuse_norm": true,
|
| 11 |
+
"hidden_act": "swish",
|
| 12 |
+
"hidden_ratio": 4,
|
| 13 |
+
"hidden_size": 2048,
|
| 14 |
+
"initializer_range": 0.02,
|
| 15 |
+
"intermediate_size": null,
|
| 16 |
+
"model_type": "delta_net",
|
| 17 |
+
"norm_eps": 1e-06,
|
| 18 |
+
"num_heads": 16,
|
| 19 |
+
"num_hidden_layers": 24,
|
| 20 |
+
"pad_token_id": 2,
|
| 21 |
+
"qk_activation": "silu",
|
| 22 |
+
"qk_norm": "l2",
|
| 23 |
+
"tie_word_embeddings": false,
|
| 24 |
+
"use_beta": true,
|
| 25 |
+
"use_cache": true,
|
| 26 |
+
"use_gate": false,
|
| 27 |
+
"use_output_norm": true,
|
| 28 |
+
"use_short_conv": true
|
| 29 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/delta_net_340M.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn_mode": "chunk",
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"conv_size": 4,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand_k": 1,
|
| 7 |
+
"expand_v": 1,
|
| 8 |
+
"fuse_cross_entropy": true,
|
| 9 |
+
"hidden_act": "swish",
|
| 10 |
+
"hidden_ratio": 4,
|
| 11 |
+
"hidden_size": 1024,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"intermediate_size": null,
|
| 14 |
+
"model_type": "delta_net",
|
| 15 |
+
"norm_eps": 1e-06,
|
| 16 |
+
"num_heads": 8,
|
| 17 |
+
"num_hidden_layers": 24,
|
| 18 |
+
"qk_activation": "silu",
|
| 19 |
+
"qk_norm": "l2",
|
| 20 |
+
"tie_word_embeddings": false,
|
| 21 |
+
"use_beta": true,
|
| 22 |
+
"use_cache": true,
|
| 23 |
+
"use_gate": false,
|
| 24 |
+
"use_output_norm": true,
|
| 25 |
+
"use_short_conv": true
|
| 26 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gated_deltanet_1B.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn_mode": "chunk",
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"conv_size": 4,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand_v": 2,
|
| 7 |
+
"fuse_cross_entropy": true,
|
| 8 |
+
"head_dim": 256,
|
| 9 |
+
"hidden_act": "swish",
|
| 10 |
+
"hidden_ratio": 4,
|
| 11 |
+
"hidden_size": 2048,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"intermediate_size": null,
|
| 14 |
+
"model_type": "gated_deltanet",
|
| 15 |
+
"norm_eps": 1e-06,
|
| 16 |
+
"num_heads": 6,
|
| 17 |
+
"num_hidden_layers": 21,
|
| 18 |
+
"tie_word_embeddings": false,
|
| 19 |
+
"use_cache": true,
|
| 20 |
+
"use_gate": true,
|
| 21 |
+
"use_short_conv": true
|
| 22 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gated_deltanet_340M.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn_mode": "chunk",
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"conv_size": 4,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand_v": 2,
|
| 7 |
+
"fuse_cross_entropy": true,
|
| 8 |
+
"head_dim": 256,
|
| 9 |
+
"hidden_act": "swish",
|
| 10 |
+
"hidden_ratio": 4,
|
| 11 |
+
"hidden_size": 1024,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"intermediate_size": null,
|
| 14 |
+
"model_type": "gated_deltanet",
|
| 15 |
+
"norm_eps": 1e-06,
|
| 16 |
+
"num_heads": 6,
|
| 17 |
+
"num_hidden_layers": 21,
|
| 18 |
+
"tie_word_embeddings": false,
|
| 19 |
+
"use_cache": true,
|
| 20 |
+
"use_gate": true,
|
| 21 |
+
"use_short_conv": true
|
| 22 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gla_340M.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn_mode": "chunk",
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"clamp_min": null,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand_k": 0.5,
|
| 7 |
+
"expand_v": 1,
|
| 8 |
+
"fuse_cross_entropy": true,
|
| 9 |
+
"fuse_norm": true,
|
| 10 |
+
"hidden_act": "swish",
|
| 11 |
+
"hidden_ratio": 4,
|
| 12 |
+
"hidden_size": 1024,
|
| 13 |
+
"initializer_range": 0.02,
|
| 14 |
+
"intermediate_size": null,
|
| 15 |
+
"model_type": "gla",
|
| 16 |
+
"num_heads": 4,
|
| 17 |
+
"num_hidden_layers": 24,
|
| 18 |
+
"norm_eps": 1e-06,
|
| 19 |
+
"tie_word_embeddings": false,
|
| 20 |
+
"use_cache": true,
|
| 21 |
+
"use_gk": true,
|
| 22 |
+
"use_gv": false,
|
| 23 |
+
"vocab_size": 32000
|
| 24 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gla_7B.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn": null,
|
| 3 |
+
"attn_mode": "chunk",
|
| 4 |
+
"bos_token_id": 1,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand_k": 0.5,
|
| 7 |
+
"expand_v": 1,
|
| 8 |
+
"fuse_cross_entropy": true,
|
| 9 |
+
"fuse_norm": true,
|
| 10 |
+
"hidden_act": "swish",
|
| 11 |
+
"hidden_ratio": 4,
|
| 12 |
+
"hidden_size": 4096,
|
| 13 |
+
"initializer_range": 0.02,
|
| 14 |
+
"intermediate_size": 11008,
|
| 15 |
+
"model_type": "gla",
|
| 16 |
+
"norm_eps": 1e-06,
|
| 17 |
+
"num_heads": 16,
|
| 18 |
+
"num_hidden_layers": 32,
|
| 19 |
+
"tie_word_embeddings": false,
|
| 20 |
+
"use_cache": true,
|
| 21 |
+
"use_gk": true,
|
| 22 |
+
"use_gv": false,
|
| 23 |
+
"use_output_gate": true,
|
| 24 |
+
"use_short_conv": false
|
| 25 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/gsa_340M.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"conv_size": 4,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"expand_k": 1,
|
| 6 |
+
"expand_v": 1,
|
| 7 |
+
"elementwise_affine": false,
|
| 8 |
+
"feature_map": "swish",
|
| 9 |
+
"fuse_cross_entropy": true,
|
| 10 |
+
"fuse_norm": true,
|
| 11 |
+
"gate_logit_normalizer": 4,
|
| 12 |
+
"hidden_act": "swish",
|
| 13 |
+
"hidden_ratio": 4,
|
| 14 |
+
"hidden_size": 1024,
|
| 15 |
+
"initializer_range": 0.02,
|
| 16 |
+
"intermediate_size": null,
|
| 17 |
+
"model_type": "gsa",
|
| 18 |
+
"num_heads": 4,
|
| 19 |
+
"num_hidden_layers": 24,
|
| 20 |
+
"num_slots": 64,
|
| 21 |
+
"norm_eps": 1e-06,
|
| 22 |
+
"share_conv_kernel": true,
|
| 23 |
+
"tie_word_embeddings": false,
|
| 24 |
+
"use_cache": true,
|
| 25 |
+
"use_norm": true,
|
| 26 |
+
"use_output_gate": true,
|
| 27 |
+
"use_rope": false,
|
| 28 |
+
"use_short_conv": false
|
| 29 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/hgrn2_340M.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn_mode": "chunk",
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"expand_ratio": 128,
|
| 6 |
+
"fuse_cross_entropy": true,
|
| 7 |
+
"fuse_norm": true,
|
| 8 |
+
"hidden_act": "swish",
|
| 9 |
+
"hidden_ratio": 4,
|
| 10 |
+
"hidden_size": 1024,
|
| 11 |
+
"initializer_range": 0.02,
|
| 12 |
+
"intermediate_size": null,
|
| 13 |
+
"model_type": "hgrn2",
|
| 14 |
+
"num_heads": 8,
|
| 15 |
+
"num_hidden_layers": 24,
|
| 16 |
+
"norm_eps": 1e-06,
|
| 17 |
+
"tie_word_embeddings": false,
|
| 18 |
+
"use_cache": true,
|
| 19 |
+
"vocab_size": 32000
|
| 20 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba2_1B.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"chunk_size": 256,
|
| 4 |
+
"conv_kernel": 4,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand": 2,
|
| 7 |
+
"fuse_cross_entropy": true,
|
| 8 |
+
"fuse_norm": true,
|
| 9 |
+
"head_dim": 64,
|
| 10 |
+
"hidden_act": "silu",
|
| 11 |
+
"hidden_size": 2048,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"norm_eps": 1e-05,
|
| 14 |
+
"model_type": "mamba2",
|
| 15 |
+
"n_groups": 1,
|
| 16 |
+
"num_hidden_layers": 48,
|
| 17 |
+
"pad_token_id": 0,
|
| 18 |
+
"rescale_prenorm_residual": true,
|
| 19 |
+
"residual_in_fp32": true,
|
| 20 |
+
"rms_norm": true,
|
| 21 |
+
"state_size": 128,
|
| 22 |
+
"tie_word_embeddings": false,
|
| 23 |
+
"time_step_floor": 0.0001,
|
| 24 |
+
"time_step_max": 0.1,
|
| 25 |
+
"time_step_min": 0.001,
|
| 26 |
+
"time_step_rank": 128,
|
| 27 |
+
"transformers_version": "4.50.1",
|
| 28 |
+
"use_bias": false,
|
| 29 |
+
"use_cache": true,
|
| 30 |
+
"use_conv_bias": true,
|
| 31 |
+
"vocab_size": 32000
|
| 32 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba2_340M.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"chunk_size": 256,
|
| 4 |
+
"conv_kernel": 4,
|
| 5 |
+
"eos_token_id": 2,
|
| 6 |
+
"expand": 2,
|
| 7 |
+
"fuse_cross_entropy": true,
|
| 8 |
+
"fuse_norm": true,
|
| 9 |
+
"head_dim": 64,
|
| 10 |
+
"hidden_act": "silu",
|
| 11 |
+
"hidden_size": 1024,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"norm_eps": 1e-05,
|
| 14 |
+
"model_type": "mamba2",
|
| 15 |
+
"n_groups": 1,
|
| 16 |
+
"num_hidden_layers": 48,
|
| 17 |
+
"pad_token_id": 0,
|
| 18 |
+
"rescale_prenorm_residual": true,
|
| 19 |
+
"residual_in_fp32": true,
|
| 20 |
+
"rms_norm": true,
|
| 21 |
+
"state_size": 128,
|
| 22 |
+
"tie_word_embeddings": false,
|
| 23 |
+
"time_step_floor": 0.0001,
|
| 24 |
+
"time_step_max": 0.1,
|
| 25 |
+
"time_step_min": 0.001,
|
| 26 |
+
"time_step_rank": 128,
|
| 27 |
+
"transformers_version": "4.50.1",
|
| 28 |
+
"use_bias": false,
|
| 29 |
+
"use_cache": true,
|
| 30 |
+
"use_conv_bias": true,
|
| 31 |
+
"vocab_size": 32000
|
| 32 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba_1B.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"conv_kernel": 4,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"expand": 2,
|
| 6 |
+
"fuse_cross_entropy": true,
|
| 7 |
+
"fuse_norm": true,
|
| 8 |
+
"hidden_act": "silu",
|
| 9 |
+
"hidden_size": 2048,
|
| 10 |
+
"initializer_range": 0.02,
|
| 11 |
+
"model_type": "mamba",
|
| 12 |
+
"norm_eps": 1e-05,
|
| 13 |
+
"num_hidden_layers": 48,
|
| 14 |
+
"pad_token_id": 0,
|
| 15 |
+
"rescale_prenorm_residual": false,
|
| 16 |
+
"residual_in_fp32": false,
|
| 17 |
+
"state_size": 16,
|
| 18 |
+
"tie_word_embeddings": false,
|
| 19 |
+
"time_step_floor": 0.0001,
|
| 20 |
+
"time_step_init_scheme": "random",
|
| 21 |
+
"time_step_max": 0.1,
|
| 22 |
+
"time_step_min": 0.001,
|
| 23 |
+
"time_step_rank": 128,
|
| 24 |
+
"time_step_scale": 1.0,
|
| 25 |
+
"transformers_version": "4.50.1",
|
| 26 |
+
"use_bias": false,
|
| 27 |
+
"use_cache": true,
|
| 28 |
+
"use_conv_bias": true,
|
| 29 |
+
"vocab_size": 32000
|
| 30 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/mamba_340M.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"conv_kernel": 4,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"expand": 2,
|
| 6 |
+
"fuse_cross_entropy": true,
|
| 7 |
+
"fuse_norm": true,
|
| 8 |
+
"hidden_act": "silu",
|
| 9 |
+
"hidden_size": 1024,
|
| 10 |
+
"initializer_range": 0.02,
|
| 11 |
+
"model_type": "mamba",
|
| 12 |
+
"norm_eps": 1e-05,
|
| 13 |
+
"num_hidden_layers": 48,
|
| 14 |
+
"pad_token_id": 0,
|
| 15 |
+
"rescale_prenorm_residual": false,
|
| 16 |
+
"residual_in_fp32": false,
|
| 17 |
+
"state_size": 16,
|
| 18 |
+
"tie_word_embeddings": false,
|
| 19 |
+
"time_step_floor": 0.0001,
|
| 20 |
+
"time_step_init_scheme": "random",
|
| 21 |
+
"time_step_max": 0.1,
|
| 22 |
+
"time_step_min": 0.001,
|
| 23 |
+
"time_step_rank": 128,
|
| 24 |
+
"time_step_scale": 1.0,
|
| 25 |
+
"transformers_version": "4.50.1",
|
| 26 |
+
"use_bias": false,
|
| 27 |
+
"use_cache": true,
|
| 28 |
+
"use_conv_bias": true,
|
| 29 |
+
"vocab_size": 32000
|
| 30 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/samba_1B.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attn": {
|
| 3 |
+
"layers": [
|
| 4 |
+
1,
|
| 5 |
+
3,
|
| 6 |
+
5,
|
| 7 |
+
7,
|
| 8 |
+
9,
|
| 9 |
+
11,
|
| 10 |
+
13,
|
| 11 |
+
15,
|
| 12 |
+
17
|
| 13 |
+
],
|
| 14 |
+
"num_heads": 18,
|
| 15 |
+
"num_kv_heads": 18,
|
| 16 |
+
"qkv_bias": false,
|
| 17 |
+
"rope_theta": 10000.0,
|
| 18 |
+
"window_size": 2048
|
| 19 |
+
},
|
| 20 |
+
"bos_token_id": 1,
|
| 21 |
+
"conv_kernel": 4,
|
| 22 |
+
"eos_token_id": 2,
|
| 23 |
+
"expand": 2,
|
| 24 |
+
"fuse_cross_entropy": true,
|
| 25 |
+
"fuse_norm": true,
|
| 26 |
+
"fuse_swiglu": true,
|
| 27 |
+
"hidden_act": "swish",
|
| 28 |
+
"hidden_ratio": 4,
|
| 29 |
+
"hidden_size": 2304,
|
| 30 |
+
"initializer_range": 0.02,
|
| 31 |
+
"intermediate_size": 4608,
|
| 32 |
+
"max_position_embeddings": 2048,
|
| 33 |
+
"model_type": "samba",
|
| 34 |
+
"norm_eps": 1e-05,
|
| 35 |
+
"num_hidden_layers": 18,
|
| 36 |
+
"pad_token_id": 0,
|
| 37 |
+
"rescale_prenorm_residual": false,
|
| 38 |
+
"residual_in_fp32": false,
|
| 39 |
+
"state_size": 16,
|
| 40 |
+
"tie_word_embeddings": false,
|
| 41 |
+
"time_step_floor": 0.0001,
|
| 42 |
+
"time_step_init_scheme": "random",
|
| 43 |
+
"time_step_max": 0.1,
|
| 44 |
+
"time_step_min": 0.001,
|
| 45 |
+
"time_step_rank": 144,
|
| 46 |
+
"time_step_scale": 1.0,
|
| 47 |
+
"transformers_version": "4.50.1",
|
| 48 |
+
"use_bias": false,
|
| 49 |
+
"use_cache": true,
|
| 50 |
+
"use_conv_bias": true,
|
| 51 |
+
"vocab_size": 32000
|
| 52 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/sba_340m.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"fuse_cross_entropy": true,
|
| 6 |
+
"fuse_norm": true,
|
| 7 |
+
"hidden_act": "swish",
|
| 8 |
+
"hidden_size": 1024,
|
| 9 |
+
"initializer_range": 0.006,
|
| 10 |
+
"max_position_embeddings": 8192,
|
| 11 |
+
"model_type": "sba",
|
| 12 |
+
"num_heads": 16,
|
| 13 |
+
"num_hidden_layers": 24,
|
| 14 |
+
"norm_eps": 1e-06,
|
| 15 |
+
"tie_word_embeddings": false,
|
| 16 |
+
"use_cache": true,
|
| 17 |
+
"vocab_size": 32000
|
| 18 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/transformer_1B.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 1,
|
| 3 |
+
"elementwise_affine": true,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"fuse_cross_entropy": true,
|
| 6 |
+
"fuse_norm": true,
|
| 7 |
+
"fuse_swiglu": true,
|
| 8 |
+
"hidden_act": "swish",
|
| 9 |
+
"hidden_ratio": 4,
|
| 10 |
+
"hidden_size": 2048,
|
| 11 |
+
"initializer_range": 0.02,
|
| 12 |
+
"intermediate_size": null,
|
| 13 |
+
"max_position_embeddings": 8192,
|
| 14 |
+
"model_type": "transformer",
|
| 15 |
+
"norm_eps": 1e-06,
|
| 16 |
+
"num_heads": 32,
|
| 17 |
+
"num_hidden_layers": 24,
|
| 18 |
+
"num_kv_heads": null,
|
| 19 |
+
"pad_token_id": 2,
|
| 20 |
+
"rope_theta": 10000.0,
|
| 21 |
+
"tie_word_embeddings": false
|
| 22 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/transformer_340M.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"fuse_cross_entropy": true,
|
| 6 |
+
"fuse_norm": true,
|
| 7 |
+
"hidden_act": "swish",
|
| 8 |
+
"hidden_size": 1024,
|
| 9 |
+
"initializer_range": 0.02,
|
| 10 |
+
"max_position_embeddings": 8192,
|
| 11 |
+
"model_type": "transformer",
|
| 12 |
+
"num_heads": 16,
|
| 13 |
+
"num_hidden_layers": 24,
|
| 14 |
+
"norm_eps": 1e-06,
|
| 15 |
+
"tie_word_embeddings": false,
|
| 16 |
+
"use_cache": true,
|
| 17 |
+
"vocab_size": 32000
|
| 18 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/configs/transformer_7B.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"fuse_cross_entropy": true,
|
| 6 |
+
"fuse_norm": true,
|
| 7 |
+
"hidden_act": "swish",
|
| 8 |
+
"hidden_ratio": 4,
|
| 9 |
+
"hidden_size": 4096,
|
| 10 |
+
"initializer_range": 0.02,
|
| 11 |
+
"intermediate_size": 14336,
|
| 12 |
+
"model_type": "transformer",
|
| 13 |
+
"norm_eps": 1e-06,
|
| 14 |
+
"num_heads": 32,
|
| 15 |
+
"num_hidden_layers": 32,
|
| 16 |
+
"num_kv_heads": 8,
|
| 17 |
+
"rope_theta": 10000.0,
|
| 18 |
+
"tie_word_embeddings": false,
|
| 19 |
+
"use_cache": true,
|
| 20 |
+
"window_size": null
|
| 21 |
+
}
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/download.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datasets import load_dataset
|
| 2 |
+
|
| 3 |
+
# load fineweb-edu with parallel processing
|
| 4 |
+
dataset = load_dataset("Salesforce/wikitext", "wikitext-2-v1", cache_dir="/home/uceeppm/Data")
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__version__ = "0.1.0"
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (166 Bytes). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/__init__.cpython-39.pyc
ADDED
|
Binary file (149 Bytes). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/config_manager.cpython-311.pyc
ADDED
|
Binary file (37.6 kB). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/data.cpython-311.pyc
ADDED
|
Binary file (41.6 kB). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/__pycache__/train.cpython-311.pyc
ADDED
|
Binary file (25 kB). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/__init__.py
ADDED
|
File without changes
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (157 Bytes). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/__pycache__/checkpoint.cpython-311.pyc
ADDED
|
Binary file (3.62 kB). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/components/checkpoint.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, field
|
| 8 |
+
from datetime import timedelta
|
| 9 |
+
from io import BytesIO
|
| 10 |
+
from typing import Any, Dict, List
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch.distributed.checkpoint.stateful import Stateful
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass
|
| 17 |
+
class TrainState(Stateful):
|
| 18 |
+
step: int = 0
|
| 19 |
+
skipped_step: int = 0
|
| 20 |
+
token: int = 0
|
| 21 |
+
elapsed: timedelta = timedelta(0)
|
| 22 |
+
global_avg_losses: List[float] = field(default_factory=list)
|
| 23 |
+
global_max_losses: List[float] = field(default_factory=list)
|
| 24 |
+
log_steps: List[int] = field(default_factory=list)
|
| 25 |
+
|
| 26 |
+
def state_dict(self) -> Dict[str, Any]:
|
| 27 |
+
# Only checkpoint global_avg_losses and global_max_losses per log frequency
|
| 28 |
+
# to avoid sync overhead in every iteration.
|
| 29 |
+
global_avg_losses_bytes = BytesIO()
|
| 30 |
+
torch.save(self.global_avg_losses, global_avg_losses_bytes)
|
| 31 |
+
global_max_losses_bytes = BytesIO()
|
| 32 |
+
torch.save(self.global_max_losses, global_max_losses_bytes)
|
| 33 |
+
log_steps_bytes = BytesIO()
|
| 34 |
+
torch.save(self.log_steps, log_steps_bytes)
|
| 35 |
+
return {
|
| 36 |
+
"step": torch.tensor(self.step, dtype=torch.int32),
|
| 37 |
+
"skipped_step": torch.tensor(self.skipped_step, dtype=torch.int32),
|
| 38 |
+
"token": torch.tensor(self.token, dtype=torch.int64),
|
| 39 |
+
"elapsed": self.elapsed,
|
| 40 |
+
"global_avg_losses": global_avg_losses_bytes,
|
| 41 |
+
"global_max_losses": global_max_losses_bytes,
|
| 42 |
+
"log_steps": log_steps_bytes,
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
def load_state_dict(self, state_dict) -> None:
|
| 46 |
+
self.step = state_dict["step"].item()
|
| 47 |
+
self.skipped_step = state_dict.get("skipped_step", 0).item()
|
| 48 |
+
self.token = state_dict["token"].item()
|
| 49 |
+
self.elapsed = state_dict["elapsed"]
|
| 50 |
+
state_dict["global_avg_losses"].seek(0)
|
| 51 |
+
self.global_avg_losses = torch.load(
|
| 52 |
+
state_dict["global_avg_losses"], weights_only=False
|
| 53 |
+
)
|
| 54 |
+
state_dict["global_max_losses"].seek(0)
|
| 55 |
+
self.global_max_losses = torch.load(
|
| 56 |
+
state_dict["global_max_losses"], weights_only=False
|
| 57 |
+
)
|
| 58 |
+
state_dict["log_steps"].seek(0)
|
| 59 |
+
self.log_steps = torch.load(state_dict["log_steps"], weights_only=False)
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/config_manager.py
ADDED
|
@@ -0,0 +1,911 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
import argparse
|
| 8 |
+
import sys
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from typing import Tuple
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import tomllib
|
| 16 |
+
except ModuleNotFoundError:
|
| 17 |
+
import tomli as tomllib
|
| 18 |
+
|
| 19 |
+
from torchtitan.tools.logging import logger
|
| 20 |
+
|
| 21 |
+
TORCH_DTYPE_MAP = {
|
| 22 |
+
"float16": torch.float16,
|
| 23 |
+
"float32": torch.float32,
|
| 24 |
+
"bfloat16": torch.bfloat16,
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def string_list(raw_arg):
|
| 29 |
+
"""Comma-separated string list argument."""
|
| 30 |
+
return [s.strip() for s in raw_arg.split(",") if s.strip()]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def check_string_list_argument(args_dict: dict[str, any], fullargname: str):
|
| 34 |
+
section, name = fullargname.split(".")
|
| 35 |
+
# Split string list which are still raw strings.
|
| 36 |
+
if (
|
| 37 |
+
section in args_dict
|
| 38 |
+
and name in args_dict[section]
|
| 39 |
+
and isinstance(args_dict[section][name], str)
|
| 40 |
+
):
|
| 41 |
+
sec = args_dict[section]
|
| 42 |
+
sec[name] = string_list(sec[name])
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class JobConfig:
|
| 46 |
+
"""
|
| 47 |
+
A helper class to manage the train configuration.
|
| 48 |
+
Semantics:
|
| 49 |
+
- Default config is loaded from a toml file. If no toml file is provided,
|
| 50 |
+
then the default config is loaded from argparse defaults.
|
| 51 |
+
- if toml file has missing keys, they are filled with argparse defaults.
|
| 52 |
+
- if additional explicit cmd args are provided in addition to the toml
|
| 53 |
+
file, they will override the toml config and the argparse defaults
|
| 54 |
+
|
| 55 |
+
precedence order: cmdline > toml > argparse default
|
| 56 |
+
|
| 57 |
+
Arg parsing semantics:
|
| 58 |
+
|
| 59 |
+
Each argument starts with <prefix>_ which is the section name in the toml file
|
| 60 |
+
followed by name of the option in the toml file. For ex,
|
| 61 |
+
model.name translates to:
|
| 62 |
+
[model]
|
| 63 |
+
name
|
| 64 |
+
in the toml file
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self.args_dict = None
|
| 69 |
+
# main parser
|
| 70 |
+
self.parser = argparse.ArgumentParser(description="torchtitan arg parser.")
|
| 71 |
+
|
| 72 |
+
self.parser.add_argument(
|
| 73 |
+
"--job.config_file",
|
| 74 |
+
type=str,
|
| 75 |
+
default=None,
|
| 76 |
+
help="Job config file",
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# job level configs
|
| 80 |
+
self.parser.add_argument(
|
| 81 |
+
"--job.dump_folder",
|
| 82 |
+
type=str,
|
| 83 |
+
default="./torchtitan/outputs",
|
| 84 |
+
help="Folder to dump job outputs",
|
| 85 |
+
)
|
| 86 |
+
self.parser.add_argument(
|
| 87 |
+
"--job.description",
|
| 88 |
+
type=str,
|
| 89 |
+
default="default job",
|
| 90 |
+
help="Description of the job",
|
| 91 |
+
)
|
| 92 |
+
self.parser.add_argument(
|
| 93 |
+
"--job.use_for_integration_test",
|
| 94 |
+
action="store_true",
|
| 95 |
+
help="Add this config to the integration test suite",
|
| 96 |
+
)
|
| 97 |
+
self.parser.add_argument(
|
| 98 |
+
"--job.print_args",
|
| 99 |
+
action="store_true",
|
| 100 |
+
help="Print the args to terminal",
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# model configs
|
| 104 |
+
self.parser.add_argument(
|
| 105 |
+
"--model.name",
|
| 106 |
+
type=str,
|
| 107 |
+
default="fla",
|
| 108 |
+
help="Which model to train",
|
| 109 |
+
)
|
| 110 |
+
self.parser.add_argument(
|
| 111 |
+
"--model.config",
|
| 112 |
+
type=str,
|
| 113 |
+
default="fla-hub/transformer-1.3B-100B",
|
| 114 |
+
help="Path to the model config",
|
| 115 |
+
)
|
| 116 |
+
self.parser.add_argument(
|
| 117 |
+
"--model.tokenizer_path",
|
| 118 |
+
type=str,
|
| 119 |
+
default="fla-hub/transformer-1.3B-100B",
|
| 120 |
+
help="Tokenizer path",
|
| 121 |
+
)
|
| 122 |
+
self.parser.add_argument(
|
| 123 |
+
"--model.converters",
|
| 124 |
+
type=string_list,
|
| 125 |
+
nargs="+",
|
| 126 |
+
default=[],
|
| 127 |
+
help="""
|
| 128 |
+
Comma separated list of converters to apply to the model.
|
| 129 |
+
For instance, the `float8` converter swaps `torch.nn.Linear`
|
| 130 |
+
with `Float8Linear`. This feature requires you to install 'torchao'
|
| 131 |
+
which can be found here: https://github.com/pytorch/ao
|
| 132 |
+
""",
|
| 133 |
+
)
|
| 134 |
+
self.parser.add_argument(
|
| 135 |
+
"--model.print_after_conversion",
|
| 136 |
+
action="store_true",
|
| 137 |
+
help="""
|
| 138 |
+
If true, model definition will be printed to stdout after all model
|
| 139 |
+
converters have been applied.
|
| 140 |
+
""",
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# profiling configs
|
| 144 |
+
self.parser.add_argument(
|
| 145 |
+
"--profiling.enable_profiling",
|
| 146 |
+
action="store_true",
|
| 147 |
+
help="Whether to enable pytorch profiler",
|
| 148 |
+
)
|
| 149 |
+
self.parser.add_argument(
|
| 150 |
+
"--profiling.save_traces_folder",
|
| 151 |
+
type=str,
|
| 152 |
+
default="profile_traces",
|
| 153 |
+
help="Trace files location",
|
| 154 |
+
)
|
| 155 |
+
self.parser.add_argument(
|
| 156 |
+
"--profiling.profile_freq",
|
| 157 |
+
type=int,
|
| 158 |
+
default=10,
|
| 159 |
+
help="How often to collect profiler traces, in iterations",
|
| 160 |
+
)
|
| 161 |
+
self.parser.add_argument(
|
| 162 |
+
"--profiling.enable_memory_snapshot",
|
| 163 |
+
action="store_true",
|
| 164 |
+
help="Whether to dump memory snapshot",
|
| 165 |
+
)
|
| 166 |
+
self.parser.add_argument(
|
| 167 |
+
"--profiling.save_memory_snapshot_folder",
|
| 168 |
+
type=str,
|
| 169 |
+
default="memory_snapshot",
|
| 170 |
+
help="Memeory snapshot files location",
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# optimizer configs
|
| 174 |
+
self.parser.add_argument(
|
| 175 |
+
"--optimizer.name", type=str, default="AdamW", help="Optimizer to use"
|
| 176 |
+
)
|
| 177 |
+
self.parser.add_argument(
|
| 178 |
+
"--optimizer.eps",
|
| 179 |
+
type=float,
|
| 180 |
+
default=1e-8,
|
| 181 |
+
help="Epsilon value for the optimizer.",
|
| 182 |
+
)
|
| 183 |
+
self.parser.add_argument(
|
| 184 |
+
"--optimizer.lr", type=float, default=8e-4, help="Learning rate to use"
|
| 185 |
+
)
|
| 186 |
+
self.parser.add_argument(
|
| 187 |
+
"--optimizer.implementation",
|
| 188 |
+
type=str,
|
| 189 |
+
default="fused",
|
| 190 |
+
choices=["for-loop", "foreach", "fused"],
|
| 191 |
+
help="""
|
| 192 |
+
Specify which optimizer implementation to use:
|
| 193 |
+
- 'fused': Use fused implementation (CUDA only) for best performance.
|
| 194 |
+
- 'foreach': Use some horizontal fusion of tensors for better performance.
|
| 195 |
+
- 'for-loop': Use the default implementation for the optimizer (slowest).
|
| 196 |
+
- more info: https://pytorch.org/docs/stable/optim.html
|
| 197 |
+
""",
|
| 198 |
+
)
|
| 199 |
+
self.parser.add_argument(
|
| 200 |
+
"--optimizer.early_step_in_backward",
|
| 201 |
+
action="store_true",
|
| 202 |
+
help="""
|
| 203 |
+
Whether to apply optimizer in the backward. Caution, optimizer_in_backward
|
| 204 |
+
is not compatible with gradients clipping, users should not call
|
| 205 |
+
register_post_accumulate_grad_hook after the optimizer is built.""",
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# lr scheduler configs
|
| 209 |
+
self.parser.add_argument(
|
| 210 |
+
"--lr_scheduler.warmup_steps",
|
| 211 |
+
type=int,
|
| 212 |
+
default=200,
|
| 213 |
+
help="Steps for lr scheduler warmup, normally 1/5 of --training.steps",
|
| 214 |
+
)
|
| 215 |
+
self.parser.add_argument(
|
| 216 |
+
"--lr_scheduler.decay_ratio",
|
| 217 |
+
type=float,
|
| 218 |
+
default=None,
|
| 219 |
+
help="""
|
| 220 |
+
Controls the proportion of the training steps allocated to the learning rate decay phase.
|
| 221 |
+
|
| 222 |
+
If `None`, the learning rate will begin decaying immediately after the warmup period.
|
| 223 |
+
Otherwise, the learning rate will remain stable after the warmup period and
|
| 224 |
+
only start decaying during the last `decay_ratio` portion of the total training steps.
|
| 225 |
+
|
| 226 |
+
This is known as the Warmup-Stable-Decay (WSD) schedule, as described in https://arxiv.org/abs/2404.06395.
|
| 227 |
+
""",
|
| 228 |
+
)
|
| 229 |
+
self.parser.add_argument(
|
| 230 |
+
"--lr_scheduler.decay_type",
|
| 231 |
+
type=str,
|
| 232 |
+
default="linear",
|
| 233 |
+
choices=["linear", "sqrt", "cosine"],
|
| 234 |
+
help="""
|
| 235 |
+
Learning rate decay type to use during training:
|
| 236 |
+
- 'linear': linearly decays learning rate from initial to final value
|
| 237 |
+
- 'sqrt': decays learning rate following a 1 minus square root curve
|
| 238 |
+
- 'cosine': smoothly decays learning rate following a cosine curve
|
| 239 |
+
""",
|
| 240 |
+
)
|
| 241 |
+
self.parser.add_argument(
|
| 242 |
+
"--lr_scheduler.lr_min",
|
| 243 |
+
type=float,
|
| 244 |
+
default=0.0,
|
| 245 |
+
help="""
|
| 246 |
+
Min lr ratio for lr scheduler.
|
| 247 |
+
|
| 248 |
+
If provided, the range of decay factor is scaled from 1 to `lr_min`
|
| 249 |
+
to ensure the learning rate does not drop below `optimizer.lr * lr_scheduler.lr_min`.
|
| 250 |
+
""",
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# training configs
|
| 254 |
+
self.parser.add_argument(
|
| 255 |
+
"--training.batch_size", type=int, default=8, help="Batch size"
|
| 256 |
+
)
|
| 257 |
+
self.parser.add_argument(
|
| 258 |
+
"--training.seq_len", type=int, default=2048, help="Sequence length"
|
| 259 |
+
)
|
| 260 |
+
self.parser.add_argument(
|
| 261 |
+
"--training.context_len",
|
| 262 |
+
type=int,
|
| 263 |
+
default=2048,
|
| 264 |
+
help="Max length allowed for each sequence",
|
| 265 |
+
)
|
| 266 |
+
self.parser.add_argument(
|
| 267 |
+
"--training.varlen",
|
| 268 |
+
action="store_true",
|
| 269 |
+
help="Whether to take sequences of variable length as input",
|
| 270 |
+
)
|
| 271 |
+
self.parser.add_argument(
|
| 272 |
+
"--training.gradient_accumulation_steps",
|
| 273 |
+
type=int,
|
| 274 |
+
default=1,
|
| 275 |
+
help="Number of steps to accumulate gradients before updating parameters",
|
| 276 |
+
)
|
| 277 |
+
self.parser.add_argument(
|
| 278 |
+
"--training.steps",
|
| 279 |
+
type=int,
|
| 280 |
+
default=10000,
|
| 281 |
+
help="How many train steps to run",
|
| 282 |
+
)
|
| 283 |
+
self.parser.add_argument(
|
| 284 |
+
"--training.max_norm",
|
| 285 |
+
type=float,
|
| 286 |
+
default=1.0,
|
| 287 |
+
help="Max norm for gradient clipping",
|
| 288 |
+
)
|
| 289 |
+
self.parser.add_argument(
|
| 290 |
+
"--training.skip_nan_inf",
|
| 291 |
+
action="store_true",
|
| 292 |
+
help="Skip batch updates when NaN or INF gradients are encountered during training",
|
| 293 |
+
)
|
| 294 |
+
self.parser.add_argument(
|
| 295 |
+
"--training.dataset",
|
| 296 |
+
default="HuggingFaceFW/fineweb-edu",
|
| 297 |
+
help="Dataset to use, with comma separated values",
|
| 298 |
+
)
|
| 299 |
+
self.parser.add_argument(
|
| 300 |
+
"--training.dataset_name",
|
| 301 |
+
default=None,
|
| 302 |
+
help="The name of the dataset config, with comma separated values if provided",
|
| 303 |
+
)
|
| 304 |
+
self.parser.add_argument(
|
| 305 |
+
"--training.dataset_split",
|
| 306 |
+
default=None,
|
| 307 |
+
help="Dataset split to use, with comma separated values if provided",
|
| 308 |
+
)
|
| 309 |
+
self.parser.add_argument(
|
| 310 |
+
"--training.data_dir",
|
| 311 |
+
default=None,
|
| 312 |
+
help="Data dirs to use, with comma separated values if provided",
|
| 313 |
+
)
|
| 314 |
+
self.parser.add_argument(
|
| 315 |
+
"--training.data_files",
|
| 316 |
+
default=None,
|
| 317 |
+
help="Data files to use, with comma separated values if provided",
|
| 318 |
+
)
|
| 319 |
+
self.parser.add_argument(
|
| 320 |
+
"--training.data_probs",
|
| 321 |
+
default=None,
|
| 322 |
+
help="Data sampling probabilities, with comma separated values if provided",
|
| 323 |
+
)
|
| 324 |
+
self.parser.add_argument(
|
| 325 |
+
"--training.streaming",
|
| 326 |
+
action="store_true",
|
| 327 |
+
help="Whether to load dataset in streaming mode, used for huge dataset",
|
| 328 |
+
)
|
| 329 |
+
self.parser.add_argument(
|
| 330 |
+
"--training.num_workers",
|
| 331 |
+
type=int,
|
| 332 |
+
default=32,
|
| 333 |
+
help="Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process.",
|
| 334 |
+
)
|
| 335 |
+
self.parser.add_argument(
|
| 336 |
+
"--training.prefetch_factor",
|
| 337 |
+
type=int,
|
| 338 |
+
default=2,
|
| 339 |
+
help="Number of batches loaded in advance by each worker."
|
| 340 |
+
"2 means there will be a total of 2 * num_workers batches prefetched across all workers.",
|
| 341 |
+
)
|
| 342 |
+
self.parser.add_argument(
|
| 343 |
+
"--training.data_parallel_replicate_degree",
|
| 344 |
+
type=int,
|
| 345 |
+
default=1,
|
| 346 |
+
help="""
|
| 347 |
+
The `data_parallel_replicate_degree` argument specifies the degree of
|
| 348 |
+
data parallelism for weight replication. When this value is greater
|
| 349 |
+
than 1, weights will be replicated across `data_parallel_replicate_degree`
|
| 350 |
+
ranks. If `data_parallel_shard_degree` is also greater than 1, the parallelism
|
| 351 |
+
method used is HSDP (Hybrid Sharded Data Parallelism). Otherwise, the
|
| 352 |
+
parallelism method used is DDP (Distributed Data Parallelism).
|
| 353 |
+
1 means disabled.""",
|
| 354 |
+
)
|
| 355 |
+
self.parser.add_argument(
|
| 356 |
+
"--training.data_parallel_shard_degree",
|
| 357 |
+
type=int,
|
| 358 |
+
default=-1,
|
| 359 |
+
help="""
|
| 360 |
+
The `data_parallel_shard_degree` argument specifies the degree of data
|
| 361 |
+
parallelism for weight sharding. When this value is greater than 1, weights
|
| 362 |
+
will be sharded across `data_parallel_shard_degree` ranks. If
|
| 363 |
+
`data_parallel_replicate_degree` is also greater than 1, the parallelism
|
| 364 |
+
method used is HSDP (Hybrid Sharded Data Parallelism). Otherwise, the
|
| 365 |
+
parallelism method used is FSDP (Fully Sharded Data Parallelism).
|
| 366 |
+
|
| 367 |
+
-1 means leftover ranks will be used (After DP_REPLICATE/SP/PP). Note that
|
| 368 |
+
only `data_parallel_shard_degree` can be negative. 1 means disabled.""",
|
| 369 |
+
)
|
| 370 |
+
self.parser.add_argument(
|
| 371 |
+
"--training.enable_cpu_offload",
|
| 372 |
+
action="store_true",
|
| 373 |
+
help="""
|
| 374 |
+
Whether to apply CPU offloading of parameters, gradients, and optimizer states in FSDP""",
|
| 375 |
+
)
|
| 376 |
+
self.parser.add_argument(
|
| 377 |
+
"--training.tensor_parallel_degree",
|
| 378 |
+
type=int,
|
| 379 |
+
default=1,
|
| 380 |
+
help="Tensor Parallelism degree. 1 means disabled.",
|
| 381 |
+
)
|
| 382 |
+
self.parser.add_argument(
|
| 383 |
+
"--training.disable_loss_parallel",
|
| 384 |
+
action="store_true",
|
| 385 |
+
help="Whether to apply loss parallel when sequence parallel is enabled",
|
| 386 |
+
)
|
| 387 |
+
self.parser.add_argument(
|
| 388 |
+
"--training.fsdp_reshard_after_forward",
|
| 389 |
+
type=str,
|
| 390 |
+
default="default",
|
| 391 |
+
choices=["default", "always", "never"],
|
| 392 |
+
help="""
|
| 393 |
+
`reshard_after_forward` specifies the policy for applying `reshard_after_forward`
|
| 394 |
+
within an FSDP setup. `reshard_after_forward` controls parameter behavior after forward,
|
| 395 |
+
trading off memory and communication. See torch's `fully_shard` API for more documentation
|
| 396 |
+
on `reshard_after_forward`.
|
| 397 |
+
The supported policies include "default", "always" and "never":
|
| 398 |
+
- "default" applies default resharding behavior, implementing "smart defaults" for known optimal
|
| 399 |
+
scenarios.
|
| 400 |
+
- "always" will enable `reshard_after_forward` for all forward passes.
|
| 401 |
+
- "never" will disable `reshard_after_forward` for all forward passes.
|
| 402 |
+
""",
|
| 403 |
+
)
|
| 404 |
+
self.parser.add_argument(
|
| 405 |
+
"--training.mixed_precision_param",
|
| 406 |
+
type=str,
|
| 407 |
+
default="bfloat16",
|
| 408 |
+
choices=["bfloat16", "float32"],
|
| 409 |
+
help="""
|
| 410 |
+
torch dtype to use for parameters when applying mixed precision via FSDP.
|
| 411 |
+
This feature only takes effect when data_parallel_shard_degree > 1
|
| 412 |
+
""",
|
| 413 |
+
)
|
| 414 |
+
self.parser.add_argument(
|
| 415 |
+
"--training.mixed_precision_reduce",
|
| 416 |
+
type=str,
|
| 417 |
+
default="float32",
|
| 418 |
+
choices=["float32"],
|
| 419 |
+
help="""
|
| 420 |
+
torch dtype to use for reductions when applying mixed precision via FSDP.
|
| 421 |
+
This feature only takes effect when data_parallel_shard_degree > 1
|
| 422 |
+
""",
|
| 423 |
+
)
|
| 424 |
+
self.parser.add_argument(
|
| 425 |
+
"--training.compile",
|
| 426 |
+
action="store_true",
|
| 427 |
+
help="Whether to compile the model",
|
| 428 |
+
)
|
| 429 |
+
self.parser.add_argument(
|
| 430 |
+
"--training.gc_freq",
|
| 431 |
+
type=int,
|
| 432 |
+
default=50,
|
| 433 |
+
help="Python garbage control scheduling interval, in steps",
|
| 434 |
+
)
|
| 435 |
+
self.parser.add_argument(
|
| 436 |
+
"--training.seed",
|
| 437 |
+
type=int,
|
| 438 |
+
default=42,
|
| 439 |
+
help="Choose the base RNG seed used for training",
|
| 440 |
+
)
|
| 441 |
+
self.parser.add_argument(
|
| 442 |
+
"--training.deterministic",
|
| 443 |
+
action="store_true",
|
| 444 |
+
help="Use deterministic algorithms wherever possible, may be slower",
|
| 445 |
+
)
|
| 446 |
+
# metrics configs
|
| 447 |
+
self.parser.add_argument(
|
| 448 |
+
"--metrics.log_freq",
|
| 449 |
+
type=int,
|
| 450 |
+
default=10,
|
| 451 |
+
help="How often to log metrics to TensorBoard, in iterations",
|
| 452 |
+
)
|
| 453 |
+
self.parser.add_argument(
|
| 454 |
+
"--metrics.enable_tensorboard",
|
| 455 |
+
action="store_true",
|
| 456 |
+
help="Whether to log metrics to TensorBoard",
|
| 457 |
+
)
|
| 458 |
+
self.parser.add_argument(
|
| 459 |
+
"--metrics.disable_color_printing",
|
| 460 |
+
action="store_true",
|
| 461 |
+
help="Whether to disable color printing in logs",
|
| 462 |
+
)
|
| 463 |
+
self.parser.add_argument(
|
| 464 |
+
"--metrics.save_tb_folder",
|
| 465 |
+
type=str,
|
| 466 |
+
default="tb",
|
| 467 |
+
help="Folder to dump TensorBoard states",
|
| 468 |
+
)
|
| 469 |
+
self.parser.add_argument(
|
| 470 |
+
"--metrics.save_for_all_ranks",
|
| 471 |
+
action="store_true",
|
| 472 |
+
default=False,
|
| 473 |
+
help="""
|
| 474 |
+
Whether to save TensorBoard/Wandb metrics only for rank 0 or for all ranks.
|
| 475 |
+
When this option is False and pipeline_parallel_degree is > 1, the metrics
|
| 476 |
+
component uses the 0th rank of the last stage pipeline group, which is the
|
| 477 |
+
only stage that computes loss metrics.
|
| 478 |
+
""",
|
| 479 |
+
)
|
| 480 |
+
self.parser.add_argument(
|
| 481 |
+
"--metrics.enable_wandb",
|
| 482 |
+
action="store_true",
|
| 483 |
+
help="Whether to log metrics to Weights & Biases",
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
self.parser.add_argument(
|
| 487 |
+
"--experimental.enable_async_tensor_parallel",
|
| 488 |
+
action="store_true",
|
| 489 |
+
help="Whether to apply async tensor parallel (currently only effective when compile is enabled)",
|
| 490 |
+
)
|
| 491 |
+
self.parser.add_argument(
|
| 492 |
+
"--experimental.pipeline_parallel_degree",
|
| 493 |
+
type=int,
|
| 494 |
+
default=1,
|
| 495 |
+
help="""
|
| 496 |
+
Pipeline Parallelism degree, or number of ranks. 1 means disabled.
|
| 497 |
+
If using looped schedules, this still specifies the number of physical ranks, not the number
|
| 498 |
+
of stages. Stages per rank are inferred from split points degree, and schedule.""",
|
| 499 |
+
)
|
| 500 |
+
self.parser.add_argument(
|
| 501 |
+
"--experimental.pipeline_parallel_split_points",
|
| 502 |
+
type=string_list,
|
| 503 |
+
nargs="+",
|
| 504 |
+
default=[],
|
| 505 |
+
help="""
|
| 506 |
+
Specify comma-separated names of modules to use as the beginning of a split point.
|
| 507 |
+
|
| 508 |
+
e.g. "layers.0,layers.2" will cause the model to be split into 3 stages,
|
| 509 |
+
the first containing all the layers up to layers.0,
|
| 510 |
+
the second containing layers.0 and up to layers.2,
|
| 511 |
+
the third containing layers.2 and all the remaining layers.
|
| 512 |
+
|
| 513 |
+
Note: fully-automated splitting may be enabled in the future,
|
| 514 |
+
but currently the split points must be specified manually.""",
|
| 515 |
+
)
|
| 516 |
+
self.parser.add_argument(
|
| 517 |
+
"--experimental.pipeline_parallel_schedule",
|
| 518 |
+
type=str,
|
| 519 |
+
default="1F1B",
|
| 520 |
+
help="""
|
| 521 |
+
Specify the Pipeline Parallel schedule to use. The supported schedules are:
|
| 522 |
+
https://github.com/pytorch/pytorch/blob/de4c2a3b4e89d96334dc678d1c3f2ae51a6630a0/torch/distributed/pipelining/schedules.py#L2161.
|
| 523 |
+
The schedule must be compatible with the split points and stages_per_rank.
|
| 524 |
+
|
| 525 |
+
Looped schedules (e.g. Interleaved1F1B) require specifying pipeline_parallel_degree = number of ranks,
|
| 526 |
+
and split_points = number of stages - 1
|
| 527 |
+
""",
|
| 528 |
+
)
|
| 529 |
+
self.parser.add_argument(
|
| 530 |
+
"--experimental.pipeline_parallel_schedule_csv",
|
| 531 |
+
type=str,
|
| 532 |
+
default="",
|
| 533 |
+
help="""
|
| 534 |
+
Specify the path to the pipeline parallel schedule csv file to use.
|
| 535 |
+
The pipeline_parallel_schedule argument must be either
|
| 536 |
+
PipelineScheduleSingle, PipelineScheduleMulti, or _PipelineScheduleRuntime.
|
| 537 |
+
""",
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
self.parser.add_argument(
|
| 541 |
+
"--experimental.pipeline_parallel_microbatches",
|
| 542 |
+
type=int,
|
| 543 |
+
default=None,
|
| 544 |
+
help="""
|
| 545 |
+
How many microbatches to split the global training batch into when using pipeline parallelism.
|
| 546 |
+
|
| 547 |
+
The global training batch size must be evenly divisible by the number of microbatches.
|
| 548 |
+
|
| 549 |
+
The default value will be the number of pipeline stages, if unspecified.
|
| 550 |
+
""",
|
| 551 |
+
)
|
| 552 |
+
self.parser.add_argument(
|
| 553 |
+
"--experimental.enable_compiled_autograd",
|
| 554 |
+
action="store_true",
|
| 555 |
+
help="Enable CompiledAutograd to compile the backward.",
|
| 556 |
+
)
|
| 557 |
+
self.parser.add_argument(
|
| 558 |
+
"--experimental.context_parallel_degree",
|
| 559 |
+
type=int,
|
| 560 |
+
default=1,
|
| 561 |
+
help="Context parallelism degree. 1 means disabled.",
|
| 562 |
+
)
|
| 563 |
+
self.parser.add_argument(
|
| 564 |
+
"--experimental.context_parallel_rotate_method",
|
| 565 |
+
type=str,
|
| 566 |
+
default="allgather",
|
| 567 |
+
help="""
|
| 568 |
+
The collective to use in context parallel SDPA for kv shards exchange.
|
| 569 |
+
|
| 570 |
+
'allgather' means to all-gather all kv shards on ranks after the first sub-SDPA computation,
|
| 571 |
+
|
| 572 |
+
'alltoall' means to all-to-all shuffle the kv shards.
|
| 573 |
+
|
| 574 |
+
The default value is 'allgather'.
|
| 575 |
+
""",
|
| 576 |
+
)
|
| 577 |
+
# I'm not particularly fond of this. Users can choose to write their own wrapper
|
| 578 |
+
# module and import TorchTitan training loop and execute it, which look cleaner.
|
| 579 |
+
# One reason to provide this option is to allow users to use the existing run script.
|
| 580 |
+
# While the script is pretty trivial now, we may add more logic when integrating
|
| 581 |
+
# with TorchFT.
|
| 582 |
+
# This option is subject to change and may be deleted in the future.
|
| 583 |
+
self.parser.add_argument(
|
| 584 |
+
"--experimental.custom_model_path",
|
| 585 |
+
type=str,
|
| 586 |
+
default="",
|
| 587 |
+
help="""
|
| 588 |
+
The --custom_model_path option allows to specify a custom path to a model module
|
| 589 |
+
that is not natively implemented within TorchTitan.
|
| 590 |
+
Acceptable values are the file system path to the module (e.g., my_models/model_x)
|
| 591 |
+
dotted import module (e.g., some_package.model_x).
|
| 592 |
+
""",
|
| 593 |
+
)
|
| 594 |
+
# checkpointing configs
|
| 595 |
+
self.parser.add_argument(
|
| 596 |
+
"--checkpoint.enable_checkpoint",
|
| 597 |
+
action="store_true",
|
| 598 |
+
help="Whether to enable checkpoint",
|
| 599 |
+
)
|
| 600 |
+
self.parser.add_argument(
|
| 601 |
+
"--checkpoint.folder",
|
| 602 |
+
type=str,
|
| 603 |
+
default="checkpoint",
|
| 604 |
+
help="""
|
| 605 |
+
The folder to store the checkpoints.
|
| 606 |
+
When enable_checkpoint is set to true, checkpoints will be in {--job.dump_folder}/{--checkpoint.folder}.
|
| 607 |
+
""",
|
| 608 |
+
)
|
| 609 |
+
self.parser.add_argument(
|
| 610 |
+
"--checkpoint.interval",
|
| 611 |
+
type=int,
|
| 612 |
+
default=500,
|
| 613 |
+
help="Checkpointing interval in steps.",
|
| 614 |
+
)
|
| 615 |
+
self.parser.add_argument(
|
| 616 |
+
"--checkpoint.model_weights_only",
|
| 617 |
+
action="store_true",
|
| 618 |
+
help="""
|
| 619 |
+
When model_weights_only=True, only model weights will be saved at the end of training.
|
| 620 |
+
With this, checkpoints can be loaded using `torch.load(..., weights_only=True)` after conversion.
|
| 621 |
+
When model_weights_only=False, the full checkpoint will be saved.
|
| 622 |
+
A full checkpoint includes model, optimizer and train_state, which can be used to resume training.
|
| 623 |
+
The default value is false.
|
| 624 |
+
""",
|
| 625 |
+
)
|
| 626 |
+
self.parser.add_argument(
|
| 627 |
+
"--checkpoint.export_dtype",
|
| 628 |
+
type=str,
|
| 629 |
+
default="float32",
|
| 630 |
+
choices=["float16", "bfloat16", "float32"],
|
| 631 |
+
help="""
|
| 632 |
+
Converts to the specified precision when training completes and model_weights_only=true.
|
| 633 |
+
Currently supports float32, float16, and bfloat16.
|
| 634 |
+
The default value is float32.
|
| 635 |
+
""",
|
| 636 |
+
)
|
| 637 |
+
self.parser.add_argument(
|
| 638 |
+
"--checkpoint.create_seed_checkpoint",
|
| 639 |
+
action="store_true",
|
| 640 |
+
help="""
|
| 641 |
+
Initializes the full model without applying parallelisms, and then saves it as a seed checkpoint.
|
| 642 |
+
Note: requires user to call train.py without specifying any parallelisms, e.g. NGPU=1.
|
| 643 |
+
Could be implemented as a separate script, but this way shares more code.
|
| 644 |
+
""",
|
| 645 |
+
)
|
| 646 |
+
self.parser.add_argument(
|
| 647 |
+
"--checkpoint.async_mode",
|
| 648 |
+
type=str,
|
| 649 |
+
default="disabled",
|
| 650 |
+
help="""
|
| 651 |
+
Which async checkpoint mode to use. Currently there are 3 different modes.
|
| 652 |
+
1. "disabled": synchronized checkpointing will be used.
|
| 653 |
+
2. "async": torch.distributed.checkpoint.async_save will be used.
|
| 654 |
+
3. "async_with_pinned_mem": this option utilizes a dedicated pinned memory
|
| 655 |
+
space and creates a separate process for faster GPU->CPU transfer
|
| 656 |
+
performance and eliminating GIL contention. The cost is increased CPU
|
| 657 |
+
memory usage. If insufficient CPU memory is available, performance may
|
| 658 |
+
degrade due to memory paging. For most users, "async" should suffice as
|
| 659 |
+
the performance overhead is typically small (on the order of tens of
|
| 660 |
+
seconds) compared to checkpointing frequency. This mode can be employed
|
| 661 |
+
to pursue near-zero checkpointing times (e.g., < 1 second) given
|
| 662 |
+
appropriate hardware support such as ample CPU memory and fast PCIe.
|
| 663 |
+
|
| 664 |
+
"disabled" is the default mode.
|
| 665 |
+
""",
|
| 666 |
+
)
|
| 667 |
+
self.parser.add_argument(
|
| 668 |
+
"--checkpoint.keep_latest_k",
|
| 669 |
+
type=int,
|
| 670 |
+
default=0,
|
| 671 |
+
help="""
|
| 672 |
+
Keeps only the latest k checkpoints, and purging older ones. If 0, keep all checkpoints.
|
| 673 |
+
0 is the default value. k cannot be 1 as the last one may be in the process of being
|
| 674 |
+
saved. As a result, the metadata of the last one may not be ready yet.
|
| 675 |
+
""",
|
| 676 |
+
)
|
| 677 |
+
self.parser.add_argument(
|
| 678 |
+
"--checkpoint.load_step",
|
| 679 |
+
type=int,
|
| 680 |
+
default=-1,
|
| 681 |
+
help="Load the checkpoint at the specified step. If -1, load the latest checkpoint.",
|
| 682 |
+
)
|
| 683 |
+
self.parser.add_argument(
|
| 684 |
+
"--checkpoint.exclude_from_loading",
|
| 685 |
+
type=string_list,
|
| 686 |
+
nargs="*",
|
| 687 |
+
default=[],
|
| 688 |
+
help="""
|
| 689 |
+
Exclude specific keys from being loaded from the checkpoint.
|
| 690 |
+
Provide a comma-separated list of keys to exclude, e.g. 'optimizer,lr_scheduler,dataloader'.
|
| 691 |
+
This will load the model only, excluding the specified keys.
|
| 692 |
+
""",
|
| 693 |
+
)
|
| 694 |
+
# activation checkpointing configs
|
| 695 |
+
self.parser.add_argument(
|
| 696 |
+
"--activation_checkpoint.mode",
|
| 697 |
+
type=str,
|
| 698 |
+
default="selective",
|
| 699 |
+
help="Type of activation checkpointing to use ['none', 'full', 'selective']",
|
| 700 |
+
)
|
| 701 |
+
self.parser.add_argument(
|
| 702 |
+
"--activation_checkpoint.selective_ac_option",
|
| 703 |
+
type=str,
|
| 704 |
+
default="2", # 2 = checkpoint every other layer
|
| 705 |
+
help="""
|
| 706 |
+
Selective activation checkpointing options ['int', 'op'].
|
| 707 |
+
'int' (e.g., 2) for every nth layer, or 'op' for op level ac.
|
| 708 |
+
""",
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
self.parser.add_argument(
|
| 712 |
+
"--activation_offload.mode",
|
| 713 |
+
type=str,
|
| 714 |
+
default="none",
|
| 715 |
+
help="""
|
| 716 |
+
if we are using activation offload or not. Options are ['none', 'full'].
|
| 717 |
+
""",
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
# float8 configs
|
| 721 |
+
self.parser.add_argument(
|
| 722 |
+
"--float8.enable_fsdp_float8_all_gather",
|
| 723 |
+
action="store_true",
|
| 724 |
+
help="Whether enable float8 all-gather in FSDP, recommended for tensorwise scaling",
|
| 725 |
+
)
|
| 726 |
+
self.parser.add_argument(
|
| 727 |
+
"--float8.precompute_float8_dynamic_scale_for_fsdp",
|
| 728 |
+
action="store_true",
|
| 729 |
+
help="Whether precompute float8 scales dynamically for FSDP, recommended for tensorwise scaling",
|
| 730 |
+
)
|
| 731 |
+
self.parser.add_argument(
|
| 732 |
+
"--float8.force_recompute_fp8_weight_in_bwd",
|
| 733 |
+
action="store_true",
|
| 734 |
+
help="""
|
| 735 |
+
Whether to force the recomputation of FP8 weights during backward pass.
|
| 736 |
+
When using FSDP with tensorwise scaling, it is recommended to enable
|
| 737 |
+
`force_recompute_fp8_weight_in_bwd` to prevent saving unsharded FP8 weights
|
| 738 |
+
for backward computation.
|
| 739 |
+
""",
|
| 740 |
+
)
|
| 741 |
+
self.parser.add_argument(
|
| 742 |
+
"--float8.recipe_name",
|
| 743 |
+
type=str,
|
| 744 |
+
default=None,
|
| 745 |
+
choices=["tensorwise", "rowwise", "rowwise_with_gw_hp"],
|
| 746 |
+
help="""
|
| 747 |
+
If specified, creates float8 config from recipe name, valid choices are
|
| 748 |
+
`tensorwise`, `rowwise` and `rowwise_with_gw_hp`.
|
| 749 |
+
""",
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
# communications library settings
|
| 753 |
+
self.parser.add_argument(
|
| 754 |
+
"--comm.init_timeout_seconds",
|
| 755 |
+
type=int,
|
| 756 |
+
default=300,
|
| 757 |
+
help="Timeout for communication operations, during initialization and first train step.",
|
| 758 |
+
)
|
| 759 |
+
self.parser.add_argument(
|
| 760 |
+
"--comm.train_timeout_seconds",
|
| 761 |
+
type=int,
|
| 762 |
+
default=100,
|
| 763 |
+
help=(
|
| 764 |
+
"Timeout for communication operations after the first train step -- "
|
| 765 |
+
"usually a tighter bound than during initialization."
|
| 766 |
+
),
|
| 767 |
+
)
|
| 768 |
+
self.parser.add_argument(
|
| 769 |
+
"--comm.trace_buf_size",
|
| 770 |
+
type=int,
|
| 771 |
+
default=20000,
|
| 772 |
+
help="Flight recorder ring buffer size, >0 means recording by default, 0 means disabled",
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
# memory estimation settings
|
| 776 |
+
self.parser.add_argument(
|
| 777 |
+
"--memory_estimation.enabled",
|
| 778 |
+
help="Whether to estimate memory usage for FSDP",
|
| 779 |
+
action="store_true",
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
self.parser.add_argument(
|
| 783 |
+
"--memory_estimation.disable_fake_mode",
|
| 784 |
+
help="Whether to estimate memory under FakeTensorMode",
|
| 785 |
+
action="store_true",
|
| 786 |
+
)
|
| 787 |
+
|
| 788 |
+
self.parser.add_argument(
|
| 789 |
+
"--fault_tolerance.enable",
|
| 790 |
+
action="store_true",
|
| 791 |
+
help="""
|
| 792 |
+
Enable TorchFT integration. When TorchFT is enabled, HSDP will be used.
|
| 793 |
+
And --fault_tolerance.data_parallel_replicate_degree should be 1 and
|
| 794 |
+
--fault_tolerance.group_size will be used to control the maximum
|
| 795 |
+
replicate group size as the replicate group size is dynamic.
|
| 796 |
+
|
| 797 |
+
Note that this is still an experimental feature.
|
| 798 |
+
""",
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
self.parser.add_argument(
|
| 802 |
+
"--fault_tolerance.replica_id",
|
| 803 |
+
type=int,
|
| 804 |
+
default=0,
|
| 805 |
+
help="The TorchFT replica ID of this run.",
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
self.parser.add_argument(
|
| 809 |
+
"--fault_tolerance.group_size",
|
| 810 |
+
type=int,
|
| 811 |
+
default=0,
|
| 812 |
+
help="""
|
| 813 |
+
The number of TorchFT replicate groups. This number will be used for
|
| 814 |
+
dataloader to split the dataset across the replicate groups and FSDP
|
| 815 |
+
dimension
|
| 816 |
+
""",
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
self.parser.add_argument(
|
| 820 |
+
"--fault_tolerance.min_replica_size",
|
| 821 |
+
type=int,
|
| 822 |
+
default=1,
|
| 823 |
+
help="The minimum number of FT replica for each step.",
|
| 824 |
+
)
|
| 825 |
+
|
| 826 |
+
def to_dict(self):
|
| 827 |
+
return self.args_dict
|
| 828 |
+
|
| 829 |
+
def parse_args(self, args_list: list = sys.argv[1:]):
|
| 830 |
+
args, cmd_args = self.parse_args_from_command_line(args_list)
|
| 831 |
+
config_file = getattr(args, "job.config_file", None)
|
| 832 |
+
# build up a two level dict
|
| 833 |
+
args_dict = self._args_to_two_level_dict(args)
|
| 834 |
+
if config_file is not None:
|
| 835 |
+
try:
|
| 836 |
+
with open(config_file, "rb") as f:
|
| 837 |
+
for k, v in tomllib.load(f).items():
|
| 838 |
+
# to prevent overwrite of non-specified keys
|
| 839 |
+
args_dict[k] |= v
|
| 840 |
+
except (FileNotFoundError, tomllib.TOMLDecodeError) as e:
|
| 841 |
+
logger.exception(
|
| 842 |
+
f"Error while loading the configuration file: {config_file}"
|
| 843 |
+
)
|
| 844 |
+
logger.exception(f"Error details: {str(e)}")
|
| 845 |
+
raise e
|
| 846 |
+
|
| 847 |
+
# Checking string-list arguments are properly split into a list
|
| 848 |
+
# if split-points came from 'args' (from cmd line) it would have already been parsed into a list by that parser
|
| 849 |
+
string_list_argnames = self._get_string_list_argument_names()
|
| 850 |
+
for n in string_list_argnames:
|
| 851 |
+
check_string_list_argument(args_dict, n)
|
| 852 |
+
|
| 853 |
+
# override args dict with cmd_args
|
| 854 |
+
cmd_args_dict = self._args_to_two_level_dict(cmd_args)
|
| 855 |
+
for section, section_args in cmd_args_dict.items():
|
| 856 |
+
for k, v in section_args.items():
|
| 857 |
+
args_dict[section][k] = v
|
| 858 |
+
|
| 859 |
+
self.args_dict = args_dict
|
| 860 |
+
|
| 861 |
+
for k, v in args_dict.items():
|
| 862 |
+
class_type = type(k.title(), (), v)
|
| 863 |
+
setattr(self, k, class_type())
|
| 864 |
+
self._validate_config()
|
| 865 |
+
|
| 866 |
+
def _args_to_two_level_dict(self, args: argparse.Namespace) -> defaultdict:
|
| 867 |
+
args_dict = defaultdict(defaultdict)
|
| 868 |
+
for k, v in vars(args).items():
|
| 869 |
+
first_level_key, second_level_key = k.split(".", 1)
|
| 870 |
+
args_dict[first_level_key][second_level_key] = v
|
| 871 |
+
return args_dict
|
| 872 |
+
|
| 873 |
+
def _validate_config(self) -> None:
|
| 874 |
+
# TODO: Add more mandatory validations
|
| 875 |
+
assert self.model.config
|
| 876 |
+
assert self.model.tokenizer_path
|
| 877 |
+
|
| 878 |
+
def _get_string_list_argument_names(self) -> list[str]:
|
| 879 |
+
"""Get the parser argument names of type `string_list`."""
|
| 880 |
+
string_list_args = [
|
| 881 |
+
v.dest for v in self.parser._actions if v.type is string_list
|
| 882 |
+
]
|
| 883 |
+
return string_list_args
|
| 884 |
+
|
| 885 |
+
def parse_args_from_command_line(
|
| 886 |
+
self, args_list
|
| 887 |
+
) -> Tuple[argparse.Namespace, argparse.Namespace]:
|
| 888 |
+
"""
|
| 889 |
+
Parse command line arguments and return the parsed args and the command line only args
|
| 890 |
+
"""
|
| 891 |
+
args = self.parser.parse_args(args_list)
|
| 892 |
+
string_list_argnames = set(self._get_string_list_argument_names())
|
| 893 |
+
|
| 894 |
+
# aux parser to parse the command line only args, with no defaults from main parser
|
| 895 |
+
aux_parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
|
| 896 |
+
for arg, val in vars(args).items():
|
| 897 |
+
if isinstance(val, bool):
|
| 898 |
+
aux_parser.add_argument(
|
| 899 |
+
"--" + arg, action="store_true" if val else "store_false"
|
| 900 |
+
)
|
| 901 |
+
elif arg in string_list_argnames:
|
| 902 |
+
# without this special case, type inference breaks here,
|
| 903 |
+
# since the inferred type is just 'list' and it ends up flattening
|
| 904 |
+
# e.g. from ["layers.0", "layers.1"] into ["l", "a", "y", "e", "r", "s", ".0", ...]
|
| 905 |
+
aux_parser.add_argument("--" + arg, type=string_list)
|
| 906 |
+
else:
|
| 907 |
+
aux_parser.add_argument("--" + arg, type=type(val))
|
| 908 |
+
|
| 909 |
+
cmd_args, _ = aux_parser.parse_known_args(args_list)
|
| 910 |
+
|
| 911 |
+
return args, cmd_args
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/data.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import pickle
|
| 7 |
+
from copy import deepcopy
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Union
|
| 10 |
+
|
| 11 |
+
import datasets
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from datasets import Dataset, IterableDataset, interleave_datasets, load_dataset
|
| 15 |
+
from datasets.iterable_dataset import ShufflingConfig
|
| 16 |
+
from torch.distributed.checkpoint.stateful import Stateful
|
| 17 |
+
from torchdata.stateful_dataloader import StatefulDataLoader
|
| 18 |
+
from transformers import PreTrainedTokenizer
|
| 19 |
+
|
| 20 |
+
from torchtitan.tools import utils
|
| 21 |
+
from torchtitan.tools.logging import logger
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class BufferShuffledIterableDataset(IterableDataset):
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
dataset: Dataset,
|
| 28 |
+
tokenizer: PreTrainedTokenizer,
|
| 29 |
+
seq_len: int = 2048,
|
| 30 |
+
rank: int = 0,
|
| 31 |
+
world_size: int = 1,
|
| 32 |
+
buffer_size: int = 1024,
|
| 33 |
+
) -> BufferShuffledIterableDataset:
|
| 34 |
+
self.dataset = dataset
|
| 35 |
+
self.tokenizer = tokenizer
|
| 36 |
+
|
| 37 |
+
self.data = dataset.shard(world_size, rank)
|
| 38 |
+
self.seq_len = seq_len
|
| 39 |
+
|
| 40 |
+
self.rank = rank
|
| 41 |
+
self.world_size = world_size
|
| 42 |
+
self.buffer_size = buffer_size
|
| 43 |
+
|
| 44 |
+
if tokenizer.vocab_size < torch.iinfo(torch.uint16).max:
|
| 45 |
+
self.dtype = torch.uint16
|
| 46 |
+
elif tokenizer.vocab_size < torch.iinfo(torch.uint32).max:
|
| 47 |
+
self.dtype = torch.uint32
|
| 48 |
+
else:
|
| 49 |
+
self.dtype = torch.uint64
|
| 50 |
+
self.states = None
|
| 51 |
+
self.buffer = torch.tensor([], dtype=self.dtype)
|
| 52 |
+
self.tokens = []
|
| 53 |
+
self.rand_id = 0
|
| 54 |
+
self.token_id = 0
|
| 55 |
+
self.rng_state = None
|
| 56 |
+
self._epoch = 0
|
| 57 |
+
|
| 58 |
+
def __iter__(self):
|
| 59 |
+
g = torch.Generator()
|
| 60 |
+
g.manual_seed(self._epoch + self.rank)
|
| 61 |
+
if self.rng_state is not None:
|
| 62 |
+
g.set_state(self.rng_state)
|
| 63 |
+
|
| 64 |
+
rand_it = self.randint(0, self.buffer_size, g=g)
|
| 65 |
+
if self.states is not None:
|
| 66 |
+
self.data.load_state_dict(self.states)
|
| 67 |
+
|
| 68 |
+
# max number of tokens allowed in the chunk buffer
|
| 69 |
+
n_tokens = self.buffer_size * self.seq_len
|
| 70 |
+
|
| 71 |
+
while True:
|
| 72 |
+
for sample in self.tokenize(self.data):
|
| 73 |
+
# keep appending the samples to the token buffer
|
| 74 |
+
self.tokens += sample
|
| 75 |
+
# if the token buffer is full, start sampling
|
| 76 |
+
# NOTE: we first convert the token ids to a tensor of shape [n_chunks, seq_len] for efficiency
|
| 77 |
+
if len(self.buffer) == 0 and len(self.tokens) >= n_tokens:
|
| 78 |
+
self.buffer = torch.tensor(self.tokens[:n_tokens], dtype=self.dtype).view(self.buffer_size, -1)
|
| 79 |
+
self.tokens = self.tokens[n_tokens:]
|
| 80 |
+
if len(self.buffer) == self.buffer_size:
|
| 81 |
+
yield from self.sample(rand_it)
|
| 82 |
+
|
| 83 |
+
n_chunks = len(self.tokens) // self.seq_len
|
| 84 |
+
# handle the left tokens in the buffer
|
| 85 |
+
if n_chunks > 0:
|
| 86 |
+
n_tokens = n_chunks * self.seq_len
|
| 87 |
+
indices = torch.randperm(n_chunks, generator=g).tolist()
|
| 88 |
+
self.buffer = torch.tensor(self.tokens[:n_tokens], dtype=torch.long).view(n_chunks, -1)
|
| 89 |
+
self.tokens = self.tokens[n_tokens:]
|
| 90 |
+
for i in indices:
|
| 91 |
+
yield {'input_ids': self.buffer[i]}
|
| 92 |
+
|
| 93 |
+
def tokenize(self, data, batch_size: int = 64):
|
| 94 |
+
texts, states = [], []
|
| 95 |
+
for sample in data:
|
| 96 |
+
texts.append(sample['text'])
|
| 97 |
+
states.append(self.data.state_dict())
|
| 98 |
+
if len(texts) == batch_size:
|
| 99 |
+
for s, tokenized in zip(states, self.tokenizer(texts, return_attention_mask=False)['input_ids']):
|
| 100 |
+
self.states = s
|
| 101 |
+
yield tokenized
|
| 102 |
+
texts, states = [], []
|
| 103 |
+
if len(texts) > 0:
|
| 104 |
+
for s, tokenized in zip(states, self.tokenizer(texts, return_attention_mask=False)['input_ids']):
|
| 105 |
+
self.states = s
|
| 106 |
+
yield tokenized
|
| 107 |
+
|
| 108 |
+
def sample(self, indices):
|
| 109 |
+
n_tokens = (len(self.tokens) // self.seq_len) * self.seq_len
|
| 110 |
+
while self.token_id < n_tokens:
|
| 111 |
+
i = next(indices)
|
| 112 |
+
start, end = self.token_id, self.token_id + self.seq_len
|
| 113 |
+
self.token_id += self.seq_len
|
| 114 |
+
yield {'input_ids': self.buffer[i].to(torch.long)}
|
| 115 |
+
self.buffer[i] = torch.tensor(self.tokens[start:end], dtype=self.dtype)
|
| 116 |
+
self.token_id = 0
|
| 117 |
+
self.tokens = self.tokens[n_tokens:]
|
| 118 |
+
|
| 119 |
+
def randint(self, low: int, high: int, buffer_size: int = 1024, g: torch.Generator = torch.Generator()) -> Iterable[int]:
|
| 120 |
+
indices = torch.empty(buffer_size, dtype=torch.long)
|
| 121 |
+
while True:
|
| 122 |
+
# record the generator states before sampling
|
| 123 |
+
self.rng_state = g.get_state()
|
| 124 |
+
indices = torch.randint(low, high, (buffer_size,), out=indices, generator=g)
|
| 125 |
+
for i in indices[self.rand_id:].tolist():
|
| 126 |
+
self.rand_id += 1
|
| 127 |
+
yield i
|
| 128 |
+
self.rand_id = 0
|
| 129 |
+
|
| 130 |
+
def set_epoch(self, epoch):
|
| 131 |
+
self._epoch = epoch
|
| 132 |
+
if hasattr(self.dataset, 'set_epoch'):
|
| 133 |
+
self.dataset.set_epoch(epoch)
|
| 134 |
+
|
| 135 |
+
def state_dict(self):
|
| 136 |
+
return {
|
| 137 |
+
'states': self.states,
|
| 138 |
+
'buffer': self.buffer.clone(),
|
| 139 |
+
'tokens': deepcopy(self.tokens),
|
| 140 |
+
'rand_id': self.rand_id,
|
| 141 |
+
'token_id': self.token_id,
|
| 142 |
+
'rng_state': self.rng_state,
|
| 143 |
+
'epoch': self._epoch,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
def load_state_dict(self, state_dict):
|
| 147 |
+
self.states = state_dict['states']
|
| 148 |
+
self.buffer = state_dict['buffer'].clone()
|
| 149 |
+
self.tokens = deepcopy(state_dict['tokens'])
|
| 150 |
+
self.rand_id = state_dict['rand_id']
|
| 151 |
+
self.token_id = state_dict['token_id']
|
| 152 |
+
self.rng_state = state_dict['rng_state'].clone() if state_dict['rng_state'] is not None else None
|
| 153 |
+
self._epoch = state_dict['epoch']
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class OnlineTokenizedIterableDataset(IterableDataset):
|
| 157 |
+
def __init__(
|
| 158 |
+
self, dataset: Dataset, tokenizer: PreTrainedTokenizer, seq_len: int = 2048, rank: int = 0, world_size: int = 1
|
| 159 |
+
) -> OnlineTokenizedIterableDataset:
|
| 160 |
+
self.dataset = dataset
|
| 161 |
+
self.tokenizer = tokenizer
|
| 162 |
+
|
| 163 |
+
self.data = dataset.shard(world_size, rank)
|
| 164 |
+
self.seq_len = seq_len
|
| 165 |
+
self.rank = rank
|
| 166 |
+
self.world_size = world_size
|
| 167 |
+
|
| 168 |
+
self.states = None
|
| 169 |
+
self.tokens = []
|
| 170 |
+
|
| 171 |
+
def __iter__(self):
|
| 172 |
+
if self.states is not None:
|
| 173 |
+
self.data.load_state_dict(self.states)
|
| 174 |
+
|
| 175 |
+
while True:
|
| 176 |
+
for sample in self.tokenize(self.data):
|
| 177 |
+
# keep appending the samples to the token buffer
|
| 178 |
+
self.tokens += sample
|
| 179 |
+
|
| 180 |
+
while len(self.tokens) >= self.seq_len:
|
| 181 |
+
input_ids = torch.tensor(self.tokens[:self.seq_len], dtype=torch.long)
|
| 182 |
+
self.tokens = self.tokens[self.seq_len:]
|
| 183 |
+
yield {'input_ids': input_ids}
|
| 184 |
+
|
| 185 |
+
def tokenize(self, data, buffer_size: int = 64):
|
| 186 |
+
buffer, states = [], []
|
| 187 |
+
for sample in data:
|
| 188 |
+
if sample.get('text', None) is not None:
|
| 189 |
+
buffer.append(sample['text'])
|
| 190 |
+
elif sample.get('content', None) is not None:
|
| 191 |
+
buffer.append(sample['content'])
|
| 192 |
+
else:
|
| 193 |
+
raise ValueError(f"No 'text' or 'content' field found in sample:\n{sample}")
|
| 194 |
+
states.append(self.data.state_dict())
|
| 195 |
+
if len(buffer) == buffer_size:
|
| 196 |
+
for s, tokenized in zip(states, self.tokenizer(buffer, return_attention_mask=False)['input_ids']):
|
| 197 |
+
self.states = s
|
| 198 |
+
yield tokenized
|
| 199 |
+
buffer, states = [], []
|
| 200 |
+
if len(buffer) > 0:
|
| 201 |
+
for s, tokenized in zip(states, self.tokenizer(buffer, return_attention_mask=False)['input_ids']):
|
| 202 |
+
self.states = s
|
| 203 |
+
yield tokenized
|
| 204 |
+
|
| 205 |
+
def state_dict(self):
|
| 206 |
+
return {'states': self.states, 'tokens': deepcopy(self.tokens)}
|
| 207 |
+
|
| 208 |
+
def load_state_dict(self, state_dict):
|
| 209 |
+
self.states = state_dict['states']
|
| 210 |
+
self.tokens = deepcopy(state_dict['tokens'])
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class BufferShuffledExamplesIterable(datasets.iterable_dataset.BufferShuffledExamplesIterable):
|
| 214 |
+
def __init__(self, *args, **kwargs):
|
| 215 |
+
super().__init__(*args, **kwargs)
|
| 216 |
+
|
| 217 |
+
def _init_state_dict(self) -> dict:
|
| 218 |
+
self._state_dict = self.ex_iterable._init_state_dict()
|
| 219 |
+
self._state_dict['mem_buffer'] = ([],)
|
| 220 |
+
self._state_dict['bit_generator_state'] = self.generator.bit_generator.state
|
| 221 |
+
self._state_dict['bit_generator_index_offset'] = 0
|
| 222 |
+
self._state_dict['bit_generator_index_offset_shuffle'] = 0
|
| 223 |
+
return self._state_dict
|
| 224 |
+
|
| 225 |
+
def __iter__(self):
|
| 226 |
+
buffer_size = self.buffer_size
|
| 227 |
+
rng = deepcopy(self.generator)
|
| 228 |
+
# this is the shuffle buffer that we keep in memory
|
| 229 |
+
mem_buffer = self._state_dict['mem_buffer'][0]
|
| 230 |
+
# this is an infinite iterator that randomly samples the index of the source to pick examples from
|
| 231 |
+
index_offset = self._state_dict['bit_generator_index_offset'] if self._state_dict else 0
|
| 232 |
+
if self._state_dict:
|
| 233 |
+
rng.bit_generator.state = self._state_dict['bit_generator_state']
|
| 234 |
+
indices_iterator = self._iter_random_indices(rng, buffer_size, random_batch_size=buffer_size)
|
| 235 |
+
# skip already consumed ones
|
| 236 |
+
for _ in range(index_offset):
|
| 237 |
+
i = next(indices_iterator)
|
| 238 |
+
|
| 239 |
+
for x in self.ex_iterable:
|
| 240 |
+
if len(mem_buffer) < buffer_size: # if the buffer is not full, keep filling the buffer
|
| 241 |
+
mem_buffer.append(x)
|
| 242 |
+
else: # otherwise, pick an example from it
|
| 243 |
+
i = next(indices_iterator)
|
| 244 |
+
index_offset = (index_offset + 1) % buffer_size
|
| 245 |
+
if self._state_dict:
|
| 246 |
+
self._state_dict['bit_generator_index_offset'] = index_offset
|
| 247 |
+
if index_offset == 0:
|
| 248 |
+
self._state_dict['bit_generator_state'] = rng.bit_generator.state
|
| 249 |
+
selected = mem_buffer[i]
|
| 250 |
+
mem_buffer[i] = x # replace the picked example by a new one
|
| 251 |
+
yield selected
|
| 252 |
+
|
| 253 |
+
index_offset = self._state_dict['bit_generator_index_offset_shuffle'] if self._state_dict else 0
|
| 254 |
+
if self._state_dict:
|
| 255 |
+
rng.bit_generator.state = self._state_dict['bit_generator_state']
|
| 256 |
+
|
| 257 |
+
# when we run out of examples, we shuffle the remaining examples in the buffer and yield them
|
| 258 |
+
for i in rng.permutation(len(mem_buffer))[index_offset:].tolist():
|
| 259 |
+
index_offset = index_offset + 1
|
| 260 |
+
if self._state_dict:
|
| 261 |
+
self._state_dict['bit_generator_index_offset_shuffle'] = index_offset
|
| 262 |
+
yield mem_buffer[i]
|
| 263 |
+
|
| 264 |
+
def shuffle_data_sources(self, generator: np.random.Generator) -> BufferShuffledExamplesIterable:
|
| 265 |
+
"""Shuffle the wrapped examples iterable as well as the shuffling buffer."""
|
| 266 |
+
return BufferShuffledExamplesIterable(
|
| 267 |
+
self.ex_iterable.shuffle_data_sources(generator), buffer_size=self.buffer_size, generator=generator
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
def shard_data_sources(self, num_shards: int, index: int, contiguous=True) -> BufferShuffledExamplesIterable:
|
| 271 |
+
"""Keep only the requested shard."""
|
| 272 |
+
return BufferShuffledExamplesIterable(
|
| 273 |
+
self.ex_iterable.shard_data_sources(num_shards, index, contiguous=contiguous),
|
| 274 |
+
buffer_size=self.buffer_size,
|
| 275 |
+
generator=self.generator,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
def load_state_dict(self, state_dict: dict) -> dict:
|
| 279 |
+
def _inner_load_state_dict(state, new_state):
|
| 280 |
+
if new_state is not None and isinstance(state, dict):
|
| 281 |
+
for key in new_state:
|
| 282 |
+
state[key] = _inner_load_state_dict(state[key], new_state[key])
|
| 283 |
+
return state
|
| 284 |
+
elif new_state is not None and isinstance(state, list):
|
| 285 |
+
for i in range(len(state)):
|
| 286 |
+
state[i] = _inner_load_state_dict(state[i], new_state[i])
|
| 287 |
+
return state
|
| 288 |
+
return new_state
|
| 289 |
+
|
| 290 |
+
return _inner_load_state_dict(self._state_dict, state_dict)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def shuffle(
|
| 294 |
+
dataset: IterableDataset,
|
| 295 |
+
seed: int = 42,
|
| 296 |
+
generator: np.random.Generator = None,
|
| 297 |
+
buffer_size: int = 1024,
|
| 298 |
+
):
|
| 299 |
+
generator = np.random.default_rng(seed) if generator is None else deepcopy(generator)
|
| 300 |
+
return IterableDataset(
|
| 301 |
+
ex_iterable=BufferShuffledExamplesIterable(dataset._ex_iterable, buffer_size=buffer_size, generator=generator),
|
| 302 |
+
info=dataset._info.copy(),
|
| 303 |
+
split=dataset._split,
|
| 304 |
+
formatting=dataset._formatting,
|
| 305 |
+
shuffling=ShufflingConfig(generator=generator, _original_seed=seed),
|
| 306 |
+
distributed=copy.deepcopy(dataset._distributed),
|
| 307 |
+
token_per_repo_id=dataset._token_per_repo_id,
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@dataclass
|
| 312 |
+
class DataCollatorForLanguageModeling:
|
| 313 |
+
"""
|
| 314 |
+
Data collator used for language modeling. Inputs are dynamically padded if `varlen=False`.
|
| 315 |
+
If `varlen=True`, sequences are expected to be concatenated, and labels match inputs.
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
|
| 319 |
+
The tokenizer used for encoding the data.
|
| 320 |
+
context_len (`int`, optional):
|
| 321 |
+
When `varlen=True`, sequences longer than this length within a document
|
| 322 |
+
(as determined by `cu_seqlens`) will be further chunked.
|
| 323 |
+
varlen (`bool`):
|
| 324 |
+
Whether to handle variable length concatenated sequences (`True`) or padded batches (`False`).
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
A dictionary with the following keys:
|
| 328 |
+
- `input_ids`: Tensor of input IDs. Shape `[batch_size, seq_len]` if `varlen=False`, `[1, total_len]` if `varlen=True`.
|
| 329 |
+
- `labels`: Tensor of labels. Shape matches `input_ids`. Padding positions are masked with -100 if `varlen=False`.
|
| 330 |
+
- `attention_mask`: Tensor indicating non-padding tokens (only if `varlen=False`). Shape matches `input_ids`.
|
| 331 |
+
- `cu_seqlens`: Tensor of cumulative sequence lengths (only if `varlen=True`). Shape `[1, num_sequences + 1]`.
|
| 332 |
+
|
| 333 |
+
NOTE: When `varlen=True`, the `batch_size` must be 1.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
tokenizer: PreTrainedTokenizer
|
| 337 |
+
context_len: Optional[int] = None
|
| 338 |
+
varlen: bool = False
|
| 339 |
+
|
| 340 |
+
def __call__(self, examples: List[Union[List[int], Dict[str, Any]]]) -> Dict[str, Any]:
|
| 341 |
+
if not isinstance(examples[0], Dict):
|
| 342 |
+
examples = [{'input_ids': example} for example in examples]
|
| 343 |
+
|
| 344 |
+
def tensorize(example: Dict[str, Any]) -> Dict[str, Any]:
|
| 345 |
+
tensorized = {}
|
| 346 |
+
for key in ['input_ids', 'cu_seqlens']:
|
| 347 |
+
if key not in example:
|
| 348 |
+
continue
|
| 349 |
+
if isinstance(example[key], List):
|
| 350 |
+
tensorized[key] = torch.tensor(example[key], dtype=torch.long)
|
| 351 |
+
elif isinstance(example[key], np.ndarray):
|
| 352 |
+
tensorized[key] = torch.from_numpy(example[key])
|
| 353 |
+
else:
|
| 354 |
+
tensorized[key] = example[key]
|
| 355 |
+
return tensorized
|
| 356 |
+
|
| 357 |
+
examples = list(map(tensorize, examples))
|
| 358 |
+
|
| 359 |
+
if not self.varlen:
|
| 360 |
+
# --- Handling for varlen=False (Batch Padding) ---
|
| 361 |
+
length_of_first = examples[0]['input_ids'].size(0)
|
| 362 |
+
needs_padding = not all(example['input_ids'].size(0) == length_of_first for example in examples)
|
| 363 |
+
|
| 364 |
+
if needs_padding:
|
| 365 |
+
# Check for pad token if padding is actually required
|
| 366 |
+
if self.tokenizer.pad_token_id is None:
|
| 367 |
+
raise ValueError(
|
| 368 |
+
f'You are attempting to pad samples but the tokenizer you are using '
|
| 369 |
+
f'({self.tokenizer.__class__.__name__}) does not have a pad token.'
|
| 370 |
+
)
|
| 371 |
+
# Pad using the tokenizer, ensuring attention_mask is returned
|
| 372 |
+
batch = self.tokenizer.pad(examples, return_tensors='pt', return_attention_mask=True)
|
| 373 |
+
else:
|
| 374 |
+
# No padding needed, stack directly and create a full attention mask
|
| 375 |
+
input_ids = torch.stack([example['input_ids'] for example in examples], dim=0)
|
| 376 |
+
batch = {
|
| 377 |
+
'input_ids': input_ids,
|
| 378 |
+
# Create attention mask of all ones
|
| 379 |
+
'attention_mask': torch.ones_like(input_ids),
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
# Create labels by cloning input_ids
|
| 383 |
+
labels = batch['input_ids'].clone()
|
| 384 |
+
# Mask labels only where attention_mask is 0 (padding positions)
|
| 385 |
+
if 'attention_mask' in batch:
|
| 386 |
+
labels[batch['attention_mask'] == 0] = -100
|
| 387 |
+
batch['labels'] = labels
|
| 388 |
+
|
| 389 |
+
else:
|
| 390 |
+
# --- Handling for varlen=True (Concatenated Sequences) ---
|
| 391 |
+
if len(examples) > 1:
|
| 392 |
+
raise ValueError('The batch size must be 1 for inputs with variable lengths (varlen=True).')
|
| 393 |
+
|
| 394 |
+
batch = {'input_ids': torch.cat([example['input_ids'] for example in examples], dim=0).unsqueeze(0)}
|
| 395 |
+
|
| 396 |
+
# --- cu_seqlens calculation logic remains the same ---
|
| 397 |
+
if 'cu_seqlens' in examples[0]:
|
| 398 |
+
batch['cu_seqlens'] = (
|
| 399 |
+
torch.cat([example['cu_seqlens'] for example in examples], dim=0).unsqueeze(0).to(dtype=torch.int32)
|
| 400 |
+
) # Ensure int32
|
| 401 |
+
else:
|
| 402 |
+
# determine boundaries by bos/eos positions
|
| 403 |
+
# Check for bos_token_id first
|
| 404 |
+
if self.tokenizer.bos_token_id is not None:
|
| 405 |
+
cu_seqlens = []
|
| 406 |
+
# Handle case where the sequence doesn't start with BOS
|
| 407 |
+
if batch['input_ids'][0, 0] != self.tokenizer.bos_token_id:
|
| 408 |
+
cu_seqlens.append(torch.tensor([0], device=batch['input_ids'].device)) # Match device
|
| 409 |
+
# Find all BOS token positions
|
| 410 |
+
bos_positions = torch.where(batch['input_ids'].eq(self.tokenizer.bos_token_id))[1]
|
| 411 |
+
# Ensure bos_positions is on the correct device if empty
|
| 412 |
+
if bos_positions.numel() == 0 and len(cu_seqlens) > 0:
|
| 413 |
+
cu_seqlens.append(bos_positions.to(cu_seqlens[0].device))
|
| 414 |
+
elif bos_positions.numel() > 0:
|
| 415 |
+
cu_seqlens.append(bos_positions)
|
| 416 |
+
# Add the end of the entire batch
|
| 417 |
+
cu_seqlens.append(
|
| 418 |
+
torch.tensor([batch['input_ids'].size(1)], device=batch['input_ids'].device)
|
| 419 |
+
) # Match device and use size(1)
|
| 420 |
+
# Filter out empty tensors before cat
|
| 421 |
+
cu_seqlens = [t for t in cu_seqlens if t.numel() > 0]
|
| 422 |
+
if not cu_seqlens: # Handle case where input is empty or has no BOS
|
| 423 |
+
batch['cu_seqlens'] = torch.tensor(
|
| 424 |
+
[0, batch['input_ids'].size(1)], dtype=torch.int32, device=batch['input_ids'].device
|
| 425 |
+
)
|
| 426 |
+
else:
|
| 427 |
+
batch['cu_seqlens'] = torch.cat(cu_seqlens, dim=0).to(dtype=torch.int32)
|
| 428 |
+
|
| 429 |
+
# Else, check for eos_token_id
|
| 430 |
+
elif self.tokenizer.eos_token_id is not None:
|
| 431 |
+
cu_seqlens = [torch.tensor([0], device=batch['input_ids'].device)] # Match device
|
| 432 |
+
# Find positions *after* EOS tokens
|
| 433 |
+
eos_positions = torch.where(batch['input_ids'].eq(self.tokenizer.eos_token_id))[1] + 1
|
| 434 |
+
# Ensure eos_positions is on the correct device if empty
|
| 435 |
+
if eos_positions.numel() > 0:
|
| 436 |
+
cu_seqlens.append(eos_positions)
|
| 437 |
+
# Handle case where the sequence doesn't end with EOS
|
| 438 |
+
if batch['input_ids'][0, -1] != self.tokenizer.eos_token_id:
|
| 439 |
+
# Only add the final length if the last found EOS wasn't already the end
|
| 440 |
+
if eos_positions.numel() == 0 or eos_positions[-1] != batch['input_ids'].size(1):
|
| 441 |
+
cu_seqlens.append(
|
| 442 |
+
torch.tensor([batch['input_ids'].size(1)], device=batch['input_ids'].device)
|
| 443 |
+
) # Match device and use size(1)
|
| 444 |
+
# Filter out empty tensors before cat
|
| 445 |
+
cu_seqlens = [t for t in cu_seqlens if t.numel() > 0]
|
| 446 |
+
if not cu_seqlens: # Handle case where input is empty or has no EOS
|
| 447 |
+
batch['cu_seqlens'] = torch.tensor(
|
| 448 |
+
[0, batch['input_ids'].size(1)], dtype=torch.int32, device=batch['input_ids'].device
|
| 449 |
+
)
|
| 450 |
+
else:
|
| 451 |
+
batch['cu_seqlens'] = torch.cat(cu_seqlens, dim=0).to(dtype=torch.int32)
|
| 452 |
+
# Else, neither BOS nor EOS is usable
|
| 453 |
+
else:
|
| 454 |
+
raise ValueError(
|
| 455 |
+
'For varlen=True without precomputed cu_seqlens, the tokenizer must have either a bos_token_id '
|
| 456 |
+
'or an eos_token_id defined to act as sequence separators.'
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
# --- cu_seqlens validation checks remain the same ---
|
| 460 |
+
if batch['cu_seqlens'].numel() < 2:
|
| 461 |
+
raise ValueError(f'Calculated cu_seqlens must have at least start and end: {batch["cu_seqlens"]}')
|
| 462 |
+
if not torch.all(batch['cu_seqlens'][1:] >= batch['cu_seqlens'][:-1]):
|
| 463 |
+
raise ValueError(f'Calculated cu_seqlens are not monotonically increasing: {batch["cu_seqlens"]}')
|
| 464 |
+
if batch['cu_seqlens'][0] != 0:
|
| 465 |
+
raise ValueError(f'Calculated cu_seqlens do not start at 0: {batch["cu_seqlens"]}')
|
| 466 |
+
if batch['cu_seqlens'][-1] != batch['input_ids'].size(1):
|
| 467 |
+
# Allow empty sequence case where cu_seqlens=[0, 0] and input_ids.size(1)=0
|
| 468 |
+
if not (batch['cu_seqlens'].tolist() == [0, 0] and batch['input_ids'].size(1) == 0):
|
| 469 |
+
raise ValueError(
|
| 470 |
+
f'Calculated cu_seqlens do not end at total length {batch["input_ids"].size(1)}: '
|
| 471 |
+
f'{batch["cu_seqlens"]}'
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
# --- context_len splitting logic remains the same ---
|
| 475 |
+
if self.context_len is not None:
|
| 476 |
+
# This logic splits sequences based on context_len *after* initial boundaries are found
|
| 477 |
+
bos = batch['cu_seqlens'][:-1].tolist()
|
| 478 |
+
eos = batch['cu_seqlens'][1:].tolist()
|
| 479 |
+
# Handle empty sequences between boundaries
|
| 480 |
+
split_boundaries = []
|
| 481 |
+
for i, j in zip(bos, eos):
|
| 482 |
+
if i < j: # Only process non-empty sequences
|
| 483 |
+
split_boundaries.append(torch.arange(i, j, self.context_len, device=batch['input_ids'].device))
|
| 484 |
+
# Add the final end point if it wasn't included by arange
|
| 485 |
+
final_end_point = torch.tensor([batch['input_ids'].size(1)], device=batch['input_ids'].device)
|
| 486 |
+
# Concatenate all boundaries
|
| 487 |
+
if not split_boundaries: # Handle case of completely empty input
|
| 488 |
+
batch['cu_seqlens'] = torch.tensor([0, 0], dtype=torch.int32, device=batch['input_ids'].device)
|
| 489 |
+
else:
|
| 490 |
+
batch['cu_seqlens'] = torch.cat(split_boundaries + [final_end_point]).to(dtype=torch.int32)
|
| 491 |
+
# Ensure uniqueness and sort, as arange might duplicate the endpoint
|
| 492 |
+
batch['cu_seqlens'] = torch.unique(batch['cu_seqlens'])
|
| 493 |
+
|
| 494 |
+
# Create labels directly from input_ids, NO padding mask needed for varlen
|
| 495 |
+
labels = batch['input_ids'].clone()
|
| 496 |
+
batch['labels'] = labels
|
| 497 |
+
|
| 498 |
+
return batch
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class ParallelAwareDataLoader(StatefulDataLoader, Stateful):
|
| 502 |
+
"""
|
| 503 |
+
A wrapper around the StatefulDataLoader that ensures that the state is stored only once per DP rank.
|
| 504 |
+
"""
|
| 505 |
+
|
| 506 |
+
def __init__(
|
| 507 |
+
self,
|
| 508 |
+
rank: int,
|
| 509 |
+
dataset: IterableDataset,
|
| 510 |
+
batch_size: int,
|
| 511 |
+
collate_fn: Callable,
|
| 512 |
+
num_workers: int = 0,
|
| 513 |
+
pin_memory: bool = False,
|
| 514 |
+
prefetch_factor: int = 2,
|
| 515 |
+
persistent_workers: bool = False,
|
| 516 |
+
snapshot_every_n_steps: Optional[int] = 1,
|
| 517 |
+
):
|
| 518 |
+
super().__init__(
|
| 519 |
+
dataset=dataset,
|
| 520 |
+
batch_size=batch_size,
|
| 521 |
+
collate_fn=collate_fn,
|
| 522 |
+
num_workers=num_workers,
|
| 523 |
+
pin_memory=pin_memory,
|
| 524 |
+
prefetch_factor=prefetch_factor,
|
| 525 |
+
persistent_workers=persistent_workers,
|
| 526 |
+
snapshot_every_n_steps=snapshot_every_n_steps,
|
| 527 |
+
)
|
| 528 |
+
self.rank = rank
|
| 529 |
+
|
| 530 |
+
def state_dict(self) -> Dict[str, Any]:
|
| 531 |
+
# Store state only for dp rank to avoid replicating the same state across other dimensions
|
| 532 |
+
return {f'rank_{self.rank}': pickle.dumps(super().state_dict())}
|
| 533 |
+
|
| 534 |
+
def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
|
| 535 |
+
# State being empty is valid
|
| 536 |
+
if not state_dict:
|
| 537 |
+
return
|
| 538 |
+
|
| 539 |
+
if f'rank_{self.rank}' not in state_dict:
|
| 540 |
+
logger.warning(f'DataLoader state is empty for dp rank {self.rank}, expected key rank_{self.rank}')
|
| 541 |
+
return
|
| 542 |
+
super().load_state_dict(pickle.loads(state_dict[f'rank_{self.rank}']))
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def build_dataset(
|
| 546 |
+
dataset: str,
|
| 547 |
+
dataset_name: str = None,
|
| 548 |
+
dataset_split: str = 'train',
|
| 549 |
+
data_dir: str = None,
|
| 550 |
+
data_files: str = None,
|
| 551 |
+
data_probs: List[float] = None,
|
| 552 |
+
streaming: bool = False,
|
| 553 |
+
dp_degree: Optional[int] = None,
|
| 554 |
+
num_workers: int = 32,
|
| 555 |
+
seed: Optional[int] = None,
|
| 556 |
+
) -> IterableDataset:
|
| 557 |
+
color = utils.Color
|
| 558 |
+
min_num_shards = dp_degree * num_workers if dp_degree else None
|
| 559 |
+
if len(dataset.split(',')) == 1:
|
| 560 |
+
dataset = load_dataset(
|
| 561 |
+
path=dataset,
|
| 562 |
+
name=dataset_name,
|
| 563 |
+
split=dataset_split,
|
| 564 |
+
data_dir=data_dir,
|
| 565 |
+
data_files=data_files,
|
| 566 |
+
trust_remote_code=True,
|
| 567 |
+
streaming=streaming,
|
| 568 |
+
num_proc=num_workers if not streaming else None,
|
| 569 |
+
)
|
| 570 |
+
logger.info(f"Shuffling the dataset with seed {seed}")
|
| 571 |
+
if not streaming:
|
| 572 |
+
# the states of map-style dataset is recoverable after shuffling
|
| 573 |
+
if seed is not None:
|
| 574 |
+
dataset = dataset.shuffle(seed=seed)
|
| 575 |
+
if min_num_shards is not None:
|
| 576 |
+
dataset = dataset.to_iterable_dataset(num_shards=min_num_shards)
|
| 577 |
+
else:
|
| 578 |
+
if min_num_shards is not None and dataset.num_shards < min_num_shards:
|
| 579 |
+
logger.warning(
|
| 580 |
+
f"{color.red}"
|
| 581 |
+
f"Dataset {dataset} has insufficient shards ({dataset.num_shards}). "
|
| 582 |
+
f"Need {min_num_shards} shards minimum for {dp_degree} data parallel workers × "
|
| 583 |
+
f"{num_workers} dataloader workers. "
|
| 584 |
+
f"Disabling the streaming mode and resharding dataset to {min_num_shards} shards."
|
| 585 |
+
f"{color.reset}"
|
| 586 |
+
)
|
| 587 |
+
dataset = load_dataset(
|
| 588 |
+
path=dataset,
|
| 589 |
+
name=dataset_name,
|
| 590 |
+
split=dataset_split,
|
| 591 |
+
data_dir=data_dir,
|
| 592 |
+
data_files=data_files,
|
| 593 |
+
trust_remote_code=True,
|
| 594 |
+
streaming=False,
|
| 595 |
+
num_proc=num_workers,
|
| 596 |
+
)
|
| 597 |
+
if seed is not None:
|
| 598 |
+
dataset = dataset.shuffle(seed=seed)
|
| 599 |
+
dataset = dataset.to_iterable_dataset(num_shards=min_num_shards)
|
| 600 |
+
else:
|
| 601 |
+
if seed is not None:
|
| 602 |
+
dataset = shuffle(dataset, seed=seed)
|
| 603 |
+
else:
|
| 604 |
+
datasets = dataset.split(",")
|
| 605 |
+
if dataset_name is not None:
|
| 606 |
+
dataset_names = [
|
| 607 |
+
name or None for name in dataset_name.split(",")
|
| 608 |
+
]
|
| 609 |
+
assert len(dataset_names) == len(datasets), (
|
| 610 |
+
"The number of dataset names must match the number of datasets"
|
| 611 |
+
)
|
| 612 |
+
else:
|
| 613 |
+
dataset_names = [None] * len(datasets)
|
| 614 |
+
if dataset_split is not None:
|
| 615 |
+
dataset_splits = [split or "train"for split in dataset_split.split(",")]
|
| 616 |
+
assert len(dataset_splits) == len(datasets), (
|
| 617 |
+
"The number of dataset splits must match the number of datasets"
|
| 618 |
+
)
|
| 619 |
+
else:
|
| 620 |
+
dataset_splits = ["train"] * len(datasets)
|
| 621 |
+
if data_dir is not None:
|
| 622 |
+
data_dirs = [
|
| 623 |
+
data_dir or None for data_dir in data_dir.split(",")
|
| 624 |
+
]
|
| 625 |
+
assert len(data_dirs) == len(datasets), (
|
| 626 |
+
"The number of data dirs must match the number of datasets"
|
| 627 |
+
)
|
| 628 |
+
else:
|
| 629 |
+
data_dirs = [None] * len(datasets)
|
| 630 |
+
if data_files is not None:
|
| 631 |
+
data_files = data_files.split(",")
|
| 632 |
+
assert len(data_files) == len(datasets), (
|
| 633 |
+
"The number of data files must match the number of datasets"
|
| 634 |
+
)
|
| 635 |
+
else:
|
| 636 |
+
data_files = [None] * len(datasets)
|
| 637 |
+
if data_probs is not None:
|
| 638 |
+
data_probs = [float(p) for p in data_probs.split(",")]
|
| 639 |
+
assert len(data_probs) == len(datasets), (
|
| 640 |
+
"The number of data probabilities must match the number of datasets"
|
| 641 |
+
)
|
| 642 |
+
else:
|
| 643 |
+
raise ValueError(
|
| 644 |
+
"Data sampling probabilities are required if using multiple datasets"
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
subsets = []
|
| 648 |
+
for i, prob in enumerate(data_probs):
|
| 649 |
+
subset = load_dataset(
|
| 650 |
+
path=datasets[i],
|
| 651 |
+
name=dataset_names[i],
|
| 652 |
+
split=dataset_splits[i],
|
| 653 |
+
data_dir=data_dirs[i],
|
| 654 |
+
data_files=data_files[i],
|
| 655 |
+
trust_remote_code=True,
|
| 656 |
+
streaming=streaming,
|
| 657 |
+
num_proc=(
|
| 658 |
+
num_workers
|
| 659 |
+
if not streaming
|
| 660 |
+
else None
|
| 661 |
+
),
|
| 662 |
+
)
|
| 663 |
+
logger.info(
|
| 664 |
+
f"Subset {color.cyan}{datasets[i]}"
|
| 665 |
+
+ (f":{dataset_names[i]} " if dataset_names[i] else " ")
|
| 666 |
+
+ f"(p = {prob:.3f}){color.reset}:\n"
|
| 667 |
+
+ f"{subset}"
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
logger.info(f"Shuffling the dataset with seed {seed}")
|
| 671 |
+
if not streaming:
|
| 672 |
+
# the states of map-style dataset is recoverable after shuffling
|
| 673 |
+
if seed is not None:
|
| 674 |
+
subset = subset.shuffle(seed=seed)
|
| 675 |
+
if min_num_shards is not None:
|
| 676 |
+
subset = subset.to_iterable_dataset(num_shards=min_num_shards)
|
| 677 |
+
else:
|
| 678 |
+
if min_num_shards is not None and subset.num_shards < min_num_shards:
|
| 679 |
+
logger.warning(
|
| 680 |
+
f"{color.red}"
|
| 681 |
+
f"Dataset {datasets[i]} has insufficient shards ({subset.num_shards}). "
|
| 682 |
+
f"Need {min_num_shards} shards minimum for desired data parallel workers × "
|
| 683 |
+
f"{num_workers} dataloader workers. "
|
| 684 |
+
f"Resharding dataset to {min_num_shards} shards and disabling streaming mode."
|
| 685 |
+
f"{color.reset}"
|
| 686 |
+
)
|
| 687 |
+
# again, it's ok to directly shuffle the map-style dataset
|
| 688 |
+
# we expect an error raised if the map-style dataset still has not enough data shards
|
| 689 |
+
subset = load_dataset(
|
| 690 |
+
path=datasets[i],
|
| 691 |
+
name=dataset_names[i],
|
| 692 |
+
split=dataset_splits[i],
|
| 693 |
+
data_dir=data_dirs[i],
|
| 694 |
+
data_files=data_files[i],
|
| 695 |
+
trust_remote_code=True,
|
| 696 |
+
streaming=False,
|
| 697 |
+
num_proc=num_workers,
|
| 698 |
+
)
|
| 699 |
+
if seed is not None:
|
| 700 |
+
subset = subset.shuffle(seed=seed)
|
| 701 |
+
subset = subset.to_iterable_dataset(num_shards=min_num_shards)
|
| 702 |
+
else:
|
| 703 |
+
# we set relatively small buffer size here as interleaving could provide some randomness
|
| 704 |
+
if seed is not None:
|
| 705 |
+
subset = shuffle(subset, seed=seed, buffer_size=max(128, 1024 // len(datasets)))
|
| 706 |
+
|
| 707 |
+
if "text" in subset.column_names:
|
| 708 |
+
subset = subset.select_columns("text")
|
| 709 |
+
elif "content" in subset.column_names:
|
| 710 |
+
subset = subset.select_columns("content")
|
| 711 |
+
else:
|
| 712 |
+
raise ValueError(
|
| 713 |
+
f"Subset {datasets[i]} has no 'text' or 'content' column"
|
| 714 |
+
)
|
| 715 |
+
subsets.append(subset)
|
| 716 |
+
|
| 717 |
+
logger.info(
|
| 718 |
+
f"Interleaving {len(subsets)} datasets with probabilities {data_probs}"
|
| 719 |
+
)
|
| 720 |
+
dataset = interleave_datasets(
|
| 721 |
+
datasets=subsets,
|
| 722 |
+
probabilities=data_probs,
|
| 723 |
+
stopping_strategy="all_exhausted",
|
| 724 |
+
seed=seed,
|
| 725 |
+
)
|
| 726 |
+
logger.info(f"{dataset}")
|
| 727 |
+
return dataset
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def build_dataloader(
|
| 731 |
+
dataset: IterableDataset,
|
| 732 |
+
tokenizer: PreTrainedTokenizer,
|
| 733 |
+
rank: int,
|
| 734 |
+
world_size: int,
|
| 735 |
+
batch_size: int,
|
| 736 |
+
seq_len: int,
|
| 737 |
+
context_len: Optional[int] = None,
|
| 738 |
+
varlen: bool = False,
|
| 739 |
+
num_workers: int = 0,
|
| 740 |
+
pin_memory: bool = False,
|
| 741 |
+
persistent_workers: bool = False,
|
| 742 |
+
snapshot_every_n_steps: Optional[int] = 1,
|
| 743 |
+
):
|
| 744 |
+
dataset = OnlineTokenizedIterableDataset(
|
| 745 |
+
dataset=dataset, tokenizer=tokenizer, seq_len=seq_len, rank=rank, world_size=world_size
|
| 746 |
+
)
|
| 747 |
+
return ParallelAwareDataLoader(
|
| 748 |
+
rank=rank,
|
| 749 |
+
dataset=dataset,
|
| 750 |
+
batch_size=batch_size,
|
| 751 |
+
collate_fn=DataCollatorForLanguageModeling(tokenizer=tokenizer, context_len=context_len, varlen=varlen),
|
| 752 |
+
num_workers=num_workers,
|
| 753 |
+
pin_memory=pin_memory,
|
| 754 |
+
persistent_workers=persistent_workers,
|
| 755 |
+
snapshot_every_n_steps=snapshot_every_n_steps,
|
| 756 |
+
)
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__init__.py
ADDED
|
File without changes
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (153 Bytes). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__pycache__/parallelize_fla.cpython-311.pyc
ADDED
|
Binary file (23.6 kB). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/__pycache__/pipeline_fla.cpython-311.pyc
ADDED
|
Binary file (6.37 kB). View file
|
|
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/activation_offloading.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://github.com/pytorch/torchtune/blob/main/torchtune/training/_activation_offloading.py
|
| 2 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 3 |
+
# All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# This source code is licensed under the BSD-style license found in the
|
| 6 |
+
# LICENSE file in the root directory of this source tree.
|
| 7 |
+
|
| 8 |
+
import contextlib
|
| 9 |
+
from typing import Union
|
| 10 |
+
from warnings import warn
|
| 11 |
+
|
| 12 |
+
import psutil
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
from torch.autograd.graph import saved_tensors_hooks
|
| 16 |
+
|
| 17 |
+
from torchtitan.tools.logging import logger
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
import torchao
|
| 21 |
+
from torchao.dtypes.nf4tensor import NF4Tensor
|
| 22 |
+
except ImportError:
|
| 23 |
+
torchao = None
|
| 24 |
+
NF4Tensor = None
|
| 25 |
+
logger.warning("torchao not found. ")
|
| 26 |
+
|
| 27 |
+
# from torchtune.modules import TiedLinear
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class OffloadActivations(saved_tensors_hooks):
|
| 31 |
+
"""Context manager under which activation tensors created in the forward pass will be offloaded.
|
| 32 |
+
|
| 33 |
+
Enable the memory efficiency technique of activation offloading, where activations bigger than
|
| 34 |
+
min_offload_size bytes will be offloaded to CPU in the forward and brought back in the backward.
|
| 35 |
+
This is in contrast to maintaining the activation on GPU VRAM throughout the program.
|
| 36 |
+
|
| 37 |
+
This manager contains the option of using one additional CUDA stream to handle the communication
|
| 38 |
+
between CUDA and CPU, which is intended to overlap with the default computation stream to improve
|
| 39 |
+
runtime. We designed synchronization with a few heuristics for optimizing the tradeoff between
|
| 40 |
+
runtime vs memory usage.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
use_pin_memory (bool): Whether or not the offloaded Tensor will be placed in pinned
|
| 44 |
+
memory on the CPU. Pinned memory allows the Tensor to be moved back onto GPU more quickly
|
| 45 |
+
but is a limited resource. Default: True.
|
| 46 |
+
|
| 47 |
+
use_streams (bool): Whether or not to use streams for performance optimization where
|
| 48 |
+
the communications get overlapped with the computation. Requires a torch build
|
| 49 |
+
after torch-2.5.0.]. Default: True.
|
| 50 |
+
|
| 51 |
+
max_fwd_stash_size (int): The maximum size of the forward stash, or the maximum number of
|
| 52 |
+
consecutive activations to keep alive during the forward pass. This number must be at
|
| 53 |
+
least 1. Keeping alive more activations will potentially allow more overlap between the
|
| 54 |
+
communication and compute streams at the cost of increasing memory usage. Keeping alive
|
| 55 |
+
fewer activations will conserve memory, but may cause poor overlap between the streams,
|
| 56 |
+
increasing runtime. Default: 5.
|
| 57 |
+
|
| 58 |
+
min_offload_size (int): The minimum number of bytes a Tensor must be in order to qualify
|
| 59 |
+
for offloading. If the tensor is too small, we do not want to waste bandwidth and resources
|
| 60 |
+
moving it to CPU and back. Default: 1024 bytes.
|
| 61 |
+
|
| 62 |
+
Raises:
|
| 63 |
+
ValueError: if max_fwd_stash_size is not at least 1.
|
| 64 |
+
|
| 65 |
+
Example:
|
| 66 |
+
>>> with OffloadActivations():
|
| 67 |
+
>>> logits = model(inputs)
|
| 68 |
+
>>> loss = ...
|
| 69 |
+
>>> loss.backward()
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(
|
| 73 |
+
self,
|
| 74 |
+
use_pin_memory: bool = True,
|
| 75 |
+
use_streams: bool = True,
|
| 76 |
+
max_fwd_stash_size: int = 5,
|
| 77 |
+
min_offload_size: int = 1024,
|
| 78 |
+
) -> None:
|
| 79 |
+
|
| 80 |
+
self.use_streams: bool = use_streams
|
| 81 |
+
|
| 82 |
+
self.min_tensor_size_bytes = (
|
| 83 |
+
min_offload_size # we don't want to bother with small tensors
|
| 84 |
+
)
|
| 85 |
+
self.tracker = (
|
| 86 |
+
{}
|
| 87 |
+
) # tensor_id => (new_tensor, if_modified) ---> track what saved/offloaded tensors are where
|
| 88 |
+
self.tensor_id: int = 0
|
| 89 |
+
self.is_first_forward_call = True
|
| 90 |
+
self.is_first_backward_call = True
|
| 91 |
+
self.is_first_forward_pass = True
|
| 92 |
+
|
| 93 |
+
# managing cpu memory
|
| 94 |
+
self.use_pin_memory: bool = use_pin_memory
|
| 95 |
+
self.virtual_memory_safe_pct = (
|
| 96 |
+
60 # we should not exceed this percentage of memory
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
self.s0 = torch.cuda.default_stream() # comp stream
|
| 100 |
+
|
| 101 |
+
# for streaming
|
| 102 |
+
if self.use_streams:
|
| 103 |
+
self.s1 = torch.cuda.Stream() # comms stream
|
| 104 |
+
self.fwd_stash = {} # tensor_id => (activation, ev1)
|
| 105 |
+
if max_fwd_stash_size < 1:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
f"max_fwd_stash_size should be at least 1 but is {max_fwd_stash_size}"
|
| 108 |
+
)
|
| 109 |
+
self.max_fwd_stash_size = max_fwd_stash_size
|
| 110 |
+
self.bwd_tensor_stash = {} # tensor_id => activation
|
| 111 |
+
self.bwd_ev_stash = {} # tensor_id => ev0
|
| 112 |
+
self.curr_graph_id = None
|
| 113 |
+
self.curr_autograd_node = None
|
| 114 |
+
|
| 115 |
+
# -------- platform util functions -------- #
|
| 116 |
+
def verify_sufficient_virtual_memory():
|
| 117 |
+
curr_pct = get_cpu_ram_pct()
|
| 118 |
+
if curr_pct > self.virtual_memory_safe_pct:
|
| 119 |
+
warn(
|
| 120 |
+
f"***** WARNING: {curr_pct=}% > {self.virtual_memory_safe_pct=}% of virtual memory used"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def get_cpu_ram_pct() -> float:
|
| 124 |
+
# get the percentage of memory used by the system
|
| 125 |
+
return psutil.virtual_memory().percent
|
| 126 |
+
|
| 127 |
+
def get_tensor_id() -> int:
|
| 128 |
+
# create a unique id for each tensor we are managing
|
| 129 |
+
self.tensor_id += 1
|
| 130 |
+
return self.tensor_id
|
| 131 |
+
|
| 132 |
+
def get_num_bytes_tensor(x: torch.Tensor) -> int:
|
| 133 |
+
# get the number of bytes in a tensor, for memory management purposes
|
| 134 |
+
return (
|
| 135 |
+
x.element_size() * x.nelement()
|
| 136 |
+
) # x.element_size() * x._base_storage().nbytes()
|
| 137 |
+
|
| 138 |
+
# -------- core pack / unpack work -------- #
|
| 139 |
+
def pack_tensor(activation: torch.Tensor) -> int:
|
| 140 |
+
# activations are passed in during forward pass - from here we take over and return a unique id
|
| 141 |
+
if self.is_first_forward_call:
|
| 142 |
+
assert (
|
| 143 |
+
len(self.tracker) == 0
|
| 144 |
+
), "backward pass should have cleared tracker of all tensors"
|
| 145 |
+
|
| 146 |
+
# set training phase trackers
|
| 147 |
+
self.is_first_forward_call = False
|
| 148 |
+
self.is_first_backward_call = True
|
| 149 |
+
|
| 150 |
+
# query for basic tensor info
|
| 151 |
+
num_bytes = get_num_bytes_tensor(activation)
|
| 152 |
+
tensor_id = get_tensor_id()
|
| 153 |
+
|
| 154 |
+
# only offload hefty bois if they're activations on CUDA (our heuristic
|
| 155 |
+
# for that is to check if they're not params or buffers)!
|
| 156 |
+
if (
|
| 157 |
+
activation.is_cuda
|
| 158 |
+
and num_bytes >= self.min_tensor_size_bytes
|
| 159 |
+
and (
|
| 160 |
+
not isinstance(activation, torch.nn.Parameter)
|
| 161 |
+
and not isinstance(activation, torch.nn.Buffer)
|
| 162 |
+
)
|
| 163 |
+
):
|
| 164 |
+
if self.use_streams:
|
| 165 |
+
# First, sync back and dereference previously offloaded tensors
|
| 166 |
+
# as the offloading should be done sufficiently long ago.
|
| 167 |
+
for id in [k for k in self.fwd_stash.keys()]:
|
| 168 |
+
if id <= tensor_id - self.max_fwd_stash_size:
|
| 169 |
+
_, ev = self.fwd_stash[id]
|
| 170 |
+
self.s0.wait_event(ev)
|
| 171 |
+
del self.fwd_stash[id]
|
| 172 |
+
else:
|
| 173 |
+
break
|
| 174 |
+
|
| 175 |
+
# Sync in, offload, and add an event to sync back later
|
| 176 |
+
self.s1.wait_stream(self.s0)
|
| 177 |
+
|
| 178 |
+
stream = self.s1 if self.use_streams else self.s0
|
| 179 |
+
with torch.cuda.stream(stream):
|
| 180 |
+
try:
|
| 181 |
+
cpu_tensor = torch.empty_like(
|
| 182 |
+
activation, pin_memory=self.use_pin_memory, device="cpu"
|
| 183 |
+
)
|
| 184 |
+
except NotImplementedError as e:
|
| 185 |
+
if (
|
| 186 |
+
isinstance(activation, NF4Tensor)
|
| 187 |
+
and torchao.__version__ < "0.6.0.dev20240917"
|
| 188 |
+
):
|
| 189 |
+
raise RuntimeError(
|
| 190 |
+
"Offloading NF4Tensors requires torchao-0.6.0.dev20240917 or later"
|
| 191 |
+
) from e
|
| 192 |
+
raise e
|
| 193 |
+
cpu_tensor.copy_(activation, non_blocking=True)
|
| 194 |
+
self.tracker[tensor_id] = (
|
| 195 |
+
cpu_tensor,
|
| 196 |
+
True,
|
| 197 |
+
) # True = (in future) modified
|
| 198 |
+
|
| 199 |
+
if self.use_streams:
|
| 200 |
+
event = self.s1.record_event()
|
| 201 |
+
|
| 202 |
+
# Stash to keep activation alive til s1 is done
|
| 203 |
+
self.fwd_stash[tensor_id] = (activation, event)
|
| 204 |
+
else:
|
| 205 |
+
self.tracker[tensor_id] = (
|
| 206 |
+
activation,
|
| 207 |
+
False,
|
| 208 |
+
) # False = not modified, tensor is as is
|
| 209 |
+
|
| 210 |
+
return tensor_id
|
| 211 |
+
|
| 212 |
+
def unpack_tensor_single_stream(unpack_tensor_id: int) -> torch.Tensor:
|
| 213 |
+
# backward pass - we are called with the tensor_id, which
|
| 214 |
+
# we will use to retrieve the saved/offloaded tensor
|
| 215 |
+
if self.is_first_backward_call:
|
| 216 |
+
if self.is_first_forward_pass:
|
| 217 |
+
self.is_first_forward_pass = False
|
| 218 |
+
if self.use_pin_memory:
|
| 219 |
+
verify_sufficient_virtual_memory()
|
| 220 |
+
|
| 221 |
+
self.is_first_backward_call = False
|
| 222 |
+
self.is_first_forward_call = True
|
| 223 |
+
|
| 224 |
+
assert (
|
| 225 |
+
unpack_tensor_id in self.tracker
|
| 226 |
+
), f"untracked tensor with id {unpack_tensor_id}"
|
| 227 |
+
|
| 228 |
+
maybe_gpu_tensor, modified = self.tracker[unpack_tensor_id]
|
| 229 |
+
if modified:
|
| 230 |
+
gpu_tensor = maybe_gpu_tensor.to("cuda", non_blocking=True)
|
| 231 |
+
maybe_gpu_tensor = gpu_tensor
|
| 232 |
+
|
| 233 |
+
# clear tensor from tracking
|
| 234 |
+
del self.tracker[unpack_tensor_id]
|
| 235 |
+
return maybe_gpu_tensor
|
| 236 |
+
|
| 237 |
+
def unpack_tensor_with_streams(unpack_tensor_id: int) -> torch.Tensor:
|
| 238 |
+
# backward pass - we are called with the tensor_id, which
|
| 239 |
+
# we will use to retrieve the saved/offloaded tensor
|
| 240 |
+
if self.is_first_backward_call:
|
| 241 |
+
self.curr_graph_id = torch._C._current_graph_task_id()
|
| 242 |
+
|
| 243 |
+
def wait_and_del_remaining_references() -> None:
|
| 244 |
+
for id in [k for k in self.bwd_tensor_stash.keys()]:
|
| 245 |
+
event = self.bwd_ev_stash[id]
|
| 246 |
+
self.s1.wait_event(event)
|
| 247 |
+
del self.bwd_tensor_stash[id]
|
| 248 |
+
|
| 249 |
+
# Register a callback to the end of autograd to clean everything up
|
| 250 |
+
torch.autograd.variable.Variable._execution_engine.queue_callback(
|
| 251 |
+
wait_and_del_remaining_references
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
if self.is_first_forward_pass:
|
| 255 |
+
self.is_first_forward_pass = False
|
| 256 |
+
if self.use_pin_memory:
|
| 257 |
+
verify_sufficient_virtual_memory()
|
| 258 |
+
|
| 259 |
+
self.is_first_backward_call = False
|
| 260 |
+
self.is_first_forward_call = True
|
| 261 |
+
|
| 262 |
+
assert (
|
| 263 |
+
unpack_tensor_id in self.tracker
|
| 264 |
+
), f"untracked tensor with id {unpack_tensor_id}"
|
| 265 |
+
|
| 266 |
+
maybe_gpu_tensor, modified = self.tracker[unpack_tensor_id]
|
| 267 |
+
if modified:
|
| 268 |
+
# Get data on the current autograd node
|
| 269 |
+
graph_id = torch._C._current_graph_task_id()
|
| 270 |
+
node = torch._C._current_autograd_node()
|
| 271 |
+
prev_node_ids = []
|
| 272 |
+
|
| 273 |
+
# If we're on a new node, mark prev node's tensors to be freed later
|
| 274 |
+
if graph_id == self.curr_graph_id and self.curr_autograd_node != node:
|
| 275 |
+
self.curr_autograd_node = node
|
| 276 |
+
prev_node_ids = [id for id in self.bwd_tensor_stash.keys()]
|
| 277 |
+
|
| 278 |
+
brought_back_from_cpu = True
|
| 279 |
+
if unpack_tensor_id in self.fwd_stash:
|
| 280 |
+
maybe_gpu_tensor = self.fwd_stash[unpack_tensor_id][0]
|
| 281 |
+
brought_back_from_cpu = False
|
| 282 |
+
else:
|
| 283 |
+
# Kick off the process to bring tensors back
|
| 284 |
+
with torch.cuda.stream(self.s1):
|
| 285 |
+
gpu_tensor = maybe_gpu_tensor.to("cuda", non_blocking=True)
|
| 286 |
+
maybe_gpu_tensor = gpu_tensor
|
| 287 |
+
|
| 288 |
+
# Tell comp stream to wait for the info to be loaded before executing
|
| 289 |
+
self.s0.wait_stream(self.s1)
|
| 290 |
+
|
| 291 |
+
# Stash the tensor to keep memory alive until compute stream is complete
|
| 292 |
+
self.bwd_tensor_stash[unpack_tensor_id] = maybe_gpu_tensor
|
| 293 |
+
|
| 294 |
+
# Note: [Track views of the unpacked]
|
| 295 |
+
# Why do we get the use count of the unpacked tensor here? We want an
|
| 296 |
+
# initial count to compare to later, during the post-hook of the
|
| 297 |
+
# backward node, when we need to decide whether we're allowed to free
|
| 298 |
+
# the tensor yet. In what obscure cases must we delay freeing the
|
| 299 |
+
# tensor (and thus call record_stream)?
|
| 300 |
+
# 1. Any of the outputs of the backward node is a view of the unpacked
|
| 301 |
+
# tensor.
|
| 302 |
+
# 2. In the case that this unpacked tensor will be used in a
|
| 303 |
+
# checkpointed region, if one of the recomputed saved tensors ends
|
| 304 |
+
# up as a view of the unpacked tensor.
|
| 305 |
+
# 3. The user abuses the system somehow and manually relies on the
|
| 306 |
+
# unpacked tensor to exist after the backward node has executed.
|
| 307 |
+
storage_refcount = torch._C._storage_Use_Count(
|
| 308 |
+
maybe_gpu_tensor.untyped_storage()._cdata
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
def hook(outputs, inputs):
|
| 312 |
+
# create events for the current node inputs/outputs if they were streamed in
|
| 313 |
+
if brought_back_from_cpu:
|
| 314 |
+
# See Note: [Track views of the unpacked]
|
| 315 |
+
# IF any of the outputs is a view of the tensor, OR if a view of
|
| 316 |
+
# the tensor has been saved as a part of checkpoint's recompute
|
| 317 |
+
# process, OR the user has abusedly incurred a reference on the
|
| 318 |
+
# unpacked tensor, THEN the tensor might be used later and we
|
| 319 |
+
# cannot presume to delete it after only the current node is
|
| 320 |
+
# done! So we use our frenemy, record_stream, to ensure the
|
| 321 |
+
# Tensor stays unmessed with until it's done getting used in the
|
| 322 |
+
# compute stream (s0 here). Note that the con here is we introduce
|
| 323 |
+
# non-deterministic (thus higher) memory usage, but this case
|
| 324 |
+
# should not happen often.
|
| 325 |
+
unpacked_tensor = self.bwd_tensor_stash[unpack_tensor_id]
|
| 326 |
+
if (
|
| 327 |
+
torch._C._storage_Use_Count(
|
| 328 |
+
unpacked_tensor.untyped_storage()._cdata
|
| 329 |
+
)
|
| 330 |
+
> storage_refcount
|
| 331 |
+
):
|
| 332 |
+
unpacked_tensor.record_stream(self.s0)
|
| 333 |
+
del self.bwd_tensor_stash[unpack_tensor_id]
|
| 334 |
+
else:
|
| 335 |
+
event = self.s0.record_event()
|
| 336 |
+
self.bwd_ev_stash[unpack_tensor_id] = event
|
| 337 |
+
|
| 338 |
+
# if there are still things in the fwd_stash, get rid of them as we're in bwd now
|
| 339 |
+
for id in [k for k in self.fwd_stash.keys()]:
|
| 340 |
+
_, ev = self.fwd_stash[id]
|
| 341 |
+
self.s0.wait_event(ev)
|
| 342 |
+
del self.fwd_stash[id]
|
| 343 |
+
|
| 344 |
+
# wait on prev node's events and del those
|
| 345 |
+
for id in prev_node_ids:
|
| 346 |
+
event = self.bwd_ev_stash[id]
|
| 347 |
+
self.s1.wait_event(event)
|
| 348 |
+
del self.bwd_tensor_stash[id]
|
| 349 |
+
|
| 350 |
+
return outputs
|
| 351 |
+
|
| 352 |
+
node.register_hook(hook)
|
| 353 |
+
|
| 354 |
+
# clear tensor from tracking
|
| 355 |
+
del self.tracker[unpack_tensor_id]
|
| 356 |
+
return maybe_gpu_tensor
|
| 357 |
+
|
| 358 |
+
unpack_tensor = (
|
| 359 |
+
unpack_tensor_with_streams
|
| 360 |
+
if self.use_streams
|
| 361 |
+
else unpack_tensor_single_stream
|
| 362 |
+
)
|
| 363 |
+
super().__init__(pack_tensor, unpack_tensor)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
class NoOpManager(saved_tensors_hooks):
|
| 367 |
+
"""
|
| 368 |
+
A saved_tensors_hook manager used to disable any other saved_tensors_hook manager
|
| 369 |
+
applied before. This relies on the behavior that only the most recently registered
|
| 370 |
+
saved_tensors_hook will run.
|
| 371 |
+
|
| 372 |
+
One example usage is to opt a local region of code out of activations offloading,
|
| 373 |
+
which is usually applied globally to best track state.
|
| 374 |
+
"""
|
| 375 |
+
|
| 376 |
+
def __init__(self) -> None:
|
| 377 |
+
def noop(tensor):
|
| 378 |
+
return tensor
|
| 379 |
+
|
| 380 |
+
super().__init__(noop, noop)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def get_act_offloading_ctx_manager(
|
| 384 |
+
model: nn.Module, enable_activation_offloading: bool
|
| 385 |
+
) -> Union[OffloadActivations, contextlib.nullcontext]:
|
| 386 |
+
"""Returns the activation offloading context manager for the model, which will be
|
| 387 |
+
a null context if enable_activation_offloading is False.
|
| 388 |
+
|
| 389 |
+
If activation offloading is enabled, we return the OffloadActivations context manager.
|
| 390 |
+
If activation offloading is disabled, we return a NoOpManager context manager.
|
| 391 |
+
|
| 392 |
+
Args:
|
| 393 |
+
model (nn.Module): the model to wrap with the activation offloading context manager.
|
| 394 |
+
enable_activation_offloading (bool): whether or not to enable activation offloading
|
| 395 |
+
for the model.
|
| 396 |
+
|
| 397 |
+
Returns:
|
| 398 |
+
contextlib.ContextDecorator: the activation offloading context manager for the model.
|
| 399 |
+
|
| 400 |
+
Raises:
|
| 401 |
+
NotImplementedError: If the model is a multimodal model and activation offloading is enabled.
|
| 402 |
+
"""
|
| 403 |
+
if enable_activation_offloading:
|
| 404 |
+
activations_handling_ctx = OffloadActivations()
|
| 405 |
+
|
| 406 |
+
# Below is our hack to disable offloading the last output Linear in every
|
| 407 |
+
# step, as the cost for offloading the activation and then soon after bringing
|
| 408 |
+
# it back is expensive. Moreover, due to heuristics in our streaming API,
|
| 409 |
+
# we actually use more memory if we offload it as it interferes with chunkedCE.
|
| 410 |
+
output_head_detected = False
|
| 411 |
+
noop_ctx = NoOpManager()
|
| 412 |
+
|
| 413 |
+
if hasattr(model, "output"):
|
| 414 |
+
if isinstance(model.output, nn.Module):
|
| 415 |
+
model.output.register_forward_pre_hook(
|
| 416 |
+
lambda *args: noop_ctx.__enter__()
|
| 417 |
+
)
|
| 418 |
+
model.output.register_forward_hook(
|
| 419 |
+
lambda *args: noop_ctx.__exit__(), always_call=True
|
| 420 |
+
)
|
| 421 |
+
print("registering hooks for model.output ============ ")
|
| 422 |
+
output_head_detected = True
|
| 423 |
+
# ================================
|
| 424 |
+
# ! TODO[flame] check if we need to detal with TiedLinear
|
| 425 |
+
# The following code appears in `torchtune`
|
| 426 |
+
# elif isinstance(model.output, TiedLinear):
|
| 427 |
+
# model.output.linear.register_forward_pre_hook(
|
| 428 |
+
# lambda *args: noop_ctx.__enter__()
|
| 429 |
+
# )
|
| 430 |
+
# model.output.linear.register_forward_hook(
|
| 431 |
+
# lambda *args: noop_ctx.__exit__(), always_call=True
|
| 432 |
+
# )
|
| 433 |
+
# output_head_detected = True
|
| 434 |
+
|
| 435 |
+
if not output_head_detected:
|
| 436 |
+
logger.warning(
|
| 437 |
+
"During activation offloading, no output head was detected. "
|
| 438 |
+
"If your model has an output head, it will be offloaded. "
|
| 439 |
+
"This usually greatly slows training, given the large vocabulary size. "
|
| 440 |
+
"To change this behavior, set your output head as model.output and make it "
|
| 441 |
+
"an nn.Module."
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
else:
|
| 445 |
+
activations_handling_ctx = contextlib.nullcontext()
|
| 446 |
+
|
| 447 |
+
return activations_handling_ctx
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/fla.toml
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[model]
|
| 2 |
+
config = "fla-hub/transformer-1.3B-100B"
|
| 3 |
+
tokenizer_path = "fla-hub/transformer-1.3B-100B"
|
| 4 |
+
|
| 5 |
+
[job]
|
| 6 |
+
dump_folder = "exp"
|
| 7 |
+
print_args = true
|
| 8 |
+
|
| 9 |
+
[training]
|
| 10 |
+
batch_size = 32
|
| 11 |
+
seq_len = 2048
|
| 12 |
+
context_len = 2048
|
| 13 |
+
gradient_accumulation_steps = 1
|
| 14 |
+
steps = 20480
|
| 15 |
+
max_norm = 1.0
|
| 16 |
+
skip_nan_inf = true
|
| 17 |
+
data_parallel_replicate_degree = 1
|
| 18 |
+
data_parallel_shard_degree = -1
|
| 19 |
+
tensor_parallel_degree = 1
|
| 20 |
+
compile = false
|
| 21 |
+
dataset = "HuggingFaceFW/fineweb-edu"
|
| 22 |
+
dataset_name = "default"
|
| 23 |
+
num_workers = 32
|
| 24 |
+
pin_memory = false
|
| 25 |
+
persistent_workers = false
|
| 26 |
+
prefetch_factor = 2
|
| 27 |
+
seed = 42
|
| 28 |
+
varlen = false
|
| 29 |
+
|
| 30 |
+
[optimizer]
|
| 31 |
+
name = "AdamW"
|
| 32 |
+
eps = 1e-15
|
| 33 |
+
lr = 3e-4
|
| 34 |
+
|
| 35 |
+
[lr_scheduler]
|
| 36 |
+
warmup_steps = 1024
|
| 37 |
+
decay_type = "cosine"
|
| 38 |
+
lr_min = 0.1
|
| 39 |
+
|
| 40 |
+
[checkpoint]
|
| 41 |
+
enable_checkpoint = true
|
| 42 |
+
folder = "checkpoint"
|
| 43 |
+
interval_type = "steps"
|
| 44 |
+
interval = 2048
|
| 45 |
+
model_weights_only = false
|
| 46 |
+
export_dtype = "float32"
|
| 47 |
+
async_mode = "disabled" # ["disabled", "async", "async_with_pinned_mem"]
|
| 48 |
+
|
| 49 |
+
[profiling]
|
| 50 |
+
enable_profiling = true
|
| 51 |
+
save_traces_folder = "profile_trace"
|
| 52 |
+
profile_freq = 512
|
| 53 |
+
|
| 54 |
+
[metrics]
|
| 55 |
+
log_freq = 32
|
| 56 |
+
enable_wandb = true
|
| 57 |
+
|
| 58 |
+
[experimental]
|
| 59 |
+
context_parallel_degree = 1
|
| 60 |
+
pipeline_parallel_degree = 1
|
| 61 |
+
|
| 62 |
+
[float8]
|
| 63 |
+
enable_fsdp_float8_all_gather = false
|
| 64 |
+
precompute_float8_dynamic_scale_for_fsdp = false
|
| 65 |
+
|
| 66 |
+
[activation_checkpoint]
|
| 67 |
+
mode = "none"
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/parallelize_fla.py
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# This file applies the PT-D parallelisms (except pipeline parallelism) and various
|
| 8 |
+
# training techniques (e.g. activation checkpointing and compile) to the Llama model.
|
| 9 |
+
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch.distributed import DeviceMesh
|
| 15 |
+
from torch.distributed._composable.fsdp import CPUOffloadPolicy, MixedPrecisionPolicy, fully_shard
|
| 16 |
+
from torch.distributed._composable.replicate import replicate
|
| 17 |
+
from torch.distributed._tensor import Replicate, Shard
|
| 18 |
+
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper as ptd_checkpoint_wrapper
|
| 19 |
+
from torch.distributed.tensor.parallel import (
|
| 20 |
+
ColwiseParallel,
|
| 21 |
+
PrepareModuleInput,
|
| 22 |
+
PrepareModuleOutput,
|
| 23 |
+
RowwiseParallel,
|
| 24 |
+
SequenceParallel,
|
| 25 |
+
parallelize_module
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
from fla.modules.fused_linear_cross_entropy import LinearLossParallel
|
| 29 |
+
from fla.modules.mlp import SwiGLULinearParallel
|
| 30 |
+
from fla.modules.parallel import PrepareModuleWeight
|
| 31 |
+
from torchtitan.config_manager import TORCH_DTYPE_MAP, JobConfig
|
| 32 |
+
from torchtitan.distributed.parallel_dims import ParallelDims
|
| 33 |
+
from torchtitan.tools.logging import logger
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def parallelize_fla(
|
| 37 |
+
model: nn.Module,
|
| 38 |
+
world_mesh: DeviceMesh,
|
| 39 |
+
parallel_dims: ParallelDims,
|
| 40 |
+
job_config: JobConfig,
|
| 41 |
+
):
|
| 42 |
+
"""
|
| 43 |
+
Apply tensor parallelism, activation checkpointing, torch.compile, and data
|
| 44 |
+
parallelism to the model.
|
| 45 |
+
|
| 46 |
+
NOTE: The passed-in model preferably should be on meta device. Otherwise,
|
| 47 |
+
the model must fit on GPU or CPU memory.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
if parallel_dims.tp_enabled:
|
| 51 |
+
if (
|
| 52 |
+
job_config.experimental.enable_async_tensor_parallel
|
| 53 |
+
and not job_config.training.compile
|
| 54 |
+
):
|
| 55 |
+
raise RuntimeError("Async TP requires --training.compile")
|
| 56 |
+
enable_float8_linear = "float8" in job_config.model.converters
|
| 57 |
+
apply_tp(
|
| 58 |
+
model,
|
| 59 |
+
world_mesh["tp"],
|
| 60 |
+
loss_parallel=parallel_dims.loss_parallel_enabled,
|
| 61 |
+
enable_float8=enable_float8_linear,
|
| 62 |
+
enable_async_tp=job_config.experimental.enable_async_tensor_parallel,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
if job_config.activation_checkpoint.mode != "none":
|
| 66 |
+
apply_ac(model, job_config.activation_checkpoint)
|
| 67 |
+
|
| 68 |
+
# turn on per-block compile after AC wrapping and before FSDP
|
| 69 |
+
if job_config.training.compile:
|
| 70 |
+
apply_compile(model)
|
| 71 |
+
|
| 72 |
+
if (
|
| 73 |
+
parallel_dims.dp_shard_enabled or parallel_dims.cp_enabled
|
| 74 |
+
): # apply FSDP or HSDP, potentially with Context Parallel
|
| 75 |
+
if parallel_dims.dp_replicate_enabled:
|
| 76 |
+
dp_mesh_dim_names = ("dp_replicate", "dp_shard_cp")
|
| 77 |
+
else:
|
| 78 |
+
dp_mesh_dim_names = ("dp_shard_cp",)
|
| 79 |
+
|
| 80 |
+
apply_fsdp(
|
| 81 |
+
model,
|
| 82 |
+
world_mesh[tuple(dp_mesh_dim_names)],
|
| 83 |
+
param_dtype=TORCH_DTYPE_MAP[job_config.training.mixed_precision_param],
|
| 84 |
+
reduce_dtype=TORCH_DTYPE_MAP[job_config.training.mixed_precision_reduce],
|
| 85 |
+
pp_enabled=parallel_dims.pp_enabled,
|
| 86 |
+
cpu_offload=job_config.training.enable_cpu_offload,
|
| 87 |
+
reshard_after_forward_policy=job_config.training.fsdp_reshard_after_forward,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if parallel_dims.dp_replicate_enabled:
|
| 91 |
+
logger.info("Applied HSDP to the model")
|
| 92 |
+
else:
|
| 93 |
+
logger.info("Applied FSDP to the model")
|
| 94 |
+
|
| 95 |
+
if parallel_dims.cp_enabled:
|
| 96 |
+
logger.info("Applied Context Parallel to the model")
|
| 97 |
+
|
| 98 |
+
if job_config.training.enable_cpu_offload:
|
| 99 |
+
logger.info("Applied CPU Offloading to the model")
|
| 100 |
+
elif parallel_dims.dp_replicate_enabled:
|
| 101 |
+
if world_mesh.ndim > 1:
|
| 102 |
+
raise RuntimeError("DDP has not supported > 1D parallelism")
|
| 103 |
+
apply_ddp(
|
| 104 |
+
model,
|
| 105 |
+
world_mesh,
|
| 106 |
+
enable_compile=job_config.training.compile,
|
| 107 |
+
enable_compiled_autograd=job_config.experimental.enable_compiled_autograd,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class TPPlan:
|
| 112 |
+
def __init__(
|
| 113 |
+
self,
|
| 114 |
+
model=None,
|
| 115 |
+
loss_parallel=False,
|
| 116 |
+
enable_float8=False,
|
| 117 |
+
):
|
| 118 |
+
self.model = model
|
| 119 |
+
self.loss_parallel = loss_parallel
|
| 120 |
+
self.enable_float8 = enable_float8
|
| 121 |
+
self.base_model_prefix = getattr(model, "base_model_prefix", "model")
|
| 122 |
+
|
| 123 |
+
# TODO(vkuzo): once float8 configuration supports delayed scaling,
|
| 124 |
+
# add a check here to enforce supported float8 all-gather configurations
|
| 125 |
+
# TODO(vkuzo): add the items below to __init__.py of torchao.float8 and import from there
|
| 126 |
+
try:
|
| 127 |
+
from torchao.float8.float8_tensor_parallel import (
|
| 128 |
+
Float8ColwiseParallel,
|
| 129 |
+
Float8RowwiseParallel,
|
| 130 |
+
PrepareFloat8ModuleInput
|
| 131 |
+
)
|
| 132 |
+
except ImportError:
|
| 133 |
+
Float8ColwiseParallel = None
|
| 134 |
+
Float8RowwiseParallel = None
|
| 135 |
+
PrepareFloat8ModuleInput = None
|
| 136 |
+
if self.enable_float8 and Float8ColwiseParallel is not None:
|
| 137 |
+
self.rowwise_parallel = Float8RowwiseParallel
|
| 138 |
+
self.colwise_parallel = Float8ColwiseParallel
|
| 139 |
+
self.prepare_module_input = PrepareFloat8ModuleInput
|
| 140 |
+
self.prepare_module_output = PrepareModuleOutput
|
| 141 |
+
else:
|
| 142 |
+
self.rowwise_parallel = RowwiseParallel
|
| 143 |
+
self.colwise_parallel = ColwiseParallel
|
| 144 |
+
self.prepare_module_input = PrepareModuleInput
|
| 145 |
+
self.prepare_module_output = PrepareModuleOutput
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def model_plan(self):
|
| 149 |
+
plans = {
|
| 150 |
+
f"{self.base_model_prefix}.embeddings": RowwiseParallel(
|
| 151 |
+
input_layouts=Replicate(),
|
| 152 |
+
output_layouts=Shard(1),
|
| 153 |
+
),
|
| 154 |
+
f"{self.base_model_prefix}.norm": SequenceParallel(),
|
| 155 |
+
}
|
| 156 |
+
if self.loss_parallel:
|
| 157 |
+
plans.update(
|
| 158 |
+
{
|
| 159 |
+
"lm_head": ColwiseParallel(
|
| 160 |
+
input_layouts=Shard(1),
|
| 161 |
+
output_layouts=Shard(-1) if self.loss_parallel else Replicate(),
|
| 162 |
+
use_local_output=not self.loss_parallel,
|
| 163 |
+
),
|
| 164 |
+
}
|
| 165 |
+
)
|
| 166 |
+
else:
|
| 167 |
+
plans.update(
|
| 168 |
+
{
|
| 169 |
+
"lm_head": PrepareModuleWeight(layouts=Replicate()),
|
| 170 |
+
"criterion": LinearLossParallel(),
|
| 171 |
+
}
|
| 172 |
+
)
|
| 173 |
+
return plans
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def layer_plan(self):
|
| 177 |
+
return {
|
| 178 |
+
"attn_norm": SequenceParallel(),
|
| 179 |
+
**self.attn_plan,
|
| 180 |
+
"mlp_norm": SequenceParallel(),
|
| 181 |
+
**self.mlp_plan,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def attn_plan(self):
|
| 186 |
+
raise NotImplementedError(
|
| 187 |
+
f"TP plans for token mixing layers of {self.model.config.model_type} not implemented"
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def mlp_plan(self):
|
| 192 |
+
return {
|
| 193 |
+
"mlp": self.prepare_module_input(
|
| 194 |
+
input_layouts=(Shard(1),),
|
| 195 |
+
desired_input_layouts=(Replicate(),),
|
| 196 |
+
),
|
| 197 |
+
"mlp.gate_proj": self.colwise_parallel(),
|
| 198 |
+
"mlp.up_proj": self.colwise_parallel(),
|
| 199 |
+
"mlp.down_proj": self.rowwise_parallel(output_layouts=Shard(1)),
|
| 200 |
+
"mlp.swiglu_linear": SwiGLULinearParallel(output_layouts=Shard(1)),
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class TransformerTPPlan(TPPlan):
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def attn_plan(self):
|
| 208 |
+
return {
|
| 209 |
+
"attn": self.prepare_module_input(
|
| 210 |
+
input_kwarg_layouts={"hidden_states": Shard(1)},
|
| 211 |
+
desired_input_kwarg_layouts={"hidden_states": Replicate()},
|
| 212 |
+
),
|
| 213 |
+
"attn.q_proj": self.colwise_parallel(),
|
| 214 |
+
"attn.k_proj": self.colwise_parallel(),
|
| 215 |
+
"attn.v_proj": self.colwise_parallel(),
|
| 216 |
+
"attn.o_proj": self.rowwise_parallel(output_layouts=Shard(1)),
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class GLATPPlan(TPPlan):
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def attn_plan(self):
|
| 224 |
+
return {
|
| 225 |
+
"attn": self.prepare_module_input(
|
| 226 |
+
input_kwarg_layouts={"hidden_states": Shard(1)},
|
| 227 |
+
desired_input_kwarg_layouts={"hidden_states": Replicate()},
|
| 228 |
+
),
|
| 229 |
+
"attn.q_proj": self.colwise_parallel(),
|
| 230 |
+
"attn.k_proj": self.colwise_parallel(),
|
| 231 |
+
"attn.v_proj": self.colwise_parallel(),
|
| 232 |
+
"attn.g_proj": self.colwise_parallel(),
|
| 233 |
+
"attn.gk_proj.0": PrepareModuleWeight(layouts=Replicate()),
|
| 234 |
+
"attn.gk_proj.1": self.colwise_parallel(),
|
| 235 |
+
"attn.g_norm": SequenceParallel(sequence_dim=-1),
|
| 236 |
+
"attn.o_proj": self.rowwise_parallel(output_layouts=Shard(1)),
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
TP_PLAN_MAP = {"transformer": TransformerTPPlan, "gla": GLATPPlan}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def apply_tp(
|
| 244 |
+
model: nn.Module,
|
| 245 |
+
tp_mesh: DeviceMesh,
|
| 246 |
+
loss_parallel: bool,
|
| 247 |
+
enable_float8: bool,
|
| 248 |
+
enable_async_tp: bool,
|
| 249 |
+
):
|
| 250 |
+
"""Apply tensor parallelism."""
|
| 251 |
+
# 1. Parallelize the embedding and shard its outputs (which are the first
|
| 252 |
+
# transformer block's inputs)
|
| 253 |
+
# 2. Parallelize the root norm layer over the sequence dim
|
| 254 |
+
# 3. Parallelize the final linear output layer
|
| 255 |
+
tp_plan = TP_PLAN_MAP[model.config.model_type](
|
| 256 |
+
model, loss_parallel=loss_parallel, enable_float8=enable_float8
|
| 257 |
+
)
|
| 258 |
+
parallelize_module(model, tp_mesh, tp_plan.model_plan)
|
| 259 |
+
|
| 260 |
+
blocks = get_blocks(model)
|
| 261 |
+
if blocks is None:
|
| 262 |
+
logger.warning("No block found for tensor parallelism")
|
| 263 |
+
else:
|
| 264 |
+
for _, block in enumerate(blocks):
|
| 265 |
+
parallelize_module(
|
| 266 |
+
module=block,
|
| 267 |
+
device_mesh=tp_mesh,
|
| 268 |
+
parallelize_plan=tp_plan.layer_plan,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
if enable_async_tp:
|
| 272 |
+
from torch.distributed._symmetric_memory import enable_symm_mem_for_group
|
| 273 |
+
|
| 274 |
+
torch._inductor.config._micro_pipeline_tp = True
|
| 275 |
+
enable_symm_mem_for_group(tp_mesh.get_group().group_name)
|
| 276 |
+
|
| 277 |
+
logger.info(
|
| 278 |
+
f"Applied {'Float8 ' if enable_float8 else ''}{'Async ' if enable_async_tp else ''}"
|
| 279 |
+
"Tensor Parallelism to the model"
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# for selective op activation checkpointing
|
| 284 |
+
_save_list = {
|
| 285 |
+
torch.ops.aten.mm.default,
|
| 286 |
+
torch.ops.aten._scaled_dot_product_efficient_attention.default,
|
| 287 |
+
torch.ops.aten._scaled_dot_product_flash_attention.default,
|
| 288 |
+
torch.ops._c10d_functional.reduce_scatter_tensor.default,
|
| 289 |
+
# for low precision training, it's useful to always save
|
| 290 |
+
# the result of max, since the absolute maximum is
|
| 291 |
+
# used to compute the scaling factor for quantization.
|
| 292 |
+
torch.ops.aten.max.default,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _apply_ac_to_block(module: nn.Module, ac_config):
|
| 297 |
+
valid_ac_modes = ("full", "selective")
|
| 298 |
+
if ac_config.mode not in valid_ac_modes:
|
| 299 |
+
raise ValueError(
|
| 300 |
+
f"Invalid AC mode: {ac_config.mode}. Valid modes: {valid_ac_modes}"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
if ac_config.mode == "full":
|
| 304 |
+
return ptd_checkpoint_wrapper(module, preserve_rng_state=False)
|
| 305 |
+
|
| 306 |
+
assert ac_config.mode == "selective", f"{ac_config.mode}"
|
| 307 |
+
use_op_sac = ac_config.selective_ac_option == "op"
|
| 308 |
+
use_layer_sac = ac_config.selective_ac_option.isdigit()
|
| 309 |
+
if not use_op_sac and not use_layer_sac:
|
| 310 |
+
raise ValueError(
|
| 311 |
+
f"Invalid selective AC option: {ac_config.selective_ac_option}. "
|
| 312 |
+
f"Valid options: 'op' or a positive int representing layer frequency"
|
| 313 |
+
)
|
| 314 |
+
if use_op_sac:
|
| 315 |
+
from torch.utils.checkpoint import CheckpointPolicy, create_selective_checkpoint_contexts
|
| 316 |
+
|
| 317 |
+
def _get_custom_policy(meta):
|
| 318 |
+
def _custom_policy(ctx, func, *args, **kwargs):
|
| 319 |
+
mode = "recompute" if ctx.is_recompute else "forward"
|
| 320 |
+
mm_count_key = f"{mode}_mm_count"
|
| 321 |
+
if func == torch.ops.aten.mm.default:
|
| 322 |
+
meta[mm_count_key] += 1
|
| 323 |
+
# Saves output of all compute ops, except every second mm
|
| 324 |
+
to_save = func in _save_list and not (
|
| 325 |
+
func == torch.ops.aten.mm.default and meta[mm_count_key] % 2 == 0
|
| 326 |
+
)
|
| 327 |
+
return (
|
| 328 |
+
CheckpointPolicy.MUST_SAVE
|
| 329 |
+
if to_save
|
| 330 |
+
else CheckpointPolicy.PREFER_RECOMPUTE
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
return _custom_policy
|
| 334 |
+
|
| 335 |
+
def selective_checkpointing_context_fn():
|
| 336 |
+
meta = defaultdict(int)
|
| 337 |
+
return create_selective_checkpoint_contexts(_get_custom_policy(meta))
|
| 338 |
+
|
| 339 |
+
return ptd_checkpoint_wrapper(
|
| 340 |
+
module,
|
| 341 |
+
context_fn=selective_checkpointing_context_fn,
|
| 342 |
+
preserve_rng_state=False,
|
| 343 |
+
)
|
| 344 |
+
elif use_layer_sac:
|
| 345 |
+
# Checkpoint every `ac_freq` of the modules passed to this function
|
| 346 |
+
ac_freq = int(ac_config.selective_ac_option)
|
| 347 |
+
ptd_checkpoint_wrapper.__dict__.setdefault("_count", 0)
|
| 348 |
+
ptd_checkpoint_wrapper._count += 1
|
| 349 |
+
if not ac_freq or ptd_checkpoint_wrapper._count % ac_freq == 0:
|
| 350 |
+
return ptd_checkpoint_wrapper(module, preserve_rng_state=False)
|
| 351 |
+
else:
|
| 352 |
+
return module
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def apply_ac(model: nn.Module, ac_config):
|
| 356 |
+
"""Apply activation checkpointing to the model."""
|
| 357 |
+
blocks = get_blocks(model)
|
| 358 |
+
if blocks is None:
|
| 359 |
+
logger.warning("No block found for activation checkpointing")
|
| 360 |
+
return
|
| 361 |
+
|
| 362 |
+
for layer_id, block in blocks.named_children():
|
| 363 |
+
block = _apply_ac_to_block(block, ac_config)
|
| 364 |
+
blocks.register_module(layer_id, block)
|
| 365 |
+
|
| 366 |
+
logger.info(f"Applied {ac_config.mode} activation checkpointing to the model")
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def apply_compile(model: nn.Module):
|
| 370 |
+
"""
|
| 371 |
+
Apply torch.compile to each block, which makes compilation efficient due to
|
| 372 |
+
repeated structure. Alternatively one can compile the whole model (after applying DP).
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
blocks = get_blocks(model)
|
| 376 |
+
if blocks is None:
|
| 377 |
+
logger.warning("No block found for torch.compile")
|
| 378 |
+
else:
|
| 379 |
+
for layer_id, block in blocks.named_children():
|
| 380 |
+
block = torch.compile(block)
|
| 381 |
+
blocks.register_module(layer_id, block)
|
| 382 |
+
logger.info("Compiling each block with torch.compile")
|
| 383 |
+
|
| 384 |
+
real_model = get_model(model)
|
| 385 |
+
|
| 386 |
+
logger.info("Compiling the embedding, norm, and lm_head layers with torch.compile")
|
| 387 |
+
embeddings_key = get_components_name(real_model, "tok_embeddings")
|
| 388 |
+
if embeddings_key is not None:
|
| 389 |
+
embeddings = torch.compile(getattr(real_model, embeddings_key), fullgraph=True)
|
| 390 |
+
real_model.register_module(embeddings_key, embeddings)
|
| 391 |
+
|
| 392 |
+
norm_key = get_components_name(real_model, "norm")
|
| 393 |
+
if norm_key is not None:
|
| 394 |
+
norm = torch.compile(getattr(real_model, norm_key), fullgraph=True)
|
| 395 |
+
real_model.register_module(norm_key, norm)
|
| 396 |
+
|
| 397 |
+
lm_head_key = get_components_name(model, "lm_head")
|
| 398 |
+
if lm_head_key is not None:
|
| 399 |
+
lm_head = torch.compile(getattr(model, lm_head_key), fullgraph=True)
|
| 400 |
+
model.register_module(lm_head_key, lm_head)
|
| 401 |
+
|
| 402 |
+
logger.info("Compiling the entire model with torch.compile")
|
| 403 |
+
model = torch.compile(model)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def apply_fsdp(
|
| 407 |
+
model: nn.Module,
|
| 408 |
+
dp_mesh: DeviceMesh,
|
| 409 |
+
param_dtype: torch.dtype,
|
| 410 |
+
reduce_dtype: torch.dtype,
|
| 411 |
+
pp_enabled: bool,
|
| 412 |
+
cpu_offload: bool = False,
|
| 413 |
+
reshard_after_forward_policy: str = "default",
|
| 414 |
+
):
|
| 415 |
+
"""
|
| 416 |
+
Apply data parallelism (via FSDP2) to the model.
|
| 417 |
+
|
| 418 |
+
Args:
|
| 419 |
+
model (nn.Module): The model to apply data parallelism to.
|
| 420 |
+
dp_mesh (DeviceMesh): The device mesh to use for data parallelism.
|
| 421 |
+
param_dtype (torch.dtype): The data type to use for model parameters.
|
| 422 |
+
reduce_dtype (torch.dtype): The data type to use for reduction operations.
|
| 423 |
+
pp_enabled (bool): Whether pipeline parallelism is enabled.
|
| 424 |
+
cpu_offload (bool, optional): Whether to offload model parameters to CPU. Defaults to False.
|
| 425 |
+
reshard_after_forward_policy (str, optional):
|
| 426 |
+
The policy to use for resharding after forward pass. Defaults to "default".
|
| 427 |
+
Other options: "never", "always".
|
| 428 |
+
- "default" applies default resharding behavior, implementing "smart defaults" for known optimal scenarios.
|
| 429 |
+
- "always" will enable `reshard_after_forward` for all forward passes.
|
| 430 |
+
- "never" will disable `reshard_after_forward` for all forward passes.
|
| 431 |
+
|
| 432 |
+
"""
|
| 433 |
+
mp_policy = MixedPrecisionPolicy(param_dtype=param_dtype, reduce_dtype=reduce_dtype)
|
| 434 |
+
fsdp_config = {"mesh": dp_mesh, "mp_policy": mp_policy}
|
| 435 |
+
if cpu_offload:
|
| 436 |
+
fsdp_config["offload_policy"] = CPUOffloadPolicy()
|
| 437 |
+
|
| 438 |
+
blocks = get_blocks(model)
|
| 439 |
+
if blocks is None:
|
| 440 |
+
logger.warning("No block found for FSDP")
|
| 441 |
+
else:
|
| 442 |
+
total_blocks = len(blocks)
|
| 443 |
+
for layer_id, block in enumerate(blocks):
|
| 444 |
+
if reshard_after_forward_policy == "always":
|
| 445 |
+
reshard_after_forward = True
|
| 446 |
+
elif reshard_after_forward_policy == "never":
|
| 447 |
+
reshard_after_forward = False
|
| 448 |
+
elif reshard_after_forward_policy == "default":
|
| 449 |
+
if pp_enabled:
|
| 450 |
+
# For PP, do not reshard after forward to avoid per-microbatch
|
| 451 |
+
# all-gathers, which can be expensive and non-overlapped
|
| 452 |
+
reshard_after_forward = False
|
| 453 |
+
else:
|
| 454 |
+
# As an optimization, do not reshard after forward for the last
|
| 455 |
+
# transformer block since FSDP would prefetch it immediately
|
| 456 |
+
reshard_after_forward = int(layer_id) < total_blocks - 1
|
| 457 |
+
else:
|
| 458 |
+
raise ValueError(
|
| 459 |
+
f"Invalid reshard_after_forward_policy: {reshard_after_forward_policy}."
|
| 460 |
+
)
|
| 461 |
+
fully_shard(
|
| 462 |
+
block,
|
| 463 |
+
**fsdp_config,
|
| 464 |
+
reshard_after_forward=reshard_after_forward,
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
fully_shard(model, **fsdp_config, reshard_after_forward=not pp_enabled)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def apply_ddp(
|
| 471 |
+
model: nn.Module,
|
| 472 |
+
dp_mesh: DeviceMesh,
|
| 473 |
+
enable_compile: bool,
|
| 474 |
+
enable_compiled_autograd: bool,
|
| 475 |
+
):
|
| 476 |
+
if enable_compile:
|
| 477 |
+
if enable_compiled_autograd:
|
| 478 |
+
torch._dynamo.config.optimize_ddp = (
|
| 479 |
+
"python_reducer_without_compiled_forward"
|
| 480 |
+
)
|
| 481 |
+
else:
|
| 482 |
+
torch._dynamo.config.optimize_ddp = "ddp_optimizer"
|
| 483 |
+
|
| 484 |
+
replicate(model, device_mesh=dp_mesh, bucket_cap_mb=100)
|
| 485 |
+
|
| 486 |
+
logger.info("Applied DDP to the model")
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def get_model(model):
|
| 490 |
+
base_model_prefix = getattr(model, "base_model_prefix", "model")
|
| 491 |
+
if not hasattr(model, base_model_prefix):
|
| 492 |
+
return None
|
| 493 |
+
model = getattr(model, base_model_prefix)
|
| 494 |
+
return model
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def get_blocks(model):
|
| 498 |
+
# TODO[flame]: adapt for network not using 'layers' attribute
|
| 499 |
+
model = get_model(model)
|
| 500 |
+
if not hasattr(model, "layers"):
|
| 501 |
+
logger.warning('no "layers" in model can be found')
|
| 502 |
+
return None
|
| 503 |
+
return model.layers
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def get_components_name(model, component_name):
|
| 507 |
+
"""
|
| 508 |
+
We try to catch tok_embeddings, norm layers and lm_head layers
|
| 509 |
+
We do not catch the layer names in the blocks, for blocks see `get_blocks`
|
| 510 |
+
We assume the model has the following structure:
|
| 511 |
+
LlamaForCausalLM:
|
| 512 |
+
Model:
|
| 513 |
+
embed_tokens,
|
| 514 |
+
layers,
|
| 515 |
+
norm,
|
| 516 |
+
lm_head
|
| 517 |
+
***
|
| 518 |
+
so, to search 'tok_embeddings' and 'norm' we need to pass `get_model(model)`
|
| 519 |
+
and for 'lm_head' we need to pass `model`
|
| 520 |
+
***
|
| 521 |
+
"""
|
| 522 |
+
|
| 523 |
+
if component_name == "tok_embeddings":
|
| 524 |
+
if hasattr(model, "tok_embeddings"):
|
| 525 |
+
return "tok_embeddings"
|
| 526 |
+
elif hasattr(model, "embed_tokens"):
|
| 527 |
+
return "embed_tokens"
|
| 528 |
+
elif hasattr(model, "embeddings"):
|
| 529 |
+
return "embeddings"
|
| 530 |
+
else:
|
| 531 |
+
logger.warning("No tok_embeddings found in model")
|
| 532 |
+
return None
|
| 533 |
+
|
| 534 |
+
elif component_name == "norm":
|
| 535 |
+
if hasattr(model, "norm"):
|
| 536 |
+
return "norm"
|
| 537 |
+
elif hasattr(model, "norms"):
|
| 538 |
+
return "norms"
|
| 539 |
+
elif hasattr(model, "layernorm"):
|
| 540 |
+
return "layernorm"
|
| 541 |
+
else:
|
| 542 |
+
logger.warning("No norm found in model")
|
| 543 |
+
return None
|
| 544 |
+
|
| 545 |
+
elif component_name == "lm_head":
|
| 546 |
+
if hasattr(model, "lm_head"):
|
| 547 |
+
return "lm_head"
|
| 548 |
+
else:
|
| 549 |
+
logger.warning("No lm_head found in model")
|
| 550 |
+
return None
|
batch1.seqlen32768.bs32.warmup1024.update1.steps4.lr1e-3.cosine.1gpu/flame/models/pipeline_fla.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
# This file applies the PT-D pipeline parallelism to the Llama model.
|
| 8 |
+
|
| 9 |
+
import copy
|
| 10 |
+
from typing import Callable, Optional, Union
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch.distributed import DeviceMesh
|
| 15 |
+
from torch.distributed.pipelining import PipelineStage
|
| 16 |
+
from torch.distributed.pipelining.schedules import ScheduleZBVZeroBubble, _PipelineSchedule, get_schedule_class
|
| 17 |
+
from transformers import PretrainedConfig
|
| 18 |
+
|
| 19 |
+
from flame.models.parallelize_fla import get_blocks, get_components_name, get_model
|
| 20 |
+
from torchtitan.config_manager import JobConfig
|
| 21 |
+
from torchtitan.distributed.parallel_dims import ParallelDims
|
| 22 |
+
from torchtitan.distributed.pipeline import build_pipeline_schedule, generate_split_points, stage_ids_this_rank
|
| 23 |
+
from torchtitan.tools.logging import logger
|
| 24 |
+
|
| 25 |
+
DeviceType = Union[int, str, torch.device]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def pipeline_fla(
|
| 29 |
+
model: nn.Module,
|
| 30 |
+
pp_mesh: DeviceMesh,
|
| 31 |
+
parallel_dims: ParallelDims,
|
| 32 |
+
job_config: JobConfig,
|
| 33 |
+
device: DeviceType,
|
| 34 |
+
model_config: PretrainedConfig,
|
| 35 |
+
loss_fn: Callable[..., torch.Tensor],
|
| 36 |
+
) -> tuple[_PipelineSchedule, list[nn.Module], bool, bool]:
|
| 37 |
+
stages, models = pipeline_fla_manual_split(
|
| 38 |
+
model, pp_mesh, parallel_dims, job_config, device, model_config
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
pp_schedule = build_pipeline_schedule(job_config, stages, loss_fn)
|
| 42 |
+
|
| 43 |
+
# This is used in the train loop to determine whether to pass in the input_ids and labels
|
| 44 |
+
has_first_stage = False
|
| 45 |
+
has_last_stage = False
|
| 46 |
+
for stage in stages:
|
| 47 |
+
if stage.is_first:
|
| 48 |
+
has_first_stage = True
|
| 49 |
+
if stage.is_last:
|
| 50 |
+
has_last_stage = True
|
| 51 |
+
|
| 52 |
+
return pp_schedule, models, has_first_stage, has_last_stage
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def pipeline_fla_manual_split(
|
| 56 |
+
whole_model: nn.Module,
|
| 57 |
+
pp_mesh: DeviceMesh,
|
| 58 |
+
parallel_dims: ParallelDims,
|
| 59 |
+
job_config: JobConfig,
|
| 60 |
+
device: DeviceType,
|
| 61 |
+
model_config: PretrainedConfig,
|
| 62 |
+
) -> tuple[list[PipelineStage], list[nn.Module]]:
|
| 63 |
+
"""
|
| 64 |
+
This API extracts one torch.nn.Module objects for the part of the model configured to run inside this stage.
|
| 65 |
+
|
| 66 |
+
It wraps the model chunk in a ManualPipelineStage object and returns both the stage and model objects.
|
| 67 |
+
|
| 68 |
+
The stage object is used to create a pipeline schedule, and the model object can be used for applying SPMD
|
| 69 |
+
parallelism.
|
| 70 |
+
"""
|
| 71 |
+
pp_rank = pp_mesh.get_local_rank()
|
| 72 |
+
pp_size = pp_mesh.size()
|
| 73 |
+
|
| 74 |
+
splits = (
|
| 75 |
+
job_config.experimental.pipeline_parallel_split_points
|
| 76 |
+
or generate_split_points(
|
| 77 |
+
job_config, parallel_dims.pp, model_config.num_hidden_layers
|
| 78 |
+
)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def _build_stage(
|
| 82 |
+
stage_idx: int,
|
| 83 |
+
start_layer: Optional[str],
|
| 84 |
+
stop_layer: Optional[str],
|
| 85 |
+
is_first: bool = False,
|
| 86 |
+
is_last: bool = False,
|
| 87 |
+
) -> tuple[PipelineStage, nn.Module]:
|
| 88 |
+
model = copy.deepcopy(whole_model)
|
| 89 |
+
if not is_first:
|
| 90 |
+
# we do `model.tok_embeddings = None` here
|
| 91 |
+
real_model = get_model(model)
|
| 92 |
+
tok_embeddings_name = get_components_name(real_model, "tok_embeddings")
|
| 93 |
+
setattr(real_model, tok_embeddings_name, None)
|
| 94 |
+
|
| 95 |
+
drop_layers = start_layer is not None
|
| 96 |
+
# Get module dictionary from get_blocks(model)
|
| 97 |
+
# and Create a list of keys before modifying dictionary
|
| 98 |
+
module_dict = get_blocks(model)._modules # Store reference
|
| 99 |
+
layer_names = list(module_dict.keys())
|
| 100 |
+
|
| 101 |
+
# Iterate over the list of keys instead of `_modules.items()`
|
| 102 |
+
for name in layer_names:
|
| 103 |
+
# Dynamically determine prefix (blocks.* or layers.*)
|
| 104 |
+
prefix = start_layer.split(".")[0] if start_layer else "layers"
|
| 105 |
+
layer_name = f"{prefix}.{name}" # Construct the correct name format
|
| 106 |
+
|
| 107 |
+
# Ensure `drop_layers` activation is based on actual naming
|
| 108 |
+
if layer_name == start_layer:
|
| 109 |
+
drop_layers = False
|
| 110 |
+
if layer_name == stop_layer:
|
| 111 |
+
drop_layers = True
|
| 112 |
+
|
| 113 |
+
# Delete layer if drop_layers is active
|
| 114 |
+
if drop_layers:
|
| 115 |
+
del module_dict[name] # Safe deletion from stored dictionary
|
| 116 |
+
|
| 117 |
+
if not is_last:
|
| 118 |
+
# we do `model.norm = None` and `model.output = None`
|
| 119 |
+
real_model = get_model(model)
|
| 120 |
+
norm_name = get_components_name(real_model, "norm")
|
| 121 |
+
setattr(real_model, norm_name, None)
|
| 122 |
+
|
| 123 |
+
head_name = get_components_name(model, "lm_head")
|
| 124 |
+
setattr(model, head_name, None)
|
| 125 |
+
|
| 126 |
+
stage = PipelineStage(
|
| 127 |
+
model,
|
| 128 |
+
stage_idx,
|
| 129 |
+
num_stages,
|
| 130 |
+
device,
|
| 131 |
+
group=pp_mesh.get_group("pp"),
|
| 132 |
+
)
|
| 133 |
+
return stage, model
|
| 134 |
+
|
| 135 |
+
num_stages = len(splits) + 1
|
| 136 |
+
stage_idx = pp_rank
|
| 137 |
+
|
| 138 |
+
stages = []
|
| 139 |
+
models = []
|
| 140 |
+
|
| 141 |
+
schedule_class = get_schedule_class(
|
| 142 |
+
job_config.experimental.pipeline_parallel_schedule
|
| 143 |
+
)
|
| 144 |
+
style = "v" if schedule_class == ScheduleZBVZeroBubble else "loop"
|
| 145 |
+
|
| 146 |
+
for stage_idx in stage_ids_this_rank(pp_rank, pp_size, num_stages, style=style):
|
| 147 |
+
start_layer = splits[stage_idx - 1] if stage_idx > 0 else None
|
| 148 |
+
stop_layer = splits[stage_idx] if stage_idx < num_stages - 1 else None
|
| 149 |
+
stage, model_chunk = _build_stage(
|
| 150 |
+
stage_idx,
|
| 151 |
+
start_layer,
|
| 152 |
+
stop_layer,
|
| 153 |
+
is_first=stage_idx == 0,
|
| 154 |
+
is_last=stage_idx == num_stages - 1,
|
| 155 |
+
)
|
| 156 |
+
logger.info(
|
| 157 |
+
f"PP rank {pp_rank} is building stage_idx {stage_idx}"
|
| 158 |
+
f" with start_layer {start_layer}, stop_layer {stop_layer}"
|
| 159 |
+
)
|
| 160 |
+
stages.append(stage)
|
| 161 |
+
models.append(model_chunk)
|
| 162 |
+
return stages, models
|