Replaces the residual add with 4 parallel streams and a learned, Sinkhorn-normalized mixing of sublayer output into them.
The residual stream is widened into 4 parallel streams (hc_mult=4).
At each junction where a plain model would compute x + f(x), hyper-connections
instead:
- read the sublayer input as a learned combination of the 4 streams,
- write the sublayer output back into the streams through a learned mixing matrix,
- let the streams themselves exchange content through learned inter-stream weights.
The mixing weights are normalized by 20 Sinkhorn iterations
(alternating row/column normalization, eps=0.000001) toward doubly-stochastic form —
so mixing rearranges signal across streams without inflating or collapsing its total
magnitude, the failure mode that plagues naive learned residuals.
Why: a single residual stream forces every layer to read and write through one
d-dim bottleneck, creating a gradient tug-of-war between adjacent layers
(the "seesaw" the Hyper-Connections paper describes). Multiple streams let layers
specialize in where they write, at the cost of 4× residual activation
memory (weights are barely affected).
At the stack's end the streams are averaged (or summed) back to width d before the
final norm.
class HyperConnection(nn.Module):
"""Replaces: x = x + f(norm(x)), with x now [B, T, 4, d]."""
def __init__(self, d_model, n=4, sinkhorn_iters=20, eps=0.000001):
super().__init__()
self.read = nn.Parameter(torch.full((n,), 1.0 / n)) # stream → input
self.write = nn.Parameter(torch.eye(n)) # output → streams
self.iters, self.eps = sinkhorn_iters, eps
def sinkhorn(self, w):
w = w.exp()
for _ in range(self.iters): # → doubly stochastic
w = w / (w.sum(0, keepdim=True) + self.eps)
w = w / (w.sum(1, keepdim=True) + self.eps)
return w
def forward(self, streams, f): # streams: [B, T, 4, d]
x_in = (self.read[None, None, :, None] * streams).sum(2)
y = f(x_in) # attention or FFN
mix = self.sinkhorn(self.write) # [4, 4]
streams = torch.einsum("mn,btnd->btmd", mix, streams)
return streams + y[:, :, None, :] / 4