| """Manual data-parallel helpers for 8-GPU training (torchrun). |
| |
| Why manual all-reduce instead of DistributedDataParallel: |
| The training loops here are non-standard for DDP β |
| * FlexQwen3 has a custom forward signature (no attention_mask kwarg) and the |
| per-user cartridge KV-prefix is passed via `self.cache`, NOT through the |
| module args DDP intercepts. |
| * One optimizer step spans MANY forward+backward passes (cross-user grad |
| accumulation; DAPO recomputes logprobs per trajectory). DDP's autograd hooks |
| assume one backward per forward and would all-reduce on every micro-backward, |
| or require `no_sync()` gymnastics that interact badly with `cache.clear()`. |
| So each rank holds a FULL model on its own GPU, trains on a disjoint data shard, |
| and we all-reduce the (tiny β LoRA-only) gradients ONCE right before each step. |
| This reproduces DDP's gradient math exactly while sidestepping every fragility. |
| |
| Collective-safety rule (deadlock avoidance): every rank MUST call each collective |
| the same number of times. Callers guarantee this by (a) truncating per-rank shards |
| to a common length, and (b) gating step/skip decisions on globally-reduced scalars, |
| never on per-rank-local counts. |
| |
| When WORLD_SIZE<=1 (plain `python ...`) every function is a no-op and behaviour is |
| identical to the original single-GPU code. |
| """ |
|
|
| import os |
| from typing import Iterable |
|
|
| import torch |
|
|
| try: |
| import torch.distributed as dist |
| _DIST_IMPORTABLE = True |
| except Exception: |
| dist = None |
| _DIST_IMPORTABLE = False |
|
|
|
|
| def _env_world_size() -> int: |
| try: |
| return int(os.environ.get("WORLD_SIZE", "1")) |
| except ValueError: |
| return 1 |
|
|
|
|
| def setup_distributed(): |
| """Init the process group from torchrun env vars. |
| |
| Returns a dict: {rank, local_rank, world_size, is_distributed}. Safe to call |
| when not launched under torchrun (returns the single-process context). |
| """ |
| world_size = _env_world_size() |
| if not _DIST_IMPORTABLE or world_size <= 1: |
| return {"rank": 0, "local_rank": 0, "world_size": 1, "is_distributed": False} |
|
|
| rank = int(os.environ.get("RANK", "0")) |
| local_rank = int(os.environ.get("LOCAL_RANK", str(rank))) |
| backend = "nccl" if torch.cuda.is_available() else "gloo" |
| if not dist.is_initialized(): |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| from datetime import timedelta |
| timeout_min = int(os.environ.get("NCCL_TIMEOUT_MIN", "20")) |
| dist.init_process_group(backend=backend, timeout=timedelta(minutes=timeout_min)) |
| if torch.cuda.is_available(): |
| torch.cuda.set_device(local_rank) |
| return { |
| "rank": rank, |
| "local_rank": local_rank, |
| "world_size": world_size, |
| "is_distributed": True, |
| } |
|
|
|
|
| def is_initialized() -> bool: |
| return bool(_DIST_IMPORTABLE and dist.is_available() and dist.is_initialized()) |
|
|
|
|
| def get_rank() -> int: |
| return dist.get_rank() if is_initialized() else 0 |
|
|
|
|
| def get_world_size() -> int: |
| return dist.get_world_size() if is_initialized() else 1 |
|
|
|
|
| def is_main_process() -> bool: |
| return get_rank() == 0 |
|
|
|
|
| def barrier(): |
| if is_initialized(): |
| dist.barrier() |
|
|
|
|
| def cleanup_distributed(): |
| if is_initialized(): |
| dist.destroy_process_group() |
|
|
|
|
| def _reduce_device() -> str: |
| return "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
| def all_reduce_value(value, op: str = "sum"): |
| """All-reduce a python scalar across ranks. Returns the reduced python float. |
| |
| op in {"sum","mean","min","max"}. No-op (returns value) when single-process. |
| """ |
| if not is_initialized(): |
| return value |
| t = torch.tensor([float(value)], dtype=torch.float64, device=_reduce_device()) |
| op_map = { |
| "sum": dist.ReduceOp.SUM, |
| "mean": dist.ReduceOp.SUM, |
| "min": dist.ReduceOp.MIN, |
| "max": dist.ReduceOp.MAX, |
| } |
| dist.all_reduce(t, op=op_map[op]) |
| if op == "mean": |
| t /= get_world_size() |
| return t.item() |
|
|
|
|
| def all_reduce_flag(local_flag: bool) -> bool: |
| """Global logical-OR of a boolean across ranks: returns True iff ANY rank passed True. |
| |
| Implemented as MAX over {0.0, 1.0}. Used for OOM synchronization β if any rank hit a |
| CUDA OOM this step, ALL ranks learn it and skip the optimizer step together, keeping |
| the per-step collective count identical on every rank (no NCCL desync). No-op |
| (returns local_flag) when single-process. |
| """ |
| return bool(all_reduce_value(1.0 if local_flag else 0.0, op="max")) |
|
|
|
|
| def all_reduce_floats(values, op: str = "sum"): |
| """All-reduce a LIST of python floats in ONE collective. Returns a python list. |
| |
| Used to reduce many per-MS sum/count scalars at once (e.g. reward_sum/reward_cnt |
| for SM/PM/VM/NM) without issuing one collective per key. The list length and order |
| MUST be identical across ranks (callers build it from a fixed key order). No-op |
| (returns list(values)) when single-process. |
| """ |
| vals = [float(v) for v in values] |
| if not is_initialized() or not vals: |
| return vals |
| t = torch.tensor(vals, dtype=torch.float64, device=_reduce_device()) |
| op_map = {"sum": dist.ReduceOp.SUM, "mean": dist.ReduceOp.SUM, |
| "min": dist.ReduceOp.MIN, "max": dist.ReduceOp.MAX} |
| dist.all_reduce(t, op=op_map[op]) |
| if op == "mean": |
| t /= get_world_size() |
| return t.tolist() |
|
|
|
|
| def _grad_chunk_numel() -> int: |
| """Maximum number of gradient elements per coalesced all-reduce chunk. |
| |
| LoRA runs stay as one collective because their total grad size is far below this. |
| Full-FT Qwen2.5 has ~7.6B trainable elements; one flattened all-reduce would allocate |
| a huge contiguous buffer and enqueue a single 7.6B-element NCCL op. Chunking keeps the |
| collective order deterministic while reducing peak temporary memory and making NCCL |
| progress easier to diagnose. Set MANUAL_DP_GRAD_CHUNK_NUMEL=0 to restore one buffer. |
| """ |
| try: |
| return int(os.environ.get("MANUAL_DP_GRAD_CHUNK_NUMEL", "250000000")) |
| except ValueError: |
| return 250000000 |
|
|
|
|
| def _iter_param_chunks(plist): |
| max_numel = _grad_chunk_numel() |
| if max_numel <= 0: |
| yield plist |
| return |
| chunk = [] |
| n = 0 |
| for p in plist: |
| p_numel = p.grad.numel() |
| if chunk and n + p_numel > max_numel: |
| yield chunk |
| chunk = [] |
| n = 0 |
| chunk.append(p) |
| n += p_numel |
| if chunk: |
| yield chunk |
|
|
|
|
| def all_reduce_grads(params: Iterable[torch.nn.Parameter], op: str = "sum"): |
| """In-place all-reduce of `.grad` over ranks (SUM by default), coalesced in a |
| deterministic set of chunks. |
| |
| π΄ Call AFTER local backward/accumulation and BEFORE grad-clip + optimizer.step, |
| so the clip operates on the synced gradient and every rank steps with identical |
| grads (weights stay bit-identical across ranks). |
| |
| π΄ Coalesced chunks (not one per param): we flatten consecutive grads into contiguous |
| buffers, all_reduce each buffer, then copy back. Two reasons: |
| (1) Correctness/robustness: the chunks are derived solely from the fixed param list |
| and MANUAL_DP_GRAD_CHUNK_NUMEL, so every rank calls the same collectives in the |
| same order. Per-param all_reduce would expose NCCL to param-list drift. |
| (2) Memory: LoRA still uses one small buffer, while full-FT avoids a single |
| 7.6B-element temporary buffer / NCCL op. |
| `params` MUST be the SAME fixed list (same order, same length) on every rank β the |
| caller guarantees this via a name-sorted cached list. grad=None β zero-filled so the |
| buffer layout is identical across ranks even when a rank produced no gradient. |
| """ |
| if not is_initialized(): |
| return |
| plist = list(params) |
| for p in plist: |
| if p.grad is None: |
| p.grad = torch.zeros_like(p) |
| for chunk in _iter_param_chunks(plist): |
| grads = [p.grad for p in chunk] |
| flat = torch._utils._flatten_dense_tensors(grads) |
| dist.all_reduce(flat, op=dist.ReduceOp.SUM) |
| if op == "mean": |
| flat /= get_world_size() |
| for p, synced in zip(chunk, torch._utils._unflatten_dense_tensors(flat, grads)): |
| p.grad.copy_(synced) |
|
|
|
|
| def build_zero_optimizer(params, lr: float, weight_decay: float = 0.0): |
| """Build an AdamW optimizer, ZeRO-1-sharded across ranks when distributed. |
| |
| For FULL fine-tuning the AdamW optimizer state of a 7B model (~90GB fp32 m/v) cannot |
| fit on one 80GB GPU. ZeroRedundancyOptimizer (torch built-in ZeRO stage 1) shards the |
| optimizer STATE across ranks: each rank owns AdamW state for ~1/world_size of the |
| params, runs step() only on its shard, then all_gathers the updated params so every |
| rank ends with identical weights. |
| |
| Compatibility with the existing manual all-reduce scheme: grads are still produced on |
| EVERY param on EVERY rank and synced by all_reduce_grads(op="sum") BEFORE step(). ZeRO |
| does NOT touch gradient computation/sync β it only partitions the optimizer UPDATE. So |
| clip_grad_norm_ over the full param list (identical synced grads on every rank) stays |
| correct and the gradient math is unchanged. (LoRA mode keeps plain AdamW; this helper |
| is only used by the full-FT branch.) |
| |
| Single-process (world_size<=1) β plain AdamW (no ZeRO machinery, identical behaviour). |
| """ |
| plist = list(params) |
| if not is_initialized() or get_world_size() <= 1: |
| return torch.optim.AdamW(plist, lr=lr, weight_decay=weight_decay) |
| from torch.distributed.optim import ZeroRedundancyOptimizer |
| return ZeroRedundancyOptimizer( |
| plist, |
| optimizer_class=torch.optim.AdamW, |
| lr=lr, |
| weight_decay=weight_decay, |
| ) |
|
|
|
|
| def zero_optimizer_full_state_dict(optimizer): |
| """Return the FULL (unsharded) optimizer state_dict on rank 0, None elsewhere. |
| |
| ZeroRedundancyOptimizer shards optimizer state across ranks. consolidate_state_dict(to=0) |
| is a COLLECTIVE (every rank must call it) that gathers all shards onto rank 0. After it, |
| ONLY rank 0 may call state_dict() β non-zero ranks raise "Optimizer state has not been |
| consolidated on this rank". So we consolidate on all ranks but return the dict on rank 0 |
| only (callers save on rank 0 anyway). Plain AdamW (no consolidate) β state_dict() direct. |
| """ |
| if hasattr(optimizer, "consolidate_state_dict"): |
| optimizer.consolidate_state_dict(to=0) |
| return optimizer.state_dict() if get_rank() == 0 else None |
| return optimizer.state_dict() |
|
|