Publish credential-free structural-smoke runner
Browse files
config/benching/fable-router-training-campaign.v1.json
CHANGED
|
@@ -94,6 +94,34 @@
|
|
| 94 |
"private_evidence_persisted_before_runtime_termination"
|
| 95 |
]
|
| 96 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
"training": {
|
| 98 |
"stages": [
|
| 99 |
{"name": "A-host-anchor", "steps": 200},
|
|
|
|
| 94 |
"private_evidence_persisted_before_runtime_termination"
|
| 95 |
]
|
| 96 |
},
|
| 97 |
+
"optimizerAdmission": {
|
| 98 |
+
"requiredBeforeStageA": true,
|
| 99 |
+
"steps": 2,
|
| 100 |
+
"learningRate": 0.0002,
|
| 101 |
+
"gradientClipNorm": 1.0,
|
| 102 |
+
"counterfactualLayer": 29,
|
| 103 |
+
"counterfactualCandidates": [0, 1, 8, 16],
|
| 104 |
+
"counterfactualScale": 0.025,
|
| 105 |
+
"memoryProof": {
|
| 106 |
+
"path": "downloads/audits/fable-router-full-bank-training-memory-proof/result.json",
|
| 107 |
+
"sha256": "64de6936e05e9f1d24df325fc1c2bf2bbb2e5109a45f888e940e3d366adce706",
|
| 108 |
+
"privateRepo": "Swordnael/LFM2.5-Fable-Router-Smoke-Evidence",
|
| 109 |
+
"privateCommit": "939142a74bdf42cfdebb304f1990c1883ae4f9e5",
|
| 110 |
+
"requiredStatus": "training_memory_admission_passed_nonrouting"
|
| 111 |
+
},
|
| 112 |
+
"privateResultRepo": "Swordnael/LFM2.5-Fable-Router-Smoke-Evidence",
|
| 113 |
+
"requiredGates": [
|
| 114 |
+
"training_memory_proof_identity",
|
| 115 |
+
"host_and_all_experts_frozen",
|
| 116 |
+
"host_preservation_and_verified_expert_rows_complete",
|
| 117 |
+
"four_independent_counterfactual_candidates",
|
| 118 |
+
"positive_benefit_and_host_only_targets_present",
|
| 119 |
+
"finite_sft_kl_ranking_and_route_cost_losses",
|
| 120 |
+
"all_30_router_gates_updated",
|
| 121 |
+
"expert_scales_bounded_by_stage_a_maximum",
|
| 122 |
+
"router_and_optimizer_checkpoint_persisted_privately"
|
| 123 |
+
]
|
| 124 |
+
},
|
| 125 |
"training": {
|
| 126 |
"stages": [
|
| 127 |
{"name": "A-host-anchor", "steps": 200},
|
training/run_fable_router_optimizer_smoke.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Two-step fail-closed optimizer admission for one frozen donor bank."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import platform
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
import traceback
|
| 12 |
+
from datetime import datetime, timezone
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from safetensors.torch import load_file, save_file
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
if str(HERE) not in sys.path:
|
| 23 |
+
sys.path.insert(0, str(HERE))
|
| 24 |
+
|
| 25 |
+
from fable_router_common import read_json, selected_expert_ids, sha256, validate_bank_header, verify_file
|
| 26 |
+
from fable_router_hybrid import (
|
| 27 |
+
FrozenExpertRouterBlock,
|
| 28 |
+
assert_trainable_isolation,
|
| 29 |
+
attach_router_block,
|
| 30 |
+
benefit_targets,
|
| 31 |
+
benefit_weighted_router_loss,
|
| 32 |
+
freeze_except_routers,
|
| 33 |
+
router_state_dict,
|
| 34 |
+
)
|
| 35 |
+
from run_fable_router_full_bank_fit import download, verify_authorization
|
| 36 |
+
from run_fable_router_structural_smoke import (
|
| 37 |
+
batch_rows,
|
| 38 |
+
compute_dtype,
|
| 39 |
+
gpu_facts,
|
| 40 |
+
select_complete_rows,
|
| 41 |
+
token_nll,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def now() -> str:
|
| 46 |
+
return datetime.now(timezone.utc).isoformat()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def set_blocks(blocks: list[FrozenExpertRouterBlock], enabled: bool) -> None:
|
| 50 |
+
for block in blocks:
|
| 51 |
+
block.enabled = enabled
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def shifted_valid(logits: torch.Tensor, labels: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 55 |
+
valid = labels[:, 1:] != -100
|
| 56 |
+
return logits[:, :-1, :][valid], valid
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def host_forward(model: torch.nn.Module, blocks: list[FrozenExpertRouterBlock], batch: dict[str, torch.Tensor]) -> torch.Tensor:
|
| 60 |
+
set_blocks(blocks, False)
|
| 61 |
+
model.eval()
|
| 62 |
+
with torch.inference_mode():
|
| 63 |
+
logits = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False).logits.detach()
|
| 64 |
+
return logits
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
|
| 68 |
+
campaign, config, manifest = verify_authorization(args.campaign.resolve(), result)
|
| 69 |
+
optimizer_contract = campaign["optimizerAdmission"]
|
| 70 |
+
proof_path = args.memory_proof.resolve()
|
| 71 |
+
if sha256(proof_path) != optimizer_contract["memoryProof"]["sha256"]:
|
| 72 |
+
raise RuntimeError("training-memory proof hash mismatch")
|
| 73 |
+
proof = read_json(proof_path)
|
| 74 |
+
if proof.get("passed") is not True or proof.get("status") != optimizer_contract["memoryProof"]["requiredStatus"]:
|
| 75 |
+
raise RuntimeError("training-memory admission prerequisite is not a pass")
|
| 76 |
+
if args.bank not in campaign["selectedBanks"]["ids"]:
|
| 77 |
+
raise RuntimeError("bank is outside the frozen authorized set")
|
| 78 |
+
result["memoryProof"] = {"path": str(proof_path), "sha256": sha256(proof_path), "status": proof["status"]}
|
| 79 |
+
result["bank"] = args.bank
|
| 80 |
+
result["gpu"] = gpu_facts(14.0)
|
| 81 |
+
if result["gpu"]["name"] not in campaign["computePolicy"]["allowedAccelerators"]:
|
| 82 |
+
raise RuntimeError("optimizer smoke accelerator is outside the zero-cost allowlist")
|
| 83 |
+
|
| 84 |
+
banks = {row["id"]: row for row in manifest["banks"]}
|
| 85 |
+
bank_definition = banks[args.bank]
|
| 86 |
+
bank_repo = config["banks"]
|
| 87 |
+
artifact = bank_repo["artifacts"][args.bank]
|
| 88 |
+
token = os.environ.get("HF_TOKEN")
|
| 89 |
+
bank_path = download(bank_repo["repo"], bank_repo["revision"], artifact["path"], "model", token)
|
| 90 |
+
result["bankArtifact"] = verify_file(bank_path, int(artifact["bytes"]), artifact["sha256"])
|
| 91 |
+
result["bankValidation"] = validate_bank_header(bank_path, bank_definition).as_dict()
|
| 92 |
+
warm = bank_repo["routerWarmstart"]
|
| 93 |
+
warm_path = download(bank_repo["repo"], bank_repo["revision"], warm["path"], "model", token)
|
| 94 |
+
verify_file(warm_path, int(warm["bytes"]), warm["sha256"])
|
| 95 |
+
train_cfg = config["curriculum"]["sftTrain"]
|
| 96 |
+
train_path = args.curriculum_path.resolve()
|
| 97 |
+
result["curriculumArtifact"] = verify_file(train_path, int(train_cfg["bytes"]), train_cfg["sha256"])
|
| 98 |
+
|
| 99 |
+
host = config["host"]
|
| 100 |
+
tokenizer = AutoTokenizer.from_pretrained(host["repo"], revision=host["revision"], token=token, trust_remote_code=True, fix_mistral_regex=True)
|
| 101 |
+
rows = select_complete_rows(train_path, tokenizer, 320)
|
| 102 |
+
result["rows"] = [{"id": row["id"], "lane": row["lane"], "tokens": len(row["inputIds"])} for row in rows]
|
| 103 |
+
device = torch.device("cuda:0")
|
| 104 |
+
dtype = compute_dtype(result["gpu"])
|
| 105 |
+
torch.cuda.reset_peak_memory_stats(device)
|
| 106 |
+
started = time.perf_counter()
|
| 107 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 108 |
+
host["repo"], revision=host["revision"], token=token, trust_remote_code=True,
|
| 109 |
+
torch_dtype=dtype, low_cpu_mem_usage=True, attn_implementation="sdpa",
|
| 110 |
+
).to(device)
|
| 111 |
+
model.config.use_cache = False
|
| 112 |
+
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
|
| 113 |
+
model.enable_input_require_grads()
|
| 114 |
+
warm_state = load_file(str(warm_path), device="cpu")
|
| 115 |
+
blocks: list[FrozenExpertRouterBlock] = []
|
| 116 |
+
for layer in range(30):
|
| 117 |
+
block = FrozenExpertRouterBlock(selected_expert_ids(bank_definition, layer), top_k=2, initial_scale=0.005, maximum_scale=0.025)
|
| 118 |
+
attach_router_block(model, layer, block)
|
| 119 |
+
block.router.to(device=device, dtype=torch.float32)
|
| 120 |
+
block.expert_scale.data = block.expert_scale.data.to(device=device)
|
| 121 |
+
block.materialize_experts(bank_path, layer, device=torch.device("cpu"), dtype=dtype)
|
| 122 |
+
block.load_router_warmstart(warm_state[f"layers.{layer}.router.gate.weight"])
|
| 123 |
+
block.checkpoint_enabled = True
|
| 124 |
+
blocks.append(block)
|
| 125 |
+
counts = freeze_except_routers(model)
|
| 126 |
+
names = assert_trainable_isolation(model)
|
| 127 |
+
if len(names) != 60:
|
| 128 |
+
raise RuntimeError(f"optimizer smoke found {len(names)} trainable tensors instead of 60")
|
| 129 |
+
result["trainableIsolation"] = {"counts": counts, "names": names}
|
| 130 |
+
before_state = router_state_dict(model)
|
| 131 |
+
parameters = [parameter for parameter in model.parameters() if parameter.requires_grad]
|
| 132 |
+
optimizer = torch.optim.AdamW(parameters, lr=float(optimizer_contract["learningRate"]), weight_decay=0.0)
|
| 133 |
+
|
| 134 |
+
metrics = []
|
| 135 |
+
positive_and_off = False
|
| 136 |
+
for step, row in enumerate(rows):
|
| 137 |
+
batch = batch_rows([row], int(tokenizer.pad_token_id), device)
|
| 138 |
+
host_logits = host_forward(model, blocks, batch)
|
| 139 |
+
host_losses = token_nll(host_logits, batch["labels"])[0]
|
| 140 |
+
valid = batch["labels"][0, 1:] != -100
|
| 141 |
+
host_nll = host_losses[valid].detach().cpu()
|
| 142 |
+
ranking_loss = torch.zeros((), device=device)
|
| 143 |
+
discovery: dict[str, Any] | None = None
|
| 144 |
+
probe_layer = int(optimizer_contract["counterfactualLayer"])
|
| 145 |
+
|
| 146 |
+
if row["lane"] == "verified_expert":
|
| 147 |
+
candidates = [int(item) for item in optimizer_contract["counterfactualCandidates"]]
|
| 148 |
+
candidate_losses = []
|
| 149 |
+
set_blocks(blocks, False)
|
| 150 |
+
blocks[probe_layer].enabled = True
|
| 151 |
+
for candidate in candidates:
|
| 152 |
+
with blocks[probe_layer].forced_route(candidate, float(optimizer_contract["counterfactualScale"])), torch.inference_mode():
|
| 153 |
+
logits = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False).logits
|
| 154 |
+
candidate_losses.append(token_nll(logits, batch["labels"])[0][valid].detach().cpu())
|
| 155 |
+
candidate_matrix = torch.stack(candidate_losses, dim=-1)
|
| 156 |
+
column_targets = benefit_targets(host_nll, candidate_matrix, margin=0.0)
|
| 157 |
+
mapped = torch.full_like(column_targets, blocks[probe_layer].off_class_index)
|
| 158 |
+
for column, local_expert in enumerate(candidates):
|
| 159 |
+
mapped[column_targets == column] = local_expert
|
| 160 |
+
positive = mapped != blocks[probe_layer].off_class_index
|
| 161 |
+
positive_and_off = bool(positive.any() and (~positive).any())
|
| 162 |
+
discovery = {
|
| 163 |
+
"layer": probe_layer,
|
| 164 |
+
"candidates": candidates,
|
| 165 |
+
"eligibleTokens": int(mapped.numel()),
|
| 166 |
+
"positiveBenefitTokens": int(positive.sum()),
|
| 167 |
+
"hostOnlyTargets": int((~positive).sum()),
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
set_blocks(blocks, True)
|
| 171 |
+
model.train()
|
| 172 |
+
optimizer.zero_grad(set_to_none=True)
|
| 173 |
+
routed = model(**batch, use_cache=False)
|
| 174 |
+
routed_valid, _ = shifted_valid(routed.logits, batch["labels"])
|
| 175 |
+
host_valid, _ = shifted_valid(host_logits, batch["labels"])
|
| 176 |
+
kl = F.kl_div(
|
| 177 |
+
F.log_softmax(routed_valid.float(), dim=-1),
|
| 178 |
+
F.softmax(host_valid.float(), dim=-1),
|
| 179 |
+
reduction="batchmean",
|
| 180 |
+
)
|
| 181 |
+
if discovery is not None:
|
| 182 |
+
trace = blocks[probe_layer].last_trace
|
| 183 |
+
if trace is None:
|
| 184 |
+
raise RuntimeError("probe-layer router trace is missing")
|
| 185 |
+
trace_logits = trace.logits[:-1][valid]
|
| 186 |
+
ranking_loss = benefit_weighted_router_loss(
|
| 187 |
+
trace_logits,
|
| 188 |
+
mapped.to(device),
|
| 189 |
+
host_nll.to(device),
|
| 190 |
+
candidate_matrix.to(device),
|
| 191 |
+
)
|
| 192 |
+
route_cost = torch.stack([F.softplus(block.expert_scale).clamp(max=0.025) for block in blocks]).mean()
|
| 193 |
+
kl_weight = 1.0 if row["lane"] == "host_preservation" else 0.25
|
| 194 |
+
total = routed.loss + kl_weight * kl + ranking_loss + 0.015 * route_cost
|
| 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"],
|
| 203 |
+
"sftLoss": float(routed.loss.detach()),
|
| 204 |
+
"klLoss": float(kl.detach()),
|
| 205 |
+
"rankingLoss": float(ranking_loss.detach()),
|
| 206 |
+
"routeCost": float(route_cost.detach()),
|
| 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 |
+
key = f"model.layers.{layer}.expert_block.router.gate.weight"
|
| 219 |
+
if not torch.equal(before_state[key], after_state[key]):
|
| 220 |
+
changed_layers.append(layer)
|
| 221 |
+
if changed_layers != list(range(30)):
|
| 222 |
+
raise RuntimeError(f"not every router gate updated: {changed_layers}")
|
| 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"
|
| 229 |
+
optimizer_path = output / "optimizer.pt"
|
| 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"] = {"changedRouterLayers": changed_layers, "maximumExpertScale": maximum_scale}
|
| 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"] = {
|
| 237 |
+
"seconds": time.perf_counter() - started,
|
| 238 |
+
"peakAllocatedVramMiB": torch.cuda.max_memory_allocated(device) / 2**20,
|
| 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 |
+
|
| 245 |
+
def main() -> int:
|
| 246 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 247 |
+
parser.add_argument("--owner-execute", action="store_true")
|
| 248 |
+
parser.add_argument("--campaign", type=Path, required=True)
|
| 249 |
+
parser.add_argument("--bank", required=True)
|
| 250 |
+
parser.add_argument("--curriculum-path", type=Path, required=True)
|
| 251 |
+
parser.add_argument("--memory-proof", type=Path, required=True)
|
| 252 |
+
parser.add_argument("--work-dir", type=Path, default=Path("/content/autonoma-fable-training"))
|
| 253 |
+
args = parser.parse_args()
|
| 254 |
+
if not args.owner_execute:
|
| 255 |
+
raise SystemExit("refusing optimizer execution without --owner-execute")
|
| 256 |
+
args.work_dir.mkdir(parents=True, exist_ok=True)
|
| 257 |
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 258 |
+
output = args.work_dir / f"fable-router-optimizer-smoke-{args.bank}-{stamp}"
|
| 259 |
+
output.mkdir(parents=True, exist_ok=False)
|
| 260 |
+
result: dict[str, Any] = {
|
| 261 |
+
"schema": "AutonomaFableRouterOptimizerSmoke.v1",
|
| 262 |
+
"status": "running_nonrouting",
|
| 263 |
+
"passed": False,
|
| 264 |
+
"nonRouting": True,
|
| 265 |
+
"trainingAuthorized": True,
|
| 266 |
+
"productionRoutingAuthorized": False,
|
| 267 |
+
"startedAt": now(),
|
| 268 |
+
"output": str(output),
|
| 269 |
+
"system": {"python": sys.version, "platform": platform.platform()},
|
| 270 |
+
}
|
| 271 |
+
try:
|
| 272 |
+
run(args, result)
|
| 273 |
+
result.update(status="optimizer_smoke_passed_nonrouting", passed=True)
|
| 274 |
+
except BaseException as exc:
|
| 275 |
+
result.update(status="optimizer_smoke_failed_nonrouting", error={"type": type(exc).__name__, "message": str(exc), "traceback": traceback.format_exc()})
|
| 276 |
+
finally:
|
| 277 |
+
result["finishedAt"] = now()
|
| 278 |
+
result_path = output / "result.json"
|
| 279 |
+
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
|
| 280 |
+
print(result_path.resolve())
|
| 281 |
+
return 0 if result.get("passed") else 1
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
if __name__ == "__main__":
|
| 285 |
+
raise SystemExit(main())
|