Switch Transformer › Worked Example: Routing Visualization
Language AI HandbookAll chapters Switch Transformer › Worked Example: Routing VisualizationOne section · Sections in this chapter10 / 14 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's visualize how tokens get routed to experts in a trained Switch layer. This visualization helps build intuition about what the router learns and how it distributes tokens across the available experts. We will trace through a full forward pass with concrete numbers to make the routing mechanism tangible.
# Create a Switch layer and process some text
torch.manual_seed(7)
num_viz_experts = 8
switch_layer = SwitchLayer(
d_model=128, d_ff=512, num_experts=num_viz_experts, capacity_factor=1.5
)
# Simulate token embeddings for a sentence
# Different semantic categories should route differently
batch_size, seq_len, d_model = 1, 20, 128
tokens = torch.randn(batch_size, seq_len, d_model) * 5.0
# Get routing decisions
with torch.no_grad():
expert_indices, expert_weights, router_logits = switch_layer.router(tokens)
router_probs = F.softmax(router_logits, dim=-1)

The heatmap shows each token's probability distribution over experts. Notice how most tokens have one dominant expert (high probability in one column, near-zero in the others). This shows the router's confident routing decisions even with random initialization. This confidence emerges naturally from the softmax: when one logit is substantially higher than the others, the softmax output is a near-one-hot vector. The bar chart shows the actual token distribution, with the red line showing perfect balance. With random initialization, we see large variance in expert popularity. During actual training, the auxiliary load balancing loss would apply pressure to even out this distribution, driving the bar heights toward the red line while letting real departures driven by token content.