From 9511f1287d095bcaf35fd2fd813368333f57dd0c Mon Sep 17 00:00:00 2001 From: Fona <62028332+FonaTech@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:30:13 +0800 Subject: [PATCH] Release 0.3.5: budget cluster objective, dispatch mass, gate-only cluster gradient The 0.3.4 cluster-locality term (attached mutual-information objective on the soft router mass) confined each stream to one cluster and trained the trunk toward document identity; on the 15M shape it cost +0.290 CE at step 600 with 3.89 distinct experts per token against 7.45 at lambda 0. - cluster_locality_objective: "budget" (default) or "mutual_info" - cluster_locality_budget: clusters per stream, 0 = half, rounded up - cluster_locality_mass: "dispatch" (default) or "soft" - cluster_input_detach: gate-only cluster gradient (default on), Torch and MLX, read inside the compiled and recomputed MLX step - pre-0.3.5 checkpoints load with the old objective - config schema, training CLIs, WebUI fields and 4-language help - docs/CLUSTER_LOCALITY.md section 9; doc line anchors remapped - reports/cluster_budget_20261127/summary.json: measured numbers - tests/test_cluster_budget.py: 15 tests Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 45 + chronos/__init__.py | 2 +- chronos/config_schema.py | 1 + chronos/expert_clusters.py | 11 + chronos/mlx/moe.py | 19 + chronos/mlx/training/trainer.py | 72 +- chronos/model/checkpoint.py | 12 +- chronos/model/config.py | 22 + chronos/model/moe_chronos.py | 8 + chronos/model/temporal_loss.py | 26 +- chronos/trainer/loss_mixin.py | 29 +- chronos/trainer/stage_utils.py | 7 +- chronos/webui/i18n/en.json | 13 + chronos/webui/i18n/ja.json | 13 + chronos/webui/i18n/zh-Hans.json | 13 + chronos/webui/i18n/zh-Hant.json | 13 + chronos/webui/schema.py | 8 + docs/CLUSTER_LOCALITY.md | 101 +- docs/KERNEL_ARCHITECTURE.md | 4 +- docs/LAZY_EXPERTS.md | 2 +- docs/LONG_CONTEXT.md | 2 +- docs/LOOKAHEAD.md | 12 +- docs/MOE_ROUTING.md | 18 +- docs/RESIDENCY.md | 2 +- docs/THEORY.md | 8 +- pyproject.toml | 2 +- reports/cluster_budget_20261127/summary.json | 1371 ++++++++++++++++++ tests/test_cluster_budget.py | 255 ++++ 28 files changed, 2034 insertions(+), 57 deletions(-) create mode 100644 reports/cluster_budget_20261127/summary.json create mode 100644 tests/test_cluster_budget.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c0ca55..7e5f3f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/chronos/__init__.py b/chronos/__init__.py index 0cf71a6..f0356c9 100644 --- a/chronos/__init__.py +++ b/chronos/__init__.py @@ -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. diff --git a/chronos/config_schema.py b/chronos/config_schema.py index b97aa1b..4170fed 100644 --- a/chronos/config_schema.py +++ b/chronos/config_schema.py @@ -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", diff --git a/chronos/expert_clusters.py b/chronos/expert_clusters.py index 37b1e36..a035962 100644 --- a/chronos/expert_clusters.py +++ b/chronos/expert_clusters.py @@ -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))) diff --git a/chronos/mlx/moe.py b/chronos/mlx/moe.py index 0829a2e..2e74df1 100644 --- a/chronos/mlx/moe.py +++ b/chronos/mlx/moe.py @@ -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) @@ -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) @@ -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) diff --git a/chronos/mlx/training/trainer.py b/chronos/mlx/training/trainer.py index 6c2e4df..bc22f79 100644 --- a/chronos/mlx/training/trainer.py +++ b/chronos/mlx/training/trainer.py @@ -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 @@ -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) @@ -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``. @@ -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: @@ -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: diff --git a/chronos/model/checkpoint.py b/chronos/model/checkpoint.py index 4b3e22f..7f6fc57 100644 --- a/chronos/model/checkpoint.py +++ b/chronos/model/checkpoint.py @@ -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 @@ -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(): @@ -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(): diff --git a/chronos/model/config.py b/chronos/model/config.py index cf2e214..70f0556 100644 --- a/chronos/model/config.py +++ b/chronos/model/config.py @@ -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. diff --git a/chronos/model/moe_chronos.py b/chronos/model/moe_chronos.py index fe3862d..538521d 100644 --- a/chronos/model/moe_chronos.py +++ b/chronos/model/moe_chronos.py @@ -87,6 +87,10 @@ def __init__(self, config: ChronosConfig): # load-balance term must cover all of them (reset per model forward). self.iteration_router_probs: list[torch.Tensor] = [] self.iteration_router_probs_grad: list[torch.Tensor] = [] + # cluster_input_detach: the gate applied to x.detach(), recorded per training dispatch. Only the cluster term + # reads it, so that term trains the gate weights and never the hidden states (MLX twin: iteration_cluster_probs). + self.cluster_input_detach = bool(getattr(config, "cluster_input_detach", False)) + self.iteration_cluster_probs_grad: list[torch.Tensor] = [] self._iteration_aux_raw: list[torch.Tensor] = [] # router_scope="shared": iterations after the first reuse the first # iteration's expert ids (weights are re-gathered from the current @@ -103,6 +107,7 @@ def __init__(self, config: ChronosConfig): self.last_fallback_weight_mass = 0.0 def reset_iteration_routing(self) -> None: + self.iteration_cluster_probs_grad = [] self.iteration_router_probs = [] self.iteration_router_probs_grad = [] self._iteration_aux_raw = [] @@ -151,6 +156,9 @@ def forward( self.last_router_probs = scores_bse.detach() self.iteration_router_probs.append(self.last_router_probs) self.iteration_router_probs_grad.append(scores_bse) + if self.cluster_input_detach and self.training: + self.iteration_cluster_probs_grad.append( + F.softmax(self.gate(x_flat.detach()).float(), dim=-1).view(B, S, self.num_experts)) # Graded top-k: a later loop iteration may route to fewer experts (top_k < num_experts_per_tok). k = self.num_experts_per_tok if not top_k else max(1, min(int(top_k), self.num_experts_per_tok)) diff --git a/chronos/model/temporal_loss.py b/chronos/model/temporal_loss.py index cab49b0..b16cf97 100644 --- a/chronos/model/temporal_loss.py +++ b/chronos/model/temporal_loss.py @@ -84,10 +84,30 @@ def _entropy(p: torch.Tensor) -> torch.Tensor: return -(p * p.log()).sum(dim=-1) +def cluster_spill(p: torch.Tensor, budget: int) -> torch.Tensor: + """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. MLX twin: ``chronos.mlx.training.trainer._cluster_spill``.""" + if budget >= int(p.shape[-1]): + return p.new_zeros(p.shape[:-1]) + outside = torch.ones_like(p).scatter(-1, p.detach().topk(budget, dim=-1).indices, 0.0) + return (p * outside).sum(dim=-1) + + +def dispatch_mass(router_4d: torch.Tensor, top_k: int) -> torch.Tensor: + """Router probabilities kept on each dispatch's top-k experts and renormalized; the gradient reaches those k + entries. MLX twin: ``chronos.mlx.training.trainer._dispatch_mass``.""" + k = max(1, min(int(top_k or 1), int(router_4d.shape[-1]))) + idx = router_4d.detach().topk(k, dim=-1).indices + sel = router_4d * torch.zeros_like(router_4d).scatter(-1, idx, 1.0) + return sel / sel.sum(dim=-1, keepdim=True).clamp_min(1e-9) + + def cluster_locality_loss( router_4d: torch.Tensor, membership: torch.Tensor, window: int = 0, + budget: int = 0, ) -> torch.Tensor: """Cluster-locality constraint over a stream and its recurrent iterations. @@ -112,12 +132,14 @@ def cluster_locality_loss( if pw is None: return router_4d.new_zeros(()) log_c = math.log(int(membership.shape[1])) + if budget > 0: # budget objective: balance over clusters + mass outside each window's top clusters + return 1.0 - _entropy(pw.mean(dim=0)) / log_c + cluster_spill(pw, budget).mean() mutual = _entropy(pw.mean(dim=0)) - _entropy(pw).mean() return 1.0 - mutual / log_c def segment_cluster_loss(router_4d: torch.Tensor, membership: torch.Tensor, segments, - token_mask: torch.Tensor | None = None) -> torch.Tensor: + token_mask: torch.Tensor | None = None, budget: int = 0) -> torch.Tensor: """``1 − I(segment; cluster)/log C`` with the batch's documents as streams. ``segments`` ``[B, S]`` is ``chronos.expert_clusters.segment_ids(input_ids, @@ -148,6 +170,8 @@ def segment_cluster_loss(router_4d: torch.Tensor, membership: torch.Tensor, segm ps = total / count.clamp_min(1.0)[:, None] weight = count / count.sum().clamp_min(1.0) marginal = (ps * weight[:, None]).sum(dim=0) + if budget > 0: # budget objective (see cluster_locality_loss) + return 1.0 - _entropy(marginal) / math.log(C) + (cluster_spill(ps, budget) * weight).sum() mutual = _entropy(marginal) - (_entropy(ps) * weight).sum() return 1.0 - mutual / math.log(C) diff --git a/chronos/trainer/loss_mixin.py b/chronos/trainer/loss_mixin.py index 8e7b553..418405e 100644 --- a/chronos/trainer/loss_mixin.py +++ b/chronos/trainer/loss_mixin.py @@ -28,6 +28,7 @@ from chronos.model.moe_chronos import ChronosMOEFeedForward from chronos.model.temporal_loss import ( cluster_locality_loss, + dispatch_mass, iteration_cluster_spread, temporal_locality_loss, lookahead_supervision_loss, @@ -98,6 +99,26 @@ def collect_iteration_router_probs(model, *, with_grad: bool = False) -> Optiona return torch.stack(probs, dim=2) +def cluster_source_probs(model, config, router_4d: torch.Tensor) -> torch.Tensor: + """The ``[B, S, V, E]`` probabilities the cluster term reads (MLX twin: ``_cluster_objective``). With + ``cluster_input_detach`` they are the gate applied to ``x.detach()`` (the term trains the gate weights only); + ``cluster_locality_mass="dispatch"`` keeps each dispatch's top-k experts, renormalized.""" + source = router_4d + if bool(getattr(config, "cluster_input_detach", False)): + probs: List[torch.Tensor] = [] + for layer in model.model.layers: + mlp = getattr(layer, "mlp", None) + if isinstance(mlp, ChronosMOEFeedForward): + probs.extend(getattr(mlp, "iteration_cluster_probs_grad", None) or []) + if probs: + stacked = torch.stack(probs, dim=2) + if stacked.shape == router_4d.shape: + source = stacked + if str(getattr(config, "cluster_locality_mass", "soft") or "soft") == "dispatch": + source = dispatch_mass(source.float(), int(getattr(config, "num_experts_per_tok", 1) or 1)) + return source + + def first_iteration_router_probs(model) -> Optional[torch.Tensor]: """Step-0 routing per physical layer (lookahead teacher; prefetch key).""" probs = [] @@ -210,15 +231,17 @@ def chronos_loss_term( ) lambda_cluster = float(getattr(config, "lambda_cluster_locality", 0.0) or 0.0) if lambda_cluster > 0.0: - from chronos.expert_clusters import cluster_locality_mode, segment_ids + from chronos.expert_clusters import cluster_budget, cluster_locality_mode, segment_ids membership = cluster_membership_tensor(config, router_4d.device) window = int(getattr(config, "cluster_locality_window", 0) or 0) + source = cluster_source_probs(model, config, router_4d) + budget = cluster_budget(config) if cluster_locality_mode(config) == "segment" and input_ids is not None: ids = input_ids.detach().cpu().numpy() mask = None if labels is None else real_token_mask_torch(labels) - cluster_term = segment_cluster_loss(router_4d, membership, segment_ids(ids, window), mask) + cluster_term = segment_cluster_loss(source, membership, segment_ids(ids, window), mask, budget=budget) else: - cluster_term = cluster_locality_loss(router_4d, membership, window) + cluster_term = cluster_locality_loss(source, membership, window, budget=budget) loss = loss + lambda_cluster * cluster_term lambda_iteration = float(getattr(config, "lambda_iteration_cluster", 0.0) or 0.0) diff --git a/chronos/trainer/stage_utils.py b/chronos/trainer/stage_utils.py index 2ca6551..8eec901 100644 --- a/chronos/trainer/stage_utils.py +++ b/chronos/trainer/stage_utils.py @@ -109,11 +109,16 @@ def add_topology_args(parser, *, defaults: bool = False): "recurrent_dt_init": (float, .25), "recurrent_dt_min": (float, .05), "recurrent_dt_max": (float, 1.), + # Cluster objective (0.3.5): see ChronosConfig and docs/CLUSTER_LOCALITY.md section 9. + "cluster_locality_objective": (str, "budget"), + "cluster_locality_budget": (int, 0), + "cluster_locality_mass": (str, "dispatch"), } for name, (kind, value) in fields.items(): parser.add_argument("--"+name, type=kind, default=value if defaults else None) for name, value in (("recurrent_enabled", True), ("layer_aware_lookahead", True), - ("layer_aware_cache", True), ("activation_checkpointing", False)): + ("layer_aware_cache", True), ("activation_checkpointing", False), + ("cluster_input_detach", True)): parser.add_argument("--"+name, action=argparse.BooleanOptionalAction, default=value if defaults else None) diff --git a/chronos/webui/i18n/en.json b/chronos/webui/i18n/en.json index 7b1d325..d769fe4 100644 --- a/chronos/webui/i18n/en.json +++ b/chronos/webui/i18n/en.json @@ -24,10 +24,12 @@ "choice.auto": "Auto", "choice.balanced": "Balanced", "choice.block": "Whole block", + "choice.budget": "Cluster budget", "choice.cluster": "By cluster", "choice.cluster_locality_mode.segment": "Documents (segment)", "choice.cluster_locality_mode.window": "Fixed windows (window)", "choice.compare": "Compare lazy vs full", + "choice.dispatch": "Dispatched experts", "choice.expanded": "Expanded (reference)", "choice.expert": "By expert", "choice.experts": "Active experts", @@ -41,6 +43,7 @@ "choice.lookahead_teacher_scope.iterations": "All iterations averaged", "choice.mla": "Global (MLA) blocks", "choice.mlp": "MoE/FFN only", + "choice.mutual_info": "Mutual information", "choice.none": "None", "choice.offload": "Lazy experts only", "choice.on_demand": "Load, may skip late experts (on_demand)", @@ -58,6 +61,7 @@ "choice.scheduled": "Scheduled", "choice.segment": "By document", "choice.shared": "Shared", + "choice.soft": "Full softmax", "choice.swa": "Sliding-window blocks", "choice.sync_on_demand": "Load and wait (sync_on_demand)", "choice.true": "On", @@ -158,10 +162,18 @@ "field.beta.label": "β (DPO/GRPO)", "field.ce_chunk_size.help": "Compute the language-model loss in row chunks from the last hidden state, so the [batch, length, vocabulary] logits never exist. 0 = full logits. Exact.", "field.ce_chunk_size.label": "Loss chunk size", + "field.cluster_input_detach.help": "On: the cluster term reads the gate applied to a gradient-free copy of the hidden state, so it trains only the router weights and does not pull the hidden states toward document identity. Off: the 0.3.4 behaviour, where its gradient also reaches the hidden states.", + "field.cluster_input_detach.label": "Gate-only cluster gradient", + "field.cluster_locality_budget.help": "B, the number of clusters one stream may use under the budget objective. 0 = half the clusters, rounded up; values above the cluster count are capped at it.", + "field.cluster_locality_budget.label": "Clusters per stream", "field.cluster_locality_clusters.help": "Number of expert clusters for the locality term. 0 chooses it from the expert count.", "field.cluster_locality_clusters.label": "Clusters", + "field.cluster_locality_mass.help": "Which router probabilities the cluster term counts. dispatch: each token's top-k dispatched experts only, renormalized, so the term sees the experts that actually run. soft: the full softmax over all experts (the 0.3.4 behaviour).", + "field.cluster_locality_mass.label": "Cluster mass", "field.cluster_locality_mode.help": "What one stream is for the cluster constraint. window: fixed windows of the length above. segment: each document of the batch (split at the data's own separators, long ones cut to the window), so similar documents learn to share a cluster without labels or task tags.", "field.cluster_locality_mode.label": "Locality unit", + "field.cluster_locality_objective.help": "How the cluster term scores a stream. budget (default since 0.3.5): use all clusters evenly overall, and keep each stream inside its B heaviest clusters while the split among those B stays free. mutual_info: the 0.3.1–0.3.4 objective, which pushes each stream into a single cluster; in the 0.3.5 experiments it lowered the number of distinct experts per token and raised the loss. Checkpoints saved before 0.3.5 keep mutual_info.", + "field.cluster_locality_objective.label": "Cluster objective", "field.cluster_locality_window.help": "Segment length (tokens) the cluster constraint applies to. Best results matched the typical record length.", "field.cluster_locality_window.label": "Locality window", "field.coda_layers.help": "Layers that run once after the loop, before the output head.", @@ -788,6 +800,7 @@ "probe.variant": "Variant", "probe.vs_full": "Speed vs full memory", "probe.wait": "Prefetch wait (s)", + "rule.cluster_budget_auto": "0 = half the clusters, rounded up", "rule.clusters_auto": "0 = derived from the expert count", "rule.equals_recurrent_depth": "equal to the training depth", "rule.loopback": "127.0.0.1 (this machine only)", diff --git a/chronos/webui/i18n/ja.json b/chronos/webui/i18n/ja.json index 871e8ed..66a9301 100644 --- a/chronos/webui/i18n/ja.json +++ b/chronos/webui/i18n/ja.json @@ -24,10 +24,12 @@ "choice.auto": "自動", "choice.balanced": "バランス", "choice.block": "ブロック全体", + "choice.budget": "クラスタ予算", "choice.cluster": "クラスタ単位", "choice.cluster_locality_mode.segment": "文書単位(segment)", "choice.cluster_locality_mode.window": "固定ウィンドウ(window)", "choice.compare": "遅延ロードと全メモリを比較", + "choice.dispatch": "実際に割り当てたエキスパート", "choice.expanded": "展開(参照)", "choice.expert": "エキスパート単位", "choice.experts": "アクティブエキスパート数", @@ -41,6 +43,7 @@ "choice.lookahead_teacher_scope.iterations": "全反復の平均", "choice.mla": "グローバル(MLA)ブロック", "choice.mlp": "MoE/FFN のみ", + "choice.mutual_info": "相互情報量", "choice.none": "なし", "choice.offload": "遅延エキスパートのみ", "choice.on_demand": "読み込み、遅延したエキスパートは省略(on_demand)", @@ -58,6 +61,7 @@ "choice.scheduled": "スケジュール", "choice.segment": "文書単位", "choice.shared": "共有", + "choice.soft": "全体の softmax", "choice.swa": "スライディングウィンドウブロック", "choice.sync_on_demand": "読み込んで待機(sync_on_demand)", "choice.true": "オン", @@ -158,10 +162,18 @@ "field.beta.label": "β(DPO/GRPO)", "field.ce_chunk_size.help": "最後の隠れ状態から行チャンクごとに言語モデルの損失を計算し、[バッチ, 長さ, 語彙] の logits を作りません。0 で全 logits。結果は厳密です。", "field.ce_chunk_size.label": "損失のチャンクサイズ", + "field.cluster_input_detach.help": "オン: クラスタ項は勾配を持たない隠れ状態のコピーにゲートを適用した出力を読み、ルーターの重みだけを学習します。隠れ状態を文書の識別へ引き寄せません。オフ: 0.3.4 の動作で、勾配は隠れ状態にも届きます。", + "field.cluster_input_detach.label": "クラスタ勾配はゲートのみ", + "field.cluster_locality_budget.help": "budget 目的関数で一続きの入力が使えるクラスタ数 B。0 はクラスタ数の半分(切り上げ)。クラスタ数を超える値はクラスタ数に切り詰めます。", + "field.cluster_locality_budget.label": "入力あたりのクラスタ数", "field.cluster_locality_clusters.help": "局所性項で使うエキスパートクラスタの数。0 ならエキスパート数から決めます。", "field.cluster_locality_clusters.label": "クラスタ数", + "field.cluster_locality_mass.help": "クラスタ項が数えるルーター確率。dispatch: 各トークンが実際に割り当てた top-k エキスパートだけを再正規化して使い、実際に動くエキスパートを見ます。soft: 全エキスパートの softmax(0.3.4 の動作)。", + "field.cluster_locality_mass.label": "クラスタ質量の取り方", "field.cluster_locality_mode.help": "クラスタ制約で一続きの入力とみなす単位。window: 上の長さの固定ウィンドウ。segment: バッチ内の各文書(データ自身の区切りで分割し、長い文書はウィンドウ長で再分割)。ラベルやタスクタグなしで、似た文書が同じクラスタを使うよう自発的に学習します。", "field.cluster_locality_mode.label": "局所性の単位", + "field.cluster_locality_objective.help": "クラスタ項が一続きの入力をどう評価するか。budget(0.3.5 からの既定): 全体ではすべてのクラスタを均等に使い、各入力は重い上位 B 個のクラスタ内にとどめます。B 個の間の配分は自由です。mutual_info: 0.3.1–0.3.4 の目的関数で、各入力を 1 つのクラスタへ押し込みます。0.3.5 の実験では、トークンあたりの異なるエキスパート数が減り、損失が上がりました。0.3.5 より前に保存したチェックポイントは mutual_info のままです。", + "field.cluster_locality_objective.label": "クラスタ目的関数", "field.cluster_locality_window.help": "クラスタ制約をかける区間の長さ(トークン)。典型的なレコード長に合わせたときに最良の結果が出ました。", "field.cluster_locality_window.label": "局所性ウィンドウ", "field.coda_layers.help": "ループの後、出力ヘッドの前に 1 回だけ実行する層。", @@ -788,6 +800,7 @@ "probe.variant": "組み合わせ", "probe.vs_full": "全メモリ比の速度", "probe.wait": "プリフェッチ待ち(秒)", + "rule.cluster_budget_auto": "0 = クラスタ数の半分(切り上げ)", "rule.clusters_auto": "0 = エキスパート数から決定", "rule.equals_recurrent_depth": "学習時の深さと同じ", "rule.loopback": "127.0.0.1(このマシンのみ)", diff --git a/chronos/webui/i18n/zh-Hans.json b/chronos/webui/i18n/zh-Hans.json index 2cb5b8e..5b2b493 100644 --- a/chronos/webui/i18n/zh-Hans.json +++ b/chronos/webui/i18n/zh-Hans.json @@ -24,10 +24,12 @@ "choice.auto": "自动", "choice.balanced": "均衡", "choice.block": "整个块", + "choice.budget": "簇预算", "choice.cluster": "按簇", "choice.cluster_locality_mode.segment": "按文档(segment)", "choice.cluster_locality_mode.window": "固定窗口(window)", "choice.compare": "懒加载与全内存对比", + "choice.dispatch": "实际分派的专家", "choice.expanded": "展开(参考)", "choice.expert": "按专家", "choice.experts": "激活专家数", @@ -41,6 +43,7 @@ "choice.lookahead_teacher_scope.iterations": "所有迭代取平均", "choice.mla": "全局(MLA)块", "choice.mlp": "仅 MoE/FFN", + "choice.mutual_info": "互信息", "choice.none": "无", "choice.offload": "仅懒加载专家", "choice.on_demand": "按需加载,可跳过迟到专家(on_demand)", @@ -58,6 +61,7 @@ "choice.scheduled": "按调度", "choice.segment": "按文档", "choice.shared": "共享", + "choice.soft": "完整 softmax", "choice.swa": "滑动窗口块", "choice.sync_on_demand": "同步按需加载(sync_on_demand)", "choice.true": "开", @@ -158,10 +162,18 @@ "field.beta.label": "β(DPO/GRPO)", "field.ce_chunk_size.help": "按行分块、从最后的隐状态计算语言模型损失,不再生成 [批, 长度, 词表] 的 logits。0 表示完整 logits。结果精确。", "field.ce_chunk_size.label": "损失分块大小", + "field.cluster_input_detach.help": "开启:簇约束读取门控作用在不带梯度的隐状态副本上的输出,只训练路由权重,不会把隐状态拉向文档身份。关闭:0.3.4 的行为,梯度也会传到隐状态。", + "field.cluster_input_detach.label": "簇梯度只训练门控", + "field.cluster_locality_budget.help": "预算目标下一段输入可使用的簇数 B。0 表示簇数的一半(向上取整);超过簇数时按簇数计。", + "field.cluster_locality_budget.label": "每段可用簇数", "field.cluster_locality_clusters.help": "局部性约束使用的专家簇数。0 表示按专家数自动选择。", "field.cluster_locality_clusters.label": "簇数", + "field.cluster_locality_mass.help": "簇约束统计哪些路由概率。dispatch:只取每个 token 实际分派的 top-k 专家并重新归一化,即真正运行的专家。soft:全部专家上的完整 softmax(0.3.4 的行为)。", + "field.cluster_locality_mass.label": "簇质量来源", "field.cluster_locality_mode.help": "簇约束以什么作为一段连续输入。window:按上面的长度切固定窗口。segment:批次中的每篇文档(按数据自身的分隔符切分,过长的按窗口再切),相似文档会自发学到同一个簇,不依赖标签或任务标记。", "field.cluster_locality_mode.label": "局部性单元", + "field.cluster_locality_objective.help": "簇约束如何给一段输入打分。budget(0.3.5 起默认):整体上均匀使用所有簇,并把每段输入限制在它最重的 B 个簇内,这 B 个簇之间的分配不受约束。mutual_info:0.3.1–0.3.4 的目标,把每段输入推向单个簇;在 0.3.5 的实验中它减少了每个 token 用到的不同专家数,并抬高了损失。0.3.5 之前保存的检查点继续使用 mutual_info。", + "field.cluster_locality_objective.label": "簇目标", "field.cluster_locality_window.help": "簇约束作用的片段长度(token)。与典型记录长度一致时效果最好。", "field.cluster_locality_window.label": "局部性窗口", "field.coda_layers.help": "循环之后、输出头之前只运行一次的层。", @@ -788,6 +800,7 @@ "probe.variant": "组合", "probe.vs_full": "相对全内存速度", "probe.wait": "预取等待(秒)", + "rule.cluster_budget_auto": "0 = 簇数的一半,向上取整", "rule.clusters_auto": "0 = 按专家数推导", "rule.equals_recurrent_depth": "等于训练深度", "rule.loopback": "127.0.0.1(仅本机)", diff --git a/chronos/webui/i18n/zh-Hant.json b/chronos/webui/i18n/zh-Hant.json index 6b842fb..0f7b7a3 100644 --- a/chronos/webui/i18n/zh-Hant.json +++ b/chronos/webui/i18n/zh-Hant.json @@ -24,10 +24,12 @@ "choice.auto": "自動", "choice.balanced": "平衡", "choice.block": "整個區塊", + "choice.budget": "叢集預算", "choice.cluster": "按叢集", "choice.cluster_locality_mode.segment": "按文件(segment)", "choice.cluster_locality_mode.window": "固定窗口(window)", "choice.compare": "延遲載入與全記憶體比較", + "choice.dispatch": "實際分派的專家", "choice.expanded": "展開(參考)", "choice.expert": "按專家", "choice.experts": "啟用專家數", @@ -41,6 +43,7 @@ "choice.lookahead_teacher_scope.iterations": "所有迭代取平均", "choice.mla": "全域(MLA)區塊", "choice.mlp": "僅 MoE/FFN", + "choice.mutual_info": "互資訊", "choice.none": "無", "choice.offload": "僅延遲載入專家", "choice.on_demand": "按需載入,可略過遲到專家(on_demand)", @@ -58,6 +61,7 @@ "choice.scheduled": "依排程", "choice.segment": "按文件", "choice.shared": "共用", + "choice.soft": "完整 softmax", "choice.swa": "滑動視窗區塊", "choice.sync_on_demand": "同步按需載入(sync_on_demand)", "choice.true": "開", @@ -158,10 +162,18 @@ "field.beta.label": "β(DPO/GRPO)", "field.ce_chunk_size.help": "按列分塊、從最後的隱狀態計算語言模型損失,不再產生 [批, 長度, 詞表] 的 logits。0 表示完整 logits。結果精確。", "field.ce_chunk_size.label": "損失分塊大小", + "field.cluster_input_detach.help": "開啟:叢集約束讀取門控作用在不帶梯度的隱狀態副本上的輸出,只訓練路由權重,不會把隱狀態拉向文件身分。關閉:0.3.4 的行為,梯度也會傳到隱狀態。", + "field.cluster_input_detach.label": "叢集梯度只訓練門控", + "field.cluster_locality_budget.help": "預算目標下一段輸入可使用的叢集數 B。0 表示叢集數的一半(無條件進位);超過叢集數時按叢集數計。", + "field.cluster_locality_budget.label": "每段可用叢集數", "field.cluster_locality_clusters.help": "區域性約束使用的專家叢集數。0 表示按專家數自動選擇。", "field.cluster_locality_clusters.label": "叢集數", + "field.cluster_locality_mass.help": "叢集約束統計哪些路由機率。dispatch:只取每個 token 實際分派的 top-k 專家並重新正規化,即真正執行的專家。soft:全部專家上的完整 softmax(0.3.4 的行為)。", + "field.cluster_locality_mass.label": "叢集質量來源", "field.cluster_locality_mode.help": "簇約束以什麼作為一段連續輸入。window:按上面的長度切固定窗口。segment:批次中的每篇文件(按資料自身的分隔符切分,過長的按窗口再切),相似文件會自發學到同一個簇,不依賴標籤或任務標記。", "field.cluster_locality_mode.label": "局部性單元", + "field.cluster_locality_objective.help": "叢集約束如何給一段輸入評分。budget(0.3.5 起預設):整體上均勻使用所有叢集,並把每段輸入限制在它最重的 B 個叢集內,這 B 個叢集之間的分配不受約束。mutual_info:0.3.1–0.3.4 的目標,把每段輸入推向單一叢集;在 0.3.5 的實驗中它減少了每個 token 用到的不同專家數,並抬高了損失。0.3.5 之前儲存的檢查點繼續使用 mutual_info。", + "field.cluster_locality_objective.label": "叢集目標", "field.cluster_locality_window.help": "叢集約束作用的片段長度(token)。與典型記錄長度一致時效果最好。", "field.cluster_locality_window.label": "區域性視窗", "field.coda_layers.help": "循環之後、輸出頭之前只執行一次的層。", @@ -788,6 +800,7 @@ "probe.variant": "組合", "probe.vs_full": "相對全記憶體速度", "probe.wait": "預先擷取等待(秒)", + "rule.cluster_budget_auto": "0 = 叢集數的一半,無條件進位", "rule.clusters_auto": "0 = 依專家數推導", "rule.equals_recurrent_depth": "等於訓練深度", "rule.loopback": "127.0.0.1(僅本機)", diff --git a/chronos/webui/schema.py b/chronos/webui/schema.py index 1e3e7d5..30dae4e 100644 --- a/chronos/webui/schema.py +++ b/chronos/webui/schema.py @@ -154,6 +154,14 @@ def _f(key, group, type_, default=None, **kw) -> Field: recommended="data", source="rule", ref="window_median_record"), _f("cluster_locality_mode", "objectives", "choice", "window", choices=["window", "segment"], source="code", advanced=True), + _f("cluster_locality_objective", "objectives", "choice", "budget", choices=["budget", "mutual_info"], + recommended="budget", source="measured", ref="docs/CLUSTER_LOCALITY.md", advanced=True), + _f("cluster_locality_budget", "objectives", "int", 0, min=0, max=1024, step=1, + recommended=0, source="rule", ref="cluster_budget_auto", advanced=True), + _f("cluster_locality_mass", "objectives", "choice", "dispatch", choices=["dispatch", "soft"], + recommended="dispatch", source="measured", ref="docs/CLUSTER_LOCALITY.md", advanced=True), + _f("cluster_input_detach", "objectives", "bool", True, recommended=True, source="measured", + ref="docs/CLUSTER_LOCALITY.md", advanced=True), _f("lambda_iteration_cluster", "objectives", "float", 0.0, min=0.0, max=10.0, step=0.01, recommended=0.0, source="planner", advanced=True), _f("lookahead_teacher_scope", "objectives", "choice", "first", choices=["first", "iterations"], diff --git a/docs/CLUSTER_LOCALITY.md b/docs/CLUSTER_LOCALITY.md index 6ff5b5b..baf04bf 100644 --- a/docs/CLUSTER_LOCALITY.md +++ b/docs/CLUSTER_LOCALITY.md @@ -33,14 +33,14 @@ There is no implemented `clusters.partition_json` training field in this snapsho Every physical MoE layer has its own expert weights. Applying the same expert-ID partition across layers does not tie those weights. It aligns group labels used by the objective and by packed storage. -The trainer supplies raw soft router probabilities +The trainer supplies router probabilities $$ Q\in\mathbb R^{B\times T\times V\times E},\qquad \sum_eQ_{b,t,v,e}=1, $$ -where $V$ indexes the collected dispatches, including repeated calls of recurrent layers. These are **pre-top-k softmax probabilities**, not only the selected or renormalized expert gates. [Collection and loss assembly](../chronos/trainer/loss_mixin.py#L197). +where $V$ indexes the collected dispatches, including repeated calls of recurrent layers. Since 0.3.5 the default $Q$ is the **dispatch mass**: each dispatch keeps its $k$ selected experts, renormalized, and the probabilities come from the gate applied to a gradient-free copy of the MoE input (section 9). With `cluster_locality_mass="soft"` and `cluster_input_detach=False`, $Q$ is the full pre-top-k softmax of the live router, which every release before 0.3.5 used. [Collection and loss assembly](../chronos/trainer/loss_mixin.py#L218), [source selection](../chronos/trainer/loss_mixin.py#L102). For an equal-length window $w$ with $n_w$ tokens, @@ -58,8 +58,8 @@ flowchart TB Q["Soft router probabilities: B ×
T × V × E"] --> Pool["Pool tokens and dispatches"] M --> Pool Pool --> PW["One cluster distribution per
stream window"] - PW --> MI["Mutual-information locality
objective"] - MI -. "Gradient updates routing and
upstream representations" .-> Q + PW --> MI["Budget objective (default)
or mutual information"] + MI -. "Gradient updates the gate weights;
attached mode also upstream representations" .-> Q ``` *Training objects. Cluster boundaries remain fixed. The learned probabilities change; the arrows do not depict expert migration.* @@ -102,7 +102,9 @@ This last decomposition explains the two pressures: A single global popular cluster does not solve the objective: both entropies then vanish and $L_{\mathrm{cl}}=1$. Conversely, $L_{\mathrm{cl}}=0$ requires deterministic per-window assignments **and a uniform cluster marginal**. Deterministic assignments alone do not suffice. Finite-batch composition may make this ideal unattainable. -[Exact Torch loss](../chronos/model/temporal_loss.py#L87), [MLX counterpart](../chronos/mlx/training/trainer.py#L243). +[Exact Torch loss](../chronos/model/temporal_loss.py#L106), [MLX counterpart](../chronos/mlx/training/trainer.py#L277). + +Since 0.3.5 this objective is selected with `cluster_locality_objective="mutual_info"`. The default is the budget objective of section 9, because the mutual-information optimum confines each stream to one cluster and, in the 0.3.5 experiments, that confinement cost language-model loss. ```mermaid flowchart TD @@ -134,7 +136,7 @@ The distinction between a zero loss and a constant loss of one matters when logg ## 3. Segment mode and valid-token weighting -The real field is `cluster_locality_mode="segment"`, not `segment_mode=True`. Segment IDs come from token-stream separators through `segment_ids(input_ids, chunk=window)`. Longer documents are divided into bounded parts. The code does not obtain those IDs from the attention-mask tensor. `document_masking` controls attention and is a different mechanism. [Segment construction](../chronos/expert_clusters.py#L185). +The real field is `cluster_locality_mode="segment"`, not `segment_mode=True`. Segment IDs come from token-stream separators through `segment_ids(input_ids, chunk=window)`. Longer documents are divided into bounded parts. The code does not obtain those IDs from the attention-mask tensor. `document_masking` controls attention and is a different mechanism. [Segment construction](../chronos/expert_clusters.py#L196). For a segment $w$ containing $n_w$ valid tokens, masked pooling is @@ -144,9 +146,9 @@ $$ \alpha_w=\frac{\sum_{t\in w}m_t}{\sum_{w'}\sum_{t\in w'}m_t}. $$ -The objective therefore weights segments by valid-token count. Changing from fixed windows to documents changes both the statistical unit and potentially its empirical weighting; it is not merely a renamed boundary list. Padding must not become an artificial “topic.” [Segment objective](../chronos/model/temporal_loss.py#L119). +The objective therefore weights segments by valid-token count. Changing from fixed windows to documents changes both the statistical unit and potentially its empirical weighting; it is not merely a renamed boundary list. Padding must not become an artificial “topic.” [Segment objective](../chronos/model/temporal_loss.py#L141). -There is a backend boundary worth retaining in the documentation. MLX's fixed-window helper accepts a valid-token mask and weights windows accordingly. The Torch fixed-window helper in this snapshot does not accept that mask, whereas the Torch segment helper does. Do not claim fully identical masking behavior for every loss mode. [MLX mask path](../chronos/mlx/training/trainer.py#L269), [Torch calls](../chronos/trainer/loss_mixin.py#L211). +There is a backend boundary worth retaining in the documentation. MLX's fixed-window helper accepts a valid-token mask and weights windows accordingly. The Torch fixed-window helper in this snapshot does not accept that mask, whereas the Torch segment helper does. Do not claim fully identical masking behavior for every loss mode. [MLX mask path](../chronos/mlx/training/trainer.py#L306), [Torch calls](../chronos/trainer/loss_mixin.py#L232). ```mermaid flowchart TB @@ -178,9 +180,9 @@ $$ \left[\frac12\sum_c|q_{b,t,g,r,c}-\bar q_{b,t,g,c}|\right], $$ -with a valid-token-weighted mean when a mask is supplied. This is **not** a fixed teacher at iteration zero. It permits different expert IDs inside the same cluster. [Iteration term](../chronos/model/temporal_loss.py#L450). +with a valid-token-weighted mean when a mask is supplied. This is **not** a fixed teacher at iteration zero. It permits different expert IDs inside the same cluster. [Iteration term](../chronos/model/temporal_loss.py#L474). -This term contributes only when the required iteration tensor is available. The Torch collector requires at least two calls and the same recorded call count for every recurrent layer. Prefix-block skipping can invalidate that shape condition; an enabled coefficient does not by itself guarantee a nonzero computed term. [Collector contract](../chronos/trainer/loss_mixin.py#L111). +This term contributes only when the required iteration tensor is available. The Torch collector requires at least two calls and the same recorded call count for every recurrent layer. Prefix-block skipping can invalidate that shape condition; an enabled coefficient does not by itself guarantee a nonzero computed term. [Collector contract](../chronos/trainer/loss_mixin.py#L132). ## 5. What the recorded synthetic sweep establishes @@ -234,7 +236,7 @@ Storage benefits remain backend-specific. Torch selects requested and budgeted n Under a fixed partition, an expert community means a routing association with an existing set of IDs. Topic purity in the synthetic benchmark measures association with known synthetic topics; it is not a measured geometric separation of expert weight vectors or a proof that natural-language domains emerge identically. -Expert parameters continue to learn through the language-model task and other available gradients. The fixed objects are their IDs and this membership map, not frozen expert weights. Locality can also influence upstream representations that produce router inputs. No physical motion or autonomous creation of experts is implemented. +Expert parameters continue to learn through the language-model task and other available gradients. The fixed objects are their IDs and this membership map, not frozen expert weights. With `cluster_input_detach=False`, locality can also influence upstream representations that produce router inputs. The 0.3.5 default sends this term's gradient to the gate weights only (section 9). No physical motion or autonomous creation of experts is implemented. Further, balanced expert use and balanced cluster use are not identical objectives. Near-equal partitions can contain different numbers of experts; a uniform expert marginal then induces cluster mass proportional to group size, whereas the mutual-information normalization favors a uniform cluster marginal at its ideal maximum. This interaction is worth checking when choosing a non-divisible partition. @@ -248,10 +250,81 @@ The next decisive evidence would connect these stages on the **same checkpoint a | `cluster_locality_clusters` | `0` | Zero chooses $\lceil E/(2k)\rceil$ | | `cluster_locality_window` | `32` | Window length; zero means a whole row | | `cluster_locality_mode` | `"window"` | `"window"` or `"segment"` | +| `cluster_locality_objective` | `"budget"` | `"budget"` (section 9) or `"mutual_info"` (section 2); checkpoints saved before 0.3.5 load as `"mutual_info"` | +| `cluster_locality_budget` | `0` | Clusters per stream $B$ under the budget objective; zero chooses $\lceil N_c/2\rceil$ | +| `cluster_locality_mass` | `"dispatch"` | `"dispatch"`: top-k mass, renormalized; `"soft"`: full softmax | +| `cluster_input_detach` | `True` | The cluster term reads the gate on a gradient-free input and trains the gate weights only | | `lambda_iteration_cluster` | `0.0` | Optional iteration spread | -[Configuration](../chronos/model/config.py#L279). The planner can select `DEFAULT_LAMBDA=0.3` for eligible MoE training plans, while old checkpoints retain their stored recipe. Thus “class default zero” is not equivalent to “all new training recipes disable locality.” [Planner choice](../chronos/model/planner.py#L566), [shared training helper](../chronos/expert_clusters.py#L142). +[Configuration](../chronos/model/config.py#L279). The planner can select `DEFAULT_LAMBDA=0.3` for eligible MoE training plans, while old checkpoints retain their stored recipe. Thus “class default zero” is not equivalent to “all new training recipes disable locality.” [Planner choice](../chronos/model/planner.py#L566), [shared training helper](../chronos/expert_clusters.py#L153). + +`inference_clusters(..., paging="auto")` uses training groups when the stored coefficient is positive and otherwise uses singleton expert pages. This is a **metadata-based decision**, not an independent inspection proving how the weights were trained. Editing a checkpoint coefficient after training does not establish learned locality. [Automatic paging](../chronos/expert_clusters.py#L90). + +## 9. The budget objective (0.3.5) + +### 9.1 Why the mutual-information objective cost loss + +At the mutual-information optimum each stream places all of its routing mass in one cluster. A token then reuses the same few experts at every layer and loop iteration. The 0.3.4 default also trained the trunk through this term: its gradient reached attention, embeddings and experts, not only the gate. 0.3.5 changes three things, each behind a field: the objective (`cluster_locality_objective`), the probabilities it reads (`cluster_locality_mass`) and the path of its gradient (`cluster_input_detach`). + +The table isolates these choices on one recipe. All runs use the 15M shape (hidden size 160, 24 routed experts, top-2, one shared expert, loop depth 4; 14.98M total and 6.87M active parameters), MLX on one Apple M5, constant learning rate 1.5e-3, 65,536 tokens per step, seed 1234, segment mode with window 256 and $\lambda_{\mathrm{cl}}=0.3$. The CE gap is the validation CE minus that of the $\lambda_{\mathrm{cl}}=0$ run (5.248) at step 600. Distinct experts per token count the union of selected experts over all 18 dispatches (layers and loop iterations); hitC is the share of the experts used one and two tokens later that lie in the cluster the lookahead predictor ranks first. Both come from a routing probe of each run's final checkpoint (step 745–1290). All values are measured. + +| Run | Objective | Mass | Cluster gradient | CE gap, step 600 | Distinct experts / token | hitC | +|---|---|---|---|---:|---:|---:| +| 0.3.4 default | mutual information | soft | attached | +0.290 | 3.89 | 0.975 | +| | mutual information | soft | gate only | +0.019 | 6.11 | 0.690 | +| | budget, $B=3$ | soft | gate only | +0.000 | 6.99 | 0.579 | +| 0.3.5 default | budget, $B=3$ | dispatch | gate only | −0.009 | 6.98 | 0.564 | +| $\lambda_{\mathrm{cl}}=0$ rerun | none | – | – | −0.001 | 7.40 | 0.408 | + +The $\lambda_{\mathrm{cl}}=0$ reference itself uses 7.45 distinct experts per token. On the trained 0.3.4-default checkpoint, the cluster gradient norm was 0.27 of the CE gradient norm in attention, 0.19 in the gate, 0.11 in the embeddings and 0.07 in routed and shared experts. Detaching the router input removed most of the loss cost, yet the mutual-information objective still cut distinct experts per token to 6.11. The budget objective keeps 6.98–6.99, and its step-600 gap lies within that of the $\lambda_{\mathrm{cl}}=0$ rerun. + +### 9.2 Definition + +Let $p(\cdot\mid w)$ be the pooled cluster distribution of stream $w$ (sections 1 and 3) and $\bar p$ its weighted marginal. For a budget $B0$; a configuration without shared experts has no shared term. See [MoE dispatch and shared averaging](../chronos/model/moe_chronos.py#L114). +With `norm_topk_prob=True`, $a_i=p_i/\sum_{j\in I}p_j$. Otherwise the selected probabilities retain their original mass. Equation (K.4) assumes $S_s>0$; a configuration without shared experts has no shared term. See [MoE dispatch and shared averaging](../chronos/model/moe_chronos.py#L119). -The Torch selected-row path and supported MLX grouped sparse path reduce routed expert matrix work. For width $d_e$, the routed parameter pool contains $3d d_eE$ weights, while ideal selected matrix work scales with $k$. The MLX masked-dense reference path evaluates all $E$ experts before masking. Sparse dispatch is configurable and capability-dependent; see [MLX dispatch branches](../chronos/mlx/moe.py#L272). These counts exclude the router, shared experts, attention, activations and optimizer state. +The Torch selected-row path and supported MLX grouped sparse path reduce routed expert matrix work. For width $d_e$, the routed parameter pool contains $3d d_eE$ weights, while ideal selected matrix work scales with $k$. The MLX masked-dense reference path evaluates all $E$ experts before masking. Sparse dispatch is configurable and capability-dependent; see [MLX dispatch branches](../chronos/mlx/moe.py#L291). These counts exclude the router, shared experts, attention, activations and optimizer state. ## 3. Recurrence is applied around each physical block diff --git a/docs/LAZY_EXPERTS.md b/docs/LAZY_EXPERTS.md index e47b447..43d7c88 100644 --- a/docs/LAZY_EXPERTS.md +++ b/docs/LAZY_EXPERTS.md @@ -169,7 +169,7 @@ The Torch inference API supports three policy strings. Their behavior concerns * | `sync_on_demand` | Execute the real expert after dependencies are satisfied. | Load and wait for the real expert; raise if it cannot be loaded. | Preserves the intended expert computation, subject to ordinary numerical effects. | | `fallback_diagnostic` | Use available experts. | No demand-loader hook; use shared fallback for unavailable selections. | Diagnostic approximation. | -The distinction follows [the installed runtime hooks](../chronos/runtime/inference_engine.py#L121) and [the MoE execution branch](../chronos/model/moe_chronos.py#L312). The MLX engine installs `sync_on_demand` hooks; these Torch policy names should not be presented as an interchangeable MLX generation argument. [MLX hooks](../chronos/mlx/inference.py#L87) +The distinction follows [the installed runtime hooks](../chronos/runtime/inference_engine.py#L121) and [the MoE execution branch](../chronos/model/moe_chronos.py#L320). The MLX engine installs `sync_on_demand` hooks; these Torch policy names should not be presented as an interchangeable MLX generation argument. [MLX hooks](../chronos/mlx/inference.py#L87) Let $S(h)$ be the mean shared output, $I$ the selected experts, $M\subseteq I$ the missing subset, and $w_i$ the already computed routing weights. The exact and fallback outputs are diff --git a/docs/LONG_CONTEXT.md b/docs/LONG_CONTEXT.md index a621013..3458a12 100644 --- a/docs/LONG_CONTEXT.md +++ b/docs/LONG_CONTEXT.md @@ -165,7 +165,7 @@ flowchart TB `activation_checkpointing=True` enables the outer recomputation mechanism during training without incoming cache. `recompute_scope="block"` applies `recompute_policy` to selected blocks; its policies are `all`, `mla`, `swa` and `alternate`. MLX also supports `recompute_scope="mlp"` for only the feed-forward region. These are fields, rather than separate `recompute_block` and `recompute_mlp` booleans. [Scope implementation](../chronos/mlx/model.py#L126), [block selection](../chronos/mlx/model.py#L238) -Sparse expert dispatch can also chunk flattened tokens with `moe_chunk_tokens`. In the MLX training path, each dispatch chunk is checkpointed, reducing the lifetime of gate/up activations of approximate shape $[ck,d_e]$, where $k$ is routed top-$k$ and $d_e$ expert intermediate width. Router outputs and final sequence tensors still exist outside this working set. [MoE chunking](../chronos/mlx/moe.py#L130) +Sparse expert dispatch can also chunk flattened tokens with `moe_chunk_tokens`. In the MLX training path, each dispatch chunk is checkpointed, reducing the lifetime of gate/up activations of approximate shape $[ck,d_e]$, where $k$ is routed top-$k$ and $d_e$ expert intermediate width. Router outputs and final sequence tensors still exist outside this working set. [MoE chunking](../chronos/mlx/moe.py#L143) ## 6. What the recorded experiment establishes diff --git a/docs/LOOKAHEAD.md b/docs/LOOKAHEAD.md index 9cea999..bd15abe 100644 --- a/docs/LOOKAHEAD.md +++ b/docs/LOOKAHEAD.md @@ -30,7 +30,7 @@ $$ Q\in\mathbb R^{B\times T\times(K+1)\times G\times E} $$ -when that flag is true. Softmax is over the final expert axis. Group $g$ is aligned to physical layer $P+g$ in the layer-aware teacher path. It does not mean a separate head for every prelude and coda layer. [Head implementation](../chronos/model/lookahead_router.py#L22), [teacher alignment](../chronos/trainer/loss_mixin.py#L140). +when that flag is true. Softmax is over the final expert axis. Group $g$ is aligned to physical layer $P+g$ in the layer-aware teacher path. It does not mean a separate head for every prelude and coda layer. [Head implementation](../chronos/model/lookahead_router.py#L22), [teacher alignment](../chronos/trainer/loss_mixin.py#L161). | Axis | Meaning | What it is not | |---|---|---| @@ -111,7 +111,7 @@ The teacher is a **soft future routing distribution**, not just hard expert IDs. - `lookahead_teacher_scope="first"`: use the first recorded dispatch distribution. - `lookahead_teacher_scope="iterations"`: average the recorded distributions across that physical layer's iterations. -The accepted string is `"iterations"`, not `"all"`. Averaging probabilities across recurrent calls is not taking a union of their hard selected IDs. The separate future-union objective below concerns **token offsets**. [Scope validation](../chronos/model/config.py#L301), [teacher sources](../chronos/trainer/loss_mixin.py#L101). +The accepted string is `"iterations"`, not `"all"`. Averaging probabilities across recurrent calls is not taking a union of their hard selected IDs. The separate future-union objective below concerns **token offsets**. [Scope validation](../chronos/model/config.py#L323), [teacher sources](../chronos/trainer/loss_mixin.py#L122). When predictions lack a group axis, teacher probabilities are averaged across physical layers. With a group axis, the trainer selects physical recurrent layers $P$ through $P+G-1$. In either case, the teacher is stop-gradient. Denote that aligned distribution by $\mathrm{sg}(P_{b,t,g,e})$. @@ -163,7 +163,7 @@ $$ \ell=H(P)+D_{\mathrm{KL}}(P\|Q). $$ -Because $P$ is detached, its entropy is constant with respect to the prediction branch. Minimizing this term therefore fits the teacher distribution without encouraging the teacher to chase its own prediction. For a prediction logit vector, the local derivative is $Q-P$. [Torch loss](../chronos/model/temporal_loss.py#L259), [MLX masked loss](../chronos/mlx/training/trainer.py#L415). +Because $P$ is detached, its entropy is constant with respect to the prediction branch. Minimizing this term therefore fits the teacher distribution without encouraging the teacher to chase its own prediction. For a prediction logit vector, the local derivative is $Q-P$. [Torch loss](../chronos/model/temporal_loss.py#L283), [MLX masked loss](../chronos/mlx/training/trainer.py#L469). The displayed formula assumes unmasked pairs. Document boundaries and valid-token masks determine which pairs may enter the mean on the relevant trainer path. Their switches must be recorded with a packed-document experiment; a temporal offset crossing unrelated documents is not a valid continuation target. @@ -176,7 +176,7 @@ $$ L_{\mathrm{hit}}=\mathrm{mean}\left[-\log\frac{M^{(\delta)}}{k}\right]. $$ -The division by $k$ is a constant for the selected setting. It gives a uniform predictor the same reference loss $\log E$ across top-k choices. It does not alter the derivative with respect to $Q$. A prediction can place most of its mass on only part of the teacher set, so this is a differentiable **coverage proxy**, not a theorem guaranteeing exact top-k recall. [Hit-mass implementation](../chronos/model/temporal_loss.py#L316). +The division by $k$ is a constant for the selected setting. It gives a uniform predictor the same reference loss $\log E$ across top-k choices. It does not alter the derivative with respect to $Q$. A prediction can place most of its mass on only part of the teacher set, so this is a differentiable **coverage proxy**, not a theorem guaranteeing exact top-k recall. [Hit-mass implementation](../chronos/model/temporal_loss.py#L340). ### 4.3 A union across future token offsets @@ -194,7 +194,7 @@ $$ -\log\frac{\sum_eU_e\widehat Q_e}{\sum_eU_e}\right]. $$ -The maximum across offsets is **not** a normalized categorical distribution or a probabilistic union formula. It summarizes each expert's largest forecast probability over the prefetch window. This term rewards coverage of distinct future needs, while soft cross-entropy preserves offset-specific structure. [Union implementation](../chronos/model/temporal_loss.py#L362). +The maximum across offsets is **not** a normalized categorical distribution or a probabilistic union formula. It summarizes each expert's largest forecast probability over the prefetch window. This term rewards coverage of distinct future needs, while soft cross-entropy preserves offset-specific structure. [Union implementation](../chronos/model/temporal_loss.py#L386). The trainer combines the available terms as @@ -205,7 +205,7 @@ $$ +\lambda_{\mathrm{union}}L_{\mathrm{union}}. $$ -It adds them only when prediction/teacher tensors and future offsets are available. [Assembly](../chronos/trainer/loss_mixin.py#L231). +It adds them only when prediction/teacher tensors and future offsets are available. [Assembly](../chronos/trainer/loss_mixin.py#L254). ## 5. From probabilities to bounded runtime requests diff --git a/docs/MOE_ROUTING.md b/docs/MOE_ROUTING.md index c6c1798..8b8ab20 100644 --- a/docs/MOE_ROUTING.md +++ b/docs/MOE_ROUTING.md @@ -23,7 +23,7 @@ z=W_rh,\quad W_r\in\mathbb R^{E\times d},\qquad g_i=\frac{\exp z_i}{\sum_{j=1}^{E}\exp z_j}. $$ -The router linear layer has **no bias**. Both Torch and MLX cast the router scores to FP32 before softmax; this is a numerical policy, not evidence of a measured latency benefit. Torch uses `torch.topk`; MLX uses `argpartition` and gathers the selected scores. The separate sorting of dispatch rows groups tokens by expert; it should not be confused with the top-k selection algorithm. [Torch selection](../chronos/model/moe_chronos.py#L138), [MLX selection](../chronos/mlx/moe.py#L233). +The router linear layer has **no bias**. Both Torch and MLX cast the router scores to FP32 before softmax; this is a numerical policy, not evidence of a measured latency benefit. Torch uses `torch.topk`; MLX uses `argpartition` and gathers the selected scores. The separate sorting of dispatch rows groups tokens by expert; it should not be confused with the top-k selection algorithm. [Torch selection](../chronos/model/moe_chronos.py#L143), [MLX selection](../chronos/mlx/moe.py#L246). Write $I(h)=\mathrm{TopK}(g,k)$. If `norm_topk_prob=True`, @@ -67,7 +67,7 @@ $$ y(h)=r(h)+s(h). $$ -The implementation takes the **mean** of shared experts, not their sum. This branch runs during normal training and full-resident inference as well as during offloaded inference. When no shared expert is configured, the corresponding contribution is omitted. [Shared mean and standard path](../chronos/model/moe_chronos.py#L117). +The implementation takes the **mean** of shared experts, not their sum. This branch runs during normal training and full-resident inference as well as during offloaded inference. When no shared expert is configured, the corresponding contribution is omitted. [Shared mean and standard path](../chronos/model/moe_chronos.py#L122). For the bias-free matrices above, the per-layer parameter count is the algebraic count @@ -75,7 +75,7 @@ $$ P_{\mathrm{MoE}}=dE+3dd_e(E+S). $$ -A sparse token dispatch performs approximately $3dd_e(k+S)$ matrix FMAs, plus router, activation, normalization and dispatch work. Under a convention of two arithmetic operations per FMA, the corresponding matrix FLOPs are approximately $6dd_e(k+S)$. These are operation counts, **not measured execution times**. In particular, MLX's masked-dense reference path can evaluate every expert before masking; the sparse active-set count does not describe that path's realized cost. [Sparse and reference branches](../chronos/mlx/moe.py#L272). +A sparse token dispatch performs approximately $3dd_e(k+S)$ matrix FMAs, plus router, activation, normalization and dispatch work. Under a convention of two arithmetic operations per FMA, the corresponding matrix FLOPs are approximately $6dd_e(k+S)$. These are operation counts, **not measured execution times**. In particular, MLX's masked-dense reference path can evaluate every expert before masking; the sparse active-set count does not describe that path's realized cost. [Sparse and reference branches](../chronos/mlx/moe.py#L291). ### A named configuration is not a library default @@ -124,9 +124,9 @@ $$ L_{\mathrm{bal}}=E\sum_{i=1}^{E}f_iP_i. $$ -Here $\sum_i f_i=k$, while $\sum_iP_i=1$. Uniform selection and uniform importance therefore give $L_{\mathrm{bal}}=k$, **not one**, under this normalization. This reference value is not a general lower-bound theorem. The Torch implementation averages one-hot selections over token rows, retains the selected-position axis and sums that axis in the loss. [Dispatch loss](../chronos/model/moe_chronos.py#L230), [MLX counterpart](../chronos/mlx/training/trainer.py#L366). +Here $\sum_i f_i=k$, while $\sum_iP_i=1$. Uniform selection and uniform importance therefore give $L_{\mathrm{bal}}=k$, **not one**, under this normalization. This reference value is not a general lower-bound theorem. The Torch implementation averages one-hot selections over token rows, retains the selected-position axis and sums that axis in the loss. [Dispatch loss](../chronos/model/moe_chronos.py#L238), [MLX counterpart](../chronos/mlx/training/trainer.py#L420). -Repeated calls of one recurrent MoE average their raw balance terms. The Torch trainer sums raw terms across physical MoE layers, then multiplies by `lambda_balance`. It does not multiply the already scaled `router_aux_loss_coef` again. [Raw iteration mean](../chronos/model/moe_chronos.py#L111), [trainer assembly](../chronos/trainer/loss_mixin.py#L178). +Repeated calls of one recurrent MoE average their raw balance terms. The Torch trainer sums raw terms across physical MoE layers, then multiplies by `lambda_balance`. It does not multiply the already scaled `router_aux_loss_coef` again. [Raw iteration mean](../chronos/model/moe_chronos.py#L116), [trainer assembly](../chronos/trainer/loss_mixin.py#L199). The implemented regularized objective is usefully written as a sum of **conditional** terms: @@ -144,7 +144,7 @@ $$ \end{aligned} $$ -A term contributes only when its coefficient is positive and the required tensors exist. The table lists the implemented objectives and configuration fields. [Torch assembly](../chronos/trainer/loss_mixin.py#L197), [MLX assembly](../chronos/mlx/training/trainer.py#L675). +A term contributes only when its coefficient is positive and the required tensors exist. The table lists the implemented objectives and configuration fields. [Torch assembly](../chronos/trainer/loss_mixin.py#L218), [MLX assembly](../chronos/mlx/training/trainer.py#L729). [CLUSTER_LOCALITY.md](CLUSTER_LOCALITY.md) derives the partition objective. [LOOKAHEAD.md](LOOKAHEAD.md) derives the three prediction losses. Their roles differ from global expert-load balancing: uniform global use does not ensure a small per-stream working set. @@ -169,7 +169,7 @@ flowchart TB - `router_scope="per_iteration"` reselects IDs. With `"shared"`, later calls reuse the first selected IDs, gather current weights, and, when a smaller top-k is requested, retain the best of that first set. - `lambda_iteration_cluster` penalizes differences from the **mean cluster-mass distribution across iterations**. It is not specifically a distance to iteration zero. See the derivation in [CLUSTER_LOCALITY.md](CLUSTER_LOCALITY.md). -These meanings are enforced by [configuration validation](../chronos/model/config.py#L81), [executor](../chronos/model/model_chronos.py#L277) and [MoE selection](../chronos/model/moe_chronos.py#L155). The KV cache stores attention state, not expert weights. An iteration can reuse KV while requesting a different expert-page set. +These meanings are enforced by [configuration validation](../chronos/model/config.py#L81), [executor](../chronos/model/model_chronos.py#L277) and [MoE selection](../chronos/model/moe_chronos.py#L163). The KV cache stores attention state, not expert weights. An iteration can reuse KV while requesting a different expert-page set. ## 6. Missing routed experts: the shared branch is still present @@ -186,7 +186,7 @@ $$ y_{\mathrm{fallback}}=(1+m)s(h)+\sum_{i\in I:A_i=1}a_iE_i(h). $$ -The shared residual is not removed when it also substitutes for missing routed mass. Training-time miss simulation, controlled by `fallback_mask_prob`, exposes the model to this form. Strict `sync_on_demand` instead loads the exact expert or raises on failure. Expert computation follows the model/store dtype; it is not unconditionally forced to bf16. [Fallback implementation](../chronos/model/moe_chronos.py#L303). +The shared residual is not removed when it also substitutes for missing routed mass. Training-time miss simulation, controlled by `fallback_mask_prob`, exposes the model to this form. Strict `sync_on_demand` instead loads the exact expert or raises on failure. Expert computation follows the model/store dtype; it is not unconditionally forced to bf16. [Fallback implementation](../chronos/model/moe_chronos.py#L311). ```mermaid flowchart TD @@ -239,7 +239,7 @@ The following are **class defaults in this source snapshot**, not a promise that | `recurrent_later_groups` | `0` | Zero retains all recurrent blocks | | `lambda_iteration_cluster` | `0` | Iteration cluster-spread weight | -Sources: [base fields](../chronos/model/kernel.py#L75), [Chronos fields](../chronos/model/config.py#L201), [later-iteration controls](../chronos/model/config.py#L81), [runtime/training controls](../chronos/model/config.py#L297). Planner and preset choices must be reported with the selected recipe, rather than substituted into this table. +Sources: [base fields](../chronos/model/kernel.py#L75), [Chronos fields](../chronos/model/config.py#L201), [later-iteration controls](../chronos/model/config.py#L81), [runtime/training controls](../chronos/model/config.py#L319). Planner and preset choices must be reported with the selected recipe, rather than substituted into this table. Routing evaluations should report expert-load statistics, entropy, task, seed and dispatch timing. The repository does not include `moe_balance.json` or `router_entropy.json`, so no standalone before/after trajectory is reported here. Generalization to larger models and different serving workloads requires additional measurements. diff --git a/docs/RESIDENCY.md b/docs/RESIDENCY.md index 4f5bc21..89c6671 100644 --- a/docs/RESIDENCY.md +++ b/docs/RESIDENCY.md @@ -25,7 +25,7 @@ flowchart TB ``` *Figure 2. Layout, loading and residency are separate mechanisms. Training-aligned and offline graph-derived partitions are alternative layout routes. Reader granularity differs between Torch and MLX, as detailed in [LAZY_EXPERTS.md](LAZY_EXPERTS.md).* -For automatic lazy paging, `inference_clusters` uses the fixed training partition when `lambda_cluster_locality>0`. Otherwise it returns singleton expert groups. Explicit `paging="cluster"` or `paging="expert"` overrides that choice. Offline repacking can also be attached through a manifest; it does not imply that the training loss used the new partition. [Layout selection](../chronos/expert_clusters.py#L64), [manifest override](../chronos/runtime/cache_manager.py#L47) +For automatic lazy paging, `inference_clusters` uses the fixed training partition when `lambda_cluster_locality>0`. Otherwise it returns singleton expert groups. Explicit `paging="cluster"` or `paging="expert"` overrides that choice. Offline repacking can also be attached through a manifest; it does not imply that the training loss used the new partition. [Layout selection](../chronos/expert_clusters.py#L75), [manifest override](../chronos/runtime/cache_manager.py#L47) The `.ctsr` extension denotes a safetensors container. The actual sidecar is `cluster_manifest.json`, with cluster membership and filenames. [Storage schema](../chronos/io/storage.py#L38) diff --git a/docs/THEORY.md b/docs/THEORY.md index 5bffb9b..3238ee0 100644 --- a/docs/THEORY.md +++ b/docs/THEORY.md @@ -197,7 +197,7 @@ M(z)=\sum_{i\in\mathcal I_k(z)}\widehat p_i(z)E_i(z) \tag{T14} $$ -Equation T14 assumes $S_s>0$; omit the shared branch when no shared experts are configured. When top-k normalization is disabled, selected probabilities retain their original softmax mass. The shared branch is an **average** and runs independently of routed selection. Cache-miss substitution is an additional runtime policy. Its formula and quality boundary are covered in [MOE_ROUTING.md](MOE_ROUTING.md) and [LAZY_EXPERTS.md](LAZY_EXPERTS.md). Code: [router and top-k weights](../chronos/model/moe_chronos.py#L138), [shared average](../chronos/model/moe_chronos.py#L117). +Equation T14 assumes $S_s>0$; omit the shared branch when no shared experts are configured. When top-k normalization is disabled, selected probabilities retain their original softmax mass. The shared branch is an **average** and runs independently of routed selection. Cache-miss substitution is an additional runtime policy. Its formula and quality boundary are covered in [MOE_ROUTING.md](MOE_ROUTING.md) and [LAZY_EXPERTS.md](LAZY_EXPERTS.md). Code: [router and top-k weights](../chronos/model/moe_chronos.py#L143), [shared average](../chronos/model/moe_chronos.py#L122). Let $A_{ic}$ be the fixed expert-to-cluster membership matrix. Aggregate routing mass across tokens and all dispatches in a window $w$: @@ -215,7 +215,7 @@ $$ \tag{T16} $$ -Low within-window entropy concentrates a stream. High marginal entropy preserves diversity across streams. The segment variant weights document segments by valid-token count. These are [normalized mutual-information objectives](../chronos/model/temporal_loss.py#L87), not a rolling dot-product loss. +Low within-window entropy concentrates a stream. High marginal entropy preserves diversity across streams. The segment variant weights document segments by valid-token count. These are [normalized mutual-information objectives](../chronos/model/temporal_loss.py#L106), not a rolling dot-product loss. ```mermaid flowchart TB @@ -255,7 +255,7 @@ $$ Only horizons $\mathcal J$ with available token pairs contribute. The implementation clamps predicted probabilities below at $10^{-9}$ before taking logs. For fixed detached $P$, soft-target cross-entropy equals $\mathrm{KL}(P\|Q)+H(P)$. The teacher entropy has no gradient through this loss, so its optimization direction matches forward KL. -Padding and document-boundary handling depend on the active training path. This loss differs from classifying one cluster ID. Expert-to-page mapping occurs later in the runtime. Code: [lookahead_supervision_loss](../chronos/model/temporal_loss.py#L259). +Padding and document-boundary handling depend on the active training path. This loss differs from classifying one cluster ID. Expert-to-page mapping occurs later in the runtime. Code: [lookahead_supervision_loss](../chronos/model/temporal_loss.py#L283). The teacher can use first-iteration routing or an iteration mean. The recurrent path reads the post-prelude state. The depth-one path reads physical block zero. [LOOKAHEAD.md](LOOKAHEAD.md) details those contracts and separates prediction quality from page readiness. @@ -329,7 +329,7 @@ $$ | Relative-step penalty | `recurrent_contraction_coef` | Penalizes a diagnostic above its budget; no Lipschitz guarantee. | | Draft-exit KL | `draft_exit_kl_coef` | Aligns shallow-exit logits with detached full-depth logits. | -The coefficient application is in [chronos_loss_term](../chronos/trainer/loss_mixin.py#L152). Each term also requires its source tensors and the caller's activation conditions. In that helper, top-k and union lookahead terms are nested under the enabled soft-target lookahead path. Stage-specific anchoring and masking also depend on the caller. The retained name `recurrent_distill_coef` refers to symmetric depth-state consistency in this implementation. It should not be confused with the detached teacher in draft-exit Kullback–Leibler (KL) divergence. +The coefficient application is in [chronos_loss_term](../chronos/trainer/loss_mixin.py#L173). Each term also requires its source tensors and the caller's activation conditions. In that helper, top-k and union lookahead terms are nested under the enabled soft-target lookahead path. Stage-specific anchoring and masking also depend on the caller. The retained name `recurrent_distill_coef` refers to symmetric depth-state consistency in this implementation. It should not be confused with the detached teacher in draft-exit Kullback–Leibler (KL) divergence. ## 8. What is established and what remains conditional diff --git a/pyproject.toml b/pyproject.toml index f4c3383..fbd555e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "Project_Chronos" -version = "0.3.4" +version = "0.3.5" description = "Storage-aware recurrent-depth MoE: lookahead expert prefetch, SSD-lazy experts, hybrid MLA/SWA attention, self-speculative decoding" readme = "README.md" license = "Apache-2.0" diff --git a/reports/cluster_budget_20261127/summary.json b/reports/cluster_budget_20261127/summary.json new file mode 100644 index 0000000..64b9158 --- /dev/null +++ b/reports/cluster_budget_20261127/summary.json @@ -0,0 +1,1371 @@ +{ + "note": "Measured on one Apple M5 machine with the MLX backend; local workspace experiments/cluster_15m. valid_ce_64 = mean CE over 64 fixed validation batches of the 5-source pretrain mix at the final step.", + "root_cause_15m_constant_lr": { + "reference_lambda0": { + "file": "results_s1/arm_base_nocl.json", + "label": "base_nocl", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.0015, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.765549622476101, + "final_step": 930, + "valid_ce_at": { + "200": 6.3025, + "400": 5.6758, + "600": 5.2477, + "800": 4.8713 + }, + "probe": { + "hit_cluster": 0.4019952964419215, + "expert_ids_per_token": 7.451578776041667, + "clusters_per_token": 4.563663736979167, + "segment_share": 0.3133877224392361, + "source_cluster_mi_over_h": null + }, + "budget_probe": { + "tail_ce_mean_full": 4.508589703838031, + "tail_ce_mean_b8": 4.667029829323292, + "tail_ce_mean_b12": 4.5746500780185055, + "tail_ce_cost_b8": 0.15844012548526099, + "tail_ce_cost_b12": 0.06606037418047439 + } + }, + "arms": { + "base_034_attached_mutual_info": { + "file": "../loop_depth_15m/results_abc/arm_base.json", + "label": "base", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.0015, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.734924830496311, + "final_step": 1290, + "valid_ce_at": { + "200": 6.4407, + "400": 5.9028, + "600": 5.5372, + "800": 5.2098, + "1000": 4.9199, + "1250": 4.7278 + }, + "probe": { + "hit_cluster": 0.9746172054366837, + "expert_ids_per_token": 3.8873616536458333, + "clusters_per_token": 1.0874104817708334, + "segment_share": 0.948264114945023, + "source_cluster_mi_over_h": null + }, + "budget_probe": { + "tail_ce_mean_full": 4.49411123941342, + "tail_ce_mean_b8": 4.5030681669712065, + "tail_ce_mean_b12": 4.498117421070734, + "tail_ce_cost_b8": 0.008956927557786543, + "tail_ce_cost_b12": 0.004006181657314478 + }, + "gap_vs_lambda0": { + "200": 0.1382, + "400": 0.227, + "600": 0.2895, + "800": 0.3385 + } + }, + "mutual_info_detached": { + "file": "results_s2/arm_cl_det.json", + "label": "cl_det", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.0015, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": null, + "mass": "soft", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 5.016251280903816, + "final_step": 745, + "valid_ce_at": { + "200": 6.3146, + "400": 5.7017, + "600": 5.2671 + }, + "probe": { + "hit_cluster": 0.689827648953417, + "expert_ids_per_token": 6.105851236979166, + "clusters_per_token": 2.1542317708333334, + "segment_share": 0.6156797055844907, + "source_cluster_mi_over_h": 0.6422631592094905 + }, + "budget_probe": { + "tail_ce_mean_full": 4.75290385534366, + "tail_ce_mean_b8": 4.85005846619606, + "tail_ce_mean_b12": 4.785193948944409, + "tail_ce_cost_b8": 0.0971546108524004, + "tail_ce_cost_b12": 0.03229009360074908 + }, + "gap_vs_lambda0": { + "200": 0.0121, + "400": 0.0259, + "600": 0.0194 + } + }, + "budget_detached_soft": { + "file": "results_s9/arm_tb3_det.json", + "label": "tb3_det", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.0015, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "soft", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.910358682274818, + "final_step": 800, + "valid_ce_at": { + "200": 6.3209, + "400": 5.685, + "600": 5.2478, + "800": 4.8774 + }, + "probe": { + "hit_cluster": 0.5794669469885556, + "expert_ids_per_token": 6.991162109375, + "clusters_per_token": 2.8167317708333335, + "segment_share": 0.48720364040798614, + "source_cluster_mi_over_h": 0.5543163825523396 + }, + "budget_probe": { + "tail_ce_mean_full": 4.647531774143378, + "tail_ce_mean_b8": 4.773786926269532, + "tail_ce_mean_b12": 4.679250356058279, + "tail_ce_cost_b8": 0.1262551521261539, + "tail_ce_cost_b12": 0.03171858191490173 + }, + "gap_vs_lambda0": { + "200": 0.0184, + "400": 0.0092, + "600": 0.0001, + "800": 0.0061 + } + }, + "budget_detached_dispatch": { + "file": "results_s13/arm_tb3_disp.json", + "label": "tb3_disp", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.0015, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.907915368676186, + "final_step": 800, + "valid_ce_at": { + "200": 6.3128, + "400": 5.6816, + "600": 5.2389, + "800": 4.8758 + }, + "probe": { + "hit_cluster": 0.5642272436942813, + "expert_ids_per_token": 6.983146158854167, + "clusters_per_token": 3.016259765625, + "segment_share": 0.47841457790798614, + "source_cluster_mi_over_h": 0.5793633535451501 + }, + "budget_probe": { + "tail_ce_mean_full": 4.650813452899456, + "tail_ce_mean_b8": 4.777694658438365, + "tail_ce_mean_b12": 4.681595531105995, + "tail_ce_cost_b8": 0.12688120553890858, + "tail_ce_cost_b12": 0.03078207820653933 + }, + "gap_vs_lambda0": { + "200": 0.0103, + "400": 0.0058, + "600": -0.0088, + "800": 0.0045 + } + }, + "free_lambda0_rerun": { + "file": "results_s6/arm_nocl_800.json", + "label": "nocl_800", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.0015, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.900621257722378, + "final_step": 800, + "valid_ce_at": { + "200": 6.3076, + "400": 5.6748, + "600": 5.2472, + "800": 4.8674 + }, + "probe": { + "hit_cluster": 0.40767012245109235, + "expert_ids_per_token": 7.403792317708334, + "clusters_per_token": 4.568904622395833, + "segment_share": 0.3244118019386574, + "source_cluster_mi_over_h": 0.4199789647822853 + }, + "budget_probe": { + "tail_ce_mean_full": 4.642232518394788, + "tail_ce_mean_b8": 4.794470183054606, + "tail_ce_mean_b12": 4.70589718123277, + "tail_ce_cost_b8": 0.15223766465981736, + "tail_ce_cost_b12": 0.063664662837982 + }, + "gap_vs_lambda0": { + "200": 0.0051, + "400": -0.001, + "600": -0.0005, + "800": -0.0039 + } + } + }, + "gradient_norm_ratio_cluster_over_ce_034": { + "embed": { + "ce_norm": 0.3518937828257994, + "cluster_norm": 0.040123177857237825, + "ratio": 0.11402070685943405, + "cos": -0.012463339878569504 + }, + "gate": { + "ce_norm": 0.04228637567737463, + "cluster_norm": 0.007888628521233723, + "ratio": 0.1865524863473826, + "cos": 0.017703000745301456 + }, + "lookahead": { + "ce_norm": 0.0, + "cluster_norm": 0.0, + "ratio": 0.0, + "cos": 0.0 + }, + "norm": { + "ce_norm": 0.038709494972754284, + "cluster_norm": 0.006247079249720366, + "ratio": 0.16138364125177504, + "cos": -0.04539293957191707 + }, + "recurrent_controller": { + "ce_norm": 0.01012309326283239, + "cluster_norm": 0.0009304985387203124, + "ratio": 0.09191840029141089, + "cos": 0.3451551063100188 + }, + "routed_experts": { + "ce_norm": 0.18991958533924902, + "cluster_norm": 0.013911601489351595, + "ratio": 0.07324995715687574, + "cos": -0.019431801482148993 + }, + "self_attn": { + "ce_norm": 0.7437663261282579, + "cluster_norm": 0.2012380600139693, + "ratio": 0.27056624230560694, + "cos": -0.015367643959601735 + }, + "shared_experts": { + "ce_norm": 0.4423843855071996, + "cluster_norm": 0.030230941041005377, + "ratio": 0.06833636545816417, + "cos": -0.0026403787272281463 + } + } + }, + "m15_cosine2000": [ + { + "seed": 1234, + "free": { + "file": "results_s101/arm_cos2k_free.json", + "label": "cos2k_free", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.148943725973368, + "final_step": 2000, + "valid_ce_at": { + "200": 5.93, + "400": 5.0328, + "600": 4.7148, + "800": 4.5442, + "1000": 4.4266, + "1250": 4.307, + "1500": 4.2152, + "2000": 4.1244 + }, + "probe": { + "hit_cluster": 0.43777808155225556, + "expert_ids_per_token": 7.7321044921875, + "clusters_per_token": 4.6631103515625, + "segment_share": 0.3147275571469907, + "source_cluster_mi_over_h": 0.4261170089741294 + }, + "budget_probe": { + "tail_ce_mean_full": 3.9042965076863765, + "tail_ce_mean_b8": 4.091934700558583, + "tail_ce_mean_b12": 3.9889972597360606, + "tail_ce_mean_b24": 3.9042965081830823, + "tail_ce_cost_b8": 0.1876381928722064, + "tail_ce_cost_b12": 0.08470075204968408, + "tail_ce_cost_b24": 4.967057876115177e-10 + } + }, + "clustered": { + "file": "results_s102/arm_cos2k_tb3d.json", + "label": "cos2k_tb3d", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.134436387568712, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9129, + "400": 5.0199, + "600": 4.6978, + "800": 4.5308, + "1000": 4.409, + "1250": 4.289, + "1500": 4.1979, + "2000": 4.1086 + }, + "probe": { + "hit_cluster": 0.586016660231444, + "expert_ids_per_token": 6.9187744140625, + "clusters_per_token": 2.8533040364583333, + "segment_share": 0.4762331362123842, + "source_cluster_mi_over_h": 0.4944468336103336 + }, + "budget_probe": { + "tail_ce_mean_full": 3.894266611834367, + "tail_ce_mean_b8": 4.053938173751037, + "tail_ce_mean_b12": 3.9302760347723953, + "tail_ce_mean_b24": 3.8942664568622902, + "tail_ce_cost_b8": 0.15967156191666998, + "tail_ce_cost_b12": 0.03600942293802811, + "tail_ce_cost_b24": -1.5497207694892268e-07 + } + }, + "free_e12": { + "file": "results_s107/arm_cos2k_e12.json", + "label": "cos2k_e12", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 10539373, + "params_active": 6852973, + "tokens_per_step": 65536, + "num_experts": 12, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.188645422458649, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9555, + "400": 5.064, + "600": 4.7309, + "800": 4.566, + "1000": 4.4469, + "1250": 4.3347, + "1500": 4.2475, + "2000": 4.1626 + }, + "probe": { + "hit_cluster": 0.4997969012804893, + "expert_ids_per_token": 5.780696614583333, + "clusters_per_token": 2.9373128255208334, + "segment_share": 0.4427234790943287, + "source_cluster_mi_over_h": 0.3720361068294024 + }, + "budget_probe": { + "tail_ce_mean_full": 3.9442759851614637, + "tail_ce_mean_b8": 3.9653506691257157, + "tail_ce_mean_b12": 3.9442759856581686, + "tail_ce_mean_b24": 3.9442759856581686, + "tail_ce_cost_b8": 0.02107468396425194, + "tail_ce_cost_b12": 4.96704899433098e-10, + "tail_ce_cost_b24": 4.96704899433098e-10 + } + }, + "gap_clustered_vs_free": { + "200": -0.0171, + "400": -0.0129, + "600": -0.017, + "800": -0.0134, + "1000": -0.0176, + "1250": -0.018, + "1500": -0.0173, + "2000": -0.0158 + } + }, + { + "seed": 2026, + "free": { + "file": "results_s103/arm_cos2k_free_s2.json", + "label": "cos2k_free_s2", + "seed": 2026, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.14517804980278, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9035, + "400": 5.0082, + "600": 4.6929, + "800": 4.5386, + "1000": 4.4152, + "1250": 4.2988, + "1500": 4.2121, + "2000": 4.1167 + }, + "probe": { + "hit_cluster": 0.41502430720433153, + "expert_ids_per_token": 7.446834309895833, + "clusters_per_token": 4.787980143229166, + "segment_share": 0.31289492006655095, + "source_cluster_mi_over_h": 0.4784393908836279 + }, + "budget_probe": { + "tail_ce_mean_full": 3.9027038740615048, + "tail_ce_mean_b8": 4.074782450497151, + "tail_ce_mean_b12": 3.9666780496637033, + "tail_ce_mean_b24": 3.9027038921912514, + "tail_ce_cost_b8": 0.17207857643564584, + "tail_ce_cost_b12": 0.06397417560219854, + "tail_ce_cost_b24": 1.8129746592876472e-08 + } + }, + "clustered": { + "file": "results_s104/arm_cos2k_tb3d_s2.json", + "label": "cos2k_tb3d_s2", + "seed": 2026, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.150886956602335, + "final_step": 2000, + "valid_ce_at": { + "200": 5.983, + "400": 5.0651, + "600": 4.7188, + "800": 4.5498, + "1000": 4.4206, + "1250": 4.3051, + "1500": 4.219, + "2000": 4.1264 + }, + "probe": { + "hit_cluster": 0.5844983089554315, + "expert_ids_per_token": 7.331241861979167, + "clusters_per_token": 3.1883870442708333, + "segment_share": 0.45577098705150465, + "source_cluster_mi_over_h": 0.5019231832133811 + }, + "budget_probe": { + "tail_ce_mean_full": 3.903949062526226, + "tail_ce_mean_b8": 4.041738101591666, + "tail_ce_mean_b12": 3.9318622236450516, + "tail_ce_mean_b24": 3.903958321611087, + "tail_ce_cost_b8": 0.13778903906544038, + "tail_ce_cost_b12": 0.02791316111882569, + "tail_ce_cost_b24": 9.259084861046318e-06 + } + }, + "free_e12": { + "file": "results_s108/arm_cos2k_e12_s2.json", + "label": "cos2k_e12_s2", + "seed": 2026, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 10539373, + "params_active": 6852973, + "tokens_per_step": 65536, + "num_experts": 12, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.191990464925766, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9558, + "400": 5.061, + "600": 4.7404, + "800": 4.5755, + "1000": 4.4498, + "1250": 4.3369, + "1500": 4.2555, + "2000": 4.167 + }, + "probe": { + "hit_cluster": 0.5174364704143644, + "expert_ids_per_token": 5.508561197916666, + "clusters_per_token": 2.8633463541666666, + "segment_share": 0.482548240379051, + "source_cluster_mi_over_h": 0.4236398324999779 + }, + "budget_probe": { + "tail_ce_mean_full": 3.9535563593109453, + "tail_ce_mean_b8": 3.977897242705027, + "tail_ce_mean_b12": 3.953556589782238, + "tail_ce_mean_b24": 3.953556589782238, + "tail_ce_cost_b8": 0.024340883394081914, + "tail_ce_cost_b12": 2.3047129271702715e-07, + "tail_ce_cost_b24": 2.3047129271702715e-07 + } + }, + "gap_clustered_vs_free": { + "200": 0.0795, + "400": 0.0569, + "600": 0.0259, + "800": 0.0112, + "1000": 0.0054, + "1250": 0.0063, + "1500": 0.0069, + "2000": 0.0097 + } + }, + { + "seed": 77, + "free": { + "file": "results_s105/arm_cos2k_free_s3.json", + "label": "cos2k_free_s3", + "seed": 77, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.156006887555122, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9641, + "400": 5.0464, + "600": 4.722, + "800": 4.5519, + "1000": 4.4262, + "1250": 4.3151, + "1500": 4.2241, + "2000": 4.1293 + }, + "probe": { + "hit_cluster": 0.4243892744026834, + "expert_ids_per_token": 7.740926106770833, + "clusters_per_token": 4.823828125, + "segment_share": 0.3114260073061343, + "source_cluster_mi_over_h": 0.4462879397033662 + }, + "budget_probe": { + "tail_ce_mean_full": 3.909285458177328, + "tail_ce_mean_b8": 4.093319493035476, + "tail_ce_mean_b12": 3.986116265008847, + "tail_ce_mean_b24": 3.909285493195057, + "tail_ce_cost_b8": 0.1840340348581475, + "tail_ce_cost_b12": 0.07683080683151866, + "tail_ce_cost_b24": 3.501772871672415e-08 + } + }, + "clustered": { + "file": "results_s106/arm_cos2k_tb3d_s3.json", + "label": "cos2k_tb3d_s3", + "seed": 77, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.153386767953634, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9031, + "400": 5.0161, + "600": 4.71, + "800": 4.5487, + "1000": 4.4258, + "1250": 4.311, + "1500": 4.22, + "2000": 4.1263 + }, + "probe": { + "hit_cluster": 0.5961109737131153, + "expert_ids_per_token": 7.130965169270834, + "clusters_per_token": 3.0689208984375, + "segment_share": 0.467289451316551, + "source_cluster_mi_over_h": 0.5242775772522839 + }, + "budget_probe": { + "tail_ce_mean_full": 3.9050379380583764, + "tail_ce_mean_b8": 4.044394898414612, + "tail_ce_mean_b12": 3.928987141201893, + "tail_ce_mean_b24": 3.905037931601207, + "tail_ce_cost_b8": 0.13935696035623524, + "tail_ce_cost_b12": 0.023949203143516673, + "tail_ce_cost_b24": -6.4571694657900025e-09 + } + }, + "free_e12": { + "file": "results_s109/arm_cos2k_e12_s3.json", + "label": "cos2k_e12_s3", + "seed": 77, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 10539373, + "params_active": 6852973, + "tokens_per_step": 65536, + "num_experts": 12, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.1814477145671844, + "final_step": 2000, + "valid_ce_at": { + "200": 5.9223, + "400": 5.0156, + "600": 4.715, + "800": 4.5555, + "1000": 4.4393, + "1250": 4.3291, + "1500": 4.2428, + "2000": 4.1564 + }, + "probe": { + "hit_cluster": 0.5432573817198113, + "expert_ids_per_token": 6.0090576171875, + "clusters_per_token": 2.8601969401041667, + "segment_share": 0.49213889793113424, + "source_cluster_mi_over_h": 0.43071188625481366 + }, + "budget_probe": { + "tail_ce_mean_full": 3.9447170409063497, + "tail_ce_mean_b8": 3.9667404567201934, + "tail_ce_mean_b12": 3.9447170252601302, + "tail_ce_mean_b24": 3.9447170252601302, + "tail_ce_cost_b8": 0.022023415813843705, + "tail_ce_cost_b12": -1.5646219431175723e-08, + "tail_ce_cost_b24": -1.5646219431175723e-08 + } + }, + "gap_clustered_vs_free": { + "200": -0.061, + "400": -0.0303, + "600": -0.012, + "800": -0.0032, + "1000": -0.0004, + "1250": -0.0041, + "1500": -0.0041, + "2000": -0.003 + } + } + ], + "m30_cosine2000": [ + { + "seed": 1234, + "free": { + "file": "results_s110/arm_m30_free.json", + "label": "m30_free", + "seed": 1234, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.044818956404924, + "final_step": 2000, + "valid_ce_at": { + "200": 6.1631, + "400": 5.3189, + "600": 4.7657, + "800": 4.5335, + "1000": 4.3857, + "1250": 4.2424, + "1500": 4.1336, + "2000": 4.0213 + }, + "probe": { + "hit_cluster": 0.439654014234832, + "expert_ids_per_token": 7.4804931640625, + "clusters_per_token": 3.772696940104167, + "segment_share": 0.3549029181985294, + "source_cluster_mi_over_h": 0.3312667891699438 + }, + "budget_probe": { + "tail_ce_mean_full": 3.8011005068818733, + "tail_ce_mean_b8": 3.8920693919062614, + "tail_ce_mean_b12": 3.8260115745166936, + "tail_ce_mean_b24": 3.801100528240204, + "tail_ce_cost_b8": 0.09096888502438816, + "tail_ce_cost_b12": 0.024911067634820316, + "tail_ce_cost_b24": 2.135833065963766e-08 + } + }, + "clustered": { + "file": "results_s111/arm_m30_tb2d.json", + "label": "m30_tb2d", + "seed": 1234, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 2, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.0258311703801155, + "final_step": 2000, + "valid_ce_at": { + "200": 6.0869, + "400": 5.2019, + "600": 4.7081, + "800": 4.496, + "1000": 4.3542, + "1250": 4.2166, + "1500": 4.1124, + "2000": 4.002 + }, + "probe": { + "hit_cluster": 0.5669844046529856, + "expert_ids_per_token": 7.801424153645834, + "clusters_per_token": 3.1454671223958335, + "segment_share": 0.5113633099724264, + "source_cluster_mi_over_h": 0.4943629779568808 + }, + "budget_probe": { + "tail_ce_mean_full": 3.7871177598834036, + "tail_ce_mean_b8": 3.8287469496329627, + "tail_ce_mean_b12": 3.7933511078357696, + "tail_ce_mean_b24": 3.7871193575362363, + "tail_ce_cost_b8": 0.04162918974955909, + "tail_ce_cost_b12": 0.006233347952365964, + "tail_ce_cost_b24": 1.5976528326966388e-06 + } + }, + "gap_clustered_vs_free": { + "200": -0.0762, + "400": -0.117, + "600": -0.0576, + "800": -0.0375, + "1000": -0.0315, + "1250": -0.0258, + "1500": -0.0212, + "2000": -0.0193 + }, + "lambda_ramp_015_030": { + "file": "results_s117/arm_m30_tr.json", + "label": "m30_tr", + "seed": 1234, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 2, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.034920964390039, + "final_step": 2000, + "valid_ce_at": { + "200": 6.1114, + "400": 5.1925, + "600": 4.7302, + "800": 4.5108, + "1000": 4.3672, + "1250": 4.2253, + "1500": 4.1221, + "2000": 4.0112 + } + }, + "gap_ramp_vs_free": { + "200": -0.0517, + "400": -0.1264, + "600": -0.0355, + "800": -0.0227, + "1000": -0.0185, + "1250": -0.0171, + "1500": -0.0115, + "2000": -0.0101 + } + }, + { + "seed": 2026, + "free": { + "file": "results_s112/arm_m30_free_s2.json", + "label": "m30_free_s2", + "seed": 2026, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.028371699154377, + "final_step": 2000, + "valid_ce_at": { + "200": 6.1373, + "400": 5.3656, + "600": 4.7636, + "800": 4.5368, + "1000": 4.3668, + "1250": 4.2223, + "1500": 4.113, + "2000": 4.0038 + }, + "probe": { + "hit_cluster": 0.4546502130568266, + "expert_ids_per_token": 7.437369791666667, + "clusters_per_token": 3.796126302083333, + "segment_share": 0.36096837660845593, + "source_cluster_mi_over_h": 0.2516153586693769 + }, + "budget_probe": { + "tail_ce_mean_full": 3.7820316741863884, + "tail_ce_mean_b8": 3.908116427063942, + "tail_ce_mean_b12": 3.8086130152146027, + "tail_ce_mean_b24": 3.782031650096178, + "tail_ce_cost_b8": 0.12608475287755372, + "tail_ce_cost_b12": 0.0265813410282143, + "tail_ce_cost_b24": -2.4090210271054957e-08 + } + }, + "clustered": { + "file": "results_s113/arm_m30_tb2d_s2.json", + "label": "m30_tb2d_s2", + "seed": 2026, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 2, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.017955616116524, + "final_step": 2000, + "valid_ce_at": { + "200": 6.1309, + "400": 5.3554, + "600": 4.7398, + "800": 4.5144, + "1000": 4.3587, + "1250": 4.2123, + "1500": 4.1063, + "2000": 3.9952 + }, + "probe": { + "hit_cluster": 0.5710031407682936, + "expert_ids_per_token": 7.3731689453125, + "clusters_per_token": 3.0381429036458334, + "segment_share": 0.5298288382735906, + "source_cluster_mi_over_h": 0.5106025264703986 + }, + "budget_probe": { + "tail_ce_mean_full": 3.776889292399088, + "tail_ce_mean_b8": 3.80828393449386, + "tail_ce_mean_b12": 3.781118153035641, + "tail_ce_mean_b24": 3.7768893492718534, + "tail_ce_cost_b8": 0.03139464209477172, + "tail_ce_cost_b12": 0.004228860636552589, + "tail_ce_cost_b24": 5.687276516397333e-08 + } + }, + "gap_clustered_vs_free": { + "200": -0.0064, + "400": -0.0102, + "600": -0.0238, + "800": -0.0224, + "1000": -0.0081, + "1250": -0.01, + "1500": -0.0067, + "2000": -0.0086 + } + }, + { + "seed": 77, + "free": { + "file": "results_s114/arm_m30_free_s3.json", + "label": "m30_free_s3", + "seed": 77, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.019855294376612, + "final_step": 2000, + "valid_ce_at": { + "200": 6.0553, + "400": 5.124, + "600": 4.6923, + "800": 4.493, + "1000": 4.3412, + "1250": 4.2083, + "1500": 4.1061, + "2000": 3.9971 + }, + "probe": { + "hit_cluster": 0.44126531113301487, + "expert_ids_per_token": 7.315958658854167, + "clusters_per_token": 3.7721354166666665, + "segment_share": 0.3609878839231005, + "source_cluster_mi_over_h": 0.33862601436647116 + }, + "budget_probe": { + "tail_ce_mean_full": 3.775821361442407, + "tail_ce_mean_b8": 3.8841581453879677, + "tail_ce_mean_b12": 3.7955558930834137, + "tail_ce_mean_b24": 3.775821348031362, + "tail_ce_cost_b8": 0.10833678394556046, + "tail_ce_cost_b12": 0.01973453164100647, + "tail_ce_cost_b24": -1.3411045163280733e-08 + } + }, + "clustered": { + "file": "results_s115/arm_m30_tb2d_s3.json", + "label": "m30_tb2d_s3", + "seed": 77, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 2, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.071601551026106, + "final_step": 2000, + "valid_ce_at": { + "200": 6.201, + "400": 5.4925, + "600": 4.9118, + "800": 4.6052, + "1000": 4.4307, + "1250": 4.2781, + "1500": 4.1686, + "2000": 4.0503 + }, + "probe": { + "hit_cluster": 0.6277365476370342, + "expert_ids_per_token": 7.6467041015625, + "clusters_per_token": 3.070060221354167, + "segment_share": 0.5427863625919118, + "source_cluster_mi_over_h": 0.47544739486638987 + }, + "budget_probe": { + "tail_ce_mean_full": 3.831576986362536, + "tail_ce_mean_b8": 3.8703337845702963, + "tail_ce_mean_b12": 3.838647613922755, + "tail_ce_mean_b24": 3.8315769784152507, + "tail_ce_cost_b8": 0.038756798207760124, + "tail_ce_cost_b12": 0.007070627560219034, + "tail_ce_cost_b24": -7.947285496356926e-09 + } + }, + "gap_clustered_vs_free": { + "200": 0.1457, + "400": 0.3685, + "600": 0.2195, + "800": 0.1122, + "1000": 0.0895, + "1250": 0.0698, + "1500": 0.0625, + "2000": 0.0532 + }, + "lambda_ramp_015_030": { + "file": "results_s116/arm_m30_tr_s3.json", + "label": "m30_tr_s3", + "seed": 77, + "hidden": 256, + "depth": 8, + "peak_lr": 0.006, + "schedule": "cosine to 0.1 over 2000 steps", + "params_total": 29683397, + "params_active": 13168325, + "tokens_per_step": 65536, + "num_experts": 16, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 2, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.042298197746277, + "final_step": 2000, + "valid_ce_at": { + "200": 6.1201, + "400": 5.4029, + "600": 4.7767, + "800": 4.5413, + "1000": 4.3833, + "1250": 4.2437, + "1500": 4.1362, + "2000": 4.0218 + } + }, + "gap_ramp_vs_free": { + "200": 0.0648, + "400": 0.2789, + "600": 0.0844, + "800": 0.0483, + "1000": 0.0421, + "1250": 0.0354, + "1500": 0.0301, + "2000": 0.0247 + } + } + ], + "loop_depth_15m_6e-3_800": { + "free_d4": { + "file": "results_s73/arm_free_lr6.json", + "label": "free_lr6", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.6168240159749985, + "final_step": 800, + "valid_ce_at": { + "200": 5.9289, + "400": 5.0253, + "600": 4.7298, + "800": 4.5856 + }, + "probe": { + "hit_cluster": 0.38794704711222383, + "expert_ids_per_token": 7.933984375, + "clusters_per_token": 4.927628580729166, + "segment_share": 0.2839995207609954, + "source_cluster_mi_over_h": 0.3310879061747147 + }, + "budget_probe": { + "tail_ce_mean_full": 4.367536327242851, + "tail_ce_mean_b8": 4.506971610089143, + "tail_ce_mean_b12": 4.430228581527869, + "tail_ce_mean_b24": 4.367536487181981, + "tail_ce_cost_b8": 0.13943528284629192, + "tail_ce_cost_b12": 0.06269225428501812, + "tail_ce_cost_b24": 1.5993913038414576e-07 + } + }, + "clustered_d4": { + "file": "results_s74/arm_tb3d_lr6.json", + "label": "tb3d_lr6", + "seed": 1234, + "hidden": 160, + "depth": 4, + "peak_lr": 0.006, + "schedule": "constant", + "params_total": 14980333, + "params_active": 6870253, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.598569922149181, + "final_step": 800, + "valid_ce_at": { + "200": 5.8853, + "400": 5.0001, + "600": 4.7158, + "800": 4.5708 + }, + "probe": { + "hit_cluster": 0.5857592463355206, + "expert_ids_per_token": 6.926302083333334, + "clusters_per_token": 3.073006184895833, + "segment_share": 0.4841249819155093, + "source_cluster_mi_over_h": 0.5695650056728566 + }, + "budget_probe": { + "tail_ce_mean_full": 4.365454926590125, + "tail_ce_mean_b8": 4.46286535759767, + "tail_ce_mean_b12": 4.385067540903886, + "tail_ce_mean_b24": 4.365458450714748, + "tail_ce_cost_b8": 0.09741043100754432, + "tail_ce_cost_b12": 0.019612614313761156, + "tail_ce_cost_b24": 3.5241246223449707e-06 + } + }, + "free_d1": { + "file": "results_s89/arm_free_lr6_d1.json", + "label": "free_lr6_d1", + "seed": 1234, + "hidden": 160, + "depth": 1, + "peak_lr": 0.006, + "schedule": "constant", + "params_total": 14979853, + "params_active": 6869773, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.0, + "cluster_budget": null, + "mass": "soft", + "detach": false, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.79989954829216, + "final_step": 800, + "valid_ce_at": { + "200": 6.2574, + "400": 5.5492, + "600": 5.0185, + "800": 4.7686 + } + }, + "clustered_d1": { + "file": "results_s90/arm_tb3d_lr6_d1.json", + "label": "tb3d_lr6_d1", + "seed": 1234, + "hidden": 160, + "depth": 1, + "peak_lr": 0.006, + "schedule": "constant", + "params_total": 14979853, + "params_active": 6869773, + "tokens_per_step": 65536, + "num_experts": 24, + "top_k": 2, + "lambda_cluster": 0.3, + "cluster_budget": 3, + "mass": "dispatch", + "detach": true, + "mode": "segment", + "window": 256, + "valid_ce_64": 4.793829917907715, + "final_step": 800, + "valid_ce_at": { + "200": 6.2758, + "400": 5.5396, + "600": 4.987, + "800": 4.7612 + } + } + } +} \ No newline at end of file diff --git a/tests/test_cluster_budget.py b/tests/test_cluster_budget.py new file mode 100644 index 0000000..b6af58b --- /dev/null +++ b/tests/test_cluster_budget.py @@ -0,0 +1,255 @@ +"""Cluster objective of 0.3.5: the budget objective, dispatch mass and the gate-only (detached) cluster gradient, +with Torch/MLX parity, the config defaults and the pre-0.3.5 checkpoint backfill.""" +import json +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +from chronos.expert_clusters import cluster_budget +from chronos.model.config import ChronosConfig +from chronos.model.temporal_loss import cluster_locality_loss, dispatch_mass, segment_cluster_loss + +E = 12 + + +@pytest.fixture +def mx(): + """MLX on the CPU: the GPU matmul rounds fp32 inputs to a TF32-class mantissa.""" + core = pytest.importorskip("mlx.core") + old = core.default_device() + core.set_default_device(core.cpu) + yield core + core.set_default_device(old) + + +def _router(seed=0): + rng = np.random.default_rng(seed) + logits = rng.normal(size=(2, 16, 3, E)) * 2.0 + p = np.exp(logits - logits.max(-1, keepdims=True)) + return (p / p.sum(-1, keepdims=True)).astype(np.float32) + + +def _membership(c): + return np.array([[1.0 if e * c // E == j else 0.0 for j in range(c)] for e in range(E)], np.float32) + + +def _window_pw(r, memb, window): + B, S, V, _ = r.shape + mass = np.einsum("bsve,ec->bsvc", r, memb) + return mass.reshape(B, S // window, window, V, -1).mean(axis=(2, 3)).reshape(B * (S // window), -1) + + +def _cfg(**kw): + base = dict(hidden_size=32, num_experts=E, num_experts_per_tok=2, moe_intermediate_size=16, num_shared_experts=1, + cluster_locality_window=8) + base.update(kw) + return ChronosConfig(**base) + + +def test_defaults_and_budget_rule(): + cfg = ChronosConfig() + assert (cfg.cluster_locality_objective, cfg.cluster_locality_budget, cfg.cluster_locality_mass, + cfg.cluster_input_detach) == ("budget", 0, "dispatch", True) + assert cluster_budget(_cfg()) == 2 # ceil(E / 2k) = 3 clusters, half rounded up + assert cluster_budget(_cfg(cluster_locality_clusters=4)) == 2 + assert cluster_budget(_cfg(cluster_locality_clusters=6)) == 3 + assert cluster_budget(_cfg(cluster_locality_clusters=4, cluster_locality_budget=3)) == 3 + assert cluster_budget(_cfg(cluster_locality_clusters=4, cluster_locality_budget=9)) == 4 + assert cluster_budget(_cfg(cluster_locality_objective="mutual_info")) == 0 + assert cluster_budget(SimpleNamespace(num_experts=E, num_experts_per_tok=2)) == 0 # predates the fields + for bad in (dict(cluster_locality_objective="x"), dict(cluster_locality_mass="x"), dict(cluster_locality_budget=-1)): + with pytest.raises(ValueError): + ChronosConfig(**bad) + assert ChronosConfig(cluster_input_detach=False).cluster_input_detach is False + assert ChronosConfig(cluster_input_detach=None).cluster_input_detach is True + + +def test_fields_survive_the_schema(): + from chronos.config_schema import MODEL_FIELDS, model_config_kwargs + raw = dict(cluster_locality_objective="mutual_info", cluster_locality_budget=3, cluster_locality_mass="soft", + cluster_input_detach=False) + assert set(raw) <= set(MODEL_FIELDS) + kept = model_config_kwargs(raw) + assert all(kept[k] == v for k, v in raw.items()) + + +def test_pre_035_checkpoint_keeps_the_old_objective(tmp_path): + from chronos.model.checkpoint import checkpoint_config_path, read_checkpoint_config + ckpt = str(tmp_path / "model.pth") + old = {"num_experts": E, "lambda_cluster_locality": 0.3, "recurrent_enabled": True} + with open(checkpoint_config_path(ckpt), "w") as fh: + json.dump({"config": old, "checkpoint_config_version": 2}, fh) + cfg, _ = read_checkpoint_config(ckpt) + assert (cfg["cluster_locality_objective"], cfg["cluster_locality_mass"], cfg["cluster_input_detach"]) == ( + "mutual_info", "soft", False) + new = dict(old, cluster_locality_objective="budget") + with open(checkpoint_config_path(ckpt), "w") as fh: + json.dump({"config": new, "checkpoint_config_version": 2}, fh) + cfg, _ = read_checkpoint_config(ckpt) + assert cfg["cluster_locality_objective"] == "budget" and "cluster_input_detach" not in cfg + + +def test_budget_is_balance_plus_spill(): + r, memb = _router(3), _membership(4) + pw = _window_pw(r, memb, 8) + marg = pw.mean(axis=0) + balance = 1.0 + float((marg * np.log(marg)).sum()) / np.log(4) + for budget in (1, 2, 3, 4): + spill = float((1.0 - np.sort(pw, axis=-1)[:, -budget:].sum(axis=-1)).mean()) + got = float(cluster_locality_loss(torch.tensor(r), torch.tensor(memb), 8, budget=budget)) + assert got == pytest.approx(balance + spill, abs=1e-5) + assert float(cluster_locality_loss(torch.tensor(r), torch.tensor(memb), 8, budget=4)) == pytest.approx(balance, abs=1e-5) + + +def test_budget_leaves_the_split_inside_the_resident_clusters_free(): + memb = _membership(4) + r = np.zeros((2, 16, 3, E), np.float32) + for b in range(2): + for w in range(2): + pair = (0, 1) if (b + w) % 2 == 0 else (2, 3) + experts = [e for e in range(E) if e * 4 // E in pair] + r[b, w * 8:(w + 1) * 8, :, experts] = 1.0 / len(experts) + rt = torch.tensor(r) + assert float(cluster_locality_loss(rt, torch.tensor(memb), 8, budget=2)) == pytest.approx(0.0, abs=1e-5) + assert float(cluster_locality_loss(rt, torch.tensor(memb), 8)) == pytest.approx(0.5, abs=1e-4) # mutual info + assert float(cluster_locality_loss(rt, torch.tensor(memb), 8, budget=1)) == pytest.approx(0.5, abs=1e-5) + + +@pytest.mark.parametrize("detach", [False, True]) +def test_torch_detach_reaches_the_gate_only(detach): + from chronos.model.moe_chronos import ChronosMOEFeedForward + torch.manual_seed(0) + moe = ChronosMOEFeedForward(_cfg(cluster_input_detach=detach)).train() + x = torch.randn(2, 16, 32, requires_grad=True) + moe(x) + probs = moe.iteration_cluster_probs_grad if detach else moe.iteration_router_probs_grad + assert len(probs) == 1 + loss = cluster_locality_loss(torch.stack(probs, dim=2), torch.tensor(_membership(3)), 8, budget=2) + gate, gx = torch.autograd.grad(loss, [moe.gate.weight, x], allow_unused=True) + assert float(gate.abs().sum()) > 0.0 + assert (gx is None or float(gx.abs().sum()) == 0.0) == detach + moe.reset_iteration_routing() + moe.eval() + with torch.no_grad(): + moe(torch.randn(1, 4, 32)) + assert moe.iteration_cluster_probs_grad == [] # recorded in training only + + +def test_torch_cluster_source_reads_the_detached_dispatch_mass(): + from chronos.model.moe_chronos import ChronosMOEFeedForward + from chronos.trainer.loss_mixin import cluster_source_probs + torch.manual_seed(0) + cfg = _cfg() + moe = ChronosMOEFeedForward(cfg).train() + x = torch.randn(2, 16, 32, requires_grad=True) + moe(x) + router = torch.stack(moe.iteration_router_probs_grad, dim=2) + model = SimpleNamespace(model=SimpleNamespace(layers=[SimpleNamespace(mlp=moe)])) + src = cluster_source_probs(model, cfg, router) + assert torch.allclose(src, dispatch_mass(router, 2), atol=1e-6) + assert ((src > 0).sum(-1) == 2).all() + loss = cluster_locality_loss(src, torch.tensor(_membership(3)), 8, budget=cluster_budget(cfg)) + gate, gx = torch.autograd.grad(loss, [moe.gate.weight, x], allow_unused=True) + assert float(gate.abs().sum()) > 0.0 and gx is None + assert cluster_source_probs(model, _cfg(cluster_input_detach=False, cluster_locality_mass="soft"), router) is router + + +def test_mlx_dispatch_mass_and_budget_match_torch(mx): + from chronos.mlx.training.trainer import _cluster_locality_loss, _dispatch_mass, _segment_cluster_loss + r = _router(2) + assert np.allclose(dispatch_mass(torch.tensor(r), 2).numpy(), np.array(_dispatch_mass(mx.array(r), 2)), atol=1e-6) + memb = _membership(4) + seg = np.array([[0] * 8 + [1] * 8, [0] * 5 + [1] * 11]) + mask = np.ones((2, 16), np.float32) + mask[1, 14:] = 0.0 + for budget in (1, 2, 3, 4): + t_win = float(cluster_locality_loss(torch.tensor(r), torch.tensor(memb), 8, budget=budget)) + m_win = float(_cluster_locality_loss(mx.array(r), mx.array(memb), 8, None, budget=budget)) + m_ones = float(_cluster_locality_loss(mx.array(r), mx.array(memb), 8, mx.ones((2, 16)), budget=budget)) + t_seg = float(segment_cluster_loss(torch.tensor(r), torch.tensor(memb), seg, torch.tensor(mask), budget=budget)) + m_seg = float(_segment_cluster_loss(mx.array(r), mx.array(memb), mx.array(seg), mx.array(mask), budget=budget)) + assert t_win == pytest.approx(m_win, abs=1e-5) + assert m_ones == pytest.approx(m_win, abs=1e-5) + assert t_seg == pytest.approx(m_seg, abs=1e-5) + + +@pytest.mark.parametrize("detach", [False, True]) +def test_mlx_objective_reads_the_detached_gate(mx, detach): + from chronos.mlx.moe import ChronosMLXMOE + from chronos.mlx.training.trainer import _cluster_locality_loss, _cluster_membership, _cluster_objective, _dispatch_mass + cfg = _cfg(cluster_input_detach=detach) + mx.random.seed(0) + moe = ChronosMLXMOE(cfg) + moe.train() + model = SimpleNamespace(layers=[SimpleNamespace(mlp=moe)]) + x = mx.random.normal((2, 16, 32)) + + def f(params, x): + moe.update(params) + moe.reset_iteration_routing() + y = moe(x) + router = mx.stack(moe.iteration_router_probs, axis=2) + return _cluster_objective(router, cfg, None, None, model) + 0.0 * y.sum() + + value = f(moe.trainable_parameters(), x) + router = mx.stack(moe.iteration_router_probs, axis=2) + want = _cluster_locality_loss(_dispatch_mass(router, 2), _cluster_membership(cfg), 8, None, budget=cluster_budget(cfg)) + assert float(value) == pytest.approx(float(want), abs=1e-5) + assert len(moe.iteration_cluster_probs) == (1 if detach else 0) + gp, gx = mx.grad(f, argnums=(0, 1))(moe.trainable_parameters(), x) + assert float(mx.abs(gp["gate"]["weight"]).sum()) > 0.0 + assert (float(mx.abs(gx).sum()) == 0.0) == detach + + +def test_mlx_mutual_info_soft_attached_is_the_034_objective(mx): + from chronos.mlx.training.trainer import _cluster_locality_loss, _cluster_membership, _cluster_objective + cfg = _cfg(cluster_locality_objective="mutual_info", cluster_locality_mass="soft", cluster_input_detach=False) + r = mx.array(_router(4)) + want = float(_cluster_locality_loss(r, _cluster_membership(cfg), 8)) + assert float(_cluster_objective(r, cfg)) == pytest.approx(want, abs=1e-6) + assert float(_cluster_objective(r, _cfg())) != pytest.approx(want, abs=1e-4) + + +@pytest.mark.parametrize("mode,recompute", [("window", False), ("segment", False), ("window", True)]) +def test_mlx_compiled_step_matches_eager_with_the_035_defaults(mx, mode, recompute): + """The gate-only record is read inside the compiled (and recomputed) step; loss and gradients match eager.""" + import mlx.nn as nn + from mlx.utils import tree_flatten + from chronos.mlx.model import ChronosMLXModel + from chronos.mlx.training.compiled import make_grad_fn + from chronos.mlx.training.trainer import _ce_stage_loss + cfg = ChronosConfig(architecture_version=3, hidden_size=64, num_hidden_layers=4, prelude_layers=1, coda_layers=1, + recurrent_depth=3, min_recurrent_depth=2, num_attention_heads=4, num_key_value_heads=2, kv_latent_dim=16, + rope_dim=8, num_experts=6, num_experts_per_tok=2, num_shared_experts=1, moe_intermediate_size=32, + vocab_size=97, max_position_embeddings=128, sliding_window_size=8, dropout=0.0, fallback_mask_prob=0.0, + adaptive_halting=True, lookahead_steps=2, layer_aware_lookahead=True, lambda_cluster_locality=0.5, + cluster_locality_window=8, cluster_locality_mode=mode, activation_checkpointing=recompute) + assert cluster_budget(cfg) == 1 and cfg.cluster_input_detach + mx.random.seed(1) + ids = mx.random.randint(3, cfg.vocab_size, (2, 40)) + ids = mx.where(mx.arange(40)[None, :] % 11 == 10, 0, ids) + labels = mx.random.randint(3, cfg.vocab_size, (2, 40)) + + def build(): + mx.random.seed(0) + model = ChronosMLXModel(cfg) + mx.eval(model.parameters()) + model.train() + return model + + model = build() + eager_loss, eager_grads = nn.value_and_grad(model, _ce_stage_loss)(model, ids, labels) + mx.eval(eager_loss, eager_grads) + want = dict(tree_flatten(eager_grads)) + model2 = build() + step = make_grad_fn(model2, _ce_stage_loss, mode="on", log=lambda m: None) + loss, grads = step(model2, ids, labels) + mx.eval(loss, grads) + assert step.stats["compiled"] == 1 and step.stats["eager"] == 0 + assert abs(loss.item() - eager_loss.item()) < 1e-4 + for name, g in dict(tree_flatten(grads)).items(): + denom = float(mx.maximum(mx.abs(want[name]).max(), 1e-12).item()) + assert float(mx.abs(g - want[name]).max().item()) / denom < 1e-3, name + assert model2._last_loss_components["cluster_locality_loss"].item() > 0.0