Sign in

Multi-gate mixture of experts (MMoE)

Multi-gate Mixture-of-Experts

A multi-task network in which several tasks share a pool of expert sub-networks, and each task has its own gate that decides how much to use each expert.

Overview

Suppose one model must predict both whether a user clicks an item and whether they then buy it. The two tasks share a lot, but not everything. A single shared layer forces them to use the same features, and they can pull it in opposite directions. Multi-gate Mixture-of-Experts gives the tasks a set of small expert networks instead. Each task has a gate that looks at the input and produces weights over the experts, then feeds the weighted mix into its own small tower. Tasks that agree can lean on the same experts, and tasks that disagree can lean on different ones.

A short history

Jiaqi Ma and colleagues at Google published MMoE at KDD in 2018. Multi-task models with one shared bottom suffer when the tasks are only loosely related, because the tasks pull the shared layers in different directions. MMoE gives each task its own gate over a shared pool of experts, so tasks can share where it helps and separate where it does not. A 2019 paper from Google described its use in ranking YouTube videos.

How it works

  1. Every expert computes one ReLU layer on the input: he=relu⁡(xWe+be)\mathbf{h}_e = \operatorname{relu}(\mathbf{x} W_e + \mathbf{b}_e).
  2. For each task tt, a gate computes a softmax over the experts from the same input, giving weights that sum to 1.
  3. The task's mix is the weighted sum of the expert outputs, zt=∑egt,ehe\mathbf{z}_t = \sum_e g_{t,e} \mathbf{h}_e.
  4. The task's tower, a hidden ReLU layer and a linear output, turns the mix into one number: a logit for a binary task or a value for a regression task.
  5. The total loss is the weighted sum of the task losses. Its gradient flows into every tower, every gate and, through the gates, the shared experts.
  6. Train with Adam on shuffled mini-batches. After training, the gates method shows how each task divides its attention among the experts.

Watch out for

  • Task losses on different scales let one task dominate the shared experts, because its gradients are larger. Balance them with task_weights.
  • All gates can settle on the same expert, which wastes the others and brings back the problems of a fully shared layer. Inspect the output of gates to check.
  • Rows with a missing label for one task still need a value in that column of Y, so this template assumes every row has every label.
  • This is a small version with one layer per expert and one hidden layer per tower. Production models use deeper experts and often several stacked levels.

Use cases

When to use it

Ranking and recommendation models that must predict several related outcomes at once, such as click, like and purchase, especially when the tasks are only loosely related and a fully shared layer hurts one of them.

In industry

Video platforms
Ranking with several objectives at once, such as click, watch time and satisfaction, as described for YouTube in 2019.
E-commerce
Predicting click and purchase together, so that the rare purchase signal benefits from the plentiful click signal.
Online advertising
Jointly estimating click-through and conversion rates for the same impression.

Choosing it: what must hold

  • Two or more prediction targets on the same examples.
  • Tasks that are related enough to share features but not identical.
  • A rule for combining the task outputs into one ranking score, decided outside the model.

When to choose something else

IfUse instead
There is only one targetA single-task ranking model such as DeepFM or DCN
The tasks are very closely relatedA shared-bottom network with one small head per task
The tasks are unrelatedSeparate models, one per task

Math foundations

  1. The experts

    he=relu⁡ ⁣(xWe+be),e=1,…,E\mathbf{h}_e = \operatorname{relu}\!\left(\mathbf{x} W_e + \mathbf{b}_e\right), \qquad e = 1, \dots, E

    Each of the EE experts is a small network that sees the full input and produces a vector of width kk. All tasks share them.

  2. The gate of task t

    gt=softmax⁡ ⁣(xWtg+btg),∑e=1Egt,e=1\mathbf{g}_t = \operatorname{softmax}\!\left(\mathbf{x} W^{g}_t + \mathbf{b}^{g}_t\right), \qquad \sum_{e=1}^{E} g_{t,e} = 1

    One weight per expert, computed from the input, so different rows can use different mixes. Each task owns its gate. This is the part that the name multi-gate refers to.

  3. The gated mix

    zt=∑e=1Egt,e he\mathbf{z}_t = \sum_{e=1}^{E} g_{t,e} \, \mathbf{h}_e

    A weighted average of the expert outputs. It is the shared representation as seen by task tt.

  4. The tower

    ot=relu⁡ ⁣(ztWt(1)+bt(1))wt(2)+bt(2)o_t = \operatorname{relu}\!\left(\mathbf{z}_t W^{(1)}_t + \mathbf{b}^{(1)}_t\right) \mathbf{w}^{(2)}_t + b^{(2)}_t

    A small private network per task that maps the mix to one output. A binary task applies a sigmoid to oto_t to get a probability.

  5. The joint loss

    L=∑t=1Tαt LtL = \sum_{t=1}^{T} \alpha_t \, L_t

    Each LtL_t is the mean log loss for a binary task or half the mean squared error for a regression task. The weights αt\alpha_t set how much each task matters and default to 1.

  6. How experts receive gradient

    ∂L∂he=∑t=1Tgt,e ∂L∂zt\frac{\partial L}{\partial \mathbf{h}_e} = \sum_{t=1}^{T} g_{t,e} \, \frac{\partial L}{\partial \mathbf{z}_t}

    An expert learns from every task, in proportion to how much that task's gate uses it. A task whose gate ignores an expert does not disturb it.

Symbols

x\mathbf{x}
input row with d features
E,TE, T
number of experts and number of tasks
he\mathbf{h}_e
output of expert e, a vector of width k
We,beW_e, \mathbf{b}_e
weights and bias of expert e
gt\mathbf{g}_t
gate of task t: weights over the experts
Wtg,btgW^{g}_t, \mathbf{b}^{g}_t
weights and bias of the gate of task t
zt\mathbf{z}_t
gated mix fed to the tower of task t
oto_t
raw output of task t
Wt(1),bt(1),wt(2),bt(2)W^{(1)}_t, \mathbf{b}^{(1)}_t, \mathbf{w}^{(2)}_t, b^{(2)}_t
hidden and output parameters of the tower of task t
Lt,αtL_t, \alpha_t
loss of task t and its weight

Worked by hand

Two experts give h1=(1,0)\mathbf{h}_1 = (1, 0) and h2=(0,2)\mathbf{h}_2 = (0, 2) for some row. A task's gate scores for that row are (0,ln⁡3)(0, \ln 3).

g=(e0e0+eln⁡3,  eln⁡3e0+eln⁡3)=(14,  34)\mathbf{g} = \left(\frac{e^{0}}{e^{0} + e^{\ln 3}},\; \frac{e^{\ln 3}}{e^{0} + e^{\ln 3}}\right) = \left(\tfrac{1}{4},\; \tfrac{3}{4}\right)
z=14(1,0)+34(0,2)=(0.25,  1.5)\mathbf{z} = \tfrac{1}{4}(1, 0) + \tfrac{3}{4}(0, 2) = (0.25,\; 1.5)

The task's tower receives (0.25,1.5)(0.25, 1.5), mostly the second expert. A second task with gate scores (ln⁡3,0)(\ln 3, 0) would receive (0.75,0.5)(0.75, 0.5) from the same two experts.

Visual example

Loading the example.

Try this

  • Set the shared experts to 1 and read the two losses: one task is sacrificed.
  • With one expert, lower the loss weight of task B to 0.1 and see which task the expert serves now.
  • Slide the tasks toward fully alike and watch the two gates agree.

Code sample

import numpy as np
from impl import MMoE
from config import MMoEConfig

rng = np.random.default_rng(0)
X = rng.normal(size=(500, 6))
click = (X[:, 0] + X[:, 1] > 0).astype(float)             # task 0: binary
watch = np.abs(X[:, 0]) + 0.5 * X[:, 2]                   # task 1: regression
Y = np.stack([click, watch], axis=1)                      # (n, 2)

model = MMoE(MMoEConfig(task_types=["binary", "regression"], epochs=60)).fit(X, Y)
pred = model.predict(X)                                   # (n, 2): probability for task 0, value for task 1
print(((pred[:, 0] > 0.5) == click).mean())               # accuracy on task 0
print(np.mean((pred[:, 1] - watch) ** 2))                 # mean squared error on task 1
print(model.gates(X[:1]).round(2))                        # (1, 2, 4): each task's weights over the 4 experts
Read the implementation (170 lines)
"""Multi-gate Mixture-of-Experts (MMoE) for multi-task learning, with manual backpropagation and Adam.

NumPy only. With n rows, d features, E experts of width k, T tasks and tower width m:

    H[n, e, :]  = relu(X We[e] + be[e])                 expert outputs, shape (n, E, k)
    G_t[n, :]   = softmax(X Wg[t] + bg[t])              gate of task t, shape (n, E)
    Z_t         = sum_e G_t[:, e] * H[:, e, :]          gated mix, shape (n, k)
    out_t       = relu(Z_t Wt1[t] + bt1[t]) Wt2[t] + bt2[t]    task tower, shape (n,)
"""
from __future__ import annotations

import numpy as np

try:
    from .config import MMoEConfig
except ImportError:  # run from the template's own folder
    from config import MMoEConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

def _sigmoid(z: np.ndarray) -> np.ndarray:
    e = np.exp(-np.abs(z))
    return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))


def _softmax(z: np.ndarray) -> np.ndarray:
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


class MMoE:
    """MMoE network. After `fit`: `params`, `loss_history_` (mean total loss per epoch)."""

    def __init__(self, config: MMoEConfig | None = None) -> None:
        self.config = config or MMoEConfig()
        self.params: dict[str, np.ndarray] = {}
        self.loss_history_: list[float] = []

    @property
    def num_tasks(self) -> int:
        return len(self.config.task_types)

    def initialize(self, n_features: int) -> None:
        """Create the weights for inputs with `n_features` columns."""
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        d, E, k, m, T = n_features, cfg.num_experts, cfg.expert_dim, cfg.tower_dim, self.num_tasks
        self.params = {
            "We": np.sqrt(2.0 / d) * rng.normal(size=(E, d, k)),
            "be": np.zeros((E, k)),
            "Wg": 0.1 * rng.normal(size=(T, d, E)),
            "bg": np.zeros((T, E)),
            "Wt1": np.sqrt(2.0 / k) * rng.normal(size=(T, k, m)),
            "bt1": np.zeros((T, m)),
            "Wt2": np.sqrt(1.0 / m) * rng.normal(size=(T, m)),
            "bt2": np.zeros(T),
        }

    def _forward(self, X: np.ndarray) -> dict:
        """Run the network and keep the intermediate values needed by the backward pass. X: (n, d)."""
        p = self.params
        H = np.maximum(np.einsum("nd,edk->nek", X, p["We"]) + p["be"], 0.0)  # (n, E, k)
        gates, mixes, hiddens, outs = [], [], [], []
        for t in range(self.num_tasks):
            G = _softmax(X @ p["Wg"][t] + p["bg"][t])  # (n, E)
            Z = np.einsum("ne,nek->nk", G, H)  # (n, k)
            A = np.maximum(Z @ p["Wt1"][t] + p["bt1"][t], 0.0)  # (n, m)
            gates.append(G)
            mixes.append(Z)
            hiddens.append(A)
            outs.append(A @ p["Wt2"][t] + p["bt2"][t])  # (n,)
        return {"H": H, "G": gates, "Z": mixes, "A": hiddens, "out": np.stack(outs, axis=1)}

    def _weights(self) -> np.ndarray:
        """Per-task loss weights, shape (T,)."""
        return np.array(self.config.task_weights, dtype=float) if self.config.task_weights else np.ones(self.num_tasks)

    def loss_and_grads(self, X: np.ndarray, Y: np.ndarray) -> tuple[float, dict]:
        """Weighted sum of the task losses on a batch, and its gradient for every parameter.

        X: (n, d). Y: (n, T), column t holds 0/1 for a `binary` task or a real value for a `regression` task.
        """
        p = self.params
        n = len(X)
        cache = self._forward(X)
        H, out = cache["H"], cache["out"]
        grads = {key: np.zeros_like(value) for key, value in p.items()}
        dH = np.zeros_like(H)
        loss = 0.0
        for t, (kind, weight) in enumerate(zip(self.config.task_types, self._weights())):
            o, y = out[:, t], Y[:, t]
            if kind == "binary":
                loss += weight * np.mean(np.logaddexp(0.0, o) - y * o)
                d_out = weight * (_sigmoid(o) - y) / n
            else:
                loss += weight * 0.5 * np.mean((o - y) ** 2)
                d_out = weight * (o - y) / n
            G, Z, A = cache["G"][t], cache["Z"][t], cache["A"][t]
            grads["Wt2"][t] = A.T @ d_out
            grads["bt2"][t] = d_out.sum()
            dA = np.outer(d_out, p["Wt2"][t]) * (A > 0)  # (n, m)
            grads["Wt1"][t] = Z.T @ dA
            grads["bt1"][t] = dA.sum(axis=0)
            dZ = dA @ p["Wt1"][t].T  # (n, k)
            dG = np.einsum("nk,nek->ne", dZ, H)
            dH += G[:, :, None] * dZ[:, None, :]
            d_logit = G * (dG - np.sum(G * dG, axis=1, keepdims=True))  # softmax backward
            grads["Wg"][t] = X.T @ d_logit
            grads["bg"][t] = d_logit.sum(axis=0)
        dH *= H > 0
        grads["We"] = np.einsum("nd,nek->edk", X, dH)
        grads["be"] = dH.sum(axis=0)
        return float(loss), grads

    def fit(self, X: np.ndarray, Y: np.ndarray) -> "MMoE":
        """Train with mini-batch Adam. X: features, shape (n, d). Y: targets, shape (n, T), one column per task."""
        cfg = self.config
        X = np.asarray(X, dtype=float)
        Y = np.asarray(Y, dtype=float)
        if X.ndim != 2 or Y.shape != (len(X), self.num_tasks):
            raise ValueError(f"X must be (n, d) and Y must be (n, {self.num_tasks})")
        self.initialize(X.shape[1])
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        n = len(X)
        for _ in range(cfg.epochs):
            order = rng.permutation(n)
            total = 0.0
            for start in range(0, n, cfg.batch_size):
                rows = order[start : start + cfg.batch_size]
                loss, grads = self.loss_and_grads(X[rows], Y[rows])
                optimizer.step(grads)
                total += loss * len(rows)
            self.loss_history_.append(total / n)
        return self

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predictions for every task. X: (n, d). Returns (n, T): probabilities for `binary`, values for `regression`."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        out = self._forward(np.asarray(X, dtype=float))["out"].copy()
        for t, kind in enumerate(self.config.task_types):
            if kind == "binary":
                out[:, t] = _sigmoid(out[:, t])
        return out

    def gates(self, X: np.ndarray) -> np.ndarray:
        """Each task's mixing weights over the experts. X: (n, d). Returns (n, T, E); the last axis sums to 1."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        return np.stack(self._forward(np.asarray(X, dtype=float))["G"], axis=1)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
6, run with python3 -m unittest -v

Practice

Build X with two groups of features and two binary targets, the first depending only on the first group and the second only on the second group. Fit MMoE with MMoEConfig num_experts 4 and task_types set to two binary tasks. Call gates on X and average over rows to see which experts each task prefers. Then repeat with num_experts 1 and compare the final value of loss_history_.

Check on learning

  1. With one expert the model reduces to a fully shared bottom layer. What does a second expert allow two conflicting tasks to do that they could not do before?
    A way to think about it

    Think about the gradient each task sends into the shared weights. With a gate, a task can lower its weight on an expert and so stop pushing on it.

  2. The gate depends on the input row, not only on the task. What would be lost if each task had a fixed set of expert weights instead?
    A way to think about it

    Imagine two kinds of users for whom the tasks relate differently. A fixed mix must choose one compromise, an input-dependent gate need not.

  3. One task has a loss around 0.01 and another around 5. Predict which task the experts will serve, and say how you would correct it.
    A way to think about it

    Compare the sizes of the two terms in ∂L/∂he\partial L / \partial \mathbf{h}_e. Then look at what task_weights multiplies.

  4. After training, both gates put almost all their weight on the same expert. Is that a failure? How would you decide?
    A way to think about it

    It may mean the tasks really agree, or that the other experts started badly and were never used. Compare against a run with one expert and against other seeds.