Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
# Changelog

## [0.3.5] — 2026-11-27 (stable)

The cluster-locality term gets a new default objective. In the 0.3.4 form it
cost language-model loss; in the 0.3.5 form it matches free routing at full
memory and improves CE under a resident-expert limit. The measurements and
the derivation are in `docs/CLUSTER_LOCALITY.md` section 9, with the numbers
in `reports/cluster_budget_20261127/summary.json`.

### Changed
- `cluster_locality_objective="budget"` is the new default: a balance term
over clusters plus, per stream, the mass outside its B heaviest clusters
(`cluster_locality_budget`, 0 = half the clusters, rounded up). The split
among those B clusters is free. `"mutual_info"` keeps the 0.3.1–0.3.4
objective.
- `cluster_locality_mass="dispatch"` is the new default: the term counts each
dispatch's top-k experts, renormalized. `"soft"` keeps the full softmax.
- `cluster_input_detach=True` is the new default: the term reads the gate
applied to a gradient-free copy of the MoE input, so it trains the gate
weights only. The cost is one extra gate projection per training dispatch.

### Compatibility
- A checkpoint saved before 0.3.5 has no `cluster_locality_objective` field;
loading it sets `"mutual_info"`, `"soft"` and `cluster_input_detach=False`,
so continued training keeps its objective unless the fields are overridden.
- The four fields are in the config schema, the training CLIs
(`--cluster_locality_objective`, `--cluster_locality_budget`,
`--cluster_locality_mass`, `--[no-]cluster_input_detach`) and the WebUI
(Objectives, advanced), with help text in all four languages.
- Torch and MLX compute the same values; the MLX record is read inside the
compiled and the recomputed step.

### Measured — MLX, one Apple M5, 0.3.5 defaults, segment mode, window 256
- 15M shape (24 experts), 0.3.4 default vs λ=0 at step 600: +0.290 CE, with
3.89 distinct experts per token against 7.45. With the 0.3.5 defaults:
−0.009 and 6.98.
- Cosine schedule over 2,000 steps, three seeds, valid CE clustered minus
free: 15M −0.0145, +0.0057, −0.0026; 30M −0.0190, −0.0104, +0.0517. This is
parity. In the 30M setup, two runs that matched the free runs' loss for the
first 300 steps already differed from them by +0.065 and −0.052 at step 200.
- Under a resident-memory limit the clustered model wins on every seed: at
15M with 12 experts resident it beats a free 12-expert model by
0.014–0.022 tail CE; at 30M with 8 of 16 experts resident it beats the
paged free model by 0.014–0.100.
- Cluster-level lookahead hit rate: 0.57–0.63 clustered vs 0.42–0.46 free.

## [0.3.4] — 2026-11-18 (stable)

One decoding-side fix lands on the shared_first serving path. Default
Expand Down
2 changes: 1 addition & 1 deletion chronos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Project Chronos: On-device low-latency lookahead dual-layer MoE inference
__version__ = "0.3.4"
__version__ = "0.3.5"

# Register with HuggingFace AutoXXX factories so
# AutoModelForCausalLM.from_pretrained("path/to/chronos") works out of the box.
Expand Down
1 change: 1 addition & 0 deletions chronos/config_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"lambda_balance", "lambda_temporal", "lambda_lookahead",
"lambda_lookahead_topk", "lambda_lookahead_union", "lambda_router_locality",
"lambda_cluster_locality", "lambda_iteration_cluster", "lookahead_teacher_scope", "cluster_locality_clusters", "cluster_locality_window", "cluster_locality_mode",
"cluster_locality_objective", "cluster_locality_budget", "cluster_locality_mass", "cluster_input_detach",
"lambda_router_anchor", "fallback_mask_prob", "offload_miss_policy_default",
"use_hybrid_attention", "kv_latent_dim", "rope_dim", "rope_layout", "sliding_window_size",
"kv_cache_dtype", "kv_quant_group_size", "mla_decode", "mla_cache_rope", "router_scope",
Expand Down
11 changes: 11 additions & 0 deletions chronos/expert_clusters.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ def resolve_cluster_count(config) -> int:
return max(1, min(n, e))


def cluster_budget(config) -> int:
"""Clusters one stream may use under ``cluster_locality_objective="budget"``; 0 selects the mutual-information
objective. ``cluster_locality_budget`` > 0 is used as given (at most the cluster count); 0 means half the clusters,
rounded up. A config without the field predates 0.3.5 and keeps the mutual-information objective."""
if str(getattr(config, "cluster_locality_objective", "mutual_info") or "mutual_info") != "budget":
return 0
c = resolve_cluster_count(config)
b = int(getattr(config, "cluster_locality_budget", 0) or 0)
return min(b, c) if b > 0 else max(1, -(-c // 2))


def contiguous_clusters(num_experts: int, num_clusters: int) -> List[List[int]]:
"""Split ``0..E-1`` into ``num_clusters`` contiguous, near-equal groups."""
e, c = int(num_experts), max(1, min(int(num_clusters), int(num_experts)))
Expand Down
19 changes: 19 additions & 0 deletions chronos/mlx/moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ def __init__(self, config):
object.__setattr__(self, "_last_router_probs", None) # [B, S, E]
# One entry per call: a recurrent block dispatches once per iteration.
object.__setattr__(self, "_iteration_router_probs", [])
# cluster_input_detach: one more record per training dispatch, the gate applied to stop_gradient(x). Only the
# cluster-locality term reads it, so that term trains the gate weights and never the hidden states. The loss
# reads it inside the (compiled) step, so it is not a compile side output.
object.__setattr__(self, "cluster_input_detach", bool(getattr(config, "cluster_input_detach", False)))
object.__setattr__(self, "_iteration_cluster_probs", [])
# router_scope="shared": later iterations reuse iteration zero's ids.
object.__setattr__(self, "router_scope", str(getattr(config, "router_scope", "per_iteration") or "per_iteration"))
object.__setattr__(self, "_shared_topk_idx", None)
Expand All @@ -91,14 +96,22 @@ def last_router_probs(self):
def iteration_router_probs(self):
return self._iteration_router_probs

@property
def iteration_cluster_probs(self):
return self._iteration_cluster_probs

def accept_side_output(self, kind, value):
"""Record one dispatch's router probabilities ``[B, S, E]``."""
if kind == "cluster_probs":
self._iteration_cluster_probs.append(value)
return
if kind != "probs":
raise ValueError(f"unknown MoE side output {kind!r}")
object.__setattr__(self, "_last_router_probs", value)
self._iteration_router_probs.append(value)

def reset_iteration_routing(self):
object.__setattr__(self, "_iteration_cluster_probs", [])
object.__setattr__(self, "_iteration_router_probs", [])
object.__setattr__(self, "_shared_topk_idx", None)

Expand Down Expand Up @@ -263,6 +276,12 @@ def __call__(
sink.append((self, "probs", probs))
else:
self.accept_side_output("probs", probs)
if self.cluster_input_detach and self.training:
cprobs = mx.softmax(self.gate(mx.stop_gradient(x_flat)).astype(mx.float32), axis=-1).reshape(B, S, self.num_experts)
if sink is not None:
sink.append((self, "cluster_probs", cprobs))
else:
self.accept_side_output("cluster_probs", cprobs)
topk_weight = mx.take_along_axis(scores, topk_idx, axis=-1) # [N, K]
if self.norm_topk_prob:
topk_weight = topk_weight / (topk_weight.sum(axis=-1, keepdims=True) + 1e-20)
Expand Down
72 changes: 63 additions & 9 deletions chronos/mlx/training/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,44 @@ def _cluster_membership(config) -> mx.array:
return hit


def _moe_probs(layers, attr: str) -> mx.array | None:
"""``[B, S, V, E]`` stack of one per-dispatch record (``attr``) over the MoE ``layers``, in the order of
``_collect_router_probs``."""
probs = []
for layer in layers:
moe = getattr(layer, "mlp", None)
if isinstance(moe, ChronosMLXMOE):
probs.extend(getattr(moe, attr, None) or [])
return mx.stack(probs, axis=2) if probs else None


def _dispatch_mass(router_4d: mx.array, top_k: int) -> mx.array:
"""Router probabilities kept on each dispatch's top-k experts and renormalized; the gradient reaches those k
entries. Torch twin: ``chronos.model.temporal_loss.dispatch_mass``."""
E = int(router_4d.shape[-1])
k = max(1, min(int(top_k or 1), E))
idx = mx.stop_gradient(mx.argpartition(-router_4d, kth=k - 1, axis=-1)[..., :k])
keep = (idx[..., None] == mx.arange(E)).astype(router_4d.dtype).sum(axis=-2)
sel = router_4d * keep
return sel / mx.maximum(sel.sum(axis=-1, keepdims=True), 1e-9)


def _cluster_spill(p: mx.array, budget: int) -> mx.array:
"""Per unit, the cluster mass outside its ``budget`` heaviest clusters (``[..., C]`` -> ``[...]``). The ranking
is held fixed, so the gradient moves mass into the unit's top clusters and leaves the split among them free;
``budget >= C`` gives 0. Torch twin: ``chronos.model.temporal_loss.cluster_spill``."""
C = int(p.shape[-1])
if budget >= C:
return mx.zeros(p.shape[:-1], p.dtype)
idx = mx.stop_gradient(mx.argpartition(-p, kth=budget - 1, axis=-1)[..., :budget])
outside = 1.0 - (idx[..., None] == mx.arange(C)).astype(p.dtype).sum(axis=-2)
return (p * outside).sum(axis=-1)


def _cluster_locality_loss(router_4d: mx.array, membership: mx.array, window: int = 0,
token_mask: mx.array | None = None) -> mx.array:
"""MLX twin of ``chronos.model.temporal_loss.cluster_locality_loss``: ``1 − I(window; cluster)/log C``.
token_mask: mx.array | None = None, budget: int = 0) -> mx.array:
"""MLX twin of ``chronos.model.temporal_loss.cluster_locality_loss``: ``1 − I(window; cluster)/log C``, or with
``budget`` = B > 0 the budget objective ``1 − H(marginal)/log C`` + the mass outside each window's B heaviest clusters.
``token_mask`` ``[B, S]`` (1 = real token) drops right-padding: a window's
cluster distribution averages its real tokens only, and windows count in
Expand All @@ -264,6 +299,8 @@ def entropy(p):

if token_mask is None:
pw = mass.mean(axis=(2, 3)).reshape(B * n, C)
if budget > 0:
return 1.0 - entropy(pw.mean(axis=0)) / math.log(C) + _cluster_spill(pw, budget).mean()
mutual = entropy(pw.mean(axis=0)) - entropy(pw).mean()
return 1.0 - mutual / math.log(C)
m = token_mask[:, : n * w].astype(mx.float32).reshape(B, n, w)
Expand All @@ -272,12 +309,14 @@ def entropy(p):
/ mx.maximum(count, 1.0)[..., None]).reshape(B * n, C)
weight = (count / mx.maximum(count.sum(), 1.0)).reshape(B * n) # windows ∝ real tokens
marginal = (pw * weight[:, None]).sum(axis=0)
if budget > 0:
return 1.0 - entropy(marginal) / math.log(C) + (_cluster_spill(pw, budget) * weight).sum()
mutual = entropy(marginal) - (entropy(pw) * weight).sum()
return 1.0 - mutual / math.log(C)


def _segment_cluster_loss(router_4d: mx.array, membership: mx.array, segments,
token_mask: mx.array | None = None) -> mx.array:
token_mask: mx.array | None = None, budget: int = 0) -> mx.array:
"""``1 − I(segment; cluster)/log C`` with documents as the unit (MLX twin of
``chronos.model.temporal_loss.segment_cluster_loss``), written with static shapes so it traces
under ``mx.compile``.
Expand Down Expand Up @@ -308,20 +347,35 @@ def entropy(p):
return -(p * mx.log(p)).sum(axis=-1)

marginal = (ps * weight[:, None]).sum(axis=0)
if budget > 0: # budget objective (see _cluster_locality_loss)
loss = 1.0 - entropy(marginal) / math.log(C) + (_cluster_spill(ps, budget) * weight).sum()
return mx.where((present > 0).sum() > 1, loss, mx.zeros(()))
mutual = entropy(marginal) - (entropy(ps) * weight).sum()
loss = 1.0 - mutual / math.log(C)
return mx.where((present > 0).sum() > 1, loss, mx.zeros(()))


def _cluster_objective(router_4d: mx.array, config, token_mask=None, input_ids=None) -> mx.array:
def _cluster_objective(router_4d: mx.array, config, token_mask=None, input_ids=None, model=None) -> mx.array:
"""The configured cluster-locality term: ``window`` (fixed token windows)
or ``segment`` (documents found from ``input_ids``; window form without them)."""
from chronos.expert_clusters import cluster_locality_mode, segment_ids_mx
or ``segment`` (documents found from ``input_ids``; window form without them).
``cluster_input_detach`` reads the gate-only record of ``model``'s MoE layers, so the term trains the gate weights
only; ``cluster_locality_mass="dispatch"`` keeps each dispatch's top-k experts, renormalized;
``chronos.expert_clusters.cluster_budget`` selects the budget or the mutual-information objective."""
from chronos.expert_clusters import cluster_budget, cluster_locality_mode, segment_ids_mx
window = int(getattr(config, "cluster_locality_window", 0) or 0)
membership = _cluster_membership(config)
if bool(getattr(config, "cluster_input_detach", False)) and model is not None:
detached = _moe_probs(getattr(model, "layers", []), "iteration_cluster_probs")
if detached is not None and tuple(detached.shape) == tuple(router_4d.shape):
router_4d = detached.astype(mx.float32)
if str(getattr(config, "cluster_locality_mass", "soft") or "soft") == "dispatch":
router_4d = _dispatch_mass(router_4d.astype(mx.float32), int(config.num_experts_per_tok))
budget = cluster_budget(config)
if cluster_locality_mode(config) == "segment" and input_ids is not None:
return _segment_cluster_loss(router_4d, membership, segment_ids_mx(input_ids, chunk=window), token_mask)
return _cluster_locality_loss(router_4d, membership, window, token_mask)
segments = segment_ids_mx(input_ids, chunk=window)
return _segment_cluster_loss(router_4d, membership, segments, token_mask, budget=budget)
return _cluster_locality_loss(router_4d, membership, window, token_mask, budget=budget)


def _recurrent_iteration_probs(model, config) -> mx.array | None:
Expand Down Expand Up @@ -695,7 +749,7 @@ def add(name, coefficient, value):
add("balance_loss", config.lambda_balance, _load_balance_loss(router, top_k, token_mask))
if float(getattr(config, "lambda_cluster_locality", 0.0) or 0.0) > 0.0:
add("cluster_locality_loss", config.lambda_cluster_locality,
_cluster_objective(router, config, token_mask, input_ids))
_cluster_objective(router, config, token_mask, input_ids, model))
if float(getattr(config, "lambda_iteration_cluster", 0.0) or 0.0) > 0.0:
iteration_probs = _recurrent_iteration_probs(model, config)
if iteration_probs is not None:
Expand Down
12 changes: 9 additions & 3 deletions chronos/model/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,12 @@ def read_checkpoint_config(checkpoint_path: str) -> tuple[dict, str | None]:
# Saved before the cluster-locality field existed: those weights were
# trained without the constraint (the field defaults on since 0.3.1).
cfg["lambda_cluster_locality"] = 0.0
if "cluster_locality_objective" not in cfg:
# Saved before 0.3.5: the cluster term was the attached mutual-information objective on the soft
# router mass. Continued training keeps it unless the caller overrides these fields.
cfg["cluster_locality_objective"] = "mutual_info"
cfg.setdefault("cluster_locality_mass", "soft")
cfg.setdefault("cluster_input_detach", False)
return cfg, path


Expand Down Expand Up @@ -402,7 +408,8 @@ def config_dict_for_checkpoint(

# How the weights were trained is a property of the checkpoint: a project
# config must not fill it in (0.0 would otherwise count as "missing").
trained_lambda = cfg.get("lambda_cluster_locality")
trained = {k: cfg[k] for k in ("lambda_cluster_locality", "cluster_input_detach", "cluster_locality_budget")
if cfg.get(k) is not None}
project_cfg, project_path = read_project_config(project_config_path)
if project_cfg:
for key, value in project_cfg.items():
Expand All @@ -411,8 +418,7 @@ def config_dict_for_checkpoint(
if key not in cfg or cfg.get(key) in (None, "", 0):
cfg[key] = value
sources.append(project_path or project_config_path or "chronos_config.json")
if trained_lambda is not None:
cfg["lambda_cluster_locality"] = trained_lambda
cfg.update(trained)

if overrides:
for key, value in overrides.items():
Expand Down
22 changes: 22 additions & 0 deletions chronos/model/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,28 @@ def __init__(self, **kwargs):
# document longer than the window is cut into window-sized parts).
# Neither consults labels or task tokens.
self.cluster_locality_mode: str = str(kwargs.pop("cluster_locality_mode", "window") or "window")
# Cluster objective (0.3.5; measured in experiments/cluster_15m, see docs/CLUSTER_LOCALITY.md section 9).
# "budget": each stream may spread over the ``cluster_locality_budget`` clusters it uses most and pays for the
# routing mass outside them, plus a balance term over clusters; its tokens keep the choice among every expert
# of those clusters. "mutual_info" (0.3.4 and earlier): 1 - I(stream; cluster) / log C, which also asks every
# stream for a single cluster. A config that predates these fields keeps the 0.3.4 objective (checkpoint.py).
self.cluster_locality_objective: str = str(kwargs.pop("cluster_locality_objective", "budget") or "budget")
if self.cluster_locality_objective not in ("budget", "mutual_info"):
raise ValueError("cluster_locality_objective must be 'budget' or 'mutual_info'")
# Clusters per stream under "budget"; 0 = half the clusters, rounded up (3 of 6, 2 of 4: the measured setting).
self.cluster_locality_budget: int = int(kwargs.pop("cluster_locality_budget", 0) or 0)
if self.cluster_locality_budget < 0:
raise ValueError("cluster_locality_budget must be >= 0 (0 = half the clusters)")
# Router mass the objective reads: "dispatch" = the top-k experts each token runs, renormalized; "soft" = the
# whole router softmax (0.3.4 and earlier).
self.cluster_locality_mass: str = str(kwargs.pop("cluster_locality_mass", "dispatch") or "dispatch")
if self.cluster_locality_mass not in ("dispatch", "soft"):
raise ValueError("cluster_locality_mass must be 'dispatch' or 'soft'")
# cluster_input_detach: the cluster term reads the gate applied to the detached hidden states, so it trains the
# gate weights only. Attached (0.3.4 and earlier) its gradient also reached the trunk, pulled the hidden states
# toward document identity and lowered the number of distinct experts a token used.
_detach = kwargs.pop("cluster_input_detach", None)
self.cluster_input_detach: bool = True if _detach is None else bool(_detach)
# Iteration-axis cluster locality (0 = off): weight on the total variation between the cluster
# distribution of each loop iteration of a token and the mean over its iterations, so every iteration
# of a recurrent layer reads the same expert clusters. Experts inside a cluster stay free to differ.
Expand Down
Loading
Loading