"""Verify sparse expert routing, capacity overflow, and a learned gate."""
import torch
from torch import nn
from torch.nn import functional as F
from lab_tools import run_exercise
def route(logits,k):
ranked=logits.argsort(dim=1,descending=True,stable=True)[:,:k]
weights=logits.gather(1,ranked).softmax(1)
return ranked,weights
def dispatch(data,ids,weights,experts):
result=torch.zeros_like(data)
counts=[]
for expert_index,expert in enumerate(experts):
token,slot=(ids==expert_index).nonzero(as_tuple=True)
counts.append(len(token))
if len(token):
result.index_add_(0,token,expert(data[token])*weights[token,slot,None])
return result,counts
def capped(logits,capacity):
chosen=[]
used=[0]*logits.shape[1]
for ranking in logits.argsort(dim=1,descending=True,stable=True).tolist():
expert=next((index for index in ranking if used[index]<capacity),None)
chosen.append(expert)
if expert is not None:
used[expert]+=1
return chosen,used
def sparse_run(checks):
logits=torch.tensor([[-5.,-2.,-2.,-6.],[2.,0.,-4.,1.]],dtype=torch.float64)
ids,weights=route(logits,2)
ids_shift,weight_shift=route(logits+100,2)
checks.expect("frontier_topk",logits.tolist(),"Choose stable top-2 experts and use softmax even when all selected logits are negative",
[[[1,2],[0,3]],[1.,1.],[.5,.5],True,True],
[ids.tolist(),[round(float(x),8) for x in weights.sum(1)],weights[0].tolist(),
bool(torch.equal(ids,ids_shift)),bool(torch.allclose(weights,weight_shift))])
values=torch.tensor([[2.,4.],[1.,3.]],dtype=torch.float64)
experts=[]
for gain in (1.,2.,4.,8.):
layer=nn.Linear(2,2,bias=False,dtype=torch.float64)
with torch.no_grad():
layer.weight.copy_(torch.eye(2,dtype=torch.float64)*gain)
experts.append(layer)
result,counts=dispatch(values,ids,weights,experts)
second_gain=(torch.exp(torch.tensor(1.,dtype=torch.float64))+8)/(torch.exp(torch.tensor(1.,dtype=torch.float64))+1)
reference=torch.stack((values[0]*3,values[1]*second_gain))
checks.expect("frontier_sparse_dispatch",values.tolist(),
"Execute only selected rows for each expert and compare the weighted output to manual mixing",
[[1,1,1,1],4,True],[counts,sum(counts),bool(torch.allclose(result,reference))])
loads=[[3.,2.],[3.,2.],[3.,2.]]
assigned,used=capped(torch.tensor(loads),1)
checks.expect("frontier_capacity",loads,"Route to a lower-ranked expert after capacity fills, and record overflow",
[[0,1,None],[1,1]],[assigned,used])
def train_gate(checks):
torch.manual_seed(692)
model=nn.Linear(2,4)
target=torch.arange(4)
training=torch.tensor([[2.,1.],[-2.,1.],[-2.,-1.],[2.,-1.]])
heldout=torch.tensor([[1.5,.7],[-1.2,.8],[-1.8,-.9],[1.7,-.6]])
opt=torch.optim.SGD(model.parameters(),lr=.2)
for _ in range(120):
opt.zero_grad(set_to_none=True)
F.cross_entropy(model(training),target).backward()
opt.step()
with torch.inference_mode():
ranks,weights=route(model(heldout),1)
observed=ranks[:,0].tolist()
checks.expect("frontier_learned_gate",heldout.tolist(),
"Train a supervised toy router and verify assignments on new points",
[[0,1,2,3],True],[observed,bool((weights==1).all())])
def exercise(checks,_):
torch.set_num_threads(1)
sparse_run(checks)
train_gate(checks)
if __name__=="__main__":
run_exercise(exercise)
本例需在 CPython 3.12.14、PyTorch 2.10.0+cpu、NumPy 2.5.4、SciPy 1.18.1,本机固定数据。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、PyTorch 2.10.0+cpu、NumPy 2.5.4、SciPy 1.18.1,本机固定数据。
入口文件:projects/ai-frontier-research/moe_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
moe_lab.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、PyTorch 2.10.0+cpu、NumPy 2.5.4、SciPy 1.18.1,本机固定数据。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a12.zip
课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip