File size: 55,593 Bytes
e8bee02 | 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 | """Architecture-preserving correctness fixes and modular A100-SXM4 optimizations.
Never modifies sources/train_a100_wikipedia.py; installs runtime patches cleanly.
Includes L8 upgrades:
- FlashAttention-2 SWA (window_size=(SWA_WINDOW-1, 0)) with natural-log LSE for MoLA
- Async-pipelined 4-owner NVLink broadcasts in sharded NorMuon
- Backward-overlapped dense gradient AllReduce (post-accumulate-grad bucket hooks)
- Optional pre-200B routing balance (ULTRAMEM_BIAS_GAMMA=3.5e-2, clamp[-2.5, 2.5])
and smooth progressive-depth transition
"""
from __future__ import annotations
import math
import queue
import threading
import types
from typing import Dict, List, Optional, Sequence, Tuple
import fsspec
import numpy as np
import pyarrow.parquet as pq
import torch
import torch.distributed as dist
import torch.nn.functional as F
from huggingface_hub import HfApi, hf_hub_url
from tokenizers import Tokenizer
try:
import triton
import triton.language as tl
_HAS_TRITON = True
except Exception:
triton = None
tl = None
_HAS_TRITON = False
try:
from liger_kernel.transformers import LigerFusedLinearCrossEntropyLoss
_HAS_LIGER_CE = True
except Exception:
LigerFusedLinearCrossEntropyLoss = None
_HAS_LIGER_CE = False
try:
from flash_attn import flash_attn_func as _flash_attn_func
_HAS_FLASH_ATTN = True
except Exception:
_flash_attn_func = None
_HAS_FLASH_ATTN = False
if _HAS_TRITON:
@triton.jit
def _triton_ultramem_gather_reduce_fwd_fast(
weight_ptr,
wscale_ptr,
slots_ptr,
weights_ptr,
out_ptr,
N,
n_rows,
D,
M_TOTAL: tl.constexpr,
BLOCK_D: tl.constexpr,
OUT_BF16: tl.constexpr,
USE_FP8: tl.constexpr,
):
"""Skip out-of-shard (slot < 0) and zero-weight entries before any HBM row load."""
pid_n = tl.program_id(0)
if pid_n >= N:
return
pid_d = tl.program_id(1)
tok_i64 = pid_n.to(tl.int64)
offs_d = pid_d.to(tl.int64) * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
tok_m_base = tok_i64 * M_TOTAL
acc = tl.zeros((BLOCK_D,), dtype=tl.float32)
for k in range(M_TOTAL):
slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64)
w_scalar = tl.load(weights_ptr + tok_m_base + k).to(tl.float32)
if (slot >= 0) & (slot < n_rows) & (w_scalar != 0.0):
row_offs = slot * D + offs_d
val = tl.load(weight_ptr + row_offs, mask=mask_d, other=0.0).to(tl.float32)
if USE_FP8:
sc = tl.load(wscale_ptr + slot).to(tl.float32)
w_scalar = w_scalar * sc
acc += val * w_scalar
out_offs = tok_i64 * D + offs_d
if OUT_BF16:
tl.store(out_ptr + out_offs, acc.to(tl.bfloat16), mask=mask_d)
else:
tl.store(out_ptr + out_offs, acc, mask=mask_d)
@triton.jit
def _triton_ultramem_dweights_bwd_fast(
weight_ptr,
wscale_ptr,
slots_ptr,
dv_agg_ptr,
dweights_ptr,
N,
n_rows,
D,
M_TOTAL: tl.constexpr,
BLOCK_D: tl.constexpr,
SINGLE_TILE: tl.constexpr,
OUT_BF16: tl.constexpr,
USE_FP8: tl.constexpr,
):
"""Skip out-of-shard (slot < 0) HBM reads during routing-weight backward."""
pid_n = tl.program_id(0)
if pid_n >= N:
return
tok_i64 = pid_n.to(tl.int64)
tok_d_base = tok_i64 * D
tok_m_base = tok_i64 * M_TOTAL
if SINGLE_TILE:
offs_d = tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32)
for k in range(M_TOTAL):
slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64)
dot = 0.0
if (slot >= 0) & (slot < n_rows):
row_offs = slot * D + offs_d
val = tl.load(weight_ptr + row_offs, mask=mask_d, other=0.0).to(tl.float32)
dot = tl.sum(dv * val, axis=0)
if USE_FP8:
sc = tl.load(wscale_ptr + slot).to(tl.float32)
dot = dot * sc
if OUT_BF16:
tl.store(dweights_ptr + tok_m_base + k, dot.to(tl.bfloat16))
else:
tl.store(dweights_ptr + tok_m_base + k, dot)
else:
for k in range(M_TOTAL):
slot = tl.load(slots_ptr + tok_m_base + k).to(tl.int64)
dot = tl.zeros((), dtype=tl.float32)
if (slot >= 0) & (slot < n_rows):
d_start = 0
while d_start < D:
offs_d = tl.arange(0, BLOCK_D).to(tl.int64) + d_start
mask_d = offs_d < D
dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32)
val = tl.load(weight_ptr + slot * D + offs_d, mask=mask_d, other=0.0).to(tl.float32)
dot += tl.sum(dv * val, axis=0)
d_start += BLOCK_D
if USE_FP8:
sc = tl.load(wscale_ptr + slot).to(tl.float32)
dot = dot * sc
if OUT_BF16:
tl.store(dweights_ptr + tok_m_base + k, dot.to(tl.bfloat16))
else:
tl.store(dweights_ptr + tok_m_base + k, dot)
@triton.jit
def _triton_ultramem_scatter_grad_fast(
inv_ptr,
weights_ptr,
dv_agg_ptr,
g_sum_ptr,
N,
n_unique,
D,
M_TOTAL: tl.constexpr,
BLOCK_D: tl.constexpr,
):
"""Skip out-of-shard (u_row < 0) and zero-weight entries before any atomic_add."""
pid_n = tl.program_id(0)
if pid_n >= N:
return
pid_d = tl.program_id(1)
tok_i64 = pid_n.to(tl.int64)
offs_d = pid_d.to(tl.int64) * BLOCK_D + tl.arange(0, BLOCK_D).to(tl.int64)
mask_d = offs_d < D
tok_d_base = tok_i64 * D
tok_m_base = tok_i64 * M_TOTAL
dv = tl.load(dv_agg_ptr + tok_d_base + offs_d, mask=mask_d, other=0.0).to(tl.float32)
for k in range(M_TOTAL):
u_row = tl.load(inv_ptr + tok_m_base + k).to(tl.int64)
w_scalar = tl.load(weights_ptr + tok_m_base + k).to(tl.float32)
if (u_row >= 0) & (u_row < n_unique) & (w_scalar != 0.0):
g_offs = u_row * D + offs_d
tl.atomic_add(g_sum_ptr + g_offs, dv * w_scalar, mask=mask_d)
class AsyncFineWebStreamLoader:
"""High-throughput document-disjoint FineWeb-Edu streaming loader.
- Rank 0 fetches the fixed held-out validation prefix once and broadcasts it via NCCL.
- Training shards are partitioned across ranks (files[rank::world_size]) with the same
SHA-256 is_validation(doc_id) exclusion filter, cutting HTTP/parquet work by world_size.
- A background producer thread prefetches and pre-tokenizes pinned CPU batches into a
bounded queue so GPUs never stall waiting on HTTP range reads or BPE tokenization.
"""
def __init__(
self,
fineweb_mod,
seq_len: int,
batch_size: int,
device: torch.device,
extra_horizon: int = 2,
prefetch_batches: int = 8,
batch_docs: int = 64,
val_seqs: int = 32,
):
self._fw = fineweb_mod
self.seq_len = int(seq_len)
self.batch_size = int(batch_size)
self.device = device
self.extra_horizon = int(extra_horizon)
self.batch_docs = int(batch_docs)
self.rank = dist.get_rank() if dist.is_initialized() else 0
self.world_size = dist.get_world_size() if dist.is_initialized() else 1
self.tokenizer = Tokenizer.from_file(str(fineweb_mod.TOKENIZER_PATH))
self.eos_id = self.tokenizer.token_to_id("<|endoftext|>")
if self.eos_id is None:
raise ValueError("Tokenizer missing <|endoftext|>")
val_len = val_seqs * (self.seq_len + 1)
val_tensor = torch.empty(val_len, dtype=torch.int32, device=device)
if self.rank == 0:
arr, prompts, val_ids = fineweb_mod.validation_data(self.tokenizer, val_len)
val_tensor.copy_(torch.from_numpy(arr.astype(np.int32)).to(device))
self.val_prompts = prompts
self.validation_ids = val_ids
else:
self.val_prompts = []
self.validation_ids = []
if dist.is_initialized():
dist.broadcast(val_tensor, src=0)
self.data = val_tensor.cpu().numpy().astype(np.uint16)
files_box = [None]
if self.rank == 0:
prefix = "sample/" + fineweb_mod.CONFIG.removeprefix("sample-")
entries = HfApi().list_repo_tree(
fineweb_mod.REPO, path_in_repo=prefix, repo_type="dataset", revision=fineweb_mod.REVISION
)
files_box[0] = sorted(item.path for item in entries if item.path.endswith(".parquet"))
if dist.is_initialized():
dist.broadcast_object_list(files_box, src=0)
all_files = files_box[0]
if not all_files:
raise RuntimeError("No FineWeb-Edu parquet shards found")
if len(all_files) >= self.world_size:
self._rank_files = all_files[self.rank :: self.world_size]
self._shard_by_doc_id = False
else:
self._rank_files = all_files
self._shard_by_doc_id = True
self._stop_event = threading.Event()
self._queue: "queue.Queue[object]" = queue.Queue(maxsize=prefetch_batches)
self._error: Optional[BaseException] = None
self._docs_consumed = 0
self._thread = threading.Thread(target=self._producer_loop, daemon=True)
self._thread.start()
def _iter_rank_docs(self):
fw = self._fw
for path in self._rank_files:
if self._stop_event.is_set():
return
url = hf_hub_url(fw.REPO, path, repo_type="dataset", revision=fw.REVISION)
with fsspec.open(url, "rb", block_size=8 << 20, cache_type="readahead") as remote:
parquet = pq.ParquetFile(remote, pre_buffer=True)
for batch in parquet.iter_batches(batch_size=512, columns=["id", "text"], use_threads=True):
if self._stop_event.is_set():
return
cols = batch.to_pydict()
for doc_id, text in zip(cols["id"], cols["text"]):
if not isinstance(text, str) or not text.strip():
continue
if fw.is_validation(doc_id):
continue
if self._shard_by_doc_id and fw.rank_for_document(doc_id, self.world_size) != self.rank:
continue
yield text
def _producer_loop(self):
span = self.seq_len + self.extra_horizon
needed = self.batch_size * span
buf = np.empty(0, dtype=np.int64)
pending = []
eos = self.eos_id
try:
for text in self._iter_rank_docs():
if self._stop_event.is_set():
return
pending.append(text)
if len(pending) < self.batch_docs:
continue
encs = self.tokenizer.encode_batch(pending, add_special_tokens=False)
self._docs_consumed += len(pending)
pending.clear()
chunks = [buf] if buf.size else []
for e in encs:
arr = np.empty(len(e.ids) + 1, dtype=np.int64)
arr[:-1] = e.ids
arr[-1] = eos
chunks.append(arr)
buf = np.concatenate(chunks) if len(chunks) > 1 else chunks[0]
while buf.size >= needed:
if self._stop_event.is_set():
return
rows = np.ascontiguousarray(buf[:needed].reshape(self.batch_size, span))
buf = buf[needed:]
t = torch.from_numpy(rows)
if self.device.type == "cuda":
t = t.pin_memory()
while not self._stop_event.is_set():
try:
self._queue.put(t, timeout=0.5)
break
except queue.Full:
continue
self._queue.put(StopIteration("FineWeb-Edu training stream exhausted"))
except BaseException as exc:
self._error = exc
self._queue.put(exc)
def next_batch(self):
item = self._queue.get()
if isinstance(item, BaseException):
raise RuntimeError(f"AsyncFineWebStreamLoader failed: {item}") from item
chunk = item.to(self.device, non_blocking=self.device.type == "cuda")
return chunk[:, : self.seq_len], [
chunk[:, k : k + self.seq_len] for k in range(1, self.extra_horizon + 1)
]
def close(self):
self._stop_event.set()
while not self._queue.empty():
try:
self._queue.get_nowait()
except queue.Empty:
break
if self._thread.is_alive():
self._thread.join(timeout=2.0)
def _make_fa2_swa_runner(swa_window: int):
"""Build a torch.compiler.disable-wrapped FlashAttention-2 SWA runner returning (o_bhtd, lse_bht).
Isolating ONLY the FA2 CUDA kernel with @torch.compiler.disable preserves full Inductor
fusion on QKV+RoPE before FA2 and MoLA+OProj+FFN after FA2, with zero flash-attn
version-specific private API dependencies.
"""
disable_dec = (
torch.compiler.disable
if (hasattr(torch, "compiler") and hasattr(torch.compiler, "disable"))
else (lambda fn: fn)
)
win = (int(swa_window) - 1, 0)
@disable_dec
def _run_fa2_swa_lse(q_bhtd: torch.Tensor, k_bhtd: torch.Tensor, v_bhtd: torch.Tensor):
q_c = q_bhtd.transpose(1, 2).contiguous()
k_c = k_bhtd.transpose(1, 2).contiguous()
v_c = v_bhtd.transpose(1, 2).contiguous()
out_bthd, lse_bht, _ = _flash_attn_func(
q_c,
k_c,
v_c,
dropout_p=0.0,
causal=True,
window_size=win,
return_attn_probs=True,
)
return out_bthd.transpose(1, 2), lse_bht
return _run_fa2_swa_lse
class OverlappedDenseAllReduce:
"""Overlap dense parameter AllReduce directly behind backward() via post-accumulate hooks.
Usage in runner loop:
ar_mgr = install_overlapped_dense_allreduce(model, world_size, bucket_mb=32.0)
for micro_idx in range(grad_accum):
ar_mgr.set_sync(micro_idx == grad_accum - 1)
(loss / grad_accum).backward()
ar_mgr.finish() # waits on in-flight NCCL buckets + averages any straggler grads
"""
def __init__(self, model: torch.nn.Module, world_size: int, bucket_mb: float = 32.0):
self.model = model
self.world_size = int(world_size)
self.inv_world = 1.0 / float(max(1, self.world_size))
self.enabled = dist.is_initialized() and self.world_size > 1
self._sync_active = True
self._handles = []
self._buckets: List[List[torch.nn.Parameter]] = []
self._bucket_ready: List[int] = []
self._param_to_bucket: Dict[int, int] = {}
self._synced_param_ids: set = set()
self._hooks = []
if not self.enabled:
return
# Group trainable dense params in reverse order (approx backward order) by dtype
bucket_bytes = max(1, int(bucket_mb * 1024 * 1024))
by_dtype: Dict[torch.dtype, List[torch.nn.Parameter]] = {}
for p in reversed(list(model.parameters())):
if p.requires_grad:
by_dtype.setdefault(p.dtype, []).append(p)
for _, plist in by_dtype.items():
cur: List[torch.nn.Parameter] = []
cur_b = 0
for p in plist:
pb = p.numel() * p.element_size()
if cur and (cur_b + pb > bucket_bytes):
self._register_bucket(cur)
cur, cur_b = [], 0
cur.append(p)
cur_b += pb
if cur:
self._register_bucket(cur)
# Register post-accumulate hooks
for b_idx, plist in enumerate(self._buckets):
for p in plist:
self._param_to_bucket[id(p)] = b_idx
h = p.register_post_accumulate_grad_hook(self._make_hook(b_idx))
self._hooks.append(h)
def _register_bucket(self, plist: List[torch.nn.Parameter]):
self._buckets.append(plist)
self._bucket_ready.append(0)
def _make_hook(self, b_idx: int):
def _hook(param: torch.Tensor):
if not self._sync_active:
return
self._bucket_ready[b_idx] += 1
if self._bucket_ready[b_idx] == len(self._buckets[b_idx]):
grads = [p.grad for p in self._buckets[b_idx] if p.grad is not None]
if grads:
flat = torch._utils._flatten_dense_tensors(grads)
work = dist.all_reduce(flat, op=dist.ReduceOp.SUM, async_op=True)
self._handles.append((grads, flat, work))
for p in self._buckets[b_idx]:
if p.grad is not None:
self._synced_param_ids.add(id(p))
return _hook
def set_sync(self, active: bool):
"""Enable on final microbatch of step; resets bucket counters."""
self._sync_active = bool(active)
if active and self.enabled:
for i in range(len(self._bucket_ready)):
self._bucket_ready[i] = 0
self._handles.clear()
self._synced_param_ids.clear()
def finish(self):
"""Wait for all overlapped buckets and AllReduce any partial buckets (e.g. unused params)."""
if not self.enabled:
return
# Wait on in-flight overlapped buckets
for grads, flat, work in self._handles:
work.wait()
flat.mul_(self.inv_world)
for g, synced in zip(grads, torch._utils._unflatten_dense_tensors(flat, grads)):
g.copy_(synced)
self._handles.clear()
# Sweep any dense params whose bucket didn't fire (e.g. conditional/unused params in bucket)
leftover: Dict[torch.dtype, List[torch.Tensor]] = {}
for p in self.model.parameters():
if p.grad is not None and id(p) not in self._synced_param_ids:
leftover.setdefault(p.grad.dtype, []).append(p.grad)
if leftover:
in_flight = []
for _, grads in leftover.items():
flat = torch._utils._flatten_dense_tensors(grads)
work = dist.all_reduce(flat, op=dist.ReduceOp.SUM, async_op=True)
in_flight.append((grads, flat, work))
for grads, flat, work in in_flight:
work.wait()
flat.mul_(self.inv_world)
for g, synced in zip(grads, torch._utils._unflatten_dense_tensors(flat, grads)):
g.copy_(synced)
self._synced_param_ids.clear()
def remove(self):
for h in self._hooks:
h.remove()
self._hooks.clear()
def install_overlapped_dense_allreduce(
model: torch.nn.Module, world_size: int, bucket_mb: float = 32.0
) -> OverlappedDenseAllReduce:
"""Attach backward-overlapped dense AllReduce hooks to `model`."""
return OverlappedDenseAllReduce(model, world_size=world_size, bucket_mb=bucket_mb)
def apply_all_patches(
source,
*,
fast_sparse: bool = False,
int32_indices: bool = False,
fused_ce: bool = False,
fast_muon_scalars: bool = False,
async_engram: bool = False,
use_fa2_swa: bool = False,
strong_ultramem_balance: bool = False,
smooth_prog_depth: bool = False,
):
"""Apply baseline correctness fixes plus selected A100-SXM4 speed & stability optimizations."""
# 1. Always fix _DistAllToAllFn contiguous buffer allocation (source bug on 4 GPUs)
class ContiguousAllToAll(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
x_c = x.contiguous()
out = torch.empty_like(x_c, memory_format=torch.contiguous_format)
dist.all_to_all_single(out, x_c)
return out
@staticmethod
def backward(ctx, grad_out):
g_c = grad_out.contiguous()
grad_in = torch.empty_like(g_c, memory_format=torch.contiguous_format)
dist.all_to_all_single(grad_in, g_c)
return grad_in
source._DistAllToAllFn = ContiguousAllToAll
# 2. Optional int32 Engram index all_gather (max row = 11.7M << 2^31)
if int32_indices:
def engram_prefetch_int32(self, token_ids):
indices = self.compute_ngram_indices(token_ids)
if self.world_size == 1 or not source.dist_is_active():
retrieved = self.sparse_table.lookup(indices)
return retrieved.reshape(token_ids.size(0), token_ids.size(1), source.D_STREAM)
B, T = token_ids.shape
idx32 = indices.to(torch.int32).contiguous()
all_idx32 = torch.empty((self.world_size, B, T, self.n_heads), device=indices.device, dtype=torch.int32)
dist.all_gather_into_tensor(all_idx32, idx32)
local_idx = all_idx32[..., self.head_start : self.head_end].to(torch.long) - self.local_row_offset
local_emb = self.sparse_table.lookup(local_idx)
gathered_emb = source._DistAllToAllFn.apply(local_emb)
return gathered_emb.permute(1, 2, 0, 3, 4).reshape(B, T, source.D_STREAM)
source.EngramConditionalMemory.prefetch_embeddings = engram_prefetch_int32
# 3. Fast zero-skip Triton UltraMemV2 kernels & coalescing
if fast_sparse and _HAS_TRITON:
source._triton_ultramem_gather_reduce_fwd = _triton_ultramem_gather_reduce_fwd_fast
source._triton_ultramem_dweights_bwd = _triton_ultramem_dweights_bwd_fast
source._triton_ultramem_scatter_grad = _triton_ultramem_scatter_grad_fast
def coalesce_fast(
grad_buffer: Sequence[Tuple[torch.Tensor, ...]],
dim: int,
device: Optional[torch.device] = None,
chunk_tokens: int = 256,
) -> Tuple[torch.Tensor, torch.Tensor]:
if not grad_buffer:
dev = device if device is not None else torch.device("cpu")
return (
torch.empty((0,), device=dev, dtype=torch.long),
torch.empty((0, dim), device=dev, dtype=torch.float32),
)
compact_entries = []
legacy_entries = []
for item in grad_buffer:
if len(item) == 3:
compact_entries.append((item[0], item[1], item[2]))
elif len(item) == 2:
legacy_entries.append((item[0], item[1]))
else:
raise ValueError(f"Unsupported grad_buffer entry length: {len(item)}")
flat_idx_parts = []
compact_counts = []
for slots_2d, weights_2d, _ in compact_entries:
s_eff = torch.where(weights_2d != 0, slots_2d.to(torch.long), -1)
flat_s = s_eff.reshape(-1)
flat_idx_parts.append(flat_s)
compact_counts.append(flat_s.numel())
legacy_counts = []
for flat_idx, _ in legacy_entries:
flat_s = flat_idx.reshape(-1).to(torch.long)
flat_idx_parts.append(flat_s)
legacy_counts.append(flat_s.numel())
all_idx = flat_idx_parts[0] if len(flat_idx_parts) == 1 else torch.cat(flat_idx_parts, dim=0)
dev = device if device is not None else all_idx.device
u_idx, inv = torch.unique(all_idx, return_inverse=True)
if u_idx.numel() > 0 and int(u_idx[0].item()) < 0:
u_idx = u_idx[1:]
inv = inv - 1
n_unique = u_idx.numel()
if n_unique == 0:
return (
torch.empty((0,), device=dev, dtype=torch.long),
torch.empty((0, dim), device=dev, dtype=torch.float32),
)
g_sum = torch.zeros((n_unique, dim), device=dev, dtype=torch.float32)
offset = 0
for (slots_2d, weights_2d, dv_agg), count in zip(compact_entries, compact_counts):
N, M = slots_2d.shape
inv_2d = inv[offset : offset + count].view(N, M)
offset += count
if N == 0:
continue
if g_sum.is_cuda and dv_agg.is_cuda and weights_2d.is_cuda:
block_d = source._select_block_d(dim)
grid = (N, triton.cdiv(dim, block_d))
_triton_ultramem_scatter_grad_fast[grid](
inv_2d.contiguous(),
weights_2d.contiguous(),
dv_agg.contiguous(),
g_sum,
N,
n_unique,
dim,
M_TOTAL=M,
BLOCK_D=block_d,
num_warps=8 if block_d >= 512 else 4,
)
else:
for n0 in range(0, N, chunk_tokens):
n1 = min(N, n0 + chunk_tokens)
i_c = inv_2d[n0:n1].reshape(-1)
w_c = weights_2d[n0:n1].float().reshape(-1)
valid = (i_c >= 0) & (w_c != 0)
if valid.any():
dv_c = dv_agg[n0:n1].float().unsqueeze(1).expand(-1, M, -1).reshape(-1, dim)
g_sum.index_add_(0, i_c[valid], dv_c[valid] * w_c[valid].unsqueeze(-1))
for (flat_idx, grad_out), count in zip(legacy_entries, legacy_counts):
inv_c = inv[offset : offset + count]
offset += count
if count == 0:
continue
valid = inv_c >= 0
if valid.all():
g_sum.index_add_(0, inv_c, grad_out.reshape(-1, dim).float())
elif valid.any():
g_sum.index_add_(0, inv_c[valid], grad_out.reshape(-1, dim).float()[valid])
return u_idx, g_sum
source.coalesce_compact_sparse_grads = coalesce_fast
else:
orig_sparse_step = source.GDDR7SparseTable.sparse_adam_step
def sparse_step_filtered(self, *args, **kwargs):
filtered = []
for entry in self.grad_buffer:
if len(entry) != 3:
filtered.append(entry)
continue
slots, weights, dv = entry
valid = weights != 0
elig = slots[valid]
if elig.numel() == 0:
continue
filtered.append((torch.where(valid, slots, elig[0]), weights, dv))
self.grad_buffer[:] = filtered
return orig_sparse_step(self, *args, **kwargs)
source.GDDR7SparseTable.sparse_adam_step = sparse_step_filtered
# 4. UltraMemV2 forward_flat: static MoD training + padded causal eval + sentinel -1 + int32 slots
def bridge_forward_flat(self, x_flat):
eval_valid = getattr(self, "_eval_valid_mask", None)
route_fn = (
self._route_flat_compiled
if (self.training and self._route_flat_compiled is not None)
else self._route_and_score_flat
)
h, sr_sub, sc_sub, idx_r, idx_c, qr_mean_raw, qc_mean_raw = route_fn(x_flat)
inv_temp = (1.0 / torch.exp(self.log_temp).clamp(0.05, 10.0)).view(1, self.n_heads, 1).float()
_, sub_r, sub_c, weights_f32 = source.fused_tdqkr_tucker_topk(
sr_sub, sc_sub, self.tucker_core.float(), inv_temp, topk=self.topk
)
real_r = torch.gather(idx_r, dim=-1, index=sub_r)
real_c = torch.gather(idx_c, dim=-1, index=sub_c)
global_slots = real_r * self.grid_k + real_c + self.head_offsets.view(1, self.n_heads, 1)
weights = weights_f32.to(h.dtype)
if eval_valid is not None:
weights = weights * eval_valid[:, None, None].to(h.dtype)
if self.training and torch.is_grad_enabled():
with torch.no_grad():
H = self.n_heads
ir = idx_r.permute(1, 0, 2).reshape(H, -1)
ic = idx_c.permute(1, 0, 2).reshape(H, -1)
ones = torch.ones_like(ir, dtype=torch.float32)
self.step_c_row.scatter_add_(1, ir, ones)
self.step_c_col.scatter_add_(1, ic, ones)
self.step_q_sum_r.add_(qr_mean_raw.sum(dim=1))
self.step_q_sum_c.add_(qc_mean_raw.sum(dim=1))
self.step_tok_count += x_flat.size(0)
if self.world_size == 1 or not source.dist_is_active():
slots_arg = global_slots if not fast_sparse else torch.where(weights != 0, global_slots, -1)
v_agg = source.fused_ultramem_gather_reduce(
self.sparse_table.weight,
slots_arg,
weights,
self.sparse_table.grad_buffer if torch.is_grad_enabled() else None,
w_scale=(self.sparse_table.w_scale if self.sparse_table.use_fp8 else None),
)
else:
N_loc = global_slots.size(0)
if int32_indices:
g_s32 = global_slots.to(torch.int32).contiguous()
all_s32 = torch.empty((self.world_size, *g_s32.shape), device=g_s32.device, dtype=torch.int32)
dist.all_gather_into_tensor(all_s32, g_s32)
all_slots = all_s32.to(torch.long)
else:
all_slots = torch.empty(
(self.world_size, *global_slots.shape),
device=global_slots.device,
dtype=global_slots.dtype,
)
dist.all_gather_into_tensor(all_slots, global_slots.contiguous())
all_weights = source._DistAllGatherFn.apply(weights)
in_shard = (all_slots >= self.shard_start) & (all_slots < self.shard_end)
if fast_sparse:
local_slots = torch.where(in_shard, all_slots - self.shard_start, -1)
local_weights = all_weights * in_shard.to(all_weights.dtype)
else:
local_slots = (all_slots - self.shard_start).clamp(0, self.local_slots - 1)
local_weights = all_weights * in_shard.to(all_weights.dtype)
v_partial_flat = source.fused_ultramem_gather_reduce(
self.sparse_table.weight,
local_slots.reshape(self.world_size * N_loc, self.n_heads, self.topk),
local_weights.reshape(self.world_size * N_loc, self.n_heads, self.topk),
self.sparse_table.grad_buffer if torch.is_grad_enabled() else None,
w_scale=(self.sparse_table.w_scale if self.sparse_table.use_fp8 else None),
)
v_agg = source._DistReduceScatterSumFn.apply(
v_partial_flat.view(self.world_size, N_loc, self.dv)
)
proj_fn = (
self._proj_flat_compiled
if (self.training and self._proj_flat_compiled is not None)
else self._gate_and_project_flat
)
return proj_fn(h, v_agg), None
source.UltraMemV2TDQKRBridge.forward_flat = bridge_forward_flat
# 5. ReversibleReasoningBlock.forward: exact MoD top-25% in training, strictly causal padded threshold in eval
def block_forward_mod_causal_eval(
self,
x1,
x2,
a1=None,
a2=None,
bridge=None,
collect_telemetry=False,
cached_masks=None,
contraction_gate=None,
):
if self.swa is None:
bm, tm = None, None
elif cached_masks is not None:
bm, tm = cached_masks
else:
bm, tm = self.swa.prepare_mask(x1.shape[1], x1.device, self.qkv_fg_fused.weight.dtype)
if self.use_anchor_inject and a1 is not None:
lam1 = torch.exp(-F.softplus(self.zoh_log_decay_1.float()))
lam2 = torch.exp(-F.softplus(self.zoh_log_decay_2.float()))
g1 = torch.sigmoid(self.anchor_gate_1.float())
g2 = torch.sigmoid(self.anchor_gate_2.float())
x1 = source.fused_orthoinj_zoh(x1, a1, lam1, g1, eps=source.EPS)
x2 = source.fused_orthoinj_zoh(x2, a2, lam2, g2, eps=source.EPS)
fn = (
self._dense_step_compiled
if (self.training and self._dense_step_compiled is not None)
else self._dense_step_impl
)
tala_kv = getattr(self, "_active_tala_kv", None)
if tala_kv is not None:
y1, xp2, ffn_out, h_ffn_mg = fn(x1, x2, bm, tm, tala_kv[0], tala_kv[1])
else:
y1, xp2, ffn_out, h_ffn_mg = fn(x1, x2, bm, tm)
dt = x1.dtype
aux_loss = None
if self.use_gated_mem and bridge is not None and h_ffn_mg is not None:
c_flat = contraction_gate.reshape(-1) if contraction_gate is not None else None
eff_score = source.fused_mod_gate_score(
h_ffn_mg.reshape(-1, source.D_STREAM),
self.mem_need_gate.weight,
self.mem_need_gate.bias,
c_flat,
)
n_tok = eff_score.numel()
if self.training:
k_tok = max(1, int(n_tok * source.MEM_CAPACITY_FRAC))
top_g, top_idx = torch.topk(eff_score, k=k_tok, sorted=False)
h_sel = y1.reshape(-1, source.D_STREAM).index_select(0, top_idx)
m_sel, aux_loss = bridge.forward_flat(h_sel)
if torch.is_grad_enabled():
is_sel = torch.zeros_like(eff_score, dtype=torch.float32)
is_sel.scatter_(0, top_idx, 1.0)
gate_bce = F.binary_cross_entropy(
eff_score.float().clamp(1e-6, 1.0 - 1e-6), is_sel
)
aux_loss = 0.05 * gate_bce
with torch.no_grad():
self.eval_thr.lerp_(top_g.min().detach().float(), 0.05)
ffn_out = source.fused_mod_scaled_scatter_add(
ffn_out.reshape(-1, source.D_STREAM),
top_idx,
top_g,
bridge.bridge_scale,
m_sel,
inplace=False,
).view_as(ffn_out)
if collect_telemetry:
with torch.no_grad():
self.last_mem_gate_mean = float(eff_score.mean().item())
self.last_mem_active_frac = float(k_tok / max(1, n_tok))
b_scale_f = float(bridge.bridge_scale.float().item())
b_rms = (
(top_g.float().pow(2) * m_sel.float().pow(2).mean(dim=-1))
.mean()
.sqrt()
.item()
* abs(b_scale_f)
)
f_rms = ffn_out.float().pow(2).mean().sqrt().clamp_min(1e-6).item()
bridge.last_bridge_rms_ratio = float(b_rms / f_rms)
else:
selected = torch.nonzero(eff_score > self.eval_thr, as_tuple=False).flatten()
local_count = selected.numel()
if source.dist_is_active():
padded_t = torch.tensor(local_count, device=y1.device, dtype=torch.int64)
dist.all_reduce(padded_t, op=dist.ReduceOp.MAX)
padded_count = int(padded_t.item())
else:
padded_count = local_count
if padded_count > 0:
valid = torch.arange(padded_count, device=y1.device) < local_count
if local_count < padded_count:
indices = torch.cat(
(selected, torch.zeros(padded_count - local_count, dtype=selected.dtype, device=y1.device))
)
else:
indices = selected
h_sel = y1.reshape(-1, source.D_STREAM).index_select(0, indices)
bridge._eval_valid_mask = valid
try:
m_sel, _ = bridge.forward_flat(h_sel)
finally:
bridge._eval_valid_mask = None
if local_count > 0:
gates = eff_score.index_select(0, selected)
ffn_out = source.fused_mod_scaled_scatter_add(
ffn_out.reshape(-1, source.D_STREAM),
selected,
gates,
bridge.bridge_scale,
m_sel[:local_count],
inplace=False,
).view_as(ffn_out)
y2 = xp2 + self.scale_2.to(dt) * ffn_out
if self.use_sandwich_norm:
y2 = source.rms_norm(y2, self.stream_norm_2, out_dtype=dt)
return y1, y2, aux_loss
source.ReversibleReasoningBlock.forward = block_forward_mod_causal_eval
# 6. Optional FlashAttention-2 SWA (window_size=(SWA_WINDOW-1, 0)) replacing Triton flex_attention
if use_fa2_swa and _HAS_FLASH_ATTN:
fa2_runner = _make_fa2_swa_runner(source.SWA_WINDOW)
orig_prepare_mask = source.HiSASlidingWindowAttention.prepare_mask
orig_run_flex_lse = source.HiSASlidingWindowAttention._run_flex_lse
def prepare_mask_fa2(self, T, device, dtype):
if device.type == "cuda" and dtype in (torch.bfloat16, torch.float16):
# Non-None sentinel routes HiSASlidingWindowAttention.forward straight to _run_flex_lse + MoLA
return "fa2_swa", None
return orig_prepare_mask(self, T, device, dtype)
def run_fa2_or_flex_lse(self, q, k, v, block_mask):
if block_mask == "fa2_swa" and q.is_cuda and q.dtype in (torch.bfloat16, torch.float16):
return fa2_runner(q, k, v)
return orig_run_flex_lse(self, q, k, v, block_mask)
source.HiSASlidingWindowAttention.prepare_mask = prepare_mask_fa2
source.HiSASlidingWindowAttention._run_flex_lse = run_fa2_or_flex_lse
# 7. Optional Fused Single-Pass Liger CE for Main + ECHO + r_mid
if fused_ce and _HAS_LIGER_CE:
_liger_none = LigerFusedLinearCrossEntropyLoss(reduction="none")
def forward_train_fused_liger(
self,
input_ids,
target_horizons,
n_shared_iters,
dds_depth=source.ECHO_FIXED_DEPTH,
echo_batch_frac=source.ECHO_BATCH_FRAC,
tbptt_iters=source.TBPTT_BACKPROP_ITERS,
):
h_backbone, aux_loss, h_mid_out = self.forward_backbone(
input_ids, n_shared_iters=n_shared_iters, tbptt_iters=tbptt_iters
)
if echo_batch_frac > 0.0 and dds_depth == 1 and self._liger_ce is not None:
b_echo = max(1, int(round(input_ids.size(0) * echo_batch_frac)))
h_echo_in = h_backbone[:b_echo]
future_embs = [self.embed_tokens(target_horizons[0][:b_echo])]
horizon_states = self.echo(self.coda[-1], h_echo_in, future_embs)
norm_fn = (
self._final_norm_compiled
if (self.training and self._final_norm_compiled is not None)
else self._apply_final_norm
)
parts_h = [h_backbone, horizon_states[0]]
parts_t = [target_horizons[0], target_horizons[1][:b_echo]]
if h_mid_out is not None:
parts_h.append(h_mid_out)
parts_t.append(target_horizons[0][: h_mid_out.size(0)])
h_norm = norm_fn(torch.cat(parts_h, dim=0))
h_flat = h_norm.reshape(-1, source.D_VOCAB)
t_flat = torch.cat(parts_t, dim=0).reshape(-1)
losses = _liger_none(self.tok_emb.weight, h_flat, t_flat)
T_seq = h_backbone.size(1)
n_main = h_backbone.size(0) * T_seq
n_echo = horizon_states[0].size(0) * T_seq
lm_loss = losses[:n_main].mean()
echo_loss = losses[n_main : n_main + n_echo].mean()
rmid_loss = losses[n_main + n_echo :].mean() if h_mid_out is not None else None
total_loss = lm_loss + source.ECHO_LOSS_COEFF * echo_loss + aux_loss
if rmid_loss is not None:
mono_hinge = F.relu(lm_loss - rmid_loss.detach() + 0.01)
total_loss = (
total_loss
+ source.RMID_LOSS_COEFF * rmid_loss
+ source.MONO_LOSS_COEFF * mono_hinge
)
return total_loss, {
"lm_loss": lm_loss.detach(),
"echo_loss": echo_loss.detach(),
"aux_loss": aux_loss.detach(),
"total_loss": total_loss.detach(),
}
return self._orig_forward_train(
input_ids,
target_horizons,
n_shared_iters=n_shared_iters,
dds_depth=dds_depth,
echo_batch_frac=echo_batch_frac,
tbptt_iters=tbptt_iters,
)
if not hasattr(source.L2GDDR7HybridLanguageModel, "_orig_forward_train"):
source.L2GDDR7HybridLanguageModel._orig_forward_train = (
source.L2GDDR7HybridLanguageModel.forward_train
)
source.L2GDDR7HybridLanguageModel.forward_train = forward_train_fused_liger
# 8. Optional Muon/AdamW scalar hoisting
if fast_muon_scalars:
@torch.no_grad()
def fast_muon_step(self, lr_scale=1.0):
self.step_count += 1
lr_a = self.lr_adamw * lr_scale
for p in self.params_2d:
if p.grad is None:
continue
g = p.grad.float()
st = self.muon_state[id(p)]
m = self.dequantize_int8_blockwise(st["q_mom"], st["scales"], self.block_size, p.shape)
m.mul_(self.momentum).add_(g)
st["q_mom"], st["scales"] = self.quantize_int8_blockwise(m.reshape(-1), self.block_size)
u_in = (g + self.momentum * m) if self.nesterov else m
lr_p = st["lr_base"] * lr_scale
ortho = self._ns5_fn(u_in, self.ns_steps)
v_row = st["v_row"]
v_row.mul_(0.95).add_(ortho.pow(2).mean(dim=-1), alpha=0.05)
v_hat = v_row / (1.0 - 0.95 ** self.step_count)
ortho = ortho / (v_hat.sqrt().unsqueeze(-1) + 1e-8)
rms_scale = (0.2 * math.sqrt(p.numel())) / ortho.norm().clamp_min(1e-8)
p_fp32 = p.float()
if self.weight_decay > 0.0:
p_fp32.sub_(p_fp32 * (ortho * p_fp32 >= 0.0).float(), alpha=lr_p * self.weight_decay)
p_fp32.add_(ortho * (-lr_p * rms_scale))
source.write_back_(p, p_fp32)
if self.adamw_fp32_opt is not None:
for pg in self.adamw_fp32_opt.param_groups:
pg["lr"] = lr_a * pg.get("lr_mult", 1.0)
self.adamw_fp32_opt.step()
if self.params_1d_bf16:
b1, b2 = self.betas
bc1 = 1.0 - b1 ** self.step_count
bc2 = 1.0 - b2 ** self.step_count
dev = self.params_1d_bf16[0].device
lr_t = torch.tensor(lr_a, device=dev, dtype=torch.float32)
bc1_t = torch.tensor(bc1, device=dev, dtype=torch.float32)
bc2_t = torch.tensor(bc2, device=dev, dtype=torch.float32)
for p in self.params_1d_bf16:
if p.grad is None:
continue
st = self.adamw_bf16_state[id(p)]
p.copy_(
self._adamw_bf16_fn(
p, p.grad.float(), st["m"], st["v"], lr_t, self.weight_decay, b1, b2, bc1_t, bc2_t
)
)
source.Muon8BitWithAdamW.step = fast_muon_step
if async_engram:
orig_init = source.L2GDDR7HybridLanguageModel.__init__
def init_with_engram_stream(self, *args, **kwargs):
orig_init(self, *args, **kwargs)
dev = self.tok_emb.weight.device
if dev.type == "cuda" and self._engram_stream is None:
self._engram_stream = torch.cuda.Stream(device=dev)
source.L2GDDR7HybridLanguageModel.__init__ = init_with_engram_stream
# 9. Optional pre-200B UltraMemV2 stronger load balancing (fixes 96x MaxLoad)
if strong_ultramem_balance:
source.ULTRAMEM_BIAS_GAMMA = 3.5e-2
orig_update_bias = source.UltraMemV2TDQKRBridge.update_routing_bias_and_ema
@torch.no_grad()
def update_bias_wider_clamp(self, gamma=None, collect_telemetry=False):
if gamma is None:
gamma = source.ULTRAMEM_BIAS_GAMMA
if self.step_tok_count == 0:
return
tok_count_eff = float(self.step_tok_count)
if self.world_size > 1 and source.dist_is_active():
dist.all_reduce(self.step_c_row, op=dist.ReduceOp.SUM)
dist.all_reduce(self.step_c_col, op=dist.ReduceOp.SUM)
dist.all_reduce(self.step_q_sum_r, op=dist.ReduceOp.SUM)
dist.all_reduce(self.step_q_sum_c, op=dist.ReduceOp.SUM)
tok_count_eff *= float(self.world_size)
if gamma > 0.0:
avg_r = self.step_c_row.mean(dim=-1, keepdim=True)
avg_c = self.step_c_col.mean(dim=-1, keepdim=True)
ratio_r = self.step_c_row / (avg_r + 1e-6)
ratio_c = self.step_c_col / (avg_c + 1e-6)
delta_r = torch.where(ratio_r > 1.0, -(ratio_r - 1.0).clamp(max=6.0), 1.0 - ratio_r)
delta_c = torch.where(ratio_c > 1.0, -(ratio_c - 1.0).clamp(max=6.0), 1.0 - ratio_c)
self.b_row.add_(gamma * delta_r)
self.b_col.add_(gamma * delta_c)
self.b_row.sub_(self.b_row.mean(dim=-1, keepdim=True))
self.b_col.sub_(self.b_col.mean(dim=-1, keepdim=True))
self.b_row.clamp_(-2.5, 2.5)
self.b_col.clamp_(-2.5, 2.5)
self.ema_qr_mean.lerp_(self.step_q_sum_r / tok_count_eff, 0.05)
self.ema_qc_mean.lerp_(self.step_q_sum_c / tok_count_eff, 0.05)
if collect_telemetry:
p_r = self.step_c_row / self.step_c_row.sum(dim=-1, keepdim=True).clamp_min(1.0)
p_c = self.step_c_col / self.step_c_col.sum(dim=-1, keepdim=True).clamp_min(1.0)
p_avg = 0.5 * (p_r + p_c).clamp_min(1e-12)
ent = -(p_avg * p_avg.log()).sum(dim=-1).mean().item()
self.last_entropy_norm = float(ent / math.log(self.grid_k))
self.last_max_load_ratio = float(max(p_r.max().item(), p_c.max().item()) * self.grid_k)
self.step_c_row.zero_()
self.step_c_col.zero_()
self.step_q_sum_r.zero_()
self.step_q_sum_c.zero_()
self.step_tok_count = 0
source.UltraMemV2TDQKRBridge.update_routing_bias_and_ema = update_bias_wider_clamp
# 10. Optional smoother progressive-depth transition (reduces S1->S3 spike & 32L-40L StepRMS drift)
if smooth_prog_depth:
source.CONTRACTION_REG_COEFF = 0.01
source.PROGRESSIVE_DEPTH_STAGES = (
(0.55, 2, (3, 4, 5, 7), (0.28, 0.37, 0.30, 0.05), "S1-10L+probe"),
(0.65, 3, (3, 5, 7, 9, 11), (0.12, 0.22, 0.32, 0.22, 0.12), "S2-16L"),
(0.90, 4, source.PLN_ITER_BUCKETS, source.DEPTH_BUCKET_PROBS_MAIN, "S3-24L"),
(1.01, 4, source.PLN_ITER_BUCKETS, source.DEPTH_BUCKET_PROBS_ANNEAL, "S4-26L"),
)
return source
def install_sharded_muon(source, optimizer):
"""Shard NorMuon 2D updates and BF16 tok_emb AdamW updates across ranks over NVLink.
Uses async-pipelined dist.broadcast(async_op=True) across all 4 owner buckets to
saturate full-duplex NVLink instead of serializing owners 0 -> 3.
"""
if not dist.is_initialized() or dist.get_world_size() <= 1:
return
rank = dist.get_rank()
world_size = dist.get_world_size()
loads = [0] * world_size
rank_buckets = [[] for _ in range(world_size)]
for p in sorted(optimizer.params_2d, key=lambda t: t.numel(), reverse=True):
owner = int(min(range(world_size), key=lambda r: loads[r]))
rank_buckets[owner].append(p)
loads[owner] += p.numel()
optimizer._sharded_rank_buckets = rank_buckets
optimizer._sharded_rank = rank
optimizer._sharded_world_size = world_size
local_bf16_slices = {}
for p in optimizer.params_1d_bf16:
if p.ndim == 2 and (p.size(0) % world_size == 0):
chunk = p.size(0) // world_size
r0, r1 = rank * chunk, (rank + 1) * chunk
st = optimizer.adamw_bf16_state[id(p)]
st["m"] = st["m"][r0:r1].contiguous()
st["v"] = st["v"][r0:r1].contiguous()
local_bf16_slices[id(p)] = (r0, r1)
optimizer._sharded_bf16_slices = local_bf16_slices
def _muon_post_ns(p_data, ortho, v_row, lr_p, wd, bc_v, rms_target):
v_row.mul_(0.95).add_(ortho.pow(2).mean(dim=-1), alpha=0.05)
v_hat = v_row / bc_v
o_normed = ortho / (v_hat.sqrt().unsqueeze(-1) + 1e-8)
rms_scale = rms_target / o_normed.norm().clamp_min(1e-8)
p_fp32 = p_data.float()
if wd > 0.0:
p_fp32 = p_fp32 - (lr_p * wd) * p_fp32 * (o_normed * p_fp32 >= 0.0).float()
return p_fp32 - (lr_p * rms_scale) * o_normed
post_ns_fn = (
torch.compile(_muon_post_ns, mode="default", dynamic=True)
if (source.USE_TORCH_COMPILE and hasattr(torch, "compile"))
else _muon_post_ns
)
@torch.no_grad()
def sharded_step(self, lr_scale=1.0):
self.step_count += 1
lr_a = self.lr_adamw * lr_scale
bc_v = 1.0 - 0.95 ** self.step_count
# 1. Each rank updates ONLY its owned ~25% of Muon 2D matrices
owned = self._sharded_rank_buckets[self._sharded_rank]
for p in owned:
if p.grad is None:
continue
g = p.grad.float()
st = self.muon_state[id(p)]
m = self.dequantize_int8_blockwise(st["q_mom"], st["scales"], self.block_size, p.shape)
m.mul_(self.momentum).add_(g)
st["q_mom"], st["scales"] = self.quantize_int8_blockwise(m.reshape(-1), self.block_size)
u_in = (g + self.momentum * m) if self.nesterov else m
lr_p = st["lr_base"] * lr_scale
ortho = self._ns5_fn(u_in, self.ns_steps)
p_fp32 = post_ns_fn(p.data, ortho, st["v_row"], lr_p, self.weight_decay, bc_v, 0.2 * math.sqrt(p.numel()))
source.write_back_(p, p_fp32)
# Async-pipelined broadcasts across all 4 owners over full-duplex NVLink
bcast_jobs = []
for owner, plist in enumerate(self._sharded_rank_buckets):
active = [p.data for p in plist if p.grad is not None]
if not active:
continue
flat = torch._utils._flatten_dense_tensors(active)
work = dist.broadcast(flat, src=owner, async_op=True)
bcast_jobs.append((owner, active, flat, work))
# 2. Run fused CUDA FP32 AdamW (tiny 1D/norm/router params) while NVLink broadcasts are in flight!
if self.adamw_fp32_opt is not None:
for pg in self.adamw_fp32_opt.param_groups:
pg["lr"] = lr_a * pg.get("lr_mult", 1.0)
self.adamw_fp32_opt.step()
# Wait & unflatten all 4 owner broadcasts
for owner, active, flat, work in bcast_jobs:
work.wait()
if self._sharded_rank != owner:
for p_data, synced in zip(active, torch._utils._unflatten_dense_tensors(flat, active)):
p_data.copy_(synced)
# 3. Row-sharded BF16 tok_emb AdamW + all_gather over NVLink
if self.params_1d_bf16:
b1, b2 = self.betas
bc1 = 1.0 - b1 ** self.step_count
bc2 = 1.0 - b2 ** self.step_count
dev = self.params_1d_bf16[0].device
lr_t = torch.tensor(lr_a, device=dev, dtype=torch.float32)
bc1_t = torch.tensor(bc1, device=dev, dtype=torch.float32)
bc2_t = torch.tensor(bc2, device=dev, dtype=torch.float32)
for p in self.params_1d_bf16:
if p.grad is None:
continue
st = self.adamw_bf16_state[id(p)]
sl = self._sharded_bf16_slices.get(id(p))
if sl is not None:
r0, r1 = sl
upd = self._adamw_bf16_fn(
p.data[r0:r1],
p.grad[r0:r1].float(),
st["m"],
st["v"],
lr_t,
self.weight_decay,
b1,
b2,
bc1_t,
bc2_t,
).contiguous()
dist.all_gather_into_tensor(p.data, upd)
else:
p.copy_(
self._adamw_bf16_fn(
p, p.grad.float(), st["m"], st["v"], lr_t, self.weight_decay, b1, b2, bc1_t, bc2_t
)
)
optimizer.step = types.MethodType(sharded_step, optimizer)
def coalesced_allreduce_dense_grads(model, world_size: int):
"""Flatten dense gradients by dtype and issue one async-pipelined NCCL all_reduce per dtype."""
if not dist.is_initialized() or world_size <= 1:
return
by_dtype = {}
for p in model.parameters():
if p.grad is not None:
by_dtype.setdefault(p.grad.dtype, []).append(p.grad)
inv_w = 1.0 / float(world_size)
in_flight = []
for _, grads in by_dtype.items():
flat = torch._utils._flatten_dense_tensors(grads)
work = dist.all_reduce(flat, op=dist.ReduceOp.SUM, async_op=True)
in_flight.append((grads, flat, work))
for grads, flat, work in in_flight:
work.wait()
flat.mul_(inv_w)
for g, synced in zip(grads, torch._utils._unflatten_dense_tensors(flat, grads)):
g.copy_(synced) |