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
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pure deterministic scheduling helpers for the frozen Fable router curriculum."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import random
|
| 9 |
+
from typing import Any, Iterable
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def canonical_seed(*parts: object) -> int:
|
| 13 |
+
payload = json.dumps(parts, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
| 14 |
+
return int.from_bytes(hashlib.sha256(payload).digest()[:8], "big")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def linear_anneal(initial: float, final: float, step: int, anneal_steps: int) -> float:
|
| 18 |
+
if anneal_steps <= 0:
|
| 19 |
+
return float(final)
|
| 20 |
+
progress = min(max(int(step), 0), int(anneal_steps)) / float(anneal_steps)
|
| 21 |
+
return float(initial) + (float(final) - float(initial)) * progress
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def benefit_margin(step: int, final_margin: float = 0.02) -> float:
|
| 25 |
+
if step <= 100:
|
| 26 |
+
return 0.0
|
| 27 |
+
return linear_anneal(0.0, final_margin, step - 100, 200)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def route_cost_multiplier(step: int) -> float:
|
| 31 |
+
if step < 100:
|
| 32 |
+
return 0.0
|
| 33 |
+
return linear_anneal(0.0, 1.0, step - 100, 200)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass(frozen=True)
|
| 37 |
+
class StagePosition:
|
| 38 |
+
name: str
|
| 39 |
+
global_step: int
|
| 40 |
+
stage_step: int
|
| 41 |
+
stage_start: int
|
| 42 |
+
stage_end: int
|
| 43 |
+
router_scale_maximum: float
|
| 44 |
+
loop_negative_ratio: float
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def stage_position(curriculum: dict[str, Any], global_step: int) -> StagePosition:
|
| 48 |
+
if global_step < 0:
|
| 49 |
+
raise ValueError("global step must be non-negative")
|
| 50 |
+
start = 0
|
| 51 |
+
for stage in curriculum["curriculum"]:
|
| 52 |
+
end = start + int(stage["steps"])
|
| 53 |
+
if global_step < end:
|
| 54 |
+
return StagePosition(
|
| 55 |
+
name=str(stage["stage"]),
|
| 56 |
+
global_step=global_step,
|
| 57 |
+
stage_step=global_step - start,
|
| 58 |
+
stage_start=start,
|
| 59 |
+
stage_end=end,
|
| 60 |
+
router_scale_maximum=float(stage["routerScaleMaximum"]),
|
| 61 |
+
loop_negative_ratio=float(stage.get("loopNegativeRatio", 0.0)),
|
| 62 |
+
)
|
| 63 |
+
start = end
|
| 64 |
+
raise IndexError(f"global step {global_step} is outside the frozen {start}-step curriculum")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _mixture_counts(stage: dict[str, Any]) -> dict[str, int]:
|
| 68 |
+
steps = int(stage["steps"])
|
| 69 |
+
raw = {str(lane): float(weight) * steps for lane, weight in stage["mixture"].items()}
|
| 70 |
+
counts = {lane: int(value) for lane, value in raw.items()}
|
| 71 |
+
remainder = steps - sum(counts.values())
|
| 72 |
+
order = sorted(raw, key=lambda lane: (-(raw[lane] - counts[lane]), lane))
|
| 73 |
+
for lane in order[:remainder]:
|
| 74 |
+
counts[lane] += 1
|
| 75 |
+
if sum(counts.values()) != steps:
|
| 76 |
+
raise RuntimeError("stage mixture did not resolve to the exact declared step count")
|
| 77 |
+
return counts
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def frozen_lane_schedule(curriculum: dict[str, Any], seed: int) -> list[str]:
|
| 81 |
+
schedule: list[str] = []
|
| 82 |
+
for stage_index, stage in enumerate(curriculum["curriculum"]):
|
| 83 |
+
stage_rows = [lane for lane, count in _mixture_counts(stage).items() for _ in range(count)]
|
| 84 |
+
random.Random(canonical_seed(seed, stage_index, stage["stage"])).shuffle(stage_rows)
|
| 85 |
+
schedule.extend(stage_rows)
|
| 86 |
+
return schedule
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class ExpertCoverageSchedule:
|
| 90 |
+
"""Yield four independent local expert candidates while covering every layer/bank row.
|
| 91 |
+
|
| 92 |
+
One eligible step probes exactly one source layer. Layers are visited round-robin.
|
| 93 |
+
Eight visits cover all 32 selected experts in that layer. Later 240-step cycles use
|
| 94 |
+
a new deterministic permutation, preserving exploration without changing cardinality.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, layers: int = 30, experts_per_layer: int = 32,
|
| 98 |
+
candidates_per_step: int = 4, seed: int = 0):
|
| 99 |
+
if layers <= 0 or experts_per_layer <= 0 or candidates_per_step <= 0:
|
| 100 |
+
raise ValueError("coverage dimensions must be positive")
|
| 101 |
+
if experts_per_layer % candidates_per_step:
|
| 102 |
+
raise ValueError("experts per layer must be divisible by candidates per step")
|
| 103 |
+
self.layers = int(layers)
|
| 104 |
+
self.experts_per_layer = int(experts_per_layer)
|
| 105 |
+
self.candidates_per_step = int(candidates_per_step)
|
| 106 |
+
self.visits_per_layer = self.experts_per_layer // self.candidates_per_step
|
| 107 |
+
self.steps_per_cycle = self.layers * self.visits_per_layer
|
| 108 |
+
self.seed = int(seed)
|
| 109 |
+
|
| 110 |
+
def probe(self, eligible_step: int) -> tuple[int, list[int]]:
|
| 111 |
+
if eligible_step < 0:
|
| 112 |
+
raise ValueError("eligible step must be non-negative")
|
| 113 |
+
cycle, within = divmod(int(eligible_step), self.steps_per_cycle)
|
| 114 |
+
layer = within % self.layers
|
| 115 |
+
visit = within // self.layers
|
| 116 |
+
order = list(range(self.experts_per_layer))
|
| 117 |
+
random.Random(canonical_seed(self.seed, cycle, layer)).shuffle(order)
|
| 118 |
+
start = visit * self.candidates_per_step
|
| 119 |
+
candidates = order[start:start + self.candidates_per_step]
|
| 120 |
+
if len(candidates) != self.candidates_per_step or len(set(candidates)) != len(candidates):
|
| 121 |
+
raise RuntimeError("coverage scheduler emitted an invalid candidate set")
|
| 122 |
+
return layer, candidates
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class PositiveReplayBuffer:
|
| 126 |
+
"""Bounded, serializable positive-benefit replay with deterministic sampling."""
|
| 127 |
+
|
| 128 |
+
def __init__(self, maximum: int = 4096):
|
| 129 |
+
if maximum <= 0:
|
| 130 |
+
raise ValueError("replay maximum must be positive")
|
| 131 |
+
self.maximum = int(maximum)
|
| 132 |
+
self.rows: list[dict[str, Any]] = []
|
| 133 |
+
|
| 134 |
+
def add(self, rows: Iterable[dict[str, Any]]) -> None:
|
| 135 |
+
for row in rows:
|
| 136 |
+
required = {"rowId", "lane", "layer", "expert", "token", "benefitNats"}
|
| 137 |
+
if set(row) < required:
|
| 138 |
+
raise ValueError(f"replay row is missing fields: {sorted(required - set(row))}")
|
| 139 |
+
if float(row["benefitNats"]) <= 0:
|
| 140 |
+
continue
|
| 141 |
+
self.rows.append(dict(row))
|
| 142 |
+
if len(self.rows) > self.maximum:
|
| 143 |
+
del self.rows[:len(self.rows) - self.maximum]
|
| 144 |
+
|
| 145 |
+
def sample(self, seed: int, count: int = 1) -> list[dict[str, Any]]:
|
| 146 |
+
if count <= 0 or not self.rows:
|
| 147 |
+
return []
|
| 148 |
+
rng = random.Random(canonical_seed(seed, len(self.rows), count))
|
| 149 |
+
indices = list(range(len(self.rows)))
|
| 150 |
+
rng.shuffle(indices)
|
| 151 |
+
return [dict(self.rows[index]) for index in indices[:min(count, len(indices))]]
|
| 152 |
+
|
| 153 |
+
def state_dict(self) -> dict[str, Any]:
|
| 154 |
+
return {"maximum": self.maximum, "rows": self.rows}
|
| 155 |
+
|
| 156 |
+
@classmethod
|
| 157 |
+
def from_state_dict(cls, state: dict[str, Any]) -> "PositiveReplayBuffer":
|
| 158 |
+
buffer = cls(int(state["maximum"]))
|
| 159 |
+
buffer.rows = [dict(row) for row in state.get("rows", [])][-buffer.maximum:]
|
| 160 |
+
return buffer
|
training/run_fable_router_optimizer_smoke.py
CHANGED
|
@@ -195,8 +195,31 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 195 |
if not torch.isfinite(total):
|
| 196 |
raise RuntimeError("optimizer smoke produced a non-finite objective")
|
| 197 |
total.backward()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
grad_norm = float(torch.nn.utils.clip_grad_norm_(parameters, float(optimizer_contract["gradientClipNorm"])))
|
| 199 |
optimizer.step()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
metrics.append({
|
| 201 |
"step": step,
|
| 202 |
"lane": row["lane"],
|
|
@@ -207,22 +230,32 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 207 |
"totalLoss": float(total.detach()),
|
| 208 |
"gradientNorm": grad_norm,
|
| 209 |
"discovery": discovery,
|
|
|
|
|
|
|
| 210 |
})
|
|
|
|
| 211 |
del batch, host_logits, routed
|
| 212 |
|
| 213 |
if not positive_and_off:
|
| 214 |
raise RuntimeError("counterfactual optimizer smoke did not produce both expert and host-only targets")
|
| 215 |
after_state = router_state_dict(model)
|
| 216 |
changed_layers = []
|
|
|
|
| 217 |
for layer in range(30):
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
| 220 |
changed_layers.append(layer)
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
maximum_scale = max(float(F.softplus(block.expert_scale).detach()) for block in blocks)
|
| 224 |
-
if maximum_scale > 0.0250001:
|
| 225 |
-
raise RuntimeError(f"Stage A expert scale exceeded 0.025: {maximum_scale}")
|
| 226 |
|
| 227 |
output = Path(result["output"])
|
| 228 |
checkpoint = output / "router-checkpoint.safetensors"
|
|
@@ -230,7 +263,11 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 230 |
save_file(after_state, str(checkpoint), metadata={"autonoma": "non-routing-optimizer-smoke", "bank": args.bank})
|
| 231 |
torch.save({"optimizer": optimizer.state_dict(), "completedSteps": 2, "bank": args.bank}, optimizer_path)
|
| 232 |
result["steps"] = metrics
|
| 233 |
-
result["updateGate"] = {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
result["checkpoint"] = {"path": str(checkpoint), "bytes": checkpoint.stat().st_size, "sha256": sha256(checkpoint)}
|
| 235 |
result["optimizerCheckpoint"] = {"path": str(optimizer_path), "bytes": optimizer_path.stat().st_size, "sha256": sha256(optimizer_path)}
|
| 236 |
result["runtime"] = {
|
|
@@ -239,6 +276,10 @@ def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
|
| 239 |
"peakReservedVramMiB": torch.cuda.max_memory_reserved(device) / 2**20,
|
| 240 |
"computeDtype": str(dtype),
|
| 241 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
result["gates"] = {gate: True for gate in optimizer_contract["requiredGates"]}
|
| 243 |
|
| 244 |
|
|
|
|
| 195 |
if not torch.isfinite(total):
|
| 196 |
raise RuntimeError("optimizer smoke produced a non-finite objective")
|
| 197 |
total.backward()
|
| 198 |
+
layer_gradients = []
|
| 199 |
+
for layer, block in enumerate(blocks):
|
| 200 |
+
gate_grad = block.router.gate.weight.grad
|
| 201 |
+
scale_grad = block.expert_scale.grad
|
| 202 |
+
layer_gradients.append({
|
| 203 |
+
"layer": layer,
|
| 204 |
+
"gateGradientPresent": gate_grad is not None,
|
| 205 |
+
"gateGradientL1": float(gate_grad.float().abs().sum()) if gate_grad is not None else 0.0,
|
| 206 |
+
"gateGradientMaxAbs": float(gate_grad.float().abs().max()) if gate_grad is not None else 0.0,
|
| 207 |
+
"gateGradientNonzero": int(torch.count_nonzero(gate_grad)) if gate_grad is not None else 0,
|
| 208 |
+
"scaleGradientPresent": scale_grad is not None,
|
| 209 |
+
"scaleGradientAbs": float(scale_grad.float().abs()) if scale_grad is not None else 0.0,
|
| 210 |
+
})
|
| 211 |
+
step_before = [block.router.gate.weight.detach().cpu().clone() for block in blocks]
|
| 212 |
grad_norm = float(torch.nn.utils.clip_grad_norm_(parameters, float(optimizer_contract["gradientClipNorm"])))
|
| 213 |
optimizer.step()
|
| 214 |
+
layer_updates = []
|
| 215 |
+
for layer, (block, previous) in enumerate(zip(blocks, step_before, strict=True)):
|
| 216 |
+
delta = (block.router.gate.weight.detach().cpu() - previous).abs()
|
| 217 |
+
layer_updates.append({
|
| 218 |
+
"layer": layer,
|
| 219 |
+
"gateUpdateL1": float(delta.sum()),
|
| 220 |
+
"gateUpdateMaxAbs": float(delta.max()),
|
| 221 |
+
"gateUpdateNonzero": int(torch.count_nonzero(delta)),
|
| 222 |
+
})
|
| 223 |
metrics.append({
|
| 224 |
"step": step,
|
| 225 |
"lane": row["lane"],
|
|
|
|
| 230 |
"totalLoss": float(total.detach()),
|
| 231 |
"gradientNorm": grad_norm,
|
| 232 |
"discovery": discovery,
|
| 233 |
+
"layerGradients": layer_gradients,
|
| 234 |
+
"layerUpdates": layer_updates,
|
| 235 |
})
|
| 236 |
+
result["steps"] = metrics
|
| 237 |
del batch, host_logits, routed
|
| 238 |
|
| 239 |
if not positive_and_off:
|
| 240 |
raise RuntimeError("counterfactual optimizer smoke did not produce both expert and host-only targets")
|
| 241 |
after_state = router_state_dict(model)
|
| 242 |
changed_layers = []
|
| 243 |
+
update_diagnostics = []
|
| 244 |
for layer in range(30):
|
| 245 |
+
gate_key = f"model.layers.{layer}.expert_block.router.gate.weight"
|
| 246 |
+
scale_key = f"model.layers.{layer}.expert_block.expert_scale"
|
| 247 |
+
gate_delta = (after_state[gate_key] - before_state[gate_key]).abs()
|
| 248 |
+
scale_delta = (after_state[scale_key] - before_state[scale_key]).abs()
|
| 249 |
+
if torch.count_nonzero(gate_delta):
|
| 250 |
changed_layers.append(layer)
|
| 251 |
+
update_diagnostics.append({
|
| 252 |
+
"layer": layer,
|
| 253 |
+
"gateUpdateL1": float(gate_delta.sum()),
|
| 254 |
+
"gateUpdateMaxAbs": float(gate_delta.max()),
|
| 255 |
+
"gateUpdateNonzero": int(torch.count_nonzero(gate_delta)),
|
| 256 |
+
"scaleUpdateAbs": float(scale_delta),
|
| 257 |
+
})
|
| 258 |
maximum_scale = max(float(F.softplus(block.expert_scale).detach()) for block in blocks)
|
|
|
|
|
|
|
| 259 |
|
| 260 |
output = Path(result["output"])
|
| 261 |
checkpoint = output / "router-checkpoint.safetensors"
|
|
|
|
| 263 |
save_file(after_state, str(checkpoint), metadata={"autonoma": "non-routing-optimizer-smoke", "bank": args.bank})
|
| 264 |
torch.save({"optimizer": optimizer.state_dict(), "completedSteps": 2, "bank": args.bank}, optimizer_path)
|
| 265 |
result["steps"] = metrics
|
| 266 |
+
result["updateGate"] = {
|
| 267 |
+
"changedRouterLayers": changed_layers,
|
| 268 |
+
"maximumExpertScale": maximum_scale,
|
| 269 |
+
"layerDiagnostics": update_diagnostics,
|
| 270 |
+
}
|
| 271 |
result["checkpoint"] = {"path": str(checkpoint), "bytes": checkpoint.stat().st_size, "sha256": sha256(checkpoint)}
|
| 272 |
result["optimizerCheckpoint"] = {"path": str(optimizer_path), "bytes": optimizer_path.stat().st_size, "sha256": sha256(optimizer_path)}
|
| 273 |
result["runtime"] = {
|
|
|
|
| 276 |
"peakReservedVramMiB": torch.cuda.max_memory_reserved(device) / 2**20,
|
| 277 |
"computeDtype": str(dtype),
|
| 278 |
}
|
| 279 |
+
if changed_layers != list(range(30)):
|
| 280 |
+
raise RuntimeError(f"not every router gate updated: {changed_layers}")
|
| 281 |
+
if maximum_scale > 0.0250001:
|
| 282 |
+
raise RuntimeError(f"Stage A expert scale exceeded 0.025: {maximum_scale}")
|
| 283 |
result["gates"] = {gate: True for gate in optimizer_contract["requiredGates"]}
|
| 284 |
|
| 285 |
|
training/run_fable_router_stage_a_chunk.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run one resumable, non-routing Stage-A chunk for a frozen Fable donor bank."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from collections import Counter
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import platform
|
| 10 |
+
import random
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
import traceback
|
| 14 |
+
from datetime import datetime, timezone
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn.functional as F
|
| 20 |
+
from safetensors.torch import load_file, save_file
|
| 21 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 22 |
+
|
| 23 |
+
HERE = Path(__file__).resolve().parent
|
| 24 |
+
if str(HERE) not in sys.path:
|
| 25 |
+
sys.path.insert(0, str(HERE))
|
| 26 |
+
|
| 27 |
+
from fable_router_common import iter_jsonl, read_json, selected_expert_ids, sha256, validate_bank_header, validate_curriculum_row, verify_file
|
| 28 |
+
from fable_router_hybrid import (
|
| 29 |
+
FrozenExpertRouterBlock,
|
| 30 |
+
assert_trainable_isolation,
|
| 31 |
+
attach_router_block,
|
| 32 |
+
benefit_targets,
|
| 33 |
+
benefit_weighted_router_loss,
|
| 34 |
+
freeze_except_routers,
|
| 35 |
+
load_router_state_dict,
|
| 36 |
+
router_state_dict,
|
| 37 |
+
)
|
| 38 |
+
from fable_router_training_schedule import (
|
| 39 |
+
ExpertCoverageSchedule,
|
| 40 |
+
PositiveReplayBuffer,
|
| 41 |
+
benefit_margin,
|
| 42 |
+
canonical_seed,
|
| 43 |
+
frozen_lane_schedule,
|
| 44 |
+
linear_anneal,
|
| 45 |
+
route_cost_multiplier,
|
| 46 |
+
stage_position,
|
| 47 |
+
)
|
| 48 |
+
from run_fable_router_full_bank_fit import download, verify_authorization
|
| 49 |
+
from run_fable_router_structural_smoke import compute_dtype, gpu_facts, render_and_tokenize, token_nll
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
SEED = 20260810
|
| 53 |
+
MAXIMUM_TOKENS = 2048
|
| 54 |
+
MAXIMUM_CHUNK_STEPS = 25
|
| 55 |
+
LEARNING_RATE = 2e-4
|
| 56 |
+
GRADIENT_CLIP = 1.0
|
| 57 |
+
REPLAY_MAXIMUM = 4096
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def now() -> str:
|
| 61 |
+
return datetime.now(timezone.utc).isoformat()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def set_blocks(blocks: list[FrozenExpertRouterBlock], enabled: bool) -> None:
|
| 65 |
+
for block in blocks:
|
| 66 |
+
block.enabled = enabled
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def assistant_supervision(tokenizer: Any, messages: list[dict[str, Any]]) -> tuple[list[int], list[int]]:
|
| 70 |
+
"""Create assistant-only labels while requiring a prefix-stable chat template."""
|
| 71 |
+
input_ids: list[int] = []
|
| 72 |
+
labels: list[int] = []
|
| 73 |
+
for index, message in enumerate(messages):
|
| 74 |
+
rendered = render_and_tokenize(tokenizer, messages[:index + 1])
|
| 75 |
+
if rendered[:len(input_ids)] != input_ids:
|
| 76 |
+
raise RuntimeError("chat template is not prefix-stable; assistant masking would be ambiguous")
|
| 77 |
+
added = rendered[len(input_ids):]
|
| 78 |
+
input_ids.extend(added)
|
| 79 |
+
supervised = str(message.get("role")) == "assistant"
|
| 80 |
+
labels.extend(added if supervised else [-100] * len(added))
|
| 81 |
+
if len(input_ids) != len(labels) or not any(label != -100 for label in labels):
|
| 82 |
+
raise RuntimeError("curriculum row produced no unambiguous assistant supervision")
|
| 83 |
+
return input_ids, labels
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_row_pools(path: Path, tokenizer: Any) -> dict[str, list[dict[str, Any]]]:
|
| 87 |
+
pools = {lane: [] for lane in ("host_preservation", "verified_expert", "interaction_pattern")}
|
| 88 |
+
for row in iter_jsonl(path):
|
| 89 |
+
validate_curriculum_row(row, "train")
|
| 90 |
+
lane = str(row["lane"])
|
| 91 |
+
input_ids, labels = assistant_supervision(tokenizer, row["messages"])
|
| 92 |
+
if len(input_ids) > MAXIMUM_TOKENS:
|
| 93 |
+
raise RuntimeError(f"frozen curriculum row exceeds {MAXIMUM_TOKENS} tokens after template: {row['id']}")
|
| 94 |
+
pools[lane].append({"id": str(row["id"]), "lane": lane, "inputIds": input_ids, "labels": labels})
|
| 95 |
+
for lane, rows in pools.items():
|
| 96 |
+
if not rows:
|
| 97 |
+
raise RuntimeError(f"frozen curriculum has no rows for lane {lane}")
|
| 98 |
+
random.Random(canonical_seed(SEED, "rows", lane)).shuffle(rows)
|
| 99 |
+
return pools
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def scheduled_rows(pools: dict[str, list[dict[str, Any]]], schedule: list[str], start: int, end: int) -> list[dict[str, Any]]:
|
| 103 |
+
offsets = Counter(schedule[:start])
|
| 104 |
+
selected = []
|
| 105 |
+
for lane in schedule[start:end]:
|
| 106 |
+
rows = pools[lane]
|
| 107 |
+
selected.append(rows[offsets[lane] % len(rows)])
|
| 108 |
+
offsets[lane] += 1
|
| 109 |
+
return selected
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def batch_row(row: dict[str, Any], device: torch.device) -> dict[str, torch.Tensor]:
|
| 113 |
+
return {
|
| 114 |
+
"input_ids": torch.tensor([row["inputIds"]], dtype=torch.long, device=device),
|
| 115 |
+
"attention_mask": torch.ones((1, len(row["inputIds"])), dtype=torch.long, device=device),
|
| 116 |
+
"labels": torch.tensor([row["labels"]], dtype=torch.long, device=device),
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def valid_shift_mask(labels: torch.Tensor) -> torch.Tensor:
|
| 121 |
+
return labels[:, 1:] != -100
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def host_baseline(model: torch.nn.Module, blocks: list[FrozenExpertRouterBlock], batch: dict[str, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
|
| 125 |
+
set_blocks(blocks, False)
|
| 126 |
+
model.eval()
|
| 127 |
+
with torch.inference_mode():
|
| 128 |
+
logits = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False).logits
|
| 129 |
+
valid = valid_shift_mask(batch["labels"])
|
| 130 |
+
host_valid = logits[:, :-1, :][valid].detach().to(device="cpu", dtype=torch.float16)
|
| 131 |
+
host_nll = token_nll(logits, batch["labels"])[valid].detach().cpu()
|
| 132 |
+
del logits
|
| 133 |
+
return host_valid, host_nll
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def chunked_kl(routed_valid: torch.Tensor, host_valid_cpu: torch.Tensor, chunk_tokens: int = 32) -> torch.Tensor:
|
| 137 |
+
if routed_valid.shape != host_valid_cpu.shape:
|
| 138 |
+
raise RuntimeError(f"host/routed KL shapes differ: {routed_valid.shape} {host_valid_cpu.shape}")
|
| 139 |
+
total = torch.zeros((), dtype=torch.float32, device=routed_valid.device)
|
| 140 |
+
for start in range(0, routed_valid.shape[0], chunk_tokens):
|
| 141 |
+
routed = routed_valid[start:start + chunk_tokens].float()
|
| 142 |
+
host = host_valid_cpu[start:start + chunk_tokens].to(routed_valid.device).float()
|
| 143 |
+
total = total + F.kl_div(F.log_softmax(routed, dim=-1), F.softmax(host, dim=-1), reduction="sum")
|
| 144 |
+
return total / max(1, routed_valid.shape[0])
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def counterfactual_targets(
|
| 148 |
+
model: torch.nn.Module,
|
| 149 |
+
blocks: list[FrozenExpertRouterBlock],
|
| 150 |
+
batch: dict[str, torch.Tensor],
|
| 151 |
+
host_nll: torch.Tensor,
|
| 152 |
+
layer: int,
|
| 153 |
+
candidates: list[int],
|
| 154 |
+
scale: float,
|
| 155 |
+
margin: float,
|
| 156 |
+
) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any], list[dict[str, Any]]]:
|
| 157 |
+
candidate_losses = []
|
| 158 |
+
valid = valid_shift_mask(batch["labels"])
|
| 159 |
+
set_blocks(blocks, False)
|
| 160 |
+
blocks[layer].enabled = True
|
| 161 |
+
for candidate in candidates:
|
| 162 |
+
with blocks[layer].forced_route(candidate, scale), torch.inference_mode():
|
| 163 |
+
logits = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False).logits
|
| 164 |
+
candidate_losses.append(token_nll(logits, batch["labels"])[valid].detach().cpu())
|
| 165 |
+
del logits
|
| 166 |
+
matrix = torch.stack(candidate_losses, dim=-1)
|
| 167 |
+
column_targets = benefit_targets(host_nll, matrix, margin=margin)
|
| 168 |
+
mapped = torch.full_like(column_targets, blocks[layer].off_class_index)
|
| 169 |
+
for column, local_expert in enumerate(candidates):
|
| 170 |
+
mapped[column_targets == column] = local_expert
|
| 171 |
+
positive = mapped != blocks[layer].off_class_index
|
| 172 |
+
best_nll, _ = matrix.min(dim=-1)
|
| 173 |
+
benefits = (host_nll - best_nll).clamp_min(0)
|
| 174 |
+
replay = [
|
| 175 |
+
{
|
| 176 |
+
"rowId": "__set_by_caller__",
|
| 177 |
+
"lane": "__set_by_caller__",
|
| 178 |
+
"layer": layer,
|
| 179 |
+
"expert": int(mapped[token]),
|
| 180 |
+
"token": token,
|
| 181 |
+
"benefitNats": float(benefits[token]),
|
| 182 |
+
}
|
| 183 |
+
for token in positive.nonzero(as_tuple=False).flatten().tolist()
|
| 184 |
+
]
|
| 185 |
+
discovery = {
|
| 186 |
+
"layer": layer,
|
| 187 |
+
"candidates": candidates,
|
| 188 |
+
"scale": scale,
|
| 189 |
+
"eligibleTokens": int(mapped.numel()),
|
| 190 |
+
"positiveBenefitTokens": int(positive.sum()),
|
| 191 |
+
"hostOnlyTargets": int((~positive).sum()),
|
| 192 |
+
"meanPositiveBenefitNats": float(benefits[positive].mean()) if bool(positive.any()) else 0.0,
|
| 193 |
+
}
|
| 194 |
+
return mapped, matrix, discovery, replay
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def load_resume(args: argparse.Namespace) -> tuple[dict[str, Any] | None, PositiveReplayBuffer, int]:
|
| 198 |
+
if not args.resume_dir:
|
| 199 |
+
if args.start_step != 0:
|
| 200 |
+
raise RuntimeError("a nonzero start step requires a resume directory")
|
| 201 |
+
return None, PositiveReplayBuffer(REPLAY_MAXIMUM), 0
|
| 202 |
+
directory = args.resume_dir.resolve()
|
| 203 |
+
result = read_json(directory / "result.json")
|
| 204 |
+
state = read_json(directory / "trainer-state.json")
|
| 205 |
+
if result.get("passed") is not True or result.get("status") != "stage_a_chunk_passed_nonrouting":
|
| 206 |
+
raise RuntimeError("resume result is not a passing Stage-A chunk")
|
| 207 |
+
if str(result.get("bank")) != args.bank or int(state.get("completedSteps", -1)) != args.start_step:
|
| 208 |
+
raise RuntimeError("resume bank/step identity mismatch")
|
| 209 |
+
return state, PositiveReplayBuffer.from_state_dict(state["positiveReplay"]), int(state["eligibleSteps"])
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
| 213 |
+
campaign, config, manifest = verify_authorization(args.campaign.resolve(), result)
|
| 214 |
+
curriculum_path = args.campaign.resolve().parents[2] / campaign["frozenCurriculum"]["path"]
|
| 215 |
+
curriculum = read_json(curriculum_path)
|
| 216 |
+
if args.bank not in campaign["selectedBanks"]["ids"]:
|
| 217 |
+
raise RuntimeError("bank is outside the frozen authorized set")
|
| 218 |
+
if args.steps <= 0 or args.steps > MAXIMUM_CHUNK_STEPS:
|
| 219 |
+
raise RuntimeError(f"Stage-A chunks must contain 1..{MAXIMUM_CHUNK_STEPS} steps")
|
| 220 |
+
end_step = args.start_step + args.steps
|
| 221 |
+
if args.start_step < 0 or end_step > 200:
|
| 222 |
+
raise RuntimeError("this fail-closed runner is restricted to Stage A steps 0..199")
|
| 223 |
+
for step in range(args.start_step, end_step):
|
| 224 |
+
if stage_position(curriculum, step).name != "A-host-anchor":
|
| 225 |
+
raise RuntimeError("requested chunk crosses outside Stage A")
|
| 226 |
+
|
| 227 |
+
proof = read_json(args.optimizer_proof.resolve())
|
| 228 |
+
if (
|
| 229 |
+
proof.get("schema") != "AutonomaFableRouterOptimizerSmoke.v1"
|
| 230 |
+
or proof.get("passed") is not True
|
| 231 |
+
or proof.get("status") != "optimizer_smoke_passed_nonrouting"
|
| 232 |
+
or proof.get("bank") != args.bank
|
| 233 |
+
or proof.get("nonRouting") is not True
|
| 234 |
+
or proof.get("productionRoutingAuthorized") is not False
|
| 235 |
+
):
|
| 236 |
+
raise RuntimeError("bank-specific optimizer admission prerequisite is not a pass")
|
| 237 |
+
resume_state, replay, eligible_step = load_resume(args)
|
| 238 |
+
result["optimizerProof"] = {"path": str(args.optimizer_proof.resolve()), "sha256": sha256(args.optimizer_proof.resolve())}
|
| 239 |
+
result["bank"] = args.bank
|
| 240 |
+
result["range"] = {"start": args.start_step, "end": end_step, "steps": args.steps}
|
| 241 |
+
result["gpu"] = gpu_facts(14.0)
|
| 242 |
+
if result["gpu"]["name"] not in campaign["computePolicy"]["allowedAccelerators"]:
|
| 243 |
+
raise RuntimeError("Stage-A accelerator is outside the zero-cost allowlist")
|
| 244 |
+
|
| 245 |
+
banks = {row["id"]: row for row in manifest["banks"]}
|
| 246 |
+
definition = banks[args.bank]
|
| 247 |
+
token = os.environ.get("HF_TOKEN")
|
| 248 |
+
bank_cfg = config["banks"]
|
| 249 |
+
artifact = bank_cfg["artifacts"][args.bank]
|
| 250 |
+
bank_path = download(bank_cfg["repo"], bank_cfg["revision"], artifact["path"], "model", token)
|
| 251 |
+
result["bankArtifact"] = verify_file(bank_path, int(artifact["bytes"]), artifact["sha256"])
|
| 252 |
+
result["bankValidation"] = validate_bank_header(bank_path, definition).as_dict()
|
| 253 |
+
warm = bank_cfg["routerWarmstart"]
|
| 254 |
+
warm_path = download(bank_cfg["repo"], bank_cfg["revision"], warm["path"], "model", token)
|
| 255 |
+
verify_file(warm_path, int(warm["bytes"]), warm["sha256"])
|
| 256 |
+
train_cfg = config["curriculum"]["sftTrain"]
|
| 257 |
+
train_path = args.curriculum_path.resolve()
|
| 258 |
+
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 259 |
+
|
| 260 |
+
host = config["host"]
|
| 261 |
+
tokenizer = AutoTokenizer.from_pretrained(host["repo"], revision=host["revision"], token=token, trust_remote_code=True, fix_mistral_regex=True)
|
| 262 |
+
pools = load_row_pools(train_path, tokenizer)
|
| 263 |
+
lane_schedule = frozen_lane_schedule(curriculum, SEED)
|
| 264 |
+
rows = scheduled_rows(pools, lane_schedule, args.start_step, end_step)
|
| 265 |
+
result["rows"] = [{"step": args.start_step + i, "id": row["id"], "lane": row["lane"], "tokens": len(row["inputIds"])} for i, row in enumerate(rows)]
|
| 266 |
+
|
| 267 |
+
device = torch.device("cuda:0")
|
| 268 |
+
dtype = compute_dtype(result["gpu"])
|
| 269 |
+
torch.cuda.reset_peak_memory_stats(device)
|
| 270 |
+
started = time.perf_counter()
|
| 271 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 272 |
+
host["repo"], revision=host["revision"], token=token, trust_remote_code=True,
|
| 273 |
+
torch_dtype=dtype, low_cpu_mem_usage=True, attn_implementation="sdpa",
|
| 274 |
+
).to(device)
|
| 275 |
+
model.config.use_cache = False
|
| 276 |
+
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
|
| 277 |
+
model.enable_input_require_grads()
|
| 278 |
+
warm_state = load_file(str(warm_path), device="cpu")
|
| 279 |
+
blocks: list[FrozenExpertRouterBlock] = []
|
| 280 |
+
for layer in range(30):
|
| 281 |
+
block = FrozenExpertRouterBlock(selected_expert_ids(definition, layer), top_k=2, initial_scale=0.005, maximum_scale=0.025)
|
| 282 |
+
attach_router_block(model, layer, block)
|
| 283 |
+
block.router.to(device=device, dtype=torch.float32)
|
| 284 |
+
block.expert_scale.data = block.expert_scale.data.to(device=device)
|
| 285 |
+
block.materialize_experts(bank_path, layer, device=torch.device("cpu"), dtype=dtype)
|
| 286 |
+
block.load_router_warmstart(warm_state[f"layers.{layer}.router.gate.weight"])
|
| 287 |
+
block.checkpoint_enabled = True
|
| 288 |
+
blocks.append(block)
|
| 289 |
+
counts = freeze_except_routers(model)
|
| 290 |
+
names = assert_trainable_isolation(model)
|
| 291 |
+
if len(names) != 60:
|
| 292 |
+
raise RuntimeError(f"Stage-A chunk found {len(names)} trainable tensors instead of 60")
|
| 293 |
+
if resume_state is not None:
|
| 294 |
+
load_router_state_dict(model, load_file(str(args.resume_dir.resolve() / "router-checkpoint.safetensors"), device="cpu"))
|
| 295 |
+
result["trainableIsolation"] = {"counts": counts, "names": names}
|
| 296 |
+
before = router_state_dict(model)
|
| 297 |
+
parameters = [parameter for parameter in model.parameters() if parameter.requires_grad]
|
| 298 |
+
optimizer = torch.optim.AdamW(parameters, lr=LEARNING_RATE, weight_decay=0.0)
|
| 299 |
+
if resume_state is not None:
|
| 300 |
+
payload = torch.load(args.resume_dir.resolve() / "optimizer.pt", map_location="cpu", weights_only=True)
|
| 301 |
+
if int(payload.get("completedSteps", -1)) != args.start_step or payload.get("bank") != args.bank:
|
| 302 |
+
raise RuntimeError("optimizer resume identity mismatch")
|
| 303 |
+
optimizer.load_state_dict(payload["optimizer"])
|
| 304 |
+
|
| 305 |
+
coverage = ExpertCoverageSchedule(seed=SEED)
|
| 306 |
+
metrics = []
|
| 307 |
+
oracle_scales = [float(value) for value in curriculum["routingObjective"]["exploration"]["oracleProbeScales"]]
|
| 308 |
+
for offset, row in enumerate(rows):
|
| 309 |
+
global_step = args.start_step + offset
|
| 310 |
+
batch = batch_row(row, device)
|
| 311 |
+
host_valid_cpu, host_nll = host_baseline(model, blocks, batch)
|
| 312 |
+
valid = valid_shift_mask(batch["labels"])[0]
|
| 313 |
+
mapped = matrix = None
|
| 314 |
+
discovery = None
|
| 315 |
+
replay_rows: list[dict[str, Any]] = []
|
| 316 |
+
probe_layer = None
|
| 317 |
+
if row["lane"] != "host_preservation":
|
| 318 |
+
probe_layer, candidates = coverage.probe(eligible_step)
|
| 319 |
+
scale = oracle_scales[eligible_step % len(oracle_scales)]
|
| 320 |
+
mapped, matrix, discovery, replay_rows = counterfactual_targets(
|
| 321 |
+
model, blocks, batch, host_nll, probe_layer, candidates, scale, benefit_margin(global_step)
|
| 322 |
+
)
|
| 323 |
+
for replay_row in replay_rows:
|
| 324 |
+
replay_row["rowId"] = row["id"]
|
| 325 |
+
replay_row["lane"] = row["lane"]
|
| 326 |
+
replay.add(replay_rows)
|
| 327 |
+
eligible_step += 1
|
| 328 |
+
|
| 329 |
+
set_blocks(blocks, True)
|
| 330 |
+
for block in blocks:
|
| 331 |
+
block.maximum_scale = 0.025
|
| 332 |
+
model.train()
|
| 333 |
+
optimizer.zero_grad(set_to_none=True)
|
| 334 |
+
routed = model(**batch, use_cache=False)
|
| 335 |
+
routed_valid = routed.logits[:, :-1, :][valid_shift_mask(batch["labels"])]
|
| 336 |
+
kl = chunked_kl(routed_valid, host_valid_cpu)
|
| 337 |
+
ranking = off_loss = floor_loss = load_balance = torch.zeros((), device=device)
|
| 338 |
+
entropy_reward = torch.zeros((), device=device)
|
| 339 |
+
active_penalty = torch.zeros((), device=device)
|
| 340 |
+
if probe_layer is not None and mapped is not None and matrix is not None:
|
| 341 |
+
trace = blocks[probe_layer].last_trace
|
| 342 |
+
if trace is None:
|
| 343 |
+
raise RuntimeError("eligible routed forward produced no router trace")
|
| 344 |
+
logits = trace.logits[:-1][valid]
|
| 345 |
+
ranking = benefit_weighted_router_loss(logits, mapped.to(device), host_nll.to(device), matrix.to(device))
|
| 346 |
+
probabilities = torch.softmax(logits.float(), dim=-1)
|
| 347 |
+
positive = mapped.to(device) != blocks[probe_layer].off_class_index
|
| 348 |
+
if bool(positive.any()):
|
| 349 |
+
expert_probabilities = probabilities[positive, :-1]
|
| 350 |
+
expert_mass = expert_probabilities.sum(dim=-1)
|
| 351 |
+
minimum_mass = linear_anneal(0.15, 0.0, global_step, 300)
|
| 352 |
+
floor_loss = F.relu(minimum_mass - expert_mass).mean()
|
| 353 |
+
entropy = -(expert_probabilities.clamp_min(1e-9) * expert_probabilities.clamp_min(1e-9).log()).sum(dim=-1).mean()
|
| 354 |
+
entropy_reward = linear_anneal(0.01, 0.0, global_step, 300) * entropy
|
| 355 |
+
active_penalty = expert_mass.mean()
|
| 356 |
+
mean_usage = expert_probabilities.mean(dim=0)
|
| 357 |
+
load_balance = ((mean_usage - mean_usage.mean()) ** 2).mean()
|
| 358 |
+
else:
|
| 359 |
+
off_terms = []
|
| 360 |
+
for block in blocks:
|
| 361 |
+
trace = block.last_trace
|
| 362 |
+
if trace is None:
|
| 363 |
+
raise RuntimeError("host-preservation routed forward produced no router trace")
|
| 364 |
+
logits = trace.logits[:-1][valid]
|
| 365 |
+
targets = torch.full((logits.shape[0],), block.off_class_index, dtype=torch.long, device=device)
|
| 366 |
+
off_terms.append(F.cross_entropy(logits.float(), targets))
|
| 367 |
+
off_loss = torch.stack(off_terms).mean()
|
| 368 |
+
|
| 369 |
+
lane_cfg = curriculum["lanes"][row["lane"]]
|
| 370 |
+
scale_l1 = torch.stack([F.softplus(block.expert_scale).clamp(max=0.025) for block in blocks]).mean()
|
| 371 |
+
cost_multiplier = route_cost_multiplier(global_step)
|
| 372 |
+
route_cost = cost_multiplier * (0.015 * scale_l1 + 0.005 * active_penalty)
|
| 373 |
+
total = (
|
| 374 |
+
float(lane_cfg["sftWeight"]) * routed.loss
|
| 375 |
+
+ float(lane_cfg["baseFableKlWeight"]) * kl
|
| 376 |
+
+ ranking + off_loss + floor_loss
|
| 377 |
+
+ 0.01 * load_balance + route_cost - entropy_reward
|
| 378 |
+
)
|
| 379 |
+
if not torch.isfinite(total):
|
| 380 |
+
raise RuntimeError("Stage-A chunk produced a non-finite objective")
|
| 381 |
+
total.backward()
|
| 382 |
+
gradient_norm = float(torch.nn.utils.clip_grad_norm_(parameters, GRADIENT_CLIP))
|
| 383 |
+
optimizer.step()
|
| 384 |
+
maximum_scale = max(float(F.softplus(block.expert_scale).detach()) for block in blocks)
|
| 385 |
+
if maximum_scale > 0.0250001:
|
| 386 |
+
raise RuntimeError(f"Stage-A expert scale exceeded 0.025: {maximum_scale}")
|
| 387 |
+
metrics.append({
|
| 388 |
+
"step": global_step,
|
| 389 |
+
"rowId": row["id"],
|
| 390 |
+
"lane": row["lane"],
|
| 391 |
+
"tokens": len(row["inputIds"]),
|
| 392 |
+
"sftLoss": float(routed.loss.detach()),
|
| 393 |
+
"klLoss": float(kl.detach()),
|
| 394 |
+
"rankingLoss": float(ranking.detach()),
|
| 395 |
+
"offLoss": float(off_loss.detach()),
|
| 396 |
+
"routeFloorLoss": float(floor_loss.detach()),
|
| 397 |
+
"loadBalanceLoss": float(load_balance.detach()),
|
| 398 |
+
"routeCost": float(route_cost.detach()),
|
| 399 |
+
"entropyReward": float(entropy_reward.detach()),
|
| 400 |
+
"totalLoss": float(total.detach()),
|
| 401 |
+
"gradientNorm": gradient_norm,
|
| 402 |
+
"maximumExpertScale": maximum_scale,
|
| 403 |
+
"discovery": discovery,
|
| 404 |
+
})
|
| 405 |
+
del batch, host_valid_cpu, host_nll, routed, routed_valid, total
|
| 406 |
+
|
| 407 |
+
after = router_state_dict(model)
|
| 408 |
+
changed_layers = [
|
| 409 |
+
layer for layer in range(30)
|
| 410 |
+
if not torch.equal(before[f"model.layers.{layer}.expert_block.router.gate.weight"], after[f"model.layers.{layer}.expert_block.router.gate.weight"])
|
| 411 |
+
]
|
| 412 |
+
if not changed_layers:
|
| 413 |
+
raise RuntimeError("Stage-A chunk did not update any router gate")
|
| 414 |
+
output = Path(result["output"])
|
| 415 |
+
checkpoint = output / "router-checkpoint.safetensors"
|
| 416 |
+
optimizer_path = output / "optimizer.pt"
|
| 417 |
+
state_path = output / "trainer-state.json"
|
| 418 |
+
metrics_path = output / "metrics.jsonl"
|
| 419 |
+
save_file(after, str(checkpoint), metadata={"autonoma": "non-routing-stage-a", "bank": args.bank, "completedSteps": str(end_step)})
|
| 420 |
+
torch.save({"optimizer": optimizer.state_dict(), "completedSteps": end_step, "bank": args.bank}, optimizer_path)
|
| 421 |
+
state = {
|
| 422 |
+
"schema": "AutonomaFableRouterTrainerState.v1",
|
| 423 |
+
"bank": args.bank,
|
| 424 |
+
"completedSteps": end_step,
|
| 425 |
+
"eligibleSteps": eligible_step,
|
| 426 |
+
"seed": SEED,
|
| 427 |
+
"positiveReplay": replay.state_dict(),
|
| 428 |
+
}
|
| 429 |
+
state_path.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8")
|
| 430 |
+
with metrics_path.open("w", encoding="utf-8", newline="\n") as handle:
|
| 431 |
+
for metric in metrics:
|
| 432 |
+
handle.write(json.dumps(metric, separators=(",", ":")) + "\n")
|
| 433 |
+
result["metrics"] = {"path": str(metrics_path), "bytes": metrics_path.stat().st_size, "sha256": sha256(metrics_path)}
|
| 434 |
+
result["checkpoint"] = {"path": str(checkpoint), "bytes": checkpoint.stat().st_size, "sha256": sha256(checkpoint)}
|
| 435 |
+
result["optimizerCheckpoint"] = {"path": str(optimizer_path), "bytes": optimizer_path.stat().st_size, "sha256": sha256(optimizer_path)}
|
| 436 |
+
result["trainerState"] = {"path": str(state_path), "bytes": state_path.stat().st_size, "sha256": sha256(state_path)}
|
| 437 |
+
result["updateGate"] = {"changedRouterLayers": changed_layers, "positiveReplayRows": len(replay.rows), "eligibleSteps": eligible_step}
|
| 438 |
+
result["runtime"] = {
|
| 439 |
+
"seconds": time.perf_counter() - started,
|
| 440 |
+
"peakAllocatedVramMiB": torch.cuda.max_memory_allocated(device) / 2**20,
|
| 441 |
+
"peakReservedVramMiB": torch.cuda.max_memory_reserved(device) / 2**20,
|
| 442 |
+
"computeDtype": str(dtype),
|
| 443 |
+
}
|
| 444 |
+
result["gates"] = {
|
| 445 |
+
"authorized_frozen_four_bank_campaign": True,
|
| 446 |
+
"bank_specific_optimizer_admission": True,
|
| 447 |
+
"assistant_only_prefix_stable_supervision": True,
|
| 448 |
+
"complete_rows_without_truncation": True,
|
| 449 |
+
"host_and_experts_frozen": True,
|
| 450 |
+
"deterministic_lane_and_expert_coverage": True,
|
| 451 |
+
"counterfactual_off_class_and_positive_replay": True,
|
| 452 |
+
"stage_a_scale_cap": True,
|
| 453 |
+
"resumable_private_checkpoints": True,
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def main() -> int:
|
| 458 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 459 |
+
parser.add_argument("--owner-execute", action="store_true")
|
| 460 |
+
parser.add_argument("--campaign", type=Path, required=True)
|
| 461 |
+
parser.add_argument("--bank", required=True)
|
| 462 |
+
parser.add_argument("--curriculum-path", type=Path, required=True)
|
| 463 |
+
parser.add_argument("--optimizer-proof", type=Path, required=True)
|
| 464 |
+
parser.add_argument("--start-step", type=int, required=True)
|
| 465 |
+
parser.add_argument("--steps", type=int, default=MAXIMUM_CHUNK_STEPS)
|
| 466 |
+
parser.add_argument("--resume-dir", type=Path)
|
| 467 |
+
parser.add_argument("--work-dir", type=Path, default=Path("/content/autonoma-fable-training"))
|
| 468 |
+
args = parser.parse_args()
|
| 469 |
+
if not args.owner_execute:
|
| 470 |
+
raise SystemExit("refusing Stage-A execution without --owner-execute")
|
| 471 |
+
args.work_dir.mkdir(parents=True, exist_ok=True)
|
| 472 |
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 473 |
+
output = args.work_dir / f"fable-router-stage-a-{args.bank}-{args.start_step:04d}-{args.start_step + args.steps:04d}-{stamp}"
|
| 474 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 475 |
+
result: dict[str, Any] = {
|
| 476 |
+
"schema": "AutonomaFableRouterStageAChunk.v1",
|
| 477 |
+
"status": "running_nonrouting",
|
| 478 |
+
"passed": False,
|
| 479 |
+
"nonRouting": True,
|
| 480 |
+
"trainingAuthorized": True,
|
| 481 |
+
"productionRoutingAuthorized": False,
|
| 482 |
+
"startedAt": now(),
|
| 483 |
+
"output": str(output),
|
| 484 |
+
"system": {"python": sys.version, "platform": platform.platform()},
|
| 485 |
+
}
|
| 486 |
+
try:
|
| 487 |
+
run(args, result)
|
| 488 |
+
result.update(status="stage_a_chunk_passed_nonrouting", passed=True)
|
| 489 |
+
except BaseException as exc:
|
| 490 |
+
result.update(status="stage_a_chunk_failed_nonrouting", error={"type": type(exc).__name__, "message": str(exc), "traceback": traceback.format_exc()})
|
| 491 |
+
finally:
|
| 492 |
+
result["finishedAt"] = now()
|
| 493 |
+
result_path = output / "result.json"
|
| 494 |
+
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
|
| 495 |
+
print(result_path.resolve())
|
| 496 |
+
return 0 if result.get("passed") else 1
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
if __name__ == "__main__":
|
| 500 |
+
raise SystemExit(main())
|