quantuminfer 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +9 -0
- package/README.md +96 -2
- package/bin/quantuminfer.js +61 -0
- package/c27/adapters.py +161 -0
- package/c27/harness27.py +349 -0
- package/data/input.txt +40000 -0
- package/data/wikitext/test.txt +7249 -0
- package/engine/API.txt +208 -0
- package/engine/PLUGINS.txt +4 -0
- package/engine/__init__.py +82 -0
- package/engine/adapter.py +505 -0
- package/engine/blocks.py +1180 -0
- package/engine/c12.py +324 -0
- package/engine/c12cu.py +1074 -0
- package/engine/ctx.py +87 -0
- package/engine/dev.py +11 -0
- package/engine/ds4.py +389 -0
- package/engine/kernels.py +833 -0
- package/engine/model.py +281 -0
- package/engine/record.py +140 -0
- package/engine/server.py +183 -0
- package/engine/spec.py +1030 -0
- package/engine/wcode.py +122 -0
- package/p27/SPEC.txt +66 -0
- package/p27/STATUS.txt +91 -0
- package/p27/bench_glm.py +354 -0
- package/p27/bench_multi.py +76 -0
- package/p27/mkfinal.py +98 -0
- package/p27/modal_comp.py +173 -0
- package/p27/modal_dl.py +63 -0
- package/p27/modal_p27.py +168 -0
- package/p27/modal_probe.py +49 -0
- package/p27/p27rules.py +29 -0
- package/p27/pblocks.py +1242 -0
- package/p27/pmodel.py +402 -0
- package/p27/pref.py +151 -0
- package/p27/prof_glm.py +34 -0
- package/p27/quant.py +850 -0
- package/p27/recipes/vllm_b300_single_node_tep_b300_agentx_ep.md +353 -0
- package/p27/recipes/vllm_b300_single_node_tp_b300_agentx.md +351 -0
- package/p27/recipes/vllm_b300_single_node_tp_baseline.md +250 -0
- package/p27/recipes/vllm_default_gb300.md +281 -0
- package/p27/recipes/vllm_glm53_h200.md +301 -0
- package/p27/run_window1.sh +21 -0
- package/p27/run_window2.sh +13 -0
- package/p27/sweep_glm.py +64 -0
- package/p27/t_align.py +42 -0
- package/p27/t_combine.py +28 -0
- package/p27/t_echo.py +31 -0
- package/p27/t_fp8dense.py +59 -0
- package/p27/t_fp8speed.py +48 -0
- package/p27/t_glm.py +340 -0
- package/p27/t_glu.py +30 -0
- package/p27/t_gsuf.py +23 -0
- package/p27/t_jac.py +22 -0
- package/p27/t_moebm.py +30 -0
- package/p27/t_nccl.py +36 -0
- package/p27/t_online_jac.py +31 -0
- package/p27/t_probe.py +4 -0
- package/p27/t_router.py +28 -0
- package/p27/t_symm.py +50 -0
- package/p27/t_tiny.py +116 -0
- package/package.json +10 -4
- package/results/ANALYSIS.md +156 -0
- package/results/comp_vllm_mtp_k5_b300mtp.json +235 -0
- package/results/glm53_b300x8_opt4.json +624 -0
- package/results/res_glm_c32w3_b300.json +638 -0
- package/results/res_glm_final_c32_b300.json +652 -0
- package/results/res_glm_multi_final_b300.json +1821 -0
- package/results/res_glm_online_b300.json +638 -0
- package/results/res_glm_online_fixed_b300.json +638 -0
- package/results/res_glm_opt4_b300.json +624 -0
- package/results/res_glm_text_plain_batch_b300.json +5792 -0
- package/results/res_glm_text_w1_b300.json +1635 -0
- package/results/res_glm_text_w3_b300.json +1639 -0
- package/results/res_sweep_echo_b300.json +129 -0
- package/results/res_sweep_final_b300.json +153 -0
- package/results/res_sweep_glm_b300.json +153 -0
- package/results/res_techo.json +29 -0
- package/results/res_tgsuf.json +21 -0
- package/results/res_tjac.json +17 -0
- package/results/res_tonline_jac.json +13 -0
package/p27/sweep_glm.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Online speculative-shape sweep for GLM on the multi-GPU box: decode speed and acceptance by MTP depth/suffix."""
|
|
2
|
+
import time
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
SNAP = "/vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c19c8738e2c57c71798c601d477a7bf844"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(rank=0, world=1, model=SNAP, fast=True, ar32=True, fp8a8=False, shapes=None, n=128, reps=1, SN=4):
|
|
9
|
+
import pmodel
|
|
10
|
+
import pblocks as PB
|
|
11
|
+
import quant as Q
|
|
12
|
+
import spec as SP
|
|
13
|
+
from transformers import AutoTokenizer
|
|
14
|
+
PB.FAST = fast
|
|
15
|
+
PB.AR32 = ar32
|
|
16
|
+
PB.MOE_FP8A8 = fp8a8
|
|
17
|
+
Q.ALIGN_TRITON = True
|
|
18
|
+
t0 = time.time()
|
|
19
|
+
tp = {"rank": rank, "world": world, "group": None}
|
|
20
|
+
m = pmodel.PModel(model, B=1, smax=512, tp=tp, expert_shard="ep_tp", verbose=(rank == 0))
|
|
21
|
+
tok = AutoTokenizer.from_pretrained(model)
|
|
22
|
+
prompts = {
|
|
23
|
+
"code": tok("def fibonacci(n):", add_special_tokens=False).input_ids,
|
|
24
|
+
"chat": tok("Explain in three sentences why the sky is blue.", add_special_tokens=False).input_ids,
|
|
25
|
+
}
|
|
26
|
+
shapes = shapes or [[3, 8, 0, 1], [3, 16, 0, 1], [3, 24, 0, 1], [3, 32, 0, 1], [3, 8, 0, 1, 3], [3, 8, 8, 3], [3, 16, 8, 3], [4, 16, 0, 1]]
|
|
27
|
+
rows = []
|
|
28
|
+
for sh in shapes:
|
|
29
|
+
D, C = sh[0], sh[1]
|
|
30
|
+
E = sh[2] if len(sh) > 2 else 0
|
|
31
|
+
EW = sh[3] if len(sh) > 3 else 1
|
|
32
|
+
W = sh[4] if len(sh) > 4 else 1
|
|
33
|
+
eng = None
|
|
34
|
+
try:
|
|
35
|
+
eng = SP.SpecEngine(m, D=D if m.mtp is not None else 0, C=C, W=W, T=0.0, E=E, EW=EW, SN=SN)
|
|
36
|
+
eng.capture(use_graph=True)
|
|
37
|
+
for case, ids in prompts.items():
|
|
38
|
+
for r in range(reps + 1):
|
|
39
|
+
m.reset()
|
|
40
|
+
eng.start(ids) # fresh suffix/host state and committed lengths for every repetition
|
|
41
|
+
torch.cuda.synchronize()
|
|
42
|
+
tq = time.perf_counter()
|
|
43
|
+
passes = 0
|
|
44
|
+
while len(eng.out) < n + 1:
|
|
45
|
+
eng.step()
|
|
46
|
+
a = int(eng.alen[0])
|
|
47
|
+
e = eng.em[0, :a].tolist()
|
|
48
|
+
eng.out += e
|
|
49
|
+
eng.suf.extend(e)
|
|
50
|
+
eng._fill_suffix()
|
|
51
|
+
eng._fill_echo()
|
|
52
|
+
passes += 1
|
|
53
|
+
torch.cuda.synchronize()
|
|
54
|
+
dt = time.perf_counter() - tq
|
|
55
|
+
if r == reps - 1:
|
|
56
|
+
rows.append({"D": D, "C": C, "E": E, "EW": EW, "W": W, "case": case, "decode_tok_s": n / dt, "tok_per_pass": n / passes,
|
|
57
|
+
"passes": passes, "s": dt})
|
|
58
|
+
if rank == 0:
|
|
59
|
+
print("sweep", rows[-1], flush=True)
|
|
60
|
+
except Exception as e:
|
|
61
|
+
rows.append({"D": D, "C": C, "E": E, "EW": EW, "W": W, "error": repr(e)})
|
|
62
|
+
del eng
|
|
63
|
+
torch.cuda.empty_cache()
|
|
64
|
+
return {"rows": rows, "load_s": time.time() - t0, "ar32": ar32, "fast": fast, "fp8a8": fp8a8}
|
package/p27/t_align.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Dispatch-align microbench for decode-tree top-k shapes."""
|
|
2
|
+
import torch
|
|
3
|
+
import quant as Q
|
|
4
|
+
|
|
5
|
+
def bench(fn,n=300):
|
|
6
|
+
for _ in range(5): fn()
|
|
7
|
+
torch.cuda.synchronize(); a=torch.cuda.Event(True); b=torch.cuda.Event(True); a.record()
|
|
8
|
+
for _ in range(n): fn()
|
|
9
|
+
b.record(); torch.cuda.synchronize(); return a.elapsed_time(b)/n
|
|
10
|
+
|
|
11
|
+
def gbench(fn,n=200):
|
|
12
|
+
for _ in range(3): fn()
|
|
13
|
+
torch.cuda.synchronize()
|
|
14
|
+
g=torch.cuda.CUDAGraph()
|
|
15
|
+
with torch.cuda.graph(g): fn()
|
|
16
|
+
torch.cuda.synchronize()
|
|
17
|
+
a=torch.cuda.Event(True); b=torch.cuda.Event(True); a.record()
|
|
18
|
+
for _ in range(n): g.replay()
|
|
19
|
+
b.record(); torch.cuda.synchronize(); return a.elapsed_time(b)/n
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main():
|
|
23
|
+
rows=[]
|
|
24
|
+
for R in (1,12,20,36,64,128):
|
|
25
|
+
g=torch.Generator().manual_seed(R)
|
|
26
|
+
idx=torch.stack([torch.randperm(256,generator=g)[:8] for _ in range(R)]).cuda()
|
|
27
|
+
for BM in (8,16,64):
|
|
28
|
+
row={'R':R,'BM':BM,'torch_ms':bench(lambda: Q.moe_align_torch(idx,256,0,BM))}
|
|
29
|
+
try:
|
|
30
|
+
a=Q.moe_align_torch(idx,256,0,BM); b=Q.moe_align_fast(idx,256,0,BM)
|
|
31
|
+
row['fast_eq']=all(bool((x==y).all()) for x,y in zip(a,b))
|
|
32
|
+
row['fast_ms']=bench(lambda: Q.moe_align_fast(idx,256,0,BM))
|
|
33
|
+
row['fast_graph_ms']=gbench(lambda: Q.moe_align_fast(idx,256,0,BM))
|
|
34
|
+
row['torch_graph_ms']=gbench(lambda: Q.moe_align_torch(idx,256,0,BM))
|
|
35
|
+
except Exception as e: row['fast_err']=repr(e)[:200]
|
|
36
|
+
if R*8<=256:
|
|
37
|
+
Q.ALIGN_TRITON,fast=True,Q.ALIGN_FAST
|
|
38
|
+
Q.ALIGN_FAST=False
|
|
39
|
+
row['triton_ms']=bench(lambda: Q.moe_align(idx,256,0,BM))
|
|
40
|
+
Q.ALIGN_TRITON,Q.ALIGN_FAST=False,fast
|
|
41
|
+
rows.append(row)
|
|
42
|
+
return {'rows':rows}
|
package/p27/t_combine.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""fused MoE combine exactness + CUDA-graph timing."""
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
def bench_graph(fn,n=300):
|
|
5
|
+
for _ in range(3): fn()
|
|
6
|
+
torch.cuda.synchronize(); g=torch.cuda.CUDAGraph()
|
|
7
|
+
with torch.cuda.graph(g): fn()
|
|
8
|
+
torch.cuda.synchronize(); a=torch.cuda.Event(True); b=torch.cuda.Event(True); a.record()
|
|
9
|
+
for _ in range(n): g.replay()
|
|
10
|
+
b.record(); torch.cuda.synchronize(); return a.elapsed_time(b)/n
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
import quant as Q
|
|
14
|
+
out=[]
|
|
15
|
+
for R,D,k in ((1,6144,8),(12,6144,8),(64,6144,8)):
|
|
16
|
+
torch.manual_seed(R)
|
|
17
|
+
P=640
|
|
18
|
+
y=torch.randn(P,D,device='cuda',dtype=torch.float32)
|
|
19
|
+
po=torch.randint(0,P+20,(R*k,),device='cuda',dtype=torch.long)-20
|
|
20
|
+
w=torch.randn(R,k,device='cuda',dtype=torch.float32)
|
|
21
|
+
z=Q.moe_combine(y,po,w,R,k)
|
|
22
|
+
yp=torch.cat([y,torch.zeros(1,D,device='cuda')],0)
|
|
23
|
+
sel=yp[torch.where(po>=0,po,torch.full_like(po,P))].view(R,k,-1)
|
|
24
|
+
ref=(sel*w[...,None]).sum(1)
|
|
25
|
+
row={'R':R,'maxdiff':(z-ref).abs().max().item(),'rel':((z-ref).abs().max()/ref.abs().max()).item(),
|
|
26
|
+
'graph_ms':bench_graph(lambda:Q.moe_combine(y,po,w,R,k))}
|
|
27
|
+
out.append(row)
|
|
28
|
+
return {'rows':out}
|
package/p27/t_echo.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""In-graph amplitude echo smoke/exactness test on tiny-random GLM."""
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
def main(n_gen=24, seed=0):
|
|
5
|
+
import t_glm
|
|
6
|
+
import pmodel
|
|
7
|
+
import spec as SP
|
|
8
|
+
path = t_glm.snap("tiny-random/glm-5.3")
|
|
9
|
+
m = pmodel.PModel(path, B=1, smax=256, verbose=False)
|
|
10
|
+
ids = torch.randint(100, m.V - 100, (40,), generator=torch.Generator().manual_seed(seed)).cuda().tolist()
|
|
11
|
+
R = {}
|
|
12
|
+
# fused top-k smoke: bounds and per-row uniqueness
|
|
13
|
+
from record import gumbel_topk
|
|
14
|
+
z = torch.randn(6, m.V, device="cuda", dtype=torch.bfloat16)
|
|
15
|
+
rid = torch.arange(6, device="cuda", dtype=torch.long) + 17
|
|
16
|
+
tk = gumbel_topk(z, rid, 1.0, 3)
|
|
17
|
+
R["topk_shape"] = list(tk.shape)
|
|
18
|
+
R["topk_bounds"] = bool((tk >= 0).all() and (tk < m.V).all())
|
|
19
|
+
R["topk_unique"] = all(len(set(row)) == 3 for row in tk.cpu().tolist())
|
|
20
|
+
for T in (0.0, 1.0):
|
|
21
|
+
outs = {}
|
|
22
|
+
for E in (0, 2):
|
|
23
|
+
eng = SP.SpecEngine(m, D=2 if m.mtp else 0, C=4, T=T, uid=991 + int(T), E=E, EW=2)
|
|
24
|
+
eng.capture(use_graph=True)
|
|
25
|
+
m.reset()
|
|
26
|
+
o = eng.generate(ids, n_gen)
|
|
27
|
+
outs[E] = o
|
|
28
|
+
R[f"T{T}_E{E}_tok_per_pass"] = o["tok_per_pass"]
|
|
29
|
+
R[f"T{T}_echo_exact"] = outs[0]["out"] == outs[2]["out"]
|
|
30
|
+
R["summary"] = {k: v for k, v in R.items() if k.startswith("T") or k.startswith("topk")}
|
|
31
|
+
return R
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Tile sweep for dense block-fp8 projections at GLM decode-tree shapes."""
|
|
2
|
+
import torch, triton
|
|
3
|
+
import quant as Q
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def bench(fn, n=100):
|
|
7
|
+
for _ in range(5): fn()
|
|
8
|
+
torch.cuda.synchronize()
|
|
9
|
+
a=torch.cuda.Event(True); b=torch.cuda.Event(True); a.record()
|
|
10
|
+
for _ in range(n): fn()
|
|
11
|
+
b.record(); torch.cuda.synchronize(); return a.elapsed_time(b)/n
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def lin(x,w,s,qn,qk,BN,nw):
|
|
15
|
+
M,K=x.shape; N=w.shape[0]; y=torch.empty(M,N,dtype=x.dtype,device=x.device)
|
|
16
|
+
BM=16
|
|
17
|
+
Q._fp8blk_k[(triton.cdiv(M,BM),triton.cdiv(N,BN))](x,w,s,y,M,N,K,x.stride(0),w.stride(0),s.stride(0),y.stride(0),triton.cdiv(K,qk),BM=BM,BN=BN,BK=qk,QN=qn,num_warps=nw)
|
|
18
|
+
return y
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def case(N,K,M=12):
|
|
22
|
+
torch.manual_seed(N+K)
|
|
23
|
+
qn=qk=128
|
|
24
|
+
x=torch.randn(M,K,device='cuda',dtype=torch.bfloat16)
|
|
25
|
+
w=(torch.randn(N,K,device='cuda')*.02).to(torch.float8_e4m3fn)
|
|
26
|
+
s=torch.rand((N+qn-1)//qn,(K+qk-1)//qk,device='cuda')*.01+.001
|
|
27
|
+
rows={'sk2':bench(lambda: Q.fp8blk_sk_linear(x,w,s,qn,qk,SK=2),n=100),
|
|
28
|
+
'sk4':bench(lambda: Q.fp8blk_sk_linear(x,w,s,qn,qk,SK=4),n=100),
|
|
29
|
+
'sk8':bench(lambda: Q.fp8blk_sk_linear(x,w,s,qn,qk,SK=8),n=100),
|
|
30
|
+
'base_graph':gbench(lambda: lin(x,w,s,qn,qk,64,4),n=200),
|
|
31
|
+
'sk4_graph':gbench(lambda: Q.fp8blk_sk_linear(x,w,s,qn,qk,SK=4),n=200)}
|
|
32
|
+
for bn in (32,64,128):
|
|
33
|
+
for nw in (4,8):
|
|
34
|
+
for sk in (2,4,8):
|
|
35
|
+
rows[f'g_bn{bn}w{nw}sk{sk}']=gbench(lambda bn=bn,nw=nw,sk=sk: Q.fp8blk_sk_linear(x,w,s,qn,qk,BN=bn,nw=nw,SK=sk),n=200)
|
|
36
|
+
for bn in (16,32,64,128):
|
|
37
|
+
for nw in (4,8):
|
|
38
|
+
if bn*nw: rows[f'bn{bn}w{nw}']=bench(lambda bn=bn,nw=nw: lin(x,w,s,qn,qk,bn,nw),n=100)
|
|
39
|
+
y0=lin(x,w,s,qn,qk,64,4).float(); y1=Q.fp8blk_sk_linear(x,w,s,qn,qk,SK=4).float()
|
|
40
|
+
return {'N':N,'K':K,'skdiff':(y0-y1).abs().max().item(),'rows':rows}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def gbench(fn,n=200):
|
|
44
|
+
for _ in range(3): fn()
|
|
45
|
+
torch.cuda.synchronize()
|
|
46
|
+
g=torch.cuda.CUDAGraph()
|
|
47
|
+
with torch.cuda.graph(g): fn()
|
|
48
|
+
torch.cuda.synchronize()
|
|
49
|
+
a=torch.cuda.Event(True); b=torch.cuda.Event(True); a.record()
|
|
50
|
+
for _ in range(n): g.replay()
|
|
51
|
+
b.record(); torch.cuda.synchronize(); return a.elapsed_time(b)/n
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def main():
|
|
55
|
+
out={}
|
|
56
|
+
for M in (12,44):
|
|
57
|
+
for nm,N,K in [('qa',2048,6144),('qb',2048,2048),('kva',576,6144),('o',6144,2048),('iwk',128,6144),('iwq',4096,2048)]:
|
|
58
|
+
out[f'{nm}_m{M}']=case(N,K,M)
|
|
59
|
+
return out
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Microbench/correctness for GLM-shaped grouped fp8 expert GEMMs on one GPU."""
|
|
2
|
+
import torch
|
|
3
|
+
import quant as Q
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def bench(fn, n=50):
|
|
7
|
+
for _ in range(5):
|
|
8
|
+
fn()
|
|
9
|
+
torch.cuda.synchronize()
|
|
10
|
+
t0 = torch.cuda.Event(True); t1 = torch.cuda.Event(True)
|
|
11
|
+
t0.record()
|
|
12
|
+
for _ in range(n):
|
|
13
|
+
fn()
|
|
14
|
+
t1.record(); torch.cuda.synchronize()
|
|
15
|
+
return t0.elapsed_time(t1) / n
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def case(E=256, k=8, R=1, N=512, K=6144, qn=128, qk=128):
|
|
19
|
+
torch.manual_seed(0)
|
|
20
|
+
dev = 'cuda'
|
|
21
|
+
a = torch.randn(R, K, device=dev, dtype=torch.bfloat16)
|
|
22
|
+
w = (torch.randn(E, N, K, device=dev) * .02).to(torch.float8_e4m3fn)
|
|
23
|
+
s = torch.rand(E, N // qn, K // qk, device=dev) * .01 + .001
|
|
24
|
+
g = torch.Generator(device='cpu').manual_seed(R * 100 + N + K)
|
|
25
|
+
idx = torch.stack([torch.randperm(E, generator=g)[:k] for _ in range(R)]).to(dev)
|
|
26
|
+
out = {'shape': [E, k, R, N, K]}
|
|
27
|
+
def make(BM, gv):
|
|
28
|
+
pr, be, po = Q.moe_align(idx, E, 0, BM)
|
|
29
|
+
pr2 = torch.where(pr >= 0, torch.arange(pr.shape[0], device=pr.device, dtype=pr.dtype), pr)
|
|
30
|
+
return pr, be, po, pr2, (lambda: Q.moe_fp8_gemm(a, w, s, qn, qk, pr, be, BM, gemv1=gv))
|
|
31
|
+
pr0, be0, po0, _, base = make(16, False)
|
|
32
|
+
fast = lambda: Q.moe_fp8e_gemm(a, w, s, qn, qk, pr0, be0, 16)
|
|
33
|
+
y0, y1 = base(), fast()
|
|
34
|
+
sel0 = y0[po0.reshape(-1)].reshape(-1, N)
|
|
35
|
+
sel1 = y1[po0.reshape(-1)].reshape(-1, N)
|
|
36
|
+
rel = ((sel0 - sel1).abs().max() / sel0.abs().max()).item()
|
|
37
|
+
out.update(ms_base=bench(base), ms_even=bench(fast), maxdiff=(sel0 - sel1).abs().max().item(), relmax=rel,
|
|
38
|
+
nonempty0=int((pr0 >= 0).sum()), p0=len(pr0))
|
|
39
|
+
if R in (12, 64):
|
|
40
|
+
out['tune'] = {f'bn{bn}w{nw}': bench(lambda bn=bn, nw=nw: Q.moe_fp8e_gemm(
|
|
41
|
+
a, w, s, qn, qk, pr0, be0, 16, BN=bn, nw=nw), n=30) for bn in (32, 64, 128) for nw in (4, 8)}
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main():
|
|
46
|
+
return {'up_r1': case(R=1, N=512, K=6144), 'down_r1': case(R=1, N=6144, K=256),
|
|
47
|
+
'up_r12': case(R=12, N=512, K=6144), 'down_r12': case(R=12, N=6144, K=256),
|
|
48
|
+
'up_r64': case(R=64, N=512, K=6144), 'down_r64': case(R=64, N=6144, K=256)}
|
package/p27/t_glm.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Dev test (one GPU) on tiny-random/glm-5.3 (native transformers glm_moe_dsa, block-fp8 32x32, DSA top-128):
|
|
2
|
+
our blocks (bf16 activations, exact fp8 weights) vs the HF implementation in fp32 on exactly dequantised weights.
|
|
3
|
+
Also unit tests: fp8 block GEMM, grouped fp8 MoE GEMM + capacity-free dispatch."""
|
|
4
|
+
import glob
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn.functional as F
|
|
10
|
+
|
|
11
|
+
torch.backends.cuda.matmul.allow_tf32 = False
|
|
12
|
+
torch.backends.cudnn.allow_tf32 = False
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def snap(repo, rev=None):
|
|
16
|
+
d = glob.glob(f"/vol/hf/hub/models--{repo.replace('/', '--')}/snapshots/*")
|
|
17
|
+
if not d:
|
|
18
|
+
os.environ.pop("HF_HUB_OFFLINE", None)
|
|
19
|
+
from huggingface_hub import snapshot_download
|
|
20
|
+
return snapshot_download(repo, revision=rev)
|
|
21
|
+
return sorted(d)[0]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def hf_fp32(path, device="cuda", nl=None):
|
|
25
|
+
"""native HF model (no remote code) in fp32 with every weight decoded exactly (block fp8 -> w8 * s).
|
|
26
|
+
nl: keep only the first nl decoder layers (reduced-depth check on a huge checkpoint)."""
|
|
27
|
+
from transformers import AutoConfig, AutoModelForCausalLM
|
|
28
|
+
from adapter import WeightIndex
|
|
29
|
+
import pref
|
|
30
|
+
cfg = AutoConfig.from_pretrained(path)
|
|
31
|
+
if nl:
|
|
32
|
+
cfg.num_hidden_layers = nl
|
|
33
|
+
for k in ("mlp_layer_types", "indexer_types", "layer_types"):
|
|
34
|
+
if getattr(cfg, k, None):
|
|
35
|
+
setattr(cfg, k, list(getattr(cfg, k))[:nl])
|
|
36
|
+
if hasattr(cfg, "quantization_config"):
|
|
37
|
+
del cfg.quantization_config
|
|
38
|
+
cfg._attn_implementation = "eager"
|
|
39
|
+
with torch.device("meta"):
|
|
40
|
+
m = AutoModelForCausalLM.from_config(cfg, dtype=torch.float32)
|
|
41
|
+
W = WeightIndex(path)
|
|
42
|
+
names = dict(m.named_parameters())
|
|
43
|
+
names.update(dict(m.named_buffers()))
|
|
44
|
+
sd = {}
|
|
45
|
+
for k in names:
|
|
46
|
+
if k in W.map:
|
|
47
|
+
sd[k] = pref.deq(W, k, torch.float32, device)
|
|
48
|
+
elif k.endswith("experts.gate_up_proj") or k.endswith("experts.down_proj"):
|
|
49
|
+
base = k.rsplit(".", 1)[0]
|
|
50
|
+
E = names[k].shape[0]
|
|
51
|
+
if k.endswith("gate_up_proj"):
|
|
52
|
+
sd[k] = torch.stack([torch.cat([pref.deq(W, f"{base}.{e}.gate_proj.weight"),
|
|
53
|
+
pref.deq(W, f"{base}.{e}.up_proj.weight")], 0) for e in range(E)])
|
|
54
|
+
else:
|
|
55
|
+
sd[k] = torch.stack([pref.deq(W, f"{base}.{e}.down_proj.weight") for e in range(E)])
|
|
56
|
+
m = m.to_empty(device=device)
|
|
57
|
+
miss, unexp = m.load_state_dict(sd, strict=False)
|
|
58
|
+
for n, b in m.named_buffers(): # rotary inv_freq etc. (non-persistent buffers): recompute
|
|
59
|
+
pass
|
|
60
|
+
m.model.rotary_emb.__init__(m.config)
|
|
61
|
+
m.model.rotary_emb.to(device)
|
|
62
|
+
m.eval()
|
|
63
|
+
return m, [x for x in miss if "rotary" not in x]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def unit_fp8():
|
|
67
|
+
import quant as Q
|
|
68
|
+
R = {}
|
|
69
|
+
torch.manual_seed(0)
|
|
70
|
+
N, K, qn, qk = 384, 512, 128, 128
|
|
71
|
+
w = (torch.randn(N, K, device="cuda") * 3).to(torch.float8_e4m3fn)
|
|
72
|
+
s = torch.rand(N // qn, K // qk, device="cuda") * 0.01 + 1e-3
|
|
73
|
+
W = Q.fp8blk_dequant(w, s)
|
|
74
|
+
for M in (1, 7, 40, 300):
|
|
75
|
+
x = torch.randn(M, K, device="cuda").to(torch.bfloat16)
|
|
76
|
+
y = Q.fp8blk_linear(x, w, s, qn, qk, out_dtype=torch.float32)
|
|
77
|
+
yr = x.double() @ W.double().t()
|
|
78
|
+
R[f"fp8_lin_M{M}_relerr"] = float((y.double() - yr).abs().max() / yr.abs().max())
|
|
79
|
+
# grouped MoE + dispatch
|
|
80
|
+
E, k, Rr = 8, 3, 21
|
|
81
|
+
w8 = (torch.randn(E, N, K, device="cuda")).to(torch.float8_e4m3fn)
|
|
82
|
+
s8 = torch.rand(E, N // qn, K // qk, device="cuda") * 0.01 + 1e-3
|
|
83
|
+
x = torch.randn(Rr, K, device="cuda").to(torch.bfloat16)
|
|
84
|
+
ids = torch.stack([torch.randperm(E, device="cuda")[:k] for _ in range(Rr)])
|
|
85
|
+
Q.ALIGN_TRITON = True
|
|
86
|
+
for R_ in (1, 5, 40): # Triton single-program dispatch == torch dispatch
|
|
87
|
+
ii = torch.stack([torch.randperm(256, device="cuda")[:8] for _ in range(R_)])
|
|
88
|
+
for e0_, El_ in ((0, 256), (64, 32)):
|
|
89
|
+
a = Q.moe_align(ii, El_, e0_, 16)
|
|
90
|
+
b = Q.moe_align_torch(ii, El_, e0_, 16)
|
|
91
|
+
R[f"align_R{R_}_e{e0_}_equal"] = all(bool((x == y).all()) for x, y in zip(a, b))
|
|
92
|
+
for e0, El in ((0, E), (2, 3)):
|
|
93
|
+
pr, be, po = Q.moe_align(ids, El, e0, 16)
|
|
94
|
+
c = Q.moe_fp8_gemm(x, w8[e0:e0 + El].contiguous(), s8[e0:e0 + El].contiguous(), qn, qk, pr, be, 16,
|
|
95
|
+
out_dtype=torch.float32)
|
|
96
|
+
err = 0.0
|
|
97
|
+
cnt = 0
|
|
98
|
+
for r in range(Rr):
|
|
99
|
+
for j in range(k):
|
|
100
|
+
e = int(ids[r, j])
|
|
101
|
+
slot = int(po[r * k + j])
|
|
102
|
+
if not (e0 <= e < e0 + El):
|
|
103
|
+
assert slot == -1
|
|
104
|
+
continue
|
|
105
|
+
cnt += 1
|
|
106
|
+
ref = x[r].double() @ Q.fp8blk_dequant(w8[e], s8[e]).double().t()
|
|
107
|
+
err = max(err, float((c[slot].double() - ref).abs().max() / ref.abs().max()))
|
|
108
|
+
R[f"moe_fp8_e0{e0}_relerr"] = err
|
|
109
|
+
R[f"moe_fp8_e0{e0}_pairs"] = cnt
|
|
110
|
+
return R
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main(repo="tiny-random/glm-5.3", T=40, T2=200, n_gen=24, seed=0, fast=False):
|
|
114
|
+
import pblocks as PB
|
|
115
|
+
PB.FAST = fast
|
|
116
|
+
import pmodel
|
|
117
|
+
import pref
|
|
118
|
+
from ctx import RowCtx, chain
|
|
119
|
+
import spec as SP
|
|
120
|
+
R = {"device": torch.cuda.get_device_name()}
|
|
121
|
+
R["unit"] = unit_fp8()
|
|
122
|
+
path = snap(repo)
|
|
123
|
+
R["path"] = path
|
|
124
|
+
t0 = time.time()
|
|
125
|
+
ref, miss = hf_fp32(path)
|
|
126
|
+
R["ref_missing"] = miss[:10]
|
|
127
|
+
g = torch.Generator().manual_seed(seed)
|
|
128
|
+
V = ref.config.vocab_size
|
|
129
|
+
ids = torch.randint(100, V - 100, (T2 + n_gen,), generator=g).cuda()
|
|
130
|
+
zr_all = pref.ref_logits(ref, ids)
|
|
131
|
+
R["ref_s"] = time.time() - t0
|
|
132
|
+
for smax in (120, 512): # 120 <= topk 128: dense kernel path; 512: indexer + sparse path
|
|
133
|
+
m = pmodel.PModel(path, B=1, smax=smax)
|
|
134
|
+
TT = T if smax < 128 else T2
|
|
135
|
+
zr = pref.ref_logits(ref, ids[:TT + n_gen]) if TT != T2 else zr_all
|
|
136
|
+
RR = {}
|
|
137
|
+
h = m.prefill(ids[:TT], b=0)
|
|
138
|
+
z = m.logits(h).float()
|
|
139
|
+
RR["prefill_maxdiff"] = float((z - zr[:TT]).abs().max())
|
|
140
|
+
RR["prefill_rel"] = float((z - zr[:TT]).abs().max() / zr[:TT].std())
|
|
141
|
+
RR["zr_std"] = float(zr[:TT].std())
|
|
142
|
+
RR["nonfinite"] = int((~torch.isfinite(z)).sum())
|
|
143
|
+
RR["prefill_argmax_agree"] = float((z.argmax(-1) == zr[:TT].argmax(-1)).float().mean())
|
|
144
|
+
RR["prefill_gap_max"] = float(pref.gaps(zr[:TT], z.argmax(-1)).max())
|
|
145
|
+
one = chain(1)
|
|
146
|
+
lens = torch.full((1,), TT, dtype=torch.int32, device="cuda")
|
|
147
|
+
zs = []
|
|
148
|
+
ng = min(n_gen, smax - TT - 8)
|
|
149
|
+
for i in range(ng):
|
|
150
|
+
ctx = RowCtx.tree(one, lens, 1)
|
|
151
|
+
hh = m.tree(ids[TT + i:TT + i + 1].view(1, 1), ctx)
|
|
152
|
+
zs.append(m.logits(hh).float())
|
|
153
|
+
ctx.set_accept(torch.zeros(1, dtype=torch.long, device="cuda"))
|
|
154
|
+
m.commit(ctx)
|
|
155
|
+
lens += 1
|
|
156
|
+
zd = torch.cat(zs)
|
|
157
|
+
RR["decode_maxdiff"] = float((zd - zr[TT:TT + ng]).abs().max())
|
|
158
|
+
RR["decode_rel"] = float((zd - zr[TT:TT + ng]).abs().max() / zr[TT:TT + ng].std())
|
|
159
|
+
RR["decode_gap_max"] = float(pref.gaps(zr[TT:TT + ng], zd.argmax(-1)).max())
|
|
160
|
+
m.reset()
|
|
161
|
+
m.prefill(ids[:TT], b=0)
|
|
162
|
+
c5 = chain(5)
|
|
163
|
+
lens = torch.full((1,), TT, dtype=torch.int32, device="cuda")
|
|
164
|
+
ctx = RowCtx.tree(c5, lens, 1)
|
|
165
|
+
hh = m.tree(ids[TT:TT + 5].view(1, 5), ctx)
|
|
166
|
+
RR["chain5_maxdiff"] = float((m.logits(hh).float() - zr[TT:TT + 5]).abs().max())
|
|
167
|
+
ctx.set_accept(torch.tensor([2], device="cuda"))
|
|
168
|
+
m.commit(ctx)
|
|
169
|
+
lens += 3
|
|
170
|
+
ctx = RowCtx.tree(one, lens, 1)
|
|
171
|
+
hh = m.tree(ids[TT + 3:TT + 4].view(1, 1), ctx)
|
|
172
|
+
RR["after_commit3_maxdiff"] = float((m.logits(hh).float() - zr[TT + 3:TT + 4]).abs().max())
|
|
173
|
+
# exact speculative decoding: MTP chain + suffix chain, greedy, then certificate on the fp32 reference
|
|
174
|
+
try:
|
|
175
|
+
m.reset()
|
|
176
|
+
eng = SP.SpecEngine(m, D=2 if m.mtp else 0, C=4, T=0.0)
|
|
177
|
+
eng.capture(use_graph=True)
|
|
178
|
+
out = eng.generate(ids[:TT].tolist(), ng)
|
|
179
|
+
o = torch.tensor(out["out"], device="cuda")
|
|
180
|
+
zr2 = pref.ref_logits(ref, torch.cat([ids[:TT], o]))
|
|
181
|
+
gp = pref.gaps(zr2[TT - 1:TT - 1 + o.numel()], o)
|
|
182
|
+
RR["spec"] = {"tok_per_pass": out["tok_per_pass"], "gap_max": float(gp.max()), "n": int(o.numel()),
|
|
183
|
+
"mtp": m.mtp is not None}
|
|
184
|
+
except Exception as e:
|
|
185
|
+
import traceback
|
|
186
|
+
RR["spec_err"] = traceback.format_exc()[-1500:]
|
|
187
|
+
R[f"smax{smax}"] = RR
|
|
188
|
+
del m
|
|
189
|
+
torch.cuda.empty_cache()
|
|
190
|
+
R["summary"] = {k: v for k, v in R.items() if k != "unit"}
|
|
191
|
+
return R
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def main_tp(rank=0, world=1, repo="tiny-random/glm-5.3", T=200, n_gen=16, seed=0, shards=("ep", "ep_tp")):
|
|
195
|
+
"""TP/EP correctness on the multi-GPU box: every rank builds its shard; rank 0 compares with the fp32 HF
|
|
196
|
+
reference (tiny model fits one GPU) and with the single-GPU engine. Also: SpecEngine + CUDA graph across ranks,
|
|
197
|
+
and token agreement across ranks."""
|
|
198
|
+
import torch.distributed as dist
|
|
199
|
+
import pmodel
|
|
200
|
+
import pref
|
|
201
|
+
import spec as SP
|
|
202
|
+
path = snap(repo)
|
|
203
|
+
g = torch.Generator().manual_seed(seed)
|
|
204
|
+
R = {"world": world}
|
|
205
|
+
ref = None
|
|
206
|
+
if rank == 0:
|
|
207
|
+
ref, _ = hf_fp32(path)
|
|
208
|
+
def log(*a):
|
|
209
|
+
print(f"[r{rank} {time.strftime('%H:%M:%S')}]", *a, flush=True)
|
|
210
|
+
for shard in shards:
|
|
211
|
+
log("build", shard)
|
|
212
|
+
tp = {"rank": rank, "world": world, "group": None}
|
|
213
|
+
m = pmodel.PModel(path, B=1, smax=512, tp=tp, expert_shard=shard, verbose=False)
|
|
214
|
+
V = m.V
|
|
215
|
+
ids = torch.randint(100, V - 100, (T,), generator=torch.Generator().manual_seed(seed)).cuda()
|
|
216
|
+
log("prefill")
|
|
217
|
+
h = m.prefill(ids, b=0)
|
|
218
|
+
z = m.logits(h).float()
|
|
219
|
+
torch.cuda.synchronize()
|
|
220
|
+
log("prefill done; eager spec")
|
|
221
|
+
eng = SP.SpecEngine(m, D=2 if m.mtp else 0, C=4, T=0.0)
|
|
222
|
+
m.reset()
|
|
223
|
+
out0 = eng.generate(ids.tolist(), n_gen)
|
|
224
|
+
torch.cuda.synchronize()
|
|
225
|
+
log("eager spec done", out0["passes"], "; capture")
|
|
226
|
+
m.reset()
|
|
227
|
+
eng.capture(use_graph=True)
|
|
228
|
+
log("captured")
|
|
229
|
+
out = eng.generate(ids.tolist(), n_gen)
|
|
230
|
+
torch.cuda.synchronize()
|
|
231
|
+
log("graph spec done", out["passes"])
|
|
232
|
+
o = torch.tensor(out["out"], device="cuda")
|
|
233
|
+
allo = [torch.zeros_like(o) for _ in range(world)]
|
|
234
|
+
dist.all_gather(allo, o)
|
|
235
|
+
RR = {"ranks_agree": all(bool((a == o).all()) for a in allo), "tok_per_pass": out["tok_per_pass"],
|
|
236
|
+
"graph_eq_eager": out["out"] == out0["out"]}
|
|
237
|
+
if rank == 0:
|
|
238
|
+
zr = pref.ref_logits(ref, ids)
|
|
239
|
+
RR["prefill_maxdiff"] = float((z - zr).abs().max())
|
|
240
|
+
RR["prefill_gap_max"] = float(pref.gaps(zr, z.argmax(-1)).max())
|
|
241
|
+
zr2 = pref.ref_logits(ref, torch.cat([ids, o]))
|
|
242
|
+
RR["spec_gap_max"] = float(pref.gaps(zr2[T - 1:T - 1 + o.numel()], o).max())
|
|
243
|
+
R[shard] = RR
|
|
244
|
+
del m, eng
|
|
245
|
+
torch.cuda.empty_cache()
|
|
246
|
+
return R
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def main_dbg(repo="tiny-random/glm-5.3", T=24, seed=0, smax=120):
|
|
250
|
+
"""per-layer / per-module comparison of our prefill with the fp32 HF forward."""
|
|
251
|
+
import pmodel
|
|
252
|
+
from blocks import rms
|
|
253
|
+
import pblocks as PB
|
|
254
|
+
from ctx import RowCtx
|
|
255
|
+
path = snap(repo)
|
|
256
|
+
ref, _ = hf_fp32(path)
|
|
257
|
+
ids = torch.randint(100, ref.config.vocab_size - 100, (T,), generator=torch.Generator().manual_seed(seed)).cuda()
|
|
258
|
+
cap = {}
|
|
259
|
+
|
|
260
|
+
def hk(name):
|
|
261
|
+
def f(mod, inp, out):
|
|
262
|
+
o = out[0] if isinstance(out, tuple) else out
|
|
263
|
+
cap[name] = (inp[0].detach().float()[0] if isinstance(inp, tuple) and len(inp) and torch.is_tensor(inp[0])
|
|
264
|
+
else None, o.detach().float()[0] if o.dim() == 3 else o.detach().float())
|
|
265
|
+
if isinstance(out, tuple) and len(out) > 2 and torch.is_tensor(out[2]):
|
|
266
|
+
cap[name + "_topk"] = out[2].detach()[0]
|
|
267
|
+
return f
|
|
268
|
+
for i, L in enumerate(ref.model.layers):
|
|
269
|
+
L.self_attn.register_forward_hook(hk(f"attn{i}"))
|
|
270
|
+
L.mlp.register_forward_hook(hk(f"mlp{i}"))
|
|
271
|
+
L.register_forward_hook(hk(f"layer{i}"))
|
|
272
|
+
with torch.no_grad():
|
|
273
|
+
ref(input_ids=ids[None], use_cache=False)
|
|
274
|
+
m = pmodel.PModel(path, B=1, smax=smax)
|
|
275
|
+
R = {}
|
|
276
|
+
ctx = RowCtx("prefill", b=0, pos0=0)
|
|
277
|
+
x = m.embed[ids]
|
|
278
|
+
|
|
279
|
+
def rel(a, b):
|
|
280
|
+
return round(float((a.float() - b).abs().max() / (b.abs().max() + 1e-12)), 5)
|
|
281
|
+
with torch.no_grad():
|
|
282
|
+
for i, L in enumerate(m.layers):
|
|
283
|
+
h = rms(x, L.n1, L.eps, L.off)
|
|
284
|
+
a = L.mix.prefill(h, ctx)
|
|
285
|
+
ai, ao = cap[f"attn{i}"]
|
|
286
|
+
if f"attn{i}_topk" in cap and getattr(ctx, "_topk", None) and "cur" in ctx._topk and T > 128:
|
|
287
|
+
tr, to = cap[f"attn{i}_topk"].long(), ctx._topk["cur"].long()
|
|
288
|
+
Sx = tr.shape[0]
|
|
289
|
+
mr = torch.zeros(Sx, Sx + 1, dtype=torch.bool, device=tr.device).scatter_(1, tr.clamp(max=Sx), True)[:, :Sx]
|
|
290
|
+
mo_ = torch.zeros(Sx, Sx + 1, dtype=torch.bool, device=tr.device).scatter_(1, to.clamp(max=Sx), True)[:, :Sx]
|
|
291
|
+
causal = torch.ones(Sx, Sx, dtype=torch.bool, device=tr.device).tril()
|
|
292
|
+
mr, mo_ = mr & causal, mo_ & causal
|
|
293
|
+
R[f"attn{i}_topk_rows_identical"] = float((mr == mo_).all(-1).float().mean())
|
|
294
|
+
R[f"attn{i}_topk_sym_diff_max"] = int((mr ^ mo_).sum(-1).max())
|
|
295
|
+
R[f"attn{i}_in"] = rel(h, ai) if ai is not None else None
|
|
296
|
+
R[f"attn{i}_out"] = rel(a, ao)
|
|
297
|
+
x = x + a
|
|
298
|
+
h2 = rms(x, L.n2, L.eps, L.off)
|
|
299
|
+
# feed the reference's own mlp input to isolate the MLP
|
|
300
|
+
mi, mo = cap[f"mlp{i}"]
|
|
301
|
+
R[f"mlp{i}_in"] = rel(h2, mi)
|
|
302
|
+
R[f"mlp{i}_out_own_input"] = rel(L.mlp(mi.to(torch.bfloat16)), mo)
|
|
303
|
+
x = x + L.mlp(h2)
|
|
304
|
+
R[f"layer{i}"] = rel(x, cap[f"layer{i}"][1])
|
|
305
|
+
return R
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def main_real(rank=0, world=1, model="/vol/hf/hub/models--zai-org--GLM-5.3/snapshots/ba32f8c19c8738e2c57c71798c601d477a7bf844",
|
|
309
|
+
nl=4, T=64, seed=0, shard="ep", fast=False):
|
|
310
|
+
"""reduced-depth check on the REAL checkpoint (first nl layers + final norm + head), TP/EP over the ranks, vs
|
|
311
|
+
the HF fp32 model with the same nl layers on rank 0. Also times weight loading."""
|
|
312
|
+
import torch.distributed as dist
|
|
313
|
+
import pmodel
|
|
314
|
+
import pref
|
|
315
|
+
import pblocks as PB
|
|
316
|
+
PB.FAST = fast
|
|
317
|
+
t0 = time.time()
|
|
318
|
+
m = pmodel.PModel(model, B=1, smax=256, tp={"rank": rank, "world": world, "group": None}, expert_shard=shard,
|
|
319
|
+
layers=range(nl), load_mtp=False, verbose=(rank == 0))
|
|
320
|
+
R = {"load_s": time.time() - t0, "world": world, "nl": nl, "mem_gb": torch.cuda.memory_allocated() / 1e9,
|
|
321
|
+
"weight_bytes": m.weight_bytes()}
|
|
322
|
+
ids = torch.randint(1000, 100000, (T,), generator=torch.Generator().manual_seed(seed)).cuda()
|
|
323
|
+
with torch.no_grad():
|
|
324
|
+
h = m.prefill(ids, b=0)
|
|
325
|
+
z = m.logits(h).float().cpu()
|
|
326
|
+
del m
|
|
327
|
+
torch.cuda.empty_cache()
|
|
328
|
+
dist.barrier()
|
|
329
|
+
if rank == 0:
|
|
330
|
+
t1 = time.time()
|
|
331
|
+
ref, miss = hf_fp32(model, nl=nl)
|
|
332
|
+
R["ref_missing"] = miss[:10]
|
|
333
|
+
zr = pref.ref_logits(ref, ids).cpu()
|
|
334
|
+
R["ref_s"] = time.time() - t1
|
|
335
|
+
R["rel_maxdiff"] = float((z - zr).abs().max() / zr.std())
|
|
336
|
+
R["argmax_agree"] = float((z.argmax(-1) == zr.argmax(-1)).float().mean())
|
|
337
|
+
R["gap_max"] = float(pref.gaps(zr, z.argmax(-1)).max())
|
|
338
|
+
R["zr_std"] = float(zr.std())
|
|
339
|
+
dist.barrier()
|
|
340
|
+
return R
|
package/p27/t_glu.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""fused fp8 MoE GLU epilogue exactness/performance."""
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
def gb(fn,n=200):
|
|
5
|
+
for _ in range(3): fn()
|
|
6
|
+
torch.cuda.synchronize(); g=torch.cuda.CUDAGraph()
|
|
7
|
+
with torch.cuda.graph(g): fn()
|
|
8
|
+
torch.cuda.synchronize(); a=torch.cuda.Event(True); b=torch.cuda.Event(True); a.record()
|
|
9
|
+
for _ in range(n): g.replay()
|
|
10
|
+
b.record(); torch.cuda.synchronize(); return a.elapsed_time(b)/n
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
import quant as Q
|
|
14
|
+
import torch.nn.functional as F
|
|
15
|
+
rows=[]
|
|
16
|
+
for R in (1,12,64):
|
|
17
|
+
torch.manual_seed(R); E,I,K,k=32,256,6144,8; qn=qk=128; BM=16
|
|
18
|
+
x=torch.randn(R,K,device='cuda',dtype=torch.bfloat16)
|
|
19
|
+
w=(torch.randn(E,2*I,K,device='cuda')*.02).to(torch.float8_e4m3fn)
|
|
20
|
+
s=torch.rand(E,2*I//qn,K//qk,device='cuda')*.01+.001
|
|
21
|
+
idx=torch.stack([torch.randperm(E,device='cuda')[:k] for _ in range(R)])
|
|
22
|
+
pr,be,po=Q.moe_align(idx,E,0,BM)
|
|
23
|
+
a=Q.moe_fp8glu_gemm(x,w,s,qn,qk,pr,be,BM,I)
|
|
24
|
+
h=Q.moe_fp8_gemm(x,w,s,qn,qk,pr,be,BM)
|
|
25
|
+
ref=F.silu(h[:,:I])*h[:,I:]
|
|
26
|
+
def unf():
|
|
27
|
+
hh=Q.moe_fp8_gemm(x,w,s,qn,qk,pr,be,BM); return F.silu(hh[:,:I])*hh[:,I:]
|
|
28
|
+
rows.append({'R':R,'maxdiff':(a[pr>=0].float()-ref[pr>=0].float()).abs().max().item(),'rel':((a[pr>=0].float()-ref[pr>=0].float()).abs().max()/ref[pr>=0].float().abs().max()).item(),
|
|
29
|
+
'fused64_ms':gb(lambda:Q.moe_fp8glu_gemm(x,w,s,qn,qk,pr,be,BM,I)),'fused32_ms':gb(lambda:Q.moe_fp8glu_gemm(x,w,s,qn,qk,pr,be,BM,I,BN=32)),'fused16_ms':gb(lambda:Q.moe_fp8glu_gemm(x,w,s,qn,qk,pr,be,BM,I,BN=16)),'unfused_ms':gb(unf)})
|
|
30
|
+
return {'rows':rows}
|
package/p27/t_gsuf.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""In-graph suffix exactness/equivalence smoke test."""
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
def main(n_gen=40, seed=0):
|
|
5
|
+
import t_glm
|
|
6
|
+
import pmodel
|
|
7
|
+
import spec as SP
|
|
8
|
+
path = t_glm.snap("tiny-random/glm-5.3")
|
|
9
|
+
m = pmodel.PModel(path, B=1, smax=256, verbose=False)
|
|
10
|
+
ids = torch.randint(100, m.V - 100, (36,), generator=torch.Generator().manual_seed(seed)).cuda().tolist()
|
|
11
|
+
R = {}
|
|
12
|
+
for T in (0.0, 1.0):
|
|
13
|
+
outs = {}
|
|
14
|
+
for gs in (False, True):
|
|
15
|
+
eng = SP.SpecEngine(m, D=2 if m.mtp else 0, C=6, T=T, uid=733 + int(T), SN=3, in_graph_suffix=gs)
|
|
16
|
+
eng.capture(use_graph=True)
|
|
17
|
+
m.reset()
|
|
18
|
+
outs[gs] = eng.generate(ids, n_gen)
|
|
19
|
+
R[f"T{T}_gs{int(gs)}_tok_per_pass"] = outs[gs]["tok_per_pass"]
|
|
20
|
+
R[f"T{T}_exact"] = outs[False]["out"] == outs[True]["out"]
|
|
21
|
+
R[f"T{T}_same_acceptance"] = abs(outs[False]["tok_per_pass"] - outs[True]["tok_per_pass"]) < 1e-9
|
|
22
|
+
R["summary"] = dict(R)
|
|
23
|
+
return R
|