| """Pure contract and provenance helpers for the Fable expert-router campaign. |
| |
| This module intentionally has no Torch dependency. It is shared by local |
| unit tests, the Colab/Kaggle entry points, and the GPU structural smoke. |
| """ |
| from __future__ import annotations |
|
|
| import hashlib |
| import json |
| import struct |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Any, Iterable |
|
|
|
|
| EXPECTED_PROJECTIONS = { |
| "gate_proj.weight": (512, 2048), |
| "up_proj.weight": (512, 2048), |
| "down_proj.weight": (2048, 512), |
| } |
|
|
| DTYPE_BYTES = {"BF16": 2, "F16": 2} |
|
|
|
|
| def sha256(path: Path, chunk_size: int = 8 * 1024 * 1024) -> str: |
| digest = hashlib.sha256() |
| with path.open("rb") as handle: |
| while chunk := handle.read(chunk_size): |
| digest.update(chunk) |
| return digest.hexdigest() |
|
|
|
|
| def canonical_json_sha256(value: Any) -> str: |
| encoded = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") |
| return hashlib.sha256(encoded).hexdigest() |
|
|
|
|
| def read_json(path: Path) -> dict[str, Any]: |
| payload = json.loads(path.read_text(encoding="utf-8")) |
| if not isinstance(payload, dict): |
| raise ValueError(f"expected a JSON object: {path}") |
| return payload |
|
|
|
|
| def safetensors_header(path: Path) -> tuple[int, dict[str, Any]]: |
| with path.open("rb") as handle: |
| raw_size = handle.read(8) |
| if len(raw_size) != 8: |
| raise ValueError(f"truncated Safetensors size header: {path}") |
| size = struct.unpack("<Q", raw_size)[0] |
| if size < 2 or size > 256 * 1024 * 1024: |
| raise ValueError(f"implausible Safetensors header size {size}: {path}") |
| raw_header = handle.read(size) |
| if len(raw_header) != size: |
| raise ValueError(f"truncated Safetensors JSON header: {path}") |
| header = json.loads(raw_header) |
| if not isinstance(header, dict): |
| raise ValueError(f"Safetensors header is not an object: {path}") |
| return 8 + size, header |
|
|
|
|
| @dataclass(frozen=True) |
| class BankValidation: |
| bank_id: str |
| tensor_count: int |
| payload_bytes: int |
| dtypes: tuple[str, ...] |
| layers: tuple[int, ...] |
|
|
| def as_dict(self) -> dict[str, Any]: |
| return { |
| "bankId": self.bank_id, |
| "tensorCount": self.tensor_count, |
| "payloadBytes": self.payload_bytes, |
| "dtypes": list(self.dtypes), |
| "layers": list(self.layers), |
| } |
|
|
|
|
| def selected_expert_ids(bank: dict[str, Any], layer: int) -> list[int]: |
| raw = bank.get("selectedExperts", {}).get(str(layer)) |
| if not isinstance(raw, list): |
| raise ValueError(f"bank {bank.get('id')} has no selected expert list for layer {layer}") |
| ids = [int(item) for item in raw] |
| if len(ids) != 32 or len(set(ids)) != 32: |
| raise ValueError(f"bank {bank.get('id')} layer {layer} must select 32 unique experts") |
| return ids |
|
|
|
|
| def expected_tensor_names(bank: dict[str, Any]) -> Iterable[tuple[int, int, str, tuple[int, int]]]: |
| for layer in range(30): |
| for expert in selected_expert_ids(bank, layer): |
| for projection, shape in EXPECTED_PROJECTIONS.items(): |
| yield layer, expert, f"model.layers.{layer}.mlp.experts.{expert}.{projection}", shape |
|
|
|
|
| def validate_bank_header_entries( |
| header: dict[str, Any], file_payload: int, bank: dict[str, Any] |
| ) -> BankValidation: |
| tensor_entries = {key: value for key, value in header.items() if key != "__metadata__"} |
| expected = list(expected_tensor_names(bank)) |
| expected_names = {row[2] for row in expected} |
| actual_names = set(tensor_entries) |
| missing = sorted(expected_names - actual_names) |
| extra = sorted(actual_names - expected_names) |
| if missing or extra: |
| raise ValueError( |
| f"bank tensor identity mismatch: missing={missing[:3]} ({len(missing)}), " |
| f"extra={extra[:3]} ({len(extra)})" |
| ) |
|
|
| dtypes: set[str] = set() |
| payload_bytes = 0 |
| intervals: list[tuple[int, int, str]] = [] |
| for layer, expert, name, expected_shape in expected: |
| entry = tensor_entries[name] |
| shape = tuple(int(item) for item in entry.get("shape", [])) |
| if shape != expected_shape: |
| raise ValueError( |
| f"{name} has shape {shape}, expected {expected_shape} " |
| f"(layer={layer}, expert={expert})" |
| ) |
| dtype = str(entry.get("dtype")) |
| if dtype not in DTYPE_BYTES: |
| raise ValueError(f"{name} has unsupported training dtype {dtype}") |
| offsets = entry.get("data_offsets") |
| if not isinstance(offsets, list) or len(offsets) != 2: |
| raise ValueError(f"{name} has malformed data offsets") |
| start, end = map(int, offsets) |
| expected_bytes = expected_shape[0] * expected_shape[1] * DTYPE_BYTES[dtype] |
| if start < 0 or end <= start or end - start != expected_bytes: |
| raise ValueError( |
| f"{name} has invalid data offsets {offsets}; expected {expected_bytes} bytes" |
| ) |
| intervals.append((start, end, name)) |
| payload_bytes += end - start |
| dtypes.add(dtype) |
|
|
| |
| |
| |
| previous_end = 0 |
| for start, end, name in sorted(intervals): |
| if start != previous_end: |
| relation = "overlap" if start < previous_end else "gap" |
| raise ValueError( |
| f"bank payload has a {relation} before {name}: " |
| f"expected offset {previous_end}, found {start}" |
| ) |
| previous_end = end |
|
|
| if previous_end != file_payload or payload_bytes != file_payload: |
| raise ValueError( |
| f"bank payload coverage mismatch: last={previous_end}, summed={payload_bytes}, " |
| f"file={file_payload}" |
| ) |
| return BankValidation( |
| bank_id=str(bank["id"]), |
| tensor_count=len(expected), |
| payload_bytes=payload_bytes, |
| dtypes=tuple(sorted(dtypes)), |
| layers=tuple(range(30)), |
| ) |
|
|
|
|
| def validate_bank_header(bank_path: Path, bank: dict[str, Any]) -> BankValidation: |
| data_start, header = safetensors_header(bank_path) |
| return validate_bank_header_entries(header, bank_path.stat().st_size - data_start, bank) |
|
|
|
|
| def validate_curriculum_row(row: dict[str, Any], expected_split: str) -> None: |
| if row.get("schema") != "AutonomaFableRouterRecord.v2": |
| raise ValueError(f"unexpected curriculum schema: {row.get('schema')}") |
| if row.get("split") != expected_split: |
| raise ValueError(f"row split {row.get('split')} does not match {expected_split}") |
| if row.get("lane") not in { |
| "host_preservation", |
| "verified_expert", |
| "interaction_pattern", |
| }: |
| raise ValueError(f"unexpected curriculum lane: {row.get('lane')}") |
| messages = row.get("messages") |
| if not isinstance(messages, list) or not messages: |
| raise ValueError("curriculum row has no messages") |
| if not any(message.get("role") == "assistant" for message in messages if isinstance(message, dict)): |
| raise ValueError("curriculum row has no assistant target") |
|
|
|
|
| def iter_jsonl(path: Path) -> Iterable[dict[str, Any]]: |
| with path.open("r", encoding="utf-8") as handle: |
| for line_number, line in enumerate(handle, 1): |
| try: |
| payload = json.loads(line) |
| except json.JSONDecodeError as exc: |
| raise ValueError(f"invalid JSONL at {path}:{line_number}: {exc}") from exc |
| if not isinstance(payload, dict): |
| raise ValueError(f"non-object JSONL row at {path}:{line_number}") |
| yield payload |
|
|
|
|
| def verify_file(path: Path, expected_bytes: int, expected_sha256: str) -> dict[str, Any]: |
| actual_bytes = path.stat().st_size |
| actual_sha256 = sha256(path) |
| if actual_bytes != expected_bytes or actual_sha256 != expected_sha256: |
| raise ValueError( |
| f"artifact mismatch for {path}: bytes={actual_bytes}/{expected_bytes}, " |
| f"sha256={actual_sha256}/{expected_sha256}" |
| ) |
| return {"path": str(path), "bytes": actual_bytes, "sha256": actual_sha256} |
|
|