File size: 22,822 Bytes
6ff2cd1 1ffab97 6ff2cd1 1ffab97 6ff2cd1 1ffab97 6ff2cd1 ccf6b90 6ff2cd1 80187cb 6ff2cd1 80187cb 6ff2cd1 1ffab97 6ff2cd1 0e3ceca 6ff2cd1 0e3ceca 6ff2cd1 0e3ceca 6ff2cd1 0e3ceca 6ff2cd1 0e3ceca 6ff2cd1 80187cb 6ff2cd1 756b532 6ff2cd1 756b532 6ff2cd1 0e3ceca 6ff2cd1 756b532 6ff2cd1 ccf6b90 80187cb 6ff2cd1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | #!/usr/bin/env python
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "torch>=2.4",
# "transformers>=4.56",
# "accelerate>=1.2",
# "safetensors>=0.5",
# "huggingface_hub>=0.34",
# "trackio>=0.3",
# ]
# ///
"""Run one provenance-bound, non-routing Fable donor-bank structural smoke.
This is deliberately not a quality training run. It validates all 2,880
bank tensors but attaches only the final host layer, keeping a real gradient
and counterfactual test feasible on a free 16 GiB GPU.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import shutil
import sys
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import torch
import torch.nn.functional as F
from huggingface_hub import HfApi, hf_hub_download
from safetensors.torch import load_file, save_file
from transformers import AutoModelForCausalLM, AutoTokenizer
HERE = Path(__file__).resolve().parent
if str(HERE) not in sys.path:
sys.path.insert(0, str(HERE))
from fable_router_common import ( # noqa: E402
iter_jsonl,
read_json,
selected_expert_ids,
sha256,
validate_bank_header,
validate_curriculum_row,
verify_file,
)
from fable_router_hybrid import ( # noqa: E402
FrozenExpertRouterBlock,
assert_trainable_isolation,
attach_router_block,
benefit_targets,
benefit_weighted_router_loss,
freeze_except_routers,
load_router_state_dict,
router_state_dict,
)
def now() -> str:
return datetime.now(timezone.utc).isoformat()
def download(repo: str, revision: str, filename: str, repo_type: str, token: str | None) -> Path:
return Path(
hf_hub_download(
repo_id=repo,
revision=revision,
filename=filename,
repo_type=repo_type,
token=token,
)
)
def render_and_tokenize(tokenizer: Any, messages: list[dict[str, Any]]) -> list[int]:
# Transformers 5 can return a BatchEncoding from apply_chat_template with
# tokenize=True, whose len() is the number of fields rather than tokens.
rendered = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
return list(tokenizer(rendered, add_special_tokens=False)["input_ids"])
def select_complete_rows(path: Path, tokenizer: Any, maximum_tokens: int) -> list[dict[str, Any]]:
wanted = ("host_preservation", "verified_expert")
best: dict[str, tuple[int, dict[str, Any], list[int]]] = {}
for row in iter_jsonl(path):
validate_curriculum_row(row, "train")
lane = str(row["lane"])
if lane not in wanted:
continue
ids = render_and_tokenize(tokenizer, row["messages"])
if len(ids) > maximum_tokens:
continue
previous = best.get(lane)
if previous is None or len(ids) < previous[0]:
best[lane] = (len(ids), row, ids)
missing = sorted(set(wanted) - set(best))
if missing:
raise RuntimeError(f"no complete <= {maximum_tokens}-token rows for lanes {missing}")
return [
{"id": best[lane][1]["id"], "lane": lane, "inputIds": best[lane][2]}
for lane in wanted
]
def batch_rows(rows: list[dict[str, Any]], pad_token_id: int, device: torch.device) -> dict[str, torch.Tensor]:
maximum = max(len(row["inputIds"]) for row in rows)
input_ids, attention_mask, labels = [], [], []
for row in rows:
ids = list(row["inputIds"])
padding = maximum - len(ids)
input_ids.append(ids + [pad_token_id] * padding)
attention_mask.append([1] * len(ids) + [0] * padding)
labels.append(ids + [-100] * padding)
return {
"input_ids": torch.tensor(input_ids, dtype=torch.long, device=device),
"attention_mask": torch.tensor(attention_mask, dtype=torch.long, device=device),
"labels": torch.tensor(labels, dtype=torch.long, device=device),
}
def token_nll(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
shifted_logits = logits[:, :-1, :].float()
shifted_labels = labels[:, 1:]
losses = F.cross_entropy(
shifted_logits.reshape(-1, shifted_logits.shape[-1]),
shifted_labels.reshape(-1),
reduction="none",
ignore_index=-100,
).reshape(shifted_labels.shape)
return losses
def gpu_facts(minimum_vram_gib: float) -> dict[str, Any]:
if not torch.cuda.is_available():
raise RuntimeError("a CUDA GPU is required for the structural smoke")
properties = torch.cuda.get_device_properties(0)
total_gib = properties.total_memory / 2**30
if total_gib < minimum_vram_gib:
raise RuntimeError(f"GPU has {total_gib:.2f} GiB, requires at least {minimum_vram_gib:.2f} GiB")
capability = torch.cuda.get_device_capability(0)
native_bf16 = capability[0] >= 8 and bool(torch.cuda.is_bf16_supported())
return {
"name": properties.name,
"totalVramGiB": total_gib,
"capability": list(capability),
"torchBf16Reported": bool(torch.cuda.is_bf16_supported()),
"nativeBf16Admitted": native_bf16,
}
def compute_dtype(gpu: dict[str, Any]) -> torch.dtype:
return torch.bfloat16 if gpu["nativeBf16Admitted"] else torch.float16
def upload_evidence(output: Path, repo_id: str, token: str) -> dict[str, Any]:
api = HfApi(token=token)
api.create_repo(repo_id, repo_type="dataset", private=True, exist_ok=True)
info = api.repo_info(repo_id, repo_type="dataset")
if not bool(info.private):
raise RuntimeError(f"refusing to upload smoke evidence to public repo {repo_id}")
prefix = output.name
for item in output.iterdir():
if item.is_file():
api.upload_file(
path_or_fileobj=str(item),
path_in_repo=f"runs/{prefix}/{item.name}",
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Persist non-routing structural smoke {prefix}",
)
return {"repo": repo_id, "private": True, "path": f"runs/{prefix}"}
def upload_final_result(output: Path, repo_id: str, token: str) -> None:
HfApi(token=token).upload_file(
path_or_fileobj=str(output / "result.json"),
path_in_repo=f"runs/{output.name}/result.json",
repo_id=repo_id,
repo_type="dataset",
commit_message=f"Finalize non-routing structural smoke {output.name}",
)
def run(args: argparse.Namespace, result: dict[str, Any]) -> None:
config_path = args.config.resolve()
config = read_json(config_path)
if config.get("trainingAuthorized") is not False or config.get("nonRouting") is not True:
raise RuntimeError("cloud smoke config is not explicitly non-routing/training-disabled")
smoke = config["smoke"]
bank_config = config["banks"]["artifacts"].get(args.bank)
if not bank_config:
raise RuntimeError(f"unknown bank {args.bank}")
token = os.environ.get("HF_TOKEN")
curriculum_override = getattr(args, "curriculum_path", None)
if not token and not curriculum_override:
raise RuntimeError(
"either HF_TOKEN or --curriculum-path is required for the private curriculum"
)
result["config"] = {"path": str(config_path), "sha256": sha256(config_path)}
result["bank"] = args.bank
result["platform"] = args.platform
result["gpu"] = gpu_facts(14.0)
free_disk_gib = shutil.disk_usage(args.work_dir).free / 2**30
result["freeDiskGiBBeforeDownloads"] = free_disk_gib
if free_disk_gib < float(smoke["minimumFreeDiskGiBBeforeBankDownload"]):
raise RuntimeError(
f"only {free_disk_gib:.2f} GiB free; requires "
f"{smoke['minimumFreeDiskGiBBeforeBankDownload']} GiB before downloads"
)
bank_repo = config["banks"]
curriculum = config["curriculum"]
bank_manifest = download(
bank_repo["repo"], bank_repo["revision"], bank_repo["manifestPath"], "model", token
)
if sha256(bank_manifest) != bank_repo["manifestSha256"]:
raise RuntimeError("frozen selected-bank manifest hash mismatch")
manifest = read_json(bank_manifest)
banks = {row["id"]: row for row in manifest["banks"]}
bank_definition = banks[args.bank]
warm_config = bank_repo["routerWarmstart"]
warmstart = download(bank_repo["repo"], bank_repo["revision"], warm_config["path"], "model", token)
verify_file(warmstart, int(warm_config["bytes"]), warm_config["sha256"])
bank_path = download(bank_repo["repo"], bank_repo["revision"], bank_config["path"], "model", token)
bank_artifact = verify_file(bank_path, int(bank_config["bytes"]), bank_config["sha256"])
bank_validation = validate_bank_header(bank_path, bank_definition)
result["bankArtifact"] = bank_artifact
result["bankValidation"] = bank_validation.as_dict()
train_config = curriculum["sftTrain"]
train_path = (
Path(curriculum_override).resolve()
if curriculum_override
else download(
curriculum["repo"], curriculum["revision"], train_config["path"], "dataset", token
)
)
result["curriculumArtifact"] = verify_file(
train_path, int(train_config["bytes"]), train_config["sha256"]
)
host = config["host"]
tokenizer = AutoTokenizer.from_pretrained(
host["repo"], revision=host["revision"], token=token, trust_remote_code=True,
fix_mistral_regex=True,
)
rows = select_complete_rows(train_path, tokenizer, int(smoke["maximumTokens"]))
result["retokenization"] = {
"maximumTokens": int(smoke["maximumTokens"]),
"truncated": False,
"rows": [{"id": row["id"], "lane": row["lane"], "tokens": len(row["inputIds"])} for row in rows],
}
device = torch.device("cuda:0")
dtype = compute_dtype(result["gpu"])
torch.cuda.reset_peak_memory_stats(device)
load_started = time.perf_counter()
model = AutoModelForCausalLM.from_pretrained(
host["repo"], revision=host["revision"], token=token, trust_remote_code=True,
torch_dtype=dtype, low_cpu_mem_usage=True, attn_implementation="sdpa",
).to(device)
model.config.use_cache = False
model.eval()
batch = batch_rows(rows, int(tokenizer.pad_token_id), device)
with torch.inference_mode():
baseline_logits = model(
input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False
).logits.detach().cpu()
layer = int(smoke["attachedLayer"])
block = FrozenExpertRouterBlock(
selected_expert_ids(bank_definition, layer),
top_k=int(smoke["topK"]),
initial_scale=float(smoke["initialExpertScale"]),
maximum_scale=float(smoke["maximumExpertScale"]),
)
wrapper = attach_router_block(model, layer, block)
block.router.to(device=device, dtype=torch.float32)
block.expert_scale.data = block.expert_scale.data.to(device=device)
block.materialize_experts(bank_path, layer, device=device, dtype=dtype)
warm_tensors = load_file(str(warmstart), device="cpu")
block.load_router_warmstart(warm_tensors[f"layers.{layer}.router.gate.weight"])
block.enabled = False
with torch.inference_mode():
wrapped_disabled = model(
input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], use_cache=False
).logits.detach().cpu()
identity_equal = torch.equal(baseline_logits, wrapped_disabled)
identity_max_difference = (baseline_logits.float() - wrapped_disabled.float()).abs().max().item()
result["hostDisabledIdentity"] = {
"exact": identity_equal,
"maximumAbsoluteDifference": identity_max_difference,
}
if not identity_equal:
raise RuntimeError(f"host-disabled identity failed: max difference {identity_max_difference}")
del baseline_logits, wrapped_disabled
counts = freeze_except_routers(model)
trainable_names = assert_trainable_isolation(model)
result["trainableIsolation"] = {"counts": counts, "names": trainable_names}
block.enabled = True
model.zero_grad(set_to_none=True)
gradient_output = model(**batch, use_cache=False)
gradient_loss_scale = float(smoke["gradientLossScale"])
(gradient_output.loss * gradient_loss_scale).backward()
router_gradient = block.router.gate.weight.grad
scale_gradient = block.expert_scale.grad
gradient_gate = {
"routerFinite": bool(router_gradient is not None and torch.isfinite(router_gradient).all()),
"routerL1Scaled": float(router_gradient.float().abs().sum()) if router_gradient is not None else 0.0,
"routerL1Unscaled": (
float(router_gradient.float().abs().sum() / gradient_loss_scale)
if router_gradient is not None else 0.0
),
"scaleFinite": bool(scale_gradient is not None and torch.isfinite(scale_gradient).all()),
"scaleAbsoluteScaled": float(scale_gradient.float().abs()) if scale_gradient is not None else 0.0,
"scaleAbsoluteUnscaled": (
float(scale_gradient.float().abs() / gradient_loss_scale)
if scale_gradient is not None else 0.0
),
"lossScale": gradient_loss_scale,
"routerDtype": str(block.router.gate.weight.dtype),
}
result["gradientGate"] = gradient_gate
if not all((gradient_gate["routerFinite"], gradient_gate["scaleFinite"])) or min(
gradient_gate["routerL1Scaled"], gradient_gate["scaleAbsoluteScaled"]
) <= 0:
raise RuntimeError(f"router gradient gate failed: {gradient_gate}")
expert_row = next(row for row in rows if row["lane"] == "verified_expert")
oracle_batch = batch_rows([expert_row], int(tokenizer.pad_token_id), device)
block.enabled = False
with torch.inference_mode():
host_logits = model(
input_ids=oracle_batch["input_ids"], attention_mask=oracle_batch["attention_mask"], use_cache=False
).logits
host_nll = token_nll(host_logits, oracle_batch["labels"])[0]
valid_tokens = oracle_batch["labels"][0, 1:] != -100
host_nll = host_nll[valid_tokens].detach().cpu()
candidate_indices = list(range(0, 32, max(1, 32 // int(smoke["oracleCandidateExperts"]))))[
: int(smoke["oracleCandidateExperts"])
]
best_candidate_nll = []
oracle_rows = []
block.enabled = True
for candidate in candidate_indices:
scale_losses = []
for scale in smoke["oracleProbeScales"]:
with block.forced_route(candidate, float(scale)), torch.inference_mode():
logits = model(
input_ids=oracle_batch["input_ids"],
attention_mask=oracle_batch["attention_mask"],
use_cache=False,
).logits
losses = token_nll(logits, oracle_batch["labels"])[0][valid_tokens].detach().cpu()
scale_losses.append(losses)
oracle_rows.append(
{
"localExpert": candidate,
"globalExpert": block.expert_ids[candidate],
"scale": float(scale),
"meanNll": float(losses.mean()),
"improvedTokenCount": int((losses < host_nll).sum()),
}
)
best_candidate_nll.append(torch.stack(scale_losses).min(dim=0).values)
candidate_matrix = torch.stack(best_candidate_nll, dim=-1)
targets = benefit_targets(host_nll, candidate_matrix, float(smoke["benefitMarginNats"]))
positive = targets != candidate_matrix.shape[-1]
block.enabled = True
with torch.no_grad():
_ = model(
input_ids=oracle_batch["input_ids"], attention_mask=oracle_batch["attention_mask"], use_cache=False
)
if block.last_trace is None:
raise RuntimeError("router did not retain a main-path trace")
router_logits = block.last_trace.logits[: targets.numel()].float()
ranking_loss = benefit_weighted_router_loss(router_logits, targets.to(device), host_nll.to(device), candidate_matrix.to(device))
result["counterfactualDiscovery"] = {
"hostOnlyClass": block.off_class_index,
"candidateLocalExperts": candidate_indices,
"probes": oracle_rows,
"eligibleTokens": int(targets.numel()),
"positiveBenefitTokens": int(positive.sum()),
"hostOnlyTargets": int((~positive).sum()),
"rankingLossFinite": bool(torch.isfinite(ranking_loss)),
}
if not torch.isfinite(ranking_loss) or int(positive.sum()) == 0 or int((~positive).sum()) == 0:
raise RuntimeError("counterfactual smoke did not exercise both positive expert and host-only targets")
output = Path(result["output"])
checkpoint = output / "router-checkpoint.safetensors"
saved_state = router_state_dict(model)
save_file(saved_state, str(checkpoint), metadata={"autonoma": "non-routing-structural-smoke"})
with torch.inference_mode():
before_reload = model(
input_ids=oracle_batch["input_ids"], attention_mask=oracle_batch["attention_mask"], use_cache=False
).logits.detach().cpu()
with torch.no_grad():
block.router.gate.weight.zero_()
load_router_state_dict(model, load_file(str(checkpoint), device="cpu"))
with torch.inference_mode():
after_reload = model(
input_ids=oracle_batch["input_ids"], attention_mask=oracle_batch["attention_mask"], use_cache=False
).logits.detach().cpu()
reload_equal = torch.equal(before_reload, after_reload)
result["checkpointParity"] = {
"exact": reload_equal,
"path": str(checkpoint),
"bytes": checkpoint.stat().st_size,
"sha256": sha256(checkpoint),
}
if not reload_equal:
raise RuntimeError("router checkpoint save/reload parity failed")
result["runtime"] = {
"loadAndSmokeSeconds": time.perf_counter() - load_started,
"peakAllocatedVramMiB": torch.cuda.max_memory_allocated(device) / 2**20,
"peakReservedVramMiB": torch.cuda.max_memory_reserved(device) / 2**20,
"computeDtype": str(dtype),
"torch": torch.__version__,
}
result["gates"] = {gate: True for gate in smoke["requiredGates"]}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--owner-execute", action="store_true")
parser.add_argument("--config", type=Path, required=True)
parser.add_argument("--bank", required=True)
parser.add_argument("--platform", choices=("colab", "kaggle", "other"), default="other")
parser.add_argument("--work-dir", type=Path, default=Path("/content/autonoma-fable-smoke"))
parser.add_argument(
"--curriculum-path",
type=Path,
help="Verified local sft-train.jsonl override for credential-free cloud execution",
)
args = parser.parse_args()
if not args.owner_execute:
raise SystemExit("refusing GPU/model execution without --owner-execute")
args.work_dir.mkdir(parents=True, exist_ok=True)
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
output = args.work_dir / f"fable-router-structural-smoke-{args.bank}-{stamp}"
output.mkdir(parents=True, exist_ok=False)
result: dict[str, Any] = {
"schema": "AutonomaFableRouterStructuralSmoke.v1",
"status": "running_nonrouting",
"nonRouting": True,
"trainingAuthorized": False,
"startedAt": now(),
"output": str(output),
"system": {"python": sys.version, "platform": platform.platform()},
}
tracking: dict[str, Any] = {"status": "not_started"}
try:
import trackio
# Structural-smoke evidence is persisted directly to the private Hub
# dataset. Keep Trackio local here: Trackio's Space mode configures a
# Hub Bucket/Xet write context, which can leak into a subsequent large
# model download in the same process. Full training uses a dedicated
# remote Trackio process after acquisition instead.
os.environ["TRACKIO_DIR"] = str(output / "trackio")
trackio.init(
project="autonoma-fable-router-smoke",
name=f"{args.bank}-{stamp}",
config={"bank": args.bank, "platform": args.platform, "mode": "structural-smoke"},
)
tracking = {"status": "started_local", "directory": str(output / "trackio")}
run(args, result)
result["status"] = "structural_smoke_passed_nonrouting"
result["passed"] = True
trackio.log(
{
"peak_vram_mib": result["runtime"]["peakAllocatedVramMiB"],
"positive_oracle_tokens": result["counterfactualDiscovery"]["positiveBenefitTokens"],
"router_gradient_l1_unscaled": result["gradientGate"]["routerL1Unscaled"],
}
)
except BaseException as exc:
result["status"] = "structural_smoke_failed_nonrouting"
result["passed"] = False
result["error"] = {"type": type(exc).__name__, "message": str(exc), "traceback": traceback.format_exc()}
finally:
result["finishedAt"] = now()
result["tracking"] = tracking
result_path = output / "result.json"
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
try:
if tracking["status"] == "started_local":
import trackio
trackio.finish()
tracking["status"] = "finished"
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
except BaseException as exc:
tracking["finishError"] = str(exc)
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
token = os.environ.get("HF_TOKEN")
try:
config = read_json(args.config.resolve())
if token:
result["evidenceUpload"] = upload_evidence(output, config["smoke"]["resultRepo"], token)
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
upload_final_result(output, config["smoke"]["resultRepo"], token)
else:
result["evidenceUpload"] = {
"status": "local_only_pending_authenticated_download",
"privateRemoteCredentialUsed": False,
}
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
except BaseException as exc:
result["evidenceUpload"] = {"status": "failed", "error": str(exc)}
result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
print(result_path.resolve())
return 0 if result.get("passed") else 1
if __name__ == "__main__":
raise SystemExit(main())
|