Download numeric/sync_audit/tp_sim.py from ziyan98/E2K-cd82-rl-internalization: direct link, hf CLI and curl.
- Browser
- Download file 3.58 kB
-
https://huggingface.co/datasets/ziyan98/E2K-cd82-rl-internalization/resolve/main/numeric/sync_audit/tp_sim.py
- Command line
-
hf download hf://datasets/ziyan98/E2K-cd82-rl-internalization/numeric/sync_audit/tp_sim.py
-
curl -L -o tp_sim.py https://huggingface.co/datasets/ziyan98/E2K-cd82-rl-internalization/resolve/main/numeric/sync_audit/tp_sim.py
3.58 kB
| """Simulate Megatron TP=4 sharding -> slime's all_gather_param concat -> convert_to_hf, | |
| and diff against the HF safetensors. Pure CPU, one tensor at a time.""" | |
| import json, os, sys, re | |
| from argparse import Namespace | |
| import torch | |
| import torch.distributed.checkpoint as dcp | |
| from torch.distributed.checkpoint import FileSystemReader | |
| from safetensors import safe_open | |
| sys.path.insert(0,"/opt/slime") | |
| from slime.backends.megatron_utils.megatron_to_hf import convert_to_hf | |
| CKPT="/projects/u6uv/ziyan/models/megatron/Qwen3.8-27B_torch_dist/release" | |
| HF="/projects/u6uv/ziyan/models/Qwen/Qwen3.8-27B" | |
| TP=4 | |
| md=FileSystemReader(CKPT).read_metadata(); SDM=md.state_dict_metadata | |
| idx=json.load(open(os.path.join(HF,"model.safetensors.index.json")))["weight_map"] | |
| args=Namespace(kv_channels=256,hidden_size=5120,num_attention_heads=24,num_query_groups=4, | |
| vocab_size=248320,q_lora_rank=None,num_experts=None) | |
| def hf_get(n): | |
| with safe_open(os.path.join(HF, idx[n]), framework="pt", device="cpu") as g: | |
| return g.get_tensor(n) | |
| def mg_get(n): | |
| m=SDM[n]; t=torch.empty(tuple(m.size),dtype=m.properties.dtype) | |
| dcp.load({n:t},storage_reader=FileSystemReader(CKPT),no_dist=True); return t | |
| # --- how Megatron lays out each param locally on TP rank r --- | |
| def megatron_shard(name, full, r): | |
| if "mlp.linear_fc1.weight" in name: # column-parallel, GLU stride 2 | |
| g,u = full.chunk(2, dim=0) | |
| return torch.cat([g.chunk(TP,0)[r], u.chunk(TP,0)[r]], dim=0).contiguous(), (True,0,2) | |
| if "linear_qkv.weight" in name: # column-parallel, whole query groups | |
| return full.chunk(TP,0)[r].contiguous(), (True,0,1) | |
| if "linear_proj.weight" in name or "mlp.linear_fc2.weight" in name: # row-parallel | |
| return full.chunk(TP,1)[r].contiguous(), (True,1,1) | |
| # layernorms, qk-norms and every GDN parameter: replicated, tensor_model_parallel=False | |
| return full.clone(), (False,-1,1) | |
| # --- verbatim reimplementation of slime all_gather_param / all_gather_params_async --- | |
| def slime_gather(name, parts, attrs): | |
| tmp, pdim, pstride = attrs | |
| if not tmp: | |
| return parts[0] # common.py:24-25 / :76-77 -> param.data | |
| assert pstride==1 or (pstride==2 and "linear_fc1" in name) # common.py:43-45 | |
| if "linear_fc1.weight" in name or "linear_fc1.bias" in name: # common.py:48-50 | |
| c=[p.chunk(2,dim=0) for p in parts] | |
| parts=[p[0] for p in c]+[p[1] for p in c] | |
| if "linear_fc2.weight" in name and pdim==0: # common.py:52-53 | |
| pdim=1 | |
| return torch.cat(parts, dim=pdim) # common.py:55 | |
| names=[n for n in sorted(SDM) if re.match(r"decoder\.layers\.(0|3)\.",n) and "_extra_state" not in n] | |
| print(f"{'megatron name':62s} {'shard[0]':16s} {'tp?':5s} gather_ok hf_name / maxabs") | |
| allok=True | |
| for n in names: | |
| full=mg_get(n) | |
| parts=[]; attrs=None | |
| for r in range(TP): | |
| p,a = megatron_shard(n, full, r); parts.append(p); attrs=a | |
| g = slime_gather("module.module."+n, parts, attrs) | |
| ok = g.shape==full.shape and bool((g.view(torch.int16)==full.view(torch.int16)).all()) | |
| allok &= ok | |
| out=convert_to_hf(args,"qwen3_5config","module.module."+n, g, None) | |
| det=[] | |
| for hn,ht in out: | |
| ref=hf_get(hn) | |
| d=(ref.float()-ht.float()).abs().max().item() | |
| det.append(f"{hn.split('layers.')[-1]}={d:g}") | |
| del ref | |
| print(f"{n:62s} {str(tuple(parts[0].shape)):16s} {str(attrs[0]):5s} {str(ok):9s} {' '.join(det)}") | |
| del full,parts,g,out | |
| print("ALL GATHERS BIT-EXACT:", allok) | |