Download source/src/vimeml/training/distributed.py from Voltline/vimeml-zh-v2: direct link, hf CLI and curl.
- Browser
- Download file 5.1 kB
-
https://huggingface.co/Voltline/vimeml-zh-v2/resolve/main/source/src/vimeml/training/distributed.py
- Command line
-
hf download hf://Voltline/vimeml-zh-v2/source/src/vimeml/training/distributed.py
-
curl -L -o distributed.py https://huggingface.co/Voltline/vimeml-zh-v2/resolve/main/source/src/vimeml/training/distributed.py
5.1 kB
| """Single-node data parallelism for the zh pretraining trainers (launched with torchrun). | |
| Every rank draws the same global batch from the same seeded loaders, then trains on its | |
| own strided share of the rows. The data order, the cursor and the per-update token | |
| normalization therefore stay exactly those of a one-device run: each rank scales its loss | |
| by the global supervised-token count and by the world size (DDP averages gradients), so | |
| the summed gradient is the one-device gradient up to floating-point order. Rank 0 writes | |
| checkpoints and logs; joint_zh13 validates on rank 0 while the others wait, joint_zh200m | |
| shares the LM validation batches over the ranks. | |
| With WORLD_SIZE unset or 1 nothing here changes the one-device path. | |
| """ | |
| import datetime | |
| import math | |
| import os | |
| from contextlib import nullcontext | |
| import torch | |
| import torch.distributed as dist | |
| # Rank 0 may validate alone at milestones while the others wait at a barrier; a full | |
| # FP32 validation of a large model can take far longer than NCCL's default 10 minutes. | |
| TIMEOUT = datetime.timedelta(hours=6) | |
| class Context: | |
| def __init__(self, world=1, rank=0, local_rank=0): | |
| self.world, self.rank, self.local_rank = world, rank, local_rank | |
| def active(self): | |
| return self.world > 1 | |
| def main(self): | |
| return self.rank == 0 | |
| def device(self, kind): | |
| if kind == "cuda": | |
| return torch.device("cuda", self.local_rank) | |
| return torch.device(kind) | |
| def wrap(self, model, device): | |
| """The module that runs training forwards; `model` itself stays the unwrapped one.""" | |
| if not self.active: | |
| return model | |
| from torch.nn.parallel import DistributedDataParallel | |
| ids = [device.index] if device.type == "cuda" else None | |
| return DistributedDataParallel(model, device_ids=ids, broadcast_buffers=False) | |
| def no_sync(self, module, last): | |
| """Skip the gradient all-reduce on every backward but the last of an update.""" | |
| return nullcontext() if last or not self.active else module.no_sync() | |
| def share(self, batch): | |
| """This rank's rows of a global batch, taken with stride `world` from `rank` and trimmed to | |
| this share's width (as posttraining.streams.microbatches trims). None when this rank gets | |
| no rows. | |
| The bucketed loaders sort a batch by window length (data.LengthBucketBatchSampler), so a | |
| contiguous share hands every rank a different slice of the length distribution: the last | |
| ranks pack the longest windows of every batch into several times as many padded rows and | |
| pay more attention per token, while DDP makes every other rank wait for them at the | |
| final all-reduce of the update. Striding gives every rank a uniform sample of the batch | |
| instead. The gradient is unchanged either way: each row of the global batch contributes | |
| its tokens exactly once and the per-token weights are global counts.""" | |
| part = {name: value[self.rank::self.world] for name, value in batch.items()} | |
| if not len(part["lengths"]): | |
| return None | |
| width = math.ceil(int(part["lengths"].max()) / 8) * 8 | |
| part["input_ids"] = part["input_ids"][:, :width] | |
| part["labels"] = part["labels"][:, :width] | |
| return part | |
| def sum(self, values, device): | |
| """Elementwise sum of a list of floats over all ranks (FP64).""" | |
| if not self.active: | |
| return list(values) | |
| tensor = torch.tensor(values, dtype=torch.float64, device=device) | |
| dist.all_reduce(tensor) | |
| return tensor.tolist() | |
| def any(self, flag, device): | |
| """True on every rank when any rank's flag is set (stop requests).""" | |
| if not self.active: | |
| return bool(flag) | |
| return self.sum([1.0 if flag else 0.0], device)[0] > 0 | |
| def broadcast(self, value): | |
| """Rank 0's picklable value on every rank (milestone reports).""" | |
| if not self.active: | |
| return value | |
| holder = [value] | |
| dist.broadcast_object_list(holder, src=0) | |
| return holder[0] | |
| def barrier(self): | |
| if self.active: | |
| dist.barrier() | |
| def close(self): | |
| if self.active and dist.is_initialized(): | |
| dist.destroy_process_group() | |
| class NullWriter: | |
| """Stands in for SummaryWriter on ranks other than 0.""" | |
| def add_scalar(self, *args, **kwargs): | |
| pass | |
| def close(self): | |
| pass | |
| def setup(device_kind): | |
| """Read torchrun's environment; initialize the process group when WORLD_SIZE > 1.""" | |
| world = int(os.environ.get("WORLD_SIZE", "1")) | |
| if world <= 1: | |
| return Context() | |
| rank, local = int(os.environ["RANK"]), int(os.environ["LOCAL_RANK"]) | |
| if device_kind == "cuda": | |
| if torch.cuda.device_count() <= local: | |
| raise ValueError("Data parallelism needs one visible GPU per local rank") | |
| torch.cuda.set_device(local) | |
| dist.init_process_group("nccl" if device_kind == "cuda" else "gloo", timeout=TIMEOUT) | |
| return Context(world, rank, local) | |