Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- playground/Abbie-h100/old/trainer/dense_trainer.py +325 -0
- playground/Abbie-h100/old/trainer/gargantua2_trainer.py +345 -0
- playground/Abbie-h100/old/trainer/helper.py +57 -0
- playground/Abbie-h100/old/trainer/moe_trainer.py +250 -0
- playground/Abbie-h100/old/trainer/template/1b2.yaml +6 -0
- playground/Abbie-h100/old/trainer/template/32b.yaml +6 -0
- playground/Abbie-h100/old/trainer/template/93b.yaml +6 -0
- playground/Abbie-h100/old/trainer/template/moe_30b.yaml +9 -0
- playground/Abbie-h100/old/trainer/utils.py +45 -0
- playground/Abbie-h100/tests/__init__.py +0 -0
- playground/Abbie-h100/tests/bench_qwen2.py +299 -0
- playground/Abbie-h100/tests/bench_transformer_layer.py +383 -0
- playground/Abbie-h100/tests/close_check.py +45 -0
- playground/Abbie-h100/tests/pipe_compare.py +306 -0
- playground/Abbie-h100/tests/shard_parquet.py +62 -0
- playground/Abbie-h100/tests/shared/__init__.py +0 -0
- playground/Abbie-h100/tests/shared/download.sh +23 -0
- playground/Abbie-h100/tests/shared/moe_route.py +115 -0
- playground/Abbie-h100/tests/shared/optimizer.py +103 -0
- playground/Abbie-h100/tests/shared/preparation.py +364 -0
- playground/Abbie-h100/tests/test_aux_loss.py +124 -0
- playground/Abbie-h100/tests/test_dense_baseline.py +138 -0
- playground/Abbie-h100/tests/test_dense_gargantua.py +166 -0
- playground/Abbie-h100/tests/test_dense_mlp.py +123 -0
- playground/Abbie-h100/tests/test_gemm.py +47 -0
- playground/Abbie-h100/tests/test_moe_gargantua.py +187 -0
- playground/Abbie-h100/tests/test_moe_gating.py +90 -0
- playground/Abbie-h100/tests/test_moe_mlp.py +142 -0
- playground/Abbie-h100/tests/test_moe_route.py +162 -0
- playground/Abbie-h100/tests/test_qwen2_layer.py +215 -0
- playground/Abbie-h100/tests/test_qwen3_moe_layer.py +383 -0
- playground/Abbie-h100/tests/test_swiglu.py +129 -0
- playground/Abbie-h100/tests/test_ulysses.py +92 -0
- playground/Abbie-h100/tests/utils.py +38 -0
- playground/Abbie-h100/torchrun/run_dense_pp_and_dp.sh +18 -0
- playground/Abbie-h100/torchrun/run_dense_pure_dp.sh +17 -0
- playground/Abbie-h100/torchrun/run_moe_pp.sh +1 -0
- playground/Abbie-h100/torchrun/run_moe_pure_dp.sh +1 -0
- playground/Abbie-h100/torchrun/torch_sanity.py +14 -0
- playground/Abbie-h100/torchrun/torchrun_dense_gargantua_ckpt.py +250 -0
- playground/Abbie-h100/torchrun/torchrun_dualpipe_moe_v.py +196 -0
- playground/Abbie-h100/torchrun/torchrun_dualpipe_moe_v_ckpt.py +310 -0
- playground/Abbie-h100/torchrun/torchrun_moe_gargantua.py +151 -0
- playground/Abbie-h100/torchrun/torchrun_moe_gargantua_ckpt.py +214 -0
- playground/Abbie-h100/trainer_configs/trainer_base.yaml +108 -0
- playground/Abbie-h100/trainer_configs/trainer_tivila.yaml +15 -0
- playground/Abbie-h100/trainer_utils/__init__.py +0 -0
- playground/Abbie-h100/trainer_utils/common.py +120 -0
- playground/Abbie-h100/trainer_utils/dataloader.py +285 -0
- playground/Abbie-h100/trainer_utils/thothvl_transform.py +656 -0
playground/Abbie-h100/old/trainer/dense_trainer.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from datetime import timedelta
|
| 5 |
+
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from contextlib import nullcontext
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.distributed as dist
|
| 11 |
+
|
| 12 |
+
from einops import rearrange
|
| 13 |
+
|
| 14 |
+
from checkpoint.gargantua_ckpt import DenseCheckpointer
|
| 15 |
+
from dualpipe.log import WandbLogger
|
| 16 |
+
|
| 17 |
+
from dualpipe.module.shared.loss import preprocess_labels, criterion
|
| 18 |
+
from trainer.cli import parse_args
|
| 19 |
+
from trainer.helper import resume_from_sahara_ckpt
|
| 20 |
+
from trainer.utils import (
|
| 21 |
+
load_config,
|
| 22 |
+
make_handler,
|
| 23 |
+
collect_scalars_across_data_parallel_group
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# set_deterministic(42, False)
|
| 27 |
+
|
| 28 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 29 |
+
from dualpipe.module.trainer_builder import build_dense_trainer
|
| 30 |
+
|
| 31 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/Abbie/profiles'
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class DenseTrainer:
|
| 35 |
+
def __init__(self, rank, local_rank, world_size, args):
|
| 36 |
+
print(f"Loading from path: {args.model}")
|
| 37 |
+
cfg = load_config(args.model)
|
| 38 |
+
self.rank = rank
|
| 39 |
+
self.local_rank = local_rank
|
| 40 |
+
self.world_size = world_size
|
| 41 |
+
self.args = args
|
| 42 |
+
self.cfg = cfg
|
| 43 |
+
|
| 44 |
+
def start(self):
|
| 45 |
+
assert self.args.pp_size >= 1, 'pp_size shall be true positive value'
|
| 46 |
+
# override checking
|
| 47 |
+
inner = self.args.inner if self.args.inner is not None else self.cfg.inner
|
| 48 |
+
layer_number = self.args.layer_number if self.args.layer_number is not None else self.cfg.layer_number
|
| 49 |
+
attention_dropout = self.args.attention_dropout if self.args.attention_dropout is not None else self.cfg.attention_dropout
|
| 50 |
+
residual_dropout = self.args.residual_dropout if self.args.residual_dropout is not None else self.cfg.residual_dropout
|
| 51 |
+
|
| 52 |
+
if self.args.enable_profiler:
|
| 53 |
+
assert self.args.profiler_step is not None and self.args.profiler_step > 0, \
|
| 54 |
+
'Setting up profiler without profiler step is not allowed'
|
| 55 |
+
self._do_start(
|
| 56 |
+
self.rank, self.local_rank, self.world_size,
|
| 57 |
+
experiment_name=self.args.trial_name,
|
| 58 |
+
train_home_path=self.args.train_home_path,
|
| 59 |
+
pp_size = self.args.pp_size,
|
| 60 |
+
tokenizer_path=self.args.tokenizer,
|
| 61 |
+
pad_idx = self.args.pad_idx,
|
| 62 |
+
vocab_size = self.args.vocab_size,
|
| 63 |
+
train_dataset = self.args.train_dataset,
|
| 64 |
+
train_size = self.args.train_size,
|
| 65 |
+
warmup_batch_ratio = self.args.warmup_batch_ratio,
|
| 66 |
+
seq_len = self.args.max_seq_len,
|
| 67 |
+
max_position_embeddings = self.args.max_position_embeddings,
|
| 68 |
+
stride = self.args.stride,
|
| 69 |
+
resume_ckpt_path = None,
|
| 70 |
+
resume_ckpt_step=self.args.resume_ckpt_step,
|
| 71 |
+
gbs = self.args.global_batch_size,
|
| 72 |
+
micro_batch_size = self.args.micro_batch_size,
|
| 73 |
+
layer_number = layer_number,
|
| 74 |
+
hidden_size=self.cfg.hidden_size,
|
| 75 |
+
inner=inner,
|
| 76 |
+
num_attention_head = self.cfg.num_attention_head,
|
| 77 |
+
num_shared_qheads=self.args.num_shared_qheads,
|
| 78 |
+
attention_dropout = attention_dropout,
|
| 79 |
+
residual_dropout = residual_dropout,
|
| 80 |
+
lr_max=self.args.lr_max,
|
| 81 |
+
lr_min=self.args.lr_min,
|
| 82 |
+
lr_weight_decay=self.args.lr_weight_decay,
|
| 83 |
+
lr_warmup_step_rate=self.args.lr_warmup_step_rate,
|
| 84 |
+
enable_profiler = self.args.enable_profiler,
|
| 85 |
+
profiler_step = self.args.profiler_step,
|
| 86 |
+
ckpt_every_n_step = self.args.ckpt_every_n_step,
|
| 87 |
+
resume_from_sahara = self.args.resume_from_sahara)
|
| 88 |
+
|
| 89 |
+
def _do_start(self,
|
| 90 |
+
rank, local_rank, world_size,
|
| 91 |
+
experiment_name, train_home_path,
|
| 92 |
+
pp_size: int,
|
| 93 |
+
tokenizer_path: str, pad_idx: int,
|
| 94 |
+
vocab_size: int, train_dataset: str, train_size: int, warmup_batch_ratio: float,
|
| 95 |
+
seq_len: int, max_position_embeddings: int, stride: int,
|
| 96 |
+
resume_ckpt_path: Optional[str], resume_ckpt_step: Optional[int],
|
| 97 |
+
gbs: int, micro_batch_size: int,
|
| 98 |
+
layer_number: int,
|
| 99 |
+
hidden_size: int, inner: int, num_attention_head: int, num_shared_qheads: Optional[int],
|
| 100 |
+
attention_dropout: float, residual_dropout: float,
|
| 101 |
+
lr_max: float, lr_min: float, lr_weight_decay: float, lr_warmup_step_rate: float,
|
| 102 |
+
enable_profiler: bool, profiler_step: Optional[int], ckpt_every_n_step: Optional[int], resume_from_sahara: Optional[str]):
|
| 103 |
+
epoch = 1
|
| 104 |
+
# set_deterministic(1234, False)
|
| 105 |
+
torch.manual_seed(1234)
|
| 106 |
+
|
| 107 |
+
assert world_size % pp_size == 0
|
| 108 |
+
assert gbs % micro_batch_size == 0, "global_batch_size shall be able to be divide up by micro_batch_size"
|
| 109 |
+
dp_size = world_size // pp_size
|
| 110 |
+
gbs = gbs // dp_size
|
| 111 |
+
|
| 112 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=world_size, rank=rank)
|
| 113 |
+
print(f"[Rank-{rank}] caliberating gbs to {gbs}, dp to {dp_size}, ")
|
| 114 |
+
|
| 115 |
+
device = f'cuda:{local_rank}'
|
| 116 |
+
dtype = torch.bfloat16
|
| 117 |
+
|
| 118 |
+
db_logger = WandbLogger(rank, None, experiment_name)
|
| 119 |
+
group = dist.distributed_c10d._get_default_group()
|
| 120 |
+
world_size = group.size()
|
| 121 |
+
|
| 122 |
+
rank_generator, layer, train_dataloader, optimizers = build_dense_trainer(
|
| 123 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 124 |
+
epoch_number=epoch,
|
| 125 |
+
train_path=train_dataset, train_size=train_size,
|
| 126 |
+
val_path="invalid", val_size=-1, # TODO [yuyifeng.oscar] pending for validation integration
|
| 127 |
+
warmup_step_rate=warmup_batch_ratio,
|
| 128 |
+
tokenizer_path=tokenizer_path, pad_idx=pad_idx,
|
| 129 |
+
global_batch_size=gbs, micro_batch_size=micro_batch_size,
|
| 130 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 131 |
+
lr_max=lr_max, lr_min=lr_min, weight_decay=lr_weight_decay, lr_warmup_step_rate=lr_warmup_step_rate,
|
| 132 |
+
dp_size=dp_size, pp_size=pp_size,
|
| 133 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size, inner=inner,
|
| 134 |
+
num_attention_head=num_attention_head, num_shared_qheads=num_shared_qheads,
|
| 135 |
+
attention_dropout=attention_dropout, residual_dropout=residual_dropout,
|
| 136 |
+
is_deterministic=True,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
checkpointer = DenseCheckpointer(trial_name=experiment_name, trial_path=train_home_path, ranker=rank_generator)
|
| 140 |
+
|
| 141 |
+
if resume_ckpt_step is not None:
|
| 142 |
+
print(f"[Rank-{rank}] Resuming from step: {resume_ckpt_step}")
|
| 143 |
+
if pp_size > 1:
|
| 144 |
+
layers = layer.module
|
| 145 |
+
else:
|
| 146 |
+
layers = [layer]
|
| 147 |
+
checkpointer.load(layers, train_dataloader, optimizers, resume_ckpt_step)
|
| 148 |
+
|
| 149 |
+
total_step = resume_ckpt_step if resume_ckpt_step is not None else 0
|
| 150 |
+
db_logger.set_step(total_step)
|
| 151 |
+
profiler_end_step = profiler_step + 10
|
| 152 |
+
if enable_profiler > 0:
|
| 153 |
+
prof = torch.profiler.profile(
|
| 154 |
+
schedule=torch.profiler.schedule(wait=profiler_step, warmup=2, active=1, repeat=0),
|
| 155 |
+
on_trace_ready=make_handler(rank, _DEFAULT_LOCAL_DIR),
|
| 156 |
+
record_shapes=True,
|
| 157 |
+
profile_memory=True,
|
| 158 |
+
with_modules=True,
|
| 159 |
+
with_stack=int(torch.__version__[0]) >= 2)
|
| 160 |
+
else:
|
| 161 |
+
prof = nullcontext()
|
| 162 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 163 |
+
|
| 164 |
+
if resume_from_sahara is not None:
|
| 165 |
+
resume_from_sahara_ckpt(device, dtype, hidden_size, inner, layer, layer_number, optimizers, rank,
|
| 166 |
+
resume_from_sahara, vocab_size)
|
| 167 |
+
|
| 168 |
+
with prof:
|
| 169 |
+
for i in range(train_dataloader.length - total_step):
|
| 170 |
+
# for batches in train_dataloader_iter:
|
| 171 |
+
batches = next(train_dataloader)
|
| 172 |
+
start_time = time.perf_counter()
|
| 173 |
+
if pp_size == 1:
|
| 174 |
+
losses = self._no_pp_step(layer, batches, device, gbs, micro_batch_size, hidden_size, rank_generator)
|
| 175 |
+
else:
|
| 176 |
+
losses = self._pp_step(layer, batches, device, gbs, micro_batch_size, hidden_size, rank_generator)
|
| 177 |
+
if rank_generator.get_pp_rank() == 0:
|
| 178 |
+
if pp_size > 1:
|
| 179 |
+
losses = torch.cat(losses) * (gbs // micro_batch_size)
|
| 180 |
+
loss_report = sum(losses) / len(losses)
|
| 181 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 182 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 183 |
+
seen_token = (total_step * seq_len * micro_batch_size * gbs * world_size) / 1024.0 / 1024.0 # In M
|
| 184 |
+
optimizers.step()
|
| 185 |
+
end_time = time.perf_counter()
|
| 186 |
+
if rank == 0 and total_step % 1 == 0:
|
| 187 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 188 |
+
remaining_step = (train_dataloader.length - total_step)
|
| 189 |
+
seconds = (end_time - start_time)
|
| 190 |
+
remaining_seconds = timedelta(seconds=(seconds * remaining_step))
|
| 191 |
+
|
| 192 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {seconds:.6f} ETA: {remaining_seconds} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 193 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 194 |
+
total_step += 1
|
| 195 |
+
|
| 196 |
+
if enable_profiler:
|
| 197 |
+
if total_step == profiler_end_step:
|
| 198 |
+
print("Ending profiler")
|
| 199 |
+
prof.stop()
|
| 200 |
+
if total_step < profiler_end_step:
|
| 201 |
+
prof.step()
|
| 202 |
+
if ckpt_every_n_step is not None and total_step % ckpt_every_n_step == 0:
|
| 203 |
+
if local_rank == 0:
|
| 204 |
+
checkpointer.prepare_root(total_step)
|
| 205 |
+
rank_generator.local_barrier()
|
| 206 |
+
|
| 207 |
+
if pp_size > 1:
|
| 208 |
+
layers = layer.module # Dualpipe
|
| 209 |
+
else:
|
| 210 |
+
layers = [layer] # Pure gargantua block.
|
| 211 |
+
checkpointer.save(layers, train_dataloader, optimizers, total_step)
|
| 212 |
+
|
| 213 |
+
train_dataloader.terminate()
|
| 214 |
+
print("All done")
|
| 215 |
+
|
| 216 |
+
def _no_pp_step(self, model, batches, device, gbs, mbs, hidden_size, rank_generator):
|
| 217 |
+
losses = []
|
| 218 |
+
for batch in batches:
|
| 219 |
+
input_ids = batch['input_ids'].to(device=device)
|
| 220 |
+
cu_seqlen = batch['host_seqlens'].to(device=device)
|
| 221 |
+
word_idx = batch['word_idx'].to(device=device)
|
| 222 |
+
labels = batch['labels'].to(device=device)
|
| 223 |
+
loss_mask = batch['rmpad_loss_mask'].to(device=device)
|
| 224 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 225 |
+
input_ids = input_ids[word_idx]
|
| 226 |
+
input_ids = input_ids.unsqueeze(0)
|
| 227 |
+
labels = labels.view(-1)[word_idx]
|
| 228 |
+
labels = labels.unsqueeze(0)
|
| 229 |
+
loss_mask[labels == 1] = 0
|
| 230 |
+
total_s = cu_seqlen[-1].item()
|
| 231 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen)
|
| 232 |
+
shift_labels.requires_grad = False
|
| 233 |
+
model.set_input_ctx((cu_seqlen, total_s))
|
| 234 |
+
# res = layer.forward(input_id, cu_seqlen, total_s)
|
| 235 |
+
res = model.forward(input_ids)
|
| 236 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 237 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 238 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 239 |
+
losses.append(loss_mean.detach().clone())
|
| 240 |
+
loss = loss_mean / (gbs // mbs)
|
| 241 |
+
loss.backward()
|
| 242 |
+
return losses
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _pp_step(self, model, batches, device, gbs, mbs, hidden_size, rank_generator):
|
| 246 |
+
losses = []
|
| 247 |
+
input_ids_arr = []
|
| 248 |
+
cu_seqlens_arr = []
|
| 249 |
+
inp_shapes_arr = []
|
| 250 |
+
total_ses_arr = []
|
| 251 |
+
labels_arr = []
|
| 252 |
+
loss_mask_arr = []
|
| 253 |
+
num_chunks = len(batches)
|
| 254 |
+
for b in batches:
|
| 255 |
+
# Commonly used by input_ids and labels.
|
| 256 |
+
word_idx = b['word_idx'].to(device=device)
|
| 257 |
+
|
| 258 |
+
# process input_ids
|
| 259 |
+
input_ids = b['input_ids'].to(device=device)
|
| 260 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 261 |
+
input_ids = input_ids[word_idx]
|
| 262 |
+
input_ids = input_ids.unsqueeze(0)
|
| 263 |
+
input_ids_arr.append(input_ids) # Appending
|
| 264 |
+
|
| 265 |
+
# process cu_seqlens & total_s
|
| 266 |
+
cu_seqlens = b['host_seqlens'].to(device=device)
|
| 267 |
+
cu_seqlens_arr.append(cu_seqlens)
|
| 268 |
+
total_s = cu_seqlens[-1].item()
|
| 269 |
+
total_ses_arr.append(total_s)
|
| 270 |
+
|
| 271 |
+
# process labels
|
| 272 |
+
labels = b['labels'].to(device=device)
|
| 273 |
+
labels = labels.view(-1)[word_idx]
|
| 274 |
+
labels = labels.unsqueeze(0)
|
| 275 |
+
labels_arr.append(labels)
|
| 276 |
+
|
| 277 |
+
# process loss_mask
|
| 278 |
+
loss_mask = b['rmpad_loss_mask'].to(device=device)
|
| 279 |
+
loss_mask[labels == 1] = 0
|
| 280 |
+
loss_mask_arr.append(loss_mask)
|
| 281 |
+
|
| 282 |
+
# input shapes.
|
| 283 |
+
inp_shape = (total_s, 1, hidden_size)
|
| 284 |
+
inp_shapes_arr.append(inp_shape)
|
| 285 |
+
if not rank_generator.is_first_rank():
|
| 286 |
+
hidden_states = [None for _ in range(num_chunks)]
|
| 287 |
+
else:
|
| 288 |
+
hidden_states = input_ids_arr
|
| 289 |
+
input_ctx = [(c, t, gbs // mbs) for c, t in zip(cu_seqlens_arr, total_ses_arr)]
|
| 290 |
+
loss, outputs = model.step(hidden_states, input_shapes=inp_shapes_arr, input_ctx=input_ctx,
|
| 291 |
+
num_chunks=num_chunks, criterion=criterion, labels=labels_arr,
|
| 292 |
+
return_outputs=False)
|
| 293 |
+
if rank_generator.is_first_rank():
|
| 294 |
+
losses.append(loss)
|
| 295 |
+
# res = layer.forward(input_ids)
|
| 296 |
+
# sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 297 |
+
return losses
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# Example command line:
|
| 301 |
+
'''
|
| 302 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ARNOLD_WORKER_0_HOST MASTER_PORT=$ARNOLD_WORKER_0_PORT torchrun \
|
| 303 |
+
--node_rank=$ARNOLD_ID --nproc_per_node=8 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$ARNOLD_WORKER_0_PORT \
|
| 304 |
+
/opt/tiger/Abbie/trainer/dense_trainer.py \
|
| 305 |
+
--model=1b2.yaml \
|
| 306 |
+
--trial_name=abbie_dense_1b2_1T_gbs128_gargantua_nopp_ckpt_UT1_b1 \
|
| 307 |
+
--train_home_path=hdfs://harunava/home/byte_tteng_llm/users/yuyifeng.oscar/pretrain \
|
| 308 |
+
--train_dataset=hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train \
|
| 309 |
+
--train_size=1000000000000 \
|
| 310 |
+
--tokenizer=hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227 \
|
| 311 |
+
--pad_idx=1 --vocab_size=136064 \
|
| 312 |
+
--global_batch_size=128 --micro_batch_size=1 --warmup_batch_ratio=0.005 \
|
| 313 |
+
--max_seq_len=4096 --max_position_embeddings=4096 --stride=3840 \
|
| 314 |
+
--lr_max=5e-4 --lr_min=5e-5 --lr_weight_decay=0.1 \
|
| 315 |
+
--ckpt_every_n_step=2000
|
| 316 |
+
'''
|
| 317 |
+
|
| 318 |
+
if __name__ == "__main__":
|
| 319 |
+
rank = int(os.environ['RANK'])
|
| 320 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 321 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 322 |
+
print(f"[INIT] rank: {rank} local_rank: {local_rank} world_size: {world_size}")
|
| 323 |
+
args = parse_args()
|
| 324 |
+
trainer = DenseTrainer(rank, local_rank, world_size, args)
|
| 325 |
+
trainer.start()
|
playground/Abbie-h100/old/trainer/gargantua2_trainer.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from datetime import timedelta
|
| 5 |
+
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from contextlib import nullcontext
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.distributed as dist
|
| 11 |
+
|
| 12 |
+
from einops import rearrange
|
| 13 |
+
|
| 14 |
+
from checkpoint.gargantua_ckpt import Gargantua2Checkpointer
|
| 15 |
+
from dualpipe.log import WandbLogger
|
| 16 |
+
|
| 17 |
+
from dualpipe.module.shared.dist_clip_grads import dist_clip_grad_norm
|
| 18 |
+
from dualpipe.module.shared.loss import preprocess_labels, criterion
|
| 19 |
+
from trainer.cli import parse_args
|
| 20 |
+
from trainer.helper import resume_from_sahara_ckpt
|
| 21 |
+
from trainer.utils import (
|
| 22 |
+
make_handler,
|
| 23 |
+
collect_scalars_across_data_parallel_group
|
| 24 |
+
)
|
| 25 |
+
from dualpipe.module.trainer_builder import build_gargantua_2_trainer
|
| 26 |
+
from dualpipe.module.shared.functional import get_cosine_schedule_with_warmup
|
| 27 |
+
from dualpipe.module.shared.grad_sync import BucketGradientSyncer
|
| 28 |
+
|
| 29 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/Abbie/profiles'
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Trainer:
|
| 33 |
+
def __init__(self, rank, local_rank, world_size, args):
|
| 34 |
+
print(f"Loading from path: {args.model}")
|
| 35 |
+
self.rank = rank
|
| 36 |
+
self.local_rank = local_rank
|
| 37 |
+
self.world_size = world_size
|
| 38 |
+
self.args = args
|
| 39 |
+
|
| 40 |
+
def start(self):
|
| 41 |
+
assert self.args.pp_size >= 1, 'pp_size shall be true positive value'
|
| 42 |
+
|
| 43 |
+
if self.args.enable_profiler:
|
| 44 |
+
assert self.args.profiler_step is not None and self.args.profiler_step > 0, \
|
| 45 |
+
'Setting up profiler without profiler step is not allowed'
|
| 46 |
+
self._do_start(
|
| 47 |
+
self.rank,
|
| 48 |
+
self.local_rank,
|
| 49 |
+
self.world_size,
|
| 50 |
+
experiment_name=self.args.trial_name,
|
| 51 |
+
train_home_path=self.args.train_home_path,
|
| 52 |
+
pp_size=self.args.pp_size,
|
| 53 |
+
ep_size=self.args.ep_size,
|
| 54 |
+
tokenizer_path=self.args.tokenizer,
|
| 55 |
+
# pad_idx = self.args.pad_idx,
|
| 56 |
+
# vocab_size = self.args.vocab_size,
|
| 57 |
+
train_dataset = self.args.train_dataset,
|
| 58 |
+
# train_size = self.args.train_size,
|
| 59 |
+
# warmup_batch_ratio = self.args.warmup_batch_ratio,
|
| 60 |
+
seq_len = self.args.max_seq_len,
|
| 61 |
+
# max_position_embeddings = self.args.max_position_embeddings,
|
| 62 |
+
# stride = self.args.stride,
|
| 63 |
+
# resume_ckpt_path = None,
|
| 64 |
+
# resume_ckpt_step=self.args.resume_ckpt_step,
|
| 65 |
+
gbs = self.args.global_batch_size,
|
| 66 |
+
micro_batch_size = self.args.micro_batch_size,
|
| 67 |
+
# layer_number = layer_number,
|
| 68 |
+
# hidden_size=self.cfg.hidden_size,
|
| 69 |
+
# inner=inner,
|
| 70 |
+
# num_attention_head = self.cfg.num_attention_head,
|
| 71 |
+
# num_shared_qheads=self.args.num_shared_qheads,
|
| 72 |
+
# attention_dropout = attention_dropout,
|
| 73 |
+
# residual_dropout = residual_dropout,
|
| 74 |
+
lr_max=self.args.lr_max,
|
| 75 |
+
lr_min=self.args.lr_min,
|
| 76 |
+
lr_weight_decay=self.args.lr_weight_decay,
|
| 77 |
+
lr_warmup_step_rate=self.args.lr_warmup_step_rate,
|
| 78 |
+
enable_profiler = self.args.enable_profiler,
|
| 79 |
+
profiler_step = self.args.profiler_step,
|
| 80 |
+
# ckpt_every_n_step = self.args.ckpt_every_n_step,
|
| 81 |
+
# resume_from_sahara = self.args.resume_from_sahara,
|
| 82 |
+
pretrained_hf_path=self.args.pretrained_hf_path,
|
| 83 |
+
vit_lr_max=self.args.vit_lr_max,
|
| 84 |
+
vit_lr_min=self.args.vit_lr_min,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
def _do_start(
|
| 88 |
+
self,
|
| 89 |
+
rank,
|
| 90 |
+
local_rank,
|
| 91 |
+
world_size,
|
| 92 |
+
experiment_name,
|
| 93 |
+
train_home_path,
|
| 94 |
+
pp_size: int,
|
| 95 |
+
ep_size: int,
|
| 96 |
+
tokenizer_path: str,
|
| 97 |
+
# pad_idx: int,
|
| 98 |
+
# vocab_size: int,
|
| 99 |
+
train_dataset: str,
|
| 100 |
+
# train_size: int,
|
| 101 |
+
# warmup_batch_ratio: float,
|
| 102 |
+
seq_len: int,
|
| 103 |
+
# max_position_embeddings: int,
|
| 104 |
+
# stride: int,
|
| 105 |
+
# resume_ckpt_path: Optional[str],
|
| 106 |
+
# resume_ckpt_step: Optional[int],
|
| 107 |
+
gbs: int,
|
| 108 |
+
micro_batch_size: int,
|
| 109 |
+
# layer_number: int,
|
| 110 |
+
# hidden_size: int,
|
| 111 |
+
# inner: int,
|
| 112 |
+
# num_attention_head: int,
|
| 113 |
+
# num_shared_qheads: Optional[int],
|
| 114 |
+
# attention_dropout: float,
|
| 115 |
+
# residual_dropout: float,
|
| 116 |
+
lr_max: float,
|
| 117 |
+
lr_min: float,
|
| 118 |
+
lr_weight_decay: float,
|
| 119 |
+
lr_warmup_step_rate: float,
|
| 120 |
+
enable_profiler: bool,
|
| 121 |
+
profiler_step: Optional[int],
|
| 122 |
+
# ckpt_every_n_step: Optional[int],
|
| 123 |
+
# resume_from_sahara: Optional[str],
|
| 124 |
+
pretrained_hf_path: Optional[str] = None,
|
| 125 |
+
vit_lr_max: Optional[float] = None,
|
| 126 |
+
vit_lr_min: Optional[float] = None,
|
| 127 |
+
):
|
| 128 |
+
epoch = 1
|
| 129 |
+
# set_deterministic(1234, False)
|
| 130 |
+
torch.manual_seed(1234)
|
| 131 |
+
|
| 132 |
+
assert world_size % pp_size == 0
|
| 133 |
+
assert gbs % micro_batch_size == 0, "global_batch_size shall be able to be divide up by micro_batch_size"
|
| 134 |
+
dp_size = world_size // pp_size
|
| 135 |
+
gbs = gbs // dp_size
|
| 136 |
+
|
| 137 |
+
device = f'cuda:{local_rank}'
|
| 138 |
+
dtype = torch.bfloat16
|
| 139 |
+
|
| 140 |
+
torch.cuda.set_device(device)
|
| 141 |
+
dist.init_process_group(
|
| 142 |
+
backend='nccl',
|
| 143 |
+
init_method="env://",
|
| 144 |
+
world_size=world_size,
|
| 145 |
+
rank=rank,
|
| 146 |
+
device_id=torch.device(device),
|
| 147 |
+
)
|
| 148 |
+
print(f"[Rank-{rank}] caliberating gbs to {gbs}, dp to {dp_size}, ")
|
| 149 |
+
|
| 150 |
+
db_logger = WandbLogger(rank, "thoth_dualpipe-mingrui.wang2", experiment_name)
|
| 151 |
+
group = dist.distributed_c10d._get_default_group()
|
| 152 |
+
world_size = group.size()
|
| 153 |
+
|
| 154 |
+
DMM, model, train_dataloader, optimizer = build_gargantua_2_trainer(
|
| 155 |
+
rank=rank,
|
| 156 |
+
world_size=world_size,
|
| 157 |
+
train_paths=train_dataset,
|
| 158 |
+
tokenizer_path=tokenizer_path,
|
| 159 |
+
global_batch_size=gbs,
|
| 160 |
+
micro_batch_size=micro_batch_size,
|
| 161 |
+
max_seqlen=seq_len,
|
| 162 |
+
lr_max=lr_max,
|
| 163 |
+
lr_min=lr_min,
|
| 164 |
+
weight_decay=lr_weight_decay,
|
| 165 |
+
lr_warmup_step_rate=lr_warmup_step_rate,
|
| 166 |
+
pp_size=pp_size,
|
| 167 |
+
ep_size=ep_size,
|
| 168 |
+
pretrained_hf_path=pretrained_hf_path,
|
| 169 |
+
vit_lr_max=vit_lr_max,
|
| 170 |
+
vit_lr_min=vit_lr_min,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
if getattr(model, "visual", None) is not None:
|
| 174 |
+
model.visual.gradient_checkpointing_enable({"use_reentrant": False})
|
| 175 |
+
|
| 176 |
+
# checkpointer = Gargantua2Checkpointer(
|
| 177 |
+
# trial_name=experiment_name,
|
| 178 |
+
# trial_path=train_home_path,
|
| 179 |
+
# DMM=DMM,
|
| 180 |
+
# )
|
| 181 |
+
|
| 182 |
+
resume_ckpt_step = None
|
| 183 |
+
if resume_ckpt_step is not None:
|
| 184 |
+
print(f"[Rank-{rank}] Resuming from step: {resume_ckpt_step}")
|
| 185 |
+
# Save this for later when we fix the arpeggio dataloader resume
|
| 186 |
+
raise NotImplementedError
|
| 187 |
+
# checkpointer.load(layers, train_dataloader, optimizers, resume_ckpt_step)
|
| 188 |
+
|
| 189 |
+
total_step = resume_ckpt_step if resume_ckpt_step is not None else 0
|
| 190 |
+
db_logger.set_step(total_step)
|
| 191 |
+
profiler_end_step = profiler_step + 10
|
| 192 |
+
if enable_profiler > 0:
|
| 193 |
+
prof = torch.profiler.profile(
|
| 194 |
+
schedule=torch.profiler.schedule(wait=profiler_step, warmup=2, active=1, repeat=0),
|
| 195 |
+
on_trace_ready=make_handler(rank, _DEFAULT_LOCAL_DIR),
|
| 196 |
+
record_shapes=True,
|
| 197 |
+
profile_memory=True,
|
| 198 |
+
with_modules=True,
|
| 199 |
+
with_stack=int(torch.__version__[0]) >= 2)
|
| 200 |
+
else:
|
| 201 |
+
prof = nullcontext()
|
| 202 |
+
|
| 203 |
+
# if resume_from_sahara is not None:
|
| 204 |
+
# resume_from_sahara_ckpt(device, dtype, hidden_size, inner, layer, layer_number, optimizers, rank,
|
| 205 |
+
# resume_from_sahara, vocab_size)
|
| 206 |
+
|
| 207 |
+
with prof:
|
| 208 |
+
for batch in train_dataloader:
|
| 209 |
+
start_time = time.time()
|
| 210 |
+
|
| 211 |
+
batch.to(torch.bfloat16).to("cuda")
|
| 212 |
+
|
| 213 |
+
optimizer.zero_grad()
|
| 214 |
+
outputs = model.step(
|
| 215 |
+
input_ids=batch["input_ids"],
|
| 216 |
+
attention_mask=batch["attention_mask"],
|
| 217 |
+
position_ids=batch["position_ids"],
|
| 218 |
+
labels=batch["labels"],
|
| 219 |
+
return_outputs=True,
|
| 220 |
+
pixel_values=batch.get("pixel_values"),
|
| 221 |
+
image_grid_thw=batch.get("image_grid_thw"),
|
| 222 |
+
pixel_values_videos=batch.get("pixel_values_videos"),
|
| 223 |
+
video_grid_thw=batch.get("video_grid_thw"),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
# This sync is only to calculate optimizer time more accurately
|
| 227 |
+
# the training still works and can probably be slightly faster without this
|
| 228 |
+
torch.cuda.synchronize()
|
| 229 |
+
dist.barrier()
|
| 230 |
+
|
| 231 |
+
opt_start_time = time.time()
|
| 232 |
+
optimizer.step()
|
| 233 |
+
opt_end_time = time.time()
|
| 234 |
+
|
| 235 |
+
n_tokens = batch["attention_mask"].sum().item()
|
| 236 |
+
n_tokens = sum(all_gather_objects(n_tokens))
|
| 237 |
+
|
| 238 |
+
loss = 0
|
| 239 |
+
if outputs.loss is not None:
|
| 240 |
+
loss = outputs.loss.sum().item()
|
| 241 |
+
loss = sum(all_gather_objects(loss))
|
| 242 |
+
|
| 243 |
+
end_time = time.time()
|
| 244 |
+
|
| 245 |
+
if rank == 0:
|
| 246 |
+
# caliberated_grad_norm = optimizers.grad_norm()
|
| 247 |
+
# caliberated_grad_norm = 0
|
| 248 |
+
remaining_step = (len(train_dataloader) - total_step)
|
| 249 |
+
seconds = end_time - start_time
|
| 250 |
+
remaining_seconds = timedelta(seconds=seconds * remaining_step)
|
| 251 |
+
|
| 252 |
+
metrics = {
|
| 253 |
+
"training/loss": loss,
|
| 254 |
+
"train/loss": loss,
|
| 255 |
+
# "train/grad_norm": grad_norm,
|
| 256 |
+
"data/tokens_per_step": n_tokens,
|
| 257 |
+
# "train/lr": optimizer.get_last_lr(),
|
| 258 |
+
"perf/optim_time": opt_end_time - opt_start_time,
|
| 259 |
+
"perf/max_memory_allocated": torch.cuda.max_memory_allocated(),
|
| 260 |
+
"perf/max_memory_reserved": torch.cuda.max_memory_reserved(),
|
| 261 |
+
}
|
| 262 |
+
for name, lr in optimizer.last_lr.items():
|
| 263 |
+
metrics[f"train/{name}_lr"] = lr
|
| 264 |
+
|
| 265 |
+
grad_norms = optimizer.last_grad_norm
|
| 266 |
+
for name, grad_norm in grad_norms.items():
|
| 267 |
+
metrics[f"train/{name}_grad_norm"] = grad_norm
|
| 268 |
+
metrics["train/grad_norm"] = grad_norms["llm"]
|
| 269 |
+
|
| 270 |
+
db_logger.log_step(metrics)
|
| 271 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {seconds:.6f} ETA: {remaining_seconds} n_tokens: {n_tokens} tokens Loss: {loss} grad_norm: {grad_norm}")
|
| 272 |
+
total_step += 1
|
| 273 |
+
|
| 274 |
+
if enable_profiler:
|
| 275 |
+
if total_step == profiler_end_step:
|
| 276 |
+
print("Ending profiler")
|
| 277 |
+
prof.stop()
|
| 278 |
+
if total_step < profiler_end_step:
|
| 279 |
+
prof.step()
|
| 280 |
+
|
| 281 |
+
# if total_step >= 10:
|
| 282 |
+
# break
|
| 283 |
+
|
| 284 |
+
# For now skip checkpoint
|
| 285 |
+
# if ckpt_every_n_step is not None and total_step % ckpt_every_n_step == 0:
|
| 286 |
+
# if local_rank == 0:
|
| 287 |
+
# checkpointer.prepare_root(total_step)
|
| 288 |
+
# rank_generator.local_barrier()
|
| 289 |
+
|
| 290 |
+
# if pp_size > 1:
|
| 291 |
+
# layers = layer.module # Dualpipe
|
| 292 |
+
# else:
|
| 293 |
+
# layers = [layer] # Pure gargantua block.
|
| 294 |
+
# checkpointer.save(layers, train_dataloader, optimizers, total_step)
|
| 295 |
+
|
| 296 |
+
# train_dataloader.terminate()
|
| 297 |
+
print("All done")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def all_gather_objects(value, group: Optional[dist.ProcessGroup] = None):
|
| 301 |
+
if not dist.is_initialized():
|
| 302 |
+
return [value]
|
| 303 |
+
|
| 304 |
+
if group is None:
|
| 305 |
+
group = dist.group.WORLD
|
| 306 |
+
|
| 307 |
+
values = [None for _ in range(group.size())]
|
| 308 |
+
dist.all_gather_object(
|
| 309 |
+
object_list=values,
|
| 310 |
+
obj=value,
|
| 311 |
+
group=group,
|
| 312 |
+
)
|
| 313 |
+
return values
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# Example command line:
|
| 317 |
+
'''
|
| 318 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ARNOLD_WORKER_0_HOST MASTER_PORT=$ARNOLD_WORKER_0_PORT torchrun \
|
| 319 |
+
--node_rank=$ARNOLD_ID --nproc_per_node=8 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$ARNOLD_WORKER_0_PORT \
|
| 320 |
+
/opt/tiger/Abbie/trainer/dense_trainer.py \
|
| 321 |
+
--model=1b2.yaml \
|
| 322 |
+
--trial_name=abbie_dense_1b2_1T_gbs128_gargantua_nopp_ckpt_UT1_b1 \
|
| 323 |
+
--train_home_path=hdfs://harunava/home/byte_tteng_llm/users/yuyifeng.oscar/pretrain \
|
| 324 |
+
--train_dataset=hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train \
|
| 325 |
+
--train_size=1000000000000 \
|
| 326 |
+
--tokenizer=hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227 \
|
| 327 |
+
--pad_idx=1 --vocab_size=136064 \
|
| 328 |
+
--global_batch_size=128 --micro_batch_size=1 --warmup_batch_ratio=0.005 \
|
| 329 |
+
--max_seq_len=4096 --max_position_embeddings=4096 --stride=3840 \
|
| 330 |
+
--lr_max=5e-4 --lr_min=5e-5 --lr_weight_decay=0.1 \
|
| 331 |
+
--ckpt_every_n_step=2000
|
| 332 |
+
'''
|
| 333 |
+
|
| 334 |
+
if __name__ == "__main__":
|
| 335 |
+
rank = int(os.environ['RANK'])
|
| 336 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 337 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 338 |
+
print(f"[INIT] rank: {rank} local_rank: {local_rank} world_size: {world_size}")
|
| 339 |
+
args = parse_args()
|
| 340 |
+
# if local_rank == 0:
|
| 341 |
+
# torch.cuda.memory._record_memory_history()
|
| 342 |
+
trainer = Trainer(rank, local_rank, world_size, args)
|
| 343 |
+
trainer.start()
|
| 344 |
+
# if local_rank == 0:
|
| 345 |
+
# torch.cuda.memory._dump_snapshot("memory_snapshot.pkl")
|
playground/Abbie-h100/old/trainer/helper.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _extract_weights(resume_from_path, rank, vocab_size, hidden_size, inner_size, dtype, device, layer_number):
|
| 5 |
+
vocab_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 6 |
+
logits_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 7 |
+
final_rms_norm_weight = torch.ones(hidden_size, dtype=dtype, device=device)
|
| 8 |
+
qkv = [torch.nn.Linear(hidden_size, hidden_size * 3, bias=False, dtype=dtype, device=device) for _ in
|
| 9 |
+
range(layer_number)]
|
| 10 |
+
dense = [torch.nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 11 |
+
range(layer_number)]
|
| 12 |
+
w1 = [torch.nn.Linear(hidden_size, 2 * inner_size, bias=False, dtype=dtype, device=device) for _ in
|
| 13 |
+
range(layer_number)]
|
| 14 |
+
w2 = [torch.nn.Linear(inner_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 15 |
+
range(layer_number)]
|
| 16 |
+
qkv_rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 17 |
+
rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 18 |
+
|
| 19 |
+
WEIGHT_PATH=f'{resume_from_path}/rank{rank}'
|
| 20 |
+
print(f"Loading from path: {WEIGHT_PATH}")
|
| 21 |
+
vocab_weight = torch.load(f'{WEIGHT_PATH}/vocab_weight.pt').to(device=device)
|
| 22 |
+
vocab_embedding.weight.data.copy_(vocab_weight.data)
|
| 23 |
+
|
| 24 |
+
for i in range(layer_number):
|
| 25 |
+
qkv_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.self_attention.query_key_value.weight.pt').to(device=device)
|
| 26 |
+
qkv[i].weight.data.copy_(qkv_dump.data)
|
| 27 |
+
dense_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.self_attention.dense.weight.pt').to(device=device)
|
| 28 |
+
dense[i].weight.data.copy_(dense_dump.data)
|
| 29 |
+
w1_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.mlp.fc1_weight.pt').to(device=device)
|
| 30 |
+
w1[i].weight.data.copy_(w1_dump.data)
|
| 31 |
+
w2_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.mlp.fc2_weight.pt').to(device=device)
|
| 32 |
+
w2[i].weight.data.copy_(w2_dump.data)
|
| 33 |
+
qkv_weights = [a.weight for a in qkv]
|
| 34 |
+
dense_weights = [a.weight for a in dense]
|
| 35 |
+
w1_weights = [a.weight for a in w1]
|
| 36 |
+
w2_weights = [a.weight for a in w2]
|
| 37 |
+
return vocab_embedding.weight, final_rms_norm_weight, logits_embedding.weight, qkv_weights, dense_weights, w1_weights, w2_weights, qkv_rmsnorm_weight, rmsnorm_weight
|
| 38 |
+
|
| 39 |
+
def resume_from_sahara_ckpt(device, dtype, hidden_size, inner, layer, layer_number, optimizers, rank,
|
| 40 |
+
resume_from_sahara, vocab_size):
|
| 41 |
+
(
|
| 42 |
+
vocab_weight,
|
| 43 |
+
final_rms_weight,
|
| 44 |
+
logits_weight,
|
| 45 |
+
qkv_weight,
|
| 46 |
+
dense_weight,
|
| 47 |
+
w1_weight,
|
| 48 |
+
w2_weight,
|
| 49 |
+
qkv_rmsnorm_weight,
|
| 50 |
+
rmsnorm_weight
|
| 51 |
+
) = _extract_weights(resume_from_sahara, rank, vocab_size, hidden_size, inner, dtype, device, layer_number)
|
| 52 |
+
print(f"[rank-{rank}] setting weight ... ")
|
| 53 |
+
layer.set_weight(vocab_weight, final_rms_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight,
|
| 54 |
+
w1_weight,
|
| 55 |
+
w2_weight, [], rmsnorm_weight)
|
| 56 |
+
for opt in optimizers.optimizers:
|
| 57 |
+
opt.reload_fp32_param_from_original()
|
playground/Abbie-h100/old/trainer/moe_trainer.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
from datetime import timedelta
|
| 7 |
+
|
| 8 |
+
from typing import Optional
|
| 9 |
+
from contextlib import nullcontext
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.distributed as dist
|
| 13 |
+
|
| 14 |
+
from einops import rearrange
|
| 15 |
+
|
| 16 |
+
from checkpoint.gargantua_ckpt import MoECheckpointer
|
| 17 |
+
from dualpipe.log import WandbLogger
|
| 18 |
+
from dualpipe.deterministic import set_deterministic
|
| 19 |
+
|
| 20 |
+
from dualpipe.module.shared.loss import preprocess_labels, criterion
|
| 21 |
+
from trainer.cli import parse_args
|
| 22 |
+
from trainer.utils import (
|
| 23 |
+
load_config,
|
| 24 |
+
make_handler,
|
| 25 |
+
collect_scalars_across_data_parallel_group
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
set_deterministic(42, False)
|
| 29 |
+
|
| 30 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 31 |
+
from dualpipe.module.trainer_builder import build_moe_trainer
|
| 32 |
+
from trainer.dense_trainer import DenseTrainer
|
| 33 |
+
|
| 34 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/Abbie/profiles'
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class MoETrainer(DenseTrainer):
|
| 38 |
+
def __init__(self, rank, local_rank, world_size, args):
|
| 39 |
+
super().__init__(rank, local_rank, world_size, args)
|
| 40 |
+
|
| 41 |
+
def start(self):
|
| 42 |
+
assert self.args.pp_size >= 1, 'pp_size shall be true positive value'
|
| 43 |
+
# override checking
|
| 44 |
+
inner = self.args.inner if self.args.inner is not None else self.cfg.inner
|
| 45 |
+
layer_number = self.args.layer_number if self.args.layer_number is not None else self.cfg.layer_number
|
| 46 |
+
attention_dropout = self.args.attention_dropout if self.args.attention_dropout is not None else self.cfg.attention_dropout
|
| 47 |
+
residual_dropout = self.args.residual_dropout if self.args.residual_dropout is not None else self.cfg.residual_dropout
|
| 48 |
+
|
| 49 |
+
if self.args.enable_profiler:
|
| 50 |
+
assert self.args.profiler_step is not None and self.args.profiler_step > 0, \
|
| 51 |
+
'Setting up profiler without profiler step is not allowed'
|
| 52 |
+
self._do_start(
|
| 53 |
+
self.rank, self.local_rank, self.world_size,
|
| 54 |
+
experiment_name=self.args.trial_name,
|
| 55 |
+
train_home_path=self.args.train_home_path,
|
| 56 |
+
pp_size = self.args.pp_size,
|
| 57 |
+
ep_size = self.args.ep_size,
|
| 58 |
+
tokenizer_path=self.args.tokenizer,
|
| 59 |
+
pad_idx = self.args.pad_idx,
|
| 60 |
+
vocab_size = self.args.vocab_size,
|
| 61 |
+
train_dataset = self.args.train_dataset,
|
| 62 |
+
train_size = self.args.train_size,
|
| 63 |
+
warmup_batch_ratio = self.args.warmup_batch_ratio,
|
| 64 |
+
seq_len = self.args.max_seq_len,
|
| 65 |
+
max_position_embeddings = self.args.max_position_embeddings,
|
| 66 |
+
stride = self.args.stride,
|
| 67 |
+
resume_ckpt_path = None,
|
| 68 |
+
resume_ckpt_step=self.args.resume_ckpt_step,
|
| 69 |
+
gbs = self.args.global_batch_size, micro_batch_size = self.args.micro_batch_size,
|
| 70 |
+
layer_number = layer_number,
|
| 71 |
+
hidden_size=self.cfg.hidden_size,
|
| 72 |
+
inner=inner,
|
| 73 |
+
num_attention_head =self.cfg.num_attention_head,
|
| 74 |
+
num_shared_qheads=self.args.num_shared_qheads,
|
| 75 |
+
is_tie_weight=self.cfg.is_tie_weight,
|
| 76 |
+
attention_dropout=attention_dropout,
|
| 77 |
+
residual_dropout=residual_dropout,
|
| 78 |
+
expert_num=self.cfg.expert_number,
|
| 79 |
+
top_k=self.cfg.num_experts_per_tok,
|
| 80 |
+
lr_max=self.args.lr_max,
|
| 81 |
+
lr_min=self.args.lr_min,
|
| 82 |
+
lr_weight_decay=self.args.lr_weight_decay,
|
| 83 |
+
enable_profiler = self.args.enable_profiler,
|
| 84 |
+
profiler_step = self.args.profiler_step,
|
| 85 |
+
ckpt_every_n_step = self.args.ckpt_every_n_step)
|
| 86 |
+
|
| 87 |
+
def _do_start(self,
|
| 88 |
+
rank, local_rank, world_size,
|
| 89 |
+
experiment_name, train_home_path,
|
| 90 |
+
pp_size: int,
|
| 91 |
+
ep_size: int,
|
| 92 |
+
tokenizer_path: str, pad_idx: int,
|
| 93 |
+
vocab_size: int, train_dataset: str, train_size: int, warmup_batch_ratio: float,
|
| 94 |
+
seq_len: int, max_position_embeddings: int, stride: int,
|
| 95 |
+
resume_ckpt_path: Optional[str], resume_ckpt_step: Optional[int],
|
| 96 |
+
gbs: int, micro_batch_size: int,
|
| 97 |
+
layer_number: int,
|
| 98 |
+
hidden_size: int, inner: int, num_attention_head: int, num_shared_qheads: Optional[int],
|
| 99 |
+
expert_num: int, top_k: int, is_tie_weight: bool,
|
| 100 |
+
attention_dropout: float, residual_dropout: float,
|
| 101 |
+
lr_max: float, lr_min: float, lr_weight_decay: float,
|
| 102 |
+
enable_profiler: bool, profiler_step: Optional[int], ckpt_every_n_step: Optional[int]):
|
| 103 |
+
epoch = 1
|
| 104 |
+
set_deterministic(42, False)
|
| 105 |
+
|
| 106 |
+
assert world_size % pp_size == 0
|
| 107 |
+
dp_size = world_size // pp_size
|
| 108 |
+
gbs = gbs // dp_size
|
| 109 |
+
|
| 110 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=world_size, rank=rank)
|
| 111 |
+
print(f"[Rank-{rank}] caliberating gbs to {gbs}, dp to {dp_size}, ")
|
| 112 |
+
|
| 113 |
+
device = f'cuda:{local_rank}'
|
| 114 |
+
dtype = torch.bfloat16
|
| 115 |
+
|
| 116 |
+
db_logger = WandbLogger(rank, None, experiment_name)
|
| 117 |
+
group = dist.distributed_c10d._get_default_group()
|
| 118 |
+
world_size = group.size()
|
| 119 |
+
|
| 120 |
+
rank_generator, layer, train_dataloader, optimizers = build_moe_trainer(
|
| 121 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 122 |
+
epoch_number=epoch,
|
| 123 |
+
train_path=train_dataset, train_size=train_size,
|
| 124 |
+
val_path="invalid", val_size=-1, # TODO [yuyifeng.oscar] pending for validation integration
|
| 125 |
+
warmup_step_rate=warmup_batch_ratio,
|
| 126 |
+
tokenizer_path=tokenizer_path, pad_idx=pad_idx,
|
| 127 |
+
global_batch_size=gbs, micro_batch_size=micro_batch_size,
|
| 128 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 129 |
+
lr_max=lr_max, lr_min=lr_min, weight_decay=lr_weight_decay,
|
| 130 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 131 |
+
expert_size=inner, expert_num=expert_num, top_k=top_k, is_tie_weight=is_tie_weight,
|
| 132 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size,
|
| 133 |
+
num_attention_head=num_attention_head, num_shared_qheads=num_shared_qheads,
|
| 134 |
+
attention_dropout=attention_dropout, residual_dropout=residual_dropout,
|
| 135 |
+
is_deterministic=True,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
checkpointer = MoECheckpointer(trial_name=experiment_name, trial_path=train_home_path, ranker=rank_generator)
|
| 139 |
+
if rank == 0:
|
| 140 |
+
checkpointer.save_recipes(self.recipes())
|
| 141 |
+
|
| 142 |
+
if resume_ckpt_step is not None:
|
| 143 |
+
print(f"[Rank-{rank}] Resuming from step: {resume_ckpt_step}")
|
| 144 |
+
if pp_size > 1:
|
| 145 |
+
layers = layer.module
|
| 146 |
+
else:
|
| 147 |
+
layers = [layer]
|
| 148 |
+
checkpointer.load(layers, train_dataloader, optimizers, resume_ckpt_step)
|
| 149 |
+
|
| 150 |
+
total_step = resume_ckpt_step if resume_ckpt_step is not None else 0
|
| 151 |
+
db_logger.set_step(total_step)
|
| 152 |
+
profiler_end_step = profiler_step + 10
|
| 153 |
+
if enable_profiler > 0:
|
| 154 |
+
prof = torch.profiler.profile(
|
| 155 |
+
schedule=torch.profiler.schedule(wait=profiler_step, warmup=2, active=1, repeat=0),
|
| 156 |
+
on_trace_ready=make_handler(rank, _DEFAULT_LOCAL_DIR),
|
| 157 |
+
record_shapes=True,
|
| 158 |
+
profile_memory=True,
|
| 159 |
+
with_modules=True,
|
| 160 |
+
with_stack=int(torch.__version__[0]) >= 2)
|
| 161 |
+
else:
|
| 162 |
+
prof = nullcontext()
|
| 163 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 164 |
+
with prof:
|
| 165 |
+
for i in range(train_dataloader.length - total_step):
|
| 166 |
+
# for batches in train_dataloader_iter:
|
| 167 |
+
batches = next(train_dataloader)
|
| 168 |
+
start_time = time.perf_counter()
|
| 169 |
+
if pp_size == 1:
|
| 170 |
+
losses = self._no_pp_step(layer, batches, device, gbs, micro_batch_size, hidden_size, rank_generator)
|
| 171 |
+
else:
|
| 172 |
+
losses = self._pp_step(layer, batches, device, gbs, micro_batch_size, hidden_size, rank_generator)
|
| 173 |
+
if rank_generator.get_pp_rank() == 0:
|
| 174 |
+
if pp_size > 1:
|
| 175 |
+
losses = torch.cat(losses) * gbs
|
| 176 |
+
loss_report = sum(losses) / len(losses)
|
| 177 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 178 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 179 |
+
seen_token = (total_step * seq_len * micro_batch_size * gbs * world_size) / 1024.0 / 1024.0 # In M
|
| 180 |
+
optimizers.step()
|
| 181 |
+
end_time = time.perf_counter()
|
| 182 |
+
if rank == 0 and total_step % 1 == 0:
|
| 183 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 184 |
+
remaining_step = (train_dataloader.length - total_step)
|
| 185 |
+
seconds = (end_time - start_time)
|
| 186 |
+
remaining_seconds = timedelta(seconds=(seconds * remaining_step))
|
| 187 |
+
|
| 188 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {seconds:.6f} ETA: {remaining_seconds} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 189 |
+
db_logger.log_step({
|
| 190 |
+
'training/loss': gathered_loss,
|
| 191 |
+
'training/lr': optimizers.get_last_lr()[0],
|
| 192 |
+
'training/grad_norm': caliberated_grad_norm,
|
| 193 |
+
'consumed_tokens': seen_token,
|
| 194 |
+
})
|
| 195 |
+
total_step += 1
|
| 196 |
+
|
| 197 |
+
if enable_profiler:
|
| 198 |
+
if total_step == profiler_end_step:
|
| 199 |
+
print("Ending profiler")
|
| 200 |
+
prof.stop()
|
| 201 |
+
if total_step < profiler_end_step:
|
| 202 |
+
prof.step()
|
| 203 |
+
if ckpt_every_n_step is not None and total_step % ckpt_every_n_step == 0:
|
| 204 |
+
if local_rank == 0:
|
| 205 |
+
checkpointer.prepare_root(total_step)
|
| 206 |
+
rank_generator.local_barrier()
|
| 207 |
+
|
| 208 |
+
if pp_size > 1:
|
| 209 |
+
layers = layer.module # Dualpipe
|
| 210 |
+
else:
|
| 211 |
+
layers = [layer] # Pure gargantua block.
|
| 212 |
+
checkpointer.save(layers, train_dataloader, optimizers, total_step)
|
| 213 |
+
|
| 214 |
+
train_dataloader.terminate()
|
| 215 |
+
print("All done")
|
| 216 |
+
|
| 217 |
+
def recipes(self):
|
| 218 |
+
cfg_dict = vars(self.cfg)
|
| 219 |
+
args_dict = vars(self.args)
|
| 220 |
+
|
| 221 |
+
return {**cfg_dict, **{k: v for k, v in args_dict.items() if v is not None}}
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# Example command line:
|
| 225 |
+
'''
|
| 226 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ARNOLD_WORKER_0_HOST MASTER_PORT=$ARNOLD_WORKER_0_PORT torchrun \
|
| 227 |
+
--node_rank=$ARNOLD_ID --nproc_per_node=8 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$ARNOLD_WORKER_0_PORT \
|
| 228 |
+
/opt/tiger/Abbie/trainer/dense_trainer.py \
|
| 229 |
+
--model=1b2.yaml \
|
| 230 |
+
--trial_name=abbie_moe_1b2_1T_gbs128_gargantua_nopp_ckpt_UT1_b1 \
|
| 231 |
+
--train_home_path=hdfs://harunava/home/byte_tteng_llm/users/yuyifeng.oscar/pretrain \
|
| 232 |
+
--train_dataset=hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train \
|
| 233 |
+
--train_size=1000000000000 \
|
| 234 |
+
--tokenizer=hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227 \
|
| 235 |
+
--pad_idx=1 --vocab_size=136064 \
|
| 236 |
+
--ep_size=2 \
|
| 237 |
+
--global_batch_size=128 --micro_batch_size=1 --warmup_batch_ratio=0.005 \
|
| 238 |
+
--max_seq_len=4096 --max_position_embeddings=4096 --stride=3840 \
|
| 239 |
+
--lr_max=5e-4 --lr_min=5e-5 --lr_weight_decay=0.1 \
|
| 240 |
+
--ckpt_every_n_step=2000
|
| 241 |
+
'''
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
rank = int(os.environ['RANK'])
|
| 245 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 246 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 247 |
+
print(f"[INIT] rank: {rank} local_rank: {local_rank} world_size: {world_size}")
|
| 248 |
+
args = parse_args()
|
| 249 |
+
trainer = MoETrainer(rank, local_rank, world_size, args)
|
| 250 |
+
trainer.start()
|
playground/Abbie-h100/old/trainer/template/1b2.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hidden_size: 2048
|
| 2 |
+
inner: 5504
|
| 3 |
+
num_attention_head: 16
|
| 4 |
+
layer_number: 24
|
| 5 |
+
attention_dropout: 0.1
|
| 6 |
+
residual_dropout: 0.1
|
playground/Abbie-h100/old/trainer/template/32b.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hidden_size: 6144
|
| 2 |
+
inner: 15360
|
| 3 |
+
num_attention_head: 48
|
| 4 |
+
layer_number: 72
|
| 5 |
+
attention_dropout: 0.0
|
| 6 |
+
residual_dropout: 0.0
|
playground/Abbie-h100/old/trainer/template/93b.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hidden_size: 8192
|
| 2 |
+
inner: 20480
|
| 3 |
+
num_attention_head: 64
|
| 4 |
+
layer_number: 108
|
| 5 |
+
attention_dropout: 0.0
|
| 6 |
+
residual_dropout: 0.0
|
playground/Abbie-h100/old/trainer/template/moe_30b.yaml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
hidden_size: 2048
|
| 2 |
+
inner: 768
|
| 3 |
+
num_attention_head: 32
|
| 4 |
+
layer_number: 48
|
| 5 |
+
expert_number: 128
|
| 6 |
+
num_experts_per_tok: 8
|
| 7 |
+
is_tie_weight: False
|
| 8 |
+
attention_dropout: 0.0
|
| 9 |
+
residual_dropout: 0.0
|
playground/Abbie-h100/old/trainer/utils.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import yaml
|
| 5 |
+
from types import SimpleNamespace
|
| 6 |
+
|
| 7 |
+
def dict_to_namespace(d):
|
| 8 |
+
if isinstance(d, dict):
|
| 9 |
+
return SimpleNamespace(**{k: dict_to_namespace(v) for k, v in d.items()})
|
| 10 |
+
elif isinstance(d, list):
|
| 11 |
+
return [dict_to_namespace(i) for i in d]
|
| 12 |
+
else:
|
| 13 |
+
return d
|
| 14 |
+
|
| 15 |
+
def load_config(path):
|
| 16 |
+
with open(f'/opt/tiger/Abbie/trainer/template/{path}', 'r') as f:
|
| 17 |
+
cfg_dict = yaml.safe_load(f)
|
| 18 |
+
return dict_to_namespace(cfg_dict)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def make_handler(rank, local_dir):
|
| 22 |
+
def handler_fn(p):
|
| 23 |
+
# export trace data when traces ready (schedule cycle ends)
|
| 24 |
+
fname = "profileStep" + str(p.step_num) + "_globalStep" + str(0) + "_rank" + str(rank) + "." + \
|
| 25 |
+
str(int(time.time())) + ".pt.trace.json.gz"
|
| 26 |
+
local_file = os.path.join(local_dir, fname)
|
| 27 |
+
if not os.path.exists(local_dir):
|
| 28 |
+
print("mkdir ", local_dir)
|
| 29 |
+
os.makedirs(local_dir)
|
| 30 |
+
print("Save profile results to {}".format(local_file))
|
| 31 |
+
p.export_chrome_trace(local_file)
|
| 32 |
+
print("Local profile file saved")
|
| 33 |
+
|
| 34 |
+
return handler_fn
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 38 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 39 |
+
scalars = torch.cat(
|
| 40 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 41 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 42 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 43 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 44 |
+
group=dp_group)
|
| 45 |
+
return out_scalars, group_size
|
playground/Abbie-h100/tests/__init__.py
ADDED
|
File without changes
|
playground/Abbie-h100/tests/bench_qwen2.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from functools import partial
|
| 5 |
+
from typing import Tuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch.utils.checkpoint import checkpoint, CheckpointPolicy, create_selective_checkpoint_contexts
|
| 9 |
+
from transformers import Qwen2Config
|
| 10 |
+
from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer, Qwen2RotaryEmbedding
|
| 11 |
+
|
| 12 |
+
from dualpipe.module.gargantua.models.qwen2 import Qwen2DecoderLayerFunc
|
| 13 |
+
from dualpipe.utils import run_backward
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def make_config() -> Qwen2Config:
|
| 17 |
+
if True:
|
| 18 |
+
# Qwen2.5-72B configs
|
| 19 |
+
return Qwen2Config(
|
| 20 |
+
attention_dropout=0.0,
|
| 21 |
+
bos_token_id=151643,
|
| 22 |
+
eos_token_id=151645,
|
| 23 |
+
hidden_act="silu",
|
| 24 |
+
hidden_size=8192,
|
| 25 |
+
initializer_range=0.02,
|
| 26 |
+
intermediate_size=29568,
|
| 27 |
+
max_position_embeddings=32768,
|
| 28 |
+
max_window_layers=70,
|
| 29 |
+
num_attention_heads=64,
|
| 30 |
+
num_hidden_layers=80,
|
| 31 |
+
num_key_value_heads=8,
|
| 32 |
+
rms_norm_eps=1e-06,
|
| 33 |
+
rope_theta=1000000.0,
|
| 34 |
+
sliding_window=131072,
|
| 35 |
+
tie_word_embeddings=False,
|
| 36 |
+
torch_dtype="bfloat16",
|
| 37 |
+
use_cache=False,
|
| 38 |
+
use_sliding_window=False,
|
| 39 |
+
vocab_size=152064,
|
| 40 |
+
attn_implementation="flash_attention_2",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Qwen2.5-7B configs
|
| 44 |
+
return Qwen2Config(
|
| 45 |
+
attention_dropout=0.0,
|
| 46 |
+
bos_token_id=151643,
|
| 47 |
+
eos_token_id=151645,
|
| 48 |
+
hidden_act="silu",
|
| 49 |
+
hidden_size=3584,
|
| 50 |
+
initializer_range=0.02,
|
| 51 |
+
intermediate_size=18944,
|
| 52 |
+
max_position_embeddings=32768,
|
| 53 |
+
max_window_layers=28,
|
| 54 |
+
num_attention_heads=28,
|
| 55 |
+
num_hidden_layers=28,
|
| 56 |
+
num_key_value_heads=4,
|
| 57 |
+
rms_norm_eps=1e-06,
|
| 58 |
+
rope_theta=1000000.0,
|
| 59 |
+
sliding_window=131072,
|
| 60 |
+
tie_word_embeddings=False,
|
| 61 |
+
torch_dtype="bfloat16",
|
| 62 |
+
use_cache=True,
|
| 63 |
+
use_sliding_window=False,
|
| 64 |
+
vocab_size=152064,
|
| 65 |
+
attn_implementation="flash_attention_2",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def zero_grads(layer: Qwen2DecoderLayer):
|
| 70 |
+
for param in layer.parameters():
|
| 71 |
+
param.grad = None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def bench_qwen2_decoder_layer_hf(
|
| 75 |
+
layer: Qwen2DecoderLayer,
|
| 76 |
+
input_tensor: torch.Tensor,
|
| 77 |
+
attention_mask: torch.Tensor,
|
| 78 |
+
position_ids: torch.Tensor,
|
| 79 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 80 |
+
cu_seqlens: torch.Tensor,
|
| 81 |
+
max_seqlen: torch.Tensor,
|
| 82 |
+
d_output_tensor: torch.Tensor,
|
| 83 |
+
n_rounds: int = 6,
|
| 84 |
+
recompute: bool = False,
|
| 85 |
+
recompute_skip_attn: bool = False,
|
| 86 |
+
):
|
| 87 |
+
forward_kwargs = dict(
|
| 88 |
+
hidden_states=input_tensor,
|
| 89 |
+
attention_mask=attention_mask,
|
| 90 |
+
position_ids=position_ids,
|
| 91 |
+
position_embeddings=position_embeddings,
|
| 92 |
+
cumulative_seqlens_q=cu_seqlens,
|
| 93 |
+
cumulative_seqlens_k=cu_seqlens,
|
| 94 |
+
max_length_q=max_seqlen,
|
| 95 |
+
max_length_k=max_seqlen,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
if recompute:
|
| 99 |
+
compute_intensive_ops = []
|
| 100 |
+
if recompute_skip_attn:
|
| 101 |
+
# Based on past experience, saving attn output is the optimal
|
| 102 |
+
compute_intensive_ops = [
|
| 103 |
+
torch.ops.flash_attn._flash_attn_varlen_forward.default,
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
def policy_fn(ctx, op, *args, **kwargs):
|
| 107 |
+
if op in compute_intensive_ops:
|
| 108 |
+
return CheckpointPolicy.MUST_SAVE
|
| 109 |
+
return CheckpointPolicy.PREFER_RECOMPUTE
|
| 110 |
+
|
| 111 |
+
context_fn = partial(create_selective_checkpoint_contexts, policy_fn)
|
| 112 |
+
|
| 113 |
+
for run_nb in range(n_rounds):
|
| 114 |
+
zero_grads(layer)
|
| 115 |
+
input_tensor.grad = None
|
| 116 |
+
|
| 117 |
+
torch.cuda.synchronize()
|
| 118 |
+
start_time = time.time()
|
| 119 |
+
|
| 120 |
+
mem_a_gb = torch.cuda.memory_allocated() / (1 << 30)
|
| 121 |
+
print(f"before fwd {mem_a_gb=:.2f}GB")
|
| 122 |
+
|
| 123 |
+
if recompute:
|
| 124 |
+
output_tensor = checkpoint(
|
| 125 |
+
layer,
|
| 126 |
+
use_reentrant=False,
|
| 127 |
+
context_fn=context_fn,
|
| 128 |
+
**forward_kwargs,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
else:
|
| 132 |
+
output_tensor = layer(**forward_kwargs)
|
| 133 |
+
|
| 134 |
+
mem_a_gb = torch.cuda.memory_allocated() / (1 << 30)
|
| 135 |
+
print(f"after fwd {mem_a_gb=:.2f}GB")
|
| 136 |
+
|
| 137 |
+
if isinstance(output_tensor, tuple):
|
| 138 |
+
output_tensor = output_tensor[0]
|
| 139 |
+
run_backward((output_tensor,), (d_output_tensor,))
|
| 140 |
+
|
| 141 |
+
mem_a_gb = torch.cuda.memory_allocated() / (1 << 30)
|
| 142 |
+
print(f"after bwd {mem_a_gb=:.2f}GB")
|
| 143 |
+
|
| 144 |
+
torch.cuda.synchronize()
|
| 145 |
+
finish_time = time.time()
|
| 146 |
+
time_taken = finish_time - start_time
|
| 147 |
+
|
| 148 |
+
mem_a_gb = torch.cuda.max_memory_allocated() / (1 << 30)
|
| 149 |
+
mem_r_gb = torch.cuda.max_memory_reserved() / (1 << 30)
|
| 150 |
+
if recompute:
|
| 151 |
+
ctx_size_gb = input_tensor.numel() * input_tensor.element_size() / (1 << 30)
|
| 152 |
+
print(f"{run_nb=} {time_taken=:.5f}s {mem_a_gb=:.2f}GB {mem_r_gb=:.2f}GB {ctx_size_gb=:.2f}GB")
|
| 153 |
+
else:
|
| 154 |
+
print(f"{run_nb=} {time_taken=:.5f}s {mem_a_gb=:.2f}GB {mem_r_gb=:.2f}GB")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def bench_qwen2_decoder_layer_gargantua(
|
| 158 |
+
layer: Qwen2DecoderLayer,
|
| 159 |
+
input_tensor: torch.Tensor,
|
| 160 |
+
position_embeddings: Tuple[torch.Tensor, torch.Tensor],
|
| 161 |
+
cu_seqlens: torch.Tensor,
|
| 162 |
+
max_seqlen: torch.Tensor,
|
| 163 |
+
d_output_tensor: torch.Tensor,
|
| 164 |
+
recompute_rms_norm: bool = False,
|
| 165 |
+
recompute_qkv_proj: bool = False,
|
| 166 |
+
recompute_attn: bool = False,
|
| 167 |
+
recompute_mlp: bool = False,
|
| 168 |
+
recompute_silu: bool = False,
|
| 169 |
+
n_rounds: int = 10,
|
| 170 |
+
):
|
| 171 |
+
for run_nb in range(n_rounds):
|
| 172 |
+
zero_grads(layer)
|
| 173 |
+
input_tensor.grad = None
|
| 174 |
+
|
| 175 |
+
torch.cuda.synchronize()
|
| 176 |
+
start_time = time.time()
|
| 177 |
+
|
| 178 |
+
output_tensor, ctx = Qwen2DecoderLayerFunc.apply_module(
|
| 179 |
+
layer=layer,
|
| 180 |
+
x=input_tensor,
|
| 181 |
+
cos=position_embeddings[0],
|
| 182 |
+
sin=position_embeddings[1],
|
| 183 |
+
cu_seqlens=cu_seqlens,
|
| 184 |
+
max_seqlen=max_seqlen,
|
| 185 |
+
recompute_rms_norm=recompute_rms_norm,
|
| 186 |
+
recompute_qkv_proj=recompute_qkv_proj,
|
| 187 |
+
recompute_attn=recompute_attn,
|
| 188 |
+
recompute_mlp=recompute_mlp,
|
| 189 |
+
recompute_silu=recompute_silu,
|
| 190 |
+
)
|
| 191 |
+
ctx_size_gb = ctx.calc_size() / (1 << 30)
|
| 192 |
+
run_backward((output_tensor,), (d_output_tensor,))
|
| 193 |
+
|
| 194 |
+
torch.cuda.synchronize()
|
| 195 |
+
finish_time = time.time()
|
| 196 |
+
time_taken = finish_time - start_time
|
| 197 |
+
|
| 198 |
+
mem_a_gb = torch.cuda.max_memory_allocated() / (1 << 30)
|
| 199 |
+
mem_r_gb = torch.cuda.max_memory_reserved() / (1 << 30)
|
| 200 |
+
print(f"{run_nb=} {time_taken=:.5f}s {mem_a_gb=:.2f}GB {mem_r_gb=:.2f}GB {ctx_size_gb=:.2f}GB")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def main():
|
| 204 |
+
parser = argparse.ArgumentParser()
|
| 205 |
+
parser.add_argument("-s", "--seqlen", type=int, default=4 << 10)
|
| 206 |
+
parser.add_argument("-t", "--type", choices=["gargantua", "hf"], default="gargantua")
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--deterministic",
|
| 209 |
+
action="store_true",
|
| 210 |
+
help="Use deterministic algo",
|
| 211 |
+
)
|
| 212 |
+
parser.add_argument(
|
| 213 |
+
"--compile",
|
| 214 |
+
action="store_true",
|
| 215 |
+
help="Compile layer (only effective for hf)",
|
| 216 |
+
)
|
| 217 |
+
parser.add_argument("--use_liger", action="store_true")
|
| 218 |
+
parser.add_argument("--activation_memory_budget", type=float, default=1.0)
|
| 219 |
+
parser.add_argument("--recompute_hf", action="store_true")
|
| 220 |
+
parser.add_argument("--recompute_hf_skip_attn", action="store_true")
|
| 221 |
+
parser.add_argument("--recompute_rms_norm", action="store_true")
|
| 222 |
+
parser.add_argument("--recompute_qkv_proj", action="store_true")
|
| 223 |
+
parser.add_argument("--recompute_attn", action="store_true")
|
| 224 |
+
parser.add_argument("--recompute_mlp", action="store_true")
|
| 225 |
+
parser.add_argument("--recompute_silu", action="store_true")
|
| 226 |
+
args = parser.parse_args()
|
| 227 |
+
print(args)
|
| 228 |
+
|
| 229 |
+
torch._functorch.config.activation_memory_budget = args.activation_memory_budget
|
| 230 |
+
|
| 231 |
+
if args.deterministic:
|
| 232 |
+
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
|
| 233 |
+
os.environ["FLASH_ATTENTION_DETERMINISTIC"] = "1"
|
| 234 |
+
seed = 1729 # interesting
|
| 235 |
+
torch.manual_seed(seed)
|
| 236 |
+
torch.cuda.manual_seed(seed)
|
| 237 |
+
torch.cuda.manual_seed_all(seed)
|
| 238 |
+
torch.backends.cudnn.deterministic = True
|
| 239 |
+
torch.backends.cudnn.benchmark = False
|
| 240 |
+
torch.use_deterministic_algorithms(True)
|
| 241 |
+
|
| 242 |
+
if args.use_liger:
|
| 243 |
+
from liger_kernel.transformers import apply_liger_kernel_to_qwen2
|
| 244 |
+
apply_liger_kernel_to_qwen2()
|
| 245 |
+
|
| 246 |
+
# Init model
|
| 247 |
+
config = make_config()
|
| 248 |
+
layer = Qwen2DecoderLayer(config=config, layer_idx=0)
|
| 249 |
+
rotary_emb = Qwen2RotaryEmbedding(config, device="cuda")
|
| 250 |
+
layer.train().to(torch.bfloat16).cuda()
|
| 251 |
+
|
| 252 |
+
if args.compile:
|
| 253 |
+
layer.compile(dynamic=True)
|
| 254 |
+
|
| 255 |
+
# Make some dummy data
|
| 256 |
+
seqlen = args.seqlen
|
| 257 |
+
input_tensor = torch.randn(1, seqlen, config.hidden_size, dtype=torch.bfloat16, device="cuda")
|
| 258 |
+
position_ids = torch.arange(seqlen, dtype=torch.long, device="cuda")[None]
|
| 259 |
+
attention_mask = torch.ones_like(position_ids)
|
| 260 |
+
|
| 261 |
+
position_embeddings = rotary_emb(input_tensor, position_ids)
|
| 262 |
+
cu_seqlens = torch.tensor([0, seqlen], dtype=torch.int32, device="cuda")
|
| 263 |
+
max_seqlen = cu_seqlens.diff().max()
|
| 264 |
+
|
| 265 |
+
d_output_tensor = torch.randn_like(input_tensor)
|
| 266 |
+
input_tensor = input_tensor.detach().requires_grad_(True)
|
| 267 |
+
|
| 268 |
+
if args.type == "gargantua":
|
| 269 |
+
bench_qwen2_decoder_layer_gargantua(
|
| 270 |
+
layer=layer,
|
| 271 |
+
input_tensor=input_tensor,
|
| 272 |
+
position_embeddings=position_embeddings,
|
| 273 |
+
cu_seqlens=cu_seqlens,
|
| 274 |
+
max_seqlen=max_seqlen,
|
| 275 |
+
d_output_tensor=d_output_tensor,
|
| 276 |
+
recompute_rms_norm=args.recompute_rms_norm,
|
| 277 |
+
recompute_qkv_proj=args.recompute_qkv_proj,
|
| 278 |
+
recompute_attn=args.recompute_attn,
|
| 279 |
+
recompute_mlp=args.recompute_mlp,
|
| 280 |
+
recompute_silu=args.recompute_silu,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
else:
|
| 284 |
+
bench_qwen2_decoder_layer_hf(
|
| 285 |
+
layer=layer,
|
| 286 |
+
input_tensor=input_tensor,
|
| 287 |
+
attention_mask=attention_mask,
|
| 288 |
+
position_ids=position_ids,
|
| 289 |
+
position_embeddings=position_embeddings,
|
| 290 |
+
cu_seqlens=cu_seqlens,
|
| 291 |
+
max_seqlen=max_seqlen,
|
| 292 |
+
d_output_tensor=d_output_tensor,
|
| 293 |
+
recompute=args.recompute_hf,
|
| 294 |
+
recompute_skip_attn=args.recompute_hf_skip_attn,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
if __name__ == "__main__":
|
| 299 |
+
main()
|
playground/Abbie-h100/tests/bench_transformer_layer.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
from contextlib import nullcontext
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.distributed as dist
|
| 7 |
+
from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeRotaryEmbedding
|
| 8 |
+
|
| 9 |
+
from abbie.device_mesh_manager import DMM
|
| 10 |
+
from abbie.gargantua.config import GenericTransformerConfig
|
| 11 |
+
from abbie.gargantua.functional import GargantuaLayerFunc
|
| 12 |
+
from abbie.gargantua.layer import GenericTransformerLayer
|
| 13 |
+
from abbie.gargantua.overlapper import get_overlapper
|
| 14 |
+
from abbie.utils.deterministic_utils import set_deterministic
|
| 15 |
+
from abbie.utils.flash_attn_utils import gather_cu_seqlens_from_position_ids
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
MODEL_TYPE_TO_CONFIG_KWARGS = {
|
| 19 |
+
"qwen2_7b": {
|
| 20 |
+
"hidden_size": 3584,
|
| 21 |
+
"num_attention_heads": 28,
|
| 22 |
+
"num_key_value_heads": 4,
|
| 23 |
+
"use_qkv_bias": False,
|
| 24 |
+
"use_o_bias": False,
|
| 25 |
+
"use_qk_norm": False,
|
| 26 |
+
"intermediate_size": 18944,
|
| 27 |
+
"use_mlp_gate_up_bias": False,
|
| 28 |
+
"use_mlp_down_bias": False,
|
| 29 |
+
},
|
| 30 |
+
"qwen3_4b": {
|
| 31 |
+
"hidden_size": 2560,
|
| 32 |
+
"head_size": 128,
|
| 33 |
+
"num_attention_heads": 32,
|
| 34 |
+
"num_key_value_heads": 8,
|
| 35 |
+
"use_qkv_bias": False,
|
| 36 |
+
"use_o_bias": False,
|
| 37 |
+
"use_qk_norm": True,
|
| 38 |
+
"intermediate_size": 9728,
|
| 39 |
+
"use_mlp_gate_up_bias": False,
|
| 40 |
+
"use_mlp_down_bias": False,
|
| 41 |
+
},
|
| 42 |
+
"qwen3_8b": {
|
| 43 |
+
"hidden_size": 4096,
|
| 44 |
+
"head_size": 128,
|
| 45 |
+
"num_attention_heads": 32,
|
| 46 |
+
"num_key_value_heads": 8,
|
| 47 |
+
"use_qkv_bias": False,
|
| 48 |
+
"use_o_bias": False,
|
| 49 |
+
"use_qk_norm": True,
|
| 50 |
+
"intermediate_size": 12288,
|
| 51 |
+
"use_mlp_gate_up_bias": False,
|
| 52 |
+
"use_mlp_down_bias": False,
|
| 53 |
+
},
|
| 54 |
+
"qwen3_moe_30b": {
|
| 55 |
+
"hidden_size": 2048,
|
| 56 |
+
"head_size": 128,
|
| 57 |
+
"num_attention_heads": 32,
|
| 58 |
+
"num_key_value_heads": 4,
|
| 59 |
+
"use_qkv_bias": False,
|
| 60 |
+
"use_o_bias": False,
|
| 61 |
+
"use_qk_norm": True,
|
| 62 |
+
"num_experts_per_tok": 8,
|
| 63 |
+
"num_routed_experts": 128,
|
| 64 |
+
"moe_intermediate_size": 768,
|
| 65 |
+
},
|
| 66 |
+
"qwen3_moe_235b": {
|
| 67 |
+
"hidden_size": 4096,
|
| 68 |
+
"head_size": 128,
|
| 69 |
+
"num_attention_heads": 64,
|
| 70 |
+
"num_key_value_heads": 4,
|
| 71 |
+
"use_qkv_bias": False,
|
| 72 |
+
"use_o_bias": False,
|
| 73 |
+
"use_qk_norm": True,
|
| 74 |
+
"num_experts_per_tok": 8,
|
| 75 |
+
"num_routed_experts": 128,
|
| 76 |
+
"moe_intermediate_size": 1536,
|
| 77 |
+
},
|
| 78 |
+
# We don't have sink attention or expert bias yet
|
| 79 |
+
"gpt_oss_20b": {
|
| 80 |
+
"hidden_size": 2880,
|
| 81 |
+
"head_size": 64,
|
| 82 |
+
"num_attention_heads": 64,
|
| 83 |
+
"num_key_value_heads": 8,
|
| 84 |
+
"use_qkv_bias": False,
|
| 85 |
+
"use_o_bias": False,
|
| 86 |
+
"use_qk_norm": False,
|
| 87 |
+
"num_experts_per_tok": 4,
|
| 88 |
+
"num_routed_experts": 32,
|
| 89 |
+
"moe_intermediate_size": 2880,
|
| 90 |
+
},
|
| 91 |
+
# We don't have sink attention or expert bias yet
|
| 92 |
+
"gpt_oss_120b": {
|
| 93 |
+
"hidden_size": 2880,
|
| 94 |
+
"head_size": 64,
|
| 95 |
+
"num_attention_heads": 64,
|
| 96 |
+
"num_key_value_heads": 8,
|
| 97 |
+
"use_qkv_bias": False,
|
| 98 |
+
"use_o_bias": False,
|
| 99 |
+
"use_qk_norm": False,
|
| 100 |
+
"num_experts_per_tok": 4,
|
| 101 |
+
"num_routed_experts": 128,
|
| 102 |
+
"moe_intermediate_size": 2880,
|
| 103 |
+
},
|
| 104 |
+
# We don't have MLA or shared experts yet
|
| 105 |
+
"deepseek_v3": {
|
| 106 |
+
"hidden_size": 7168,
|
| 107 |
+
"head_size": 128,
|
| 108 |
+
"num_attention_heads": 128,
|
| 109 |
+
"num_key_value_heads": 128,
|
| 110 |
+
"use_qkv_bias": False,
|
| 111 |
+
"use_o_bias": False,
|
| 112 |
+
"use_qk_norm": True,
|
| 113 |
+
"num_experts_per_tok": 9,
|
| 114 |
+
"num_routed_experts": 256,
|
| 115 |
+
"moe_intermediate_size": 2048,
|
| 116 |
+
},
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def get_gg_config(model_type: str, **extra_kwargs) -> GenericTransformerConfig:
|
| 121 |
+
kwargs = dict(MODEL_TYPE_TO_CONFIG_KWARGS[model_type])
|
| 122 |
+
kwargs.update(extra_kwargs)
|
| 123 |
+
|
| 124 |
+
return GenericTransformerConfig(
|
| 125 |
+
dp_group=DMM.dp_group,
|
| 126 |
+
pp_group=DMM.pp_group,
|
| 127 |
+
ep_group=DMM.ep_group,
|
| 128 |
+
norm_topk_prob=True,
|
| 129 |
+
use_moe_gate_up_bias=False,
|
| 130 |
+
use_moe_down_bias=False,
|
| 131 |
+
dtype=torch.bfloat16,
|
| 132 |
+
rope_theta=1e6,
|
| 133 |
+
rope_scaling={"type": "default"},
|
| 134 |
+
aux_loss_coef=None,
|
| 135 |
+
z_loss_coef=None,
|
| 136 |
+
**kwargs,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def make_gg_layer(config: GenericTransformerConfig):
|
| 141 |
+
layer = GenericTransformerLayer(config, layer_idx=0)
|
| 142 |
+
layer.train().cuda()
|
| 143 |
+
|
| 144 |
+
for param in layer.parameters():
|
| 145 |
+
param.data.normal_(0, std=1e-3)
|
| 146 |
+
|
| 147 |
+
return layer
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def bench_transformer_layer(
|
| 151 |
+
model_type: str,
|
| 152 |
+
seqlen: int = 4096,
|
| 153 |
+
num_mini_batch: int = 4,
|
| 154 |
+
num_steps: int = 10,
|
| 155 |
+
token_dispatch_method: str = "all-to-all",
|
| 156 |
+
**extra_kwargs,
|
| 157 |
+
):
|
| 158 |
+
# Init layer
|
| 159 |
+
config = get_gg_config(
|
| 160 |
+
model_type=model_type,
|
| 161 |
+
token_dispatch_method=token_dispatch_method,
|
| 162 |
+
**extra_kwargs,
|
| 163 |
+
)
|
| 164 |
+
layer = make_gg_layer(config)
|
| 165 |
+
rotary_emb = Qwen3MoeRotaryEmbedding(config, device="cuda")
|
| 166 |
+
|
| 167 |
+
if token_dispatch_method == "deep-ep":
|
| 168 |
+
from abbie.ops.deep_ep import setup_deep_ep_buffer
|
| 169 |
+
|
| 170 |
+
setup_deep_ep_buffer(
|
| 171 |
+
group=DMM.ep_group,
|
| 172 |
+
hidden_bytes=config.hidden_size * 2,
|
| 173 |
+
num_sms=20,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
elif token_dispatch_method == "hybrid-ep":
|
| 177 |
+
from abbie.ops.hybrid_ep import setup_hybrid_ep_buffer
|
| 178 |
+
|
| 179 |
+
setup_hybrid_ep_buffer(
|
| 180 |
+
ep_group=DMM.ep_group,
|
| 181 |
+
hidden_dim=config.hidden_size,
|
| 182 |
+
max_num_of_tokens_per_rank=seqlen,
|
| 183 |
+
num_local_experts=config.num_routed_experts_per_rank,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
if dist.get_rank() == 0:
|
| 187 |
+
print(config)
|
| 188 |
+
|
| 189 |
+
# Initialize some dummy inputs
|
| 190 |
+
input_tensor = torch.randn(seqlen, config.hidden_size, dtype=torch.bfloat16).cuda()
|
| 191 |
+
position_ids = []
|
| 192 |
+
while len(position_ids) < seqlen:
|
| 193 |
+
position_ids.extend(range(4096))
|
| 194 |
+
position_ids = position_ids[:seqlen]
|
| 195 |
+
position_ids = torch.tensor(position_ids, dtype=torch.long, device="cuda")
|
| 196 |
+
|
| 197 |
+
# attention_mask = torch.ones_like(position_ids)
|
| 198 |
+
|
| 199 |
+
position_embeddings = rotary_emb(input_tensor[None], position_ids[None])
|
| 200 |
+
cos, sin = position_embeddings[0][0], position_embeddings[1][0]
|
| 201 |
+
cu_seqlens, max_seqlen = gather_cu_seqlens_from_position_ids(position_ids)
|
| 202 |
+
|
| 203 |
+
d_output_tensor = torch.randn_like(input_tensor)
|
| 204 |
+
input_tensor.requires_grad_(True)
|
| 205 |
+
|
| 206 |
+
# Get the overlapper
|
| 207 |
+
overlapper = get_overlapper()
|
| 208 |
+
|
| 209 |
+
# Calculate some stats for perf calculations
|
| 210 |
+
ctx_size = None
|
| 211 |
+
|
| 212 |
+
n_local_params = 0
|
| 213 |
+
for param in layer.parameters():
|
| 214 |
+
n_local_params += param.numel()
|
| 215 |
+
|
| 216 |
+
n_attn_params = (config.num_attention_heads + config.num_key_value_heads) * 2
|
| 217 |
+
n_attn_params *= config.hidden_size * config.head_size
|
| 218 |
+
|
| 219 |
+
if config.num_experts_per_tok > 0:
|
| 220 |
+
n_expert_params = config.num_experts_per_tok * config.hidden_size * config.moe_intermediate_size * 3
|
| 221 |
+
n_act_params = n_attn_params + n_expert_params
|
| 222 |
+
else:
|
| 223 |
+
n_dense_params = config.hidden_size * config.intermediate_size * 3
|
| 224 |
+
n_act_params = n_attn_params + n_dense_params
|
| 225 |
+
|
| 226 |
+
seqlens = cu_seqlens.diff()
|
| 227 |
+
attn_tflop = (seqlens ** 2).sum().item() * config.hidden_size * 4 / 1e12
|
| 228 |
+
|
| 229 |
+
fwd_tflop = n_act_params * seqlen * 2 / 1e12
|
| 230 |
+
fwd_tflop += attn_tflop
|
| 231 |
+
|
| 232 |
+
event0 = torch.cuda.Event(enable_timing=True)
|
| 233 |
+
event1 = torch.cuda.Event(enable_timing=True)
|
| 234 |
+
event2 = torch.cuda.Event(enable_timing=True)
|
| 235 |
+
event3 = torch.cuda.Event(enable_timing=True)
|
| 236 |
+
|
| 237 |
+
if dist.get_rank() == 0:
|
| 238 |
+
print(f"n_local_params={n_local_params} n_act_params={n_act_params} {fwd_tflop=}")
|
| 239 |
+
|
| 240 |
+
for step_nb in range(num_steps):
|
| 241 |
+
total_forward_time = 0
|
| 242 |
+
total_overlap_time = 0
|
| 243 |
+
total_backward_time = 0
|
| 244 |
+
|
| 245 |
+
if step_nb == num_steps - 1:
|
| 246 |
+
profiler = torch.profiler.profile(
|
| 247 |
+
activities=[
|
| 248 |
+
torch.profiler.ProfilerActivity.CPU,
|
| 249 |
+
torch.profiler.ProfilerActivity.CUDA,
|
| 250 |
+
]
|
| 251 |
+
)
|
| 252 |
+
else:
|
| 253 |
+
profiler = nullcontext()
|
| 254 |
+
|
| 255 |
+
with profiler:
|
| 256 |
+
for _ in range(num_mini_batch):
|
| 257 |
+
torch.cuda.synchronize()
|
| 258 |
+
dist.barrier()
|
| 259 |
+
event0.record()
|
| 260 |
+
|
| 261 |
+
ctx0, output_tensor0 = GargantuaLayerFunc.apply_module(
|
| 262 |
+
layer=layer,
|
| 263 |
+
x=input_tensor,
|
| 264 |
+
cos=cos,
|
| 265 |
+
sin=sin,
|
| 266 |
+
cu_seqlens=cu_seqlens,
|
| 267 |
+
max_seqlen=max_seqlen,
|
| 268 |
+
global_num_tokens=seqlen,
|
| 269 |
+
)
|
| 270 |
+
event1.record()
|
| 271 |
+
|
| 272 |
+
if ctx_size is None:
|
| 273 |
+
# This will only impact first step
|
| 274 |
+
ctx_size = ctx0.calc_tensors_size()
|
| 275 |
+
# n_tokens_per_expert_in_group = ctx0.meta.get("n_tokens_per_expert_in_group")
|
| 276 |
+
|
| 277 |
+
overlapper.on()
|
| 278 |
+
ctx1, output_tensor1 = GargantuaLayerFunc.apply_module(
|
| 279 |
+
layer=layer,
|
| 280 |
+
x=input_tensor,
|
| 281 |
+
cos=position_embeddings[0],
|
| 282 |
+
sin=position_embeddings[1],
|
| 283 |
+
cu_seqlens=cu_seqlens,
|
| 284 |
+
max_seqlen=max_seqlen,
|
| 285 |
+
global_num_tokens=seqlen,
|
| 286 |
+
)
|
| 287 |
+
torch.autograd.backward(output_tensor0, d_output_tensor)
|
| 288 |
+
overlapper.off()
|
| 289 |
+
event2.record()
|
| 290 |
+
|
| 291 |
+
torch.autograd.backward(output_tensor1, d_output_tensor)
|
| 292 |
+
event3.record()
|
| 293 |
+
|
| 294 |
+
torch.cuda.synchronize()
|
| 295 |
+
|
| 296 |
+
total_forward_time += event0.elapsed_time(event1) / 1000.0
|
| 297 |
+
total_overlap_time += event1.elapsed_time(event2) / 1000.0
|
| 298 |
+
total_backward_time += event2.elapsed_time(event3) / 1000.0
|
| 299 |
+
|
| 300 |
+
if dist.get_rank() == 0:
|
| 301 |
+
fwd_tflops = fwd_tflop * num_mini_batch / total_forward_time
|
| 302 |
+
fwd_mfu = fwd_tflops / 989.5
|
| 303 |
+
bwd_tflops = fwd_tflop * num_mini_batch * 2 / total_backward_time
|
| 304 |
+
bwd_mfu = bwd_tflops / 989.5
|
| 305 |
+
overlap_tflops = fwd_tflop * num_mini_batch * 3 / total_overlap_time
|
| 306 |
+
overlap_mfu = overlap_tflops / 989.5
|
| 307 |
+
|
| 308 |
+
tokens_per_sec = seqlen * num_mini_batch / total_overlap_time
|
| 309 |
+
print(f"# {step_nb=}")
|
| 310 |
+
print("fwd / bwd / overlap")
|
| 311 |
+
print(f"time:\t{total_forward_time:.3f}\t{total_backward_time:.3f}\t{total_overlap_time:.3f}")
|
| 312 |
+
print(f"mfu:\t{fwd_mfu:.3f}\t{bwd_mfu:.3f}\t{overlap_mfu:.3f}")
|
| 313 |
+
print(f"tps: {tokens_per_sec:.1f}")
|
| 314 |
+
print(f"ctx_size={ctx_size / 1e9:.5f}GB")
|
| 315 |
+
|
| 316 |
+
if dist.get_rank() == 0:
|
| 317 |
+
if not isinstance(profiler, nullcontext):
|
| 318 |
+
profiler.export_chrome_trace("trace.json")
|
| 319 |
+
|
| 320 |
+
# print(f"rank={dist.get_rank()} ctx_size={ctx_size / 1e9:.5f}GB")
|
| 321 |
+
# import torch.distributed as DIST
|
| 322 |
+
# if DIST.get_rank() == 0:
|
| 323 |
+
# import pdb; pdb.set_trace()
|
| 324 |
+
# DIST.barrier()
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def main():
|
| 328 |
+
parser = argparse.ArgumentParser()
|
| 329 |
+
|
| 330 |
+
parser.add_argument("--model_type", default="qwen3_moe_30b", choices=MODEL_TYPE_TO_CONFIG_KWARGS.keys())
|
| 331 |
+
|
| 332 |
+
parser.add_argument("--seqlen", type=int, default=4096)
|
| 333 |
+
parser.add_argument("--ep", type=int, default=1)
|
| 334 |
+
|
| 335 |
+
parser.add_argument("--num_mini_batch", type=int, default=4)
|
| 336 |
+
parser.add_argument("--num_steps", type=int, default=10)
|
| 337 |
+
|
| 338 |
+
parser.add_argument("--recompute_norm", action="store_true")
|
| 339 |
+
parser.add_argument("--recompute_attn_up_proj", action="store_true")
|
| 340 |
+
parser.add_argument("--recompute_attn", action="store_true")
|
| 341 |
+
parser.add_argument("--recompute_attn_down_proj", action="store_true")
|
| 342 |
+
parser.add_argument("--recompute_mlp", action="store_true")
|
| 343 |
+
parser.add_argument("--recompute_mlp_act", action="store_true")
|
| 344 |
+
parser.add_argument("--recompute_dispatch", action="store_true")
|
| 345 |
+
|
| 346 |
+
parser.add_argument("--token-dispatch-method", type=str, default="all-to-all")
|
| 347 |
+
|
| 348 |
+
args = parser.parse_args()
|
| 349 |
+
|
| 350 |
+
rank = int(os.getenv("RANK"))
|
| 351 |
+
local_rank = int(os.getenv("LOCAL_RANK"))
|
| 352 |
+
world_size = int(os.getenv("WORLD_SIZE"))
|
| 353 |
+
|
| 354 |
+
device = f"cuda:{local_rank}"
|
| 355 |
+
torch.cuda.set_device(device)
|
| 356 |
+
dist.init_process_group(
|
| 357 |
+
backend="nccl", init_method="env://", world_size=world_size, rank=rank, device_id=torch.device(device)
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
set_deterministic()
|
| 361 |
+
|
| 362 |
+
try:
|
| 363 |
+
DMM.initialize(ep_size=args.ep)
|
| 364 |
+
bench_transformer_layer(
|
| 365 |
+
model_type=args.model_type,
|
| 366 |
+
seqlen=args.seqlen,
|
| 367 |
+
num_mini_batch=args.num_mini_batch,
|
| 368 |
+
num_steps=args.num_steps,
|
| 369 |
+
recompute_norm=args.recompute_norm,
|
| 370 |
+
recompute_attn_up_proj=args.recompute_attn_up_proj,
|
| 371 |
+
recompute_attn=args.recompute_attn,
|
| 372 |
+
recompute_attn_down_proj=args.recompute_attn_down_proj,
|
| 373 |
+
recompute_mlp=args.recompute_mlp,
|
| 374 |
+
recompute_mlp_act=args.recompute_mlp_act,
|
| 375 |
+
recompute_dispatch=args.recompute_dispatch,
|
| 376 |
+
token_dispatch_method=args.token_dispatch_method,
|
| 377 |
+
)
|
| 378 |
+
finally:
|
| 379 |
+
dist.destroy_process_group()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
if __name__ == "__main__":
|
| 383 |
+
main()
|
playground/Abbie-h100/tests/close_check.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
def allclose(x, y, pct=5.0):
|
| 4 |
+
mask = torch.isclose(x, y, rtol=1e-5)
|
| 5 |
+
pct_diff = (mask.numel() - mask.sum()) / mask.numel() * 100
|
| 6 |
+
if pct_diff > pct:
|
| 7 |
+
print(x[torch.logical_not(mask)], y[torch.logical_not(mask)])
|
| 8 |
+
print("Problem: {:.2f}% of values not close.".format(pct_diff))
|
| 9 |
+
return False
|
| 10 |
+
else:
|
| 11 |
+
print("Passed: {:.2f}% of, values not close pct.".format(pct_diff))
|
| 12 |
+
return True
|
| 13 |
+
|
| 14 |
+
n_probs = torch.load( '/opt/tiger/n_probs.pt', weights_only=True)
|
| 15 |
+
n_hidden_states_grad = torch.load('/opt/tiger/n_hidden_states_grad.pt', weights_only=True)
|
| 16 |
+
n_rms_grad = torch.load('/opt/tiger/n_rms_grad.pt', weights_only=True)
|
| 17 |
+
n_dense_grad = torch.load('/opt/tiger/n_dense_grad.pt', weights_only=True)
|
| 18 |
+
n_query_layer_grad = torch.load('/opt/tiger/n_query_layer_grad.pt', weights_only=True)
|
| 19 |
+
n_key_layer_grad = torch.load('/opt/tiger/n_key_layer_grad.pt', weights_only=True)
|
| 20 |
+
n_value_layer_grad = torch.load('/opt/tiger/n_value_layer_grad.pt', weights_only=True)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
o_hidden_states_grad = torch.load('/opt/tiger/hidden_states_grad.pt', weights_only=True)
|
| 24 |
+
o_hidden_states_grad = o_hidden_states_grad.squeeze()
|
| 25 |
+
o_rms_grad = torch.load('/opt/tiger/o_rms_grad.pt', weights_only=True)
|
| 26 |
+
o_dense_grad = torch.load('/opt/tiger/o_dense_grad.pt', weights_only=True)
|
| 27 |
+
o_query_layer_grad = torch.load('/opt/tiger/o_query_layer_grad.pt', weights_only=True)
|
| 28 |
+
o_key_layer_grad = torch.load('/opt/tiger/o_key_layer_grad.pt', weights_only=True)
|
| 29 |
+
o_value_layer_grad = torch.load('/opt/tiger/o_value_layer_grad.pt', weights_only=True)
|
| 30 |
+
|
| 31 |
+
query_diff = torch.max(torch.abs(o_query_layer_grad - n_query_layer_grad)).item()
|
| 32 |
+
key_diff = torch.max(torch.abs(o_key_layer_grad - n_key_layer_grad)).item()
|
| 33 |
+
value_diff = torch.max(torch.abs(o_value_layer_grad - n_value_layer_grad)).item()
|
| 34 |
+
|
| 35 |
+
allclose(n_hidden_states_grad, o_hidden_states_grad)
|
| 36 |
+
allclose(n_rms_grad.squeeze(), o_rms_grad.squeeze())
|
| 37 |
+
allclose(n_dense_grad.squeeze(), o_dense_grad.squeeze())
|
| 38 |
+
|
| 39 |
+
threshold = 1e-5
|
| 40 |
+
if (query_diff < threshold and
|
| 41 |
+
key_diff < threshold and
|
| 42 |
+
value_diff < threshold):
|
| 43 |
+
print("\nPass!")
|
| 44 |
+
else:
|
| 45 |
+
print(f"\nFailed! {query_diff} {key_diff} {value_diff}")
|
playground/Abbie-h100/tests/pipe_compare.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
from typing import List, Tuple, Any, Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.distributed as dist
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
from torch.distributed.optim import ZeroRedundancyOptimizer
|
| 10 |
+
|
| 11 |
+
from dualpipe.module.config import GargantuaConfig
|
| 12 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 13 |
+
from dualpipe.module.baseline.transformer_layer import TransformerLayer
|
| 14 |
+
from dualpipe.module.parallel_states import build_rank_generator
|
| 15 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy, initialize_kernel
|
| 16 |
+
from dualpipe.communicator import Communicator
|
| 17 |
+
from dualpipe import DualPipeTrainMoeV
|
| 18 |
+
from dualpipe.module.debug import setup_dumper, enable_dumper, setup_sniffer
|
| 19 |
+
|
| 20 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/DualPipe/profiles'
|
| 21 |
+
|
| 22 |
+
INITIALIZE_RANGE = 0.013975424859373685
|
| 23 |
+
|
| 24 |
+
def shift_labels(labels, cu_seqlens):
|
| 25 |
+
pad_idx_tensor = torch.tensor(1).long().to(device=cu_seqlens.device)
|
| 26 |
+
# Preprocess labels first.
|
| 27 |
+
shift_labels = torch.cat((labels[1:], labels.new_ones((1))*pad_idx_tensor))
|
| 28 |
+
shift_labels.requires_grad = False
|
| 29 |
+
lbl_seq_lens = (cu_seqlens[1:] - 1).long()
|
| 30 |
+
shift_labels[lbl_seq_lens] = pad_idx_tensor
|
| 31 |
+
shift_labels = shift_labels.unsqueeze(0).transpose(0, 1).contiguous()
|
| 32 |
+
return shift_labels
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def criterion(output: torch.Tensor, labels: torch.Tensor, input_ctx: Tuple[Any]) -> torch.Tensor:
|
| 36 |
+
cu_seqlens = input_ctx[0]
|
| 37 |
+
sl = shift_labels(labels, cu_seqlens)
|
| 38 |
+
return vocab_parallel_cross_entropy(output, sl).transpose(0, 1).contiguous().mean()
|
| 39 |
+
|
| 40 |
+
def duplicate_four(tl: List[torch.Tensor]):
|
| 41 |
+
r = tl + tl + tl + tl
|
| 42 |
+
return r
|
| 43 |
+
|
| 44 |
+
def set_weight(layer: TransformerGargantuaLayer, layer2: TransformerGargantuaLayer,
|
| 45 |
+
rank: int, pp_rank: int, total_rank: int, layer_number: int,
|
| 46 |
+
vocab_size: int, hidden_size:int, inner_size: int, dtype: torch.dtype, device: str):
|
| 47 |
+
real_n_layer = layer_number
|
| 48 |
+
std = INITIALIZE_RANGE / math.sqrt(2 * real_n_layer)
|
| 49 |
+
# real_n_layer = self.config.n_layer - len(self.config.noop_transformer_layers)
|
| 50 |
+
# p.data.normal_(mean=0.0, std=self.config.initializer_range / math.sqrt(2 * real_n_layer))
|
| 51 |
+
|
| 52 |
+
vocab_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 53 |
+
logits_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 54 |
+
qkv = torch.nn.Linear(hidden_size, hidden_size * 3, bias=False, dtype=dtype, device=device)
|
| 55 |
+
dense = torch.nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device)
|
| 56 |
+
w1 = torch.nn.Linear(hidden_size, 2 * inner_size, bias=False, dtype=dtype, device=device)
|
| 57 |
+
w2 = torch.nn.Linear(inner_size, hidden_size, bias=False, dtype=dtype, device=device)
|
| 58 |
+
|
| 59 |
+
qkv_rmsnorm_weight = [torch.ones(hidden_size * 3, dtype=dtype, device=device)]
|
| 60 |
+
rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device)]
|
| 61 |
+
qkv_weight: List[torch.Tensor] = [qkv.weight]
|
| 62 |
+
dense_weight: List[torch.Tensor] = [dense.weight]
|
| 63 |
+
w1_weight: List[torch.Tensor] = [w1.weight]
|
| 64 |
+
w2_weight: List[torch.Tensor] = [w2.weight]
|
| 65 |
+
#gate_weight: List[torch.Tensor] = [a.weight for a in gate]
|
| 66 |
+
|
| 67 |
+
vocab_embedding.weight.data.normal_(mean=0.0, std=std)
|
| 68 |
+
logits_embedding.weight.data.normal_(mean=0.0, std=std)
|
| 69 |
+
for i in range(layer_number):
|
| 70 |
+
qkv_weight[i].data.normal_(mean=0.0, std=std)
|
| 71 |
+
dense_weight[i].data.normal_(mean=0.0, std=std)
|
| 72 |
+
w1_weight[i].data.normal_(mean=0.0, std=std)
|
| 73 |
+
w2_weight[i].data.normal_(mean=0.0, std=std)
|
| 74 |
+
#gate_weight[i].data.normal_(mean=0.0, std=std)
|
| 75 |
+
layer.set_weight(vocab_embedding.weight, logits_embedding.weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight, w2_weight, [], rmsnorm_weight)
|
| 76 |
+
layer2.set_weight(vocab_embedding.weight, logits_embedding.weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight, w2_weight, [], rmsnorm_weight)
|
| 77 |
+
|
| 78 |
+
def dump_weight(rank, layer0, layer1):
|
| 79 |
+
# considering only two global ranks, 0 and 1 and layer_number = 1
|
| 80 |
+
# when world_rank == 0:
|
| 81 |
+
# layer0 == vocab + l0
|
| 82 |
+
# layer1 == l3 + lm_head
|
| 83 |
+
# when world_rank == 1:
|
| 84 |
+
# layer0 == l1
|
| 85 |
+
# layer1 == l2
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
p = "/opt/tiger/dump"
|
| 89 |
+
if rank == 0:
|
| 90 |
+
print("Saving for rank 0 ...")
|
| 91 |
+
torch.save(layer0.embedding.weight, f'{p}/vocab_embedding.pt')
|
| 92 |
+
torch.save(layer1.lm_head, f'{p}/lm_head.pt')
|
| 93 |
+
torch.save(layer0.qkv[0], f"{p}/qkv_l_0.pt",)
|
| 94 |
+
torch.save(layer1.qkv[0], f"{p}/qkv_l_3.pt")
|
| 95 |
+
torch.save(layer0.dense[0], f"{p}/dense_l_0.pt")
|
| 96 |
+
torch.save(layer1.dense[0], f"{p}/dense_l_3.pt")
|
| 97 |
+
torch.save(layer0.w1[0], f"{p}/w1_l_0.pt")
|
| 98 |
+
torch.save(layer1.w1[0], f"{p}/w1_l_3.pt",)
|
| 99 |
+
torch.save(layer0.w2[0], f"{p}/w2_l_0.pt",)
|
| 100 |
+
torch.save(layer1.w2[0], f"{p}/w2_l_3.pt")
|
| 101 |
+
elif rank == 1:
|
| 102 |
+
print("Saving for rank 1...")
|
| 103 |
+
torch.save(layer0.qkv[0], f"{p}/qkv_l_1.pt")
|
| 104 |
+
torch.save(layer1.qkv[0], f"{p}/qkv_l_2.pt")
|
| 105 |
+
torch.save(layer0.dense[0], f"{p}/dense_l_1.pt")
|
| 106 |
+
torch.save(layer1.dense[0], f"{p}/dense_l_2.pt")
|
| 107 |
+
torch.save(layer0.w1[0], f"{p}/w1_l_1.pt")
|
| 108 |
+
torch.save(layer1.w1[0], f"{p}/w1_l_2.pt")
|
| 109 |
+
torch.save(layer0.w2[0], f"{p}/w2_l_1.pt")
|
| 110 |
+
torch.save(layer1.w2[0], f"{p}/w2_l_2.pt")
|
| 111 |
+
|
| 112 |
+
def load_weight(layer):
|
| 113 |
+
p = "/opt/tiger/dump"
|
| 114 |
+
layer.embedding.weight.data.copy_(torch.load(f'{p}/vocab_embedding.pt'))
|
| 115 |
+
layer.lm_head.data.copy_(torch.load(f'{p}/lm_head.pt'))
|
| 116 |
+
for i in range(4):
|
| 117 |
+
layer.qkv[i].data.copy_(torch.load(f'{p}/qkv_l_{i}.pt'))
|
| 118 |
+
layer.dense[i].data.copy_(torch.load(f'{p}/dense_l_{i}.pt'))
|
| 119 |
+
layer.w1[i].data.copy_(torch.load(f'{p}/w1_l_{i}.pt'))
|
| 120 |
+
layer.w2[i].data.copy_(torch.load(f'{p}/w2_l_{i}.pt'))
|
| 121 |
+
|
| 122 |
+
def all_same(a, b):
|
| 123 |
+
assert not (a - b).nonzero().any()
|
| 124 |
+
|
| 125 |
+
def compare_weight(rank, l, m0, m1):
|
| 126 |
+
if rank == 0:
|
| 127 |
+
all_same(l.embedding.weight, m0.embedding.weight)
|
| 128 |
+
all_same(l.lm_head, m1.lm_head)
|
| 129 |
+
all_same(l.qkv[0], m0.qkv[0])
|
| 130 |
+
all_same(l.qkv[3], m1.qkv[0])
|
| 131 |
+
all_same(l.dense[0], m0.dense[0])
|
| 132 |
+
all_same(l.dense[3], m1.dense[0])
|
| 133 |
+
all_same(l.w1[0], m0.w1[0])
|
| 134 |
+
all_same(l.w1[3], m1.w1[0])
|
| 135 |
+
all_same(l.w2[0], m0.w2[0])
|
| 136 |
+
all_same(l.w2[3], m1.w2[0])
|
| 137 |
+
print("verified on rank 0")
|
| 138 |
+
else:
|
| 139 |
+
all_same(l.qkv[1], m0.qkv[0])
|
| 140 |
+
all_same(l.qkv[2], m1.qkv[0])
|
| 141 |
+
all_same(l.dense[1], m0.dense[0])
|
| 142 |
+
all_same(l.dense[2], m1.dense[0])
|
| 143 |
+
all_same(l.w1[1], m0.w1[0])
|
| 144 |
+
all_same(l.w1[2], m1.w1[0])
|
| 145 |
+
all_same(l.w2[1], m0.w2[0])
|
| 146 |
+
all_same(l.w2[2], m1.w2[0])
|
| 147 |
+
print("verified on rank 1")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def build_inputs_and_labels(rank, micro_batch_size, num_chunk, hidden_size: int, offset: int=1, mod_num:int=16):
|
| 151 |
+
inputs = []
|
| 152 |
+
cu_seqlens = []
|
| 153 |
+
total_s = []
|
| 154 |
+
labels = []
|
| 155 |
+
input_shapes = []
|
| 156 |
+
for x in range(num_chunk):
|
| 157 |
+
i = (x) % mod_num
|
| 158 |
+
i0 = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/input_ids_rank_{i}.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 159 |
+
c0 = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/cu_seqlens_rank_{i}.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 160 |
+
l0 = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/labels_{i}.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 161 |
+
t0 = c0[-1].item()
|
| 162 |
+
s0 = (t0, micro_batch_size, hidden_size)
|
| 163 |
+
inputs.append(i0)
|
| 164 |
+
cu_seqlens.append(c0)
|
| 165 |
+
total_s.append(t0)
|
| 166 |
+
labels.append(l0)
|
| 167 |
+
input_shapes.append(s0)
|
| 168 |
+
return inputs, cu_seqlens, total_s, labels, input_shapes
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def main(rank, ngpus, pp_size: int = 2,
|
| 172 |
+
vocab_size: int = 136064,
|
| 173 |
+
hidden_size: int = 4096,
|
| 174 |
+
inner_size: int = 5504,
|
| 175 |
+
num_attention_head: int = 32,
|
| 176 |
+
micro_batch_size: int=1,
|
| 177 |
+
num_chunks: int=20,
|
| 178 |
+
layer_number: int=1):
|
| 179 |
+
setup_dumper(rank, 1)
|
| 180 |
+
#enable_dumper()
|
| 181 |
+
torch.cuda.set_device(rank)
|
| 182 |
+
torch.manual_seed(42)
|
| 183 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 184 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 185 |
+
#initialize_kernel()
|
| 186 |
+
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
|
| 187 |
+
group = dist.distributed_c10d._get_default_group()
|
| 188 |
+
world_size = group.size()
|
| 189 |
+
rank_generator = build_rank_generator(rank, world_size, 1, 1, pp_size)
|
| 190 |
+
rank_generator.init()
|
| 191 |
+
pp_group = rank_generator.get_pp_group()
|
| 192 |
+
pp_rank = torch.distributed.get_rank(pp_group)
|
| 193 |
+
|
| 194 |
+
gargantua_config = (
|
| 195 |
+
GargantuaConfig(
|
| 196 |
+
vocab_size, hidden_size, -1, num_attention_head, hidden_size, is_moe=False)
|
| 197 |
+
.with_dense_inner_size(inner_size)
|
| 198 |
+
.with_async_comm()
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
# init a communicator
|
| 202 |
+
comm = Communicator(rank, pp_group)
|
| 203 |
+
comm.setup_shape([(1, micro_batch_size, hidden_size)], torch.bfloat16)
|
| 204 |
+
|
| 205 |
+
first_rank = rank_generator.is_first_rank()
|
| 206 |
+
m0 = TransformerGargantuaLayer(rank_generator, gargantua_config, layer_number=layer_number, first_stage=first_rank)
|
| 207 |
+
m1 = TransformerGargantuaLayer(rank_generator, gargantua_config, layer_number=layer_number, last_stage=first_rank)
|
| 208 |
+
set_weight(m0, m1, rank, pp_rank, ngpus, layer_number, vocab_size, hidden_size, inner_size, torch.bfloat16, f'cuda:{rank}')
|
| 209 |
+
dump_weight(rank, m0, m1)
|
| 210 |
+
#if rank == 0:
|
| 211 |
+
# baseline = TransformerGargantuaLayer(rank_generator, gargantua_config, layer_number=layer_number * 4, first_stage=True, last_stage=True)
|
| 212 |
+
# load_weight(baseline)
|
| 213 |
+
# compare_weight(rank, baseline, m0, m1)
|
| 214 |
+
#else:
|
| 215 |
+
# baseline = None
|
| 216 |
+
local_modules = torch.nn.Sequential(m0, m1)
|
| 217 |
+
#ddp_module = DDP(ddp_config, local_modules, rank_generator.get_dp_group())
|
| 218 |
+
|
| 219 |
+
# ddp_module = DDP(local_modules)
|
| 220 |
+
dualpipev_model = DualPipeTrainMoeV(local_modules, comm, rank_mapping=rank_generator.get_pp_ranks(), batch_dim=1, enable_overlap_fwd_bwd=True)
|
| 221 |
+
|
| 222 |
+
dense_optim = ZeroRedundancyOptimizer(
|
| 223 |
+
m0.dense_parameters() + m1.dense_parameters(),
|
| 224 |
+
optimizer_class=torch.optim.AdamW,
|
| 225 |
+
lr=3e-5,
|
| 226 |
+
process_group=rank_generator.get_dp_group(),
|
| 227 |
+
)
|
| 228 |
+
if rank_generator.is_first_rank():
|
| 229 |
+
print(f"[Rank-{rank}] I am the first rank among {ngpus=}, {inner_size}, {hidden_size=}, {num_attention_head=}", flush=True)
|
| 230 |
+
print(f"[Rank]")
|
| 231 |
+
hidden_states, cu_seqlens, total_s, l, hidden_shapes = build_inputs_and_labels(rank, micro_batch_size, num_chunks, hidden_size, offset=rank)
|
| 232 |
+
|
| 233 |
+
dense_optim.zero_grad()
|
| 234 |
+
if not rank_generator.is_first_rank():
|
| 235 |
+
hidden_states = [None for _ in range(num_chunks)]
|
| 236 |
+
input_ctx = [(c, t) for c, t in zip(cu_seqlens, total_s)]
|
| 237 |
+
loss, outputs = dualpipev_model.step(hidden_states, input_shapes=hidden_shapes, input_ctx=input_ctx, num_chunks=num_chunks, criterion=criterion, labels=l, return_outputs=False)
|
| 238 |
+
|
| 239 |
+
if loss is not None:
|
| 240 |
+
print(f"[Rank-{rank}]: loss mean = {loss.mean()}")
|
| 241 |
+
dense_optim.step()
|
| 242 |
+
|
| 243 |
+
print(f"[{rank}] {loss}")
|
| 244 |
+
|
| 245 |
+
def main_two(rank, ngpus, pp_size: int = 2,
|
| 246 |
+
vocab_size: int = 136064,
|
| 247 |
+
hidden_size: int = 4096,
|
| 248 |
+
inner_size: int = 5504,
|
| 249 |
+
num_attention_head: int = 32,
|
| 250 |
+
micro_batch_size: int=1,
|
| 251 |
+
num_chunks: int=20,
|
| 252 |
+
layer_number: int=1):
|
| 253 |
+
setup_sniffer(rank, 1)
|
| 254 |
+
setup_dumper(rank, 1)
|
| 255 |
+
torch.cuda.set_device(rank)
|
| 256 |
+
torch.manual_seed(42)
|
| 257 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 258 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 259 |
+
#initialize_kernel()
|
| 260 |
+
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
|
| 261 |
+
group = dist.distributed_c10d._get_default_group()
|
| 262 |
+
world_size = group.size()
|
| 263 |
+
rank_generator = build_rank_generator(rank, world_size, 1, 1, 1)
|
| 264 |
+
rank_generator.init()
|
| 265 |
+
|
| 266 |
+
gargantua_config = (
|
| 267 |
+
GargantuaConfig(
|
| 268 |
+
vocab_size, hidden_size, -1, num_attention_head, hidden_size, is_moe=False)
|
| 269 |
+
.with_dense_inner_size(inner_size)
|
| 270 |
+
.with_async_comm()
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
# init a communicator
|
| 274 |
+
first_rank = rank_generator.is_first_rank()
|
| 275 |
+
if rank == 0:
|
| 276 |
+
baseline = TransformerGargantuaLayer(rank_generator, gargantua_config, layer_number=layer_number * 4, first_stage=True, last_stage=True)
|
| 277 |
+
load_weight(baseline)
|
| 278 |
+
|
| 279 |
+
hidden_states, cu_seqlens, total_s, l, hidden_shapes = build_inputs_and_labels(rank, micro_batch_size, num_chunks, hidden_size, offset=rank)
|
| 280 |
+
for i in range(len(hidden_states)):
|
| 281 |
+
if hidden_states[i].shape[1] != 8187:
|
| 282 |
+
print(f"skipping shape: {hidden_states[i].shape}")
|
| 283 |
+
continue
|
| 284 |
+
input_id = hidden_states[i].clone()
|
| 285 |
+
cu_seqlen = cu_seqlens[i].clone()
|
| 286 |
+
label = l[i].clone()
|
| 287 |
+
total_s = cu_seqlen[-1].item()
|
| 288 |
+
sl = shift_labels(label, cu_seqlen)
|
| 289 |
+
baseline.set_input_ctx((cu_seqlen, total_s))
|
| 290 |
+
res = baseline.forward(input_id)
|
| 291 |
+
baseline_loss = vocab_parallel_cross_entropy(res, sl)
|
| 292 |
+
baseline_loss = baseline_loss.transpose(0, 1).contiguous().mean()
|
| 293 |
+
print(f"[Rank-{rank}] Loss_mean: {baseline_loss}")
|
| 294 |
+
baseline_loss.backward()
|
| 295 |
+
print("Finish baseline")
|
| 296 |
+
|
| 297 |
+
def test_cross_node(ngpus):
|
| 298 |
+
#torch.multiprocessing.spawn(main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 299 |
+
torch.multiprocessing.spawn(main_two, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
num_gpus = torch.cuda.device_count()
|
| 304 |
+
testing_gpu = 2
|
| 305 |
+
assert testing_gpu <= num_gpus
|
| 306 |
+
test_cross_node(testing_gpu)
|
playground/Abbie-h100/tests/shard_parquet.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def shard_parquet(input_path: str, output_dir: str, num_shards: int = 8):
|
| 7 |
+
"""
|
| 8 |
+
Shard a parquet file into multiple smaller files.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
input_path: Path to input parquet file
|
| 12 |
+
output_dir: Directory to save sharded files
|
| 13 |
+
num_shards: Number of shards to create (default: 8)
|
| 14 |
+
|
| 15 |
+
Returns:
|
| 16 |
+
List of output file paths
|
| 17 |
+
"""
|
| 18 |
+
# Create output directory
|
| 19 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# Read entire file
|
| 22 |
+
df = pd.read_parquet(input_path)
|
| 23 |
+
total_rows = len(df)
|
| 24 |
+
|
| 25 |
+
# Calculate rows per shard
|
| 26 |
+
rows_per_shard = total_rows // num_shards
|
| 27 |
+
remainder = total_rows % num_shards
|
| 28 |
+
|
| 29 |
+
# Create output file paths
|
| 30 |
+
input_name = Path(input_path).stem
|
| 31 |
+
output_paths = []
|
| 32 |
+
|
| 33 |
+
current_idx = 0
|
| 34 |
+
|
| 35 |
+
for i in range(num_shards):
|
| 36 |
+
# Calculate shard size (distribute remainder across first few shards)
|
| 37 |
+
shard_size = rows_per_shard + (1 if i < remainder else 0)
|
| 38 |
+
|
| 39 |
+
# Extract shard data
|
| 40 |
+
start_idx = current_idx
|
| 41 |
+
end_idx = current_idx + shard_size
|
| 42 |
+
shard_df = df.iloc[start_idx:end_idx].copy()
|
| 43 |
+
|
| 44 |
+
# Create output path
|
| 45 |
+
output_path = os.path.join(output_dir, f"{input_name}_shard_{i:03d}.parquet")
|
| 46 |
+
output_paths.append(output_path)
|
| 47 |
+
|
| 48 |
+
# Save shard
|
| 49 |
+
shard_df.to_parquet(output_path, compression='snappy', index=False)
|
| 50 |
+
|
| 51 |
+
print(f"Shard {i}: {len(shard_df):,} rows -> {output_path}")
|
| 52 |
+
|
| 53 |
+
current_idx = end_idx
|
| 54 |
+
|
| 55 |
+
print(f"Total: {total_rows:,} rows split into {num_shards} shards")
|
| 56 |
+
return output_paths
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Example usage
|
| 60 |
+
if __name__ == '__main__':
|
| 61 |
+
# Shard a parquet file into 8 sub-files
|
| 62 |
+
output_files = shard_parquet("/opt/tiger/datasets/train-00000-of-00001-b513d9e388d56453.parquet", "/opt/tiger/datasets/", num_shards=8)
|
playground/Abbie-h100/tests/shared/__init__.py
ADDED
|
File without changes
|
playground/Abbie-h100/tests/shared/download.sh
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
mkdir -p /opt/tiger/tokenizer
|
| 2 |
+
mkdir -p /opt/tiger/model_weights
|
| 3 |
+
mkdir -p /opt/tiger/datasets
|
| 4 |
+
|
| 5 |
+
# For model weights dump
|
| 6 |
+
cd /opt/tiger/model_weights
|
| 7 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/user/yuyifeng.oscar/moe_ep2
|
| 8 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/user/yuyifeng.oscar/1b2
|
| 9 |
+
# with GQA version.
|
| 10 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/users/yuyifeng.oscar/dense_gqa2_4ranks
|
| 11 |
+
|
| 12 |
+
# For inputs sample
|
| 13 |
+
cd /opt/tiger/datasets
|
| 14 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/user/yuyifeng.oscar/moe_ep2_inputs inputs_58M_2ranks
|
| 15 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/user/yuyifeng.oscar/inputs_58M_4ranks
|
| 16 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/user/yuyifeng.oscar/inputs_58M
|
| 17 |
+
|
| 18 |
+
# For tokenizer
|
| 19 |
+
cd /opt/tiger/tokenizer
|
| 20 |
+
hdfs dfs get hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227
|
| 21 |
+
|
| 22 |
+
#
|
| 23 |
+
cd /opt/tiger/Abbie
|
playground/Abbie-h100/tests/shared/moe_route.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from dualpipe.module.config import GargantuaConfig
|
| 6 |
+
from dualpipe.module.debug import MEM
|
| 7 |
+
from dualpipe.module.gargantua.aux_loss import AuxLoadbalancingLoss
|
| 8 |
+
from dualpipe.module.gargantua.functors import LinearMegatronFunc, LinearTEFunc, TopkFunc, TopKSoftmaxFunc
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
use_te_router_linear = os.getenv("ENABLE_GARGANTUA_TE_ROUTER_LINEAR", "1") == "1"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def z_loss_func(logits, z_loss_coeff):
|
| 15 |
+
"""Encourages the router's logits to remain small to enhance stability.
|
| 16 |
+
Please refer to the ST-MoE paper (https://arxiv.org/pdf/2202.08906.pdf) for details.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
logits (torch.Tensor): The logits of the router.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
torch.Tensor: The logits after applying the z-loss.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
z_loss = torch.mean(torch.square(torch.logsumexp(logits, dim=-1))) * z_loss_coeff
|
| 26 |
+
return z_loss
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class MoERouterFunc:
|
| 30 |
+
@staticmethod
|
| 31 |
+
def forward(hidden_states, gating: torch.Tensor, num_experts: int, config: GargantuaConfig, input_jitter=None):
|
| 32 |
+
topk = config.moe_router_topk
|
| 33 |
+
hidden_dtype = hidden_states.dtype
|
| 34 |
+
routing_type = config.moe_router_load_balancing_type
|
| 35 |
+
input_fp32 = hidden_states.float()
|
| 36 |
+
with torch.cuda.amp.autocast(dtype=torch.float32):
|
| 37 |
+
# jitter.
|
| 38 |
+
logits = torch.nn.functional.linear(input_fp32, gating.to(dtype=input_fp32.dtype))
|
| 39 |
+
if config.moe_z_loss_coeff is not None:
|
| 40 |
+
z_loss = z_loss_func(logits, config.moe_z_loss_coeff)
|
| 41 |
+
logits = logits.view(-1, num_experts)
|
| 42 |
+
|
| 43 |
+
if routing_type == "aux_loss":
|
| 44 |
+
probs_fp32, indices, tokens_per_expert, input_shape, topk_softmax_scores, topk, top_k_dim = (
|
| 45 |
+
TopKSoftmaxFunc.forward(logits, num_experts, topk)
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Apply load balancing loss
|
| 49 |
+
scores = torch.softmax(logits, dim=-1, dtype=torch.float32)
|
| 50 |
+
MEM.add_test("top_k_score_softmaxed", scores)
|
| 51 |
+
probs_fp32, aux_loss = AuxLoadbalancingLoss.forward(scores, tokens_per_expert, probs_fp32, config)
|
| 52 |
+
MEM.add_test("aux_loss_probs", probs_fp32)
|
| 53 |
+
probs = probs_fp32.to(dtype=hidden_dtype)
|
| 54 |
+
return probs, probs_fp32, indices, aux_loss, input_fp32, gating, input_shape, top_k_dim, logits
|
| 55 |
+
|
| 56 |
+
@staticmethod
|
| 57 |
+
def backward(
|
| 58 |
+
grad_output,
|
| 59 |
+
probs,
|
| 60 |
+
probs_fp32,
|
| 61 |
+
aux_loss,
|
| 62 |
+
tokens_per_expert,
|
| 63 |
+
config: GargantuaConfig,
|
| 64 |
+
indices,
|
| 65 |
+
input_shape,
|
| 66 |
+
top_k_dim,
|
| 67 |
+
input_fp32,
|
| 68 |
+
gating,
|
| 69 |
+
logits,
|
| 70 |
+
):
|
| 71 |
+
# TODO [yuyifeng.oscar] tricky tricky here to align grad_output to moe_baseline_router's backward probs(scores) grad.
|
| 72 |
+
# grad_output = grad_output.to(torch.bfloat16).to(torch.float32)
|
| 73 |
+
MEM.add_test_grad("router_grad_32", grad_output)
|
| 74 |
+
MEM.add_test("r_probs", probs)
|
| 75 |
+
# Calculate gradient from main loss path (dL/dprobs -> dL/dlogits_topk -> dL/dlogits)
|
| 76 |
+
# grad_topk = torch.ops.aten._softmax_backward_data(grad_output, probs.to(torch.float32), dim=top_k_dim, input_dtype=torch.float32)
|
| 77 |
+
g_probs_fp32 = grad_output.to(dtype=torch.float32)
|
| 78 |
+
grad_topk = torch.ops.aten._softmax_backward_data(
|
| 79 |
+
g_probs_fp32, probs_fp32, dim=top_k_dim, input_dtype=torch.float32
|
| 80 |
+
)
|
| 81 |
+
# grad_topk = SoftmaxFunc.backward(grad_output, probs, top_k_dim)#.to(dtype=torch.bfloat16)
|
| 82 |
+
MEM.add_test_grad("r_topk", grad_topk)
|
| 83 |
+
grad_logits_from_main_loss = TopkFunc.backward(grad_topk, indices, input_shape, top_k_dim)
|
| 84 |
+
|
| 85 |
+
# Calculate gradient from aux_loss path (dAuxLoss -> dAuxLoss/dScores_softmax -> dAuxLoss/dLogits)
|
| 86 |
+
# Recalculate scores_softmax as it's needed for aux loss backward
|
| 87 |
+
scores_softmax = torch.softmax(logits, dim=-1, dtype=torch.float32)
|
| 88 |
+
grad_scores_softmax_from_aux, _, _, _ = AuxLoadbalancingLoss.backward(
|
| 89 |
+
grad_logits_from_main_loss,
|
| 90 |
+
scores_softmax,
|
| 91 |
+
aux_loss,
|
| 92 |
+
tokens_per_expert,
|
| 93 |
+
config.moe_router_topk,
|
| 94 |
+
config.moe_aux_loss_coeff,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# Calculate dAuxLoss / dLogits using softmax backward
|
| 98 |
+
grad_logits_from_aux = torch.ops.aten._softmax_backward_data(
|
| 99 |
+
grad_scores_softmax_from_aux, scores_softmax, dim=-1, input_dtype=logits.dtype
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Combine gradients from both paths
|
| 103 |
+
grad_logits_total = grad_logits_from_main_loss + grad_logits_from_aux
|
| 104 |
+
# gating backward (dL/dLogits -> dL/dInput, dL/dGating)
|
| 105 |
+
gating = gating.to(dtype=grad_logits_total.dtype)
|
| 106 |
+
if use_te_router_linear:
|
| 107 |
+
grad_input = LinearTEFunc.backward(grad_logits_total, input_fp32, gating)
|
| 108 |
+
grad_input = grad_input.squeeze()
|
| 109 |
+
else:
|
| 110 |
+
grad_input = LinearMegatronFunc.backward(grad_logits_total, input_fp32, gating)
|
| 111 |
+
MEM.add_test_grad("r_gate_grad", grad_input)
|
| 112 |
+
|
| 113 |
+
# Return gradients for hidden_states (input) and gating weight
|
| 114 |
+
|
| 115 |
+
return grad_input, gating.grad, None, None, None
|
playground/Abbie-h100/tests/shared/optimizer.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict
|
| 2 |
+
import torch
|
| 3 |
+
import math
|
| 4 |
+
from torch.distributed.optim import ZeroRedundancyOptimizer
|
| 5 |
+
|
| 6 |
+
# ----------------------------- configurable hyper-params -----------------------------
|
| 7 |
+
total_steps = 50000 # how many optimiser.step() calls you expect
|
| 8 |
+
warmup_steps = 200 # ≈ 1-3 % of total_steps is typical
|
| 9 |
+
lr_max = 3e-4 # peak LR (your “LRmax”)
|
| 10 |
+
lr_min = 3e-5 # final LR (usually 0.05-0.1 × lr_max)
|
| 11 |
+
hold_steps = 0 # optional: keep lr_min flat for the last N steps
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# ---------------------------------------------------------------------------------------
|
| 15 |
+
|
| 16 |
+
def lr_lambda(current_step: int):
|
| 17 |
+
"""
|
| 18 |
+
0-----warm-up----------cosine----------flat--> 1 (returns *multiplicative* factor)
|
| 19 |
+
"""
|
| 20 |
+
if current_step < warmup_steps: # linear warm-up
|
| 21 |
+
return float(current_step) / float(max(1, warmup_steps))
|
| 22 |
+
|
| 23 |
+
progress = (current_step - warmup_steps) / float(max(1, total_steps - warmup_steps - hold_steps))
|
| 24 |
+
progress = min(progress, 1.0) # clip in case total_steps not precise
|
| 25 |
+
|
| 26 |
+
if current_step < total_steps - hold_steps: # cosine decay
|
| 27 |
+
cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
|
| 28 |
+
return cosine * (lr_max - lr_min) / lr_max + lr_min / lr_max
|
| 29 |
+
|
| 30 |
+
return lr_min / lr_max # flat tail
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_lr_lambda(constant: bool):
|
| 34 |
+
if constant:
|
| 35 |
+
return lambda _: lr_max
|
| 36 |
+
else:
|
| 37 |
+
return lr_lambda
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def build_optimizer(rank, world_size, module, dp_group, zero_redundant=False):
|
| 41 |
+
master_params = []
|
| 42 |
+
param_to_master_param = {}
|
| 43 |
+
name_to_param_and_master_param = {}
|
| 44 |
+
for name, param in module.named_parameters():
|
| 45 |
+
# Master gradient
|
| 46 |
+
print(f"[Rank-{rank}] GRAD_ACC, param name: {name} size: {param.shape} require_grad: {param.requires_grad}")
|
| 47 |
+
#p = param.detach().clone().float().requires_grad_()
|
| 48 |
+
p = torch.empty_like(param, dtype=torch.float32)
|
| 49 |
+
# Allocation of parameter's so called "main_grad"
|
| 50 |
+
# In TE Linear core (functors) they are just accumulated directly.
|
| 51 |
+
param.main_grad = p
|
| 52 |
+
master_params.append(p)
|
| 53 |
+
param_to_master_param[param] = p
|
| 54 |
+
name_to_param_and_master_param[name] = (param, p)
|
| 55 |
+
|
| 56 |
+
if world_size > 1 or zero_redundant:
|
| 57 |
+
optimizer = ZeroRedundancyOptimizer(
|
| 58 |
+
module.parameters(), # Still using old module's params.
|
| 59 |
+
optimizer_class=torch.optim.AdamW,
|
| 60 |
+
lr=lr_max,
|
| 61 |
+
weight_decay=0.1,
|
| 62 |
+
betas=(0.9, 0.95),
|
| 63 |
+
process_group=dp_group,
|
| 64 |
+
)
|
| 65 |
+
else:
|
| 66 |
+
optimizer = torch.optim.AdamW(master_params, lr=lr_max, betas=(0.9, 0.95), weight_decay=0.1)
|
| 67 |
+
|
| 68 |
+
# opt_param_scheduler = get_optimizer_param_scheduler(optimizer)
|
| 69 |
+
print(
|
| 70 |
+
f"Allocated CUDA Memory after configure optimizer: {torch.cuda.memory_allocated() / 1000.0 / 1000 / 1000} GB")
|
| 71 |
+
return optimizer, master_params, param_to_master_param, name_to_param_and_master_param
|
| 72 |
+
|
| 73 |
+
# This shall be booked mainly for optimizer to work.
|
| 74 |
+
def copy_back_grads(name_to_param_and_master_param):
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
for name, (p_bf16, p32_as_grad) in name_to_param_and_master_param.items():
|
| 77 |
+
if p_bf16.grad is None:
|
| 78 |
+
p_bf16.grad = p32_as_grad.bfloat16().clone()
|
| 79 |
+
else:
|
| 80 |
+
p_bf16.grad.copy_(p32_as_grad.bfloat16())
|
| 81 |
+
#assert p_bf16.grad.type() == 'torch.cuda.HalfTensor'
|
| 82 |
+
#assert p_bf16.grad.type() == 'torch.cuda.BFloat16Tensor'
|
| 83 |
+
|
| 84 |
+
def zero_out_master_grads(name_to_param_and_master_param):
|
| 85 |
+
print(f"Zeroing out accumulated master grad")
|
| 86 |
+
with torch.no_grad():
|
| 87 |
+
for name, (p_bf16, p32_grad) in name_to_param_and_master_param.items():
|
| 88 |
+
if p_bf16.grad is not None:
|
| 89 |
+
p_bf16.grad = None
|
| 90 |
+
p32_grad.zero_()
|
| 91 |
+
|
| 92 |
+
def sample_check_pow2_grad(module):
|
| 93 |
+
grads = []
|
| 94 |
+
total_grad = 0.0
|
| 95 |
+
for n, param in module.named_parameters():
|
| 96 |
+
if param.main_grad is not None:
|
| 97 |
+
copied = param.main_grad.clone().detach()
|
| 98 |
+
else:
|
| 99 |
+
copied = param.grad.clone().detach()
|
| 100 |
+
total_grad += copied.pow(2).sum()
|
| 101 |
+
#assert param.grad.type() == 'torch.cuda.FloatTensor'
|
| 102 |
+
print(f"{n} param shape: {copied.shape} grad mean: {copied.mean()} pow_2_sum: {copied.pow(2).sum()}")
|
| 103 |
+
grads.append(copied)
|
playground/Abbie-h100/tests/shared/preparation.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
from typing import Optional
|
| 4 |
+
from dualpipe.module.parallel_states import RankGenerator
|
| 5 |
+
|
| 6 |
+
NO_GQA_WEIGHT_PATH = '/opt/tiger/model_weights/1b2_4rank'
|
| 7 |
+
GQA_WEIGHT_PATH = '/opt/tiger/model_weights/dense_gqa2_4ranks/rank0'
|
| 8 |
+
MOE_WEIGHT_PATH = '/opt/tiger/model_weights/moe_weight'
|
| 9 |
+
MOE_WEIGHT_EP_PATH = '/opt/tiger/model_weights/moe_ep2'
|
| 10 |
+
TEST_PARQUET = "/opt/tiger/datasets/train-00000-of-00001-b513d9e388d56453.parquet"
|
| 11 |
+
SAHARA_INPUT_58M_PATH = '/opt/tiger/datasets/inputs_58M'
|
| 12 |
+
SAHARA_INPUT_58M_PATH_2RANK = '/opt/tiger/datasets/inputs_58M_2ranks'
|
| 13 |
+
SAHARA_INPUT_426M_PATH_2RANK = '/opt/tiger/datasets/inputs_426M_2ranks'
|
| 14 |
+
SAHARA_INPUT_58M_PATH_4RANK_MBS1 = '/opt/tiger/datasets/inputs_20250821_4rank'
|
| 15 |
+
SAHARA_INPUT_58M_PATH_4RANK_MBS2 = '/opt/tiger/datasets/input_58M_4rank_mbs2'
|
| 16 |
+
|
| 17 |
+
def get_parquet(rank, world_size):
|
| 18 |
+
if world_size == 1:
|
| 19 |
+
return TEST_PARQUET
|
| 20 |
+
else:
|
| 21 |
+
return f"hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_15T_0612_sample_200B/459eaadf/train/part-0000{rank}-51b7c256-8c76-480f-8dcc-6cd0946003b1-c000.snappy.parquet"
|
| 22 |
+
# return f"{TEST_PARQUET_TEMPLATE}_shard_00{rank}.parquet"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def preprare_data_input_58M(dp_rank, world_rank=None, mbs: int=1):
|
| 26 |
+
# for i in range(2):
|
| 27 |
+
if world_rank is None:
|
| 28 |
+
world_rank = dp_rank
|
| 29 |
+
input_ids = torch.load(f'{SAHARA_INPUT_58M_PATH}/input_ids_{dp_rank + 1}.pt', map_location=f'cuda:{world_rank}')
|
| 30 |
+
cu_seqlens = torch.load(f'{SAHARA_INPUT_58M_PATH}/cu_seqlens_{dp_rank + 1}.pt', map_location=f'cuda:{world_rank}')
|
| 31 |
+
word_idx = torch.load(f'{SAHARA_INPUT_58M_PATH}/word_idx_{dp_rank + 1}.pt', map_location=f'cuda:{world_rank}')
|
| 32 |
+
position_idx = torch.load(f'{SAHARA_INPUT_58M_PATH}/position_ids_{dp_rank + 1}.pt', map_location=f'cuda:{world_rank}')
|
| 33 |
+
lbl = torch.load(f'{SAHARA_INPUT_58M_PATH}/lbl_seq_lens_{dp_rank + 1}.pt', map_location=f'cuda:{world_rank}')
|
| 34 |
+
return input_ids, cu_seqlens, lbl, position_idx, word_idx
|
| 35 |
+
|
| 36 |
+
def preprare_data_input_58M_4rank(dp_rank, world_rank=None, mbs = 1):
|
| 37 |
+
# for i in range(2):
|
| 38 |
+
if world_rank is None:
|
| 39 |
+
world_rank = dp_rank
|
| 40 |
+
if mbs == 1:
|
| 41 |
+
SAHARA_INPUT_58M_PATH_4RANK = SAHARA_INPUT_58M_PATH_4RANK_MBS1
|
| 42 |
+
elif mbs == 2:
|
| 43 |
+
SAHARA_INPUT_58M_PATH_4RANK = SAHARA_INPUT_58M_PATH_4RANK_MBS2
|
| 44 |
+
else:
|
| 45 |
+
raise Exception("No dump data available for mbs not in (1,2) and dp_size=4")
|
| 46 |
+
print(f"preparing 4 rank data from {SAHARA_INPUT_58M_PATH_4RANK}")
|
| 47 |
+
input_ids = torch.load(f'{SAHARA_INPUT_58M_PATH_4RANK}/input_ids_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 48 |
+
cu_seqlens = torch.load(f'{SAHARA_INPUT_58M_PATH_4RANK}/cu_seqlens_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 49 |
+
word_idx = torch.load(f'{SAHARA_INPUT_58M_PATH_4RANK}/word_idx_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 50 |
+
position_idx = torch.load(f'{SAHARA_INPUT_58M_PATH_4RANK}/position_ids_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 51 |
+
lbl = torch.load(f'{SAHARA_INPUT_58M_PATH_4RANK}/lbl_seq_lens_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 52 |
+
return input_ids, cu_seqlens, lbl, position_idx, word_idx
|
| 53 |
+
|
| 54 |
+
def preprare_data_input_58M_2rank(dp_rank, world_rank=None, mbs: int=1):
|
| 55 |
+
# for i in range(2):
|
| 56 |
+
if world_rank is None:
|
| 57 |
+
world_rank = dp_rank
|
| 58 |
+
input_ids = torch.load(f'{SAHARA_INPUT_58M_PATH_2RANK}/input_ids_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 59 |
+
cu_seqlens = torch.load(f'{SAHARA_INPUT_58M_PATH_2RANK}/cu_seqlens_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 60 |
+
word_idx = torch.load(f'{SAHARA_INPUT_58M_PATH_2RANK}/word_idx_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 61 |
+
position_idx = torch.load(f'{SAHARA_INPUT_58M_PATH_2RANK}/position_ids_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 62 |
+
lbl = torch.load(f'{SAHARA_INPUT_58M_PATH_2RANK}/lbl_seq_lens_rank{dp_rank}_1.pt', map_location=f'cuda:{world_rank}')
|
| 63 |
+
return input_ids, cu_seqlens, lbl, position_idx, word_idx
|
| 64 |
+
|
| 65 |
+
def prepare_data_input_426M_2rank(dp_rank, world_rank=None, mbs: int=1):
|
| 66 |
+
if world_rank is None:
|
| 67 |
+
world_rank = dp_rank
|
| 68 |
+
input_ids = []
|
| 69 |
+
cu_seqlens = []
|
| 70 |
+
word_idx = []
|
| 71 |
+
position_idx = []
|
| 72 |
+
lbl = []
|
| 73 |
+
for i in range(6):
|
| 74 |
+
input_ids += torch.load(f'{SAHARA_INPUT_426M_PATH_2RANK}/input_ids_rank{dp_rank}_{i+1}.pt', map_location=f'cuda:{world_rank}')
|
| 75 |
+
cu_seqlens += torch.load(f'{SAHARA_INPUT_426M_PATH_2RANK}/cu_seqlens_rank{dp_rank}_{i+1}.pt', map_location=f'cuda:{world_rank}')
|
| 76 |
+
word_idx += torch.load(f'{SAHARA_INPUT_426M_PATH_2RANK}/word_idx_rank{dp_rank}_{i+1}.pt', map_location=f'cuda:{world_rank}')
|
| 77 |
+
position_idx += torch.load(f'{SAHARA_INPUT_426M_PATH_2RANK}/position_ids_rank{dp_rank}_{i+1}.pt', map_location=f'cuda:{world_rank}')
|
| 78 |
+
lbl += torch.load(f'{SAHARA_INPUT_426M_PATH_2RANK}/lbl_seq_lens_rank{dp_rank}_{i+1}.pt', map_location=f'cuda:{world_rank}')
|
| 79 |
+
return input_ids, cu_seqlens, lbl, position_idx, word_idx
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_sahara_58M_dataloader(dp_rank, dp_size, seq_len, tokenizer, mbs: int = 1, world_rank=None):
|
| 83 |
+
assert seq_len == 4096, "currently for sahara dump it's dumped in 4K fashion for test purpose"
|
| 84 |
+
if dp_size == 1:
|
| 85 |
+
input_ids, cu_seqlens, lbl_seq_lens, position_idxs, word_idxs = preprare_data_input_58M(dp_rank, world_rank, mbs)
|
| 86 |
+
elif dp_size == 2:
|
| 87 |
+
print("Using 2 rank sahara dump")
|
| 88 |
+
input_ids, cu_seqlens, lbl_seq_lens, position_idxs, word_idxs = preprare_data_input_58M_2rank(dp_rank, world_rank, mbs)
|
| 89 |
+
elif dp_size == 4:
|
| 90 |
+
print("Using 4 rank sahara dump")
|
| 91 |
+
input_ids, cu_seqlens, lbl_seq_lens, position_idxs, word_idxs = preprare_data_input_58M_4rank(dp_rank, world_rank, mbs)
|
| 92 |
+
else:
|
| 93 |
+
raise Exception("No dump data available")
|
| 94 |
+
for i, c, l, p, w in zip(input_ids, cu_seqlens, lbl_seq_lens, position_idxs, word_idxs):
|
| 95 |
+
yield {
|
| 96 |
+
"input_ids": i,
|
| 97 |
+
"cu_seqlens": c,
|
| 98 |
+
"lbl_seqlens": l,
|
| 99 |
+
"position_ids": p,
|
| 100 |
+
"word_ids": w
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
def get_sahara_426M_dataloader(dp_rank, dp_size, seq_len, tokenizer, mbs: int = 128, world_rank=None):
|
| 104 |
+
assert seq_len == 4096, "currently for sahara dump it's dumped in 4K fashion for test purpose"
|
| 105 |
+
if dp_size == 2:
|
| 106 |
+
print("Using 2 rank sahara dump")
|
| 107 |
+
input_ids, cu_seqlens, lbl_seq_lens, position_idxs, word_idxs = prepare_data_input_426M_2rank(dp_rank, world_rank, mbs)
|
| 108 |
+
else:
|
| 109 |
+
raise Exception("No dump data available")
|
| 110 |
+
for i, c, l, p, w in zip(input_ids, cu_seqlens, lbl_seq_lens, position_idxs, word_idxs):
|
| 111 |
+
yield {
|
| 112 |
+
"input_ids": i,
|
| 113 |
+
"cu_seqlens": c,
|
| 114 |
+
"lbl_seqlens": l,
|
| 115 |
+
"position_ids": p,
|
| 116 |
+
"word_ids": w
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
def moe_extract_weights(rank, expert_num, expert_size, local_experts, vocab_size, hidden_size, dtype, device, layer_number):
|
| 120 |
+
loading_path = MOE_WEIGHT_PATH
|
| 121 |
+
if local_experts != expert_num:
|
| 122 |
+
loading_path = f'{MOE_WEIGHT_EP_PATH}/rank{rank}'
|
| 123 |
+
vocab_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 124 |
+
logits_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 125 |
+
qkv = [torch.nn.Linear(hidden_size, hidden_size * 3, bias=False, dtype=dtype, device=device) for _ in
|
| 126 |
+
range(layer_number)]
|
| 127 |
+
dense = [torch.nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 128 |
+
range(layer_number)]
|
| 129 |
+
w1 = [torch.nn.Linear(2 * expert_size * local_experts, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 130 |
+
range(layer_number)]
|
| 131 |
+
w2 = [torch.nn.Linear(hidden_size, expert_size * local_experts, bias=False, dtype=dtype, device=device) for _ in
|
| 132 |
+
range(layer_number)]
|
| 133 |
+
gate = [torch.nn.Linear(hidden_size, expert_num, bias=False, dtype=dtype, device=device) for _ in
|
| 134 |
+
range(layer_number)]
|
| 135 |
+
qkv_rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 136 |
+
rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 137 |
+
|
| 138 |
+
# Loading from path:
|
| 139 |
+
print(f"Loading from path: {loading_path}")
|
| 140 |
+
vocab_weight = torch.load(f'{loading_path}/vocab_weight.pt').to(device=device)
|
| 141 |
+
vocab_embedding.weight.data.copy_(vocab_weight.data)
|
| 142 |
+
for i in range(layer_number):
|
| 143 |
+
qkv_dump = torch.load(f'{loading_path}/layers.{i}.self_attention.query_key_value.weight.pt').to(device=device)
|
| 144 |
+
qkv[i].weight.data.copy_(qkv_dump.data)
|
| 145 |
+
dense_dump = torch.load(f'{loading_path}/layers.{i}.self_attention.dense.weight.pt').to(device=device)
|
| 146 |
+
dense[i].weight.data.copy_(dense_dump.data)
|
| 147 |
+
w1_dump = torch.load(f'{loading_path}/layers.{i}.mlp.experts.weight1.pt').to(device=device)
|
| 148 |
+
w1[i].weight.data.copy_(w1_dump.data)
|
| 149 |
+
w2_dump = torch.load(f'{loading_path}/layers.{i}.mlp.experts.weight2.pt').to(device=device)
|
| 150 |
+
w2[i].weight.data.copy_(w2_dump.data)
|
| 151 |
+
gating_dump = torch.load(f'{loading_path}/layers.{i}.mlp.router.weight.pt').to(device=device)
|
| 152 |
+
gate[i].weight.data.copy_(gating_dump.data)
|
| 153 |
+
|
| 154 |
+
qkv_weights = [a.weight for a in qkv]
|
| 155 |
+
dense_weights = [a.weight for a in dense]
|
| 156 |
+
w1_weights = [a.weight for a in w1]
|
| 157 |
+
w2_weights = [a.weight for a in w2]
|
| 158 |
+
gate_weights = [a.weight for a in gate]
|
| 159 |
+
return vocab_embedding.weight, logits_embedding.weight, qkv_weights, dense_weights, w1_weights, w2_weights, gate_weights, qkv_rmsnorm_weight, rmsnorm_weight
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def extract_weights(vocab_size, hidden_size, inner_size, dtype, device, layer_number, initialize_from_raw=False, num_attention_head: Optional[int] = None, n_shared_qhead: Optional[int] = None):
|
| 163 |
+
INITIALIZE_RANGE = 0.013975424859373685
|
| 164 |
+
#INITIALIZE_RANGE = 0.01976423537605237
|
| 165 |
+
std = INITIALIZE_RANGE / math.sqrt(2 * layer_number)
|
| 166 |
+
#std = 1e-5
|
| 167 |
+
|
| 168 |
+
qkv_size = hidden_size * 3
|
| 169 |
+
if n_shared_qhead is not None:
|
| 170 |
+
assert num_attention_head is not None
|
| 171 |
+
num_gqa_groups = num_attention_head // n_shared_qhead
|
| 172 |
+
qkv_size = hidden_size + 2 * int(hidden_size * num_gqa_groups // num_attention_head)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
vocab_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 176 |
+
logits_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 177 |
+
final_rmsnorm_weight = torch.ones(hidden_size, dtype=dtype, device=device)
|
| 178 |
+
qkv = [torch.nn.Linear(hidden_size, qkv_size, bias=False, dtype=dtype, device=device) for _ in
|
| 179 |
+
range(layer_number)]
|
| 180 |
+
dense = [torch.nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 181 |
+
range(layer_number)]
|
| 182 |
+
w1 = [torch.nn.Linear(hidden_size, 2 * inner_size, bias=False, dtype=dtype, device=device) for _ in
|
| 183 |
+
range(layer_number)]
|
| 184 |
+
w2 = [torch.nn.Linear(inner_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 185 |
+
range(layer_number)]
|
| 186 |
+
qkv_rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 187 |
+
rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 188 |
+
if initialize_from_raw:
|
| 189 |
+
print(f"Initializing from Raw with std: {std}...")
|
| 190 |
+
vocab_embedding.weight.data.normal_(mean=0.0, std=math.sqrt(1.0 / (2 * hidden_size)))
|
| 191 |
+
logits_embedding.weight.data.normal_(mean=0.0, std=math.sqrt(1.0 / (2 * hidden_size)))
|
| 192 |
+
for i in range(len(qkv)):
|
| 193 |
+
qkv[i].weight.data.normal_(mean=0.0, std=INITIALIZE_RANGE)
|
| 194 |
+
dense[i].weight.data.normal_(mean=0.0, std=std)
|
| 195 |
+
w1[i].weight.data.normal_(mean=0.0, std=INITIALIZE_RANGE)
|
| 196 |
+
w2[i].weight.data.normal_(mean=0.0, std=std)
|
| 197 |
+
else:
|
| 198 |
+
if n_shared_qhead is not None and n_shared_qhead == 2:
|
| 199 |
+
WEIGHT_PATH = GQA_WEIGHT_PATH
|
| 200 |
+
elif (n_shared_qhead is not None and n_shared_qhead == 1) or n_shared_qhead is None:
|
| 201 |
+
WEIGHT_PATH = NO_GQA_WEIGHT_PATH
|
| 202 |
+
print(f"Loading from path: {WEIGHT_PATH}")
|
| 203 |
+
vocab_weight = torch.load(f'{WEIGHT_PATH}/vocab_weight.pt').to(device=device)
|
| 204 |
+
vocab_embedding.weight.data.copy_(vocab_weight.data)
|
| 205 |
+
for i in range(layer_number):
|
| 206 |
+
qkv_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.self_attention.query_key_value.weight.pt').to(device=device)
|
| 207 |
+
qkv[i].weight.data.copy_(qkv_dump.data)
|
| 208 |
+
dense_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.self_attention.dense.weight.pt').to(device=device)
|
| 209 |
+
dense[i].weight.data.copy_(dense_dump.data)
|
| 210 |
+
w1_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.mlp.fc1_weight.pt').to(device=device)
|
| 211 |
+
w1[i].weight.data.copy_(w1_dump.data)
|
| 212 |
+
w2_dump = torch.load(f'{WEIGHT_PATH}/layers.{i}.mlp.fc2_weight.pt').to(device=device)
|
| 213 |
+
w2[i].weight.data.copy_(w2_dump.data)
|
| 214 |
+
qkv_weights = [a.weight for a in qkv]
|
| 215 |
+
dense_weights = [a.weight for a in dense]
|
| 216 |
+
w1_weights = [a.weight for a in w1]
|
| 217 |
+
w2_weights = [a.weight for a in w2]
|
| 218 |
+
return vocab_embedding.weight, final_rmsnorm_weight, logits_embedding.weight, qkv_weights, dense_weights, w1_weights, w2_weights, qkv_rmsnorm_weight, rmsnorm_weight
|
| 219 |
+
|
| 220 |
+
def extract_layer(layer_number:int, dp_rank:int, pp_rank:int, pp_size: int, phase:int,
|
| 221 |
+
vocab_weight,
|
| 222 |
+
logits_weight,
|
| 223 |
+
qkv_weight,
|
| 224 |
+
dense_weight,
|
| 225 |
+
w1_weight,
|
| 226 |
+
w2_weight,
|
| 227 |
+
gate_weight,
|
| 228 |
+
qkv_rmsnorm_weight,
|
| 229 |
+
rmsnorm_weight):
|
| 230 |
+
layer_indices = torch.arange(0, layer_number)
|
| 231 |
+
split_size = int(pp_size * 2)
|
| 232 |
+
layer_indices_splitted = torch.split(layer_indices, layer_number // split_size)
|
| 233 |
+
mid = split_size // 2
|
| 234 |
+
if phase == 0:
|
| 235 |
+
layer_indices_first_half = list(layer_indices_splitted[:mid])
|
| 236 |
+
assert len(layer_indices_first_half) == pp_size
|
| 237 |
+
my_idx = layer_indices_first_half[pp_rank]
|
| 238 |
+
print(f'[DP-rank-{dp_rank}][PP-Rank-{pp_rank}] For FIRST half selecting layer_idx: {my_idx}')
|
| 239 |
+
# handling m0.
|
| 240 |
+
elif phase == 1:
|
| 241 |
+
layer_indices_second_half = list(layer_indices_splitted[mid:])
|
| 242 |
+
layer_indices_second_half.reverse()
|
| 243 |
+
assert len(layer_indices_second_half) == pp_size
|
| 244 |
+
my_idx = layer_indices_second_half[pp_rank]
|
| 245 |
+
print(f'[DP-rank-{dp_rank}][PP-Rank-{pp_rank}] For SECOND half selecting layer_idx: {my_idx}')
|
| 246 |
+
else:
|
| 247 |
+
raise Exception(f"Unsupported phase number: {phase}")
|
| 248 |
+
qkvs = [qkv_weight[i] for i in my_idx]
|
| 249 |
+
denses = [dense_weight[i] for i in my_idx]
|
| 250 |
+
w1s = [w1_weight[i] for i in my_idx]
|
| 251 |
+
w2s = [w2_weight[i] for i in my_idx]
|
| 252 |
+
gates = [gate_weight[i] for i in my_idx]
|
| 253 |
+
qkv_norms = [qkv_rmsnorm_weight[i] for i in my_idx]
|
| 254 |
+
norms = [rmsnorm_weight[i] for i in my_idx]
|
| 255 |
+
return my_idx, vocab_weight, logits_weight, qkvs, denses, w1s, w2s, gates, qkv_norms, norms
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def moe_nopipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device):
|
| 259 |
+
def ckpt_callback(m, rank_generator: RankGenerator):
|
| 260 |
+
(
|
| 261 |
+
vocab_weight,
|
| 262 |
+
logits_weight,
|
| 263 |
+
qkv_weight,
|
| 264 |
+
dense_weight,
|
| 265 |
+
w1_weight,
|
| 266 |
+
w2_weight,
|
| 267 |
+
gate_weight,
|
| 268 |
+
qkv_rmsnorm_weight,
|
| 269 |
+
rmsnorm_weight
|
| 270 |
+
) = moe_extract_weights(rank_generator.get_dp_rank(), expert_num, expert_size, local_experts, vocab_size, hidden_size, dtype, device, layer_number)
|
| 271 |
+
|
| 272 |
+
m.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight,
|
| 273 |
+
w2_weight, gate_weight, rmsnorm_weight)
|
| 274 |
+
|
| 275 |
+
del vocab_weight
|
| 276 |
+
del logits_weight
|
| 277 |
+
del qkv_weight
|
| 278 |
+
del dense_weight
|
| 279 |
+
del w1_weight
|
| 280 |
+
del w2_weight
|
| 281 |
+
del qkv_rmsnorm_weight
|
| 282 |
+
del rmsnorm_weight
|
| 283 |
+
del gate_weight
|
| 284 |
+
|
| 285 |
+
return ckpt_callback
|
| 286 |
+
|
| 287 |
+
def moe_dualpipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device):
|
| 288 |
+
def ckpt_callback(m0, m1, rank_generator: RankGenerator):
|
| 289 |
+
(
|
| 290 |
+
vocab_weight,
|
| 291 |
+
logits_weight,
|
| 292 |
+
qkv_weight,
|
| 293 |
+
dense_weight,
|
| 294 |
+
w1_weight,
|
| 295 |
+
w2_weight,
|
| 296 |
+
gate_weight,
|
| 297 |
+
qkv_rmsnorm_weight,
|
| 298 |
+
rmsnorm_weight
|
| 299 |
+
) = moe_extract_weights(rank_generator.get_dp_rank(), expert_num, expert_size, local_experts, vocab_size, hidden_size, dtype, device, layer_number)
|
| 300 |
+
|
| 301 |
+
(
|
| 302 |
+
offset_slice_m0,
|
| 303 |
+
vocab_weight_m0,
|
| 304 |
+
logits_weight_m0,
|
| 305 |
+
qkv_weight_m0,
|
| 306 |
+
dense_weight_m0,
|
| 307 |
+
w1_weight_m0,
|
| 308 |
+
w2_weight_m0,
|
| 309 |
+
gate_weight_m0,
|
| 310 |
+
qkv_rmsnorm_weight_m0,
|
| 311 |
+
rmsnorm_weight_m0
|
| 312 |
+
) = extract_layer(layer_number, rank_generator.get_dp_rank(), rank_generator.get_pp_rank(), rank_generator.get_pp_size(), 0, vocab_weight, logits_weight, qkv_weight, dense_weight, w1_weight, w2_weight, gate_weight, qkv_rmsnorm_weight, rmsnorm_weight)
|
| 313 |
+
|
| 314 |
+
(
|
| 315 |
+
offset_slice_m1,
|
| 316 |
+
vocab_weight_m1,
|
| 317 |
+
logits_weight_m1,
|
| 318 |
+
qkv_weight_m1,
|
| 319 |
+
dense_weight_m1,
|
| 320 |
+
w1_weight_m1,
|
| 321 |
+
w2_weight_m1,
|
| 322 |
+
gate_weight_m1,
|
| 323 |
+
qkv_rmsnorm_weight_m1,
|
| 324 |
+
rmsnorm_weight_m1
|
| 325 |
+
) = extract_layer(layer_number, rank_generator.get_dp_rank(), rank_generator.get_pp_rank(), rank_generator.get_pp_size(), 1, vocab_weight, logits_weight, qkv_weight, dense_weight, w1_weight, w2_weight, gate_weight, qkv_rmsnorm_weight, rmsnorm_weight)
|
| 326 |
+
|
| 327 |
+
m0.set_weight(vocab_weight_m0, logits_weight_m0, qkv_weight_m0, qkv_rmsnorm_weight_m0, dense_weight_m0, w1_weight_m0,
|
| 328 |
+
w2_weight_m0, gate_weight_m0, rmsnorm_weight_m0, global_offset_slice=offset_slice_m0)
|
| 329 |
+
m1.set_weight(vocab_weight_m1, logits_weight_m1, qkv_weight_m1, qkv_rmsnorm_weight_m1, dense_weight_m1, w1_weight_m1,
|
| 330 |
+
w2_weight_m1, gate_weight_m1, rmsnorm_weight_m1, global_offset_slice=offset_slice_m1)
|
| 331 |
+
|
| 332 |
+
del offset_slice_m0
|
| 333 |
+
del vocab_weight_m0
|
| 334 |
+
del logits_weight_m0
|
| 335 |
+
del qkv_weight_m0
|
| 336 |
+
del dense_weight_m0
|
| 337 |
+
del w1_weight_m0
|
| 338 |
+
del w2_weight_m0
|
| 339 |
+
del gate_weight_m0
|
| 340 |
+
del qkv_rmsnorm_weight_m0
|
| 341 |
+
del rmsnorm_weight_m0
|
| 342 |
+
|
| 343 |
+
del offset_slice_m1
|
| 344 |
+
del vocab_weight_m1
|
| 345 |
+
del logits_weight_m1
|
| 346 |
+
del qkv_weight_m1
|
| 347 |
+
del dense_weight_m1
|
| 348 |
+
del w1_weight_m1
|
| 349 |
+
del w2_weight_m1
|
| 350 |
+
del gate_weight_m1
|
| 351 |
+
del qkv_rmsnorm_weight_m1
|
| 352 |
+
del rmsnorm_weight_m1
|
| 353 |
+
|
| 354 |
+
del vocab_weight
|
| 355 |
+
del logits_weight
|
| 356 |
+
del qkv_weight
|
| 357 |
+
del dense_weight
|
| 358 |
+
del w1_weight
|
| 359 |
+
del w2_weight
|
| 360 |
+
del gate_weight
|
| 361 |
+
del qkv_rmsnorm_weight
|
| 362 |
+
del rmsnorm_weight
|
| 363 |
+
|
| 364 |
+
return ckpt_callback
|
playground/Abbie-h100/tests/test_aux_loss.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import numpy as np
|
| 4 |
+
from dualpipe.module.gargantua.aux_loss import AuxLoadbalancingLoss, switch_load_balancing_loss_func
|
| 5 |
+
from dualpipe.module.config import GargantuaConfig
|
| 6 |
+
|
| 7 |
+
torch.manual_seed(42)
|
| 8 |
+
np.random.seed(42)
|
| 9 |
+
|
| 10 |
+
def test_aux_loss_forward_backward():
|
| 11 |
+
|
| 12 |
+
hidden_size = 1344
|
| 13 |
+
num_attention_heads = 21
|
| 14 |
+
config = GargantuaConfig(hidden_size, hidden_size, num_attention_heads)
|
| 15 |
+
config.moe_router_topk = 2
|
| 16 |
+
config.moe_aux_loss_coeff = 0.01
|
| 17 |
+
|
| 18 |
+
batch_size = 32
|
| 19 |
+
num_experts = 4
|
| 20 |
+
|
| 21 |
+
probs = torch.randn(batch_size, num_experts, requires_grad=True)
|
| 22 |
+
probs_softmax = F.softmax(probs, dim=-1)
|
| 23 |
+
|
| 24 |
+
splits = torch.rand(num_experts-1).sort()[0] * (batch_size*config.moe_router_topk)
|
| 25 |
+
splits = splits.round().int()
|
| 26 |
+
tokens_per_expert = torch.zeros(num_experts, dtype=torch.int)
|
| 27 |
+
tokens_per_expert[0] = splits[0]
|
| 28 |
+
for i in range(1, num_experts-1):
|
| 29 |
+
tokens_per_expert[i] = splits[i] - splits[i-1]
|
| 30 |
+
tokens_per_expert[-1] = (batch_size*config.moe_router_topk) - splits[-1]
|
| 31 |
+
|
| 32 |
+
activation = torch.randn(batch_size, hidden_size, requires_grad=True)
|
| 33 |
+
|
| 34 |
+
def auto_grad_version():
|
| 35 |
+
probs_clone = probs_softmax.clone().detach().requires_grad_(True)
|
| 36 |
+
tokens_clone = tokens_per_expert.clone().detach()
|
| 37 |
+
act_clone = activation.clone().detach().requires_grad_(True)
|
| 38 |
+
|
| 39 |
+
aux_loss = switch_load_balancing_loss_func(
|
| 40 |
+
probs_clone, tokens_clone, config.moe_router_topk, config.moe_aux_loss_coeff
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
scaled_output = act_clone
|
| 44 |
+
|
| 45 |
+
mse_loss = torch.mean(scaled_output ** 2)
|
| 46 |
+
total_loss = mse_loss + aux_loss
|
| 47 |
+
|
| 48 |
+
total_loss.backward()
|
| 49 |
+
|
| 50 |
+
return {
|
| 51 |
+
'output': scaled_output.detach(),
|
| 52 |
+
'aux_loss': aux_loss.detach(),
|
| 53 |
+
'activation_grad': act_clone.grad.clone(),
|
| 54 |
+
'probs_grad': probs_clone.grad.clone() if probs_clone.grad is not None else None,
|
| 55 |
+
'total_loss': total_loss.detach()
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
def custom_module_version():
|
| 59 |
+
probs_clone = probs_softmax.clone().detach().requires_grad_(True)
|
| 60 |
+
tokens_clone = tokens_per_expert.clone().detach()
|
| 61 |
+
act_clone = activation.clone().detach().requires_grad_(True)
|
| 62 |
+
|
| 63 |
+
output, aux_loss = AuxLoadbalancingLoss.forward(
|
| 64 |
+
probs_clone, tokens_clone, act_clone, config
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
mse_loss = torch.mean(output ** 2)
|
| 68 |
+
total_loss = mse_loss + aux_loss
|
| 69 |
+
|
| 70 |
+
grad_output = 2 * output / output.numel()
|
| 71 |
+
|
| 72 |
+
grad_probs, grad_tokens, grad_activation, _ = AuxLoadbalancingLoss.backward(
|
| 73 |
+
grad_output, probs_clone, aux_loss, tokens_clone,
|
| 74 |
+
config.moe_router_topk, config.moe_aux_loss_coeff
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
return {
|
| 79 |
+
'output': output.detach(),
|
| 80 |
+
'aux_loss': aux_loss.detach(),
|
| 81 |
+
'activation_grad': grad_activation,
|
| 82 |
+
'probs_grad': grad_probs,
|
| 83 |
+
'total_loss': total_loss.detach()
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
print("PyTorch AutoGrad:")
|
| 87 |
+
auto_results = auto_grad_version()
|
| 88 |
+
# print(auto_results)
|
| 89 |
+
print("AuxLoadbalancingLoss Function:")
|
| 90 |
+
custom_results = custom_module_version()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
print("\nDiff forward:")
|
| 94 |
+
output_diff = torch.max(torch.abs(auto_results['output'] - custom_results['output'])).item()
|
| 95 |
+
print(f" max output diff: {output_diff}")
|
| 96 |
+
|
| 97 |
+
aux_loss_diff = torch.abs(auto_results['aux_loss'] - custom_results['aux_loss']).item()
|
| 98 |
+
print(f" aux loss diff: {aux_loss_diff}")
|
| 99 |
+
|
| 100 |
+
total_loss_diff = torch.abs(auto_results['total_loss'] - custom_results['total_loss']).item()
|
| 101 |
+
print(f" total loss diff: {total_loss_diff}")
|
| 102 |
+
|
| 103 |
+
print("\nDiff backward:")
|
| 104 |
+
activation_grad_diff = torch.max(torch.abs(auto_results['activation_grad'] - custom_results['activation_grad'])).item()
|
| 105 |
+
print(f" activation grad diff: {activation_grad_diff}")
|
| 106 |
+
|
| 107 |
+
if auto_results['probs_grad'] is not None and custom_results['probs_grad'] is not None:
|
| 108 |
+
probs_grad_diff = torch.max(torch.abs(auto_results['probs_grad'] - custom_results['probs_grad'])).item()
|
| 109 |
+
print(f" probs grad diff: {probs_grad_diff}")
|
| 110 |
+
|
| 111 |
+
# check
|
| 112 |
+
threshold = 1e-5
|
| 113 |
+
if (output_diff < threshold and
|
| 114 |
+
aux_loss_diff < threshold and
|
| 115 |
+
total_loss_diff < threshold and
|
| 116 |
+
activation_grad_diff < threshold and
|
| 117 |
+
(auto_results['probs_grad'] is None or
|
| 118 |
+
torch.max(torch.abs(auto_results['probs_grad'] - custom_results['probs_grad'])).item() < threshold)):
|
| 119 |
+
print("\nPass!")
|
| 120 |
+
else:
|
| 121 |
+
print("\nFailed!")
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
test_aux_loss_forward_backward()
|
playground/Abbie-h100/tests/test_dense_baseline.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
|
| 6 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from transformers import AutoTokenizer
|
| 11 |
+
|
| 12 |
+
from dualpipe.module.parallel_states import build_rank_generator
|
| 13 |
+
from dualpipe.module.config import GargantuaConfig
|
| 14 |
+
from dualpipe.module.baseline.transformer_layer import TransformerLayer
|
| 15 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 16 |
+
|
| 17 |
+
from tests.shared.preparation import (
|
| 18 |
+
extract_weights,
|
| 19 |
+
get_sahara_58M_dataloader,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from tests.shared.optimizer import (
|
| 23 |
+
build_optimizer,
|
| 24 |
+
get_lr_lambda
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 28 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 29 |
+
|
| 30 |
+
torch.manual_seed(42)
|
| 31 |
+
np.random.seed(42)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def preprocess_labels(labels, cu_seqlens, pad_idx_tensor):
|
| 35 |
+
shift_labels = torch.cat((labels[1:], labels.new_ones((1)) * pad_idx_tensor))
|
| 36 |
+
shift_labels.requires_grad = False
|
| 37 |
+
lbl_seq_lens = (cu_seqlens[1:] - 1).long()
|
| 38 |
+
shift_labels[lbl_seq_lens] = pad_idx_tensor
|
| 39 |
+
shift_labels = shift_labels.unsqueeze(0).transpose(0, 1).contiguous()
|
| 40 |
+
return shift_labels
|
| 41 |
+
|
| 42 |
+
def convert_gradients_to_fp32(model):
|
| 43 |
+
for name, param in model.named_parameters():
|
| 44 |
+
print(f"Converting model param precision: {name} on address: {id(param)}")
|
| 45 |
+
if param.grad is not None:
|
| 46 |
+
print(f"Converted model param precision: {name}")
|
| 47 |
+
param.grad.data = param.grad.data.float()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main(rank, ngpus, expert_num: int = 32, pp_size: int = 1, vocab_size: int = 136064, inner: int = 5504,
|
| 51 |
+
hidden_size: int = 2048, num_attention_head: int = 16, layer_number: int = 24, seq_len: int = 4096):
|
| 52 |
+
torch.cuda.set_device(rank)
|
| 53 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 54 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 55 |
+
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
|
| 56 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 57 |
+
|
| 58 |
+
device = f'cuda:{rank}'
|
| 59 |
+
dtype = torch.bfloat16
|
| 60 |
+
(
|
| 61 |
+
vocab_weight,
|
| 62 |
+
logits_weight,
|
| 63 |
+
qkv_weight,
|
| 64 |
+
dense_weight,
|
| 65 |
+
w1_weight,
|
| 66 |
+
w2_weight,
|
| 67 |
+
qkv_rmsnorm_weight,
|
| 68 |
+
rmsnorm_weight
|
| 69 |
+
) = extract_weights(vocab_size, hidden_size, inner, dtype, device, layer_number)
|
| 70 |
+
|
| 71 |
+
group = dist.distributed_c10d._get_default_group()
|
| 72 |
+
world_size = group.size()
|
| 73 |
+
rank_generator = build_rank_generator(rank, world_size, expert_num, 1, pp_size)
|
| 74 |
+
rank_generator.init()
|
| 75 |
+
dp_group = rank_generator.get_dp_group()
|
| 76 |
+
pad_idx_tensor = torch.tensor(1).long().to(device=device)
|
| 77 |
+
moe_config = (GargantuaConfig(vocab_size, hidden_size, -1, num_attention_head, seq_len, is_moe=False)
|
| 78 |
+
.with_dense_inner_size(inner)
|
| 79 |
+
.with_tie_weight()
|
| 80 |
+
.with_deterministic()
|
| 81 |
+
.with_async_comm())
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
layer = TransformerLayer(rank_generator, config=moe_config, layer_number=layer_number)
|
| 85 |
+
|
| 86 |
+
layer.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight,
|
| 87 |
+
w2_weight, [], rmsnorm_weight)
|
| 88 |
+
|
| 89 |
+
optim = build_optimizer(rank, ngpus, layer, dp_group)
|
| 90 |
+
scheduler = LambdaLR(optim, lr_lambda=get_lr_lambda(False))
|
| 91 |
+
|
| 92 |
+
epoch = 10
|
| 93 |
+
mbs = 1
|
| 94 |
+
gbs = 128 // ngpus
|
| 95 |
+
for e in range(epoch):
|
| 96 |
+
real_step = 0
|
| 97 |
+
opt_step = 0
|
| 98 |
+
for batch in get_sahara_58M_dataloader(rank, ngpus, seq_len, tokenizer):
|
| 99 |
+
input_id = batch['input_ids']
|
| 100 |
+
cu_seqlen = batch['cu_seqlens']
|
| 101 |
+
lbl_seqlen = batch['lbl_seqlens']
|
| 102 |
+
loss_mask = torch.ones_like(input_id, dtype=torch.int32)
|
| 103 |
+
loss_mask[0, lbl_seqlen] = 0
|
| 104 |
+
real_step += 1
|
| 105 |
+
labels = input_id.clone()
|
| 106 |
+
total_s = cu_seqlen[-1].item()
|
| 107 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen, pad_idx_tensor)
|
| 108 |
+
shift_labels.requires_grad = False
|
| 109 |
+
|
| 110 |
+
res = layer.forward(input_id, cu_seqlen, total_s)
|
| 111 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 112 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 113 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 114 |
+
loss = loss_mean / (gbs * ngpus)
|
| 115 |
+
loss.backward()
|
| 116 |
+
# non_zero_grad(layer)
|
| 117 |
+
if real_step % gbs == 0:
|
| 118 |
+
opt_step += 1
|
| 119 |
+
seen_token = (opt_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 120 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(layer.parameters(), 1)
|
| 121 |
+
print(
|
| 122 |
+
f"[Rank-{rank}] epoch: {e} step: {opt_step} consumed: {seen_token}M tokens Loss_mean: {loss_mean} grad_norm: {grad_norm} lr: {scheduler.get_last_lr()[0]:.3e}")
|
| 123 |
+
# print(f"[Rank-{rank}] epoch: {e} step: {i} Loss_mean: {loss_mean} grad_norm: {grad_norm}")
|
| 124 |
+
optim.step()
|
| 125 |
+
scheduler.step()
|
| 126 |
+
optim.zero_grad()
|
| 127 |
+
print("All done")
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_cross_node(ngpus):
|
| 131 |
+
torch.multiprocessing.spawn(main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
num_gpus = torch.cuda.device_count()
|
| 136 |
+
testing_gpu = 1
|
| 137 |
+
assert testing_gpu <= num_gpus
|
| 138 |
+
test_cross_node(testing_gpu)
|
playground/Abbie-h100/tests/test_dense_gargantua.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
|
| 6 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from transformers import AutoTokenizer
|
| 11 |
+
from dualpipe.log import WandbLogger
|
| 12 |
+
|
| 13 |
+
from dualpipe.module.parallel_states import build_rank_generator
|
| 14 |
+
from dualpipe.module.config import GargantuaConfig, OptimizerConfig
|
| 15 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 16 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 17 |
+
from dualpipe.module.shared.optimizer import MixPrecisionDDPOptimizer
|
| 18 |
+
|
| 19 |
+
from tests.shared.preparation import (
|
| 20 |
+
extract_weights,
|
| 21 |
+
get_sahara_58M_dataloader,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from trainer.utils import (
|
| 25 |
+
collect_scalars_across_data_parallel_group
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 29 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 30 |
+
|
| 31 |
+
torch.manual_seed(42)
|
| 32 |
+
np.random.seed(42)
|
| 33 |
+
|
| 34 |
+
def preprocess_labels(labels, cu_seqlens, pad_idx_tensor):
|
| 35 |
+
shift_labels = torch.cat((labels[1:], labels.new_ones((1)) * pad_idx_tensor))
|
| 36 |
+
shift_labels.requires_grad = False
|
| 37 |
+
lbl_seq_lens = (cu_seqlens[1:] - 1).long()
|
| 38 |
+
shift_labels[lbl_seq_lens] = pad_idx_tensor
|
| 39 |
+
shift_labels = shift_labels.unsqueeze(0).transpose(0, 1).contiguous()
|
| 40 |
+
return shift_labels
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main(rank, dp_size, expert_num: int = 32, pp_size: int = 1, gbs = 128, mbs = 2, vocab_size: int = 136064, inner: int = 5504,
|
| 44 |
+
hidden_size: int = 2048, num_attention_head: int = 16, n_shared_qhead: int = 1, layer_number: int = 24, seq_len:int = 4096):
|
| 45 |
+
torch.cuda.set_device(rank)
|
| 46 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=dp_size, rank=rank)
|
| 47 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 48 |
+
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
|
| 49 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 50 |
+
db_logger = WandbLogger(rank, None, f"test_gargantua_6_gqa1_mbs{mbs}")
|
| 51 |
+
|
| 52 |
+
device = f'cuda:{rank}'
|
| 53 |
+
dtype = torch.bfloat16
|
| 54 |
+
(
|
| 55 |
+
vocab_weight,
|
| 56 |
+
final_rmsnorm_weight,
|
| 57 |
+
logits_weight,
|
| 58 |
+
qkv_weight,
|
| 59 |
+
dense_weight,
|
| 60 |
+
w1_weight,
|
| 61 |
+
w2_weight,
|
| 62 |
+
qkv_rmsnorm_weight,
|
| 63 |
+
rmsnorm_weight
|
| 64 |
+
) = extract_weights(vocab_size, hidden_size, inner, dtype, device, layer_number, initialize_from_raw=False, num_attention_head=num_attention_head, n_shared_qhead=n_shared_qhead)
|
| 65 |
+
|
| 66 |
+
group = dist.distributed_c10d._get_default_group()
|
| 67 |
+
world_size = group.size()
|
| 68 |
+
rank_generator = build_rank_generator(rank, world_size, expert_num, 1, pp_size, world_size, local_rank=rank)
|
| 69 |
+
rank_generator.init()
|
| 70 |
+
dp_group = rank_generator.get_dp_group()
|
| 71 |
+
pad_idx_tensor = torch.tensor(1).long().to(device=device)
|
| 72 |
+
moe_config = (GargantuaConfig(vocab_size, hidden_size, -1, num_attention_head, n_shared_qhead, seq_len, is_moe=False)
|
| 73 |
+
.with_dense_inner_size(inner)
|
| 74 |
+
.with_tie_weight()
|
| 75 |
+
.with_deterministic()
|
| 76 |
+
.with_async_comm()
|
| 77 |
+
.with_attn_dropout(0.0)
|
| 78 |
+
.with_residual_dropout(0.0)
|
| 79 |
+
)
|
| 80 |
+
optimizer_config = OptimizerConfig(
|
| 81 |
+
total_steps=2034515, warmup_steps=10172.57500, hold_steps=0,
|
| 82 |
+
lr_max=5e-4, lr_min=5e-5, constant_lr=False, weight_decay=0.1,
|
| 83 |
+
enable_zero_redundant=True
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
layer = TransformerGargantuaLayer(rank_generator, config=moe_config, layer_number=layer_number, first_stage=True, last_stage=True)
|
| 87 |
+
|
| 88 |
+
layer.set_weight(vocab_weight, final_rmsnorm_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight,
|
| 89 |
+
w2_weight, [], rmsnorm_weight)
|
| 90 |
+
|
| 91 |
+
del vocab_weight
|
| 92 |
+
del logits_weight
|
| 93 |
+
del qkv_weight
|
| 94 |
+
del dense_weight
|
| 95 |
+
del w1_weight
|
| 96 |
+
del w2_weight
|
| 97 |
+
del qkv_rmsnorm_weight
|
| 98 |
+
del rmsnorm_weight
|
| 99 |
+
print(f"Allocated CUDA Memory before configure optimizer: {torch.cuda.memory_allocated() / 1000.0 / 1000 / 1000} GB")
|
| 100 |
+
optim = MixPrecisionDDPOptimizer(rank, dp_size, layer.dense_parameters(), group, dp_group, optimizer_config)
|
| 101 |
+
print(f"Allocated CUDA Memory after configure optimizer: {torch.cuda.memory_allocated() / 1000.0 / 1000 / 1000} GB")
|
| 102 |
+
|
| 103 |
+
epoch = 1
|
| 104 |
+
gbs = gbs // (dp_size * mbs)
|
| 105 |
+
|
| 106 |
+
real_step = 0
|
| 107 |
+
opt_step = 0
|
| 108 |
+
db_logger.set_step(opt_step)
|
| 109 |
+
for e in range(epoch):
|
| 110 |
+
real_step = 0
|
| 111 |
+
opt_step = 0
|
| 112 |
+
losses = []
|
| 113 |
+
for batch in get_sahara_58M_dataloader(rank, dp_size, seq_len, tokenizer, mbs=mbs):
|
| 114 |
+
#for batch in get_thoth_v2_dataloader(rank, ngpus, seq_len, tokenizer):
|
| 115 |
+
input_id = batch['input_ids']
|
| 116 |
+
cu_seqlen = batch['cu_seqlens']
|
| 117 |
+
lbl_seqlen = batch['lbl_seqlens']
|
| 118 |
+
loss_mask = torch.ones_like(input_id, dtype=torch.int32)
|
| 119 |
+
loss_mask[0, lbl_seqlen] = 0
|
| 120 |
+
real_step += 1
|
| 121 |
+
labels = input_id.clone()
|
| 122 |
+
total_s = cu_seqlen[-1].item()
|
| 123 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen, pad_idx_tensor)
|
| 124 |
+
shift_labels.requires_grad = False
|
| 125 |
+
|
| 126 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 127 |
+
#res = layer.forward(input_id, cu_seqlen, total_s)
|
| 128 |
+
res = layer.forward(input_id)
|
| 129 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 130 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 131 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 132 |
+
loss = loss_mean / gbs
|
| 133 |
+
losses.append(loss_mean)
|
| 134 |
+
loss.backward()
|
| 135 |
+
#accumulate_grads(param_to_master_params)
|
| 136 |
+
#non_zero_grad(layer)
|
| 137 |
+
if real_step % gbs == 0:
|
| 138 |
+
#copy_back_grads(name_to_param_and_master_param)
|
| 139 |
+
opt_step += 1
|
| 140 |
+
seen_token = (opt_step * seq_len * mbs * gbs * dp_size) / 1024.0 / 1024.0 # In M
|
| 141 |
+
#grad_norm = torch.nn.utils.clip_grad_norm_(layer.parameters(), 1)
|
| 142 |
+
#print(f"[Rank-{rank}] epoch: {e} step: {i} Loss_mean: {loss_mean} grad_norm: {grad_norm}")
|
| 143 |
+
optim.step()
|
| 144 |
+
loss_report = sum(losses) / len(losses)
|
| 145 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 146 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 147 |
+
losses = []
|
| 148 |
+
if rank == 0 and opt_step % 1 == 0:
|
| 149 |
+
print(f"[Rank-{rank}] epoch: {e} step: {opt_step} consumed: {seen_token}M tokens Loss_mean: {gathered_loss} grad_norm: {optim.grad_norm} lr: {optim.scheduler.get_last_lr()[0]:.3e}")
|
| 150 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 151 |
+
|
| 152 |
+
#scheduler.step()
|
| 153 |
+
#optim.zero_grad(set_to_none=True)
|
| 154 |
+
#zero_out_master_grads(name_to_param_and_master_param)
|
| 155 |
+
print("All done")
|
| 156 |
+
|
| 157 |
+
def test_cross_node(ngpus):
|
| 158 |
+
torch.multiprocessing.spawn(main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
|
| 163 |
+
num_gpus = torch.cuda.device_count()
|
| 164 |
+
testing_gpu = 4
|
| 165 |
+
assert testing_gpu <= num_gpus
|
| 166 |
+
test_cross_node(testing_gpu)
|
playground/Abbie-h100/tests/test_dense_mlp.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from dualpipe.module.parallel_states import RankGenerator, build_rank_generator
|
| 8 |
+
from dualpipe.module.config import GargantuaConfig
|
| 9 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 10 |
+
from dualpipe.module.baseline.transformer_layer import TransformerLayer
|
| 11 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 12 |
+
|
| 13 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 14 |
+
|
| 15 |
+
torch.manual_seed(42)
|
| 16 |
+
np.random.seed(42)
|
| 17 |
+
from dualpipe.module.debug import MEM
|
| 18 |
+
|
| 19 |
+
def _extract_weights(inner_size, vocab_size, hidden_size, dtype, device, layer_number):
|
| 20 |
+
vocab_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 21 |
+
logits_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 22 |
+
qkv = [torch.nn.Linear(hidden_size, hidden_size * 3, bias=False, dtype=dtype, device=device) for _ in
|
| 23 |
+
range(layer_number)]
|
| 24 |
+
dense = [torch.nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 25 |
+
range(layer_number)]
|
| 26 |
+
w1 = [torch.nn.Linear(hidden_size, 2 * inner_size, bias=False, dtype=dtype, device=device) for _ in
|
| 27 |
+
range(layer_number)]
|
| 28 |
+
w2 = [torch.nn.Linear(inner_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 29 |
+
range(layer_number)]
|
| 30 |
+
qkv_rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 31 |
+
rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 32 |
+
|
| 33 |
+
qkv_weights = [a.weight for a in qkv]
|
| 34 |
+
dense_weights = [a.weight for a in dense]
|
| 35 |
+
w1_weights = [a.weight for a in w1]
|
| 36 |
+
w2_weights = [a.weight for a in w2]
|
| 37 |
+
return vocab_embedding.weight, logits_embedding.weight, qkv_weights, dense_weights, w1_weights, w2_weights, qkv_rmsnorm_weight, rmsnorm_weight
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def preprocess_labels(labels, cu_seqlens, pad_idx_tensor):
|
| 41 |
+
shift_labels = torch.cat((labels[1:], labels.new_ones((1))*pad_idx_tensor))
|
| 42 |
+
shift_labels.requires_grad = False
|
| 43 |
+
lbl_seq_lens = (cu_seqlens[1:] - 1).long()
|
| 44 |
+
shift_labels[lbl_seq_lens] = pad_idx_tensor
|
| 45 |
+
shift_labels = shift_labels.unsqueeze(0).transpose(0, 1).contiguous()
|
| 46 |
+
return shift_labels
|
| 47 |
+
|
| 48 |
+
def main(rank, ngpus, vocab_size: int = 136064, inner: int = 8192, hidden_size: int = 4096, expert_size: int = 1536, num_attention_head: int = 32, layer_number: int=2, top_k=8):
|
| 49 |
+
is_first_rank = rank == 0
|
| 50 |
+
torch.cuda.set_device(rank)
|
| 51 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 52 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 53 |
+
device = f'cuda:{rank}'
|
| 54 |
+
dtype = torch.bfloat16
|
| 55 |
+
(
|
| 56 |
+
vocab_weight,
|
| 57 |
+
logits_weight,
|
| 58 |
+
qkv_weight,
|
| 59 |
+
dense_weight,
|
| 60 |
+
w1_weight,
|
| 61 |
+
w2_weight,
|
| 62 |
+
qkv_rmsnorm_weight,
|
| 63 |
+
rmsnorm_weight
|
| 64 |
+
) = _extract_weights(inner, vocab_size, hidden_size, dtype, device, layer_number)
|
| 65 |
+
group = dist.distributed_c10d._get_default_group()
|
| 66 |
+
world_size = group.size()
|
| 67 |
+
rank_generator = build_rank_generator(rank, world_size, 1, 1, 1)
|
| 68 |
+
rank_generator.init()
|
| 69 |
+
#moe = MoELayer(rank, ep_group, hidden_size, expert_num, top_k=2, ep_rank=ep_rank, ep_size=ep_size)
|
| 70 |
+
if not RANDOM_INPUTS:
|
| 71 |
+
input_ids = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/input_ids_rank_1.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 72 |
+
cu_seqlens = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/cu_seqlens_rank_1.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 73 |
+
labels = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/labels_1.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 74 |
+
pad_idx_tensor = torch.tensor(1).long().to(device=device)
|
| 75 |
+
else:
|
| 76 |
+
seq_len = 256
|
| 77 |
+
cu_seqlens = torch.tensor([0, seq_len], dtype=torch.int32)
|
| 78 |
+
total_s = cu_seqlens[-1].item()
|
| 79 |
+
moe_config = (GargantuaConfig(vocab_size, hidden_size, -1, num_attention_head, 4096, is_moe=False)
|
| 80 |
+
.with_dense_inner_size(inner)
|
| 81 |
+
.with_deterministic()
|
| 82 |
+
.with_async_comm())
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
layer = TransformerGargantuaLayer(rank_generator, config=moe_config, layer_number=layer_number, first_stage=True, last_stage=True)
|
| 86 |
+
layer_baseline = TransformerLayer(rank_generator, config=moe_config, layer_number=layer_number)
|
| 87 |
+
layer.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight, w2_weight, [], rmsnorm_weight)
|
| 88 |
+
layer.set_input_ctx((cu_seqlens, total_s))
|
| 89 |
+
#layer.set_head_and_tail(True, True)
|
| 90 |
+
layer_baseline.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight, w2_weight, [], rmsnorm_weight)
|
| 91 |
+
layer_baseline.prepare()
|
| 92 |
+
input_ids2 = input_ids.detach().clone()
|
| 93 |
+
|
| 94 |
+
#layer = DDP(ddp_config, layer, rank_generator.get_dp_group())
|
| 95 |
+
|
| 96 |
+
shift_labels = preprocess_labels(labels, cu_seqlens, pad_idx_tensor)
|
| 97 |
+
res2 = layer_baseline.forward(input_ids2, cu_seqlens, total_s)
|
| 98 |
+
res = layer.forward(input_ids)
|
| 99 |
+
MEM.compare()
|
| 100 |
+
|
| 101 |
+
loss = vocab_parallel_cross_entropy(res, shift_labels)
|
| 102 |
+
loss2 = vocab_parallel_cross_entropy(res2, shift_labels)
|
| 103 |
+
|
| 104 |
+
loss = loss.transpose(0, 1).contiguous().mean()
|
| 105 |
+
loss2 = loss2.transpose(0, 1).contiguous().mean()
|
| 106 |
+
assert torch.allclose(loss, loss2)
|
| 107 |
+
loss.backward()
|
| 108 |
+
loss2.backward()
|
| 109 |
+
MEM.compare_bwd()
|
| 110 |
+
MEM.is_bitwise_close()
|
| 111 |
+
#optim.step()
|
| 112 |
+
print("All done")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_cross_node(ngpus):
|
| 116 |
+
torch.multiprocessing.spawn(main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
num_gpus = torch.cuda.device_count()
|
| 121 |
+
testing_gpu = 4
|
| 122 |
+
assert testing_gpu <= num_gpus
|
| 123 |
+
test_cross_node(testing_gpu)
|
playground/Abbie-h100/tests/test_gemm.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from dualpipe.module.gargantua.functors import LinearTEFunc
|
| 4 |
+
from abbie_cpp import bf16_gemm_lt
|
| 5 |
+
|
| 6 |
+
_cublas_workspace = None
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_cublas_workspace_size_bytes() -> None:
|
| 10 |
+
"""Return 32 MiB if using hopper, 4 MiB for all other architectures."""
|
| 11 |
+
if torch.cuda.get_device_properties(torch.cuda.current_device()).major >= 9:
|
| 12 |
+
return 33_554_432
|
| 13 |
+
return 4_194_304
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_workspace() -> torch.Tensor:
|
| 17 |
+
"""Returns workspace for cublas."""
|
| 18 |
+
global _cublas_workspace
|
| 19 |
+
if _cublas_workspace is None:
|
| 20 |
+
_cublas_workspace = torch.empty(get_cublas_workspace_size_bytes(), dtype=torch.uint8, device="cuda")
|
| 21 |
+
return _cublas_workspace
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
fwd_input = torch.load('/opt/tiger/gemm_test_sample/fwd_inputmat.pt').to(device='cuda:0')
|
| 25 |
+
fwd_weight = torch.load('/opt/tiger/gemm_test_sample/fwd_weight.pt').to(device='cuda:0')
|
| 26 |
+
fwd_output = torch.load('/opt/tiger/gemm_test_sample/fwd_output.pt').to(device='cuda:0')
|
| 27 |
+
|
| 28 |
+
bwd_grad_output = torch.load('/opt/tiger/gemm_test_sample/bwd_grad_output.pt').to(device='cuda:0')
|
| 29 |
+
bwd_weight = torch.load('/opt/tiger/gemm_test_sample/bwd_weight.pt').to(device='cuda:0')
|
| 30 |
+
bwd_inputmat = torch.load('/opt/tiger/gemm_test_sample/bwd_inputmat.pt').to(device='cuda:0')
|
| 31 |
+
bwd_dgrad = torch.load('/opt/tiger/gemm_test_sample/bwd_dgrad.pt').to(device='cuda:0')
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
out = LinearTEFunc.forward(fwd_input, fwd_weight).squeeze()
|
| 35 |
+
out2 = bf16_gemm_lt.gemm_bf16_row_major(fwd_input, fwd_weight, trans_a=False, trans_b=True, accumulate=False, accumulate_target=None, workspace=get_workspace())
|
| 36 |
+
print(torch.nonzero(out - out2))
|
| 37 |
+
|
| 38 |
+
bwd_weight_2 = bwd_weight.detach().clone()
|
| 39 |
+
bwd_weight.main_grad = torch.zeros_like(bwd_weight, dtype=torch.float32)
|
| 40 |
+
bwd_weight_2.main_grad = torch.zeros_like(bwd_weight_2, dtype=torch.float32)
|
| 41 |
+
|
| 42 |
+
dgrad = LinearTEFunc.backward(bwd_grad_output, bwd_inputmat, bwd_weight).squeeze()
|
| 43 |
+
bf16_gemm_lt.gemm_bf16_row_major(bwd_grad_output, bwd_inputmat, trans_a=True, trans_b=False, accumulate=True, accumulate_target=bwd_weight_2.main_grad, workspace=get_workspace())
|
| 44 |
+
dgrad_2 = bf16_gemm_lt.gemm_bf16_row_major(bwd_grad_output, bwd_weight_2, trans_a=False, trans_b=False, accumulate=False, accumulate_target=None, workspace=get_workspace())
|
| 45 |
+
print(torch.nonzero(dgrad - dgrad_2))
|
| 46 |
+
print(torch.nonzero(bwd_weight.main_grad - bwd_weight_2.main_grad))
|
| 47 |
+
|
playground/Abbie-h100/tests/test_moe_gargantua.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import random
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 7 |
+
|
| 8 |
+
from dualpipe.deterministic import set_deterministic
|
| 9 |
+
from dualpipe.log import WandbLogger
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
set_deterministic(42, False)
|
| 14 |
+
from transformers import AutoTokenizer
|
| 15 |
+
from dualpipe.module.parallel_states import build_rank_generator
|
| 16 |
+
from dualpipe.module.config import GargantuaConfig, OptimizerConfig
|
| 17 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 18 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 19 |
+
from dualpipe.module.shared.optimizer import MixPrecisionDDPOptimizer
|
| 20 |
+
from tests.shared.preparation import (
|
| 21 |
+
# set_deterministic,
|
| 22 |
+
moe_extract_weights,
|
| 23 |
+
get_sahara_426M_dataloader,
|
| 24 |
+
)
|
| 25 |
+
from tests.shared.optimizer import (
|
| 26 |
+
sample_check_pow2_grad
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 30 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def preprocess_labels(labels, cu_seqlens, pad_idx_tensor):
|
| 34 |
+
shift_labels = torch.cat((labels[1:], labels.new_ones((1)) * pad_idx_tensor))
|
| 35 |
+
shift_labels.requires_grad = False
|
| 36 |
+
lbl_seq_lens = (cu_seqlens[1:] - 1).long()
|
| 37 |
+
shift_labels[lbl_seq_lens] = pad_idx_tensor
|
| 38 |
+
shift_labels = shift_labels.unsqueeze(0).transpose(0, 1).contiguous()
|
| 39 |
+
return shift_labels
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 43 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 44 |
+
scalars = torch.cat(
|
| 45 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 46 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 47 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 48 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 49 |
+
group=dp_group)
|
| 50 |
+
return out_scalars, group_size
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main(rank, ngpus, expert_num: int = 16, dp_size: int = 2, ep_size: int = 2, pp_size: int = 1,
|
| 54 |
+
vocab_size: int = 136064, expert_size: int = 640, top_k=2,
|
| 55 |
+
gbs: int = 128, hidden_size: int = 2048, num_attention_head: int = 16, layer_number: int = 24,
|
| 56 |
+
seq_len: int = 4096):
|
| 57 |
+
epoch = 1
|
| 58 |
+
mbs = 1
|
| 59 |
+
gbs = gbs // ngpus
|
| 60 |
+
set_deterministic(42, False)
|
| 61 |
+
|
| 62 |
+
torch.cuda.set_device(rank)
|
| 63 |
+
local_experts = (expert_num // ep_size)
|
| 64 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 65 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 66 |
+
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_PATH)
|
| 67 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 68 |
+
device = f'cuda:{rank}'
|
| 69 |
+
dtype = torch.bfloat16
|
| 70 |
+
(
|
| 71 |
+
vocab_weight,
|
| 72 |
+
logits_weight,
|
| 73 |
+
qkv_weight,
|
| 74 |
+
dense_weight,
|
| 75 |
+
w1_weight,
|
| 76 |
+
w2_weight,
|
| 77 |
+
gate_weight,
|
| 78 |
+
qkv_rmsnorm_weight,
|
| 79 |
+
rmsnorm_weight
|
| 80 |
+
) = moe_extract_weights(rank, expert_num, expert_size, local_experts, vocab_size, hidden_size, dtype, device,
|
| 81 |
+
layer_number)
|
| 82 |
+
db_logger = WandbLogger(rank, None, 'abbie_moe_test_gargantua')
|
| 83 |
+
group = dist.distributed_c10d._get_default_group()
|
| 84 |
+
world_size = group.size()
|
| 85 |
+
rank_generator = build_rank_generator(rank, world_size, expert_num, ep_size, pp_size)
|
| 86 |
+
rank_generator.init()
|
| 87 |
+
dp_group = rank_generator.get_dp_group()
|
| 88 |
+
dep_group = rank_generator.get_dep_group()
|
| 89 |
+
pad_idx_tensor = torch.tensor(1).long().to(device=device)
|
| 90 |
+
moe_config = (GargantuaConfig(vocab_size, hidden_size, expert_size, num_attention_head, 4096)
|
| 91 |
+
.with_gbs(gbs)
|
| 92 |
+
.with_ep_size(ep_size)
|
| 93 |
+
.with_expert_number(expert_num)
|
| 94 |
+
.with_moe_topk(top_k)
|
| 95 |
+
.with_tie_weight()
|
| 96 |
+
.with_deterministic()
|
| 97 |
+
# .with_mlp_checkpoint()
|
| 98 |
+
# .with_async_comm()
|
| 99 |
+
)
|
| 100 |
+
moe_config.moe_aux_loss_coeff = 5e-3
|
| 101 |
+
moe_config.moe_z_loss_coeff = 1e-3
|
| 102 |
+
|
| 103 |
+
optimizer_config = OptimizerConfig(
|
| 104 |
+
total_steps=2034515, warmup_steps=10172.57500, hold_steps=0,
|
| 105 |
+
lr_max=5e-4, lr_min=5e-5, constant_lr=False, weight_decay=0.1,
|
| 106 |
+
enable_zero_redundant=True
|
| 107 |
+
)
|
| 108 |
+
layer = TransformerGargantuaLayer(rank_generator, config=moe_config, layer_number=layer_number, first_stage=True,
|
| 109 |
+
last_stage=True)
|
| 110 |
+
# layer = TransformerLayer(rank_generator, config=moe_config, layer_number=layer_number)
|
| 111 |
+
layer.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight,
|
| 112 |
+
w2_weight, gate_weight, rmsnorm_weight)
|
| 113 |
+
del vocab_weight
|
| 114 |
+
del logits_weight
|
| 115 |
+
del qkv_weight
|
| 116 |
+
del dense_weight
|
| 117 |
+
del w1_weight
|
| 118 |
+
del w2_weight
|
| 119 |
+
del qkv_rmsnorm_weight
|
| 120 |
+
del rmsnorm_weight
|
| 121 |
+
del gate_weight
|
| 122 |
+
print(
|
| 123 |
+
f"Allocated CUDA Memory before configure optimizer: {torch.cuda.memory_allocated() / 1000.0 / 1000 / 1000} GB")
|
| 124 |
+
optim1 = MixPrecisionDDPOptimizer(rank, ngpus, layer.dense_parameters(), None, dp_group, optimizer_config)
|
| 125 |
+
optim2 = MixPrecisionDDPOptimizer(rank, ngpus, layer.moe_parameters(), None, dep_group, optimizer_config)
|
| 126 |
+
print(f"Allocated CUDA Memory after configure optimizer: {torch.cuda.memory_allocated() / 1000.0 / 1000 / 1000} GB")
|
| 127 |
+
losses = []
|
| 128 |
+
for e in range(epoch):
|
| 129 |
+
real_step = 0
|
| 130 |
+
opt_step = 0
|
| 131 |
+
for batch in get_sahara_426M_dataloader(rank, ngpus, seq_len, tokenizer):
|
| 132 |
+
# for batch in get_thoth_v2_dataloader(rank, ngpus, seq_len, tokenizer):
|
| 133 |
+
input_id = batch['input_ids']
|
| 134 |
+
cu_seqlen = batch['cu_seqlens']
|
| 135 |
+
lbl_seqlen = batch['lbl_seqlens']
|
| 136 |
+
loss_mask = torch.ones_like(input_id, dtype=torch.int32)
|
| 137 |
+
loss_mask[0, lbl_seqlen] = 0
|
| 138 |
+
real_step += 1
|
| 139 |
+
labels = input_id.clone()
|
| 140 |
+
total_s = cu_seqlen[-1].item()
|
| 141 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen, pad_idx_tensor)
|
| 142 |
+
shift_labels.requires_grad = False
|
| 143 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 144 |
+
# res = layer.forward(input_id, cu_seqlen, total_s)
|
| 145 |
+
res = layer.forward(input_id)
|
| 146 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 147 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 148 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 149 |
+
losses.append(loss_mean.detach().clone())
|
| 150 |
+
loss = loss_mean / (gbs)
|
| 151 |
+
loss.backward()
|
| 152 |
+
# sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 153 |
+
if real_step % gbs == 0:
|
| 154 |
+
# copy_back_grads(name_to_param_and_master_param)
|
| 155 |
+
# layer.scale_main_grad(1.0 / torch.distributed.get_world_size(dp_group))
|
| 156 |
+
loss_report = sum(losses) / len(losses)
|
| 157 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], dp_group)
|
| 158 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 159 |
+
losses = []
|
| 160 |
+
seen_token = (opt_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 161 |
+
# grad_norm = torch.nn.utils.clip_grad_norm_(layer.parameters(), 1)
|
| 162 |
+
# print(f"[Rank-{rank}] epoch: {e} step: {i} Loss_mean: {loss_mean} grad_norm: {grad_norm}")
|
| 163 |
+
optim1.step()
|
| 164 |
+
optim2.step()
|
| 165 |
+
if rank == 0 and opt_step % 1 == 0:
|
| 166 |
+
caliberated_grad_norm = math.sqrt(optim1.grad_norm ** 2 + optim2.grad_norm ** 2)
|
| 167 |
+
print(
|
| 168 |
+
f"[Rank-{rank}] epoch: {e} step: {opt_step} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optim1.scheduler.get_last_lr()[0]:.3e}")
|
| 169 |
+
db_logger.log_step({
|
| 170 |
+
'training/loss': gathered_loss,
|
| 171 |
+
})
|
| 172 |
+
opt_step += 1
|
| 173 |
+
# scheduler.step()
|
| 174 |
+
# optim.zero_grad(set_to_none=True)
|
| 175 |
+
# zero_out_master_grads(name_to_param_and_master_param)
|
| 176 |
+
print("All done")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_cross_node(ngpus):
|
| 180 |
+
torch.multiprocessing.spawn(main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
num_gpus = torch.cuda.device_count()
|
| 185 |
+
testing_gpu = 2
|
| 186 |
+
assert testing_gpu <= num_gpus
|
| 187 |
+
test_cross_node(testing_gpu)
|
playground/Abbie-h100/tests/test_moe_gating.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from dualpipe.module.config import GargantuaConfig
|
| 4 |
+
from dualpipe.module.gargantua.functors import LinearFunc
|
| 5 |
+
|
| 6 |
+
torch.manual_seed(42)
|
| 7 |
+
np.random.seed(42)
|
| 8 |
+
|
| 9 |
+
def test_linear_func_forward_backward():
|
| 10 |
+
hidden_size = 1344
|
| 11 |
+
num_attention_heads = 21
|
| 12 |
+
config = GargantuaConfig(hidden_size, hidden_size, num_attention_heads)
|
| 13 |
+
config.moe_router_topk = 2
|
| 14 |
+
config.moe_aux_loss_coeff = 0.01
|
| 15 |
+
|
| 16 |
+
batch_size = 32
|
| 17 |
+
num_experts = 4
|
| 18 |
+
|
| 19 |
+
hidden_states = torch.randn(batch_size, hidden_size, requires_grad=True)
|
| 20 |
+
gating = torch.randn(num_experts, hidden_size, requires_grad=True)
|
| 21 |
+
|
| 22 |
+
expected_shape = (batch_size, num_experts)
|
| 23 |
+
grad_output = torch.randn(expected_shape)
|
| 24 |
+
|
| 25 |
+
def auto_grad_version():
|
| 26 |
+
|
| 27 |
+
input_clone = hidden_states.clone().detach().requires_grad_(True)
|
| 28 |
+
gating_clone = gating.clone().detach().requires_grad_(True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
logits = torch.matmul(input_clone, gating_clone.t())
|
| 32 |
+
|
| 33 |
+
logits.backward(grad_output.clone())
|
| 34 |
+
|
| 35 |
+
return {
|
| 36 |
+
'output': logits.detach(),
|
| 37 |
+
'input_grad': input_clone.grad.clone(),
|
| 38 |
+
'gating_grad': gating_clone.grad.clone()
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
def custom_module_version():
|
| 42 |
+
input_clone = hidden_states.clone().detach().requires_grad_(True)
|
| 43 |
+
gating_clone = gating.clone().detach().requires_grad_(True)
|
| 44 |
+
input_fp32 = input_clone.float()
|
| 45 |
+
gating_clone.grad = None
|
| 46 |
+
|
| 47 |
+
logits = LinearFunc.forward(input_fp32, gating_clone)
|
| 48 |
+
|
| 49 |
+
grad_input = LinearFunc.backward(grad_output.clone(), input_fp32, gating_clone)
|
| 50 |
+
|
| 51 |
+
if input_clone.dtype != input_fp32.dtype:
|
| 52 |
+
grad_input = grad_input.to(dtype=input_clone.dtype)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if input_clone.grad is None:
|
| 56 |
+
input_clone.grad = grad_input
|
| 57 |
+
else:
|
| 58 |
+
input_clone.grad += grad_input
|
| 59 |
+
|
| 60 |
+
return {
|
| 61 |
+
'output': logits.detach(),
|
| 62 |
+
'input_grad': input_clone.grad.clone(),
|
| 63 |
+
'gating_grad': gating_clone.grad.clone()
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
print("Testing:")
|
| 67 |
+
auto_results = auto_grad_version()
|
| 68 |
+
custom_results = custom_module_version()
|
| 69 |
+
|
| 70 |
+
print("\nDiff forward:")
|
| 71 |
+
output_diff = torch.max(torch.abs(auto_results['output'] - custom_results['output'])).item()
|
| 72 |
+
print(f" max output diff: {output_diff}")
|
| 73 |
+
|
| 74 |
+
print("\nDiff backward:")
|
| 75 |
+
input_grad_diff = torch.max(torch.abs(auto_results['input_grad'] - custom_results['input_grad'])).item()
|
| 76 |
+
print(f" max input grad diff: {input_grad_diff}")
|
| 77 |
+
|
| 78 |
+
gating_grad_diff = torch.max(torch.abs(auto_results['gating_grad'] - custom_results['gating_grad'])).item()
|
| 79 |
+
print(f" gating grad diff: {gating_grad_diff}")
|
| 80 |
+
|
| 81 |
+
threshold = 1e-5
|
| 82 |
+
if (output_diff < threshold and
|
| 83 |
+
input_grad_diff < threshold and
|
| 84 |
+
gating_grad_diff < threshold):
|
| 85 |
+
print("\nPass!")
|
| 86 |
+
else:
|
| 87 |
+
print("\nFailed!")
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
test_linear_func_forward_backward()
|
playground/Abbie-h100/tests/test_moe_mlp.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from dualpipe.module.parallel_states import RankGenerator, build_rank_generator
|
| 8 |
+
from dualpipe.module.config import GargantuaConfig
|
| 9 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 10 |
+
from dualpipe.module.baseline.transformer_layer import TransformerLayer
|
| 11 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 12 |
+
|
| 13 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 14 |
+
|
| 15 |
+
torch.manual_seed(42)
|
| 16 |
+
np.random.seed(42)
|
| 17 |
+
from dualpipe.module.debug import MEM
|
| 18 |
+
|
| 19 |
+
def _extract_weights(expert_num, expert_size, local_experts, vocab_size, hidden_size, dtype, device, layer_number):
|
| 20 |
+
vocab_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 21 |
+
logits_embedding = torch.nn.Linear(hidden_size, vocab_size, dtype=dtype, device=device)
|
| 22 |
+
qkv = [torch.nn.Linear(hidden_size, hidden_size * 3, bias=False, dtype=dtype, device=device) for _ in
|
| 23 |
+
range(layer_number)]
|
| 24 |
+
dense = [torch.nn.Linear(hidden_size, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 25 |
+
range(layer_number)]
|
| 26 |
+
w1 = [torch.nn.Linear(hidden_size, 2 * expert_size * local_experts, bias=False, dtype=dtype, device=device) for _ in
|
| 27 |
+
range(layer_number)]
|
| 28 |
+
w2 = [torch.nn.Linear(expert_size * local_experts, hidden_size, bias=False, dtype=dtype, device=device) for _ in
|
| 29 |
+
range(layer_number)]
|
| 30 |
+
gate = [torch.nn.Linear(hidden_size, expert_num, bias=False, dtype=torch.float32, device=device) for _ in
|
| 31 |
+
range(layer_number)]
|
| 32 |
+
qkv_rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 33 |
+
rmsnorm_weight = [torch.ones(hidden_size, dtype=dtype, device=device) for _ in range(layer_number)]
|
| 34 |
+
|
| 35 |
+
qkv_weights = [a.weight for a in qkv]
|
| 36 |
+
dense_weights = [a.weight for a in dense]
|
| 37 |
+
w1_weights = [a.weight for a in w1]
|
| 38 |
+
w2_weights = [a.weight for a in w2]
|
| 39 |
+
gate_weights = [a.weight for a in gate]
|
| 40 |
+
return vocab_embedding.weight, logits_embedding.weight, qkv_weights, dense_weights, w1_weights, w2_weights, gate_weights, qkv_rmsnorm_weight, rmsnorm_weight
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def preprocess_labels(labels, cu_seqlens, pad_idx_tensor):
|
| 44 |
+
shift_labels = torch.cat((labels[1:], labels.new_ones((1))*pad_idx_tensor))
|
| 45 |
+
shift_labels.requires_grad = False
|
| 46 |
+
lbl_seq_lens = (cu_seqlens[1:] - 1).long()
|
| 47 |
+
shift_labels[lbl_seq_lens] = pad_idx_tensor
|
| 48 |
+
shift_labels = shift_labels.unsqueeze(0).transpose(0, 1).contiguous()
|
| 49 |
+
return shift_labels
|
| 50 |
+
|
| 51 |
+
def main(rank, ngpus, expert_num: int = 32, ep_size: int = 2, pp_size: int = 2, vocab_size: int = 136064, hidden_size: int = 4096, expert_size: int = 1536, num_attention_head: int = 32, layer_number: int=1, top_k=8):
|
| 52 |
+
is_first_rank = rank == 0
|
| 53 |
+
local_experts = (expert_num // ep_size)
|
| 54 |
+
torch.cuda.set_device(rank)
|
| 55 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 56 |
+
torch.set_default_device(f"cuda:{rank}")
|
| 57 |
+
attention_dropout = 0.0
|
| 58 |
+
device = f'cuda:{rank}'
|
| 59 |
+
dtype = torch.bfloat16
|
| 60 |
+
(
|
| 61 |
+
vocab_weight,
|
| 62 |
+
logits_weight,
|
| 63 |
+
qkv_weight,
|
| 64 |
+
dense_weight,
|
| 65 |
+
w1_weight,
|
| 66 |
+
w2_weight,
|
| 67 |
+
gate_weight,
|
| 68 |
+
qkv_rmsnorm_weight,
|
| 69 |
+
rmsnorm_weight
|
| 70 |
+
) = _extract_weights(expert_num, expert_size, local_experts, vocab_size, hidden_size, dtype, device, layer_number)
|
| 71 |
+
group = dist.distributed_c10d._get_default_group()
|
| 72 |
+
world_size = group.size()
|
| 73 |
+
rank_generator = build_rank_generator(rank, world_size, expert_num, ep_size, pp_size)
|
| 74 |
+
rank_generator.init()
|
| 75 |
+
#moe = MoELayer(rank, ep_group, hidden_size, expert_num, top_k=2, ep_rank=ep_rank, ep_size=ep_size)
|
| 76 |
+
if not RANDOM_INPUTS:
|
| 77 |
+
input_ids = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/input_ids_rank_1.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 78 |
+
cu_seqlens = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/cu_seqlens_rank_1.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 79 |
+
labels = torch.load(f'/opt/tiger/DualPipe/sample_data/moe_dump_ids_labels_only/labels_1.pt', weights_only=True).to(device=f'cuda:{rank}')
|
| 80 |
+
pad_idx_tensor = torch.tensor(1).long().to(device=device)
|
| 81 |
+
else:
|
| 82 |
+
seq_len = 256
|
| 83 |
+
cu_seqlens = torch.tensor([0, seq_len], dtype=torch.int32)
|
| 84 |
+
total_s = cu_seqlens[-1].item()
|
| 85 |
+
moe_config = (GargantuaConfig(vocab_size, hidden_size, expert_size, num_attention_head, 4096)
|
| 86 |
+
.with_ep_size(ep_size)
|
| 87 |
+
.with_expert_number(expert_num)
|
| 88 |
+
.with_moe_topk(top_k)
|
| 89 |
+
#.with_tie_weight()
|
| 90 |
+
.with_deterministic()
|
| 91 |
+
#.with_mlp_checkpoint()
|
| 92 |
+
.with_async_comm())
|
| 93 |
+
|
| 94 |
+
#ddp_config = DistributedDataParallelConfig()
|
| 95 |
+
#ddp_config.use_distributed_optimizer = True
|
| 96 |
+
|
| 97 |
+
layer = TransformerGargantuaLayer(rank_generator, config=moe_config, layer_number=layer_number, first_stage=True, last_stage=True)
|
| 98 |
+
layer_baseline = TransformerLayer(rank_generator, config=moe_config, layer_number=layer_number)
|
| 99 |
+
layer.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight, w2_weight, gate_weight, rmsnorm_weight)
|
| 100 |
+
layer.set_input_ctx((cu_seqlens, total_s))
|
| 101 |
+
layer.set_head_and_tail(True, True)
|
| 102 |
+
layer_baseline.set_weight(vocab_weight, logits_weight, qkv_weight, qkv_rmsnorm_weight, dense_weight, w1_weight, w2_weight, gate_weight, rmsnorm_weight)
|
| 103 |
+
layer_baseline.prepare()
|
| 104 |
+
input_ids2 = input_ids.detach().clone()
|
| 105 |
+
|
| 106 |
+
#layer = DDP(ddp_config, layer, rank_generator.get_dp_group())
|
| 107 |
+
#optim = build_optimizer(layer)
|
| 108 |
+
|
| 109 |
+
shift_labels = preprocess_labels(labels, cu_seqlens, pad_idx_tensor)
|
| 110 |
+
res = layer.forward(input_ids)
|
| 111 |
+
res2 = layer_baseline.forward(input_ids2, cu_seqlens, total_s)
|
| 112 |
+
MEM.compare()
|
| 113 |
+
|
| 114 |
+
loss = vocab_parallel_cross_entropy(res, shift_labels)
|
| 115 |
+
loss2 = vocab_parallel_cross_entropy(res2, shift_labels)
|
| 116 |
+
|
| 117 |
+
loss = loss.transpose(0, 1).contiguous().mean()
|
| 118 |
+
loss2 = loss2.transpose(0, 1).contiguous().mean()
|
| 119 |
+
assert torch.allclose(loss, loss2)
|
| 120 |
+
loss.backward()
|
| 121 |
+
loss2.backward(retain_graph=True)
|
| 122 |
+
MEM.compare_bwd()
|
| 123 |
+
MEM.is_bitwise_close()
|
| 124 |
+
#optim.step()
|
| 125 |
+
print("All done")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_cross_node(ngpus):
|
| 129 |
+
torch.multiprocessing.spawn(main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if __name__ == "__main__":
|
| 133 |
+
#d_qkv = torch.load('/opt/tiger/d_qkv.pt')
|
| 134 |
+
#qkv_inputmat = torch.load('/opt/tiger/qkv_inputmat.pt')
|
| 135 |
+
#qkv_rmsnorm_weight = torch.load('/opt/tiger/qkv_rmsnorm_weight.pt')
|
| 136 |
+
#qkv_rsigma = torch.load('/opt/tiger/qkv_rsigma.pt')
|
| 137 |
+
#RMSNormFunction.backward(d_qkv, qkv_inputmat, qkv_rmsnorm_weight, qkv_rsigma, d_qkv.shape, False)
|
| 138 |
+
|
| 139 |
+
num_gpus = torch.cuda.device_count()
|
| 140 |
+
testing_gpu = 4
|
| 141 |
+
assert testing_gpu <= num_gpus
|
| 142 |
+
test_cross_node(testing_gpu)
|
playground/Abbie-h100/tests/test_moe_route.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from tests.shared.moe_route import MoERouterFunc
|
| 4 |
+
from dualpipe.module.config import GargantuaConfig
|
| 5 |
+
from dualpipe.module.shared.moe_utils import switch_load_balancing_loss_func
|
| 6 |
+
|
| 7 |
+
torch.manual_seed(42)
|
| 8 |
+
np.random.seed(42)
|
| 9 |
+
|
| 10 |
+
def test_moe_route_forward_backward():
|
| 11 |
+
|
| 12 |
+
hidden_size = 1344
|
| 13 |
+
num_attention_heads = 21
|
| 14 |
+
config = GargantuaConfig(hidden_size, hidden_size, num_attention_heads)
|
| 15 |
+
config.moe_router_topk = 3
|
| 16 |
+
config.moe_aux_loss_coeff = 0.01
|
| 17 |
+
config.moe_router_load_balancing_type = "aux_loss"
|
| 18 |
+
config.moe_input_jitter_eps = None
|
| 19 |
+
|
| 20 |
+
batch_size = 512
|
| 21 |
+
num_experts = 4
|
| 22 |
+
|
| 23 |
+
# 创建输入数据
|
| 24 |
+
hidden_states = torch.randn(batch_size, hidden_size, requires_grad=True, dtype=torch.bfloat16).to("cuda:0")
|
| 25 |
+
gating = torch.randn(num_experts, hidden_size, requires_grad=True,dtype=torch.bfloat16).to("cuda:0")
|
| 26 |
+
|
| 27 |
+
def auto_grad_version():
|
| 28 |
+
hidden_clone = hidden_states.clone().detach().requires_grad_(True)
|
| 29 |
+
gating_clone = gating.clone().detach().requires_grad_(True)
|
| 30 |
+
|
| 31 |
+
# 前向计算
|
| 32 |
+
input_fp32 = hidden_clone.float()
|
| 33 |
+
logits = torch.nn.functional.linear(input_fp32, gating_clone.to(dtype=input_fp32.dtype))
|
| 34 |
+
logits = logits.view(-1, num_experts)
|
| 35 |
+
|
| 36 |
+
# TopK softmax
|
| 37 |
+
scores, top_indices = torch.topk(logits, k=config.moe_router_topk, dim=1)
|
| 38 |
+
probs = torch.softmax(scores, dim=-1, dtype=torch.float32)
|
| 39 |
+
|
| 40 |
+
# 计算每个专家的token数量
|
| 41 |
+
tokens_per_expert = torch.bincount(top_indices.view(-1), minlength=num_experts)
|
| 42 |
+
|
| 43 |
+
# 应用负载均衡损失
|
| 44 |
+
scores_softmax = torch.softmax(logits, dim=-1, dtype=torch.float32)
|
| 45 |
+
aux_loss = switch_load_balancing_loss_func(
|
| 46 |
+
scores_softmax, tokens_per_expert, config.moe_router_topk, config.moe_aux_loss_coeff
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# 模拟输出
|
| 50 |
+
output = probs
|
| 51 |
+
|
| 52 |
+
# 计算损失并反向传播
|
| 53 |
+
mse_loss = torch.mean(output ** 2)
|
| 54 |
+
total_loss = mse_loss + aux_loss
|
| 55 |
+
|
| 56 |
+
total_loss.backward()
|
| 57 |
+
|
| 58 |
+
return {
|
| 59 |
+
'output': output.detach(),
|
| 60 |
+
'aux_loss': aux_loss.detach(),
|
| 61 |
+
'logits': logits.detach(),
|
| 62 |
+
'hidden_grad': hidden_clone.grad.clone() if hidden_clone.grad is not None else None,
|
| 63 |
+
'gating_grad': gating_clone.grad.clone() if gating_clone.grad is not None else None,
|
| 64 |
+
'total_loss': total_loss.detach()
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def custom_module_version():
|
| 68 |
+
hidden_clone = hidden_states.clone().detach().requires_grad_(True)
|
| 69 |
+
gating_clone = gating.clone().detach().requires_grad_(True)
|
| 70 |
+
|
| 71 |
+
# 使用自定义的前向传播
|
| 72 |
+
probs, indices, aux_loss, input_fp32, gating_weight, input_shape, top_k_dim, logits = MoERouterFunc.forward(
|
| 73 |
+
hidden_clone, gating_clone, num_experts, config
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
output = probs
|
| 77 |
+
|
| 78 |
+
# 计算损失
|
| 79 |
+
mse_loss = torch.mean(output ** 2)
|
| 80 |
+
total_loss = mse_loss + aux_loss
|
| 81 |
+
|
| 82 |
+
# 计算梯度
|
| 83 |
+
grad_output = 2 * output / output.numel()
|
| 84 |
+
|
| 85 |
+
# 使用自定义的反向传播
|
| 86 |
+
tokens_per_expert = torch.bincount(indices.view(-1), minlength=num_experts)
|
| 87 |
+
grad_hidden, grad_gating, _, _, _ = MoERouterFunc.backward(
|
| 88 |
+
grad_output, probs, aux_loss, tokens_per_expert, config,
|
| 89 |
+
indices, input_shape, top_k_dim, input_fp32, gating_clone, logits
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# 注意:我们不能直接获取gating_grad,因为MoERouterFunc.backward不会直接修改gating.grad
|
| 93 |
+
# 因此我们将比较hidden_states的梯度而非gating的梯度
|
| 94 |
+
|
| 95 |
+
return {
|
| 96 |
+
'output': output.detach(),
|
| 97 |
+
'aux_loss': aux_loss.detach(),
|
| 98 |
+
'logits': logits.detach(),
|
| 99 |
+
'hidden_grad': grad_hidden,
|
| 100 |
+
'gating_grad': grad_gating,
|
| 101 |
+
'total_loss': total_loss.detach()
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
print("运行PyTorch AutoGrad版本...")
|
| 105 |
+
auto_results = auto_grad_version()
|
| 106 |
+
|
| 107 |
+
print("运行自定义MoERouterFunc版本...")
|
| 108 |
+
custom_results = custom_module_version()
|
| 109 |
+
|
| 110 |
+
print("\n前向传播对比:")
|
| 111 |
+
output_diff = torch.max(torch.abs(auto_results['output'] - custom_results['output'])).item()
|
| 112 |
+
print(f" 输出差异最大值: {output_diff}")
|
| 113 |
+
logits_diff = torch.max(torch.abs(auto_results['logits'] - custom_results['logits'])).item()
|
| 114 |
+
print(f" logits差异最大值: {logits_diff}")
|
| 115 |
+
|
| 116 |
+
aux_loss_diff = torch.abs(auto_results['aux_loss'] - custom_results['aux_loss']).item()
|
| 117 |
+
print(f" 辅助损失差异: {aux_loss_diff}")
|
| 118 |
+
|
| 119 |
+
total_loss_diff = torch.abs(auto_results['total_loss'] - custom_results['total_loss']).item()
|
| 120 |
+
print(f" 总损失差异: {total_loss_diff}")
|
| 121 |
+
|
| 122 |
+
print("\n反向传播对比:")
|
| 123 |
+
if auto_results['hidden_grad'] is not None and custom_results['hidden_grad'] is not None:
|
| 124 |
+
hidden_grad_diff = torch.max(torch.abs(auto_results['hidden_grad'] - custom_results['hidden_grad'])).item()
|
| 125 |
+
print(f" hidden_states梯度差异最大值: {hidden_grad_diff}")
|
| 126 |
+
else:
|
| 127 |
+
print(" 无法比较hidden_states梯度(至少有一个为None)")
|
| 128 |
+
|
| 129 |
+
if auto_results['gating_grad'] is not None and custom_results['gating_grad'] is not None:
|
| 130 |
+
gating_grad_diff = torch.max(torch.abs(auto_results['gating_grad'] - custom_results['gating_grad'])).item()
|
| 131 |
+
print(f" gating梯度差异最大值: {gating_grad_diff}")
|
| 132 |
+
else:
|
| 133 |
+
print(" 无法比较gating梯度(至少有一个为None)")
|
| 134 |
+
|
| 135 |
+
# 检查差异是否在阈值范围内
|
| 136 |
+
threshold = 1e-5
|
| 137 |
+
all_passed = True
|
| 138 |
+
|
| 139 |
+
if output_diff >= threshold:
|
| 140 |
+
all_passed = False
|
| 141 |
+
print(f"输出差异超过阈值: {output_diff} >= {threshold}")
|
| 142 |
+
|
| 143 |
+
if aux_loss_diff >= threshold:
|
| 144 |
+
all_passed = False
|
| 145 |
+
print(f"辅助损失差异超过阈值: {aux_loss_diff} >= {threshold}")
|
| 146 |
+
|
| 147 |
+
if total_loss_diff >= threshold:
|
| 148 |
+
all_passed = False
|
| 149 |
+
print(f"总损失差异超过阈值: {total_loss_diff} >= {threshold}")
|
| 150 |
+
|
| 151 |
+
if auto_results['hidden_grad'] is not None and custom_results['hidden_grad'] is not None:
|
| 152 |
+
if hidden_grad_diff >= threshold:
|
| 153 |
+
all_passed = False
|
| 154 |
+
print(f"hidden_states梯度差异超过阈值: {hidden_grad_diff} >= {threshold}")
|
| 155 |
+
|
| 156 |
+
if all_passed:
|
| 157 |
+
print("\n测试通过!自定义前向/反向传播与PyTorch AutoGrad结果一致")
|
| 158 |
+
else:
|
| 159 |
+
print("\n测试失败!自定义前向/反向传播与PyTorch AutoGrad结果不一致")
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
test_moe_route_forward_backward()
|
playground/Abbie-h100/tests/test_qwen2_layer.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import Qwen2Config
|
| 5 |
+
from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer, Qwen2RotaryEmbedding
|
| 6 |
+
|
| 7 |
+
from abbie.gargantua.config import GenericTransformerConfig
|
| 8 |
+
from abbie.gargantua.functional import GargantuaLayerFunc
|
| 9 |
+
from abbie.gargantua.layer import GenericTransformerLayer
|
| 10 |
+
from abbie.utils.deterministic_utils import set_deterministic
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def make_config() -> Qwen2Config:
|
| 14 |
+
# Qwen2.5-7B configs
|
| 15 |
+
return Qwen2Config(
|
| 16 |
+
attention_dropout=0.0,
|
| 17 |
+
bos_token_id=151643,
|
| 18 |
+
eos_token_id=151645,
|
| 19 |
+
hidden_act="silu",
|
| 20 |
+
hidden_size=3584,
|
| 21 |
+
initializer_range=0.02,
|
| 22 |
+
intermediate_size=18944,
|
| 23 |
+
max_position_embeddings=32768,
|
| 24 |
+
max_window_layers=28,
|
| 25 |
+
num_attention_heads=28,
|
| 26 |
+
num_hidden_layers=28,
|
| 27 |
+
num_key_value_heads=4,
|
| 28 |
+
rms_norm_eps=1e-06,
|
| 29 |
+
rope_theta=1000000.0,
|
| 30 |
+
sliding_window=131072,
|
| 31 |
+
tie_word_embeddings=False,
|
| 32 |
+
torch_dtype="bfloat16",
|
| 33 |
+
use_cache=True,
|
| 34 |
+
use_sliding_window=False,
|
| 35 |
+
vocab_size=152064,
|
| 36 |
+
attn_implementation="flash_attention_2",
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def zero_grads(layer: Qwen2DecoderLayer):
|
| 41 |
+
for param in layer.parameters():
|
| 42 |
+
param.grad = None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def gather_grads(layer: Qwen2DecoderLayer):
|
| 46 |
+
grads = {}
|
| 47 |
+
for name, param in layer.named_parameters():
|
| 48 |
+
grads[name] = param.grad
|
| 49 |
+
return grads
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def compare_tensors(
|
| 53 |
+
a: torch.Tensor,
|
| 54 |
+
b: torch.Tensor,
|
| 55 |
+
name: str = "tensor",
|
| 56 |
+
) -> torch.Tensor:
|
| 57 |
+
hidden_size = a.size(-1)
|
| 58 |
+
sims = torch.nn.functional.cosine_similarity(
|
| 59 |
+
a.reshape(-1, hidden_size),
|
| 60 |
+
b.reshape(-1, hidden_size),
|
| 61 |
+
dim=-1,
|
| 62 |
+
)
|
| 63 |
+
diff = a - b
|
| 64 |
+
print(
|
| 65 |
+
f"{name} "
|
| 66 |
+
f"min={sims.min().item():.3f} "
|
| 67 |
+
f"mean={sims.mean().item():.3f} "
|
| 68 |
+
f"ratio_diff={diff.nonzero().size(0) / diff.numel():.3f} "
|
| 69 |
+
f"max_diff={diff.abs().max().item():.3e}"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main():
|
| 74 |
+
parser = argparse.ArgumentParser()
|
| 75 |
+
parser.add_argument("-s", "--seqlen", type=int, default=4 << 10)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--deterministic",
|
| 78 |
+
action="store_true",
|
| 79 |
+
help="Use deterministic algo",
|
| 80 |
+
)
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--compile",
|
| 83 |
+
action="store_true",
|
| 84 |
+
help="Compile layer (only effective for hf)",
|
| 85 |
+
)
|
| 86 |
+
parser.add_argument("--use_liger", action="store_true")
|
| 87 |
+
|
| 88 |
+
parser.add_argument("--recompute_norm", action="store_true")
|
| 89 |
+
parser.add_argument("--recompute_attn_up_proj", action="store_true")
|
| 90 |
+
parser.add_argument("--recompute_attn", action="store_true")
|
| 91 |
+
parser.add_argument("--recompute_mlp", action="store_true")
|
| 92 |
+
parser.add_argument("--recompute_mlp_act", action="store_true")
|
| 93 |
+
parser.add_argument("--recompute_dispatch", action="store_true")
|
| 94 |
+
parser.add_argument("--activation_offloading", action="store_true")
|
| 95 |
+
|
| 96 |
+
args = parser.parse_args()
|
| 97 |
+
print(args)
|
| 98 |
+
|
| 99 |
+
if args.deterministic:
|
| 100 |
+
set_deterministic()
|
| 101 |
+
|
| 102 |
+
if args.use_liger:
|
| 103 |
+
from liger_kernel.transformers import apply_liger_kernel_to_qwen2
|
| 104 |
+
apply_liger_kernel_to_qwen2()
|
| 105 |
+
|
| 106 |
+
# Init model
|
| 107 |
+
config = make_config()
|
| 108 |
+
hf_layer = Qwen2DecoderLayer(config=config, layer_idx=0)
|
| 109 |
+
rotary_emb = Qwen2RotaryEmbedding(config, device="cuda")
|
| 110 |
+
hf_layer.train().to(torch.bfloat16).cuda()
|
| 111 |
+
|
| 112 |
+
if args.compile:
|
| 113 |
+
hf_layer.compile(dynamic=True)
|
| 114 |
+
|
| 115 |
+
# Make some dummy data
|
| 116 |
+
seqlen = args.seqlen
|
| 117 |
+
input_tensor = torch.randn(1, seqlen, config.hidden_size, dtype=torch.bfloat16, device="cuda")
|
| 118 |
+
position_ids = torch.arange(seqlen, dtype=torch.long, device="cuda")[None]
|
| 119 |
+
attention_mask = torch.ones_like(position_ids)
|
| 120 |
+
|
| 121 |
+
position_embeddings = rotary_emb(input_tensor, position_ids)
|
| 122 |
+
cu_seqlens = torch.tensor([0, seqlen], dtype=torch.int32, device="cuda")
|
| 123 |
+
max_seqlen = cu_seqlens.diff().max()
|
| 124 |
+
|
| 125 |
+
d_output_tensor = torch.randn_like(input_tensor)
|
| 126 |
+
input_tensor = input_tensor.detach().requires_grad_(True)
|
| 127 |
+
|
| 128 |
+
# Calculate reference grads
|
| 129 |
+
output_tensor_hf = hf_layer(
|
| 130 |
+
hidden_states=input_tensor,
|
| 131 |
+
attention_mask=attention_mask,
|
| 132 |
+
position_ids=position_ids,
|
| 133 |
+
position_embeddings=position_embeddings,
|
| 134 |
+
cumulative_seqlens_q=cu_seqlens,
|
| 135 |
+
cumulative_seqlens_k=cu_seqlens,
|
| 136 |
+
max_length_q=max_seqlen,
|
| 137 |
+
max_length_k=max_seqlen,
|
| 138 |
+
)
|
| 139 |
+
if isinstance(output_tensor_hf, tuple):
|
| 140 |
+
output_tensor_hf = output_tensor_hf[0]
|
| 141 |
+
|
| 142 |
+
torch.cuda.synchronize()
|
| 143 |
+
input_tensor.grad = None
|
| 144 |
+
zero_grads(hf_layer)
|
| 145 |
+
torch.autograd.backward((output_tensor_hf,), (d_output_tensor,))
|
| 146 |
+
|
| 147 |
+
torch.cuda.synchronize()
|
| 148 |
+
hf_grads = gather_grads(hf_layer)
|
| 149 |
+
hf_grads["input_tensor"] = input_tensor.grad
|
| 150 |
+
|
| 151 |
+
# Build gargantua layer
|
| 152 |
+
gg_config = GenericTransformerConfig(
|
| 153 |
+
dp_group=None,
|
| 154 |
+
pp_group=None,
|
| 155 |
+
ep_group=None,
|
| 156 |
+
vocab_size=config.vocab_size,
|
| 157 |
+
hidden_size=config.hidden_size,
|
| 158 |
+
intermediate_size=config.intermediate_size,
|
| 159 |
+
num_hidden_layers=config.num_hidden_layers,
|
| 160 |
+
num_attention_heads=config.num_attention_heads,
|
| 161 |
+
num_key_value_heads=config.num_key_value_heads,
|
| 162 |
+
max_position_embeddings=config.max_position_embeddings,
|
| 163 |
+
rms_norm_eps=config.rms_norm_eps,
|
| 164 |
+
tie_word_embeddings=config.tie_word_embeddings,
|
| 165 |
+
rope_theta=config.rope_theta,
|
| 166 |
+
use_qkv_bias=True,
|
| 167 |
+
use_o_bias=False,
|
| 168 |
+
use_mlp_gate_up_bias=False,
|
| 169 |
+
use_mlp_down_bias=False,
|
| 170 |
+
pad_token_id=config.pad_token_id,
|
| 171 |
+
head_size=None,
|
| 172 |
+
dtype=torch.bfloat16,
|
| 173 |
+
recompute_norm=args.recompute_norm,
|
| 174 |
+
recompute_attn_up_proj=args.recompute_attn_up_proj,
|
| 175 |
+
recompute_attn=args.recompute_attn,
|
| 176 |
+
recompute_mlp=args.recompute_mlp,
|
| 177 |
+
recompute_mlp_act=args.recompute_mlp_act,
|
| 178 |
+
recompute_dispatch=args.recompute_dispatch,
|
| 179 |
+
activation_offloading=args.activation_offloading,
|
| 180 |
+
)
|
| 181 |
+
gg_layer = GenericTransformerLayer(gg_config)
|
| 182 |
+
gg_layer.load_state_dict(hf_layer.state_dict())
|
| 183 |
+
|
| 184 |
+
gg_layer.train().to(torch.bfloat16).cuda()
|
| 185 |
+
gg_layer.requires_grad_(True)
|
| 186 |
+
|
| 187 |
+
# Calculate gargantua grads
|
| 188 |
+
ctx, output_tensor_gargantua = GargantuaLayerFunc.apply_module(
|
| 189 |
+
layer=gg_layer,
|
| 190 |
+
x=input_tensor,
|
| 191 |
+
cos=position_embeddings[0],
|
| 192 |
+
sin=position_embeddings[1],
|
| 193 |
+
cu_seqlens=cu_seqlens,
|
| 194 |
+
max_seqlen=max_seqlen,
|
| 195 |
+
global_num_tokens=attention_mask.ne(0).sum().item(),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
torch.cuda.synchronize()
|
| 199 |
+
input_tensor.grad = None
|
| 200 |
+
zero_grads(gg_layer)
|
| 201 |
+
torch.autograd.backward((output_tensor_gargantua,), (d_output_tensor,))
|
| 202 |
+
|
| 203 |
+
torch.cuda.synchronize()
|
| 204 |
+
gg_grads = gather_grads(gg_layer)
|
| 205 |
+
gg_grads["input_tensor"] = input_tensor.grad
|
| 206 |
+
|
| 207 |
+
# Now compare outputs and grads
|
| 208 |
+
compare_tensors(output_tensor_hf, output_tensor_gargantua, name="output_tensor")
|
| 209 |
+
for name, hf_grad in hf_grads.items():
|
| 210 |
+
gg_grad = gg_grads[name]
|
| 211 |
+
compare_tensors(hf_grad, gg_grad, name=name)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
main()
|
playground/Abbie-h100/tests/test_qwen3_moe_layer.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.distributed as dist
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from transformers import Qwen3MoeConfig
|
| 7 |
+
from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeDecoderLayer, Qwen3MoeRotaryEmbedding
|
| 8 |
+
|
| 9 |
+
from abbie.device_mesh_manager import DMM, init_distributed_env
|
| 10 |
+
from abbie.gargantua.config import GenericTransformerConfig
|
| 11 |
+
from abbie.gargantua.functional import GargantuaLayerFunc
|
| 12 |
+
from abbie.gargantua.layer import GenericTransformerLayer
|
| 13 |
+
from abbie.models.qwen3_moe import Qwen3MoeForCausalLMAbbie
|
| 14 |
+
from abbie.utils.deterministic_utils import set_deterministic
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def patched_sparse_moe_forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 18 |
+
""" """
|
| 19 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 20 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 21 |
+
# router_logits: (batch * sequence_length, n_experts)
|
| 22 |
+
router_logits = self.gate(hidden_states)
|
| 23 |
+
|
| 24 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
|
| 25 |
+
routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
|
| 26 |
+
if self.norm_topk_prob: # only diff with mixtral sparse moe block!
|
| 27 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 28 |
+
# we cast back to the input dtype
|
| 29 |
+
routing_weights = routing_weights.to(hidden_states.dtype)
|
| 30 |
+
|
| 31 |
+
# final_hidden_states = torch.zeros(
|
| 32 |
+
# (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
| 33 |
+
# )
|
| 34 |
+
debug_hidden_states = hidden_states.new_zeros(*routing_weights.shape, hidden_dim)
|
| 35 |
+
|
| 36 |
+
# One hot encode the selected experts to create an expert mask
|
| 37 |
+
# this will be used to easily index which expert is going to be sollicitated
|
| 38 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
|
| 39 |
+
|
| 40 |
+
# Loop over all available experts in the model and perform the computation on each expert
|
| 41 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 42 |
+
for expert_idx in expert_hit:
|
| 43 |
+
expert_layer = self.experts[expert_idx]
|
| 44 |
+
idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
|
| 45 |
+
|
| 46 |
+
# Index the correct hidden states and compute the expert hidden state for
|
| 47 |
+
# the current expert. We need to make sure to multiply the output hidden
|
| 48 |
+
# states by `routing_weights` on the corresponding tokens (top-1 and top-2)
|
| 49 |
+
current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
|
| 50 |
+
# current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
|
| 51 |
+
|
| 52 |
+
# However `index_add_` only support torch tensors for indexing so we'll use
|
| 53 |
+
# the `top_x` tensor here.
|
| 54 |
+
# final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
| 55 |
+
debug_hidden_states[top_x, idx] = expert_layer(current_state) * routing_weights[top_x, idx, None]
|
| 56 |
+
# final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
| 57 |
+
final_hidden_states = debug_hidden_states.sum(1)
|
| 58 |
+
return final_hidden_states, router_logits
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_hf_layer():
|
| 62 |
+
from liger_kernel.transformers import apply_liger_kernel_to_qwen3_moe
|
| 63 |
+
|
| 64 |
+
apply_liger_kernel_to_qwen3_moe()
|
| 65 |
+
|
| 66 |
+
# Qwen3MoeSparseMoeBlock.forward = patched_sparse_moe_forward
|
| 67 |
+
|
| 68 |
+
# Copied configs from qwen3-30b-a3b
|
| 69 |
+
config = Qwen3MoeConfig(
|
| 70 |
+
attention_bias=False,
|
| 71 |
+
attention_dropout=0.0,
|
| 72 |
+
bos_token_id=151643,
|
| 73 |
+
decoder_sparse_step=1,
|
| 74 |
+
eos_token_id=151645,
|
| 75 |
+
head_dim=128,
|
| 76 |
+
hidden_act="silu",
|
| 77 |
+
hidden_size=2048,
|
| 78 |
+
initializer_range=0.02,
|
| 79 |
+
intermediate_size=6144,
|
| 80 |
+
max_position_embeddings=40960,
|
| 81 |
+
max_window_layers=48,
|
| 82 |
+
mlp_only_layers=[],
|
| 83 |
+
moe_intermediate_size=768,
|
| 84 |
+
norm_topk_prob=True,
|
| 85 |
+
num_attention_heads=32,
|
| 86 |
+
num_experts=128,
|
| 87 |
+
num_experts_per_tok=8,
|
| 88 |
+
num_hidden_layers=48,
|
| 89 |
+
num_key_value_heads=4,
|
| 90 |
+
output_router_logits=False,
|
| 91 |
+
rms_norm_eps=1e-06,
|
| 92 |
+
rope_scaling=None,
|
| 93 |
+
rope_theta=1000000.0,
|
| 94 |
+
router_aux_loss_coef=0.001,
|
| 95 |
+
sliding_window=None,
|
| 96 |
+
tie_word_embeddings=False,
|
| 97 |
+
torch_dtype="bfloat16",
|
| 98 |
+
transformers_version="4.51.0",
|
| 99 |
+
use_cache=False,
|
| 100 |
+
use_sliding_window=False,
|
| 101 |
+
vocab_size=151936,
|
| 102 |
+
attn_implementation="flash_attention_2",
|
| 103 |
+
)
|
| 104 |
+
layer = Qwen3MoeDecoderLayer(config, layer_idx=0)
|
| 105 |
+
layer.train().to(torch.bfloat16).cuda()
|
| 106 |
+
|
| 107 |
+
# Sync parameter values
|
| 108 |
+
for param in layer.parameters():
|
| 109 |
+
dist.broadcast(param.data, src=0)
|
| 110 |
+
|
| 111 |
+
return config, layer
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def make_gg_layer(
|
| 115 |
+
hf_config: Qwen3MoeConfig,
|
| 116 |
+
hf_layer: Qwen3MoeDecoderLayer,
|
| 117 |
+
**kwargs,
|
| 118 |
+
):
|
| 119 |
+
config = Qwen3MoeForCausalLMAbbie.convert_hf_config(
|
| 120 |
+
hf_config=hf_config,
|
| 121 |
+
dp_group=DMM.dp_group,
|
| 122 |
+
pp_group=DMM.pp_group,
|
| 123 |
+
ep_group=DMM.ep_group,
|
| 124 |
+
ep_dp_group=DMM.ep_dp_group,
|
| 125 |
+
sp_group=DMM.sp_group,
|
| 126 |
+
pp_x_sp_group=DMM.pp_x_sp_group,
|
| 127 |
+
**kwargs,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
layer = GenericTransformerLayer(config, layer_idx=0)
|
| 131 |
+
layer.train().cuda()
|
| 132 |
+
|
| 133 |
+
# Hard code the param loading
|
| 134 |
+
layer.input_layernorm.load_state_dict(hf_layer.input_layernorm.state_dict())
|
| 135 |
+
layer.self_attn.load_state_dict(hf_layer.self_attn.state_dict())
|
| 136 |
+
layer.post_attention_layernorm.load_state_dict(hf_layer.post_attention_layernorm.state_dict())
|
| 137 |
+
|
| 138 |
+
layer.moe.router.load_state_dict(hf_layer.mlp.gate.state_dict())
|
| 139 |
+
|
| 140 |
+
expert_start_idx = config.num_routed_experts_per_rank * config.ep_group.rank()
|
| 141 |
+
expert_end_idx = config.num_routed_experts_per_rank + expert_start_idx
|
| 142 |
+
local_experts = hf_layer.mlp.experts[expert_start_idx:expert_end_idx]
|
| 143 |
+
|
| 144 |
+
gate_up_weight = torch.stack(
|
| 145 |
+
[torch.cat([e.gate_proj.weight.detach(), e.up_proj.weight.detach()], dim=0) for e in local_experts]
|
| 146 |
+
)
|
| 147 |
+
layer.moe.experts_gate_up_proj_weight.data.copy_(gate_up_weight)
|
| 148 |
+
|
| 149 |
+
layer.moe.experts_down_proj_weight.data.copy_(torch.stack([e.down_proj.weight.detach() for e in local_experts]))
|
| 150 |
+
|
| 151 |
+
return config, layer
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def zero_grads(module: torch.nn.Module):
|
| 155 |
+
for param in module.parameters():
|
| 156 |
+
param.grad = None
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def gather_grads(layer: torch.nn.Module):
|
| 160 |
+
grads = {}
|
| 161 |
+
for name, param in layer.named_parameters():
|
| 162 |
+
grads[name] = param.grad
|
| 163 |
+
return grads
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def compare_tensors(
|
| 167 |
+
a: torch.Tensor,
|
| 168 |
+
b: torch.Tensor,
|
| 169 |
+
name: str = "tensor",
|
| 170 |
+
) -> torch.Tensor:
|
| 171 |
+
assert a.shape == b.shape, f"{name} {a.shape} {b.shape}"
|
| 172 |
+
hidden_size = a.size(-1)
|
| 173 |
+
sims = torch.nn.functional.cosine_similarity(
|
| 174 |
+
a.reshape(-1, hidden_size),
|
| 175 |
+
b.reshape(-1, hidden_size),
|
| 176 |
+
dim=-1,
|
| 177 |
+
)
|
| 178 |
+
diff = a - b
|
| 179 |
+
print(
|
| 180 |
+
f"{name} "
|
| 181 |
+
f"min={sims.min().item():.3f} "
|
| 182 |
+
f"mean={sims.mean().item():.3f} "
|
| 183 |
+
f"mean={sims.mean().item():.3f} "
|
| 184 |
+
f"ratio_diff={diff.nonzero().size(0) / diff.numel():.3f} "
|
| 185 |
+
f"max_diff={diff.abs().max().item():.3e}"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_qwen3_moe_layer(
|
| 190 |
+
seqlen: int = 4096,
|
| 191 |
+
recompute_norm: bool = False,
|
| 192 |
+
recompute_attn_up_proj: bool = False,
|
| 193 |
+
recompute_attn: bool = False,
|
| 194 |
+
recompute_attn_down_proj: bool = False,
|
| 195 |
+
recompute_mlp: bool = False,
|
| 196 |
+
recompute_mlp_act: bool = False,
|
| 197 |
+
recompute_dispatch: bool = False,
|
| 198 |
+
token_dispatch_method: str = "all-to-all",
|
| 199 |
+
):
|
| 200 |
+
hf_config, hf_layer = load_hf_layer()
|
| 201 |
+
gg_config, gg_layer = make_gg_layer(
|
| 202 |
+
hf_config,
|
| 203 |
+
hf_layer,
|
| 204 |
+
recompute_norm=recompute_norm,
|
| 205 |
+
recompute_attn_up_proj=recompute_attn_up_proj,
|
| 206 |
+
recompute_attn=recompute_attn,
|
| 207 |
+
recompute_attn_down_proj=recompute_attn_down_proj,
|
| 208 |
+
recompute_mlp=recompute_mlp,
|
| 209 |
+
recompute_mlp_act=recompute_mlp_act,
|
| 210 |
+
recompute_dispatch=recompute_dispatch,
|
| 211 |
+
token_dispatch_method=token_dispatch_method,
|
| 212 |
+
)
|
| 213 |
+
rotary_emb = Qwen3MoeRotaryEmbedding(hf_config, device="cuda")
|
| 214 |
+
|
| 215 |
+
if token_dispatch_method == "deep-ep":
|
| 216 |
+
from abbie.ops.deep_ep import setup_deep_ep_buffer
|
| 217 |
+
|
| 218 |
+
setup_deep_ep_buffer(
|
| 219 |
+
group=DMM.ep_group,
|
| 220 |
+
hidden_bytes=gg_config.hidden_size * 2,
|
| 221 |
+
num_sms=20,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
elif token_dispatch_method == "hybrid-ep":
|
| 225 |
+
from abbie.ops.hybrid_ep import setup_hybrid_ep_buffer
|
| 226 |
+
|
| 227 |
+
setup_hybrid_ep_buffer(
|
| 228 |
+
ep_group=DMM.ep_group,
|
| 229 |
+
hidden_dim=gg_config.hidden_size,
|
| 230 |
+
max_num_of_tokens_per_rank=seqlen,
|
| 231 |
+
num_local_experts=gg_config.num_routed_experts_per_rank,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
expert_start_idx = gg_config.num_routed_experts_per_rank * gg_config.ep_group.rank()
|
| 235 |
+
expert_end_idx = gg_config.num_routed_experts_per_rank + expert_start_idx
|
| 236 |
+
local_experts = hf_layer.mlp.experts[expert_start_idx:expert_end_idx]
|
| 237 |
+
|
| 238 |
+
# Make some dummy data
|
| 239 |
+
input_tensor = torch.randn(1, seqlen, gg_config.hidden_size, dtype=torch.bfloat16, device="cuda")
|
| 240 |
+
position_ids = torch.arange(seqlen, dtype=torch.long, device="cuda")[None]
|
| 241 |
+
attention_mask = torch.ones_like(position_ids)
|
| 242 |
+
|
| 243 |
+
position_embeddings = rotary_emb(input_tensor, position_ids)
|
| 244 |
+
cu_seqlens = torch.tensor([0, seqlen], dtype=torch.int32, device="cuda")
|
| 245 |
+
max_seqlen = cu_seqlens.diff().max()
|
| 246 |
+
|
| 247 |
+
d_output_tensor = torch.randn_like(input_tensor)
|
| 248 |
+
input_tensor = input_tensor.detach_().requires_grad_(True)
|
| 249 |
+
|
| 250 |
+
# Run for huggingface
|
| 251 |
+
output_tensor_hf = hf_layer(
|
| 252 |
+
hidden_states=input_tensor,
|
| 253 |
+
attention_mask=attention_mask,
|
| 254 |
+
position_ids=position_ids,
|
| 255 |
+
position_embeddings=position_embeddings,
|
| 256 |
+
cumulative_seqlens_q=cu_seqlens,
|
| 257 |
+
cumulative_seqlens_k=cu_seqlens,
|
| 258 |
+
max_length_q=max_seqlen,
|
| 259 |
+
max_length_k=max_seqlen,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
torch.cuda.synchronize()
|
| 263 |
+
input_tensor.grad = None
|
| 264 |
+
zero_grads(hf_layer)
|
| 265 |
+
torch.autograd.backward((output_tensor_hf,), (d_output_tensor,))
|
| 266 |
+
output_tensor_hf = output_tensor_hf.detach()
|
| 267 |
+
|
| 268 |
+
torch.cuda.synchronize()
|
| 269 |
+
hf_grads = gather_grads(hf_layer)
|
| 270 |
+
hf_grads["input_tensor"] = input_tensor.grad
|
| 271 |
+
|
| 272 |
+
# For comparing with gg later
|
| 273 |
+
hf_grads["moe.router.weight"] = hf_layer.mlp.gate.weight.grad
|
| 274 |
+
# hf_grads["moe.experts_gate_proj_weight"] = torch.stack([e.gate_proj.weight.grad.detach() for e in local_experts])
|
| 275 |
+
# hf_grads["moe.experts_up_proj_weight"] = torch.stack([e.up_proj.weight.grad.detach() for e in local_experts])
|
| 276 |
+
|
| 277 |
+
hf_grads["moe.experts_gate_up_proj_weight"] = torch.stack(
|
| 278 |
+
[torch.cat([e.gate_proj.weight.grad.detach(), e.up_proj.weight.grad.detach()], dim=0) for e in local_experts]
|
| 279 |
+
)
|
| 280 |
+
hf_grads["moe.experts_down_proj_weight"] = torch.stack([e.down_proj.weight.grad.detach() for e in local_experts])
|
| 281 |
+
hf_grads["moe.experts_gate_up_proj_weight"] *= DMM.ep_size
|
| 282 |
+
hf_grads["moe.experts_down_proj_weight"] *= DMM.ep_size
|
| 283 |
+
|
| 284 |
+
input_tensor.grad = None
|
| 285 |
+
zero_grads(hf_layer)
|
| 286 |
+
|
| 287 |
+
# Run for gargantua
|
| 288 |
+
ctx, output_tensor_gg = GargantuaLayerFunc.apply_module(
|
| 289 |
+
layer=gg_layer,
|
| 290 |
+
x=input_tensor[0],
|
| 291 |
+
cos=position_embeddings[0],
|
| 292 |
+
sin=position_embeddings[1],
|
| 293 |
+
cu_seqlens=cu_seqlens,
|
| 294 |
+
max_seqlen=max_seqlen,
|
| 295 |
+
global_num_tokens=seqlen,
|
| 296 |
+
)
|
| 297 |
+
output_tensor_gg = output_tensor_gg[None]
|
| 298 |
+
|
| 299 |
+
ctx.tensors.keys()
|
| 300 |
+
|
| 301 |
+
with torch.no_grad():
|
| 302 |
+
hf_post_attn_states = (
|
| 303 |
+
input_tensor
|
| 304 |
+
+ hf_layer.self_attn(
|
| 305 |
+
hidden_states=hf_layer.input_layernorm(input_tensor),
|
| 306 |
+
attention_mask=attention_mask,
|
| 307 |
+
position_ids=position_ids,
|
| 308 |
+
position_embeddings=position_embeddings,
|
| 309 |
+
cumulative_seqlens_q=cu_seqlens,
|
| 310 |
+
cumulative_seqlens_k=cu_seqlens,
|
| 311 |
+
max_length_q=max_seqlen,
|
| 312 |
+
max_length_k=max_seqlen,
|
| 313 |
+
)[0]
|
| 314 |
+
)
|
| 315 |
+
gg_post_attn_states = ctx.tensors["post_attn_states"].detach().clone()
|
| 316 |
+
# copy_of_ctx_tensors = {k: v for k, v in ctx.tensors.items()}
|
| 317 |
+
if dist.get_rank() == 0:
|
| 318 |
+
compare_tensors(hf_post_attn_states, gg_post_attn_states[None], "post attn states")
|
| 319 |
+
|
| 320 |
+
torch.cuda.synchronize()
|
| 321 |
+
input_tensor.grad = None
|
| 322 |
+
zero_grads(gg_layer)
|
| 323 |
+
torch.autograd.backward((output_tensor_gg,), (d_output_tensor,))
|
| 324 |
+
output_tensor_gg = output_tensor_gg.detach().clone()
|
| 325 |
+
|
| 326 |
+
torch.cuda.synchronize()
|
| 327 |
+
gg_grads = gather_grads(gg_layer)
|
| 328 |
+
gg_grads["input_tensor"] = input_tensor.grad
|
| 329 |
+
|
| 330 |
+
input_tensor.grad = None
|
| 331 |
+
zero_grads(gg_layer)
|
| 332 |
+
|
| 333 |
+
with torch.no_grad():
|
| 334 |
+
for i in range(dist.get_world_size()):
|
| 335 |
+
if i == dist.get_rank():
|
| 336 |
+
print(f"# rank={dist.get_rank()}")
|
| 337 |
+
compare_tensors(output_tensor_hf, output_tensor_gg, "output_tensor")
|
| 338 |
+
|
| 339 |
+
for name, gg_grad in gg_grads.items():
|
| 340 |
+
if name in hf_grads:
|
| 341 |
+
hf_grad = hf_grads[name]
|
| 342 |
+
compare_tensors(gg_grad, hf_grad, name)
|
| 343 |
+
|
| 344 |
+
else:
|
| 345 |
+
print(f"Skip {name}")
|
| 346 |
+
|
| 347 |
+
dist.barrier()
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def main():
|
| 351 |
+
parser = argparse.ArgumentParser()
|
| 352 |
+
parser.add_argument("--seqlen", type=int, default=4096)
|
| 353 |
+
parser.add_argument("--ep", type=int, default=1)
|
| 354 |
+
|
| 355 |
+
parser.add_argument("--recompute_norm", action="store_true")
|
| 356 |
+
parser.add_argument("--recompute_attn_up_proj", action="store_true")
|
| 357 |
+
parser.add_argument("--recompute_attn", action="store_true")
|
| 358 |
+
parser.add_argument("--recompute_attn_down_proj", action="store_true")
|
| 359 |
+
parser.add_argument("--recompute_mlp", action="store_true")
|
| 360 |
+
parser.add_argument("--recompute_mlp_act", action="store_true")
|
| 361 |
+
parser.add_argument("--recompute_dispatch", action="store_true")
|
| 362 |
+
|
| 363 |
+
parser.add_argument("--token-dispatch-method", type=str, default="all-to-all")
|
| 364 |
+
|
| 365 |
+
args = parser.parse_args()
|
| 366 |
+
|
| 367 |
+
init_distributed_env(ep_size=args.ep)
|
| 368 |
+
set_deterministic()
|
| 369 |
+
test_qwen3_moe_layer(
|
| 370 |
+
seqlen=args.seqlen,
|
| 371 |
+
recompute_norm=args.recompute_norm,
|
| 372 |
+
recompute_attn_up_proj=args.recompute_attn_up_proj,
|
| 373 |
+
recompute_attn=args.recompute_attn,
|
| 374 |
+
recompute_attn_down_proj=args.recompute_attn_down_proj,
|
| 375 |
+
recompute_mlp=args.recompute_mlp,
|
| 376 |
+
recompute_mlp_act=args.recompute_mlp_act,
|
| 377 |
+
recompute_dispatch=args.recompute_dispatch,
|
| 378 |
+
token_dispatch_method=args.token_dispatch_method,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
if __name__ == "__main__":
|
| 383 |
+
main()
|
playground/Abbie-h100/tests/test_swiglu.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from abbie.ops.kernels.swiglu import packed_silu_mul_backward, packed_silu_mul_forward
|
| 4 |
+
from abbie.utils.deterministic_utils import set_deterministic
|
| 5 |
+
from tests.utils import compare_tensors
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def torch_silu_mul(gate_up: torch.Tensor) -> torch.Tensor:
|
| 9 |
+
"""Naive reference implementation for comparison."""
|
| 10 |
+
gate, up = gate_up.chunk(2, -1)
|
| 11 |
+
return torch.nn.functional.silu(gate) * up
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_forward():
|
| 15 |
+
"""
|
| 16 |
+
Compare kernel output vs naive PyTorch implementation.
|
| 17 |
+
Tests: Correctness of forward computation.
|
| 18 |
+
"""
|
| 19 |
+
torch.manual_seed(42)
|
| 20 |
+
dtype = torch.bfloat16
|
| 21 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
+
|
| 23 |
+
hidden_size = 1024
|
| 24 |
+
seqlen = 4096
|
| 25 |
+
|
| 26 |
+
# Generate random input [seqlen, hidden_size*2]
|
| 27 |
+
gate_up = torch.randn(seqlen, hidden_size * 2, dtype=dtype, device=device)
|
| 28 |
+
|
| 29 |
+
# Kernel forward
|
| 30 |
+
_, out_kernel = packed_silu_mul_forward(gate_up.clone())
|
| 31 |
+
|
| 32 |
+
# Reference forward
|
| 33 |
+
out_torch = torch_silu_mul(gate_up)
|
| 34 |
+
|
| 35 |
+
# Compare
|
| 36 |
+
ratio = compare_tensors(out_kernel, out_torch, atol=1e-3, rtol=1e-3)
|
| 37 |
+
assert ratio > 0.95, f"Forward pass: {ratio * 100:.2f}% values match, expected >95%"
|
| 38 |
+
print(f"PASS test_forward: {ratio * 100:.2f}% values match")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_backward():
|
| 42 |
+
"""
|
| 43 |
+
Compare kernel gradients vs autograd reference.
|
| 44 |
+
Tests: Correctness of backward gradient computation.
|
| 45 |
+
"""
|
| 46 |
+
torch.manual_seed(42)
|
| 47 |
+
dtype = torch.bfloat16
|
| 48 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 49 |
+
|
| 50 |
+
hidden_size = 1024
|
| 51 |
+
seqlen = 4096
|
| 52 |
+
|
| 53 |
+
# Generate random inputs
|
| 54 |
+
gate_up_orig = torch.randn(seqlen, hidden_size * 2, dtype=dtype, device=device, requires_grad=True)
|
| 55 |
+
dout = torch.randn(seqlen, hidden_size, dtype=dtype, device=device)
|
| 56 |
+
|
| 57 |
+
# REFERENCE: Autograd version
|
| 58 |
+
gate_up_ref = gate_up_orig.clone().detach().requires_grad_(True)
|
| 59 |
+
gate_ref, up_ref = gate_up_ref.chunk(2, dim=-1)
|
| 60 |
+
out_ref = torch.nn.functional.silu(gate_ref) * up_ref
|
| 61 |
+
loss_ref = (out_ref * dout).sum()
|
| 62 |
+
loss_ref.backward()
|
| 63 |
+
dgate_up_ref = gate_up_ref.grad.clone()
|
| 64 |
+
|
| 65 |
+
# KERNEL: Run backward (clone since it's in-place)
|
| 66 |
+
gate_up_kernel = gate_up_orig.clone().detach()
|
| 67 |
+
dgate_up_kernel = packed_silu_mul_backward(gate_up_kernel, dout)
|
| 68 |
+
|
| 69 |
+
# Extract dgate and dup components
|
| 70 |
+
dgate_ref, dup_ref = dgate_up_ref.chunk(2, dim=-1)
|
| 71 |
+
dgate_kernel, dup_kernel = dgate_up_kernel.chunk(2, dim=-1)
|
| 72 |
+
|
| 73 |
+
# Compare gradients
|
| 74 |
+
print("Comparing dgate:")
|
| 75 |
+
dgate_ratio = compare_tensors(dgate_kernel, dgate_ref, atol=1e-2, rtol=1e-2)
|
| 76 |
+
print("Comparing dup:")
|
| 77 |
+
dup_ratio = compare_tensors(dup_kernel, dup_ref, atol=1e-2, rtol=1e-2)
|
| 78 |
+
|
| 79 |
+
assert dgate_ratio > 0.90, f"Backward gate: {dgate_ratio * 100:.2f}% match, expected >90%"
|
| 80 |
+
assert dup_ratio > 0.90, f"Backward up: {dup_ratio * 100:.2f}% match, expected >90%"
|
| 81 |
+
print(f"PASS test_backward: dgate {dgate_ratio * 100:.2f}%, dup {dup_ratio * 100:.2f}%")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_batch_invariant():
|
| 85 |
+
"""
|
| 86 |
+
Verify that batched[i] == individual row i (exact bitwise match).
|
| 87 |
+
Tests: Kernel correctly handles different batch dimensions.
|
| 88 |
+
"""
|
| 89 |
+
set_deterministic()
|
| 90 |
+
torch.manual_seed(42)
|
| 91 |
+
dtype = torch.bfloat16
|
| 92 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 93 |
+
|
| 94 |
+
hidden_size = 1024
|
| 95 |
+
seqlen = 4096
|
| 96 |
+
batch_size = 64
|
| 97 |
+
|
| 98 |
+
# Generate batched input [batch_size, seqlen, hidden_size*2]
|
| 99 |
+
gate_up_batched = torch.randn(batch_size, seqlen, hidden_size * 2, dtype=dtype, device=device)
|
| 100 |
+
|
| 101 |
+
# Run forward on batched tensor
|
| 102 |
+
_, out_batched = packed_silu_mul_forward(gate_up_batched)
|
| 103 |
+
|
| 104 |
+
# Run forward on individual rows and stack
|
| 105 |
+
out_individual = []
|
| 106 |
+
for i in range(batch_size):
|
| 107 |
+
_, out_i = packed_silu_mul_forward(gate_up_batched[i : i + 1])
|
| 108 |
+
out_individual.append(out_i)
|
| 109 |
+
out_individual = torch.cat(out_individual, dim=0)
|
| 110 |
+
|
| 111 |
+
# Require exact bitwise equality
|
| 112 |
+
assert torch.equal(out_batched, out_individual), "Batch invariant: Expected exact bitwise match"
|
| 113 |
+
print("PASS test_batch_invariant: Exact bitwise match confirmed")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == "__main__":
|
| 117 |
+
print("Running test_forward...")
|
| 118 |
+
test_forward()
|
| 119 |
+
print()
|
| 120 |
+
|
| 121 |
+
print("Running test_backward...")
|
| 122 |
+
test_backward()
|
| 123 |
+
print()
|
| 124 |
+
|
| 125 |
+
print("Running test_batch_invariant...")
|
| 126 |
+
test_batch_invariant()
|
| 127 |
+
print()
|
| 128 |
+
|
| 129 |
+
print("All tests passed!")
|
playground/Abbie-h100/tests/test_ulysses.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.distributed as dist
|
| 3 |
+
|
| 4 |
+
from abbie.ops.ulysses import ulysses_all_to_all
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_ulysses():
|
| 8 |
+
dist.init_process_group(backend="nccl")
|
| 9 |
+
rank = dist.get_rank()
|
| 10 |
+
world_size = dist.get_world_size()
|
| 11 |
+
|
| 12 |
+
torch.cuda.set_device(rank)
|
| 13 |
+
device = torch.device("cuda", rank)
|
| 14 |
+
|
| 15 |
+
num_tokens = 16
|
| 16 |
+
num_heads = 8
|
| 17 |
+
head_dim = 64
|
| 18 |
+
|
| 19 |
+
if rank == 0:
|
| 20 |
+
q_full = torch.randn(num_tokens, num_heads, head_dim, device=device)
|
| 21 |
+
k_full = torch.randn(num_tokens, num_heads, head_dim, device=device)
|
| 22 |
+
v_full = torch.randn(num_tokens, num_heads, head_dim, device=device)
|
| 23 |
+
else:
|
| 24 |
+
q_full = torch.empty(num_tokens, num_heads, head_dim, device=device)
|
| 25 |
+
k_full = torch.empty(num_tokens, num_heads, head_dim, device=device)
|
| 26 |
+
v_full = torch.empty(num_tokens, num_heads, head_dim, device=device)
|
| 27 |
+
|
| 28 |
+
dist.broadcast(q_full, src=0)
|
| 29 |
+
dist.broadcast(k_full, src=0)
|
| 30 |
+
dist.broadcast(v_full, src=0)
|
| 31 |
+
|
| 32 |
+
num_tokens_local = num_tokens // world_size
|
| 33 |
+
q_local = q_full.chunk(world_size, dim=0)[rank].clone()
|
| 34 |
+
k_local = k_full.chunk(world_size, dim=0)[rank].clone()
|
| 35 |
+
v_local = v_full.chunk(world_size, dim=0)[rank].clone()
|
| 36 |
+
|
| 37 |
+
print(f"Rank {rank}: Local input shape: {q_local.shape}")
|
| 38 |
+
|
| 39 |
+
q_gathered, h1 = ulysses_all_to_all(q_local, scatter_dim=-2, group=dist.group.WORLD)
|
| 40 |
+
k_gathered, h2 = ulysses_all_to_all(k_local, scatter_dim=-2, group=dist.group.WORLD)
|
| 41 |
+
v_gathered, h3 = ulysses_all_to_all(v_local, scatter_dim=-2, group=dist.group.WORLD)
|
| 42 |
+
h1.wait()
|
| 43 |
+
h2.wait()
|
| 44 |
+
h3.wait()
|
| 45 |
+
|
| 46 |
+
q_gathered = q_gathered.flatten(0, 1)
|
| 47 |
+
k_gathered = k_gathered.flatten(0, 1)
|
| 48 |
+
v_gathered = v_gathered.flatten(0, 1)
|
| 49 |
+
|
| 50 |
+
print(f"Rank {rank}: After pre-attn all-to-all shape: {q_gathered.shape}")
|
| 51 |
+
|
| 52 |
+
num_heads_local = num_heads // world_size
|
| 53 |
+
head_start = rank * num_heads_local
|
| 54 |
+
head_end = (rank + 1) * num_heads_local
|
| 55 |
+
|
| 56 |
+
expected_q = q_full[:, head_start:head_end, :]
|
| 57 |
+
expected_k = k_full[:, head_start:head_end, :]
|
| 58 |
+
expected_v = v_full[:, head_start:head_end, :]
|
| 59 |
+
|
| 60 |
+
assert torch.allclose(q_gathered, expected_q), f"Rank {rank}: q mismatch after pre-attn"
|
| 61 |
+
assert torch.allclose(k_gathered, expected_k), f"Rank {rank}: k mismatch after pre-attn"
|
| 62 |
+
assert torch.allclose(v_gathered, expected_v), f"Rank {rank}: v mismatch after pre-attn"
|
| 63 |
+
|
| 64 |
+
print(f"Rank {rank}: Pre-attn all-to-all verified ✓")
|
| 65 |
+
|
| 66 |
+
q_reconstructed, h4 = ulysses_all_to_all(q_gathered, scatter_dim=-3, group=dist.group.WORLD)
|
| 67 |
+
k_reconstructed, h5 = ulysses_all_to_all(k_gathered, scatter_dim=-3, group=dist.group.WORLD)
|
| 68 |
+
v_reconstructed, h6 = ulysses_all_to_all(v_gathered, scatter_dim=-3, group=dist.group.WORLD)
|
| 69 |
+
h4.wait()
|
| 70 |
+
h5.wait()
|
| 71 |
+
h6.wait()
|
| 72 |
+
|
| 73 |
+
q_reconstructed = q_reconstructed.permute(1, 0, 2, 3).flatten(1, 2)
|
| 74 |
+
k_reconstructed = k_reconstructed.permute(1, 0, 2, 3).flatten(1, 2)
|
| 75 |
+
v_reconstructed = v_reconstructed.permute(1, 0, 2, 3).flatten(1, 2)
|
| 76 |
+
|
| 77 |
+
print(f"Rank {rank}: After post-attn all-to-all shape: {q_reconstructed.shape}")
|
| 78 |
+
|
| 79 |
+
assert torch.allclose(q_reconstructed, q_local), f"Rank {rank}: q round-trip mismatch"
|
| 80 |
+
assert torch.allclose(k_reconstructed, k_local), f"Rank {rank}: k round-trip mismatch"
|
| 81 |
+
assert torch.allclose(v_reconstructed, v_local), f"Rank {rank}: v round-trip mismatch"
|
| 82 |
+
|
| 83 |
+
print(f"Rank {rank}: Post-attn all-to-all (round-trip) verified ✓")
|
| 84 |
+
|
| 85 |
+
if rank == 0:
|
| 86 |
+
print("\nAll tests passed! ✓")
|
| 87 |
+
|
| 88 |
+
dist.destroy_process_group()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
test_ulysses()
|
playground/Abbie-h100/tests/utils.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def compare_tensors(
|
| 5 |
+
a: torch.Tensor,
|
| 6 |
+
b: torch.Tensor,
|
| 7 |
+
atol: float = 1e-5,
|
| 8 |
+
rtol: float = 1e-5,
|
| 9 |
+
) -> float:
|
| 10 |
+
"""
|
| 11 |
+
Compare two tensors and return the ratio of matching values.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
a, b: Tensors to compare
|
| 15 |
+
atol, rtol: Absolute and relative tolerance thresholds
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
ratio: Float between 0.0 and 1.0 indicating fraction of close values
|
| 19 |
+
"""
|
| 20 |
+
mask = torch.isclose(a, b, atol=atol, rtol=rtol)
|
| 21 |
+
matching = mask.sum().item()
|
| 22 |
+
total = mask.numel()
|
| 23 |
+
ratio = matching / total
|
| 24 |
+
|
| 25 |
+
# Log mismatches for debugging
|
| 26 |
+
if ratio < 1.0:
|
| 27 |
+
not_close_count = total - matching
|
| 28 |
+
pct_not_close = (not_close_count / total) * 100
|
| 29 |
+
print(f" {pct_not_close:.2f}% of values not close ({not_close_count}/{total})")
|
| 30 |
+
|
| 31 |
+
# Show details if small number of mismatches
|
| 32 |
+
if not_close_count <= 10:
|
| 33 |
+
mismatches = torch.where(torch.logical_not(mask))
|
| 34 |
+
print(f" Mismatch indices: {mismatches}")
|
| 35 |
+
print(f" Actual: {a[mismatches]}")
|
| 36 |
+
print(f" Expected: {b[mismatches]}")
|
| 37 |
+
|
| 38 |
+
return ratio
|
playground/Abbie-h100/torchrun/run_dense_pp_and_dp.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Below is just a sample for pure cmd line launching.
|
| 2 |
+
# For debug purpose plz refer to launch.json: torch_dense_pipeline
|
| 3 |
+
|
| 4 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ARNOLD_WORKER_0_HOST MASTER_PORT=$ARNOLD_WORKER_0_PORT torchrun \
|
| 5 |
+
--node_rank=$ARNOLD_ID --nproc_per_node=8 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$ARNOLD_WORKER_0_PORT \
|
| 6 |
+
/opt/tiger/Abbie/trainer/dense_trainer.py \
|
| 7 |
+
--model=1b2.yaml \
|
| 8 |
+
--pp_size=2 \
|
| 9 |
+
--trial_name=abbie_dense_1b2_1T_gbs128_gargantua_pp2_ckpt_UT1_b1 \
|
| 10 |
+
--train_home_path=hdfs://harunava/home/byte_tteng_llm/users/yuyifeng.oscar/pretrain \
|
| 11 |
+
--train_dataset=hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train \
|
| 12 |
+
--train_size=1000000000000 \
|
| 13 |
+
--tokenizer=hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227 \
|
| 14 |
+
--pad_idx=1 --vocab_size=136064 \
|
| 15 |
+
--global_batch_size=128 --micro_batch_size=1 --warmup_batch_ratio=0.005 \
|
| 16 |
+
--max_seq_len=4096 --max_position_embeddings=4096 --stride=3840 \
|
| 17 |
+
--lr_max=5e-4 --lr_min=5e-5 --lr_weight_decay=0.1 \
|
| 18 |
+
--ckpt_every_n_step=2000
|
playground/Abbie-h100/torchrun/run_dense_pure_dp.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Below is just a sample for pure cmd line launching.
|
| 2 |
+
# For debug purpose plz refer to launch.json: torch_dense_gargantua
|
| 3 |
+
|
| 4 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ARNOLD_WORKER_0_HOST MASTER_PORT=$ARNOLD_WORKER_0_PORT torchrun \
|
| 5 |
+
--node_rank=$ARNOLD_ID --nproc_per_node=4 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$ARNOLD_WORKER_0_PORT \
|
| 6 |
+
/opt/tiger/Abbie/trainer/dense_trainer.py \
|
| 7 |
+
--model=1b2.yaml \
|
| 8 |
+
--trial_name=abbie_dense_1b2_1T_gbs128_gargantua_nopp_ckpt_UT1_b1 \
|
| 9 |
+
--train_home_path=hdfs://harunava/home/byte_tteng_llm/users/yuyifeng.oscar/pretrain \
|
| 10 |
+
--train_dataset=hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train \
|
| 11 |
+
--train_size=1000000000000 \
|
| 12 |
+
--tokenizer=hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227 \
|
| 13 |
+
--pad_idx=1 --vocab_size=136064 \
|
| 14 |
+
--global_batch_size=128 --micro_batch_size=1 --warmup_batch_ratio=0.005 \
|
| 15 |
+
--max_seq_len=4096 --max_position_embeddings=4096 --stride=3840 \
|
| 16 |
+
--lr_max=5e-4 --lr_min=5e-5 --lr_weight_decay=0.1 \
|
| 17 |
+
--ckpt_every_n_step=2000
|
playground/Abbie-h100/torchrun/run_moe_pp.sh
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ANORLD_WORKER_0_HOST MASTER_PORT=$PORT0 torchrun --node_rank=0 --nproc_per_node=8 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$PORT0 /opt/tiger/Abbie/torchrun/torchrun_dualpipe_moe_v.py
|
playground/Abbie-h100/torchrun/run_moe_pure_dp.sh
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
NCCL_DEBUG=WARN MASTER_ADDR=$ANORLD_WORKER_0_HOST MASTER_PORT=$PORT0 torchrun --node_rank=0 --nproc_per_node=8 --nnodes=1 --rdzv_endpoint=$ARNOLD_WORKER_0_HOST:$PORT0 /opt/tiger/Abbie/torchrun/torchrun_moe_gargantua.py
|
playground/Abbie-h100/torchrun/torch_sanity.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
if __name__ == "__main__":
|
| 5 |
+
rank = int(os.environ['RANK'])
|
| 6 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 7 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 8 |
+
visible_devices = os.environ['CUDA_VISIBLE_DEVICES']
|
| 9 |
+
print(f"[SANITY] rank: {rank}, local_rank: {local_rank}, world_size: {world_size}, visible_device: {visible_devices}")
|
| 10 |
+
device = torch.device('cuda', local_rank)
|
| 11 |
+
torch.distributed.init_process_group(backend='nccl', init_method="env://", world_size=world_size, rank=rank, device_id=device)
|
| 12 |
+
group = torch.distributed.distributed_c10d._get_default_group()
|
| 13 |
+
group.barrier()
|
| 14 |
+
print("[SANITY] exiting ..")
|
playground/Abbie-h100/torchrun/torchrun_dense_gargantua_ckpt.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from contextlib import nullcontext
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed as dist
|
| 10 |
+
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from dualpipe.log import WandbLogger
|
| 13 |
+
from dualpipe.deterministic import set_deterministic
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from dualpipe.module.shared.loss import preprocess_labels
|
| 18 |
+
|
| 19 |
+
set_deterministic(42, False)
|
| 20 |
+
|
| 21 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 22 |
+
from dualpipe.module.trainer_builder import build_dense_trainer, build_dense_dataloader_only
|
| 23 |
+
|
| 24 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 25 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 26 |
+
|
| 27 |
+
torch.manual_seed(42)
|
| 28 |
+
np.random.seed(42)
|
| 29 |
+
|
| 30 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/Abbie/profiles'
|
| 31 |
+
|
| 32 |
+
def make_handler(rank, local_dir):
|
| 33 |
+
def handler_fn(p):
|
| 34 |
+
# export trace data when traces ready (schedule cycle ends)
|
| 35 |
+
fname = "profileStep" + str(p.step_num) + "_globalStep" + str(0) + "_rank" + str(rank) + "." + \
|
| 36 |
+
str(int(time.time())) + ".pt.trace.json.gz"
|
| 37 |
+
local_file = os.path.join(local_dir, fname)
|
| 38 |
+
if not os.path.exists(local_dir):
|
| 39 |
+
print("mkdir ", local_dir)
|
| 40 |
+
os.makedirs(local_dir)
|
| 41 |
+
print("Save profile results to {}".format(local_file))
|
| 42 |
+
p.export_chrome_trace(local_file)
|
| 43 |
+
print("Local profile file saved")
|
| 44 |
+
return handler_fn
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 48 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 49 |
+
scalars = torch.cat(
|
| 50 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 51 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 52 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 53 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 54 |
+
group=dp_group)
|
| 55 |
+
return out_scalars, group_size
|
| 56 |
+
|
| 57 |
+
def do_main(rank, local_rank, world_size,
|
| 58 |
+
pp_size: int = 1,
|
| 59 |
+
vocab_size: int = 136064, hidden_size: int = 4096, inner: int=5504,
|
| 60 |
+
seq_len:int = 4096, max_position_embeddings: int = 4096, stride=3840,
|
| 61 |
+
resume_ckpt_path: Optional[str] = None,
|
| 62 |
+
gbs: int = 128, num_attention_head: int = 64, layer_number: int = 24,
|
| 63 |
+
enable_profiler: bool = False, profiler_step: int = 20, dump_dataloader_step: int= 20):
|
| 64 |
+
epoch = 1
|
| 65 |
+
mbs = 1
|
| 66 |
+
gbs = gbs // world_size
|
| 67 |
+
set_deterministic(42, False)
|
| 68 |
+
|
| 69 |
+
assert world_size % pp_size == 0
|
| 70 |
+
dp_size = world_size // pp_size
|
| 71 |
+
|
| 72 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=world_size, rank=rank)
|
| 73 |
+
|
| 74 |
+
device = f'cuda:{local_rank}'
|
| 75 |
+
dtype = torch.bfloat16
|
| 76 |
+
|
| 77 |
+
db_logger = WandbLogger(rank, None, 'abbie_dense_1b2_1T_gbs128_gargantua_nopp_ckpt_UT1_b1_ckpt20')
|
| 78 |
+
group = dist.distributed_c10d._get_default_group()
|
| 79 |
+
world_size = group.size()
|
| 80 |
+
|
| 81 |
+
rank_generator, layer, train_dataloader, optimizers = build_dense_trainer(
|
| 82 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 83 |
+
epoch_number=epoch,
|
| 84 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 85 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 86 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 87 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 88 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 89 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 90 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 91 |
+
dp_size=dp_size, pp_size=pp_size,
|
| 92 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size, num_attention_head=num_attention_head, inner=inner,
|
| 93 |
+
is_deterministic=True,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
losses = []
|
| 97 |
+
total_step = 0
|
| 98 |
+
profiler_end_step = profiler_step + 10
|
| 99 |
+
if enable_profiler > 0:
|
| 100 |
+
prof = torch.profiler.profile(
|
| 101 |
+
schedule=torch.profiler.schedule(wait=profiler_step, warmup=2, active=1, repeat=0),
|
| 102 |
+
on_trace_ready=make_handler(rank, _DEFAULT_LOCAL_DIR),
|
| 103 |
+
record_shapes=True,
|
| 104 |
+
profile_memory=True,
|
| 105 |
+
with_modules=True,
|
| 106 |
+
with_stack=int(torch.__version__[0])>=2)
|
| 107 |
+
else:
|
| 108 |
+
prof = nullcontext()
|
| 109 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 110 |
+
with prof:
|
| 111 |
+
for i in range(train_dataloader.length):
|
| 112 |
+
#for batches in train_dataloader_iter:
|
| 113 |
+
batches = next(train_dataloader)
|
| 114 |
+
start_time = time.perf_counter()
|
| 115 |
+
for batch in batches:
|
| 116 |
+
input_ids = batch['input_ids'].to(device=device)
|
| 117 |
+
cu_seqlen = batch['host_seqlens'].to(device=device)
|
| 118 |
+
word_idx = batch['word_idx'].to(device=device)
|
| 119 |
+
labels = batch['labels'].to(device=device)
|
| 120 |
+
loss_mask = batch['rmpad_loss_mask'].to(device=device)
|
| 121 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 122 |
+
input_ids = input_ids[word_idx]
|
| 123 |
+
input_ids = input_ids.unsqueeze(0)
|
| 124 |
+
labels = labels.view(-1)[word_idx]
|
| 125 |
+
labels = labels.unsqueeze(0)
|
| 126 |
+
loss_mask[labels == 1] = 0
|
| 127 |
+
total_s = cu_seqlen[-1].item()
|
| 128 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen)
|
| 129 |
+
shift_labels.requires_grad = False
|
| 130 |
+
|
| 131 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 132 |
+
#res = layer.forward(input_id, cu_seqlen, total_s)
|
| 133 |
+
res = layer.forward(input_ids)
|
| 134 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 135 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 136 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 137 |
+
losses.append(loss_mean.detach().clone())
|
| 138 |
+
loss = loss_mean / (gbs)
|
| 139 |
+
loss.backward()
|
| 140 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 141 |
+
loss_report = sum(losses) / len(losses)
|
| 142 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 143 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 144 |
+
losses = []
|
| 145 |
+
seen_token = (total_step * seq_len * mbs * gbs * world_size) / 1024.0 / 1024.0 # In M
|
| 146 |
+
optimizers.step()
|
| 147 |
+
end_time = time.perf_counter()
|
| 148 |
+
if rank == 0 and total_step % 1 == 0:
|
| 149 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 150 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 151 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 152 |
+
total_step += 1
|
| 153 |
+
|
| 154 |
+
if dump_dataloader_step is not None and total_step == dump_dataloader_step:
|
| 155 |
+
res = train_dataloader.__getstate__()
|
| 156 |
+
break
|
| 157 |
+
|
| 158 |
+
if enable_profiler:
|
| 159 |
+
if total_step == profiler_end_step:
|
| 160 |
+
print("Ending profiler")
|
| 161 |
+
prof.stop()
|
| 162 |
+
if total_step < profiler_end_step:
|
| 163 |
+
prof.step()
|
| 164 |
+
|
| 165 |
+
train_dataloader.terminate()
|
| 166 |
+
|
| 167 |
+
train_dataloader_2 = build_dense_dataloader_only(
|
| 168 |
+
rank_generator, local_rank=local_rank,
|
| 169 |
+
epoch_number=epoch,
|
| 170 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 171 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 172 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 173 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 174 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 175 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 176 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 177 |
+
dp_size=dp_size, pp_size=pp_size,
|
| 178 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size, num_attention_head=num_attention_head, inner=inner,
|
| 179 |
+
is_deterministic=True,
|
| 180 |
+
#ckpt_callback=moe_dualpipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device),
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
train_dataloader_2.__setstate__(res)
|
| 184 |
+
train_dataloader_iter_2 = iter(train_dataloader_2)
|
| 185 |
+
|
| 186 |
+
with prof:
|
| 187 |
+
for i in range(train_dataloader.length - total_step):
|
| 188 |
+
#for batches in train_dataloader_iter:
|
| 189 |
+
batches = next(train_dataloader_2)
|
| 190 |
+
start_time = time.perf_counter()
|
| 191 |
+
for batch in batches:
|
| 192 |
+
input_ids = batch['input_ids'].to(device=device)
|
| 193 |
+
cu_seqlen = batch['host_seqlens'].to(device=device)
|
| 194 |
+
word_idx = batch['word_idx'].to(device=device)
|
| 195 |
+
labels = batch['labels'].to(device=device)
|
| 196 |
+
loss_mask = batch['rmpad_loss_mask'].to(device=device)
|
| 197 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 198 |
+
input_ids = input_ids[word_idx]
|
| 199 |
+
input_ids = input_ids.unsqueeze(0)
|
| 200 |
+
labels = labels.view(-1)[word_idx]
|
| 201 |
+
labels = labels.unsqueeze(0)
|
| 202 |
+
loss_mask[labels == 1] = 0
|
| 203 |
+
total_s = cu_seqlen[-1].item()
|
| 204 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen)
|
| 205 |
+
shift_labels.requires_grad = False
|
| 206 |
+
|
| 207 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 208 |
+
#res = layer.forward(input_id, cu_seqlen, total_s)
|
| 209 |
+
res = layer.forward(input_ids)
|
| 210 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 211 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 212 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 213 |
+
losses.append(loss_mean.detach().clone())
|
| 214 |
+
loss = loss_mean / (gbs)
|
| 215 |
+
loss.backward()
|
| 216 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 217 |
+
loss_report = sum(losses) / len(losses)
|
| 218 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 219 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 220 |
+
losses = []
|
| 221 |
+
seen_token = (total_step * seq_len * mbs * gbs * world_size) / 1024.0 / 1024.0 # In M
|
| 222 |
+
optimizers.step()
|
| 223 |
+
end_time = time.perf_counter()
|
| 224 |
+
if rank == 0 and total_step % 1 == 0:
|
| 225 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 226 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 227 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 228 |
+
total_step += 1
|
| 229 |
+
|
| 230 |
+
if enable_profiler:
|
| 231 |
+
if total_step == profiler_end_step:
|
| 232 |
+
print("Ending profiler")
|
| 233 |
+
prof.stop()
|
| 234 |
+
if total_step < profiler_end_step:
|
| 235 |
+
prof.step()
|
| 236 |
+
|
| 237 |
+
print("All done")
|
| 238 |
+
|
| 239 |
+
def test_cross_node(ngpus):
|
| 240 |
+
torch.multiprocessing.spawn(do_main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 241 |
+
|
| 242 |
+
def main():
|
| 243 |
+
do_main()
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
rank = int(os.environ['RANK'])
|
| 247 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 248 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 249 |
+
print(f"[INIT] rank: {rank} local_rank: {local_rank} world_size: {world_size}")
|
| 250 |
+
do_main(rank, local_rank, world_size)
|
playground/Abbie-h100/torchrun/torchrun_dualpipe_moe_v.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from contextlib import nullcontext
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
from einops import rearrange
|
| 10 |
+
|
| 11 |
+
from dualpipe.module.shared.loss import criterion
|
| 12 |
+
from dualpipe.log import WandbLogger
|
| 13 |
+
from dualpipe.module.trainer_builder import build_moe_trainer, build_moe_dataloader_only
|
| 14 |
+
|
| 15 |
+
#set_deterministic(42,False)
|
| 16 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/Abbie/profiles'
|
| 17 |
+
|
| 18 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 19 |
+
|
| 20 |
+
INITIALIZE_RANGE = 0.013975424859373685
|
| 21 |
+
|
| 22 |
+
def make_handler(rank, local_dir):
|
| 23 |
+
def handler_fn(p):
|
| 24 |
+
# export trace data when traces ready (schedule cycle ends)
|
| 25 |
+
fname = "profileStep" + str(p.step_num) + "_globalStep" + str(0) + "_rank" + str(rank) + "." + \
|
| 26 |
+
str(int(time.time())) + ".pt.trace.json.gz"
|
| 27 |
+
local_file = os.path.join(local_dir, fname)
|
| 28 |
+
if not os.path.exists(local_dir):
|
| 29 |
+
print("mkdir ", local_dir)
|
| 30 |
+
os.makedirs(local_dir)
|
| 31 |
+
print("Save profile results to {}".format(local_file))
|
| 32 |
+
p.export_chrome_trace(local_file)
|
| 33 |
+
print("Local profile file saved")
|
| 34 |
+
return handler_fn
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 38 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 39 |
+
scalars = torch.cat(
|
| 40 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 41 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 42 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 43 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 44 |
+
group=dp_group)
|
| 45 |
+
return out_scalars, group_size
|
| 46 |
+
|
| 47 |
+
def main(rank, local_rank, ngpus, expert_num: int = 32, ep_size: int = 4, pp_size: int = 2, expert_size: int = 2752, top_k=4,
|
| 48 |
+
vocab_size: int = 136064, hidden_size: int = 2048, max_position_embeddings: int = 4096, stride: int=3840,
|
| 49 |
+
num_attention_head: int = 16, micro_batch_size: int=1, num_chunks: int=32, layer_number: int=24, seq_len: int = 4096,
|
| 50 |
+
resume_ckpt_path: Optional[str] = None,
|
| 51 |
+
enable_profiler: bool = False, profiler_step: int = 20, mem_profile_enable: bool= True, dump_dataloader_step: Optional[int] = None):
|
| 52 |
+
epoch = 1
|
| 53 |
+
mbs = 1
|
| 54 |
+
dp_size = ngpus // pp_size
|
| 55 |
+
torch.cuda.set_device(local_rank)
|
| 56 |
+
#torch.manual_seed(42)
|
| 57 |
+
|
| 58 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 59 |
+
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
|
| 60 |
+
device = f'cuda:{rank}'
|
| 61 |
+
dtype = torch.bfloat16
|
| 62 |
+
|
| 63 |
+
db_logger = WandbLogger(rank, None, 'abbie_moe_1T_gbs128_dualpipe_ckpt_UT1_baseline')
|
| 64 |
+
|
| 65 |
+
# Communication group
|
| 66 |
+
group = dist.distributed_c10d._get_default_group()
|
| 67 |
+
world_size = group.size()
|
| 68 |
+
# real gbs is divided by dq_size
|
| 69 |
+
gbs = 128 // dp_size
|
| 70 |
+
if mem_profile_enable:
|
| 71 |
+
torch.cuda.memory._record_memory_history()
|
| 72 |
+
|
| 73 |
+
rank_generator, dualpipev_model, train_dataloader, optimizers = build_moe_trainer(
|
| 74 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 75 |
+
epoch_number=epoch,
|
| 76 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 77 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 78 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 79 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 80 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 81 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 82 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 83 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 84 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size,
|
| 85 |
+
num_attention_head=num_attention_head,
|
| 86 |
+
expert_size=expert_size, expert_num=expert_num, top_k=top_k,
|
| 87 |
+
is_deterministic=False,
|
| 88 |
+
#ckpt_callback=moe_dualpipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
#optim, scheduler = build_optimizer_and_scheduler(rank, ddp_module)
|
| 92 |
+
print(f'[Rank-{rank}] INFO pp_rank: {rank_generator.get_pp_rank()} dp_rank: {rank_generator.get_dp_rank()} ep_rank: {rank_generator.get_ep_rank()}')
|
| 93 |
+
if rank_generator.is_first_rank():
|
| 94 |
+
print(f"[Rank-{rank}] I am the first rank among {ngpus=}, {expert_num=}, {ep_size=}, {hidden_size=}, {num_attention_head=}", flush=True)
|
| 95 |
+
|
| 96 |
+
total_step = 0
|
| 97 |
+
profiler_end_step = profiler_step + 10
|
| 98 |
+
if enable_profiler > 0:
|
| 99 |
+
prof = torch.profiler.profile(
|
| 100 |
+
schedule=torch.profiler.schedule(wait=profiler_step, warmup=2, active=1, repeat=0),
|
| 101 |
+
on_trace_ready=make_handler(rank, _DEFAULT_LOCAL_DIR),
|
| 102 |
+
record_shapes=True,
|
| 103 |
+
profile_memory=True,
|
| 104 |
+
with_modules=True,
|
| 105 |
+
with_stack=int(torch.__version__[0])>=2)
|
| 106 |
+
else:
|
| 107 |
+
prof = nullcontext()
|
| 108 |
+
|
| 109 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 110 |
+
with prof:
|
| 111 |
+
for batches in train_dataloader_iter:
|
| 112 |
+
losses = []
|
| 113 |
+
input_ids_arr = []
|
| 114 |
+
cu_seqlens_arr = []
|
| 115 |
+
inp_shapes_arr = []
|
| 116 |
+
total_ses_arr = []
|
| 117 |
+
labels_arr = []
|
| 118 |
+
loss_mask_arr = []
|
| 119 |
+
for b in batches:
|
| 120 |
+
# Commonly used by input_ids and labels.
|
| 121 |
+
word_idx = b['word_idx'].to(device=device)
|
| 122 |
+
|
| 123 |
+
# process input_ids
|
| 124 |
+
input_ids = b['input_ids'].to(device=device)
|
| 125 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 126 |
+
input_ids = input_ids[word_idx]
|
| 127 |
+
input_ids = input_ids.unsqueeze(0)
|
| 128 |
+
input_ids_arr.append(input_ids)# Appending
|
| 129 |
+
|
| 130 |
+
# process cu_seqlens & total_s
|
| 131 |
+
cu_seqlens = b['host_seqlens'].to(device=device)
|
| 132 |
+
cu_seqlens_arr.append(cu_seqlens)
|
| 133 |
+
total_s = cu_seqlens[-1].item()
|
| 134 |
+
total_ses_arr.append(total_s)
|
| 135 |
+
|
| 136 |
+
# process labels
|
| 137 |
+
labels = b['labels'].to(device=device)
|
| 138 |
+
labels = labels.view(-1)[word_idx]
|
| 139 |
+
labels = labels.unsqueeze(0)
|
| 140 |
+
labels_arr.append(labels)
|
| 141 |
+
|
| 142 |
+
# process loss_mask
|
| 143 |
+
loss_mask = b['rmpad_loss_mask'].to(device=device)
|
| 144 |
+
loss_mask[labels == 1] = 0
|
| 145 |
+
loss_mask_arr.append(loss_mask)
|
| 146 |
+
|
| 147 |
+
# input shapes.
|
| 148 |
+
inp_shape = (total_s, micro_batch_size, hidden_size)
|
| 149 |
+
inp_shapes_arr.append(inp_shape)
|
| 150 |
+
|
| 151 |
+
if not rank_generator.is_first_rank():
|
| 152 |
+
hidden_states = [None for _ in range(num_chunks)]
|
| 153 |
+
else:
|
| 154 |
+
hidden_states = input_ids_arr
|
| 155 |
+
input_ctx = [(c, t, gbs) for c, t in zip(cu_seqlens_arr, total_ses_arr)]
|
| 156 |
+
start_time = time.perf_counter()
|
| 157 |
+
loss, outputs = dualpipev_model.step(hidden_states, input_shapes=inp_shapes_arr, input_ctx=input_ctx, num_chunks=num_chunks, criterion=criterion, labels=labels_arr, return_outputs=False)
|
| 158 |
+
end_time = time.perf_counter()
|
| 159 |
+
if rank_generator.is_first_rank():
|
| 160 |
+
losses.append(loss)
|
| 161 |
+
#res = layer.forward(input_ids)
|
| 162 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 163 |
+
if rank_generator.get_pp_rank() == 0:
|
| 164 |
+
losses = torch.cat(losses) * gbs
|
| 165 |
+
loss_report = sum(losses) / len(losses)
|
| 166 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 167 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 168 |
+
seen_token = (total_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 169 |
+
optimizers.step()
|
| 170 |
+
#dense_optim.step()
|
| 171 |
+
#moe_optim.step()
|
| 172 |
+
if rank == 0 and total_step % 1 == 0:
|
| 173 |
+
#caliberated_grad_norm = math.sqrt(dense_optim.grad_norm**2 + moe_optim.grad_norm**2)
|
| 174 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 175 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 176 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 177 |
+
total_step += 1
|
| 178 |
+
if dump_dataloader_step is not None and total_step == dump_dataloader_step:
|
| 179 |
+
res = train_dataloader.__getstate__()
|
| 180 |
+
break
|
| 181 |
+
if enable_profiler:
|
| 182 |
+
if total_step == profiler_end_step:
|
| 183 |
+
print("Ending profiler")
|
| 184 |
+
prof.stop()
|
| 185 |
+
if total_step < profiler_end_step:
|
| 186 |
+
prof.step()
|
| 187 |
+
|
| 188 |
+
train_dataloader.terminate()
|
| 189 |
+
print(f"[{rank}] {loss}")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
rank = int(os.environ['RANK'])
|
| 194 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 195 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 196 |
+
main(rank, local_rank, world_size)
|
playground/Abbie-h100/torchrun/torchrun_dualpipe_moe_v_ckpt.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from contextlib import nullcontext
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
from einops import rearrange
|
| 10 |
+
|
| 11 |
+
from transformers import AutoTokenizer
|
| 12 |
+
from dualpipe.module.shared.loss import criterion
|
| 13 |
+
from dualpipe.module.config import GargantuaConfig, OptimizerConfig
|
| 14 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 15 |
+
from dualpipe.module.parallel_states import build_rank_generator, get_dist_env, DistEnv, RankGenerator
|
| 16 |
+
from dualpipe.module.shared.vocab import initialize_kernel
|
| 17 |
+
from dualpipe.module.shared.optimizer import MixPrecisionDDPOptimizer
|
| 18 |
+
from dualpipe.communicator import Communicator
|
| 19 |
+
from dualpipe import DualPipeTrainMoeV
|
| 20 |
+
from dualpipe.deterministic import set_deterministic
|
| 21 |
+
from dualpipe.log import WandbLogger
|
| 22 |
+
from dataloader.config import TrainerConfig
|
| 23 |
+
from dataloader.unsupervised import SaharaDatamodule
|
| 24 |
+
from dualpipe.module.trainer_builder import build_moe_trainer, build_moe_dataloader_only
|
| 25 |
+
|
| 26 |
+
#set_deterministic(42,False)
|
| 27 |
+
_DEFAULT_LOCAL_DIR = '/opt/tiger/Abbie/profiles'
|
| 28 |
+
|
| 29 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 30 |
+
|
| 31 |
+
INITIALIZE_RANGE = 0.013975424859373685
|
| 32 |
+
|
| 33 |
+
def make_handler(rank, local_dir):
|
| 34 |
+
def handler_fn(p):
|
| 35 |
+
# export trace data when traces ready (schedule cycle ends)
|
| 36 |
+
fname = "profileStep" + str(p.step_num) + "_globalStep" + str(0) + "_rank" + str(rank) + "." + \
|
| 37 |
+
str(int(time.time())) + ".pt.trace.json.gz"
|
| 38 |
+
local_file = os.path.join(local_dir, fname)
|
| 39 |
+
if not os.path.exists(local_dir):
|
| 40 |
+
print("mkdir ", local_dir)
|
| 41 |
+
os.makedirs(local_dir)
|
| 42 |
+
print("Save profile results to {}".format(local_file))
|
| 43 |
+
p.export_chrome_trace(local_file)
|
| 44 |
+
print("Local profile file saved")
|
| 45 |
+
return handler_fn
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 49 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 50 |
+
scalars = torch.cat(
|
| 51 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 52 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 53 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 54 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 55 |
+
group=dp_group)
|
| 56 |
+
return out_scalars, group_size
|
| 57 |
+
|
| 58 |
+
def main(rank, local_rank, ngpus, expert_num: int = 32, ep_size: int = 4, pp_size: int = 2, expert_size: int = 2752, top_k=4,
|
| 59 |
+
vocab_size: int = 136064, hidden_size: int = 2048, max_position_embeddings: int = 4096, stride: int=3840,
|
| 60 |
+
num_attention_head: int = 16, micro_batch_size: int=1, num_chunks: int=32, layer_number: int=24, seq_len: int = 4096,
|
| 61 |
+
resume_ckpt_path: Optional[str] = None,
|
| 62 |
+
enable_profiler: bool = False, profiler_step: int = 20, mem_profile_enable: bool= True, dump_dataloader_step: int= 10):
|
| 63 |
+
epoch = 1
|
| 64 |
+
mbs = 1
|
| 65 |
+
dp_size = ngpus // pp_size
|
| 66 |
+
torch.cuda.set_device(rank)
|
| 67 |
+
local_experts = (expert_num // ep_size)
|
| 68 |
+
torch.manual_seed(42)
|
| 69 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 70 |
+
initialize_kernel()
|
| 71 |
+
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
|
| 72 |
+
device = f'cuda:{rank}'
|
| 73 |
+
dtype = torch.bfloat16
|
| 74 |
+
|
| 75 |
+
db_logger = WandbLogger(rank, None, 'abbie_moe_1T_gbs128_dualpipe_ckpt_UT1_baseline')
|
| 76 |
+
|
| 77 |
+
# Communication group
|
| 78 |
+
group = dist.distributed_c10d._get_default_group()
|
| 79 |
+
world_size = group.size()
|
| 80 |
+
# real gbs is divided by dq_size
|
| 81 |
+
gbs = 128 // dp_size
|
| 82 |
+
if mem_profile_enable:
|
| 83 |
+
torch.cuda.memory._record_memory_history()
|
| 84 |
+
|
| 85 |
+
rank_generator, dualpipev_model, train_dataloader, optimizers = build_moe_trainer(
|
| 86 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 87 |
+
epoch_number=epoch,
|
| 88 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 89 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 90 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 91 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 92 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 93 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 94 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 95 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 96 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size,
|
| 97 |
+
num_attention_head=num_attention_head,
|
| 98 |
+
expert_size=expert_size, expert_num=expert_num, top_k=top_k,
|
| 99 |
+
is_deterministic=False,
|
| 100 |
+
#ckpt_callback=moe_dualpipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device),
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
#optim, scheduler = build_optimizer_and_scheduler(rank, ddp_module)
|
| 104 |
+
print(f'[Rank-{rank}] INFO pp_rank: {rank_generator.get_pp_rank()} dp_rank: {rank_generator.get_dp_rank()} ep_rank: {rank_generator.get_ep_rank()}')
|
| 105 |
+
if rank_generator.is_first_rank():
|
| 106 |
+
print(f"[Rank-{rank}] I am the first rank among {ngpus=}, {expert_num=}, {ep_size=}, {hidden_size=}, {num_attention_head=}", flush=True)
|
| 107 |
+
|
| 108 |
+
total_step = 0
|
| 109 |
+
profiler_end_step = profiler_step + 10
|
| 110 |
+
if enable_profiler > 0:
|
| 111 |
+
prof = torch.profiler.profile(
|
| 112 |
+
schedule=torch.profiler.schedule(wait=profiler_step, warmup=2, active=1, repeat=0),
|
| 113 |
+
on_trace_ready=make_handler(rank, _DEFAULT_LOCAL_DIR),
|
| 114 |
+
record_shapes=True,
|
| 115 |
+
profile_memory=True,
|
| 116 |
+
with_modules=True,
|
| 117 |
+
with_stack=int(torch.__version__[0])>=2)
|
| 118 |
+
else:
|
| 119 |
+
prof = nullcontext()
|
| 120 |
+
|
| 121 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 122 |
+
with prof:
|
| 123 |
+
for batches in train_dataloader_iter:
|
| 124 |
+
losses = []
|
| 125 |
+
input_ids_arr = []
|
| 126 |
+
cu_seqlens_arr = []
|
| 127 |
+
inp_shapes_arr = []
|
| 128 |
+
total_ses_arr = []
|
| 129 |
+
labels_arr = []
|
| 130 |
+
loss_mask_arr = []
|
| 131 |
+
for b in batches:
|
| 132 |
+
# Commonly used by input_ids and labels.
|
| 133 |
+
word_idx = b['word_idx'].to(device=device)
|
| 134 |
+
|
| 135 |
+
# process input_ids
|
| 136 |
+
input_ids = b['input_ids'].to(device=device)
|
| 137 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 138 |
+
input_ids = input_ids[word_idx]
|
| 139 |
+
input_ids = input_ids.unsqueeze(0)
|
| 140 |
+
input_ids_arr.append(input_ids)# Appending
|
| 141 |
+
|
| 142 |
+
# process cu_seqlens & total_s
|
| 143 |
+
cu_seqlens = b['host_seqlens'].to(device=device)
|
| 144 |
+
cu_seqlens_arr.append(cu_seqlens)
|
| 145 |
+
total_s = cu_seqlens[-1].item()
|
| 146 |
+
total_ses_arr.append(total_s)
|
| 147 |
+
|
| 148 |
+
# process labels
|
| 149 |
+
labels = b['labels'].to(device=device)
|
| 150 |
+
labels = labels.view(-1)[word_idx]
|
| 151 |
+
labels = labels.unsqueeze(0)
|
| 152 |
+
labels_arr.append(labels)
|
| 153 |
+
|
| 154 |
+
# process loss_mask
|
| 155 |
+
loss_mask = b['rmpad_loss_mask'].to(device=device)
|
| 156 |
+
loss_mask[labels == 1] = 0
|
| 157 |
+
loss_mask_arr.append(loss_mask)
|
| 158 |
+
|
| 159 |
+
# input shapes.
|
| 160 |
+
inp_shape = (total_s, micro_batch_size, hidden_size)
|
| 161 |
+
inp_shapes_arr.append(inp_shape)
|
| 162 |
+
|
| 163 |
+
if not rank_generator.is_first_rank():
|
| 164 |
+
hidden_states = [None for _ in range(num_chunks)]
|
| 165 |
+
else:
|
| 166 |
+
hidden_states = input_ids_arr
|
| 167 |
+
input_ctx = [(c, t, gbs) for c, t in zip(cu_seqlens_arr, total_ses_arr)]
|
| 168 |
+
start_time = time.perf_counter()
|
| 169 |
+
loss, outputs = dualpipev_model.step(hidden_states, input_shapes=inp_shapes_arr, input_ctx=input_ctx, num_chunks=num_chunks, criterion=criterion, labels=labels_arr, return_outputs=False)
|
| 170 |
+
end_time = time.perf_counter()
|
| 171 |
+
if rank_generator.is_first_rank():
|
| 172 |
+
losses.append(loss)
|
| 173 |
+
#res = layer.forward(input_ids)
|
| 174 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 175 |
+
if rank_generator.get_pp_rank() == 0:
|
| 176 |
+
losses = torch.cat(losses) * gbs
|
| 177 |
+
loss_report = sum(losses) / len(losses)
|
| 178 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 179 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 180 |
+
seen_token = (total_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 181 |
+
optimizers.step()
|
| 182 |
+
#dense_optim.step()
|
| 183 |
+
#moe_optim.step()
|
| 184 |
+
if rank == 0 and total_step % 1 == 0:
|
| 185 |
+
#caliberated_grad_norm = math.sqrt(dense_optim.grad_norm**2 + moe_optim.grad_norm**2)
|
| 186 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 187 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 188 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 189 |
+
total_step += 1
|
| 190 |
+
if total_step == dump_dataloader_step:
|
| 191 |
+
res = train_dataloader.__getstate__()
|
| 192 |
+
break
|
| 193 |
+
if enable_profiler:
|
| 194 |
+
if total_step == profiler_end_step:
|
| 195 |
+
print("Ending profiler")
|
| 196 |
+
prof.stop()
|
| 197 |
+
if total_step < profiler_end_step:
|
| 198 |
+
prof.step()
|
| 199 |
+
|
| 200 |
+
train_dataloader.terminate()
|
| 201 |
+
|
| 202 |
+
train_dataloader_2 = build_moe_dataloader_only(
|
| 203 |
+
rank_generator, local_rank=local_rank,
|
| 204 |
+
epoch_number=epoch,
|
| 205 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 206 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 207 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 208 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 209 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 210 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 211 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 212 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 213 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size,
|
| 214 |
+
num_attention_head=num_attention_head,
|
| 215 |
+
expert_size=expert_size, expert_num=expert_num, top_k=top_k,
|
| 216 |
+
is_deterministic=False,
|
| 217 |
+
#ckpt_callback=moe_dualpipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
train_dataloader_2.__setstate__(res)
|
| 221 |
+
train_dataloader_iter2 = iter(train_dataloader_2)
|
| 222 |
+
with prof:
|
| 223 |
+
for batches in train_dataloader_iter2:
|
| 224 |
+
losses = []
|
| 225 |
+
input_ids_arr = []
|
| 226 |
+
cu_seqlens_arr = []
|
| 227 |
+
inp_shapes_arr = []
|
| 228 |
+
total_ses_arr = []
|
| 229 |
+
labels_arr = []
|
| 230 |
+
loss_mask_arr = []
|
| 231 |
+
for b in batches:
|
| 232 |
+
# Commonly used by input_ids and labels.
|
| 233 |
+
word_idx = b['word_idx'].to(device=device)
|
| 234 |
+
|
| 235 |
+
# process input_ids
|
| 236 |
+
input_ids = b['input_ids'].to(device=device)
|
| 237 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 238 |
+
input_ids = input_ids[word_idx]
|
| 239 |
+
input_ids = input_ids.unsqueeze(0)
|
| 240 |
+
input_ids_arr.append(input_ids)# Appending
|
| 241 |
+
|
| 242 |
+
# process cu_seqlens & total_s
|
| 243 |
+
cu_seqlens = b['host_seqlens'].to(device=device)
|
| 244 |
+
cu_seqlens_arr.append(cu_seqlens)
|
| 245 |
+
total_s = cu_seqlens[-1].item()
|
| 246 |
+
total_ses_arr.append(total_s)
|
| 247 |
+
|
| 248 |
+
# process labels
|
| 249 |
+
labels = b['labels'].to(device=device)
|
| 250 |
+
labels = labels.view(-1)[word_idx]
|
| 251 |
+
labels = labels.unsqueeze(0)
|
| 252 |
+
labels_arr.append(labels)
|
| 253 |
+
|
| 254 |
+
# process loss_mask
|
| 255 |
+
loss_mask = b['rmpad_loss_mask'].to(device=device)
|
| 256 |
+
loss_mask[labels == 1] = 0
|
| 257 |
+
loss_mask_arr.append(loss_mask)
|
| 258 |
+
|
| 259 |
+
# input shapes.
|
| 260 |
+
inp_shape = (total_s, micro_batch_size, hidden_size)
|
| 261 |
+
inp_shapes_arr.append(inp_shape)
|
| 262 |
+
|
| 263 |
+
if not rank_generator.is_first_rank():
|
| 264 |
+
hidden_states = [None for _ in range(num_chunks)]
|
| 265 |
+
else:
|
| 266 |
+
hidden_states = input_ids_arr
|
| 267 |
+
input_ctx = [(c, t, gbs) for c, t in zip(cu_seqlens_arr, total_ses_arr)]
|
| 268 |
+
start_time = time.perf_counter()
|
| 269 |
+
loss, outputs = dualpipev_model.step(hidden_states, input_shapes=inp_shapes_arr, input_ctx=input_ctx, num_chunks=num_chunks, criterion=criterion, labels=labels_arr, return_outputs=False)
|
| 270 |
+
end_time = time.perf_counter()
|
| 271 |
+
if rank_generator.is_first_rank():
|
| 272 |
+
losses.append(loss)
|
| 273 |
+
#res = layer.forward(input_ids)
|
| 274 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 275 |
+
if rank_generator.get_pp_rank() == 0:
|
| 276 |
+
losses = torch.cat(losses) * gbs
|
| 277 |
+
loss_report = sum(losses) / len(losses)
|
| 278 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 279 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 280 |
+
seen_token = (total_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 281 |
+
optimizers.step()
|
| 282 |
+
#dense_optim.step()
|
| 283 |
+
#moe_optim.step()
|
| 284 |
+
if rank == 0 and total_step % 1 == 0:
|
| 285 |
+
#caliberated_grad_norm = math.sqrt(dense_optim.grad_norm**2 + moe_optim.grad_norm**2)
|
| 286 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 287 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 288 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 289 |
+
total_step += 1
|
| 290 |
+
if total_step == dump_dataloader_step:
|
| 291 |
+
res = train_dataloader.__getstate__()
|
| 292 |
+
train_dataloader.__setstate__(res)
|
| 293 |
+
break
|
| 294 |
+
if enable_profiler:
|
| 295 |
+
if total_step == profiler_end_step:
|
| 296 |
+
print("Ending profiler")
|
| 297 |
+
prof.stop()
|
| 298 |
+
if total_step < profiler_end_step:
|
| 299 |
+
prof.step()
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
print(f"[{rank}] {loss}")
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
if __name__ == "__main__":
|
| 307 |
+
rank = int(os.environ['RANK'])
|
| 308 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 309 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 310 |
+
main(rank, local_rank, world_size)
|
playground/Abbie-h100/torchrun/torchrun_moe_gargantua.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from dualpipe.log import WandbLogger
|
| 12 |
+
from dualpipe.deterministic import set_deterministic
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from dualpipe.module.shared.loss import preprocess_labels
|
| 17 |
+
|
| 18 |
+
set_deterministic(42, False)
|
| 19 |
+
|
| 20 |
+
from dualpipe.module.parallel_states import build_rank_generator, get_dist_env
|
| 21 |
+
from dualpipe.module.config import GargantuaConfig, OptimizerConfig
|
| 22 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 23 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 24 |
+
from dualpipe.module.shared.optimizer import MixPrecisionDDPOptimizer
|
| 25 |
+
|
| 26 |
+
from dataloader.config import TrainerConfig
|
| 27 |
+
from dataloader.unsupervised import SaharaDatamodule
|
| 28 |
+
|
| 29 |
+
from dualpipe.module.trainer_builder import build_moe_trainer, build_moe_dataloader_only
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 33 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 34 |
+
|
| 35 |
+
torch.manual_seed(42)
|
| 36 |
+
np.random.seed(42)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 40 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 41 |
+
scalars = torch.cat(
|
| 42 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 43 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 44 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 45 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 46 |
+
group=dp_group)
|
| 47 |
+
return out_scalars, group_size
|
| 48 |
+
|
| 49 |
+
def do_main(rank, local_rank, ngpus,
|
| 50 |
+
expert_num: int = 16, ep_size: int = 2, top_k=2, pp_size: int = 1,
|
| 51 |
+
vocab_size: int = 136064, expert_size: int = 640, hidden_size: int = 2048,
|
| 52 |
+
max_position_embeddings: int = 4096, stride=3840,
|
| 53 |
+
resume_ckpt_path: Optional[str] = None,
|
| 54 |
+
gbs: int = 128, num_attention_head: int = 16, layer_number: int = 12, seq_len:int = 4096, dump_dataloader_step: int= 2000):
|
| 55 |
+
epoch = 1
|
| 56 |
+
mbs = 1
|
| 57 |
+
gbs = gbs // ngpus
|
| 58 |
+
set_deterministic(42, False)
|
| 59 |
+
|
| 60 |
+
assert ngpus % pp_size == 0
|
| 61 |
+
dp_size = ngpus // pp_size
|
| 62 |
+
|
| 63 |
+
local_experts = (expert_num // ep_size)
|
| 64 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 65 |
+
#initialize_kernel()
|
| 66 |
+
|
| 67 |
+
device = f'cuda:{rank}'
|
| 68 |
+
dtype = torch.bfloat16
|
| 69 |
+
|
| 70 |
+
db_logger = WandbLogger(rank, None, 'abbie_moe_1T_gbs128_gargantua_nopp_ckpt_UT1_b5_t2')
|
| 71 |
+
group = dist.distributed_c10d._get_default_group()
|
| 72 |
+
world_size = group.size()
|
| 73 |
+
|
| 74 |
+
rank_generator, layer, train_dataloader, optimizers = build_moe_trainer(
|
| 75 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 76 |
+
epoch_number=epoch,
|
| 77 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 78 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 79 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 80 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 81 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 82 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 83 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 84 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 85 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size, num_attention_head=num_attention_head,
|
| 86 |
+
expert_size=expert_size, expert_num=expert_num, top_k=top_k,
|
| 87 |
+
is_deterministic=True,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
losses = []
|
| 91 |
+
total_step = 0
|
| 92 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 93 |
+
for i in range(dump_dataloader_step):
|
| 94 |
+
#for batches in train_dataloader_iter:
|
| 95 |
+
batches = next(train_dataloader)
|
| 96 |
+
start_time = time.perf_counter()
|
| 97 |
+
for batch in batches:
|
| 98 |
+
input_ids = batch['input_ids'].to(device=device)
|
| 99 |
+
cu_seqlen = batch['host_seqlens'].to(device=device)
|
| 100 |
+
word_idx = batch['word_idx'].to(device=device)
|
| 101 |
+
labels = batch['labels'].to(device=device)
|
| 102 |
+
loss_mask = batch['rmpad_loss_mask'].to(device=device)
|
| 103 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 104 |
+
input_ids = input_ids[word_idx]
|
| 105 |
+
input_ids = input_ids.unsqueeze(0)
|
| 106 |
+
labels = labels.view(-1)[word_idx]
|
| 107 |
+
labels = labels.unsqueeze(0)
|
| 108 |
+
loss_mask[labels == 1] = 0
|
| 109 |
+
total_s = cu_seqlen[-1].item()
|
| 110 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen)
|
| 111 |
+
shift_labels.requires_grad = False
|
| 112 |
+
|
| 113 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 114 |
+
#res = layer.forward(input_id, cu_seqlen, total_s)
|
| 115 |
+
res = layer.forward(input_ids)
|
| 116 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 117 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 118 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 119 |
+
losses.append(loss_mean.detach().clone())
|
| 120 |
+
loss = loss_mean / (gbs)
|
| 121 |
+
loss.backward()
|
| 122 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 123 |
+
loss_report = sum(losses) / len(losses)
|
| 124 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 125 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 126 |
+
losses = []
|
| 127 |
+
seen_token = (total_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 128 |
+
optimizers.step()
|
| 129 |
+
end_time = time.perf_counter()
|
| 130 |
+
if rank == 0 and total_step % 1 == 0:
|
| 131 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 132 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 133 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 134 |
+
total_step += 1
|
| 135 |
+
|
| 136 |
+
if total_step == dump_dataloader_step:
|
| 137 |
+
res = train_dataloader.__getstate__()
|
| 138 |
+
|
| 139 |
+
print("All done")
|
| 140 |
+
|
| 141 |
+
def test_cross_node(ngpus):
|
| 142 |
+
torch.multiprocessing.spawn(do_main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 143 |
+
|
| 144 |
+
def main():
|
| 145 |
+
do_main()
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
rank = int(os.environ['RANK'])
|
| 149 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 150 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 151 |
+
do_main(rank, local_rank, world_size)
|
playground/Abbie-h100/torchrun/torchrun_moe_gargantua_ckpt.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.distributed as dist
|
| 9 |
+
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from dualpipe.log import WandbLogger
|
| 12 |
+
from dualpipe.deterministic import set_deterministic
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from dualpipe.module.shared.loss import preprocess_labels
|
| 17 |
+
|
| 18 |
+
set_deterministic(42, False)
|
| 19 |
+
|
| 20 |
+
from dualpipe.module.parallel_states import build_rank_generator, get_dist_env
|
| 21 |
+
from dualpipe.module.config import GargantuaConfig, OptimizerConfig
|
| 22 |
+
from dualpipe.module.gargantua.transformer_layer import TransformerGargantuaLayer
|
| 23 |
+
from dualpipe.module.shared.vocab import vocab_parallel_cross_entropy
|
| 24 |
+
from dualpipe.module.shared.optimizer import MixPrecisionDDPOptimizer
|
| 25 |
+
|
| 26 |
+
from dataloader.config import TrainerConfig
|
| 27 |
+
from dataloader.unsupervised import SaharaDatamodule
|
| 28 |
+
|
| 29 |
+
from dualpipe.module.trainer_builder import build_moe_trainer, build_moe_dataloader_only
|
| 30 |
+
|
| 31 |
+
RANDOM_INPUTS = os.environ.get("RANDOM_INPUTS", "0") == "1"
|
| 32 |
+
TOKENIZER_PATH = '/opt/tiger/tokenizer/bbpe-136k-ml-1227'
|
| 33 |
+
|
| 34 |
+
torch.manual_seed(42)
|
| 35 |
+
np.random.seed(42)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def collect_scalars_across_data_parallel_group(scalars, dp_group):
|
| 39 |
+
"""Reduce a tensor of losses across all GPUs."""
|
| 40 |
+
scalars = torch.cat(
|
| 41 |
+
[loss.clone().detach().view(1) for loss in scalars])
|
| 42 |
+
group_size = torch.distributed.get_world_size(group=dp_group)
|
| 43 |
+
out_scalars = [torch.ones_like(scalars) for i in range(group_size)]
|
| 44 |
+
torch.distributed.all_gather(out_scalars, scalars,
|
| 45 |
+
group=dp_group)
|
| 46 |
+
return out_scalars, group_size
|
| 47 |
+
|
| 48 |
+
def do_main(rank, local_rank, ngpus,
|
| 49 |
+
expert_num: int = 16, dp_size: int= 2, ep_size: int = 2, top_k=2, pp_size: int = 1,
|
| 50 |
+
vocab_size: int = 136064, expert_size: int = 640, hidden_size: int = 2048,
|
| 51 |
+
max_position_embeddings: int = 4096, stride=3840,
|
| 52 |
+
resume_ckpt_path: Optional[str] = None,
|
| 53 |
+
gbs: int = 128, num_attention_head: int = 16, layer_number: int = 12, seq_len:int = 4096, dump_dataloader_step: int= 2000):
|
| 54 |
+
epoch = 1
|
| 55 |
+
mbs = 1
|
| 56 |
+
gbs = gbs // ngpus
|
| 57 |
+
set_deterministic(42, False)
|
| 58 |
+
|
| 59 |
+
local_experts = (expert_num // ep_size)
|
| 60 |
+
dist.init_process_group(backend='nccl', init_method="env://", world_size=ngpus, rank=rank)
|
| 61 |
+
|
| 62 |
+
device = f'cuda:{rank}'
|
| 63 |
+
dtype = torch.bfloat16
|
| 64 |
+
|
| 65 |
+
db_logger = WandbLogger(rank, None, 'abbie_moe_1T_gbs128_gargantua_nopp_ckpt_UT1_b5_t2')
|
| 66 |
+
group = dist.distributed_c10d._get_default_group()
|
| 67 |
+
world_size = group.size()
|
| 68 |
+
|
| 69 |
+
rank_generator, layer, train_dataloader, optimizers = build_moe_trainer(
|
| 70 |
+
rank=rank, local_rank=local_rank, world_size=world_size,
|
| 71 |
+
epoch_number=epoch,
|
| 72 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 73 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 74 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 75 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 76 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 77 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 78 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 79 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 80 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size, num_attention_head=num_attention_head,
|
| 81 |
+
expert_size=expert_size, expert_num=expert_num, top_k=top_k,
|
| 82 |
+
is_deterministic=True,
|
| 83 |
+
#ckpt_callback=moe_nopipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
losses = []
|
| 87 |
+
total_step = 0
|
| 88 |
+
train_dataloader_iter = iter(train_dataloader)
|
| 89 |
+
for i in range(dump_dataloader_step):
|
| 90 |
+
#for batches in train_dataloader_iter:
|
| 91 |
+
batches = next(train_dataloader)
|
| 92 |
+
start_time = time.perf_counter()
|
| 93 |
+
for batch in batches:
|
| 94 |
+
input_ids = batch['input_ids'].to(device=device)
|
| 95 |
+
cu_seqlen = batch['host_seqlens'].to(device=device)
|
| 96 |
+
word_idx = batch['word_idx'].to(device=device)
|
| 97 |
+
labels = batch['labels'].to(device=device)
|
| 98 |
+
loss_mask = batch['rmpad_loss_mask'].to(device=device)
|
| 99 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 100 |
+
input_ids = input_ids[word_idx]
|
| 101 |
+
input_ids = input_ids.unsqueeze(0)
|
| 102 |
+
labels = labels.view(-1)[word_idx]
|
| 103 |
+
labels = labels.unsqueeze(0)
|
| 104 |
+
loss_mask[labels == 1] = 0
|
| 105 |
+
total_s = cu_seqlen[-1].item()
|
| 106 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen)
|
| 107 |
+
shift_labels.requires_grad = False
|
| 108 |
+
|
| 109 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 110 |
+
#res = layer.forward(input_id, cu_seqlen, total_s)
|
| 111 |
+
res = layer.forward(input_ids)
|
| 112 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 113 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 114 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 115 |
+
losses.append(loss_mean.detach().clone())
|
| 116 |
+
loss = loss_mean / (gbs)
|
| 117 |
+
loss.backward()
|
| 118 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 119 |
+
loss_report = sum(losses) / len(losses)
|
| 120 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 121 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 122 |
+
losses = []
|
| 123 |
+
seen_token = (total_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 124 |
+
optimizers.step()
|
| 125 |
+
end_time = time.perf_counter()
|
| 126 |
+
if rank == 0 and total_step % 1 == 0:
|
| 127 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 128 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 129 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 130 |
+
total_step += 1
|
| 131 |
+
|
| 132 |
+
if total_step == dump_dataloader_step:
|
| 133 |
+
res = train_dataloader.__getstate__()
|
| 134 |
+
|
| 135 |
+
train_dataloader.terminate()
|
| 136 |
+
|
| 137 |
+
train_dataloader_2 = build_moe_dataloader_only(
|
| 138 |
+
rank_generator, local_rank=local_rank,
|
| 139 |
+
epoch_number=epoch,
|
| 140 |
+
train_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v3.5_8T_1127_mix34/a6dac3f1/train',
|
| 141 |
+
val_path='hdfs://harunava/home/byte_tteng_llm/data/final_datasets/thoth_v2_2T_0427_with_domain/032e19a9/val',
|
| 142 |
+
train_size=1000000000000, val_size=-1, warmup_step_rate=0.005,
|
| 143 |
+
tokenizer_path='hdfs://harunava/home/byte_tteng_llm/user/thoth/tokenizer/bbpe-136k-ml-1227', pad_idx=1,
|
| 144 |
+
global_batch_size=gbs, micro_batch_size=1,
|
| 145 |
+
max_seqlen=seq_len, max_position_embeddings=max_position_embeddings, stride=stride,
|
| 146 |
+
lr_max=5e-4, lr_min=5e-5, weight_decay=0.1,
|
| 147 |
+
dp_size=dp_size, pp_size=pp_size, ep_size=ep_size,
|
| 148 |
+
layer_number=layer_number, vocab_size=vocab_size, hidden_size=hidden_size,
|
| 149 |
+
num_attention_head=num_attention_head,
|
| 150 |
+
expert_size=expert_size, expert_num=expert_num, top_k=top_k,
|
| 151 |
+
is_deterministic=False,
|
| 152 |
+
#ckpt_callback=moe_dualpipe_ckpt_loading(layer_number, vocab_size, hidden_size, expert_num, expert_size, local_experts, dtype, device),
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
train_dataloader_2.__setstate__(res)
|
| 156 |
+
train_dataloader_iter_2 = iter(train_dataloader_2)
|
| 157 |
+
|
| 158 |
+
for i in range(200000):
|
| 159 |
+
#for batches in train_dataloader_iter_2:
|
| 160 |
+
batches = next(train_dataloader_2)
|
| 161 |
+
start_time = time.perf_counter()
|
| 162 |
+
for batch in batches:
|
| 163 |
+
input_ids = batch['input_ids'].to(device=device)
|
| 164 |
+
cu_seqlen = batch['host_seqlens'].to(device=device)
|
| 165 |
+
word_idx = batch['word_idx'].to(device=device)
|
| 166 |
+
labels = batch['labels'].to(device=device)
|
| 167 |
+
loss_mask = batch['rmpad_loss_mask'].to(device=device)
|
| 168 |
+
input_ids = rearrange(input_ids, 'b s ... -> (b s) ...')
|
| 169 |
+
input_ids = input_ids[word_idx]
|
| 170 |
+
input_ids = input_ids.unsqueeze(0)
|
| 171 |
+
labels = labels.view(-1)[word_idx]
|
| 172 |
+
labels = labels.unsqueeze(0)
|
| 173 |
+
loss_mask[labels == 1] = 0
|
| 174 |
+
total_s = cu_seqlen[-1].item()
|
| 175 |
+
shift_labels = preprocess_labels(labels.squeeze(), cu_seqlen)
|
| 176 |
+
shift_labels.requires_grad = False
|
| 177 |
+
|
| 178 |
+
layer.set_input_ctx((cu_seqlen, total_s))
|
| 179 |
+
#res = layer.forward(input_id, cu_seqlen, total_s)
|
| 180 |
+
res = layer.forward(input_ids)
|
| 181 |
+
loss_arr = vocab_parallel_cross_entropy(res.float(), shift_labels).transpose(0, 1).contiguous()
|
| 182 |
+
loss_mask = loss_mask.view(-1).float().to(loss_arr.device)
|
| 183 |
+
loss_mean = torch.sum(loss_arr.view(-1) * loss_mask) / loss_mask.sum().clamp(min=1)
|
| 184 |
+
losses.append(loss_mean.detach().clone())
|
| 185 |
+
loss = loss_mean / (gbs)
|
| 186 |
+
loss.backward()
|
| 187 |
+
#sample_check_pow2_grad(dict(layer.named_parameters()))
|
| 188 |
+
loss_report = sum(losses) / len(losses)
|
| 189 |
+
gather_objs = collect_scalars_across_data_parallel_group([loss_report], rank_generator.get_dp_group())
|
| 190 |
+
gathered_loss = sum(gather_objs[0]) / dp_size
|
| 191 |
+
losses = []
|
| 192 |
+
seen_token = (total_step * seq_len * mbs * gbs * ngpus) / 1024.0 / 1024.0 # In M
|
| 193 |
+
optimizers.step()
|
| 194 |
+
end_time = time.perf_counter()
|
| 195 |
+
if rank == 0 and total_step % 1 == 0:
|
| 196 |
+
caliberated_grad_norm = optimizers.grad_norm()
|
| 197 |
+
print(f"[Rank-{rank}] epoch step: {total_step} step_time: {(end_time - start_time):.6f} consumed: {seen_token}M tokens Loss: {gathered_loss} grad_norm: {caliberated_grad_norm} lr: {optimizers.get_last_lr()[0]:.3e}")
|
| 198 |
+
db_logger.log_step({'training/loss': gathered_loss})
|
| 199 |
+
total_step += 1
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
print("All done")
|
| 203 |
+
|
| 204 |
+
def test_cross_node(ngpus):
|
| 205 |
+
torch.multiprocessing.spawn(do_main, args=(ngpus,), nprocs=ngpus, daemon=True)
|
| 206 |
+
|
| 207 |
+
def main():
|
| 208 |
+
do_main()
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
rank = int(os.environ['RANK'])
|
| 212 |
+
local_rank = int(os.environ['LOCAL_RANK'])
|
| 213 |
+
world_size = int(os.environ['WORLD_SIZE'])
|
| 214 |
+
do_main(rank, local_rank, world_size)
|
playground/Abbie-h100/trainer_configs/trainer_base.yaml
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
trainer:
|
| 2 |
+
project_name: thoth_abbie_dev
|
| 3 |
+
experiment_name: run-${now:%Y-%m-%d}-${now:%H-%M-%S}
|
| 4 |
+
output_path: runs/${trainer.project_name}/${trainer.experiment_name}
|
| 5 |
+
resume_path: auto
|
| 6 |
+
log_interval: 1
|
| 7 |
+
checkpoint_interval: null
|
| 8 |
+
checkpoint_hf_model: true
|
| 9 |
+
save_final_model: true
|
| 10 |
+
gc_interval: null
|
| 11 |
+
|
| 12 |
+
pp: 1
|
| 13 |
+
ep: 1
|
| 14 |
+
sp: 1
|
| 15 |
+
|
| 16 |
+
seed: 1729
|
| 17 |
+
|
| 18 |
+
deterministic: true
|
| 19 |
+
profile_mode: false
|
| 20 |
+
debug_steps: null
|
| 21 |
+
|
| 22 |
+
data:
|
| 23 |
+
patterns: null
|
| 24 |
+
iterable: false
|
| 25 |
+
max_seq_len: 4096
|
| 26 |
+
|
| 27 |
+
# Regarding training steps
|
| 28 |
+
num_training_steps: null
|
| 29 |
+
num_epoch: 1
|
| 30 |
+
chunks_per_step: ${eval:'${trainer.pp} * 2'}
|
| 31 |
+
|
| 32 |
+
# Batching related
|
| 33 |
+
micro_batch_size: 1
|
| 34 |
+
is_continuous_batch: false
|
| 35 |
+
max_tokens_per_batch: ${data.max_seq_len}
|
| 36 |
+
max_samples_per_batch: 32
|
| 37 |
+
pad_to_multiple_of: ${trainer.sp}
|
| 38 |
+
|
| 39 |
+
# Other data configs
|
| 40 |
+
num_workers: 4
|
| 41 |
+
seed: 52
|
| 42 |
+
shuffle: true
|
| 43 |
+
allow_skip_files: false
|
| 44 |
+
transform_extra_kwargs: null
|
| 45 |
+
|
| 46 |
+
# For continuous batching with map-style
|
| 47 |
+
dataset_meta_paths: null
|
| 48 |
+
|
| 49 |
+
# For using multi-source dataloader
|
| 50 |
+
# (Will be deprecated in favor of multi_source_configs)
|
| 51 |
+
data_source_metas: null
|
| 52 |
+
prefetch: true
|
| 53 |
+
|
| 54 |
+
# For using multiple dataloaders with MultiSourceDataloader
|
| 55 |
+
multi_source_configs: null
|
| 56 |
+
|
| 57 |
+
model:
|
| 58 |
+
template_path: null
|
| 59 |
+
pretrained_path: null
|
| 60 |
+
tokenizer_path: ${model.pretrained_path}
|
| 61 |
+
|
| 62 |
+
max_seq_len: ${data.max_seq_len}
|
| 63 |
+
loss_type: fused_ce_torch
|
| 64 |
+
aux_loss_coef: null
|
| 65 |
+
z_loss_coef: null
|
| 66 |
+
|
| 67 |
+
recompute_norm: true
|
| 68 |
+
recompute_attn_up_proj: true
|
| 69 |
+
recompute_attn_down_proj: true
|
| 70 |
+
recompute_attn: false
|
| 71 |
+
recompute_mlp: true
|
| 72 |
+
recompute_mlp_act: true
|
| 73 |
+
recompute_dispatch: true
|
| 74 |
+
recompute_visual: true
|
| 75 |
+
|
| 76 |
+
activation_offloading: false
|
| 77 |
+
visual_activation_offloading: false
|
| 78 |
+
|
| 79 |
+
token_dispatch_method: all-to-all
|
| 80 |
+
|
| 81 |
+
pp_distributed_dataloading: false
|
| 82 |
+
|
| 83 |
+
decoder_first_pipeline_num_layers: null
|
| 84 |
+
decoder_last_pipeline_num_layers: null
|
| 85 |
+
|
| 86 |
+
freeze_decoder_vocab: false
|
| 87 |
+
freeze_decoder_but_last_n_layers: null
|
| 88 |
+
freeze_visual_encoder: false
|
| 89 |
+
freeze_visual_aligner: false
|
| 90 |
+
|
| 91 |
+
global_attention_interval: null
|
| 92 |
+
local_attention_window: null
|
| 93 |
+
|
| 94 |
+
optim:
|
| 95 |
+
lr: 1e-5
|
| 96 |
+
visual_lr: 2e-6
|
| 97 |
+
lr_warmup_steps_ratio: 0.1
|
| 98 |
+
lr_schedule: cosine
|
| 99 |
+
weight_decay: 0.0
|
| 100 |
+
|
| 101 |
+
adam_beta1: 0.9
|
| 102 |
+
adam_beta2: 0.999
|
| 103 |
+
|
| 104 |
+
disable_optimizer: false
|
| 105 |
+
|
| 106 |
+
hydra:
|
| 107 |
+
run:
|
| 108 |
+
dir: ${trainer.output_path}
|
playground/Abbie-h100/trainer_configs/trainer_tivila.yaml
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
defaults:
|
| 2 |
+
- trainer_base
|
| 3 |
+
- _self_
|
| 4 |
+
|
| 5 |
+
data:
|
| 6 |
+
allow_skip_files: true
|
| 7 |
+
iterable: true
|
| 8 |
+
transform_extra_kwargs:
|
| 9 |
+
allow_skip: true
|
| 10 |
+
image_min_pixels: null
|
| 11 |
+
image_max_pixels: null
|
| 12 |
+
video_min_pixels: null
|
| 13 |
+
video_max_pixels: 307200
|
| 14 |
+
video_min_frames: null
|
| 15 |
+
video_max_frames: 16
|
playground/Abbie-h100/trainer_utils/__init__.py
ADDED
|
File without changes
|
playground/Abbie-h100/trainer_utils/common.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Tuple, TypedDict
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
from omegaconf import DictConfig, OmegaConf
|
| 7 |
+
|
| 8 |
+
from abbie.device_mesh_manager import DMM
|
| 9 |
+
from abbie.gargantua.causal_lm import GenericTransformerForCausalLM, make_model_optimizer
|
| 10 |
+
from abbie.models import load_pretrained_hf_model
|
| 11 |
+
from abbie.utils.metrics import GlobalMetrics
|
| 12 |
+
from abbie.utils.optimizer import MappedOptimizer, PseudoMappedOptimizer
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TrainingStats(TypedDict):
|
| 16 |
+
step_nb: int
|
| 17 |
+
total_tokens: int
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def set_qwen_vl_utils_log_level(level=logging.ERROR):
|
| 21 |
+
try:
|
| 22 |
+
# Qwen2.5-VL has info logging
|
| 23 |
+
from qwen_vl_utils.vision_process import logger
|
| 24 |
+
|
| 25 |
+
logger.setLevel(level)
|
| 26 |
+
except ImportError:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def init_wandb(config: DictConfig):
|
| 31 |
+
experiment_config = OmegaConf.to_object(config)
|
| 32 |
+
experiment_config.update({"trainer.world_size": dist.get_world_size()})
|
| 33 |
+
|
| 34 |
+
GlobalMetrics.initialize(
|
| 35 |
+
project_name=config.trainer.project_name,
|
| 36 |
+
experiment_name=config.trainer.experiment_name,
|
| 37 |
+
config=experiment_config,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def load_model_and_optimizer(
|
| 42 |
+
config: DictConfig,
|
| 43 |
+
num_training_steps: int,
|
| 44 |
+
) -> Tuple[
|
| 45 |
+
GenericTransformerForCausalLM,
|
| 46 |
+
MappedOptimizer,
|
| 47 |
+
]:
|
| 48 |
+
max_batch_size = config.data.micro_batch_size * config.data.chunks_per_step
|
| 49 |
+
if config.data.is_continuous_batch:
|
| 50 |
+
max_batch_size = config.data.chunks_per_step
|
| 51 |
+
|
| 52 |
+
DMM.log_rank0(f"Loading model from {config.model.pretrained_path}")
|
| 53 |
+
|
| 54 |
+
model = load_pretrained_hf_model(
|
| 55 |
+
config.model.pretrained_path,
|
| 56 |
+
max_batch_size=max_batch_size,
|
| 57 |
+
max_seq_len=config.model.max_seq_len,
|
| 58 |
+
aux_loss_coef=config.model.aux_loss_coef,
|
| 59 |
+
z_loss_coef=config.model.z_loss_coef,
|
| 60 |
+
recompute_norm=config.model.recompute_norm,
|
| 61 |
+
recompute_attn_up_proj=config.model.recompute_attn_up_proj,
|
| 62 |
+
recompute_attn=config.model.recompute_attn,
|
| 63 |
+
recompute_attn_down_proj=config.model.recompute_attn_down_proj,
|
| 64 |
+
recompute_mlp=config.model.recompute_mlp,
|
| 65 |
+
recompute_mlp_act=config.model.recompute_mlp_act,
|
| 66 |
+
recompute_dispatch=config.model.recompute_dispatch,
|
| 67 |
+
recompute_visual=config.model.recompute_visual,
|
| 68 |
+
activation_offloading=config.model.activation_offloading,
|
| 69 |
+
visual_activation_offloading=config.model.visual_activation_offloading,
|
| 70 |
+
token_dispatch_method=config.model.token_dispatch_method,
|
| 71 |
+
pp_distributed_dataloading=config.model.pp_distributed_dataloading,
|
| 72 |
+
decoder_first_pipeline_num_layers=config.model.decoder_first_pipeline_num_layers,
|
| 73 |
+
decoder_last_pipeline_num_layers=config.model.decoder_last_pipeline_num_layers,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Before making optimizer, freeze necessary params first
|
| 77 |
+
if config.model.freeze_decoder_vocab:
|
| 78 |
+
model.freeze_vocab()
|
| 79 |
+
if config.model.freeze_decoder_but_last_n_layers is not None:
|
| 80 |
+
model.freeze_all_layers_but_last_n(config.model.freeze_decoder_but_last_n_layers)
|
| 81 |
+
|
| 82 |
+
if model.config.vision_config is not None:
|
| 83 |
+
if config.model.freeze_visual_encoder:
|
| 84 |
+
model.visual.freeze_encoder()
|
| 85 |
+
if config.model.freeze_visual_aligner:
|
| 86 |
+
model.visual.freeze_aligner()
|
| 87 |
+
|
| 88 |
+
# Initializing model could have created some buffers (like for loading pretrained weights)
|
| 89 |
+
torch.cuda.empty_cache()
|
| 90 |
+
DMM.log_rank0(f"Model loaded mem_alloc={torch.cuda.max_memory_allocated() / (1 << 30):.1f}GB")
|
| 91 |
+
|
| 92 |
+
total_params = 0
|
| 93 |
+
total_trainable_params = 0
|
| 94 |
+
for param in model.parameters():
|
| 95 |
+
total_params += param.numel()
|
| 96 |
+
if param.requires_grad:
|
| 97 |
+
total_trainable_params += param.numel()
|
| 98 |
+
DMM.log_all_ranks(f"trainable_params={total_trainable_params / 1e9:.3f}B total_params={total_params / 1e9:.3f}B")
|
| 99 |
+
|
| 100 |
+
num_warmup_steps = int(num_training_steps * config.optim.lr_warmup_steps_ratio)
|
| 101 |
+
|
| 102 |
+
if config.optim.disable_optimizer:
|
| 103 |
+
optimizer = PseudoMappedOptimizer()
|
| 104 |
+
else:
|
| 105 |
+
optimizer = make_model_optimizer(
|
| 106 |
+
model=model,
|
| 107 |
+
num_training_steps=num_training_steps,
|
| 108 |
+
num_warmup_steps=num_warmup_steps,
|
| 109 |
+
lr=config.optim.lr,
|
| 110 |
+
visual_lr=config.optim.visual_lr,
|
| 111 |
+
betas=(config.optim.adam_beta1, config.optim.adam_beta2),
|
| 112 |
+
weight_decay=config.optim.weight_decay,
|
| 113 |
+
lr_schedule=config.optim.lr_schedule,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Initializing optimizer could have created some buffers
|
| 117 |
+
torch.cuda.empty_cache()
|
| 118 |
+
DMM.log_rank0(f"Optimizers created mem_alloc={torch.cuda.max_memory_allocated() / (1 << 30):.1f}GB")
|
| 119 |
+
|
| 120 |
+
return model, optimizer
|
playground/Abbie-h100/trainer_utils/dataloader.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
import threading
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from queue import Full, Queue
|
| 8 |
+
from typing import List, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.distributed as dist
|
| 12 |
+
from arpeggio import ArpeggioBaseDataloader, Chord, DataloaderArgs, TransformBase, create_dataloader, load_transform
|
| 13 |
+
from arpeggio.meta import DataSourceMeta
|
| 14 |
+
from arpeggio.version import __version__ as arpeggio_version
|
| 15 |
+
from omegaconf import DictConfig
|
| 16 |
+
from packaging.version import Version
|
| 17 |
+
|
| 18 |
+
from abbie.device_mesh_manager import DMM
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
assert Version(arpeggio_version) >= Version("0.2.0c1"), "Require atleast byted-thoth-arpeggio>=0.2.0c1"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class BufferedArpeggioDataloader:
|
| 26 |
+
"""Highly experimental buffer for arpeggio dataloader."""
|
| 27 |
+
|
| 28 |
+
dataloader: ArpeggioBaseDataloader
|
| 29 |
+
dtype: torch.dtype = torch.bfloat16
|
| 30 |
+
|
| 31 |
+
def __post_init__(self):
|
| 32 |
+
self.prev_state_dict = self.dataloader.state_dict()
|
| 33 |
+
|
| 34 |
+
# [batch, state_dict, is_done, error]
|
| 35 |
+
self.queue = Queue[Tuple[Chord, object, bool, Exception]](maxsize=1)
|
| 36 |
+
self.finished = threading.Event()
|
| 37 |
+
self.worker = threading.Thread(target=self.worker_fn, daemon=True)
|
| 38 |
+
self.worker.start()
|
| 39 |
+
|
| 40 |
+
def __del__(self):
|
| 41 |
+
self.finished.set()
|
| 42 |
+
|
| 43 |
+
def worker_fn(self):
|
| 44 |
+
def put(obj):
|
| 45 |
+
while not self.finished.is_set():
|
| 46 |
+
try:
|
| 47 |
+
return self.queue.put(obj, timeout=0.5)
|
| 48 |
+
except Full:
|
| 49 |
+
continue
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
for batch in self.dataloader:
|
| 53 |
+
state_dict = self.dataloader.state_dict()
|
| 54 |
+
batch.to(self.dtype)
|
| 55 |
+
put((batch, state_dict, False, None))
|
| 56 |
+
except Exception as e:
|
| 57 |
+
put((None, None, False, e))
|
| 58 |
+
put((None, None, True, None))
|
| 59 |
+
self.finished.set()
|
| 60 |
+
|
| 61 |
+
def __iter__(self):
|
| 62 |
+
while True:
|
| 63 |
+
try:
|
| 64 |
+
yield next(self)
|
| 65 |
+
except StopIteration:
|
| 66 |
+
self.finished.set()
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
def __next__(self):
|
| 70 |
+
if self.finished.is_set():
|
| 71 |
+
raise StopIteration
|
| 72 |
+
|
| 73 |
+
batch, state_dict, done, exc = self.queue.get()
|
| 74 |
+
if done:
|
| 75 |
+
self.finished.set()
|
| 76 |
+
raise StopIteration
|
| 77 |
+
if exc is not None:
|
| 78 |
+
self.finished.set()
|
| 79 |
+
raise exc
|
| 80 |
+
|
| 81 |
+
self.prev_state_dict = state_dict
|
| 82 |
+
return batch
|
| 83 |
+
|
| 84 |
+
def dump_checkpoint(self, checkpoint_dir: str):
|
| 85 |
+
all_states = [{}] * self.dataloader.dp_size
|
| 86 |
+
dist.all_gather_object(all_states, self.prev_state_dict, self.dataloader.dp_group)
|
| 87 |
+
gathered_states = {k: v for s in all_states for k, v in s.items()}
|
| 88 |
+
|
| 89 |
+
if self.dataloader.dp_rank == 0:
|
| 90 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 91 |
+
with open(f"{checkpoint_dir}/dataloader_state.json", "w") as f:
|
| 92 |
+
json.dump(gathered_states, f)
|
| 93 |
+
|
| 94 |
+
def resume_from_checkpoint(self, checkpoint_dir: str):
|
| 95 |
+
raise RuntimeError(
|
| 96 |
+
"BufferedArpeggioDataloader does not support resume. Please wrap after resuming the base dataloader."
|
| 97 |
+
)
|
| 98 |
+
# with open(f"{checkpoint_dir}/dataloader_state.json", "w") as f:
|
| 99 |
+
# states = json.load(f)
|
| 100 |
+
# self.dataloader.load_state_dict(states)
|
| 101 |
+
# self.prev_state_dict = self.dataloader.state_dict()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@dataclass
|
| 105 |
+
class MultipleArpeggioDataloader:
|
| 106 |
+
"""Highly experimental class to support multiple arpeggio dataloaders."""
|
| 107 |
+
|
| 108 |
+
dataloaders: List[ArpeggioBaseDataloader]
|
| 109 |
+
seed: int
|
| 110 |
+
|
| 111 |
+
def __post_init__(self):
|
| 112 |
+
self.load_order = []
|
| 113 |
+
for idx, dataloader in enumerate(self.dataloaders):
|
| 114 |
+
self.load_order += [idx] * len(dataloader)
|
| 115 |
+
|
| 116 |
+
rng = random.Random(self.seed)
|
| 117 |
+
rng.shuffle(self.load_order)
|
| 118 |
+
|
| 119 |
+
def __len__(self) -> int:
|
| 120 |
+
return len(self.load_order)
|
| 121 |
+
|
| 122 |
+
def __iter__(self):
|
| 123 |
+
dataloader_iters = [iter(d) for d in self.dataloaders]
|
| 124 |
+
for dataloader_idx in self.load_order:
|
| 125 |
+
yield next(dataloader_iters[dataloader_idx])
|
| 126 |
+
|
| 127 |
+
def convert_to_buffered(self, dtype: torch.dtype = torch.bfloat16):
|
| 128 |
+
buffered_dataloaders = []
|
| 129 |
+
for dataloader in self.dataloaders:
|
| 130 |
+
buffered_dataloaders.append(BufferedArpeggioDataloader(dataloader, dtype=dtype))
|
| 131 |
+
|
| 132 |
+
self._dataloaders = self.dataloaders
|
| 133 |
+
self.dataloaders = buffered_dataloaders
|
| 134 |
+
|
| 135 |
+
def dump_checkpoint(self, checkpoint_dir: str):
|
| 136 |
+
for idx, dataloader in enumerate(self.dataloaders):
|
| 137 |
+
dataloader.dump_checkpoint(f"{checkpoint_dir}/{idx}")
|
| 138 |
+
|
| 139 |
+
def resume_from_checkpoint(self, checkpoint_dir: str):
|
| 140 |
+
for idx, dataloader in enumerate(self.dataloaders):
|
| 141 |
+
dataloader.resume_from_checkpoint(f"{checkpoint_dir}/{idx}")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def load_dataloader_and_training_steps(
|
| 145 |
+
config: DictConfig,
|
| 146 |
+
transform: Optional[TransformBase] = None,
|
| 147 |
+
) -> Tuple[ArpeggioBaseDataloader, int]:
|
| 148 |
+
DMM.log_rank0("Creating dataloader")
|
| 149 |
+
dataloader_args = DataloaderArgs(
|
| 150 |
+
num_epoch=config.data.num_epoch,
|
| 151 |
+
iterable=config.data.iterable,
|
| 152 |
+
max_seq_len=config.data.max_seq_len,
|
| 153 |
+
generate_infinitely=config.data.num_training_steps is not None,
|
| 154 |
+
chunks_per_step=config.data.chunks_per_step,
|
| 155 |
+
micro_batch_size=config.data.micro_batch_size,
|
| 156 |
+
is_continuous_batch=config.data.is_continuous_batch,
|
| 157 |
+
max_tokens_per_batch=config.data.max_tokens_per_batch,
|
| 158 |
+
max_samples_per_batch=config.data.max_samples_per_batch,
|
| 159 |
+
pad_to_multiple_of=config.data.pad_to_multiple_of,
|
| 160 |
+
num_workers=config.data.num_workers,
|
| 161 |
+
shuffle=config.data.shuffle,
|
| 162 |
+
seed=config.data.seed,
|
| 163 |
+
allow_skip_files=config.data.allow_skip_files,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
if transform is None:
|
| 167 |
+
tokenizer_path = config.model.tokenizer_path
|
| 168 |
+
extra_kwargs = {}
|
| 169 |
+
if config.data.transform_extra_kwargs is not None:
|
| 170 |
+
extra_kwargs = config.data.transform_extra_kwargs
|
| 171 |
+
|
| 172 |
+
transform = load_transform(model_path=tokenizer_path, **extra_kwargs)
|
| 173 |
+
|
| 174 |
+
dataloader_dp_group = DMM.sp_dp_group
|
| 175 |
+
if config.model.pp_distributed_dataloading:
|
| 176 |
+
assert dataloader_args.chunks_per_step % DMM.pp_size == 0
|
| 177 |
+
dataloader_args.chunks_per_step //= DMM.pp_size
|
| 178 |
+
dataloader_dp_group = DMM.pp_x_sp_dp_group
|
| 179 |
+
|
| 180 |
+
if config.data.multi_source_configs is None:
|
| 181 |
+
# Base case, single dataloader
|
| 182 |
+
dataloader = create_dataloader(
|
| 183 |
+
data_source_metas=config.data.data_source_metas,
|
| 184 |
+
patterns=config.data.patterns,
|
| 185 |
+
args=dataloader_args,
|
| 186 |
+
transform=transform,
|
| 187 |
+
dp_group=dataloader_dp_group,
|
| 188 |
+
dataset_meta_paths=config.data.get("dataset_meta_paths", None),
|
| 189 |
+
)
|
| 190 |
+
DMM.log_rank0(f"Created dataloader with args: {dataloader.args}")
|
| 191 |
+
|
| 192 |
+
else:
|
| 193 |
+
# Handle multiple dataloaders
|
| 194 |
+
with open(config.data.multi_source_configs, "r") as f:
|
| 195 |
+
multi_source_configs = json.load(f)
|
| 196 |
+
assert isinstance(multi_source_configs, list), (
|
| 197 |
+
f"Improper format of multi_source_configs, received {multi_source_configs}"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# Currently does not support generate infinitely
|
| 201 |
+
dataloader_args.generate_infinitely = False
|
| 202 |
+
|
| 203 |
+
dataloaders = []
|
| 204 |
+
for source_metas in multi_source_configs:
|
| 205 |
+
source_metas = parse_source_metas(source_metas)
|
| 206 |
+
dataloader_name = source_metas[0]["name"] # Just sample first one
|
| 207 |
+
DMM.log_rank0(f"Building dataloader for {dataloader_name}")
|
| 208 |
+
dataloader = create_dataloader(
|
| 209 |
+
# Merging would reduce memory pressure
|
| 210 |
+
data_source_metas=merge_source_metas(source_metas),
|
| 211 |
+
args=dataloader_args,
|
| 212 |
+
transform=transform,
|
| 213 |
+
dp_group=dataloader_dp_group,
|
| 214 |
+
)
|
| 215 |
+
DMM.log_rank0(f"Created dataloader with args: {dataloader.args}")
|
| 216 |
+
DMM.log_rank0(f"dataloader max steps: {len(dataloader)}")
|
| 217 |
+
|
| 218 |
+
dataloaders.append(dataloader)
|
| 219 |
+
|
| 220 |
+
dataloader = MultipleArpeggioDataloader(dataloaders, seed=config.data.seed)
|
| 221 |
+
|
| 222 |
+
# Determine number of steps to train
|
| 223 |
+
num_training_steps = config.data.num_training_steps
|
| 224 |
+
if config.data.num_training_steps is None:
|
| 225 |
+
num_training_steps = len(dataloader)
|
| 226 |
+
|
| 227 |
+
return dataloader, num_training_steps
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def parse_source_metas(metas) -> List[DataSourceMeta]:
|
| 231 |
+
assert isinstance(metas, list), f"Improper format of data source metas, received {metas}"
|
| 232 |
+
|
| 233 |
+
for idx, meta in enumerate(metas):
|
| 234 |
+
sample_rate = 1.0
|
| 235 |
+
if isinstance(meta, (list, tuple)):
|
| 236 |
+
# Special format to support per-dataset sampling
|
| 237 |
+
meta, sample_rate = meta
|
| 238 |
+
|
| 239 |
+
if isinstance(meta, str):
|
| 240 |
+
with open(meta, "r") as f:
|
| 241 |
+
meta = json.load(f)
|
| 242 |
+
|
| 243 |
+
assert isinstance(meta, dict)
|
| 244 |
+
|
| 245 |
+
if sample_rate != 1.0:
|
| 246 |
+
meta["filepaths"] = sample_files(meta["filepaths"], sample_rate)
|
| 247 |
+
|
| 248 |
+
metas[idx] = meta
|
| 249 |
+
|
| 250 |
+
return metas
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def merge_source_metas(metas: List[DataSourceMeta]) -> DataSourceMeta:
|
| 254 |
+
assert len(metas) >= 1
|
| 255 |
+
|
| 256 |
+
filepaths = []
|
| 257 |
+
total_num_samples = 0
|
| 258 |
+
total_num_tokens = 0
|
| 259 |
+
|
| 260 |
+
for meta in metas:
|
| 261 |
+
filepaths.extend(meta["filepaths"])
|
| 262 |
+
total_num_samples += meta["avg_samples_per_file"] * len(meta["filepaths"])
|
| 263 |
+
total_num_tokens += meta["avg_tokens_per_file"] * len(meta["filepaths"])
|
| 264 |
+
|
| 265 |
+
merged_meta = deepcopy(metas[0])
|
| 266 |
+
merged_meta["filepaths"] = filepaths
|
| 267 |
+
merged_meta["avg_seq_len"] = total_num_tokens / total_num_samples
|
| 268 |
+
merged_meta["avg_samples_per_file"] = total_num_samples / len(filepaths)
|
| 269 |
+
merged_meta["avg_tokens_per_file"] = total_num_tokens / len(filepaths)
|
| 270 |
+
|
| 271 |
+
return merged_meta
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def sample_files(filepaths: List[str], sample_rate: Union[str, float]) -> List[str]:
|
| 275 |
+
if isinstance(sample_rate, str):
|
| 276 |
+
sample_rate = int(sample_rate.split("%")[0]) / 100
|
| 277 |
+
|
| 278 |
+
if sample_rate < 1:
|
| 279 |
+
n_sample = int(len(filepaths) * sample_rate)
|
| 280 |
+
return filepaths[:n_sample]
|
| 281 |
+
|
| 282 |
+
elif sample_rate > 1:
|
| 283 |
+
return filepaths * int(sample_rate // 1) + sample_files(filepaths, sample_rate % 1)
|
| 284 |
+
|
| 285 |
+
return filepaths
|
playground/Abbie-h100/trainer_utils/thothvl_transform.py
ADDED
|
@@ -0,0 +1,656 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import io
|
| 3 |
+
import os
|
| 4 |
+
from copy import deepcopy
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any, Callable, Dict, List, Optional, Set, Union
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pyarrow.parquet as pq
|
| 11 |
+
import torch
|
| 12 |
+
from arpeggio import Chord, DataloaderArgs, create_dataloader, register_transform
|
| 13 |
+
from arpeggio.chord import Chord
|
| 14 |
+
from arpeggio.tuners import Qwen3VLTransform
|
| 15 |
+
from arpeggio.utils.conversation_utils import (
|
| 16 |
+
chatml_input_ids_to_labels,
|
| 17 |
+
handle_message_extra_fields,
|
| 18 |
+
sharegpt_to_hf_format,
|
| 19 |
+
)
|
| 20 |
+
from arpeggio.utils.qwen_vl_utils import get_mrope_index_qwen3_vl
|
| 21 |
+
from decord import VideoReader, cpu
|
| 22 |
+
from PIL import Image
|
| 23 |
+
from qwen_vl_utils import fetch_image, fetch_video, process_vision_info
|
| 24 |
+
from qwen_vl_utils.vision_process import smart_resize
|
| 25 |
+
from torchvision import transforms
|
| 26 |
+
from torchvision.transforms import InterpolationMode
|
| 27 |
+
from transformers import AutoTokenizer
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
DISABLE_CV2_PATCH = os.getenv("DISABLE_CV2_PATCH", "0") == "1"
|
| 31 |
+
|
| 32 |
+
# ==================== OpenCV Resize Monkey Patch ====================
|
| 33 |
+
# Patch PIL.Image.resize to use OpenCV
|
| 34 |
+
|
| 35 |
+
_original_pil_resize = Image.Image.resize
|
| 36 |
+
|
| 37 |
+
_PIL_TO_CV2_INTERP = {
|
| 38 |
+
Image.Resampling.NEAREST: cv2.INTER_NEAREST,
|
| 39 |
+
Image.Resampling.BILINEAR: cv2.INTER_LINEAR,
|
| 40 |
+
Image.Resampling.BICUBIC: cv2.INTER_CUBIC,
|
| 41 |
+
Image.Resampling.LANCZOS: cv2.INTER_LANCZOS4,
|
| 42 |
+
# Compat with older PIL versions
|
| 43 |
+
0: cv2.INTER_NEAREST,
|
| 44 |
+
2: cv2.INTER_LINEAR,
|
| 45 |
+
3: cv2.INTER_CUBIC,
|
| 46 |
+
1: cv2.INTER_LANCZOS4,
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _cv2_resize(self, size, resample=None, box=None, reducing_gap=None):
|
| 51 |
+
"""OpenCV-accelerated PIL Image.resize()."""
|
| 52 |
+
# Fall back to original for box parameter (crop + resize)
|
| 53 |
+
if box is not None:
|
| 54 |
+
return _original_pil_resize(self, size, resample=resample, box=box, reducing_gap=reducing_gap)
|
| 55 |
+
|
| 56 |
+
if resample is None:
|
| 57 |
+
resample = Image.Resampling.BICUBIC
|
| 58 |
+
cv2_interp = _PIL_TO_CV2_INTERP.get(resample, cv2.INTER_LINEAR)
|
| 59 |
+
|
| 60 |
+
target_w, target_h = size
|
| 61 |
+
# Use INTER_AREA for downsampling (better quality)
|
| 62 |
+
if target_w < self.width or target_h < self.height:
|
| 63 |
+
cv2_interp = cv2.INTER_AREA
|
| 64 |
+
|
| 65 |
+
img_array = np.asarray(self)
|
| 66 |
+
resized = cv2.resize(img_array, (target_w, target_h), interpolation=cv2_interp)
|
| 67 |
+
return Image.fromarray(resized)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def enable_cv2_resize():
|
| 71 |
+
"""Enable OpenCV-accelerated resize."""
|
| 72 |
+
Image.Image.resize = _cv2_resize
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def disable_cv2_resize():
|
| 76 |
+
"""Restore original PIL resize."""
|
| 77 |
+
Image.Image.resize = _original_pil_resize
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# Enable by default
|
| 81 |
+
if not DISABLE_CV2_PATCH:
|
| 82 |
+
enable_cv2_resize()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@dataclass
|
| 86 |
+
class VideoData:
|
| 87 |
+
"""Processed video data with metadata."""
|
| 88 |
+
|
| 89 |
+
video: Union[torch.Tensor, List[Image.Image]] # video tensor or PIL frames
|
| 90 |
+
metadata: dict # contains fps, total_num_frames, frames_indices
|
| 91 |
+
sample_fps: float
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class ThothVLTransform(Qwen3VLTransform):
|
| 95 |
+
"""Qwen3-VL transform that supports Thoth/msswift-style data formats.
|
| 96 |
+
|
| 97 |
+
Supports:
|
| 98 |
+
- content_split: pretrain text data
|
| 99 |
+
- caption: image captioning data
|
| 100 |
+
- conversations/messages: multi-turn dialogue
|
| 101 |
+
- Various image formats: bytes, path, dict, PIL.Image
|
| 102 |
+
- Various video formats: frames, video bytes, gif
|
| 103 |
+
- Nested conversations
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
# ==================== Image Processing ====================
|
| 107 |
+
|
| 108 |
+
def _read_image(
|
| 109 |
+
self,
|
| 110 |
+
image: Union[bytes, str, Image.Image, dict, None],
|
| 111 |
+
to_pil: bool = False,
|
| 112 |
+
) -> Optional[Image.Image]:
|
| 113 |
+
"""Convert various image formats to PIL Image."""
|
| 114 |
+
if image is None:
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
if isinstance(image, Image.Image):
|
| 118 |
+
return image
|
| 119 |
+
|
| 120 |
+
if isinstance(image, bytes):
|
| 121 |
+
return Image.open(io.BytesIO(image))
|
| 122 |
+
|
| 123 |
+
if isinstance(image, str):
|
| 124 |
+
# Path to image - will be handled by fetch_image later
|
| 125 |
+
return image
|
| 126 |
+
|
| 127 |
+
if isinstance(image, dict):
|
| 128 |
+
if image.get("bytes") is not None:
|
| 129 |
+
img_bytes = image["bytes"]
|
| 130 |
+
if isinstance(img_bytes, Image.Image):
|
| 131 |
+
return img_bytes
|
| 132 |
+
return Image.open(io.BytesIO(img_bytes))
|
| 133 |
+
elif image.get("path") is not None:
|
| 134 |
+
return image["path"]
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
if isinstance(image, (np.float64, np.float32)):
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 141 |
+
|
| 142 |
+
def _process_images(self, item: dict) -> Optional[List]:
|
| 143 |
+
"""Extract and process images from item."""
|
| 144 |
+
raw_images = None
|
| 145 |
+
|
| 146 |
+
if "jpg" in item:
|
| 147 |
+
raw_images = [item.pop("jpg")]
|
| 148 |
+
elif "image" in item:
|
| 149 |
+
image_data = item.pop("image")
|
| 150 |
+
if image_data is not None and not isinstance(image_data, (np.float64, np.float32)):
|
| 151 |
+
raw_images = [image_data]
|
| 152 |
+
elif "images" in item:
|
| 153 |
+
raw_images = item.pop("images")
|
| 154 |
+
if isinstance(raw_images, np.ndarray):
|
| 155 |
+
raw_images = raw_images.tolist()
|
| 156 |
+
elif isinstance(raw_images, dict):
|
| 157 |
+
raw_images = [raw_images]
|
| 158 |
+
|
| 159 |
+
if not raw_images:
|
| 160 |
+
return None
|
| 161 |
+
|
| 162 |
+
images = []
|
| 163 |
+
for raw in raw_images:
|
| 164 |
+
img = self._read_image(raw, to_pil=True)
|
| 165 |
+
if img is None:
|
| 166 |
+
continue
|
| 167 |
+
|
| 168 |
+
if isinstance(img, str):
|
| 169 |
+
# Path - use fetch_image
|
| 170 |
+
ele = {"type": "image", "image": img}
|
| 171 |
+
self._patch_visual_element(ele)
|
| 172 |
+
img = fetch_image(ele, image_patch_size=self._patch_size)
|
| 173 |
+
|
| 174 |
+
images.append(img)
|
| 175 |
+
|
| 176 |
+
return images if images else None
|
| 177 |
+
|
| 178 |
+
# ==================== Video Processing ====================
|
| 179 |
+
|
| 180 |
+
def _read_gif(self, gif_bytes: bytes) -> List[Image.Image]:
|
| 181 |
+
"""Extract frames from a GIF."""
|
| 182 |
+
if not isinstance(gif_bytes, bytes):
|
| 183 |
+
raise TypeError(f"Unsupported gif type: {type(gif_bytes)}")
|
| 184 |
+
|
| 185 |
+
frames = []
|
| 186 |
+
with io.BytesIO(gif_bytes) as byte_stream:
|
| 187 |
+
with Image.open(byte_stream) as img:
|
| 188 |
+
try:
|
| 189 |
+
while True:
|
| 190 |
+
frames.append(img.copy())
|
| 191 |
+
img.seek(img.tell() + 1)
|
| 192 |
+
except EOFError:
|
| 193 |
+
pass
|
| 194 |
+
return frames
|
| 195 |
+
|
| 196 |
+
def _decode_video_bytes(self, video_bytes: bytes) -> tuple[torch.Tensor, dict, float]:
|
| 197 |
+
"""Decode video from bytes using decord.
|
| 198 |
+
|
| 199 |
+
Returns (video_tensor, metadata, sample_fps)
|
| 200 |
+
"""
|
| 201 |
+
vr = VideoReader(io.BytesIO(video_bytes), ctx=cpu(0), num_threads=1)
|
| 202 |
+
|
| 203 |
+
total_frames = len(vr)
|
| 204 |
+
fps = vr.get_avg_fps()
|
| 205 |
+
|
| 206 |
+
max_num_frames = self._video_ele_kwargs.get("max_frames") or int(os.environ.get("FPS_MAX_FRAMES", 32))
|
| 207 |
+
|
| 208 |
+
if total_frames <= max_num_frames:
|
| 209 |
+
indices = list(range(total_frames))
|
| 210 |
+
else:
|
| 211 |
+
indices = np.linspace(0, total_frames - 1, max_num_frames, dtype=int).tolist()
|
| 212 |
+
|
| 213 |
+
# numpy array: [N, H, W, C]
|
| 214 |
+
frames = vr.get_batch(indices).asnumpy()
|
| 215 |
+
|
| 216 |
+
# [N, C, H, W]
|
| 217 |
+
video_tensor = torch.from_numpy(frames).permute(0, 3, 1, 2)
|
| 218 |
+
|
| 219 |
+
sample_fps = len(indices) / total_frames * fps if total_frames > 0 else 1.0
|
| 220 |
+
|
| 221 |
+
metadata = {
|
| 222 |
+
"fps": fps,
|
| 223 |
+
"total_num_frames": total_frames,
|
| 224 |
+
"frames_indices": torch.tensor(indices),
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
return video_tensor, metadata, sample_fps
|
| 228 |
+
|
| 229 |
+
def _process_videos(self, item: dict) -> Optional[List[VideoData]]:
|
| 230 |
+
"""Extract and process videos from item.
|
| 231 |
+
|
| 232 |
+
Returns a list of VideoData, each containing video tensor/frames and metadata.
|
| 233 |
+
|
| 234 |
+
Supported formats:
|
| 235 |
+
- frames: List[bytes] - Each bytes is an image (frame)
|
| 236 |
+
- video: bytes - Raw mp4 video bytes
|
| 237 |
+
- video: str - Video file path
|
| 238 |
+
- gif: bytes - GIF animation bytes
|
| 239 |
+
- videos: List[...] - Multiple videos in various formats
|
| 240 |
+
"""
|
| 241 |
+
max_num_frames = int(os.environ.get("FPS_MAX_FRAMES", 16))
|
| 242 |
+
raw_videos = None
|
| 243 |
+
|
| 244 |
+
if "frames" in item:
|
| 245 |
+
raw_frames = item.pop("frames")
|
| 246 |
+
frames = []
|
| 247 |
+
for frame in raw_frames:
|
| 248 |
+
img = self._read_image(frame)
|
| 249 |
+
if img is not None and isinstance(img, Image.Image):
|
| 250 |
+
frames.append(img)
|
| 251 |
+
|
| 252 |
+
if len(frames) > max_num_frames:
|
| 253 |
+
indices = np.linspace(0, len(frames) - 1, max_num_frames, dtype=int)
|
| 254 |
+
frames = [frames[i] for i in indices]
|
| 255 |
+
|
| 256 |
+
if frames:
|
| 257 |
+
raw_videos = [frames]
|
| 258 |
+
elif "video" in item:
|
| 259 |
+
raw_videos = [item.pop("video")]
|
| 260 |
+
elif "gif" in item:
|
| 261 |
+
raw_videos = [self._read_gif(item.pop("gif"))]
|
| 262 |
+
elif "videos" in item:
|
| 263 |
+
raw_videos = item.pop("videos")
|
| 264 |
+
if isinstance(raw_videos, np.ndarray):
|
| 265 |
+
raw_videos = raw_videos.tolist()
|
| 266 |
+
if raw_videos and isinstance(raw_videos[0], np.ndarray):
|
| 267 |
+
raw_videos = [v.tolist() for v in raw_videos]
|
| 268 |
+
|
| 269 |
+
if not raw_videos:
|
| 270 |
+
return None
|
| 271 |
+
|
| 272 |
+
results = []
|
| 273 |
+
|
| 274 |
+
try:
|
| 275 |
+
for raw in raw_videos:
|
| 276 |
+
if isinstance(raw, list) and raw and isinstance(raw[0], Image.Image):
|
| 277 |
+
# List of PIL Images (frames)
|
| 278 |
+
num_frames = len(raw)
|
| 279 |
+
metadata = {
|
| 280 |
+
"fps": 1.0,
|
| 281 |
+
"total_num_frames": num_frames,
|
| 282 |
+
"frames_indices": torch.arange(num_frames),
|
| 283 |
+
}
|
| 284 |
+
results.append(VideoData(video=raw, metadata=metadata, sample_fps=1.0))
|
| 285 |
+
|
| 286 |
+
elif isinstance(raw, list) and raw and isinstance(raw[0], bytes):
|
| 287 |
+
total_frames = len(raw)
|
| 288 |
+
|
| 289 |
+
if total_frames > max_num_frames:
|
| 290 |
+
indices = np.linspace(0, total_frames - 1, max_num_frames, dtype=int)
|
| 291 |
+
else:
|
| 292 |
+
indices = range(total_frames)
|
| 293 |
+
|
| 294 |
+
frames = []
|
| 295 |
+
for i in indices:
|
| 296 |
+
img = self._read_image(raw[i])
|
| 297 |
+
if img is not None and isinstance(img, Image.Image):
|
| 298 |
+
frames.append(img)
|
| 299 |
+
|
| 300 |
+
if frames:
|
| 301 |
+
num_frames = len(frames)
|
| 302 |
+
metadata = {
|
| 303 |
+
"fps": 1.0,
|
| 304 |
+
"total_num_frames": total_frames,
|
| 305 |
+
"frames_indices": torch.tensor(
|
| 306 |
+
list(indices) if total_frames > max_num_frames else list(range(num_frames))
|
| 307 |
+
),
|
| 308 |
+
}
|
| 309 |
+
results.append(VideoData(video=frames, metadata=metadata, sample_fps=1.0))
|
| 310 |
+
|
| 311 |
+
elif isinstance(raw, bytes):
|
| 312 |
+
# Video bytes - use decord
|
| 313 |
+
video_tensor, metadata, sample_fps = self._decode_video_bytes(raw)
|
| 314 |
+
results.append(VideoData(video=video_tensor, metadata=metadata, sample_fps=sample_fps))
|
| 315 |
+
|
| 316 |
+
elif isinstance(raw, str):
|
| 317 |
+
# Video file path
|
| 318 |
+
ele = {"type": "video", "video": raw}
|
| 319 |
+
self._patch_visual_element(ele)
|
| 320 |
+
result, sample_fps = fetch_video(
|
| 321 |
+
ele,
|
| 322 |
+
image_patch_size=self._patch_size,
|
| 323 |
+
return_video_sample_fps=True,
|
| 324 |
+
return_video_metadata=True,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
if isinstance(result, tuple):
|
| 328 |
+
video_tensor, metadata = result
|
| 329 |
+
else:
|
| 330 |
+
video_tensor = result
|
| 331 |
+
num_frames = video_tensor.shape[0]
|
| 332 |
+
metadata = {
|
| 333 |
+
"fps": sample_fps,
|
| 334 |
+
"total_num_frames": num_frames,
|
| 335 |
+
"frames_indices": torch.arange(num_frames),
|
| 336 |
+
}
|
| 337 |
+
results.append(VideoData(video=video_tensor, metadata=metadata, sample_fps=sample_fps))
|
| 338 |
+
|
| 339 |
+
elif isinstance(raw, torch.Tensor):
|
| 340 |
+
num_frames = raw.shape[0]
|
| 341 |
+
metadata = {
|
| 342 |
+
"fps": 1.0,
|
| 343 |
+
"total_num_frames": num_frames,
|
| 344 |
+
"frames_indices": torch.arange(num_frames),
|
| 345 |
+
}
|
| 346 |
+
results.append(VideoData(video=raw, metadata=metadata, sample_fps=1.0))
|
| 347 |
+
except Exception as e:
|
| 348 |
+
print(f"_process_videos error: {e}")
|
| 349 |
+
raise e
|
| 350 |
+
|
| 351 |
+
return results if results else None
|
| 352 |
+
|
| 353 |
+
# ==================== Conversation Processing ====================
|
| 354 |
+
|
| 355 |
+
def _normalize_message_format(self, messages: List[Dict]) -> List[Dict]:
|
| 356 |
+
"""Convert from/value format to role/content format and filter system messages.
|
| 357 |
+
|
| 358 |
+
Handles:
|
| 359 |
+
- from: human/user -> role: user
|
| 360 |
+
- from: gpt/assistant -> role: assistant
|
| 361 |
+
- from: system -> filtered out
|
| 362 |
+
- value -> content
|
| 363 |
+
- Dirty data fix: if assistant message contains <image>/<video>, swap roles
|
| 364 |
+
"""
|
| 365 |
+
if isinstance(messages, np.ndarray):
|
| 366 |
+
messages = messages.tolist()
|
| 367 |
+
elif isinstance(messages, str):
|
| 368 |
+
messages = ast.literal_eval(messages)
|
| 369 |
+
|
| 370 |
+
normalized = []
|
| 371 |
+
for msg in messages:
|
| 372 |
+
# Skip system messages
|
| 373 |
+
if msg.get("from") == "system" or msg.get("role") == "system":
|
| 374 |
+
continue
|
| 375 |
+
|
| 376 |
+
new_msg = {}
|
| 377 |
+
|
| 378 |
+
# Handle role/from
|
| 379 |
+
if "role" in msg:
|
| 380 |
+
new_msg["role"] = msg["role"]
|
| 381 |
+
elif "from" in msg:
|
| 382 |
+
from_value = msg["from"]
|
| 383 |
+
if from_value in ("human", "user"):
|
| 384 |
+
new_msg["role"] = "user"
|
| 385 |
+
elif from_value in ("gpt", "assistant"):
|
| 386 |
+
new_msg["role"] = "assistant"
|
| 387 |
+
else:
|
| 388 |
+
new_msg["role"] = from_value
|
| 389 |
+
|
| 390 |
+
# Handle content/value
|
| 391 |
+
if "content" in msg:
|
| 392 |
+
new_msg["content"] = msg["content"]
|
| 393 |
+
elif "value" in msg:
|
| 394 |
+
new_msg["content"] = msg["value"]
|
| 395 |
+
|
| 396 |
+
normalized.append(new_msg)
|
| 397 |
+
|
| 398 |
+
# Fix dirty data: if assistant message contains <image>/<video>, swap roles
|
| 399 |
+
normalized = self._fix_misplaced_roles(normalized)
|
| 400 |
+
|
| 401 |
+
return normalized
|
| 402 |
+
|
| 403 |
+
def _fix_misplaced_roles(self, messages: List[Dict]) -> List[Dict]:
|
| 404 |
+
"""Fix dirty data where assistant messages contain <image>/<video>.
|
| 405 |
+
|
| 406 |
+
Detection pattern:
|
| 407 |
+
- First message is from assistant AND contains <image>/<video>
|
| 408 |
+
- Messages alternate between roles
|
| 409 |
+
|
| 410 |
+
Fix: Swap all user <-> assistant roles
|
| 411 |
+
"""
|
| 412 |
+
if not messages:
|
| 413 |
+
return messages
|
| 414 |
+
|
| 415 |
+
def _contains_media(content) -> bool:
|
| 416 |
+
if not isinstance(content, str):
|
| 417 |
+
return False
|
| 418 |
+
return "<image>" in content or "<video>" in content
|
| 419 |
+
|
| 420 |
+
# Check first message
|
| 421 |
+
first_msg = messages[0]
|
| 422 |
+
first_role = first_msg.get("role", "")
|
| 423 |
+
first_content = first_msg.get("content", "")
|
| 424 |
+
|
| 425 |
+
# Only fix if: first message is assistant AND contains media
|
| 426 |
+
if first_role != "assistant" or not _contains_media(first_content):
|
| 427 |
+
return messages
|
| 428 |
+
|
| 429 |
+
# Additional validation: check if this looks like a swapped conversation
|
| 430 |
+
# (i.e., roles alternate properly, just in wrong order)
|
| 431 |
+
if len(messages) >= 2:
|
| 432 |
+
second_role = messages[1].get("role", "")
|
| 433 |
+
# Expected pattern after fix: user, assistant, user, assistant...
|
| 434 |
+
# Current pattern (wrong): assistant, user, assistant, user...
|
| 435 |
+
if second_role != "user":
|
| 436 |
+
# Doesn't match expected dirty pattern, don't fix
|
| 437 |
+
return messages
|
| 438 |
+
|
| 439 |
+
# Swap all roles
|
| 440 |
+
role_map = {"user": "assistant", "assistant": "user"}
|
| 441 |
+
fixed = []
|
| 442 |
+
for msg in messages:
|
| 443 |
+
new_msg = msg.copy()
|
| 444 |
+
if new_msg.get("role") in role_map:
|
| 445 |
+
new_msg["role"] = role_map[new_msg["role"]]
|
| 446 |
+
fixed.append(new_msg)
|
| 447 |
+
|
| 448 |
+
return fixed
|
| 449 |
+
|
| 450 |
+
def _replace_image_with_video_placeholder(self, messages: List[Dict]) -> List[Dict]:
|
| 451 |
+
"""Replace <image> placeholders with <video> when videos are present."""
|
| 452 |
+
for msg in messages:
|
| 453 |
+
if "value" in msg:
|
| 454 |
+
msg["value"] = msg["value"].replace("<image>", "<video>")
|
| 455 |
+
elif "content" in msg:
|
| 456 |
+
msg["content"] = msg["content"].replace("<image>", "<video>")
|
| 457 |
+
return messages
|
| 458 |
+
|
| 459 |
+
def _is_nested_conversation(self, messages) -> bool:
|
| 460 |
+
"""Check if messages contain nested conversations."""
|
| 461 |
+
if not messages:
|
| 462 |
+
return False
|
| 463 |
+
return isinstance(messages[0], (np.ndarray, list))
|
| 464 |
+
|
| 465 |
+
# ==================== Main Preprocessing Methods ====================
|
| 466 |
+
|
| 467 |
+
def preprocess_pretrain(self, item: dict) -> Chord:
|
| 468 |
+
"""Process pretrain-style data (content_split)."""
|
| 469 |
+
item = dict(item)
|
| 470 |
+
|
| 471 |
+
content = item.pop("content_split")
|
| 472 |
+
messages = [{"role": "assistant", "content": content}]
|
| 473 |
+
|
| 474 |
+
# Process any images
|
| 475 |
+
images = self._process_images(item)
|
| 476 |
+
|
| 477 |
+
text = self.processor.apply_chat_template(messages, tokenize=False)
|
| 478 |
+
|
| 479 |
+
extra_info = item.pop("extra_info", {})
|
| 480 |
+
if self.add_raw:
|
| 481 |
+
extra_info["raw_messages"] = messages
|
| 482 |
+
|
| 483 |
+
return self._make_model_inputs(
|
| 484 |
+
text=text,
|
| 485 |
+
images=images,
|
| 486 |
+
extra_info=extra_info,
|
| 487 |
+
do_resize=True,
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
def preprocess_caption(self, item: dict) -> Chord:
|
| 491 |
+
"""Process image captioning data."""
|
| 492 |
+
item = dict(item)
|
| 493 |
+
|
| 494 |
+
caption = item.pop("caption")
|
| 495 |
+
messages = [
|
| 496 |
+
{"role": "user", "content": "<image>"},
|
| 497 |
+
{"role": "assistant", "content": caption},
|
| 498 |
+
]
|
| 499 |
+
|
| 500 |
+
# Process images
|
| 501 |
+
images = self._process_images(item)
|
| 502 |
+
|
| 503 |
+
# Convert to HF format for apply_chat_template
|
| 504 |
+
prompt = sharegpt_to_hf_format(messages)
|
| 505 |
+
text = self.processor.apply_chat_template(prompt, tokenize=False)
|
| 506 |
+
|
| 507 |
+
extra_info = item.pop("extra_info", {})
|
| 508 |
+
if self.add_raw:
|
| 509 |
+
extra_info["raw_messages"] = messages
|
| 510 |
+
|
| 511 |
+
return self._make_model_inputs(
|
| 512 |
+
text=text,
|
| 513 |
+
images=images,
|
| 514 |
+
extra_info=extra_info,
|
| 515 |
+
do_resize=True,
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
def preprocess_conversation(self, item: dict) -> Chord:
|
| 519 |
+
"""Process conversation/dialogue data."""
|
| 520 |
+
item = dict(item)
|
| 521 |
+
|
| 522 |
+
# Get messages from either 'messages' or 'conversations' key
|
| 523 |
+
if "messages" in item:
|
| 524 |
+
messages = item.pop("messages")
|
| 525 |
+
elif "conversations" in item:
|
| 526 |
+
messages = item.pop("conversations")
|
| 527 |
+
else:
|
| 528 |
+
raise ValueError("No messages or conversations found in item")
|
| 529 |
+
|
| 530 |
+
messages = self._normalize_message_format(messages)
|
| 531 |
+
|
| 532 |
+
# Process images and videos
|
| 533 |
+
images = self._process_images(item)
|
| 534 |
+
video_data_list = self._process_videos(item)
|
| 535 |
+
|
| 536 |
+
videos = None
|
| 537 |
+
video_metadatas = None
|
| 538 |
+
video_kwargs = {"do_sample_frames": False}
|
| 539 |
+
|
| 540 |
+
if video_data_list:
|
| 541 |
+
messages = self._replace_image_with_video_placeholder(messages)
|
| 542 |
+
|
| 543 |
+
videos = [vd.video for vd in video_data_list]
|
| 544 |
+
video_metadatas = [vd.metadata for vd in video_data_list]
|
| 545 |
+
fps_list = [vd.sample_fps for vd in video_data_list]
|
| 546 |
+
video_kwargs["fps"] = fps_list
|
| 547 |
+
|
| 548 |
+
# Convert to HF format
|
| 549 |
+
prompt = sharegpt_to_hf_format(messages)
|
| 550 |
+
text = self.processor.apply_chat_template(prompt, tokenize=False)
|
| 551 |
+
|
| 552 |
+
extra_info = item.pop("extra_info", {})
|
| 553 |
+
if self.add_raw:
|
| 554 |
+
extra_info["raw_messages"] = messages
|
| 555 |
+
|
| 556 |
+
return self._make_model_inputs(
|
| 557 |
+
text=text,
|
| 558 |
+
images=images,
|
| 559 |
+
videos=videos,
|
| 560 |
+
video_metadatas=video_metadatas if video_metadatas else None,
|
| 561 |
+
extra_info=extra_info,
|
| 562 |
+
do_resize=True,
|
| 563 |
+
**video_kwargs,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
def _process_nested_conversations(self, item: dict) -> List[Chord]:
|
| 567 |
+
"""Process nested conversations into a list of Chords."""
|
| 568 |
+
base_item = dict(item)
|
| 569 |
+
|
| 570 |
+
if "messages" in base_item:
|
| 571 |
+
nested_convs = base_item.pop("messages")
|
| 572 |
+
else:
|
| 573 |
+
nested_convs = base_item.pop("conversations")
|
| 574 |
+
|
| 575 |
+
if isinstance(nested_convs, np.ndarray):
|
| 576 |
+
nested_convs = nested_convs.tolist()
|
| 577 |
+
|
| 578 |
+
results = []
|
| 579 |
+
for single_conv in nested_convs:
|
| 580 |
+
if isinstance(single_conv, np.ndarray):
|
| 581 |
+
single_conv = single_conv.tolist()
|
| 582 |
+
|
| 583 |
+
single_item = deepcopy(base_item)
|
| 584 |
+
single_item["messages"] = single_conv
|
| 585 |
+
|
| 586 |
+
chord = self.preprocess_conversation(single_item)
|
| 587 |
+
results.append(chord)
|
| 588 |
+
|
| 589 |
+
return results
|
| 590 |
+
|
| 591 |
+
def preprocess(self, item: dict) -> Union[Chord, List[Chord]]:
|
| 592 |
+
"""Main preprocessing entry point.
|
| 593 |
+
|
| 594 |
+
Please refer https://code.byted.org/Thoth/ms-swift/blob/dev.gyf.thoth_vl.hdfs_support/swift/llm/dataset/preprocessor/extra.py
|
| 595 |
+
|
| 596 |
+
Handles various data formats from msswift:
|
| 597 |
+
- content_split: pretrain text data
|
| 598 |
+
- caption: image captioning data
|
| 599 |
+
- messages/conversations: multi-turn dialogue (including nested)
|
| 600 |
+
"""
|
| 601 |
+
try:
|
| 602 |
+
item = dict(item) # Shallow copy
|
| 603 |
+
|
| 604 |
+
# Handle content_split (pretrain style)
|
| 605 |
+
if "content_split" in item:
|
| 606 |
+
return self.preprocess_pretrain(item)
|
| 607 |
+
|
| 608 |
+
# Handle caption (image captioning style)
|
| 609 |
+
if "caption" in item:
|
| 610 |
+
return self.preprocess_caption(item)
|
| 611 |
+
|
| 612 |
+
# Handle conversations/messages
|
| 613 |
+
if "conversations" in item or "messages" in item:
|
| 614 |
+
# Get the conversation data
|
| 615 |
+
conv_key = "messages" if "messages" in item else "conversations"
|
| 616 |
+
conv_data = item[conv_key]
|
| 617 |
+
|
| 618 |
+
if isinstance(conv_data, np.ndarray):
|
| 619 |
+
conv_data = conv_data.tolist()
|
| 620 |
+
elif isinstance(conv_data, str):
|
| 621 |
+
conv_data = ast.literal_eval(conv_data)
|
| 622 |
+
|
| 623 |
+
# Check for nested conversations
|
| 624 |
+
if self._is_nested_conversation(conv_data):
|
| 625 |
+
item[conv_key] = conv_data
|
| 626 |
+
return self._process_nested_conversations(item)
|
| 627 |
+
|
| 628 |
+
return self.preprocess_conversation(item)
|
| 629 |
+
|
| 630 |
+
# Fallback to parent class behavior
|
| 631 |
+
if self.prompt_key in item:
|
| 632 |
+
return super().preprocess_conversation(item)
|
| 633 |
+
elif self.document_key in item:
|
| 634 |
+
return super().preprocess_document(item)
|
| 635 |
+
|
| 636 |
+
raise RuntimeError(f"Sample contained no usable fields: {list(item.keys())}")
|
| 637 |
+
|
| 638 |
+
except Exception as e:
|
| 639 |
+
if not self.allow_skip:
|
| 640 |
+
raise e
|
| 641 |
+
|
| 642 |
+
if self.should_use_mrope:
|
| 643 |
+
position_ids = torch.zeros(3, 1, 0, dtype=torch.long)
|
| 644 |
+
else:
|
| 645 |
+
position_ids = torch.zeros(1, 0, dtype=torch.long)
|
| 646 |
+
|
| 647 |
+
return {
|
| 648 |
+
"input_ids": torch.zeros(1, 0, dtype=torch.long),
|
| 649 |
+
"position_ids": position_ids,
|
| 650 |
+
"attention_mask": torch.zeros(1, 0, dtype=torch.long),
|
| 651 |
+
"labels": torch.zeros(1, 0, dtype=torch.long),
|
| 652 |
+
"extra_info": [{}],
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
register_transform("thoth_vl", ThothVLTransform)
|