Files
elizaos--eliza/packages/training/scripts/verify_optimization_stack.py
T
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

298 lines
11 KiB
Python

"""Verify the Eliza-1 PolarQuant + QJL + TurboQuant optimization stack on a bundle.
Asserts on a staged/published Eliza-1 bundle dir. It still accepts historical
``eliza1-optimized/`` directories so old evidence can be audited after the
optimizer's retirement:
* ``eliza1_manifest.json.applied.{polarquant,qjl,turboquant,fused_turboquant}.applied``
is true (or honestly recorded as skipped + reason).
* The matching GGUF ``.eliza1.json`` sidecar carries the recipe
block_layout_version / codebook_hash / per_block_tolerance pins under
``polarquant.*`` / ``qjl.*`` / ``turboquant.*`` /
``fused_turboquant.*`` (mirrored from ``recipeManifest`` in the bundle
manifest schema).
* The stage sidecar files exist and the recorded SHA matches the
safetensors blob.
* ``qjl_config.json`` + ``turboquant.json`` shape against the model arch
(``num_hidden_layers`` plus full/global-attention metadata when present).
* For hybrid/windowed-attention models, skipped/local layers and full/global
layers are disjoint and cover every decoder index when the sidecar records
both lists.
Run on a staged bundle:
uv run python scripts/verify_optimization_stack.py \\
--bundle-dir /tmp/eliza1-stage/eliza-1-2b
On a historical optimizer output:
uv run python scripts/verify_optimization_stack.py \\
--opt-dir checkpoints/eliza-1-2b-apollo-1778551769/eliza1-optimized
Exits non-zero on a failed assertion (publish-blocking).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))
from quantization._kernel_manifest import ( # noqa: E402
KERNEL_BLOCK_LAYOUT_VERSIONS,
KERNEL_CODEBOOK_HASHES,
KERNEL_PER_BLOCK_TOLERANCE,
)
@dataclass
class Report:
bundle: str
checks: list[tuple[str, bool, str]] = field(default_factory=list)
def check(self, name: str, ok: bool, detail: str = "") -> None:
self.checks.append((name, ok, detail))
@property
def ok(self) -> bool:
return all(c[1] for c in self.checks)
def render(self) -> str:
lines = [f"verify_optimization_stack({self.bundle})"]
for name, ok, detail in self.checks:
mark = "PASS" if ok else "FAIL"
lines.append(f" [{mark}] {name}{(' — ' + detail) if detail else ''}")
lines.append(f" → {'OK' if self.ok else 'BROKEN'}")
return "\n".join(lines)
def _read_json(path: Path) -> dict | None:
if not path.is_file():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return None
def _sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def _verify_recipe_pins(
rep: Report, sidecar: dict | None, key: str, target: str
) -> None:
"""Assert the recipe kernel_manifest fragment matches the canonical pins."""
if sidecar is None:
rep.check(f"{key}.kernel_manifest present", False, "sidecar missing")
return
km = sidecar.get("kernel_manifest") or {}
blv = (km.get("block_layout_version") or {}).get(target)
cbh = (km.get("codebook_hash") or {}).get(target)
tol = (km.get("per_block_tolerance") or {}).get(target)
rep.check(
f"{key}.block_layout_version[{target}]",
blv == KERNEL_BLOCK_LAYOUT_VERSIONS[target],
f"got {blv!r}, want {KERNEL_BLOCK_LAYOUT_VERSIONS[target]!r}",
)
rep.check(
f"{key}.codebook_hash[{target}]",
cbh == KERNEL_CODEBOOK_HASHES[target],
f"got {cbh!r}, want {KERNEL_CODEBOOK_HASHES[target]!r}",
)
rep.check(
f"{key}.per_block_tolerance[{target}]",
tol == KERNEL_PER_BLOCK_TOLERANCE[target],
f"got {tol!r}, want {KERNEL_PER_BLOCK_TOLERANCE[target]!r}",
)
def verify_opt_dir(opt_dir: Path) -> Report:
"""Verify a historical ``eliza1-optimized/`` output directory."""
rep = Report(bundle=str(opt_dir))
manifest = _read_json(opt_dir / "gguf" / "eliza1_manifest.json")
rep.check("eliza1_manifest.json present", manifest is not None)
polar = _read_json(opt_dir / "stage-polarquant" / "polarquant_config.json")
qjl = _read_json(opt_dir / "stage-qjl" / "qjl_config.json")
tbq = _read_json(opt_dir / "stage-turboquant" / "turboquant.json")
fused_tbq = _read_json(opt_dir / "stage-fused_turboquant" / "fused_turboquant.json")
_verify_recipe_pins(rep, polar, "polarquant", "polar_q4")
_verify_recipe_pins(rep, qjl, "qjl", "qjl1_256")
for target in ("turbo3", "turbo4", "turbo3_tcq"):
_verify_recipe_pins(rep, tbq, "turboquant", target)
_verify_recipe_pins(rep, fused_tbq, "fused_turboquant", target)
# polarquant_artifacts.safetensors must exist next to the polar sidecar
polar_art = opt_dir / "stage-polarquant" / "polarquant_artifacts.safetensors"
rep.check(
"polarquant_artifacts.safetensors present",
polar_art.is_file(),
str(polar_art),
)
if manifest is not None:
applied = manifest.get("applied") or {}
for stage in ("polarquant", "qjl", "turboquant", "fused_turboquant"):
block = applied.get(stage) or {}
rep.check(
f"manifest.applied.{stage}",
bool(block.get("applied")) or bool(block.get("skipped")),
f"got {block!r}",
)
# Sanity-check qjl/turboquant against the model arch when sidecars carry it.
if qjl is not None:
n_full = qjl.get("n_full_attention_layers")
n_total = qjl.get("num_hidden_layers")
rep.check(
"qjl.n_full_attention_layers <= num_hidden_layers",
isinstance(n_full, int) and isinstance(n_total, int) and n_full <= n_total,
f"n_full={n_full} num_hidden_layers={n_total}",
)
if tbq is not None:
full = tbq.get("full_attention_layers")
skipped = tbq.get("linear_attention_layers_skipped") or []
n_total = tbq.get("num_hidden_layers")
if (
isinstance(full, list)
and isinstance(skipped, list)
and isinstance(n_total, int)
):
union_covers = set(full) | set(skipped) == set(range(n_total))
rep.check(
"turboquant.full + skipped covers every decoder layer",
union_covers,
f"full={len(full)} skipped={len(skipped)} total={n_total}",
)
rep.check(
"turboquant.full ∩ skipped is empty",
not (set(full) & set(skipped)),
f"overlap={sorted(set(full) & set(skipped))}",
)
return rep
def verify_bundle_dir(bundle_dir: Path) -> Report:
"""Verify a staged/published Eliza-1 bundle dir (post stage_base_v1)."""
rep = Report(bundle=str(bundle_dir))
bundle_manifest = _read_json(bundle_dir / "eliza-1.manifest.json")
rep.check("eliza-1.manifest.json present", bundle_manifest is not None)
if bundle_manifest is None:
return rep
tq = bundle_manifest.get("textQuant") or {}
optimized = bool(tq.get("optimized"))
rep.check("textQuant.optimized is true", optimized, json.dumps(tq)[:200])
# The bundle stages the per-recipe sidecar JSON next to the GGUF as
# <text-gguf>.gguf.eliza1.json — that's the runtime contract. When the
# caller passes a manifest-only checkout (no GGUF blob downloaded), we
# check the textQuant block instead of the sidecar.
text_dir = bundle_dir / "text"
gguf_files = list(text_dir.glob("*.gguf")) if text_dir.is_dir() else []
eliza1: dict | None = None
if gguf_files:
side = gguf_files[0].with_suffix(".gguf.eliza1.json")
eliza1 = _read_json(side)
rep.check(
"<text>.gguf.eliza1.json present",
eliza1 is not None,
str(side),
)
else:
# No GGUF on disk (typical when verifying just the manifest+sidecar
# tracked under the HF repo without pulling the heavy blob). Fall
# back to the textQuant block in the manifest — it carries the same
# fields the sidecar would.
if isinstance(tq, dict) and optimized:
eliza1 = {
k: tq.get(k)
for k in ("polarquant", "qjl", "turboquant", "fused_turboquant")
}
if eliza1 is None:
return rep
for stage in ("polarquant", "qjl", "turboquant", "fused_turboquant"):
rep.check(
f"eliza1.{stage} block present",
isinstance(eliza1.get(stage), dict),
json.dumps(eliza1.get(stage))[:80] if eliza1.get(stage) else "missing",
)
# If the manifest declares recipe pins (`recipeManifest`), cross-check
# against the canonical kernel manifest values.
rm = (bundle_manifest.get("kernels") or {}).get("recipeManifest") or {}
for tgt in ("turbo3", "turbo4", "turbo3_tcq", "qjl1_256", "polar_q4"):
if tgt in rm:
pins = rm[tgt]
rep.check(
f"recipeManifest[{tgt}].blockLayoutVersion",
pins.get("blockLayoutVersion") == KERNEL_BLOCK_LAYOUT_VERSIONS[tgt],
f"got {pins.get('blockLayoutVersion')!r}",
)
rep.check(
f"recipeManifest[{tgt}].codebookHash",
pins.get("codebookHash") == KERNEL_CODEBOOK_HASHES[tgt],
f"got {pins.get('codebookHash')!r}",
)
return rep
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0])
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument(
"--opt-dir",
type=Path,
help="Historical eliza1-optimized/ output directory.",
)
g.add_argument(
"--bundle-dir",
type=Path,
help="Staged Eliza-1 bundle dir (the dir uploaded under elizaos/eliza-1/bundles/<tier>).",
)
ap.add_argument(
"--json",
action="store_true",
help="Emit JSON instead of human-readable report.",
)
args = ap.parse_args(argv)
rep = (
verify_opt_dir(args.opt_dir)
if args.opt_dir
else verify_bundle_dir(args.bundle_dir)
)
if args.json:
print(
json.dumps(
{
"bundle": rep.bundle,
"ok": rep.ok,
"checks": [
{"name": n, "ok": ok, "detail": d} for n, ok, d in rep.checks
],
},
indent=2,
)
)
else:
print(rep.render())
return 0 if rep.ok else 1
if __name__ == "__main__":
raise SystemExit(main())