Mixture of Experts
Study top-k mixture-of-experts routing, capacity, balancing, active and total parameters, and controlled experiments on specialization.
After this lesson you can
- Implement top-k routing, capacity, and expert dispatch.
- Derive the Switch auxiliary balancing loss and its router gradient.
- Distinguish active compute, hosted parameters, dropped assignments, and communication.
- Explain router z-loss and bias-based balancing.
- Interpret controlled MoE experiments with their limitations.
Before you start
Many parameters, few experts per token
A mixture of experts layer replaces an FFN with several expert functions and a router. The router calculates scores per token; only a subset of experts processes that token and their outputs are combined. Many parameters can thus be stored without executing all at every position. Weight storage and moving tokens to expert-hosting devices still cost resources. Classical mixtures predate large-scale sparse variants; Shazeer et al. study such a conditional layer.
If , a linear router gives and . Top-k routing selects the highest-scoring indices. A common convention renormalizes selected probabilities and calculates . If , renormalization yields weight one: the main loss receives no gradient through that single weight’s magnitude within a fixed-selection region. Other implementations retain the unnormalized probability; check the convention before reasoning about gradients.
Discrete selection has no ordinary derivative when expert ordering changes. Away from ties, autograd treats the chosen set as fixed and differentiates selected weights; if renormalized only among chosen experts, unchosen logits do not affect those weights. With full softmax without that renormalization, denominators can provide gradients to unselected logits. Both claims depend on the actual formula, not merely the name “top-k”.
For example, with full probabilities and , renormalizing the selected two gives . If the first is then dropped for capacity and there is no second renormalization, the second contributes weight 0.375, not one. The residual block is added outside that combination. A variant renormalizing after dropping changes scale and behavior when every route is lost; that case must be explicitly defined.
Practical dispatch groups assignments by expert for batched processing, then gathers outputs at original positions. Sorting and grouping add work, and uneven expert batches can underuse the GPU even when mean route count looks small. An educational implementation processing each token in a Python loop cannot measure that cost representatively. The NumPy control uses vectorized assignment and accumulation; its later reference loop only checks the result.
Capacity and dropping
For tokens, routed experts, assignments per token, and factor , one expert capacity convention is . The average does not guarantee every expert receives at most : a concentrated router can overflow some and leave others empty. Other conventions define the factor relative to or impose a minimum; record which your implementation uses.
This lesson first computes top-k and weights, accepts each expert’s first assignments in token order, and zeros the rest without renormalizing survivors. If every route for a token is dropped, MoE output is zero; the block’s residual connection can preserve input. Changing order, dropping policy, or renormalizing afterward changes the result. Inference can instead choose enough capacity to avoid dropping, with a different memory cost.
For 12 tokens, eight experts, top-2, and , capacity is per expert. There are 24 slots in total, but drops can occur when some are empty while others receive more than three requests. Higher capacity reduces the likelihood for a given distribution but can increase padding and wasted work. Dropped-assignment rate and the rate of tokens losing all routes are distinct metrics: with top-2, losing one route need not lose the other.
Balancing loss
The Switch auxiliary loss for top-1 uses as the fraction of hard selections of expert and as its mean full probability:
The expression and conventions are in Switch Transformer. Assuming , Cauchy-Schwarz gives , with equality when . That proof needs ; it does not show that every hard distribution or top-k variant always minimizes the same objective. In the usual calculation is treated as constant without gradient and differentiation passes through . Using only hard assignments in both factors provides no such router gradient.
For a batch of tokens and , holding fixed, the derivative with respect to a logit is . The term compares expert load with the token-probability-weighted average load. The next cell checks this derivative with central differences and checks dispatch and capacity; the reference loop traverses assignments only to verify the vectorized version.
Auxiliary loss adds a distribution signal to the main objective, but its coefficient must be chosen carefully. Too weak a signal may not correct persistent concentration; too strong a signal may favor uniform distribution while harming the task. The regression experiment fixes a coefficient to inspect its effects, not recommend it for other models. Also observe expert loads and drops: nearly uniform mean probabilities can coexist with concentrated hard decisions.
import numpy as np
def softmax(x):
e=np.exp(x-x.max(axis=-1,keepdims=True))
return e/e.sum(axis=-1,keepdims=True)
def route(logits,k,capacity):
T,E=logits.shape
if not 1<=k<=E or capacity<0: raise ValueError('k o capacidad inválidos')
p=softmax(logits)
chosen=np.argsort(-logits,axis=1,kind='stable')[:,:k]
weights=np.take_along_axis(p,chosen,axis=1)
weights/=weights.sum(axis=1,keepdims=True)
token=np.repeat(np.arange(T),k); expert=chosen.reshape(-1)
order=np.argsort(expert,kind='stable'); sorted_expert=expert[order]
positions=np.arange(len(order))
start=np.maximum.accumulate(np.where(np.r_[True,sorted_expert[1:]!=sorted_expert[:-1]],positions,0))
accepted=np.empty(len(order),dtype=bool); accepted[order]=(positions-start)<capacity
return token,expert,weights.reshape(-1)*accepted,accepted
def dispatch(x,W,token,expert,weight):
# W[e] actúa sobre la derecha; cada asignación se procesa en paralelo.
part=np.einsum('bi,bij->bj',x[token],W[expert])*weight[:,None]
out=np.zeros((len(x),W.shape[2])); np.add.at(out,token,part)
return out
rng=np.random.default_rng(17)
logits=rng.normal(size=(12,8)); x=rng.normal(size=(12,4)); W=rng.normal(size=(8,4,4))
token,expert,weight,accepted=route(logits,2,3)
load=np.bincount(expert[accepted],minlength=8)
assert (load<=3).all() and np.isfinite(dispatch(x,W,token,expert,weight)).all()
reference=np.zeros((len(x),W.shape[2]))
for t,e,g in zip(token,expert,weight):
reference[t]+=g*(x[t] @ W[e])
assert np.allclose(dispatch(x,W,token,expert,weight),reference)
print('carga por experto:',load,'asignaciones descartadas:',np.sum(~accepted))
_,_,full_weights,full=route(logits,2,12)
assert full.all() and np.allclose(full_weights.reshape(12,2).sum(axis=1),1)
_,_,empty,accepted_empty=route(logits,2,0)
assert not accepted_empty.any() and np.all(empty==0)
p=softmax(logits); f=np.bincount(logits.argmax(axis=1),minlength=8)/len(logits)
def auxiliary(a): return 8*np.dot(f,softmax(a).mean(axis=0))
analytic=8/len(logits)*p*(f[None,:]-(p*f).sum(axis=1,keepdims=True))
h=1e-6; errors=[]
for i,j in ((0,0),(1,4),(8,7)):
plus=logits.copy();minus=logits.copy();plus[i,j]+=h;minus[i,j]-=h
errors.append(abs((auxiliary(plus)-auxiliary(minus))/(2*h)-analytic[i,j]))
print('pérdida auxiliar:',auxiliary(logits),'máximo error de gradiente:',max(errors))
assert max(errors)<1e-8Collapse in controlled regression
The figure presents eight real synthetic-regression training runs calculated by the next cell. There are 200 points from -2 to 2 and target on the negative half and on the positive half. Two linear experts receive top-1 with capacity 100 each; expert 0 starts favored. To let the main loss update the router, output uses the selected expert’s full probability without renormalizing to one. Assignments over capacity are zeroed in input order. This order is correlated with and affects the trial; it is not representative of production dispatch.
Auxiliary loss uses , z-loss uses , and the bias alternative updates at rate 0.02 after each step. In one run with none of the three mechanisms, at step 500 expert 0 still received every selection and 50% of tokens were dropped. With only auxiliary balancing, expert 0 load was 52.5% and drops 2.5%. With only z-loss, load stayed concentrated: reducing z-loss is not the same as balancing. These are example results on a fixed set, not convergence guarantees or language evaluation.
With only auxiliary balancing, experts’ final slopes are approximately 1.88 and -0.84. The router chooses the first for negative and the second for sufficiently positive values in this set; target slopes are 2 and -1. This signals distribution by region, not exact equality between expert and target: output is also multiplied by router probability and some points are dropped. The figure displays final slopes even if the control is moved to an earlier step.
The cell checks the main-loss gradient under fixed selection using central differences and reproduces eight combinations. Balancing loss differentiates only through probabilities; selection bias is updated outside the gradient. Values are saved in router-training.json in the execution environment.
import json
from pathlib import Path
import numpy as np
def train(aux,z_loss,balance,steps=500):
n=200; E=2; x=np.linspace(-2,2,n)
y=np.where(x<0,2*x,-x)
slope=np.array([.1,-.1]); intercept=np.zeros(E)
rw=np.array([0.,0.]); rb=np.array([2.,0.]); selection_bias=np.zeros(E)
lr=.04; alpha=.5 if aux else 0.; beta=.01 if z_loss else 0.
records=[]
for step in range(steps+1):
logits=x[:,None]*rw+rb
shifted=logits-logits.max(axis=1,keepdims=True)
ex=np.exp(shifted); p=ex/ex.sum(axis=1,keepdims=True)
selected=np.argmax(logits+selection_bias,axis=1)
f=np.bincount(selected,minlength=E)/n
allowed=np.zeros(n,dtype=bool); capacity=int(np.ceil(n/E))
for e in range(E):
positions=np.flatnonzero(selected==e)
allowed[positions[:capacity]]=True
ps=p[np.arange(n),selected]
predictions=x[:,None]*slope+intercept
v=predictions[np.arange(n),selected]
out=allowed*ps*v
residual=out-y; mse=np.mean(residual**2)
lse=np.log(ex.sum(axis=1))+logits.max(axis=1)
z=np.mean(lse**2)
if step%10==0 or step==steps:
entropy=-np.sum(np.where(f>0,f*np.log(np.maximum(f,1e-30)),0))
records.append({'step':step,'loss':float(mse),'load0':float(f[0]),
'entropy':float(entropy),'drop':float(1-allowed.mean()),'z':float(z)})
if step==steps: break
one=np.eye(E)[selected]
common=2*residual*allowed/n
grad_slope=np.sum((common*ps*x)[:,None]*one,axis=0)
grad_intercept=np.sum((common*ps)[:,None]*one,axis=0)
grad_logits=(common*v*ps)[:,None]*(one-p)
grad_logits+=alpha*E/n*p*(f[None,:]-(p*f).sum(axis=1,keepdims=True))
grad_logits+=beta*(2/n)*lse[:,None]*p
slope-=lr*grad_slope;intercept-=lr*grad_intercept
rw-=lr*(grad_logits*x[:,None]).sum(axis=0); rb-=lr*grad_logits.sum(axis=0)
if balance: selection_bias+=.02*np.sign(1/E-f)
assert np.isfinite(slope).all() and np.isfinite(intercept).all()
return {'aux':aux,'z_loss':z_loss,'balance':balance,'records':records,
'slopes':slope.tolist(),'intercepts':intercept.tolist(),
'router_w':rw.tolist(),'router_b':rb.tolist(),'selection_bias':selection_bias.tolist()}
# Comprueba la derivada del peso top-1 sin renormalizar, con selección fija.
rng=np.random.default_rng(7)
a=rng.normal(size=(5,2)); p=np.exp(a-a.max(axis=1,keepdims=True));p/=p.sum(axis=1,keepdims=True)
chosen=np.argmax(a,axis=1); one=np.eye(2)[chosen]
v=rng.normal(size=5); target=rng.normal(size=5); accepted=np.array([1,1,0,1,1])
def objective(logits):
e=np.exp(logits-logits.max(axis=1,keepdims=True));probs=e/e.sum(axis=1,keepdims=True)
out=accepted*probs[np.arange(5),chosen]*v
return np.mean((out-target)**2)
selected_p=p[np.arange(5),chosen];residual=accepted*selected_p*v-target
analytic=(2*residual*accepted*v*selected_p/5)[:,None]*(one-p)
errors=[]
for i in range(5):
for j in range(2):
plus=a.copy();minus=a.copy();plus[i,j]+=1e-6;minus[i,j]-=1e-6
errors.append(abs((objective(plus)-objective(minus))/2e-6-analytic[i,j]))
print('error máximo gradiente top-1 con selección fija:',max(errors))
assert max(errors)<1e-8
results=[train(a,z,b) for a in (False,True) for z in (False,True) for b in (False,True)]
Path('router-training.json').write_text(json.dumps(results,separators=(',',':')),encoding='utf8')
for row in results:
print(row['aux'],row['z_loss'],row['balance'],row['records'][0],row['records'][-1])
Parameters and computation
A bias-free SwiGLU expert with width and intermediate dimension has weights. With routed experts, shared experts always executed, and a bias-free linear router, the layer has total parameters. If each token reaches experts plus shared, active weights are . Approximating forward as two FLOPs per active weight omits activations, softmax, selection, drops, and communication.
For those values each expert has 8650752 weights; all 66 experts and router total 571080704, while eight active experts and router total 69337088 weights per token. Do not confuse that figure with total memory that must host all experts. DeepSeekMoE explores finer and shared experts; Mixtral and OLMoE illustrate other configurations. Their full-model counts include more than this one layer.
Figure profiles use published dimensions of Mixtral 8x7B, DeepSeek-V3, and OLMoE 1B-7B. For example, Mixtral uses eight experts and top-2; V3 specifies 256 routed, top-8, and one shared; OLMoE specifies 64 and top-8. The calculator applies the same three-matrix and bias-free linear-router formula to all: this compares one layer under that convention, not each model’s full parameter count. In particular, V3 and OLMoE scores and selection constraints differ from this lesson’s simplified softmax router.
In the example, two bytes per weight give approximately 1.142 decimal GB to host full-layer weights. Multiplying only active weights by two understates capacity if remaining experts must also reside on device. Training adds gradients, optimizer states, activations, and dispatch buffers; their types and fragmentation policy depend on implementation. Active FLOPs are an ideal product count: elementwise operations and router have costs, and dropping reduces experts actually executed for that token.
Comparison with a dense FFN must state what budget is matched. If the sum of intermediate widths of active experts is matched, dominant per-token matrix counts can be comparable before drops. This does not equalize total parameters, traffic, latency, or communication. With experts distributed across devices, representations must be sent to experts and outputs returned to original order. Unbalanced distribution may make the most-loaded device determine step time even when global operation count is reasonable. Expert parallelism is studied further in the scaling module.
Stability and alternatives
The ST-MoE router z-loss averages over tokens. It controls logsumexp, does not separately bound every logit, and does not replace balancing loss. Computing router normalization in FP32 can reduce numerical errors but does not guarantee stability of the entire training run.
A common shift illustrates the distinction: adding the same constant to all logits preserves softmax and top-k order but changes logsumexp and hence z-loss. Conversely, logsumexp near zero alone does not guarantee bounded logit differences. To diagnose a loss spike compare maximum and distribution of logits, z-loss, fraction of non-finite values, and load. If the main symptom is experts never receiving tokens, start with distribution and balance; if slots are insufficient, inspect capacity and dropping policy.
Fine-grained and shared experts distribute work between specialized routes and a common route. Auxiliary-loss-free balancing can adjust per-expert biases based on load: a bias is added for selection and updated between steps without confusing that signal with the probability weighting output. Wang et al. study this strategy. In expert choice, experts choose tokens rather than each token choosing a fixed expert count; load and coverage guarantees change.
Fine-grained division reduces individual width and activates more experts, allowing similar active work while increasing possible combinations. It is not mathematical function equivalence: selecting several small FFNs and summing outputs need not reproduce a large FFN. Shared experts run for every token and must always be included in active accounting. DeepSeek-V3 describes an MoE with shared experts and bias-based balancing; its details do not follow from this lesson’s toy.
For a simple bias update, compare observed load with target : increase an underused expert’s bias and reduce an overloaded expert’s. Update rate affects oscillation and adaptation; neither this rule nor auxiliary loss ensures useful specialization. In expert choice, fixing how many tokens each expert chooses makes capacity explicit, but can give different tokens different expert counts and requires a policy for unselected tokens.
Mini Llama with experts
The next lab reconstructs lesson 13’s mini Llama from the checkpoint you generated there and replaces its FFNs with eight top-2 experts. The original dense block has intermediate width 176. Without a shared expert each expert has width 88 and two are chosen; with one shared expert the two chosen have width 59 and the shared one 58. Before drops both paths use 176 intermediate units per token like the dense model, plus router. Initial expert weights copy pieces of the trained FFN; routes and their combination do not exactly preserve the original function.
To include code and digits absent from the previous vocabulary, the lab appends new characters and preserves existing indices. New embedding rows are reinitialized; the head remains tied to that embedding. It alternates text batches from the previous corpus and a repeated synthetic-code fragment. Two validation windows are sampled with another seed from the same streams and may overlap training data; they are not independent language-quality evaluation. All models receive the same batches but have different total parameter counts.
In a 20-step RTX 3060 run, mean losses over those two windows were 3.0795 dense, 3.0398 MoE, and 3.0369 MoE with shared expert. These brief samples with repeated data and one seed are insufficient to conclude one architecture is better. Per-block printed load and drops correspond to the last validation batch, not training average. Capacity factor 1.25 applies to top-2 assignments and weights are calculated before dropping, as in the earlier control.
An additional 100-step run with the same first 20 batches and windows obtained mean losses 2.1670, 2.1320, and 2.1017 respectively. The map retains the 20-step run; it does not combine its routes with longer training. Repeated code and possible window overlap limit interpretation of both comparisons.
The MoE objective adds 0.01 times an adaptation of balancing loss and 0.001 times mean block z-loss to language loss. Here counts top-2 choices and divides by , so components sum to one; it is not exactly Switch’s top-1 definition. Load calculation and selection are discrete, whereas the probability part receives gradient. Code processes assignments grouped by expert; the small expert loop and probe loops are educational, not an optimized production kernel.
The NumPy cell breaks ties by index with stable sorting; the PyTorch lab uses topk and does not promise the same tie order. For bitwise implementation comparison, define tie policy and check routes and combined output. Assignment order also matters when capacity is exhausted, even if logits and weights match.
The next map counts top-2 choices before capacity in two fixed 32-character sequences: one text and one synthetic code. Rows sum to 100% of assignments within each category; they are not percentages of tokens able to choose only one expert. The text has 25 letters and two punctuation marks, and the other has three digits and 24 nonwhite, nondigit code characters. These are very few examples, especially punctuation and digits; the map shows observed routes and does not prove stable specialization or causality.
A map row with 50% does not necessarily mean half of all corpus tokens use that expert. Its denominator includes only the two choices of characters in that category in the test sequence. With two punctuation marks, only four assignments form the whole row: changing one choice moves the percentage by 25 points. Real specialization study would require many sequences, categories defined before analysis, separate training and evaluation, multiple seeds, and a control comparing each expert’s global load. Routes can reflect position or frequency as well as character type.
The lab also measures two imbalances. Pre-capacity load indicates what the router requests; drops indicate what does not fit the acceptance rule. If a layer records many drops, inspect both with and batch size. Validation-loss changes require caution because enlarged vocabulary, data mixture, and windows are deliberately small. A longer run can be requested with ORYON_STEPS, but improvement observed in one trial still needs repetition and suitable evaluation.
To run the cell, save definitions from class RMS through class MiniLlama from lesson 13 in mini_llama_classes.py with their imports and retain checkpoint mini-llama.pt; also save lesson 12’s gpt_pytorch.py and the course corpus. Paths can be passed through ORYON_MINI_CODE, ORYON_MINI, ORYON_GPT_TORCH_CODE, and ORYON_CORPUS. The reader generates their own files. The cell saves results in mini-moe-results.json and permits step changes through ORYON_STEPS.
import json, math, os, string, time
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
assert torch.cuda.is_available(), 'se necesita CUDA'
mini_scope={}
exec(Path(os.environ.get('ORYON_MINI_CODE','mini_llama_classes.py')).read_text(encoding='utf8'),mini_scope)
gpt_scope={}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf8'),gpt_scope)
state=torch.load(Path(os.environ.get('ORYON_MINI','mini-llama.pt')),map_location='cpu',weights_only=True)
assert not state['qknorm']
config=state['config']; chars=list(state['characters'])
prose=Path(os.environ.get('ORYON_CORPUS','corpus.txt')).read_text(encoding='utf8')
assert all(c in chars for c in prose)
code=('def add(x,y):\n return x+y+12\nx=add(1,2)\nfor i in range(3):\n print(add(i,2))\n')*500
for c in sorted(set(code)-set(chars)): chars.append(c)
stoi={c:i for i,c in enumerate(chars)}
streams=[torch.tensor([stoi[c] for c in prose],dtype=torch.long),
torch.tensor([stoi[c] for c in code],dtype=torch.long)]
length=min(32,config['context']); steps=int(os.environ.get('ORYON_STEPS','20'))
assert steps>0 and all(len(s)>length+1 for s in streams)
class Expert(nn.Module):
def __init__(self,block,start,hidden):
super().__init__(); d=block.gate.in_features
self.gate=nn.Linear(d,hidden,bias=False); self.up=nn.Linear(d,hidden,bias=False)
self.down=nn.Linear(hidden,d,bias=False)
with torch.no_grad():
self.gate.weight.copy_(block.gate.weight[start:start+hidden])
self.up.weight.copy_(block.up.weight[start:start+hidden])
self.down.weight.copy_(block.down.weight[:,start:start+hidden])
def forward(self,x): return self.down(F.silu(self.gate(x))*self.up(x))
class Moe(nn.Module):
def __init__(self,block,shared):
super().__init__(); d=block.gate.in_features; h=block.gate.out_features
assert h%2==0 and h>=4
width=math.ceil(h/3) if shared else h//2
self.router=nn.Linear(d,8,bias=False)
self.experts=nn.ModuleList([Expert(block,(i%(h//width))*width,width) for i in range(8)])
self.shared=Expert(block,2*width,h-2*width) if shared else None
self.last_choices=None
def forward(self,x):
shape=x.shape; flat=x.reshape(-1,shape[-1]); T=len(flat)
logits=self.router(flat).float(); p=logits.softmax(-1)
top=logits.topk(2,dim=-1).indices
w=p.gather(1,top); w=w/w.sum(dim=1,keepdim=True)
f=F.one_hot(top,num_classes=8).float().sum((0,1))/(2*T)
self.aux=8*(f.detach()*p.mean(0)).sum()
self.z=logits.logsumexp(-1).square().mean()
self.last_choices=top.detach()
capacity=math.ceil(1.25*T*2/8)
output=torch.zeros_like(flat); accepted=0
for i,expert in enumerate(self.experts):
positions=(top==i).nonzero(as_tuple=False)[:capacity]
if len(positions):
tok,slot=positions[:,0],positions[:,1]
value=expert(flat[tok])*w[tok,slot,None]
output=output.index_add(0,tok,value); accepted+=len(tok)
self.drop=1-accepted/(T*2); self.load=f.detach()
if self.shared is not None: output=output+self.shared(flat)
return output.reshape(shape)
class MoeBlock(nn.Module):
def __init__(self,block,shared):
super().__init__(); self.n1=block.n1; self.n2=block.n2; self.attn=block.attn
self.moe=Moe(block,shared)
def forward(self,x):
x=x+self.attn(self.n1(x))
return x+self.moe(self.n2(x))
def build(kind):
torch.manual_seed(43)
original=gpt_scope['TorchGPT'](**config)
model=mini_scope['MiniLlama'](original,False)
model.load_state_dict(state['state_dict'],strict=True)
old=model.token.weight.detach().clone()
model.token=nn.Embedding(len(chars),config['width'])
with torch.no_grad():
model.token.weight[:len(old)].copy_(old)
nn.init.normal_(model.token.weight[len(old):],std=.02)
if kind!='dense':
model.blocks=nn.ModuleList([MoeBlock(b,kind=='shared') for b in model.blocks])
return model.cuda()
def make_batches(seed,steps):
gen=torch.Generator().manual_seed(seed); result=[]
for step in range(steps):
stream=streams[step%2]; top=len(stream)-length-1
ix=torch.randint(top,(4,),generator=gen)
xx=torch.stack([stream[int(i):int(i)+length] for i in ix]).cuda()
yy=torch.stack([stream[int(i)+1:int(i)+length+1] for i in ix]).cuda()
result.append((xx,yy))
return result
train=make_batches(19,steps); val=make_batches(20,2)
results={}; maps={}
for kind in ('dense','moe','shared'):
model=build(kind); opt=torch.optim.AdamW(model.parameters(),lr=.001)
print('tipo:',kind,'parámetros totales:',sum(p.numel() for p in model.parameters()),flush=True)
torch.cuda.synchronize(); start=time.perf_counter()
for xx,yy in train:
opt.zero_grad(set_to_none=True); loss=model(xx,yy)
if kind!='dense':
aux=torch.stack([b.moe.aux for b in model.blocks]).mean()
z=torch.stack([b.moe.z for b in model.blocks]).mean()
objective=loss+.01*aux+.001*z
else: objective=loss
assert torch.isfinite(objective).item()
objective.backward(); opt.step()
torch.cuda.synchronize(); elapsed=time.perf_counter()-start
with torch.no_grad():
validation=sum(model(xx,yy).item() for xx,yy in val)/len(val)
row={'steps':steps,'train_loss':float(loss.detach()),'validation_loss':validation,'seconds':elapsed,
'parameters':sum(p.numel() for p in model.parameters())}
if kind!='dense':
row['load']=[b.moe.load.cpu().tolist() for b in model.blocks]
row['drop']=[b.moe.drop for b in model.blocks]
row['z']=[float(b.moe.z) for b in model.blocks]
counts=torch.zeros((2,4,8),dtype=torch.float64)
probes=[('prose',('Friends: the time is here. Speak!\n'*3)[:length]),
('code',('def f(x): return x+12\nx=f(3)\n'*3)[:length])]
with torch.no_grad():
for source,text in probes:
ids=torch.tensor([[stoi[c] for c in text]],device='cuda')
model.logits(ids)
for layer,b in enumerate(model.blocks):
choice=b.moe.last_choices.cpu()
for j,c in enumerate(text):
category=(0 if c.isalpha() else 1 if not c.isspace() else None) if source=='prose' else (2 if c.isdigit() else 3 if not c.isspace() else None)
if category is not None:
for e in choice[j]: counts[layer,category,int(e)]+=1
totals=counts.sum(-1,keepdim=True); assert (totals>0).all()
maps[kind]=(counts/totals).tolist()
results[kind]=row; print(kind,row,flush=True)
Path('mini-moe-results.json').write_text(json.dumps({'results':results,'maps':maps},indent=2),encoding='utf8')
npm run lab and open the connection link.Exercises
Step 1 of 3. Which inequality relates sum of squares and sum of components?
import numpy as np
def topk_route(logits, k, capacity):
pass