"""Evaluate an actual Labrador adapter with the unchanged Session 3 decoder. This does not train, prompt with references, remove repetition, or gate silence. The optional private runtime is exclusively for tests and must mark test_runtime. """ from __future__ import annotations import hashlib import json from pathlib import Path import time import labrador_eval_auto as core VERSION = "labrador-pilot-eval-1.0.0" BASE_SPEC = { "name": "labrador", "model_id": "Qwen/Qwen3-ASR-1.7B-hf", "revision": "bcd2b5b7f32b480ab5790554cfa8347f246a14f3", } def adapter_identity(adapter_dir): directory = Path(adapter_dir).resolve() config_path = directory / "adapter_config.json" weights_path = directory / "adapter_model.safetensors" config = json.loads(config_path.read_text()) return { "format": "peft_lora", "config": config, "config_sha256": core._file_sha(config_path), "weights_sha256": core._file_sha(weights_path), "weights_bytes": weights_path.stat().st_size, } class AdapterRuntime(core._CudaRuntime): def __init__(self, adapter_dir): super().__init__() self.adapter_dir = Path(adapter_dir) def load(self, spec): from pilot_train import load_adapter_into_model super().load(spec) model = load_adapter_into_model(self.model, self.adapter_dir, loaded_model_spec=spec) if model is not None: self.model = model self.model.eval() if any(p.device.type != "cuda" for p in self.model.parameters()): raise RuntimeError("The candidate must remain entirely on the GPU.") def _write_summary(output, rows, results, metadata, sessions): ordered = [results[r["id"]] for r in rows if r["id"] in results] conditions = {} for condition in sorted({row["condition"] for row in rows}): ids = {r["id"] for r in rows if r["condition"] == condition} conditions[condition] = core._aggregate( [r for r in ordered if r["id"] in ids], len(ids)) summary = { "scope": "Actual saved Labrador adapter evaluation; exploratory development data.", "runner_version": VERSION, "run_fingerprint": metadata["run_fingerprint"], "runtime": metadata["runtime"], "adapter_identity": metadata["adapter_identity"], "model_weights_trained": metadata["model_weights_trained"], "overall": core._aggregate(ordered, len(rows)), "conditions": conditions, "updated_utc": core._now(), } summary["valid_for_comparison"] = ( summary["overall"]["complete"] and not metadata["runtime"].get("test_runtime")) core._atomic_json(output / "summary.json", summary) core._atomic_json(output / "model_sessions.json", {"labrador": sessions}) return summary def evaluate_adapter(manifest, adapter_dir, output_dir, *, max_new_tokens=256, allow_incomplete=True, _runtime=None): """Resume actual adapter predictions; preserve failures and all token evidence.""" if max_new_tokens != 256: raise ValueError("The preregistered pilot uses a 256-token cap.") rows = core._manifest_rows(manifest) identity = adapter_identity(adapter_dir) training_path = Path(adapter_dir).resolve().parent / "training_summary.json" training_summary = json.loads(training_path.read_text()) if _runtime is not None and not _runtime.metadata.get("test_runtime"): raise ValueError("A substituted runtime must identify itself as a test.") runtime = _runtime if _runtime is not None else AdapterRuntime(adapter_dir) output = Path(output_dir).resolve() output.mkdir(parents=True, exist_ok=True) config = { "runner_version": VERSION, "runner_sha256": core._file_sha(Path(__file__)), "decoder_runner_sha256": core._file_sha(Path(core.__file__)), "models": [BASE_SPEC], "manifest": rows, "max_new_tokens": max_new_tokens, "language": None, "language_mode": "auto_language", "prompt": None, "assistant_prefill": "", "parser_version": core.PARSER_VERSION, "batch_size": 1, "do_sample": False, "num_beams": 1, "normalization_version": core.NORMALIZATION_VERSION, "normalization_description": core.NORMALIZATION_DESCRIPTION, "decode_description": core.DECODE_DESCRIPTION, "runtime": runtime.metadata, "adapter_identity": identity, "adapter": { "sha256": identity["weights_sha256"], "base_model_id": BASE_SPEC["model_id"], "base_revision": BASE_SPEC["revision"], }, "training_summary": training_summary, "training_summary_sha256": core._file_sha(training_path), "model_weights_trained": (not runtime.metadata.get("test_runtime") and training_summary.get("completed_optimizer_steps", 0) > 0), } fingerprint = core._digest(config) metadata_path = output / "run_metadata.json" if metadata_path.exists(): metadata = json.loads(metadata_path.read_text()) if metadata.get("run_fingerprint") != fingerprint: raise ValueError("Candidate weights, data, code or runtime changed. Use a new output directory.") else: if any(output.iterdir()): raise ValueError("Candidate output has files but no run metadata.") metadata = {**config, "run_fingerprint": fingerprint, "created_utc": core._now()} core._atomic_json(metadata_path, metadata) journal = output / "labrador.jsonl" results = core._read_journal(journal, fingerprint, {r["id"] for r in rows}) sessions_file = output / "model_sessions.json" sessions = json.loads(sessions_file.read_text()).get("labrador", []) if sessions_file.exists() else [] pending = [r for r in rows if results.get(r["id"], {}).get("status") != "ok"] interrupted = None if pending: session = {"started_utc": core._now(), "pending_clips": len(pending)} sessions.append(session) print(f"Labrador: loading the saved adapter, then evaluating {len(pending)} clips.") try: started = time.perf_counter() runtime.load(BASE_SPEC) session["load_seconds"] = time.perf_counter() - started started = time.perf_counter() runtime.transcribe(pending[0]["audio_path"], max_new_tokens=16, language=None) session["warmup_seconds"] = time.perf_counter() - started for index, row in enumerate(pending, 1): record = {**row, "model": "labrador", "run_fingerprint": fingerprint, "attempt_utc": core._now(), "status": "error"} try: prediction = runtime.transcribe(row["audio_path"], max_new_tokens=max_new_tokens, language=None) record.update(prediction) ids = prediction.get("generated_token_ids") count = prediction.get("generated_tokens") if not isinstance(prediction.get("hypothesis"), str): raise ValueError("No valid hypothesis string was returned.") if (not isinstance(count, int) or not 1 <= count <= max_new_tokens or not isinstance(ids, list) or len(ids) != count or any(not isinstance(i, int) or isinstance(i, bool) for i in ids)): raise ValueError("Complete generated-token evidence is missing or invalid.") if prediction.get("parse_status") != "ok": raise ValueError(prediction.get("parse_error") or "Malformed language header.") record["status"] = "ok" if prediction.get("ended_with_eos") else "truncated" record["score"] = core.word_errors(row["reference"], prediction["hypothesis"]) if record["status"] == "truncated": record["error"] = "Generation did not finish with EOS." except Exception as error: record.update(status="error", score=None, error=core._safe_error(error)) core._append_journal(journal, record) results[row["id"]] = record print(f" {index}/{len(pending)} {row['id']}: {record['status']}") except KeyboardInterrupt as error: interrupted = error session["error"] = "Interrupted; completed predictions are saved." except Exception as error: session["error"] = core._safe_error(error) for row in pending: if results.get(row["id"], {}).get("status") == "ok": continue record = {**row, "model": "labrador", "run_fingerprint": fingerprint, "attempt_utc": core._now(), "status": "error", "score": None, "error": f"Adapter loading/warm-up failed: {session['error']}"} core._append_journal(journal, record) results[row["id"]] = record finally: runtime.unload() session["finished_utc"] = core._now() _write_summary(output, rows, results, metadata, sessions) summary = _write_summary(output, rows, results, metadata, sessions) if interrupted is not None: raise interrupted if not summary["overall"]["complete"] and not allow_incomplete: raise core.IncompleteEvaluationError("Candidate predictions are incomplete; inspect the saved journal.") return summary