# mHC: Keeping a Wider Residual Stream Stable With Doubly Stochastic Mixing

> mHC (Manifold-Constrained Hyper-Connections) is DeepSeek's fix for hyper-connections: Sinkhorn-Knopp turns the residual mixing matrix into a doubly stochastic one, keeping multi-layer gain bounded, for a reported 6.7% extra training time. This post reviews it and checks the math in code.

- URL: https://dmxsf.com/en/blog/mhc-manifold-constrained-hyper-connections/
- [DMXSF](https://dmxsf.com/en/about/)
- Published: 2026-01-10
- Updated: 2026-11-12
- Paper notes
- Paper: [mHC: Manifold-Constrained Hyper-Connections](https://arxiv.org/abs/2512.24880) (Zhenda Xie, Yixuan Wei, Huanqi Cao, Chenggang Zhao, Chengqi Deng, et al. · arXiv, 2025)

The paper "mHC: Manifold-Constrained Hyper-Connections" (Xie et al., DeepSeek-AI) changes the least conspicuous part of a Transformer: the residual connection. Hyper-connections (HC) widen the single residual stream into $n$ streams and mix them with learned matrices. mHC points out that the mixing matrix is unconstrained, so a product over many layers can amplify or shrink the signal without bound. It therefore projects the matrix onto doubly stochastic matrices (non-negative entries, every row and column summing to 1) with the Sinkhorn-Knopp algorithm, which keeps the composite mapping bounded, and adds kernel fusion, recomputation and communication overlap to hold the extra training time to 6.7% at $n=4$.

The paper appeared on arXiv on 31 December 2025 (v1); this post follows v2 (5 January 2026). It is 19 pages long, and its experiments are DeepSeek-V3-style MoE pre-training runs at three scales (3B, 9B and 27B). The headline result needs a 27B training run, which I cannot reproduce. What I can check is the part that is mathematics: how far Sinkhorn-Knopp is from doubly stochastic after a finite number of iterations, how the gain of products of unconstrained and of doubly stochastic matrices changes with depth, how much products of doubly stochastic matrices mix the streams, and the arithmetic of the paper's Table 2 and of the parameters the mappings add. The results: row sums are exact and column sums carry a residual; the gain of unconstrained products grows with depth and has a heavy tail, while the forward gain of doubly stochastic products is exactly 1; the price is that products drift toward the average; and Table 2's totals agree with its formulas.

## Why this paper is worth reading

- **It works on a structure that has gone unquestioned for a decade.** HC adds a "width" dimension to the Transformer that costs no FLOPs. mHC asks why that route becomes unstable in large-scale training and how to repair it.
- **The argument is focused.** The stability problem is reduced to something measurable (whether the composite of residual mappings keeps the identity property, measured by the largest row and column sums), and the fix is a classical mathematical object (doubly stochastic matrices and the Birkhoff polytope).
- **Algorithm and infrastructure are designed together.** The memory-traffic arithmetic (Table 2), kernel fusion, recomputation (Eq. 20) and DualPipe overlap decide whether it works at 27B. This "architecture plus systems" style is typical of DeepSeek papers, and the infrastructure is shared with this site's [DeepSeek-V3 explainer](https://dmxsf.com/en/blog/deepseek-v3-technical-report/).
- **You can check it yourself.** The core claim is about matrix products, and a few dozen lines of NumPy show the phenomenon, and the price of the constraint.

## Background: residual connections and hyper-connections

The standard residual connection (the paper's Eq. 1 and Eq. 2) is:

$$
x_{l+1}=x_l+\mathcal F(x_l,W_l),\qquad x_L=x_l+\sum_{i=l}^{L-1}\mathcal F(x_i,W_i)
$$

The second equation unrolls many layers: the signal $x_l$ of a shallow layer reaches the deep layer unchanged. This is the identity-mapping property, which He et al. (2016) identified as the key to stable and efficient large-scale training.

HC (Zhu et al., 2024) widens $x_l$ from $C$ dimensions to an $n\times C$ matrix ($n$ residual streams) and introduces three learned mappings (the paper's Eq. 3):

$$
x_{l+1}=H^{\text{res}}_l\,x_l+H^{\text{post}\top}_l\,\mathcal F\big(H^{\text{pre}}_l\,x_l,\ W_l\big)
$$

Here $H^{\text{pre}}_l\in\mathbb R^{1\times n}$ merges the $n$ streams into a single $C$-dimensional input for $\mathcal F$, $H^{\text{post}}_l\in\mathbb R^{1\times n}$ spreads the output of $\mathcal F$ back over the $n$ streams, and $H^{\text{res}}_l\in\mathbb R^{n\times n}$ mixes the residual streams. Each mapping combines an input-dependent (dynamic) part with a global (static) part, and the overhead is small because $n$ (for example 4) is far smaller than $C$. The paper's preliminary experiment (Table 1) shows that $H^{\text{res}}$ contributes the most of the three:

| Mappings enabled | Absolute loss gap (negative = lower loss) |
| --- | --- |
| $H^{\text{res}}$ only | −0.022 |
| $H^{\text{res}}$ and $H^{\text{pre}}$ | −0.025 |
| All three mappings | −0.027 |

A disabled mapping is replaced by a fixed one: $H^{\text{pre}}$ becomes the uniform $1/n$, $H^{\text{post}}$ becomes all ones and $H^{\text{res}}$ becomes the identity. The table caption does not say what the gap is measured against; from the context it is the plain residual baseline without HC. So information exchange inside the residual stream ($H^{\text{res}}$) is the main source of HC's gain, and it is also the source of the problem below.

## The problem: composite mappings, and system overhead

### Numerical stability

Unrolling Eq. 3 over many layers gives the paper's Eq. 4:

$$
x_L=\Big(\prod_{i=1}^{L-l}H^{\text{res}}_{L-i}\Big)x_l+\sum_{i=l}^{L-1}\Big(\prod_{j=1}^{L-1-i}H^{\text{res}}_{L-j}\Big)H^{\text{post}\top}_i\,\mathcal F\big(H^{\text{pre}}_ix_i,\ W_i\big)
$$

Compare it with Eq. 2: in a standard residual network $x_l$ reaches the deep layer with coefficient exactly 1, while in HC it is multiplied by the composite mapping $\prod H^{\text{res}}$. Because $H^{\text{res}}$ is unconstrained, that product "inevitably deviates from the identity mapping", and the signal can grow or shrink without bound, in both the forward and the backward pass.

The paper quantifies this with two metrics, together called the Amax Gain Magnitude: the largest absolute row sum of the composite mapping (the worst-case forward amplification) and the largest absolute column sum (the backward pass, that is, gradients). On the 27B model:

- HC shows a loss surge around step 12k, highly correlated with an anomaly in the gradient norm (Figure 2).
- The Amax Gain Magnitude of the composite mapping reaches extreme values, "peaks of 3000", far from 1 (Figure 3).

### System overhead

HC is almost free in FLOPs, but not in memory traffic. Section 3.2 of the paper counts the elements read and written per token per layer in a pre-norm Transformer (Table 2): HC's traffic grows roughly in proportion to $n$; the three mappings have learnable parameters, so their intermediate activations must be kept for backpropagation, which raises memory use sharply and often calls for gradient checkpointing; and under pipeline parallelism every stage boundary has to send $n$ times as much data, which enlarges the pipeline bubbles. The code below works through Table 2.

## The method: mHC

### Constrain the residual mapping to the Birkhoff polytope

The core idea of mHC is to restrict $H^{\text{res}}$ to a manifold that is as stable as the identity mapping but still lets the streams exchange information (setting $H^{\text{res}}=I$ is stable, but then the streams do not interact and HC loses its point). The paper picks the Birkhoff polytope of doubly stochastic matrices (Eq. 6):

$$
\mathcal P_{\mathcal M^{\text{res}}}(H^{\text{res}}_l)=\big\{H^{\text{res}}_l\in\mathbb R^{n\times n}\ \big|\ H^{\text{res}}_l\mathbf 1_n=\mathbf 1_n,\ \ \mathbf 1_n^\top H^{\text{res}}_l=\mathbf 1_n^\top,\ \ H^{\text{res}}_l\ge 0\big\}
$$

For $n=1$ it reduces to the scalar 1 and recovers the ordinary identity mapping. The paper lists three properties:

1. **Norm preservation.** The spectral norm of a doubly stochastic matrix is at most 1, so the mapping is non-expansive, which mitigates exploding gradients.
2. **Compositional closure.** Doubly stochastic matrices are closed under multiplication, so the composite $\prod H^{\text{res}}$ over many layers is again doubly stochastic, and stability holds between any two depths.
3. **Geometric interpretation.** The Birkhoff polytope is the convex hull of the permutation matrices, so residual mixing is a convex combination of permutations; repeated application monotonically increases the mixing across streams, which the paper presents as a robust feature fusion mechanism.

The paper also makes $H^{\text{pre}}$ and $H^{\text{post}}$ non-negative, to avoid signal cancellation from composing positive and negative coefficients, and regards this as a special manifold projection too.

### Parameterization and the Sinkhorn-Knopp projection

mHC keeps HC's "dynamic plus static" form, but first flattens the $n\times C$ hidden state into an $nC$-dimensional vector, which the paper says preserves the full context (Eq. 7):

$$
\begin{aligned}\vec x'_l&=\mathrm{RMSNorm}(\vec x_l)\\ \tilde H^{\text{pre}}_l&=\alpha^{\text{pre}}_l\,(\vec x'_l\varphi^{\text{pre}}_l)+b^{\text{pre}}_l\\ \tilde H^{\text{post}}_l&=\alpha^{\text{post}}_l\,(\vec x'_l\varphi^{\text{post}}_l)+b^{\text{post}}_l\\ \tilde H^{\text{res}}_l&=\alpha^{\text{res}}_l\,\mathrm{mat}(\vec x'_l\varphi^{\text{res}}_l)+b^{\text{res}}_l\end{aligned}
$$

Here $\varphi^{\text{pre}}_l,\varphi^{\text{post}}_l\in\mathbb R^{nC\times n}$ and $\varphi^{\text{res}}_l\in\mathbb R^{nC\times n^2}$ are linear projections, $\alpha$ is a scalar gate initialized to a small value (0.01 in the paper's Table 5), $b$ is a static bias, and $\mathrm{mat}(\cdot)$ reshapes an $n^2$-vector into an $n\times n$ matrix. The constrained mappings are (Eq. 8):

$$
H^{\text{pre}}_l=\sigma\big(\tilde H^{\text{pre}}_l\big),\qquad H^{\text{post}}_l=2\sigma\big(\tilde H^{\text{post}}_l\big),\qquad H^{\text{res}}_l=\text{Sinkhorn-Knopp}\big(\tilde H^{\text{res}}_l\big)
$$

where $\sigma$ is the sigmoid (so the first two mappings are non-negative). Sinkhorn-Knopp first makes every entry positive with an exponential, $M^{(0)}=\exp(\tilde H^{\text{res}}_l)$, then alternates row normalization $\mathcal T_r$ and column normalization $\mathcal T_c$ (Eq. 9):

$$
M^{(t)}=\mathcal T_r\big(\mathcal T_c(M^{(t-1)})\big)
$$

As the number of iterations goes to infinity it converges to a doubly stochastic matrix; the paper takes $t_{\max}=20$ as a "practical value".

*Figure: Figure: the computation of one mHC layer. The top path is the residual path, where H_res mixes the n streams; the bottom path is the sub-layer path, which merges the streams, applies F and spreads the result back; the two paths are added to form the next layer's input. HC has the same structure, but all three mappings are unconstrained.*

| Item | Standard residual | HC | mHC |
| --- | --- | --- | --- |
| Residual stream width | $C$ | $n\times C$ | $n\times C$ |
| Mixing between streams | None | Arbitrary $H^{\text{res}}$ | Doubly stochastic $H^{\text{res}}$ |
| $H^{\text{pre}}$, $H^{\text{post}}$ | None | Unconstrained | Non-negative (sigmoid) |
| Composite gain over layers | Exactly 1 | Unbounded | Row sums 1, small backward residual |
| Extra cost | None | About $n$ times the memory traffic (unfused) | Reported 6.7% extra training time ($n=4$) |

### Infrastructure: making it run

Section 4.3 takes up a good part of the paper, which suggests the authors consider it as important as the algorithm:

- **Kernel fusion.** The division by the norm is moved after the matrix multiplication (mathematically equivalent), mixed precision is used ($\varphi$ in tfloat32, the hidden state in bfloat16, coefficients and biases in float32), and operations that share memory accesses are fused into a few kernels (most of them written in TileLang). The whole Sinkhorn-Knopp iteration goes into one kernel, whose backward pass recomputes the intermediate results on chip. For the kernel that applies the mappings and merges the residual, reads drop from $(3n+1)C$ to $(n+1)C$ and writes from $3nC$ to $nC$.
- **Recomputation.** The $n$-stream design costs a lot of training memory. The paper discards the intermediate activations of the mHC kernels after the forward pass and re-executes the mHC kernels in the backward pass (without redoing the heavy $\mathcal F$). It stores the input of a block only every $L_r$ layers, with $L_r$ chosen to minimize total memory (Eq. 20, computed in the code below).
- **Communication overlap in DualPipe.** The $n$ streams mean $n$ times as much data between pipeline stages. The paper extends DeepSeek-V3's DualPipe schedule: the $F_{\text{post,res}}$ kernels of MLP layers run on a high-priority compute stream so they do not block communication; attention layers avoid persistent kernels so they can be preempted; and recomputation is decoupled from pipeline communication, because each stage's initial activation is already cached locally.

By the paper's account, these optimizations hold the extra training time of an $n=4$ mHC to 6.7% in large-scale training.

## Check it yourself: Sinkhorn residuals, composite gains, mixing, and Table 2's arithmetic

The paper's headline result comes from pre-training a 27B MoE model, which I cannot reproduce. Its mathematics and its memory-traffic accounting, however, can be checked directly. The script has four parts, in the same order as its output:

1. **How far are the row and column sums from 1 after $t$ Sinkhorn-Knopp iterations?** The code follows the order of the paper's Eq. 9: column normalization first, then row normalization, so the last step of every iteration is the row normalization. I measure 10,000 random 4×4 logit matrices (normal entries, standard deviation 0.5, 1 and 2).
2. **Composite gain over many layers.** I multiply the residual matrices of 60 layers (the paper's 27B model has 30 blocks, each split into an attention layer and an FFN layer, matching the x-axis of its Figure 3) and compute the largest absolute row sum (forward gain) and the largest absolute column sum (backward gain). Two families are compared: unconstrained "HC-style" matrices $I+\sigma Z$ (with $Z$ a standard normal matrix), and mHC-style matrices (logits $3I+sZ$ projected by 20 Sinkhorn-Knopp iterations). Each family uses 200 random chains. **These are toy distributions I chose myself, not the matrices a trained model learns.**
3. **How much do the streams mix after a product of doubly stochastic matrices?** The second-largest singular value of the composite measures it (1 means the streams do not mix, 0 means every stream becomes the average of all streams). The same part checks the paper's claims that the spectral norm is at most 1 and that a doubly stochastic matrix is a convex combination of permutation matrices (a Birkhoff decomposition).
4. **Table 2's arithmetic.** With the 27B model's hidden size $C=2560$ and $n=4$, I add up each row of Table 2 to see how many times more memory traffic HC needs than a plain residual connection, then compute the extra parameters the mappings add and the recomputation block sizes from Eq. 20.

Environment: CPU (Apple M2 Max), Python 3.14.3, NumPy 2.4.2, SciPy 1.18.1, float64, a fixed and separate random seed for each part, about 5 seconds in total. Random quantities may differ slightly on another machine.

```python
import numpy as np
from scipy.optimize import linear_sum_assignment

n = 4  # number of residual streams (the paper's expansion rate n)

def sinkhorn(logits, t):
    """Paper Eq (9): exp first, then t iterations, each one
    normalizing the columns and then the rows."""
    m = np.exp(logits)
    for _ in range(t):
        m = m / m.sum(axis=-2, keepdims=True)  # T_c: columns sum to 1
        m = m / m.sum(axis=-1, keepdims=True)  # T_r: rows sum to 1
    return m

def gains(p):
    """Two gains of a composite map: max abs row sum (forward) and
    max abs column sum (backward)."""
    a = np.abs(p)
    return a.sum(-1).max(-1), a.sum(-2).max(-1)

# ---------- Part 1: deviation after t Sinkhorn-Knopp iterations ----------
rng = np.random.default_rng(1)
print("part 1: single layer, 10000 random 4x4 matrices, logits ~ N(0, scale^2)")
print("  scale  t   max|row-1|   mean max|col-1|   max max|col-1|")
for s in (0.5, 1.0, 2.0):
    z = s * rng.standard_normal((10000, n, n))
    for t in (1, 2, 5, 10, 20, 50):
        m = sinkhorn(z, t)
        row = np.abs(m.sum(-1) - 1).max()
        col = np.abs(m.sum(-2) - 1).max(-1)
        print(f"  {s:4.1f} {t:3d}   {row:.1e}     {col.mean():.1e}"
              f"          {col.max():.1e}")

# ---------- Part 2: how the composite gain changes with depth ----------
L, R, T = 60, 200, 20  # 60 sub-layers (30 blocks x attention, FFN), 200 chains
rng = np.random.default_rng(2)
z = rng.standard_normal((R, L, n, n))
eye = np.eye(n)
series = [("HC .05", eye + 0.05 * z), ("HC .10", eye + 0.10 * z),
          ("HC .20", eye + 0.20 * z)]
for s in (0.5, 1.0, 2.0):  # mHC: 3I + s*z as logits, projected
    series.append((f"mHC {s:.1f}", sinkhorn(3 * eye + s * z, T)))

ks = (1, 5, 10, 20, 30, 40, 50, 60)
fwd = {name: [] for name, _ in series}
bwd = {name: [] for name, _ in series}
worst = {}
for name, h in series:
    p = np.broadcast_to(eye, (R, n, n))
    for k in range(1, L + 1):
        p = h[:, k - 1] @ p  # the later layer multiplies on the left
        if k in ks:
            f, b = gains(p)
            fwd[name].append(np.median(f))
            bwd[name].append(np.median(b))
    worst[name] = (f.max(), b.max())  # the loop ends at k = 60
print()
print(f"part 2: composite of k layers, median of {R} chains")
print(f"  HC: H = I + sigma*z; mHC: sinkhorn(3I + s*z, T = {T}); z ~ N(0, 1)")
for title, tab in (("forward gain (max abs row sum)", fwd),
                   ("backward gain (max abs column sum)", bwd)):
    print(" ", title)
    print("    k  " + " ".join(f"{name:>9s}" for name in tab))
    for i, k in enumerate(ks):
        print(f"  {k:3d}  " + " ".join(f"{tab[name][i]:9.3g}" for name in tab))
print("  worst chain at k = 60, forward / backward gain:")
for name in worst:
    print(f"    {name:8s} {worst[name][0]:10.6g} {worst[name][1]:10.6g}")

# ---------- Part 3: how much a product of them mixes the streams ----------
rng = np.random.default_rng(3)
z = rng.standard_normal((R, L, n, n))
print()
print("part 3: second singular value of the composite (1 = no mixing)")
print("  logits = kappa*I + z, z ~ N(0, 1), 1000 Sinkhorn iterations")
ks3 = (1, 2, 5, 10, 20, 40, 60)
print("    k  " + " ".join(f"{'kappa ' + str(c):>9s}" for c in (0, 3, 6)))
sv, smax, dev = {}, 0.0, {}
for c in (0, 3, 6):
    h = sinkhorn(c * eye + z, 1000)  # 1000 iterations
    dev[c] = max(np.abs(h.sum(-1) - 1).max(), np.abs(h.sum(-2) - 1).max())
    p = np.broadcast_to(eye, (R, n, n))
    sv[c] = []
    for k in range(1, L + 1):
        p = h[:, k - 1] @ p
        s_all = np.linalg.svd(p, compute_uv=False)
        smax = max(smax, s_all[:, 0].max())
        if k in ks3:
            sv[c].append(np.median(s_all[:, 1]))
for i, k in enumerate(ks3):
    print(f"  {k:3d}  " + " ".join(f"{sv[c][i]:9.2e}" for c in (0, 3, 6)))
print(f"  largest singular value over all chains and depths: {smax:.8f}")
print("  after 1000 iterations, max |row or column sum - 1| of one layer:")
print("   " + ", ".join(f"kappa {c}: {dev[c]:.1e}" for c in (0, 3, 6)))

# Birkhoff decomposition: a converged doubly stochastic matrix is a
# convex combination of permutation matrices
m = sinkhorn(np.random.default_rng(4).standard_normal((n, n)), 1000)
rest, parts = m.copy(), []
while rest.max() > 1e-9:
    rows, cols = linear_sum_assignment((rest <= 1e-12).astype(float))
    w = rest[rows, cols].min()
    assert w > 0
    perm = np.zeros((n, n))
    perm[rows, cols] = 1
    rest = rest - w * perm
    parts.append((w, perm))
back = sum(w * perm for w, perm in parts)
print(f"Birkhoff: {len(parts)} permutations (at most {(n - 1) ** 2 + 1}),"
      f" weights sum {sum(w for w, _ in parts):.6f},"
      f" reconstruction error {np.abs(back - m).max():.1e}")

# ---------- Part 4: memory traffic (Table 2) and extra parameters ----------
C, nl = 2560, 60  # hidden size of the 27B model (paper Table 5), 60 sub-layers
res_in, res_out = 2 * C, C
rows_in = [n * C, n * C + n, C + n, n * C + n * n, 2 * n * C]
rows_out = [n * n + 2 * n, C, n * C, n * C, n * C]
hc_in, hc_out = sum(rows_in), sum(rows_out)
assert hc_in == (5 * n + 1) * C + n * n + 2 * n
assert hc_out == (3 * n + 1) * C + n * n + 2 * n
print()
print(f"part 4: C = {C}, n = {n}, elements per token per layer")
print(f"  residual   read {res_in:6d}  write {res_out:6d}")
print(f"  HC / mHC   read {hc_in:6d}  write {hc_out:6d}"
      f"  ({hc_in / res_in:.1f}x, {hc_out / res_out:.1f}x)")
b_in, b_out = (3 * n + 1) * C, 3 * n * C  # before fusion
a_in, a_out = (n + 1) * C, n * C  # after fusion
print(f"  merge kernel before fusion: read {b_in}, write {b_out}")
print(f"  merge kernel after fusion:  read {a_in}, write {a_out}")
phi = n * C * (n * n + 2 * n)
per_layer = phi + (n * n + 2 * n) + 3
total = per_layer * nl
print(f"  extra parameters: {per_layer} per layer, {total} in {nl} layers,"
      f" {total / 27.0e9:.4%} of 27.0B")
for depth in (12, 18, 30, 60):
    best = min(range(1, depth + 1),
               key=lambda r: n * C * -(-depth // r) + (n + 2) * C * r)
    approx = (n * depth / (n + 2)) ** 0.5
    print(f"  L = {depth:2d}: best block {best}, formula {approx:.2f}")
```

Output:

```text
part 1: single layer, 10000 random 4x4 matrices, logits ~ N(0, scale^2)
  scale  t   max|row-1|   mean max|col-1|   max max|col-1|
   0.5   1   4.4e-16     5.3e-02          2.4e-01
   0.5   2   3.3e-16     4.4e-03          6.9e-02
   0.5   5   4.4e-16     1.1e-05          1.4e-03
   0.5  10   4.4e-16     5.3e-09          7.4e-06
   0.5  20   3.3e-16     4.2e-14          2.1e-10
   0.5  50   2.2e-16     2.3e-17          2.2e-16
   1.0   1   4.4e-16     1.7e-01          9.0e-01
   1.0   2   4.4e-16     3.7e-02          2.9e-01
   1.0   5   4.4e-16     1.4e-03          5.9e-02
   1.0  10   4.4e-16     3.1e-05          8.0e-03
   1.0  20   4.4e-16     1.7e-07          1.5e-04
   1.0  50   2.2e-16     1.4e-12          6.2e-09
   2.0   1   4.4e-16     3.6e-01          1.5e+00
   2.0   2   4.4e-16     1.5e-01          8.8e-01
   2.0   5   4.4e-16     2.5e-02          2.6e-01
   2.0  10   4.4e-16     3.9e-03          8.7e-02
   2.0  20   4.4e-16     4.7e-04          3.1e-02
   2.0  50   3.3e-16     2.2e-05          8.7e-03

part 2: composite of k layers, median of 200 chains
  HC: H = I + sigma*z; mHC: sinkhorn(3I + s*z, T = 20); z ~ N(0, 1)
  forward gain (max abs row sum)
    k     HC .05    HC .10    HC .20   mHC 0.5   mHC 1.0   mHC 2.0
    1        1.2      1.39      1.78         1         1         1
    5       1.45      1.92         3         1         1         1
   10       1.65      2.39      4.37         1         1         1
   20       1.91      2.98      7.22         1         1         1
   30       2.19      3.88      12.2         1         1         1
   40       2.39      4.31        19         1         1         1
   50       2.51      5.13      28.3         1         1         1
   60       2.63      5.34      39.5         1         1         1
  backward gain (max abs column sum)
    k     HC .05    HC .10    HC .20   mHC 0.5   mHC 1.0   mHC 2.0
    1        1.2       1.4      1.79         1         1         1
    5       1.45      1.93      3.03         1         1         1
   10       1.62      2.31      4.31         1         1         1
   20       1.92      3.04      6.85         1         1         1
   30       2.14      3.67      11.5         1         1         1
   40       2.35      4.36      17.9         1         1         1
   50       2.57       5.1      27.9         1         1         1
   60       2.64      5.23      38.7         1         1         1
  worst chain at k = 60, forward / backward gain:
    HC .05      6.31702    5.81777
    HC .10      34.4305    26.4776
    HC .20      1285.59    1861.76
    mHC 0.5           1    1.00225
    mHC 1.0           1    1.01066
    mHC 2.0           1    1.03208

part 3: second singular value of the composite (1 = no mixing)
  logits = kappa*I + z, z ~ N(0, 1), 1000 Sinkhorn iterations
    k    kappa 0   kappa 3   kappa 6
    1   4.90e-01  8.70e-01  9.92e-01
    2   1.80e-01  7.10e-01  9.81e-01
    5   6.53e-03  3.34e-01  9.39e-01
   10   2.34e-05  8.16e-02  8.69e-01
   20   2.41e-10  5.13e-03  7.42e-01
   40   4.81e-17  1.41e-05  5.31e-01
   60   4.81e-17  3.72e-08  3.78e-01
  largest singular value over all chains and depths: 1.00000047
  after 1000 iterations, max |row or column sum - 1| of one layer:
   kappa 0: 3.3e-16, kappa 3: 1.2e-12, kappa 6: 2.4e-04
Birkhoff: 10 permutations (at most 10), weights sum 1.000000, reconstruction error 1.1e-16

part 4: C = 2560, n = 4, elements per token per layer
  residual   read   5120  write   2560
  HC / mHC   read  53784  write  33304  (10.5x, 13.0x)
  merge kernel before fusion: read 33280, write 30720
  merge kernel after fusion:  read 12800, write 10240
  extra parameters: 245787 per layer, 14747220 in 60 layers, 0.0546% of 27.0B
  L = 12: best block 3, formula 2.83
  L = 18: best block 3, formula 3.46
  L = 30: best block 5, formula 4.47
  L = 60: best block 6, formula 6.32
```

### Sinkhorn-Knopp: exact row sums, residual column sums

In the first block of the output, the row-sum error is at most 4.4e-16 for every iteration count, which is just floating-point rounding. The column-sum error shrinks quickly with the number of iterations, but how quickly depends on the scale of the logits. The table shows the average, over 10,000 matrices, of the largest column-sum error:

| Logit std | $t=1$ | $t=5$ | $t=20$ | $t=50$ |
| --- | --- | --- | --- | --- |
| 0.5 | 5.3e-02 | 1.1e-05 | 4.2e-14 | 2.3e-17 |
| 1.0 | 1.7e-01 | 1.4e-03 | 1.7e-07 | 1.4e-12 |
| 2.0 | 3.6e-01 | 2.5e-02 | 4.7e-04 | 2.2e-05 |

Why are the row sums always exact? The paper's Eq. 9 is $M^{(t)}=\mathcal T_r\mathcal T_c(M^{(t-1)})$, so every round ends with a row normalization: the row sums are exactly 1 and only the column sums carry a residual. This matches the paper's Section 5.4, where the backward gain (column sums) deviates slightly from 1. The paper uses 20 iterations. With logits of standard deviation 1, the average column-sum error after 20 iterations is 1.7e-07 and the worst matrix is 1.5e-04. With standard deviation 2, the average is 4.7e-04 and the worst is 3.1e-02. The more peaked the logits, the slower the convergence.

### Composite gain: it grows with depth when unconstrained, and stays at 1 when doubly stochastic

*Figure: Figure: median gain of 200 chains against the number of composed layers k, on a logarithmic axis. The three colored lines are unconstrained matrices I+σZ (σ = 0.05, 0.10, 0.20, Z a standard normal matrix); the blue line is 3I+sZ projected onto doubly stochastic matrices with 20 Sinkhorn-Knopp iterations (s = 0.5, 1, 2, the three lines overlap at 1). Data from the second block of the output above.*

Results at $k=60$:

| Matrix | Fwd median | Bwd median | Fwd worst | Bwd worst |
| --- | --- | --- | --- | --- |
| Unconstrained, $\sigma=0.05$ | 2.63 | 2.64 | 6.31702 | 5.81777 |
| Unconstrained, $\sigma=0.10$ | 5.34 | 5.23 | 34.4305 | 26.4776 |
| Unconstrained, $\sigma=0.20$ | 39.5 | 38.7 | 1285.59 | 1861.76 |
| Doubly stochastic, $s=0.5$ | 1 | 1 | 1 | 1.00225 |
| Doubly stochastic, $s=1.0$ | 1 | 1 | 1 | 1.01066 |
| Doubly stochastic, $s=2.0$ | 1 | 1 | 1 | 1.03208 |

"Worst" is the maximum over the 200 chains. A few points stand out:

- **Products of unconstrained matrices grow with depth.** Even when every layer deviates only slightly from the identity ($\sigma=0.05$), the median gain after 60 layers is 2.6; with $\sigma=0.20$ it is 39.5. The larger the deviation, the faster the growth.
- **The distribution has a heavy tail.** With $\sigma=0.20$ the worst chain is about 30 to 50 times the median (1285.59 forward, 1861.76 backward). The paper reports a composite-gain peak of nearly 3000 for HC on the 27B model. That is the same order of magnitude as my worst chain, but the two are different things: one comes from trained matrices, the other from a random distribution I picked, so they cannot confirm each other.
- **The forward gain of a doubly stochastic product is exactly 1.** The entries are non-negative and every row sums to 1; after any number of multiplications every row still sums to 1, so the largest absolute row sum is 1.
- **The backward gain has a small residual.** It comes from the finite number of iterations: in this toy distribution the worst 60-layer chain is 1.00225 ($s=0.5$), 1.01066 ($s=1$) and 1.03208 ($s=2$), growing with the scale of the logits. The paper measures a maximum composite backward gain of about 1.6 in its trained 27B model, so the deviation in a real model is larger than in my toy distribution; the paper does not say what the real logits look like.

### Products of doubly stochastic matrices: spectral norm at most 1, and ever more uniform

The third block of the output uses doubly stochastic matrices (per-layer logits $\kappa I+Z$, projected with 1000 iterations) and reports the second-largest singular value of the composite:

| Composed layers $k$ | $\kappa=0$ | $\kappa=3$ | $\kappa=6$ |
| --- | --- | --- | --- |
| 1 | 4.90e-01 | 8.70e-01 | 9.92e-01 |
| 5 | 6.53e-03 | 3.34e-01 | 9.39e-01 |
| 20 | 2.41e-10 | 5.13e-03 | 7.42e-01 |
| 60 | 4.81e-17 | 3.72e-08 | 3.78e-01 |

- **A spectral norm of at most 1 holds.** Over 36,000 composite matrices (3 values of $\kappa$ × 200 chains × 60 depths), the largest singular value is 1.00000047. The extra 4.7e-07 is related to imperfect projection: the logits at $\kappa=6$ are sharply peaked, and after 1000 iterations a single layer still has a row or column sum error of up to 2.4e-04 (3.3e-16 and 1.2e-12 for $\kappa=0$ and 3).
- **The composite drifts toward "take the average".** At $\kappa=0$ the per-layer logits are pure noise and a single matrix already mixes noticeably (second singular value 4.90e-01); after 5 layers only 6.53e-03 is left, and from 40 layers on it is 4.81e-17 (zero in floating-point terms): the composite is the matrix with every entry equal to $1/4$, so the four streams have become one. At $\kappa=6$ each layer is close to the identity, and after 60 layers the second singular value is still 3.78e-01, so the streams remain distinct.
- **This is the other side of the constraint: stability is bought with mixing.** To keep the streams distinct in a very deep network, each layer's matrix has to stay close to a permutation or the identity. The paper's Figure 8 shows the mHC matrices of its trained 27B model (averaged over all tokens in one sequence): the single-layer matrices at layers 30 and 60 have diagonal entries between 0.81 and 1.00, close to the identity; the layer-1 matrix mixes much more (diagonal 0.67, 0.48, 0.00, 0.69); and for the composite of all 60 layers, all 16 entries lie between 0.21 and 0.29, close to $1/4$. In that model, then, the whole 60-layer composite residual mapping is almost an average of the four streams. This is my reading of the numbers in the figure, not the paper's wording; the paper's property 3 presents "repeated application monotonically increases mixing" as robust feature fusion, and these numbers show the other side of the same fact.
- **The Birkhoff decomposition holds.** A 4×4 doubly stochastic matrix, obtained from random logits and 1000 iterations, splits into a weighted sum of 10 permutation matrices; the weights add up to 1.000000 and the reconstruction error is 1.1e-16. The Birkhoff polytope has dimension $(n-1)^2=9$, so by Carathéodory's theorem at most 10 permutations are needed.

### Table 2's arithmetic

The last block of the output adds up the paper's Table 2 for HC (elements read and written per token per layer, $C=2560$, $n=4$) and compares it with a plain residual connection:

| Item | Read (elements) | Written (elements) |
| --- | --- | --- |
| Plain residual | 5,120 | 2,560 |
| HC, unfused | 53,784 | 33,304 |
| Ratio | 10.5× | 13.0× |

The assertions in the script check that the totals agree with the table's formulas: reads are $(5n+1)C+n^2+2n$ and writes are $(3n+1)C+n^2+2n$. HC's cost is therefore not in FLOPs but in memory traffic: reads and writes grow roughly linearly in $n$, which turns directly into time when training is limited by the memory wall. Section 4.3.1 of the paper cuts the reads of the kernel that applies the mappings and merges the residual from $(3n+1)C$ to $(n+1)C$ and the writes from $3nC$ to $nC$; at $n=4$ that is reads of 33,280 down to 12,800 and writes of 30,720 down to 10,240.

Two more pieces of arithmetic:

- **The extra parameters are tiny.** By the paper's Eq. 7, each sub-layer has its own $\varphi^{\text{pre}},\varphi^{\text{post}},\varphi^{\text{res}}$ ($nC(n^2+2n)=245{,}760$ parameters in total), $n^2+2n=24$ biases and 3 scalars, 245,787 per layer. With one set for each of the 60 sub-layers that is 14,747,220 parameters, 0.0546% of the 27.0B total. This is my own estimate from Eq. 7 and Table 5, assuming each sub-layer has its own set of mappings; the paper does not state the number. mHC's extra cost is therefore almost entirely in time and memory, not in parameters.
- **Recomputation block size.** Eq. 20 balances "store the input every $L_r$ layers" against "the transient memory of recomputing inside a block": $L_r^*\approx\sqrt{nL/(n+2)}$. Enumerating integers gives an optimum within 1 of the formula: 6 for $L=60$ (formula 6.32), 5 for $L=30$ (formula 4.47), and 3 for both $L=18$ and $L=12$ (formulas 3.46 and 2.83). The paper notes that the theoretical optimum usually lines up with the number of layers per pipeline stage, so it simply aligns the recomputation boundaries with the pipeline stages.

### What this check shows, and what it does not

It shows:

- **Sinkhorn-Knopp gives exact row sums and residual column sums, with residuals depending on the scale of the logits**, consistent with the paper's Section 5.4.
- **A product of unconstrained matrices has a gain that grows with depth and has a heavy tail; the forward gain of a doubly stochastic product is exactly 1 and the backward gain has only a small residual.** This is the mathematical part of the paper's argument that the identity mapping is broken by HC and that the doubly stochastic constraint bounds it.
- **The constraint also has a mathematical cost:** products of doubly stochastic matrices drift toward the average.
- **Table 2's totals agree with its formulas**, and HC's memory traffic is more than 10 times that of a plain residual connection, which is why it needs kernel fusion.

It does not show:

- **Whether mHC really makes training more stable or better.** That requires training real models, and the paper has one set of curves and tables at the 27B scale.
- **What real HC matrices look like.** My choice of $\sigma$ has no connection to the 3000 in the paper's Figure 3.
- **Whether 20 iterations are enough.** That depends on the scale of the real logits, and the paper does not sweep the iteration count.
- **The 6.7% extra time.** It depends on their kernels, hardware and pipeline; I did not measure it.

## The paper's experiments and conclusions

Section 5 compares the baseline, HC and mHC in language-model pre-training. The models are DeepSeek-V3-style MoE models (with MLA and loss-free load balancing), and the expansion rate is $n=4$ for both HC and mHC. Appendix Table 5 gives the configurations:

| Item | 3B | 9B | 27B |
| --- | --- | --- | --- |
| Total / active params | 2.97B / 612M | 9.18B / 1.66B | 27.0B / 4.14B |
| Layers / hidden size | 12 / 1280 | 18 / 1920 | 30 / 2560 |
| Routed / active / shared experts | 64 / 6 / 2 | 64 / 6 / 2 | 72 / 6 / 2 |
| Training tokens | 39.3B | 105B | 262B |

A separate 3B model trained on 1 trillion tokens (1.05T in Table 5) is used to study token scaling. The main findings:

- **Training stability (Figure 5).** On the 27B model, mHC's final loss is 0.021 below the baseline's; its gradient norm is comparable to the baseline's and clearly better than HC's (HC shows a loss surge around step 12k).
- **Downstream benchmarks (Table 4).** 27B models, 8 benchmarks:

| Benchmark (metric, shots) | 27B baseline | 27B with HC | 27B with mHC |
| --- | --- | --- | --- |
| BBH (EM, 3-shot) | 43.8 | 48.9 | 51.0 |
| DROP (F1, 3-shot) | 47.0 | 51.6 | 53.9 |
| GSM8K (EM, 8-shot) | 46.7 | 53.2 | 53.8 |
| HellaSwag (Acc, 10-shot) | 73.7 | 74.3 | 74.7 |
| MATH (EM, 4-shot) | 22.0 | 26.4 | 26.0 |
| MMLU (Acc, 5-shot) | 59.0 | 63.0 | 63.4 |
| PIQA (Acc, 0-shot) | 78.5 | 79.9 | 80.5 |
| TriviaQA (EM, 5-shot) | 54.3 | 56.3 | 57.6 |

mHC beats the baseline on all 8 benchmarks and HC on 7 of them, falling slightly behind only on MATH. The paper highlights that relative to HC, mHC adds another 2.1 points on BBH and 2.3 points on DROP.

- **Scaling experiments (Figure 6).** Across the 3B, 9B and 27B models, each trained on a proportional amount of data, mHC's loss advantage over the baseline "is robustly maintained, showing only marginal attenuation"; the 3B model's trajectory over 1T tokens gives the token-scaling curve. The figure has no numeric labels, so I do not quote values. The paper adds that its in-house large-scale training experiments corroborate the conclusion, without giving data.
- **Propagation stability (Figures 7 and 8).** The single-layer forward gain of mHC is about 1 across the 60 layers and the backward gain deviates slightly from 1 (finite Sinkhorn iterations); the maximum composite gain is about 1.6, three orders of magnitude below HC's nearly 3000.

## Limitations and what comes next

- **One architecture family, one expansion rate.** All experiments use DeepSeek-V3-style MoE models with $n=4$; there is no dense model, no ablation over $n$, and no comparison with alternative constraints such as normalizing rows only or other manifolds, although the conclusion says the framework allows exploring other manifolds.
- **No error bars.** On the 27B model the final loss differs by only 0.021, and the baseline, HC and mHC are one run each, so seed-to-seed variation is unknown; on MATH, mHC is below HC, and there is no way to tell whether that is noise.
- **How general HC's instability is, the paper does not explore.** The loss surge appears in one 27B training run; whether a different learning rate or initialization would show it too is not discussed.
- **Twenty iterations is an empirical value.** The paper does not sweep $t_{\max}$; my experiment shows that the residual depends on the scale of the logits, and the paper does not show the real distribution.
- **Stability is bought with mixing.** Products of doubly stochastic matrices drift toward averaging the streams (visible in this post's code and in the paper's Figure 8). The paper's property 3 presents "repeated application monotonically increases mixing" as robust feature fusion, and its conclusion adds that other geometric constraints might trade off plasticity and stability better. Whether the streams of a wide residual stream keep distinct roles is not analyzed.
- **The in-house experiments come without data.** The conclusion drawn from "in-house large-scale training" is a single sentence.
- **The cost figure depends on their implementation.** The 6.7% was measured with DeepSeek's kernels, hardware and pipeline, and may not carry over to another framework.

## What to take from this paper

1. **Look at the composite mapping, not the single layer.** HC's problem is not how large one layer's $H^{\text{res}}$ is, but the product over dozens of layers; stability has to be discussed on the product.
2. **Each of the three properties of the doubly stochastic constraint does a different job.** A spectral norm of at most 1 gives "does not amplify", closure under multiplication gives "holds between any two depths", and the convex combination gives "streams can still exchange information".
3. **The constraint has a price.** Products drift toward the average, so stability trades against how different the streams stay; the 60-layer composite in Figure 8 being close to $1/4$ is consistent with that.
4. **Do the memory-traffic arithmetic before the FLOPs.** Reads and writes more than 10 times those of a plain residual connection are what make HC hard to use, and the reason the paper spends so many pages on kernels, recomputation and communication.
5. **Separate the levels of evidence.** The mathematical properties can be checked yourself (this post does); the curves and tables at 27B are the paper's observations from a single run; the "in-house large-scale experiments" have no data.

## Further reading

- Xie et al., [mHC: Manifold-Constrained Hyper-Connections](https://arxiv.org/abs/2512.24880) (arXiv:2512.24880; this post follows v2).
- Zhu et al., [Hyper-Connections](https://arxiv.org/abs/2409.19606) (arXiv:2409.19606, 2024): the method mHC improves.
- He et al., [Identity Mappings in Deep Residual Networks](https://arxiv.org/abs/1603.05027) (arXiv:1603.05027, 2016): why the identity mapping matters.
- DeepSeek-AI, [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437) (arXiv:2412.19437, 2024): the MoE architecture and DualPipe used in the paper's experiments (this site has an [explainer](https://dmxsf.com/en/blog/deepseek-v3-technical-report/)).
- On this site: the wiki pages [Transformer Block](https://dmxsf.com/en/wiki/architecture/transformer-block/) (residuals and normalization) and [Modern LLM Architecture](https://dmxsf.com/en/wiki/architecture/modern-llm-architecture/).
- Follow-up: DeepSeek-V4.1-Flash turns mHC into a Single-Pass version that shifts the input-mixing coefficients by one block and cuts activation traffic from $(4n+4)d$ to the bound $(2n+2)d$; see the [paper breakdown](https://dmxsf.com/en/blog/deepseek-v41-flash-pushing-the-limits-of-kv-cache-compression/).
- Another route to the same spot: Kimi's Attention Residuals keeps a single residual stream and replaces the weight-1 sum of earlier layer outputs with softmax attention using one pseudo-query per layer; see the [paper breakdown](https://dmxsf.com/en/blog/attention-residuals/).

## FAQ

### How does mHC differ from hyper-connections (HC)?

The structure is the same: the single residual stream becomes n streams (the paper uses n=4), managed by three learned mappings. H_pre merges the n streams into one input for the sub-layer, H_post spreads the sub-layer output back over the n streams, and H_res is an n-by-n matrix that mixes the streams. The difference is the constraint. In HC all three mappings are unconstrained, so over many layers the signal can grow or shrink without bound; on the 27B model the paper observes composite-gain peaks of nearly 3000 and a loss surge around step 12k. mHC projects H_res onto doubly stochastic matrices (non-negative entries, every row and column summing to 1) with Sinkhorn-Knopp, keeps H_pre and H_post non-negative with a sigmoid, and adds kernel fusion, recomputation and communication overlap.

### Why doubly stochastic matrices?

The paper lists three properties. First, the spectral norm of a doubly stochastic matrix is at most 1, so the mapping cannot amplify the signal. Second, the set is closed under multiplication, so the composite over any number of layers is still doubly stochastic and bounded. Third, these matrices form the Birkhoff polytope, the convex hull of permutation matrices, so residual mixing is a convex combination that exchanges information between streams without changing the overall signal scale. For n=1 the condition reduces to the scalar 1, the ordinary identity mapping. The code in this post confirms the first two properties numerically.

### How much slower does training get with mHC?

The paper reports only 6.7% extra training time at n=4 in its large-scale training, provided three optimizations are in place: kernel fusion (TileLang plus mixed precision), selective recomputation, and communication overlap in a modified DualPipe schedule. Without them memory traffic is the problem. Using the paper's Table 2 with hidden size 2560 and n=4, HC reads 10.5 times and writes 13.0 times as many elements per token per layer as a plain residual connection. The parameter increase is small: by the paper's formulas, about 0.05% of the 27B model, which is my own estimate because the paper does not state it.

### How big are mHC's gains in the paper?

On the 27B MoE model (262B training tokens), mHC's final training loss is 0.021 lower than the baseline's. On 8 downstream benchmarks it beats the baseline on all and HC on 7, falling slightly behind only on MATH (26.0 versus 26.4). For example BBH goes from 43.8 for the baseline to 48.9 for HC and 51.0 for mHC, and DROP from 47.0 to 51.6 and 53.9. The paper also shows compute-scaling curves for 3B, 9B and 27B models, with the advantage shrinking only slightly. It reports no seed variation or error bars, and each of the baseline, HC and mHC is a single training run.

### After only 20 Sinkhorn-Knopp iterations, is the matrix still doubly stochastic?

Not exactly. Each iteration normalizes columns and then rows, so the row sums are exactly 1 and only the column sums carry a residual, which matches the paper's Section 5.4, where the backward gain deviates slightly from 1. The size of the residual depends on the scale of the logits. In this post's experiment, with random logits of standard deviation 1, the average column-sum error after 20 iterations is 1.7e-07 and the worst is 1.5e-04; with standard deviation 2 the average is 4.7e-04 and the worst is 3.1e-02. In the trained 27B model the paper measures a maximum composite backward gain of about 1.6 over 60 layers, still three orders of magnitude below HC's nearly 3000.
