File size: 11,369 Bytes
4968ea3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""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:  # pragma: no cover
    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():
        # 🔴 Collective timeout sized for rank skew, NOT for OOM. DAPO's phase-1 rollout has
        # NO collective — each rank independently runs per_rank_anchors×K rollouts whose
        # sequence lengths (+ flex_attention compile cost) vary, so the fastest rank can
        # reach the phase-2 all_reduce ~10min before the slowest. NCCL's default 600s
        # watchdog would abort on that skew. We set NCCL_TIMEOUT_MIN=20 (step ~14min,
        # measured skew ~10min → 20min covers it with margin). It does NOT need to cover
        # single-rank OOM hangs anymore — those are handled by the OOM-tolerant symmetric
        # skip (all_reduce_flag), so no rank is ever left waiting on a crashed peer. A
        # tighter 20min also means a genuine hang is detected in ~20min, not an hour.
        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)  # collective — all ranks must call
        return optimizer.state_dict() if get_rank() == 0 else None
    return optimizer.state_dict()