Swordnael commited on
Commit
6ff2cd1
·
verified ·
1 Parent(s): da0bf36

Add free-GPU structural smoke runner

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