Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Sheet8 * File : src/templates/ai/mixture-of-experts.ts9 * Module : templates10 * Repository : https://git.spboucher.ai/sheet11 * Project Website : https://sheet.spboucher.ai12 * Created : 2026-11-1713 * Last Modified : 2026-11-1714 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import type { TemplateDef } from "../types";44import { T, pickSources } from "./shared";4546const r = String.raw;4748export const mixtureOfExperts: TemplateDef = {49 id: "mixture-of-experts",50 category: "ai",51 title: { fr: "Mélange d'experts et routage top-k", en: "Mixture of Experts and top-k routing" },52 description: {53 fr: "Réseau de routage, activation parcimonieuse, perte d'équilibrage de charge : pourquoi un modèle peut grossir sans que chaque jeton coûte plus cher.",54 en: "Gating network, sparse activation, load-balancing loss: why a model can grow without each token costing more.",55 },56 build: (locale) => {57 const t = T(locale);58 return {59 schemaVersion: 1,60 metadata: {61 title: t("Mélange d'experts et routage top-k", "Mixture of Experts and top-k routing"),62 slug: t("melange-experts-routage-top-k", "mixture-of-experts-top-k-routing"),63 locale,64 summary: t(65 "Un mélange d'experts confie chaque entrée à quelques sous-réseaux choisis par un routeur. Le nombre de paramètres augmente avec le nombre d'experts, mais le calcul par jeton ne dépend que de $k$.",66 "A mixture of experts hands each input to a few sub-networks chosen by a router. The parameter count grows with the number of experts, but the computation per token depends only on $k$.",67 ),68 topics: [t("IA", "AI"), t("Apprentissage profond", "Deep Learning")],69 tags: ["MoE", t("routage", "routing"), "top-k", t("parcimonie", "sparsity"), t("équilibrage de charge", "load balancing"), "LLM"],70 level: "advanced",71 kind: "explainer",72 objectives: [73 t("Décrire le rôle du réseau de routage et celui des experts.", "Describe the role of the gating network and of the experts."),74 t("Écrire le routage top-k bruité et expliquer ce que fait chaque terme.", "Write noisy top-k gating and explain what each term does."),75 t("Expliquer pourquoi une perte d'équilibrage est nécessaire.", "Explain why a load-balancing loss is needed."),76 t("Distinguer la croissance des paramètres de celle du calcul par jeton.", "Separate the growth of parameters from the growth of computation per token."),77 ],78 example: true,79 },80 theme: { preset: "scientific-light", accent: "violet" },81 blocks: [82 { id: "h-title", type: "heading", level: 1, eyebrow: t("Architecture · Calcul conditionnel", "Architecture · Conditional computation"), text: t("Mélange d'experts et routage top-k", "Mixture of Experts and top-k routing") },83 {84 id: "intro-lead", type: "paragraph", lead: true,85 text: t(86 "Dans un réseau classique, **tous** les paramètres travaillent pour **chaque** entrée. Un mélange d'experts (*Mixture of Experts*, MoE) rompt avec cette règle : un petit réseau de routage choisit, pour chaque entrée, quelques sous-réseaux spécialisés et laisse les autres au repos[^shazeer2017]. L'idée remonte aux années 1990[^jacobs1991] ; sa version parcimonieuse est celle qu'on retrouve dans les grands modèles de langage.",87 "In an ordinary network, **all** parameters work on **every** input. A Mixture of Experts (MoE) breaks that rule: a small gating network picks, for each input, a few specialised sub-networks and leaves the others idle[^shazeer2017]. The idea goes back to the 1990s[^jacobs1991]; its sparse version is the one found in large language models.",88 ),89 },90 {91 id: "c-ideas", type: "cards", columns: 3,92 items: [93 { icon: "users", tone: "violet", title: t("Des experts", "Experts"), text: t("$N$ sous-réseaux de même forme mais de paramètres différents. Dans un Transformer, chacun est un réseau à propagation avant.", "$N$ sub-networks of the same shape but with different parameters. In a Transformer, each one is a feed-forward network.") },94 { icon: "route", tone: "blue", title: t("Un routeur", "A router"), text: t("Un réseau très léger qui attribue un score à chaque expert à partir de l'entrée, puis n'en retient que $k$.", "A very light network that scores every expert from the input, then keeps only $k$ of them.") },95 { icon: "scale", tone: "amber", title: t("Un équilibrage", "A balancing term"), text: t("Une perte auxiliaire qui pousse le routeur à répartir le travail, sans quoi quelques experts reçoivent tout.", "An auxiliary loss that pushes the router to spread the work; without it a few experts receive everything.") },96 ],97 },9899 { id: "h-layer", type: "heading", level: 2, text: t("Anatomie d'une couche MoE", "Anatomy of an MoE layer") },100 {101 id: "d-moe", type: "diagram", span: 8, kind: "architecture", direction: "TB", routing: "curved",102 title: t("Routage top-k avec N = 4 experts et k = 2", "Top-k routing with N = 4 experts and k = 2"),103 caption: t(104 "Seuls les experts retenus par le routeur sont évalués ; leurs sorties sont combinées avec les poids du routeur[^shazeer2017].",105 "Only the experts kept by the router are evaluated; their outputs are combined with the router's weights[^shazeer2017].",106 ),107 alt: t(108 "Schéma d'une couche de mélange d'experts. Le vecteur d'entrée va vers un routeur, qui calcule un score par expert, y ajoute un bruit, garde les deux meilleurs scores et applique un softmax. Parmi quatre experts, deux sont actifs et reçoivent l'entrée, deux sont inactifs. Les deux sorties sont additionnées avec les poids du routeur pour donner la sortie. Une flèche pointillée relie les poids du routeur à une perte d'équilibrage de charge.",109 "Diagram of a mixture-of-experts layer. The input vector goes to a router, which computes one score per expert, adds noise, keeps the two best scores and applies a softmax. Of four experts, two are active and receive the input, two are idle. The two outputs are summed with the router's weights to give the output. A dashed arrow links the router's weights to a load-balancing loss.",110 ),111 sourceIds: ["shazeer2017"],112 groups: [113 { id: "g-router", label: t("Routeur", "Router"), tone: "blue" },114 { id: "g-experts", label: t("Experts", "Experts"), tone: "violet" },115 ],116 nodes: [117 { id: "n-x", label: t("Entrée x", "Input x"), sublabel: t("représentation d'un jeton", "one token's representation"), shape: "pill", tone: "neutral", icon: "token" },118 { id: "n-scores", label: t("Scores du routeur", "Router scores"), sublabel: t("un par expert", "one per expert"), shape: "round", tone: "blue", group: "g-router" },119 { id: "n-noise", label: t("Bruit ajustable", "Tunable noise"), sublabel: t("à l'entraînement", "during training"), shape: "note", tone: "neutral", group: "g-router" },120 { id: "n-topk", label: t("Garder les k meilleurs", "Keep the top k"), shape: "diamond", tone: "blue", icon: "filter", group: "g-router" },121 { id: "n-softmax", label: "Softmax", sublabel: t("poids G(x)", "weights G(x)"), shape: "round", tone: "blue", group: "g-router" },122 { id: "n-e1", label: t("Expert 1", "Expert 1"), sublabel: t("actif", "active"), shape: "round", tone: "violet", icon: "brain", group: "g-experts" },123 { id: "n-e2", label: t("Expert 2", "Expert 2"), sublabel: t("au repos", "idle"), shape: "round", tone: "neutral", group: "g-experts" },124 { id: "n-e3", label: t("Expert 3", "Expert 3"), sublabel: t("actif", "active"), shape: "round", tone: "violet", icon: "brain", group: "g-experts" },125 { id: "n-e4", label: t("Expert 4", "Expert 4"), sublabel: t("au repos", "idle"), shape: "round", tone: "neutral", group: "g-experts" },126 { id: "n-sum", label: t("Somme pondérée", "Weighted sum"), shape: "circle", tone: "green", icon: "merge" },127 { id: "n-y", label: t("Sortie y", "Output y"), shape: "pill", tone: "green" },128 { id: "n-loss", label: t("Perte d'équilibrage", "Balancing loss"), sublabel: t("ajoutée à la perte principale", "added to the main loss"), shape: "hexagon", tone: "amber", icon: "scale" },129 ],130 edges: [131 { id: "e-x-scores", from: "n-x", to: "n-scores", tone: "blue" },132 { id: "e-noise", from: "n-noise", to: "n-scores", style: "dotted", label: "+" },133 { id: "e-scores-topk", from: "n-scores", to: "n-topk", tone: "blue" },134 { id: "e-topk-softmax", from: "n-topk", to: "n-softmax", tone: "blue", label: t("les autres : −∞", "the others: −∞") },135 { id: "e-x-e1", from: "n-x", to: "n-e1", tone: "violet" },136 { id: "e-x-e3", from: "n-x", to: "n-e3", tone: "violet" },137 { id: "e-x-e2", from: "n-x", to: "n-e2", style: "dotted", arrow: "none" },138 { id: "e-x-e4", from: "n-x", to: "n-e4", style: "dotted", arrow: "none" },139 { id: "e-e1-sum", from: "n-e1", to: "n-sum", tone: "violet", label: "E₁(x)" },140 { id: "e-e3-sum", from: "n-e3", to: "n-sum", tone: "violet", label: "E₃(x)" },141 { id: "e-gates", from: "n-softmax", to: "n-sum", tone: "blue", label: t("poids", "weights") },142 { id: "e-sum-y", from: "n-sum", to: "n-y", tone: "green" },143 { id: "e-balance", from: "n-softmax", to: "n-loss", style: "dashed", tone: "amber", label: t("statistiques du lot", "batch statistics") },144 ],145 legend: [146 { label: t("Décision de routage", "Routing decision"), tone: "blue", shape: "arrow" },147 { label: t("Calcul effectué par un expert actif", "Computation done by an active expert"), tone: "violet", shape: "arrow" },148 { label: t("Expert au repos : chemin non emprunté, aucun calcul", "Idle expert: path not taken, no computation"), tone: "neutral", shape: "dashed" },149 { label: t("Signal d'entraînement auxiliaire", "Auxiliary training signal"), tone: "amber", shape: "dashed" },150 { label: t("Sortie de la couche", "Output of the layer"), tone: "green", shape: "circle" },151 ],152 animation: {153 steps: [154 { title: t("1. Noter chaque expert", "1. Score every expert"), text: t("Le routeur multiplie l'entrée par une matrice apprise $W_g$ : un score par expert. À l'entraînement, un bruit dont l'ampleur est elle-même apprise s'y ajoute.", "The router multiplies the input by a learned matrix $W_g$: one score per expert. During training, noise whose magnitude is itself learned is added."), nodes: ["n-x", "n-scores", "n-noise"], edges: ["e-x-scores", "e-noise"] },155 { title: t("2. Ne garder que k experts", "2. Keep only k experts"), text: t("Les $k$ meilleurs scores sont conservés, les autres sont mis à $-\\infty$. Après le softmax, leur poids vaut exactement 0.", "The top $k$ scores are kept, the others are set to $-\\infty$. After the softmax their weight is exactly 0."), nodes: ["n-topk", "n-softmax"], edges: ["e-scores-topk", "e-topk-softmax"] },156 { title: t("3. N'évaluer que les experts retenus", "3. Evaluate only the selected experts"), text: t("L'entrée n'est envoyée qu'aux experts 1 et 3. Les experts 2 et 4 ne calculent rien : c'est là que se fait l'économie.", "The input is sent to experts 1 and 3 only. Experts 2 and 4 compute nothing: this is where the saving comes from."), nodes: ["n-x", "n-e1", "n-e3"], edges: ["e-x-e1", "e-x-e3"] },157 { title: t("4. Combiner les sorties", "4. Combine the outputs"), text: t("La sortie est la somme des sorties des experts actifs, pondérée par les poids du routeur.", "The output is the sum of the active experts' outputs, weighted by the router's weights."), nodes: ["n-e1", "n-e3", "n-softmax", "n-sum", "n-y"], edges: ["e-e1-sum", "e-e3-sum", "e-gates", "e-sum-y"] },158 { title: t("5. Surveiller la répartition", "5. Watch the distribution"), text: t("Sur l'ensemble du lot, on mesure la charge reçue par chaque expert ; une perte auxiliaire pénalise les déséquilibres.", "Over the whole batch, the load received by each expert is measured; an auxiliary loss penalises imbalance."), nodes: ["n-softmax", "n-loss"], edges: ["e-balance"] },159 ],160 },161 },162 {163 id: "st-forward", type: "steps", span: 4,164 items: [165 { icon: "calculator", title: t("Noter", "Score"), text: t("Une multiplication matricielle donne $N$ scores. Son coût est négligeable devant celui d'un expert.", "One matrix multiplication yields $N$ scores. Its cost is negligible next to that of one expert.") },166 { icon: "filter", title: t("Sélectionner", "Select"), text: t("On retient $k$ experts, avec $k \\ll N$. Certains modèles routent chaque jeton vers un seul expert[^fedus2021].", "$k$ experts are kept, with $k \\ll N$. Some models route each token to a single expert[^fedus2021].") },167 { icon: "cpu", title: t("Calculer", "Compute"), text: t("Seuls les experts retenus sont exécutés, chacun sur les jetons qui lui ont été attribués.", "Only the selected experts run, each on the tokens it was assigned.") },168 { icon: "merge", title: t("Recombiner", "Recombine"), text: t("Les sorties sont pondérées, additionnées, puis la couche suivante reprend comme dans un Transformer ordinaire.", "The outputs are weighted and summed, then the next layer carries on as in an ordinary Transformer.") },169 ],170 },171172 { id: "h-math", type: "heading", level: 2, text: t("Le routage en équations", "Routing in equations") },173 {174 id: "eq-mixture", type: "equation", span: 6, label: t("Sortie de la couche", "Output of the layer"), derivation: "standard", sourceIds: ["shazeer2017"],175 latex: r`y = \sum_{i=1}^{N} G(x)_i \, E_i(x)`,176 explanation: t(177 "Quand $G(x)_i = 0$, il est inutile de calculer $E_i(x)$ : la parcimonie du vecteur $G(x)$ se traduit directement en calcul évité[^shazeer2017].",178 "Whenever $G(x)_i = 0$ there is no need to compute $E_i(x)$: the sparsity of the vector $G(x)$ translates directly into computation avoided[^shazeer2017].",179 ),180 variables: [181 { symbol: "x", meaning: t("Entrée de la couche (représentation d'un jeton)", "Input of the layer (one token's representation)") },182 { symbol: "E_i", meaning: t("Expert $i$, un réseau de neurones avec ses propres paramètres", "Expert $i$, a neural network with its own parameters") },183 { symbol: "G(x)_i", meaning: t("Poids que le routeur accorde à l'expert $i$ ; les poids somment à 1", "Weight the router gives to expert $i$; the weights sum to 1") },184 { symbol: "N", meaning: t("Nombre d'experts", "Number of experts") },185 ],186 },187 {188 id: "eq-topk", type: "equation", span: 6, label: t("Routage top-k bruité", "Noisy top-k gating"), derivation: "standard", sourceIds: ["shazeer2017"],189 latex: r`\begin{aligned} G(x) &= \mathrm{Softmax}\big(\mathrm{KeepTopK}(H(x), k)\big) \\ H(x)_i &= (x \cdot W_g)_i + \varepsilon_i \cdot \mathrm{Softplus}\big((x \cdot W_{\text{noise}})_i\big), \quad \varepsilon_i \sim \mathcal{N}(0, 1) \\ \mathrm{KeepTopK}(v, k)_i &= \begin{cases} v_i & \text{if } v_i \text{ is among the top } k \text{ elements of } v \\ -\infty & \text{otherwise} \end{cases} \end{aligned}`,190 explanation: t(191 "Le bruit, dont l'ampleur par expert est apprise, aide à répartir la charge pendant l'entraînement[^shazeer2017].",192 "The noise, whose per-expert magnitude is learned, helps spread the load during training[^shazeer2017].",193 ),194 variables: [195 { symbol: "W_g", meaning: t("Matrice de poids du routeur", "Weight matrix of the router") },196 { symbol: r`W_{\text{noise}}`, meaning: t("Matrice apprise qui règle l'ampleur du bruit par expert", "Learned matrix setting the noise magnitude per expert") },197 { symbol: "k", meaning: t("Nombre d'experts activés par entrée", "Number of experts activated per input") },198 { symbol: r`\mathrm{Softplus}`, meaning: t("Fonction $z \\mapsto \\ln(1 + e^{z})$, toujours positive", "Function $z \\mapsto \\ln(1 + e^{z})$, always positive") },199 ],200 },201 {202 id: "sim-routing", type: "simulation", span: 8, kind: "moe-routing", seed: 11,203 params: { experts: 8, topK: 2, tokens: 8, temperature: 1 }, config: {},204 title: t("Router des jetons vers des experts", "Route tokens to experts"),205 caption: t("Simulation à but pédagogique sur des scores tirés au hasard (graine fixe) : ce n'est pas le routeur d'un modèle entraîné.", "Teaching simulation on randomly drawn scores (fixed seed): this is not the router of a trained model."),206 alt: t(207 "Simulation interactive : des jetons sont distribués entre plusieurs experts selon un routage top-k. On voit quels experts sont actifs pour chaque jeton et la charge totale reçue par chacun.",208 "Interactive simulation: tokens are dispatched among several experts by top-k routing. It shows which experts are active for each token and the total load each one receives.",209 ),210 },211 {212 id: "co-where", type: "callout", span: 4, tone: "definition", title: t("Où se place la couche MoE ?", "Where does the MoE layer sit?"),213 text: t(214 "Dans les Transformers à experts, la couche MoE **remplace le réseau à propagation avant** de certains blocs ; l'attention reste dense. Le routage se fait jeton par jeton, de sorte que deux jetons d'une même phrase peuvent emprunter des experts différents[^lepikhin2020][^fedus2021].",215 "In expert-based Transformers the MoE layer **replaces the feed-forward network** of some blocks; attention stays dense. Routing is done token by token, so two tokens of the same sentence may go through different experts[^lepikhin2020][^fedus2021].",216 ),217 },218219 { id: "h-balance", type: "heading", level: 2, text: t("Équilibrer la charge", "Balancing the load") },220 {221 id: "co-collapse", type: "callout", span: 6, tone: "warning", title: t("Le piège : l'effondrement du routage", "The trap: routing collapse"),222 text: t(223 "Sans contrainte, le routeur tend à envoyer presque tout vers les mêmes experts. Le déséquilibre se renforce de lui-même : les experts favorisés s'entraînent davantage, donc sont encore plus souvent choisis[^shazeer2017]. Les autres ne servent plus à rien, et les experts surchargés créent un goulot d'étranglement matériel.",224 "Left unconstrained, the router tends to send almost everything to the same experts. The imbalance is self-reinforcing: favoured experts are trained more, so they get selected even more often[^shazeer2017]. The others become dead weight, and the overloaded experts turn into a hardware bottleneck.",225 ),226 },227 {228 id: "ch-load", type: "chart", span: 6, kind: "bar", dataKind: "illustrative",229 title: t("Part des jetons reçue par chaque expert", "Share of tokens received by each expert"),230 caption: t(231 "Valeurs illustratives choisies à la main pour montrer la forme du phénomène ; ce ne sont pas des mesures.",232 "Illustrative values chosen by hand to show the shape of the phenomenon; these are not measurements.",233 ),234 alt: t(235 "Diagramme à barres comparant, pour huit experts, la part des jetons reçue sans perte d'équilibrage (deux experts reçoivent la majorité, plusieurs presque rien) et avec perte d'équilibrage (parts proches de 12,5 % chacune).",236 "Bar chart comparing, for eight experts, the share of tokens received without a balancing loss (two experts get the majority, several almost nothing) and with a balancing loss (shares close to 12.5% each).",237 ),238 x: { label: t("Expert", "Expert"), type: "category" },239 y: { label: t("Part des jetons", "Share of tokens"), unit: "%", min: 0, max: 50 },240 series: [241 { name: t("Sans équilibrage", "Without balancing"), tone: "red", points: [["E1", 41], ["E2", 3], ["E3", 27], ["E4", 2], ["E5", 12], ["E6", 1], ["E7", 9], ["E8", 5]].map(([x, y]) => ({ x: x as string, y: y as number })) },242 { name: t("Avec équilibrage", "With balancing"), tone: "green", points: [["E1", 14], ["E2", 12], ["E3", 13], ["E4", 11], ["E5", 13], ["E6", 12], ["E7", 12], ["E8", 13]].map(([x, y]) => ({ x: x as string, y: y as number })) },243 ],244 },245 {246 id: "eq-importance", type: "equation", span: 6, label: t("Perte d'importance (Shazeer et coll.)", "Importance loss (Shazeer et al.)"), derivation: "standard", sourceIds: ["shazeer2017"],247 latex: r`\begin{aligned} \mathrm{Importance}(X) &= \sum_{x \in X} G(x) \\ L_{\text{importance}}(X) &= w_{\text{importance}} \cdot \mathrm{CV}\big(\mathrm{Importance}(X)\big)^{2} \end{aligned}`,248 explanation: t(249 "La perte est nulle quand tous les experts reçoivent la même importance totale sur le lot, et croît avec la dispersion[^shazeer2017].",250 "The loss is zero when all experts receive the same total importance over the batch, and grows with the dispersion[^shazeer2017].",251 ),252 variables: [253 { symbol: "X", meaning: t("Lot d'exemples d'entraînement", "Batch of training examples") },254 { symbol: r`\mathrm{CV}`, meaning: t("Coefficient de variation : écart-type divisé par la moyenne", "Coefficient of variation: standard deviation divided by the mean") },255 { symbol: r`w_{\text{importance}}`, meaning: t("Poids de la perte auxiliaire, réglé à la main", "Weight of the auxiliary loss, tuned by hand") },256 ],257 },258 {259 id: "eq-switch", type: "equation", span: 6, label: t("Perte auxiliaire (Switch Transformer)", "Auxiliary loss (Switch Transformer)"), derivation: "standard", sourceIds: ["fedus2021"],260 latex: r`L_{\text{aux}} = \alpha \cdot N \cdot \sum_{i=1}^{N} f_i \cdot P_i`,261 explanation: t(262 "Sous une répartition uniforme, $f_i = P_i = 1/N$ et la somme atteint son minimum $1/N$. Comme $f_i$ n'est pas dérivable, le gradient passe par $P_i$[^fedus2021].",263 "Under a uniform distribution, $f_i = P_i = 1/N$ and the sum reaches its minimum $1/N$. Since $f_i$ is not differentiable, the gradient flows through $P_i$[^fedus2021].",264 ),265 variables: [266 { symbol: "f_i", meaning: t("Fraction des jetons du lot envoyés à l'expert $i$", "Fraction of the batch's tokens dispatched to expert $i$") },267 { symbol: "P_i", meaning: t("Probabilité moyenne que le routeur attribue à l'expert $i$ sur le lot", "Mean probability the router assigns to expert $i$ over the batch") },268 { symbol: r`\alpha`, meaning: t("Coefficient de la perte auxiliaire", "Coefficient of the auxiliary loss") },269 ],270 },271272 { id: "h-scale", type: "heading", level: 2, text: t("Pourquoi cela passe à l'échelle", "Why it scales") },273 {274 id: "eq-scaling", type: "equation", span: 6, label: t("Paramètres et calcul se découplent", "Parameters and compute decouple"), derivation: "derived",275 latex: r`\underbrace{P_{\text{MoE}} \approx N \cdot P_E}_{\text{parameters}} \qquad \underbrace{C_{\text{token}} \approx k \cdot C_E + C_{\text{router}}}_{\text{compute per token}}`,276 explanation: t(277 "Relation dérivée de la définition de la couche : ajouter des experts augmente $N$, donc la capacité, sans toucher à $k$, donc au calcul par jeton. Elle néglige le coût de communication entre machines.",278 "Relation derived from the definition of the layer: adding experts raises $N$, hence capacity, without touching $k$, hence the computation per token. It ignores the cost of communication between machines.",279 ),280 variables: [281 { symbol: "P_E", meaning: t("Nombre de paramètres d'un expert", "Number of parameters of one expert") },282 { symbol: "C_E", meaning: t("Coût de calcul d'un expert pour un jeton", "Compute cost of one expert for one token") },283 { symbol: r`C_{\text{router}}`, meaning: t("Coût du routeur, petit devant $C_E$", "Cost of the router, small compared with $C_E$") },284 ],285 },286 {287 id: "cmp-dense", type: "comparison", span: 6,288 caption: t("Trois façons d'utiliser $N$ sous-réseaux.", "Three ways of using $N$ sub-networks."),289 columns: [290 { title: t("Couche dense", "Dense layer"), tone: "neutral" },291 { title: t("Mélange doux", "Soft mixture"), tone: "blue", badge: "1991" },292 { title: t("MoE top-k", "Top-k MoE"), tone: "violet", badge: t("parcimonieux", "sparse") },293 ],294 rows: [295 { label: t("Experts évalués par entrée", "Experts evaluated per input"), cells: [t("un seul réseau, toujours", "a single network, always"), t("tous les $N$", "all $N$"), t("seulement $k$", "only $k$")] },296 { label: t("Calcul par jeton", "Compute per token"), cells: ["$C_E$", "$N \\cdot C_E$", "$k \\cdot C_E$"] },297 { label: t("Paramètres", "Parameters"), cells: ["$P_E$", "$N \\cdot P_E$", "$N \\cdot P_E$"] },298 { label: t("Difficulté propre", "Specific difficulty"), cells: [t("aucune", "none"), t("coût qui croît avec $N$", "cost grows with $N$"), t("équilibrage, sélection non dérivable", "balancing, non-differentiable selection")] },299 ],300 verdict: t(301 "Le MoE top-k garde la capacité du mélange doux pour un coût de calcul proche de celui d'une couche dense. C'est ce découplage qui a permis d'entraîner des modèles de plusieurs centaines de milliards de paramètres[^lepikhin2020].",302 "Top-k MoE keeps the capacity of the soft mixture at a compute cost close to that of a dense layer. This decoupling is what made it possible to train models with several hundred billion parameters[^lepikhin2020].",303 ),304 },305 {306 id: "co-memory", type: "callout", tone: "assumption", title: t("Ce que le calcul parcimonieux n'économise pas", "What sparse computation does not save"),307 text: t(308 "Tous les experts doivent rester **chargés en mémoire**, puisque n'importe lequel peut être appelé au jeton suivant. Un modèle MoE économise du calcul par jeton, pas de la mémoire : à nombre de paramètres égal, il occupe autant de place qu'un modèle dense.",309 "All experts must stay **loaded in memory**, since any of them may be called for the next token. An MoE model saves computation per token, not memory: for the same parameter count it takes as much room as a dense model.",310 ),311 },312313 { id: "h-check", type: "heading", level: 2, text: t("Vérifier sa compréhension", "Check your understanding") },314 {315 id: "quiz-scaling", type: "quiz", span: 6,316 question: t(317 "Une couche MoE passe de 8 à 64 experts, en gardant $k = 2$. Que se passe-t-il, à peu de chose près ?",318 "An MoE layer goes from 8 to 64 experts while keeping $k = 2$. What happens, roughly?",319 ),320 choices: [321 { text: t("Les paramètres de la couche sont multipliés par 8 ; le calcul par jeton change à peine.", "The layer's parameters are multiplied by 8; computation per token barely changes."), correct: true, explanation: t("Exact : les paramètres suivent $N$, le calcul suit $k$. Seul le routeur, très léger, calcule 64 scores au lieu de 8.", "Correct: parameters follow $N$, compute follows $k$. Only the very light router computes 64 scores instead of 8.") },322 { text: t("Les paramètres et le calcul par jeton sont tous deux multipliés par 8.", "Both parameters and computation per token are multiplied by 8."), correct: false, explanation: t("Ce serait le cas d'un mélange doux, où tous les experts sont évalués.", "That would be true of a soft mixture, where every expert is evaluated.") },323 { text: t("Rien ne change, puisque seuls 2 experts sont utilisés.", "Nothing changes, since only 2 experts are used."), correct: false, explanation: t("Deux experts par jeton, mais pas toujours les mêmes : les 64 existent et doivent être stockés et entraînés.", "Two experts per token, but not always the same two: all 64 exist and must be stored and trained.") },324 ],325 },326 {327 id: "acc-faq", type: "accordion", span: 6,328 items: [329 {330 title: t("Les experts sont-ils spécialisés par sujet (médecine, droit, code) ?", "Are experts specialised by subject (medicine, law, code)?"),331 text: t(332 "Pas par construction. Personne n'attribue de rôle aux experts : la répartition émerge de l'entraînement, et le routage se décide jeton par jeton à partir de la représentation interne. Le mot « expert » désigne un sous-réseau, pas une compétence lisible par un humain.",333 "Not by design. Nobody assigns roles to experts: the division of labour emerges from training, and routing is decided token by token from the internal representation. The word “expert” names a sub-network, not a human-readable skill.",334 ),335 },336 {337 title: t("Quelle est la différence avec un ensemble de modèles ?", "How is this different from an ensemble of models?"),338 text: t(339 "Un ensemble évalue **tous** les modèles et moyenne leurs réponses. Un MoE est un seul modèle, entraîné de bout en bout, dans lequel le routeur choisit **quelques** sous-réseaux à l'intérieur d'une couche ; le reste du réseau est partagé.",340 "An ensemble evaluates **all** models and averages their answers. An MoE is a single model, trained end to end, in which the router picks **a few** sub-networks inside one layer; the rest of the network is shared.",341 ),342 },343 {344 title: t("Comment le routeur apprend-il si la sélection top-k n'est pas dérivable ?", "How does the router learn if top-k selection is not differentiable?"),345 text: t(346 "Le gradient passe par les poids des experts **retenus** : ces poids sont une fonction dérivable des scores. Les experts écartés ne reçoivent aucun gradient pour cet exemple, d'où l'utilité du bruit et de la perte d'équilibrage pour que chacun soit essayé[^shazeer2017].",347 "The gradient flows through the weights of the **selected** experts: those weights are a differentiable function of the scores. Discarded experts get no gradient for that example, hence the usefulness of noise and of the balancing loss so that each gets tried[^shazeer2017].",348 ),349 },350 {351 title: t("D'où vient l'idée ?", "Where does the idea come from?"),352 text: t(353 "Jacobs, Jordan, Nowlan et Hinton proposent en 1991 un système d'experts mis en concurrence par un réseau de routage, qui apprend à découper une tâche en sous-tâches[^jacobs1991]. Jordan et Jacobs l'étendent en 1994 à une hiérarchie d'experts[^jordan1994]. La version parcimonieuse à grande échelle date de 2017[^shazeer2017].",354 "In 1991 Jacobs, Jordan, Nowlan and Hinton proposed a system of experts made to compete by a gating network, which learns to split a task into sub-tasks[^jacobs1991]. Jordan and Jacobs extended it in 1994 to a hierarchy of experts[^jordan1994]. The large-scale sparse version dates from 2017[^shazeer2017].",355 ),356 },357 ],358 },359 { id: "refs", type: "references", title: t("Références", "References") },360 ],361 sources: pickSources("jacobs1991", "jordan1994", "shazeer2017", "lepikhin2020", "fedus2021"),362 claims: [363 { id: "cl-origin", status: "sourced", sourceIds: ["jacobs1991"], blockId: "intro-lead", text: t("Le mélange d'experts avec réseau de routage a été proposé en 1991.", "The mixture of experts with a gating network was proposed in 1991.") },364 { id: "cl-sparse", status: "sourced", sourceIds: ["shazeer2017"], blockId: "eq-mixture", text: t("Un routeur entraînable détermine une combinaison parcimonieuse d'experts pour chaque exemple ; les experts de poids nul ne sont pas calculés.", "A trainable gating network determines a sparse combination of experts for each example; experts with zero weight are not computed.") },365 { id: "cl-topk", status: "sourced", sourceIds: ["shazeer2017"], blockId: "eq-topk", text: t("Le routage top-k bruité ajoute un bruit gaussien d'ampleur apprise aux scores, garde les k meilleurs et applique un softmax.", "Noisy top-k gating adds Gaussian noise of learned magnitude to the scores, keeps the top k and applies a softmax.") },366 { id: "cl-balance", status: "sourced", sourceIds: ["shazeer2017", "fedus2021"], blockId: "eq-importance", text: t("Une perte auxiliaire est nécessaire pour répartir la charge entre les experts.", "An auxiliary loss is needed to spread the load across experts.") },367 { id: "cl-switch", status: "sourced", sourceIds: ["fedus2021"], blockId: "st-forward", text: t("Le Switch Transformer route chaque jeton vers un seul expert.", "The Switch Transformer routes each token to a single expert.") },368 { id: "cl-decouple", status: "derived", sourceIds: ["shazeer2017"], blockId: "eq-scaling", text: t("Le nombre de paramètres croît avec N alors que le calcul par jeton croît avec k : conséquence directe de la somme parcimonieuse.", "The parameter count grows with N while computation per token grows with k: a direct consequence of the sparse sum.") },369 { id: "cl-scale", status: "sourced", sourceIds: ["lepikhin2020"], blockId: "cmp-dense", text: t("Un Transformer de traduction à mélange d'experts parcimonieux a été entraîné au-delà de 600 milliards de paramètres.", "A sparsely-gated mixture-of-experts translation Transformer was trained beyond 600 billion parameters.") },370 { id: "cl-memory", status: "derived", blockId: "co-memory", text: t("Tous les experts restent en mémoire : la parcimonie réduit le calcul, pas l'empreinte mémoire des paramètres.", "All experts stay in memory: sparsity reduces computation, not the memory footprint of the parameters.") },371 ],372 };373 },374};375