Mixture of Curvature Experts¶
The feed-forward block of HELM-MiCE (He et al. 2025): a DeepSeek-style mixture of
experts on the hyperboloid. Each routed expert works on its own hyperboloid sheet with
its own (optionally learnable) curvature, and the routed and shared expert outputs are
merged by one weighted Lorentzian centroid. LorentzMoE returns the block output and
the routing statistics; the Lorentzian residual with the block input is left to the
caller (see LorentzResidual).
Attention for the same architecture is LorentzMLA.
Load balancing follows DeepSeek-V3: add moe_sequence_balance_loss(stats, alpha) to the
training loss and call update_bias(stats.mask, speed) after each optimizer step. The
update is DeepSeek-V3's sign rule, the one the HELM paper cites. The routing bias is a RoutingBias variable, not an nnx.Param, so gradient transforms and
nnx.Optimizer(..., wrt=nnx.Param) skip it.
Mixture layer¶
hyperbolix.nn_layers.LorentzMoE ¶
LorentzMoE(
dim: int,
inter_dim: int,
num_routed: int,
num_shared: int,
top_k: int,
*,
rngs: Rngs,
route_scale: float = 1.0,
score_func: ScoreFunc = "softmax",
expert_curvatures: Sequence[float] | None = None,
learnable_curvature: bool = True,
curvature_parameterization: Parameterization = "log",
c_min: float | None | Auto = AUTO,
c_max: float | None | Auto = AUTO,
init_bound: float | None = None,
param_dtype: DTypeLike = jnp.float32,
eps: float = 1e-07,
)
Bases: Module
HELM's mixture of curvature experts (MiCE), in the paper's form.
For a token x on the hyperboloid with curvature c (paper, Sec. 4, with K = -c):
- The gate (:class:
LorentzMoEGate) selectstop_kof theErouted experts and gives them weightsg_i(renormalised over the selection;g_i = 0for the others). - Routed expert
ihas its own curvaturec_i:y_i = sqrt(c_i / c) HFFN_i(sqrt(c / c_i) x), a :class:LorentzSwiGLUon thec_isheet, mapped back. - Each of the
Rshared experts givesz_j = HFFN_j(x)at the model curvaturec. -
Output: the weighted Lorentzian centroid ::
MiCE(x) = (sum_i g_i y_i + sum_j z_j) / (sqrt(c) ||sum_i g_i y_i + sum_j z_j||_L)
computed by :func:lorentz_midpoint (its cancellation-free default form) over the
E + R outputs with weights [g, 1, ..., 1].
The block's Lorentzian residual x ⊕_L MiCE(x) is not part of this module; HELM applies it
in the decoder block. With :class:~hyperbolix.nn_layers.LorentzResidual in HELM's block
configuration (learnable softplus weight, fixed sqrt(dim) output scale)::
self.moe = LorentzMoE(dim, inter_dim, num_routed=8, num_shared=1, top_k=2, rngs=rngs)
self.ffn_res = LorentzResidual(scale=True, init_gamma=math.sqrt(dim))
...
moe_out_BSA, stats = self.moe(h_BSA, c) # h_BSA: the normalised block input
x_BSA = self.ffn_res(x_BSA, moe_out_BSA, c=c)
Load balancing, as the paper takes it from DeepSeek-V3, uses the returned stats: add
moe_sequence_balance_loss(stats, alpha) to the loss (HELM's alpha = 1e-4), and after
the optimizer step call moe.update_bias(stats.mask, speed) (DeepSeek-V3's sign rule; see
:meth:LorentzMoEGate.update_bias).
Curvatures
The routed experts start at c_i = linspace(0.1, 2.0, E) (the paper: "curvature initiated
uniformly from -0.1 to -2.0"), or at expert_curvatures. With learnable_curvature=True
each routed expert has its own :class:~hyperbolix.utils.curvature.LearnableCurvature,
clamped to [c_min, c_max]. By default these are LearnableCurvature's own bounds, set per
expert: [c_i / 10, c_i * 10] for log/softplus, so with the paper's
linspace(0.1, 2.0, E) the first expert is held to [0.01, 1] and the last to
[0.2, 20]. On a bound the clamp passes only a gradient that points back inside, so no
c_i gets pinned there. The forward reads each expert's curvature once
(:meth:routed_curvatures) and reuses it. Forward-mode autodiff (jax.jvp,
jax.jacfwd) through learnable curvatures raises, because the clamp is a custom VJP;
jax.grad works, and c_min=None, c_max=None gives plain autodiff.
HELM trains the raw curvatures with its AdamW weight decay (0.01); here decay of
curvatures[i].raw is up to the caller's optax chain (under log it pulls c_i toward 1).
Dispatch
Dense: every routed expert runs on every token (the experts are stacked on a leading
parameter axis and applied with jax.vmap over their split state), and unselected
outputs enter the centroid with weight 0, so they get zero gradient for that token. Cost is E / top_k times that of a
sparse dispatch, fine for small E; large E needs a gather or ragged dispatch. One
difference from a sparse dispatch: a non-finite output of an unselected expert still
reaches the centroid (0 * inf) and turns the token's output NaN.
Differences from the HELM code
The paper's form is implemented, not the released code. Where the two differ, the paper (or the intended math) is followed, and the layer does not reproduce the released code:
- Weights always renormalised. The code renormalises the top-k weights only for
sigmoid (
if self.score_func == "sigmoid": weights /= weights.sum(dim=-1, keepdim=True)); the paper renormalises in both cases, and so does :class:LorentzMoEGate, for either score function. - One centroid, order-free. The code merges routed outputs one expert at a time with an
LResNet that rescales the space part by a fixed 2 (
y[idx] = self.weighted_sum(y[idx], expert(x[idx]), weight=weights[idx, top, None])), then merges the shared output with a second LResNet with a learnable log-scale (out = self.add_experts(z, y)), so the result depends on expert order and carries two extra scales. The two LResNets are also built under crossed conditions (add_expertsundern_activated_experts == 2, used undern_shared_experts == 1). Here the output is the paper's single centroid (:func:lorentz_midpoint) of theE + Routputs, with no extra scale. Its curvature is the model curvaturecpassed at call time, and the routed experts' curvatures enter only through their own maps onto and back from their sheets. - Curvature init. The code builds every expert at
Lorentz(c=1.0, learnable=args.train_curv); itsnp.linspace(0.1, 2.0, ...)list is unused. Herec_i = linspace(0.1, 2.0, E). The released HELM 120M checkpoint (Zenodo record 18729608) follows the code: with its one optimizer step after training undone, every expert curvature is exactlyk = 1(c = 1), so the published run kept the curvatures fixed. To match that checkpoint passexpert_curvatures=[1.0] * num_routed, learnable_curvature=False. - Shared experts are
Rseparate SwiGLU experts, each with weight 1 in the centroid (the paper'ssum_j z_j); the code has oneLorentzFeedForwardof widthn_shared_experts * moe_inter_dim. They agree forR = 1. - Routing bias. The code's bias is an
nn.Parameterthat no gradient reaches and whose update is commented out of the training loop. Here it is a :class:RoutingBiasupdated by :meth:update_biaswith the DeepSeek-V3 sign rule the paper cites. The code's proportionalupdate_bias(self.bias += self.bias_update_spd * (mean - util)), which its training loop never calls, is not offered. - Balance loss. The code's
sequence_balance_lossfixesk=2, overwrites the expert counts with the index tensor (freq = indices * (E / (k * N)), a shape error) and averages over all tokens of the batch; :func:moe_sequence_balance_lossis DeepSeek-V3's per-sequence form. - Curvature parameterization. The routed curvatures are trained through
:class:
~hyperbolix.utils.curvature.LearnableCurvaturewith the defaultcurvature_parameterization="log":c_i = exp(raw_i), withraw_iinitialised tolog(c_i)and trained by the optimizer. This keepsc_i > 0. The released code trains the curvature parameterkof its geoopt-basedLorentzmanifold directly (Lorentz(c=1.0, learnable=args.train_curv)). - Library forms replace the code's
clamp_min(1e-8)time rebuilds and centroid normalizer: :func:spatial_to_hyperboloidand :func:lorentz_midpoint. - Shared-expert curvature. The paper's equations give each shared expert its own curvature
K_{s,j}(z_j = sqrt(K_{s,j}/K) HFFN_j(sqrt(K/K_{s,j}) x)) but state no init for it; here, as in the code, the shared experts run at the model curvaturec. - Not implemented: expert groups (
n_expert_groups/n_limited_groups; HELM's config uses one group, where they are a no-op).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int
|
Model ambient dimension |
required |
inter_dim
|
int
|
Spatial hidden width |
required |
num_routed
|
int
|
Number of routed experts |
required |
num_shared
|
int
|
Number of shared experts |
required |
top_k
|
int
|
Routed experts selected per token. |
required |
rngs
|
Rngs
|
Random number generators for parameter initialization. |
required |
route_scale
|
float
|
Positive factor on the routing weights, i.e. the routed experts' total weight against each shared expert's 1 (default: 1.0). |
1.0
|
score_func
|
(softmax, sigmoid)
|
Gate score activation (default: "softmax"). |
"softmax"
|
expert_curvatures
|
sequence of float or None
|
Initial curvatures of the |
None
|
learnable_curvature
|
bool
|
Train the routed experts' curvatures (default: True). If False they stay fixed. |
True
|
curvature_parameterization
|
(log, softplus, identity)
|
Passed to each |
"log"
|
c_min
|
(float, None or AUTO)
|
Clamp of each learnable expert curvature, passed to |
AUTO
|
c_max
|
(float, None or AUTO)
|
Clamp of each learnable expert curvature, passed to |
AUTO
|
init_bound
|
float or None
|
Uniform init bound of every expert projection; |
None
|
param_dtype
|
DTypeLike
|
Storage dtype of the layer weights (default: jnp.float32). The raw curvatures stay float32 (LearnableCurvature's default). Compute follows the input dtype. |
float32
|
eps
|
float
|
Numerical floor of the time rebuilds and the centroid (default: 1e-7). |
1e-07
|
Attributes:
| Name | Type | Description |
|---|---|---|
gate |
LorentzMoEGate
|
|
experts |
LorentzSwiGLU
|
The |
shared_experts |
LorentzSwiGLU or None
|
The |
curvatures |
nnx.List of LearnableCurvature, or None
|
One per routed expert if |
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
routed_curvatures ¶
Current curvatures c_i of the routed experts, shape (E,).
Calls each expert's LearnableCurvature once. Call this once per forward and reuse the
result: the clamp masks each call's gradient separately.
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
update_bias ¶
Auxiliary-loss-free bias update of the gate; see :meth:LorentzMoEGate.update_bias.
__call__ ¶
__call__(
x: Float[Array, "... A"], c: ScalarCurvature = 1.0
) -> tuple[Float[Array, "... A"], MoERoutingStats]
Apply the mixture of curvature experts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
(Array, shape(..., A))
|
Tokens on the hyperboloid with curvature |
required |
c
|
float or scalar Array
|
Model curvature (default: 1.0). |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
(Array, shape(..., A))
|
The weighted Lorentzian centroid of the expert outputs, on the hyperboloid with
curvature |
stats |
MoERoutingStats
|
|
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
Components¶
hyperbolix.nn_layers.LorentzMoEGate ¶
LorentzMoEGate(
dim: int,
num_experts: int,
top_k: int,
*,
rngs: Rngs,
score_func: ScoreFunc = "softmax",
route_scale: float = 1.0,
param_dtype: DTypeLike = jnp.float32,
)
Bases: Module
Top-k router of HELM-MiCE, in the HELM paper's form, with DeepSeek-V3's balancing bias.
For a token x on the hyperboloid with spatial part x_s, following the HELM paper (not
the released code, which renormalises the weights only for sigmoid scores):
- Scores
s_j = act(<x_s, y_j>), withy_jthe columnjof :attr:kernelandacta softmax over the experts or an elementwise sigmoid, in at least float32. - Selection: the
top_kexperts bys_j + b_j,bthe routing bias. - Weights: the unbiased scores of the selected experts, always renormalised (softmax and
sigmoid alike) to sum to 1 over the selection, times
route_scale:g_i = route_scale * s_i / sum_{j in TopK} s_j.
The bias only changes which experts are chosen, never their weights, and it is not trained by
gradient descent: call :meth:update_bias once per training step with the step's routing
mask (DeepSeek-V3's auxiliary-loss-free load balancing).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int
|
Model ambient dimension |
required |
num_experts
|
int
|
Number of routed experts |
required |
top_k
|
int
|
Experts selected per token, |
required |
rngs
|
Rngs
|
Random number generators for parameter initialization. |
required |
score_func
|
(softmax, sigmoid)
|
Score activation (default: "softmax", HELM's config). |
"softmax"
|
route_scale
|
float
|
Positive factor on the routing weights (default: 1.0, HELM's config). |
1.0
|
param_dtype
|
DTypeLike
|
Storage dtype of the kernel and bias (default: jnp.float32). |
float32
|
Attributes:
| Name | Type | Description |
|---|---|---|
kernel |
Param
|
Gate vectors, shape |
bias |
RoutingBias
|
Routing bias, shape |
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
__call__ ¶
__call__(
x_NA: Float[Array, "N A"],
) -> tuple[
Float[Array, "N K"], Int[Array, "N K"], MoERoutingStats
]
Route a batch of tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_NA
|
(Array, shape(N, A))
|
Tokens on the hyperboloid (any curvature: the gate reads the spatial part only). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
weights_NK |
(Array, shape(N, K))
|
Routing weights of the selected experts (at least float32), renormalised over the
selection and scaled by |
indices_NK |
int Array, shape (N, K)
|
Selected experts, in descending order of biased score. |
stats |
MoERoutingStats
|
|
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
update_bias ¶
Auxiliary-loss-free bias update from the step's routing mask.
load_i is the number of tokens routed to expert i in mask. The update is
DeepSeek-V3's sign rule, the one the HELM paper cites,
b_i += speed * sign(mean(load) - load_i). An overloaded expert's bias drops by
speed, an underloaded one's rises by speed, and an exactly average one's is
unchanged. DeepSeek-V3 applies it at the end of each training step, over all tokens of
the step (gather mask across data shards first); its speed (gamma) was
0.001, HELM's config sets 0.005.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
(Array, shape(..., E))
|
The routing mask of the step (:attr: |
required |
speed
|
float
|
Bias update speed |
required |
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
hyperbolix.nn_layers.LorentzSwiGLU ¶
LorentzSwiGLU(
dim: int,
inter_dim: int,
*,
rngs: Rngs,
init_bound: float | None = None,
param_dtype: DTypeLike = jnp.float32,
eps: float = 1e-07,
)
Bases: Module
HELM's Lorentzian SwiGLU feed-forward (HFFN) in the paper's form, run on an expert's own hyperboloid sheet.
For an input x on the model sheet (curvature c) and an expert curvature c_e:
- Map onto the expert sheet,
x_e = sqrt(c / c_e) x(the paper'ssqrt(K / K_e) x), computed as the spatial scaling with the time coordinate rebuilt atc_e(:func:spatial_to_hyperboloid), which equals the scaled ambient vector for on-sheetx. h = silu(w1(x_e)_s) * w3(x_e)_s, the spatial outputs of two HTC linear maps atc_e.hgets its time coordinate atc_e.w2maps the hidden point toA - 1spatial coordinates and :func:htcscales them bysqrt(c_e / c)and rebuilds the time atc, which is the paper's map backsqrt(K_e / K) HFFN_e(x_e)(the ambient point on thec_esheet, scaled).
With c_e = c this is the paper's dense Lorentzian feed-forward: the forward map is the same
as HELM's LorentzFeedForward, but the code is not a copy of HELM's. The input time
coordinate is rebuilt from the space part (step 1) and not read from x, so the ambient
input gradient differs from HELM's only along the hyperboloid normal. In float64 probes against
a port of HELM's code the tangential difference was 3.6e-15 and the Riemannian gradients agreed
to 2.3e-13.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
int
|
Model ambient dimension |
required |
inter_dim
|
int
|
Spatial width |
required |
rngs
|
Rngs
|
Random number generators for parameter initialization. |
required |
init_bound
|
float or None
|
Uniform init bound shared by the three maps. |
None
|
param_dtype
|
DTypeLike
|
Storage dtype of the parameters (default: jnp.float32). Compute follows the input dtype. |
float32
|
eps
|
float
|
Numerical floor of the time rebuilds (default: 1e-7). |
1e-07
|
Attributes:
| Name | Type | Description |
|---|---|---|
w1, w3 |
HTCLinear
|
|
w2 |
HTCLinear
|
|
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
__call__ ¶
__call__(
x_NA: Float[Array, "N A"],
c_expert: ScalarCurvature,
c: ScalarCurvature = 1.0,
) -> Float[Array, "N A"]
Apply the expert.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_NA
|
(Array, shape(..., A))
|
Points on the model hyperboloid with curvature |
required |
c_expert
|
float or scalar Array
|
The expert's curvature |
required |
c
|
float or scalar Array
|
Model curvature (default: 1.0). |
1.0
|
Returns:
| Type | Description |
|---|---|
(Array, shape(..., A))
|
Points on the model hyperboloid with curvature |
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
Load balancing¶
hyperbolix.nn_layers.moe_sequence_balance_loss ¶
DeepSeek-V3's complementary sequence-wise balance loss, averaged over sequences.
For one sequence of T tokens, E routed experts and k experts per token
(DeepSeek-V3, Eqs. 17-20)::
L_bal = alpha * sum_i f_i P_i
f_i = E / (k T) * sum_t 1[expert i in the top-k of token t]
P_i = 1 / T * sum_t s'_{i,t}, s'_{i,t} = s_{i,t} / sum_j s_{j,t}
f_i is the expert's load relative to a uniform share (it has no gradient) and P_i its
mean normalised affinity (differentiable in the gate kernel). k is read off the mask:
k T = sum_{i,t} mask. HELM's config sets alpha = 1e-4.
Values. Balanced routing (every expert in the top-k of k T / E tokens) gives
f_i = 1 and L = alpha for any affinities, and so does any routing when the affinities
are uniform. All tokens routed to the same k experts gives L >= alpha, with equality
only for uniform affinities, since the selected experts' affinities sum to at least k / E
per token. alpha is not a lower bound in general, though: a token routed to an expert it
barely prefers lowers sum_i f_i P_i below 1 (E = 2, k = 1, two tokens at
s' = (0.6, 0.4) on expert 0 and one at (0, 1) on expert 1 give 14/15 alpha).
Selection. DeepSeek-V3 writes the indicator with the top-k of the unbiased scores; here the
mask is the routing actually used, selected on the biased scores, so f_i is the load that
the bias is balancing. The two coincide while the bias is zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
MoERoutingStats
|
Routing statistics with shape |
required |
alpha
|
float
|
Balance factor. |
required |
Returns:
| Type | Description |
|---|---|
(Array, shape())
|
The loss, averaged over sequences. |
Source code in hyperbolix/nn_layers/hyperboloid_moe.py
hyperbolix.nn_layers.MoERoutingStats ¶
Bases: NamedTuple
Per-token routing statistics, the inputs of the load-balancing updates.
Attributes:
| Name | Type | Description |
|---|---|---|
affinity |
(Array, shape(..., E))
|
Gate scores normalised to sum to 1 over the experts of each token (DeepSeek-V3's
|
mask |
(Array, shape(..., E))
|
1.0 where the expert is among the token's selected |
hyperbolix.nn_layers.RoutingBias ¶
Bases: Variable
Per-expert routing bias of :class:LorentzMoEGate: state, not a parameter.
It only shifts the top-k selection, which has no gradient, and it moves only through
:meth:LorentzMoEGate.update_bias. Being an nnx.Variable and not an nnx.Param,
nnx.grad and nnx.Optimizer(..., wrt=nnx.Param) skip it.
Example¶
import jax, jax.numpy as jnp
from flax import nnx
from hyperbolix.manifolds import Hyperboloid
from hyperbolix.nn_layers import LorentzMoE, moe_sequence_balance_loss
dim, c = 9, 1.0 # 8 spatial dims + 1 time
hyperboloid = Hyperboloid()
tangent = jnp.zeros((2, 5, dim)).at[..., 1:].set(jax.random.normal(jax.random.PRNGKey(0), (2, 5, dim - 1)) * 0.1)
x = jax.vmap(jax.vmap(hyperboloid.expmap_0, in_axes=(0, None)), in_axes=(0, None))(tangent, c) # (2, 5, 9)
moe = LorentzMoE(dim, inter_dim=16, num_routed=4, num_shared=1, top_k=2, rngs=nnx.Rngs(0))
out, stats = moe(x, c) # out: (2, 5, 9) on the hyperboloid
aux_loss = moe_sequence_balance_loss(stats, alpha=1e-4)
moe.update_bias(stats.mask, speed=0.005) # after the optimizer step
print(out.shape, stats.mask.shape) # (2, 5, 9) (2, 5, 4)