Download code/src/experiment_001b_runner.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 27.4 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/experiment_001b_runner.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/src/experiment_001b_runner.py
-
curl -L -o experiment_001b_runner.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/experiment_001b_runner.py
27.4 kB
| """Pure planning and split checks for the Modal Experiment 001B runner.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| from typing import Iterable, Mapping, Sequence | |
| CONDITIONS = ( | |
| "base", | |
| "edited", | |
| "published_constant", | |
| "independent_constant", | |
| "norm_matched_random", | |
| "rank1_activation_dependent", | |
| ) | |
| EXPLORATORY_PUBLISHED_JOINT_MEAN = "published_constant_joint_signed_mean_exploratory" | |
| EXPLORATORY_CONDITIONS = (EXPLORATORY_PUBLISHED_JOINT_MEAN,) | |
| EXPLORATORY_CANDIDATE_IDS = { | |
| EXPLORATORY_PUBLISHED_JOINT_MEAN: "published_constant__joint_signed_mean", | |
| } | |
| PRIMARY_SAMPLING = { | |
| "temperature": 0.6, | |
| "top_p": 0.95, | |
| "top_k": 20, | |
| "presence_penalty": 1.5, | |
| } | |
| MAX_NEW_TOKENS = 32768 | |
| MAX_GENERATION_SECONDS = 1500 | |
| FUNCTION_TIMEOUT_SECONDS = 1800 | |
| # Conservative blended cap based on prior Modal A10 GPU + CPU + memory usage. | |
| CONSERVATIVE_A10_ALL_IN_USD_PER_HOUR = 2.0 | |
| def sha256_bytes(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| def parse_jsonl_bytes(raw: bytes, *, label: str = "JSONL") -> list[dict]: | |
| rows = [] | |
| for line_no, line in enumerate(raw.splitlines(), start=1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| item = json.loads(line) | |
| except json.JSONDecodeError as exc: | |
| raise ValueError(f"{label} line {line_no} is invalid JSON: {exc}") from exc | |
| if not isinstance(item, dict): | |
| raise ValueError(f"{label} line {line_no} must be an object") | |
| rows.append(item) | |
| return rows | |
| def validate_manifest(manifest: Mapping) -> None: | |
| """Validate the frozen split design using manifest metadata only.""" | |
| split_rows = manifest.get("split_rows") | |
| previous = manifest.get("excluded_previous_rows") | |
| if not isinstance(split_rows, Mapping) or not isinstance(previous, list): | |
| raise ValueError("split manifest is missing split_rows or excluded_previous_rows") | |
| all_ids: list[int] = [] | |
| for split in ("discovery", "calibration", "heldout"): | |
| values = split_rows.get(split) | |
| if not isinstance(values, list) or not values: | |
| raise ValueError(f"split manifest is missing non-empty {split} row IDs") | |
| ids = [int(value) for value in values] | |
| if len(ids) != len(set(ids)): | |
| raise ValueError(f"duplicate row ID in {split} split metadata") | |
| all_ids.extend(ids) | |
| if len(all_ids) != len(set(all_ids)): | |
| raise ValueError("discovery, calibration and heldout split IDs overlap") | |
| if set(all_ids) & {int(value) for value in previous}: | |
| raise ValueError("001B split overlaps rows used by an earlier ModelClinic run") | |
| def validate_split_bytes(split: str, raw: bytes, manifest: Mapping) -> list[dict]: | |
| """Verify one frozen split's digest, row order and minimal schema.""" | |
| if split not in {"discovery", "calibration", "heldout"}: | |
| raise ValueError(f"unknown split: {split}") | |
| validate_manifest(manifest) | |
| filename = f"001b_{split}_{len(manifest['split_rows'][split])}.jsonl" | |
| expected_hash = manifest.get("split_file_sha256", {}).get(filename) | |
| if not expected_hash or sha256_bytes(raw) != expected_hash: | |
| raise ValueError(f"{split} split hash does not match frozen manifest") | |
| rows = parse_jsonl_bytes(raw, label=split) | |
| expected_rows = [int(value) for value in manifest["split_rows"][split]] | |
| actual_rows = [int(item["source_row"]) for item in rows if "source_row" in item] | |
| if actual_rows != expected_rows: | |
| raise ValueError(f"{split} row IDs do not match frozen manifest") | |
| required = {"source_row", "problem", "answer", "unique_id"} | |
| for index, item in enumerate(rows): | |
| missing = required - item.keys() | |
| if missing: | |
| raise ValueError(f"{split} row {index} missing fields: {sorted(missing)}") | |
| return rows | |
| def validate_heldout_rows(questions: Sequence[Mapping], manifest: Mapping) -> None: | |
| """Reject non-heldout rows even when the Modal function is called directly.""" | |
| validate_manifest(manifest) | |
| allowed = {int(value) for value in manifest["split_rows"]["heldout"]} | |
| rows = [int(question["source_row"]) for question in questions] | |
| if not rows or len(rows) != len(set(rows)): | |
| raise ValueError("heldout input must contain unique source rows") | |
| unexpected = set(rows) - allowed | |
| if unexpected: | |
| raise ValueError(f"remote heldout batch contains non-heldout rows: {sorted(unexpected)}") | |
| def validate_heldout_content( | |
| questions: Sequence[Mapping], frozen_questions: Sequence[Mapping] | |
| ) -> None: | |
| """Reject remote heldout payloads whose row content differs from the frozen split.""" | |
| expected_by_row = {int(question["source_row"]): dict(question) for question in frozen_questions} | |
| actual_rows = [int(question["source_row"]) for question in questions] | |
| if not actual_rows or len(actual_rows) != len(set(actual_rows)): | |
| raise ValueError("heldout input must contain unique source rows") | |
| for question in questions: | |
| row = int(question["source_row"]) | |
| expected = expected_by_row.get(row) | |
| if expected is None: | |
| raise ValueError(f"heldout input contains unexpected source row {row}") | |
| if json.dumps(dict(question), sort_keys=True, ensure_ascii=False, separators=(",", ":")) != json.dumps( | |
| expected, sort_keys=True, ensure_ascii=False, separators=(",", ":") | |
| ): | |
| raise ValueError(f"heldout source row {row} content differs from frozen split") | |
| def validate_heldout_calibration( | |
| manifest: Mapping, | |
| artifact: Mapping, | |
| *, | |
| run_id: str, | |
| expected_stage: str, | |
| split_manifest_sha256: str, | |
| calibration_rows: Sequence[int], | |
| heldout_rows: Sequence[int], | |
| expected_candidate_ids: Sequence[str], | |
| expected_model: Mapping, | |
| parent_artifact_sha256: str, | |
| max_new_tokens: int, | |
| generation_seconds: int, | |
| heldout_max_generation_seconds: int, | |
| sampling: Mapping, | |
| ) -> None: | |
| """Require a complete, internally matching long-calibration freeze for heldout.""" | |
| if manifest.get("status") != "complete": | |
| raise ValueError("long calibration manifest is incomplete") | |
| if manifest.get("run_id") != run_id or artifact.get("run_id") != run_id: | |
| raise ValueError("long calibration run ID does not match heldout run") | |
| if manifest.get("phase") != "finalists" or artifact.get("phase") != "finalists": | |
| raise ValueError("heldout requires the finalist calibration phase") | |
| if manifest.get("calibration_stage") != expected_stage or artifact.get("calibration_stage") != expected_stage: | |
| raise ValueError("long calibration stage does not match heldout requirements") | |
| artifact_hash = artifact.get("calibration_artifact_sha256") | |
| hash_payload = dict(artifact) | |
| hash_payload.pop("calibration_artifact_sha256", None) | |
| canonical = (json.dumps(hash_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") | |
| if not artifact_hash or artifact_hash != sha256_bytes(canonical): | |
| raise ValueError("long calibration artifact hash does not match its contents") | |
| manifest_artifact_hash = manifest.get("calibration_artifact_sha256") | |
| if manifest_artifact_hash is not None and manifest_artifact_hash != artifact_hash: | |
| raise ValueError("long calibration manifest and artifact hashes do not match") | |
| if not parent_artifact_sha256 or artifact.get("parent_calibration_artifact_sha256") != parent_artifact_sha256: | |
| raise ValueError("long calibration artifact does not match the completed screen parent") | |
| if manifest.get("parent_calibration_artifact_sha256") != parent_artifact_sha256: | |
| raise ValueError("long calibration manifest does not match the completed screen parent") | |
| manifest_model = manifest.get("model") | |
| if artifact.get("model") != dict(expected_model) or (manifest_model is not None and manifest_model != dict(expected_model)): | |
| raise ValueError("long calibration model revisions or precision do not match heldout model") | |
| if manifest.get("split_manifest_sha256") != split_manifest_sha256 or artifact.get("split_manifest_sha256") != split_manifest_sha256: | |
| raise ValueError("long calibration uses a different frozen split manifest") | |
| expected_calibration_rows = [int(row) for row in calibration_rows] | |
| expected_heldout_rows = [int(row) for row in heldout_rows] | |
| if set(expected_calibration_rows) & set(expected_heldout_rows): | |
| raise ValueError("calibration and heldout rows overlap") | |
| if manifest.get("calibration_rows") != expected_calibration_rows: | |
| raise ValueError("long calibration manifest has incorrect calibration row coverage") | |
| if manifest.get("heldout_rows") != expected_heldout_rows: | |
| raise ValueError("long calibration manifest has incorrect heldout row coverage") | |
| if artifact.get("calibration", {}).get("source_rows") != expected_calibration_rows: | |
| raise ValueError("long calibration artifact has incorrect calibration row coverage") | |
| artifact_calibration = artifact.get("calibration", {}) | |
| manifest_calibration = manifest.get("calibration") | |
| if (artifact_calibration.get("source_rows") != expected_calibration_rows | |
| or (manifest_calibration is not None and manifest_calibration != artifact_calibration) | |
| or manifest.get("calibration_sha256") != artifact.get("calibration_sha256") | |
| or manifest.get("independent_sha256") != artifact.get("independent_sha256")): | |
| raise ValueError("long calibration manifest and artifact calibration provenance does not match") | |
| if manifest.get("expected_calibration_question_seeds") != [[row, 0] for row in expected_calibration_rows]: | |
| raise ValueError("long calibration manifest has incorrect expected question-seed keys") | |
| expected_ids = [str(candidate_id) for candidate_id in expected_candidate_ids] | |
| if (manifest.get("stage2_candidate_ids") != expected_ids | |
| or artifact.get("stage2_candidate_ids") != expected_ids): | |
| raise ValueError("long calibration finalist candidate IDs are incomplete or out of order") | |
| manifest_candidates = manifest.get("calibration_candidates") | |
| artifact_candidates = artifact.get("grid_candidates") | |
| if not isinstance(manifest_candidates, list) or not isinstance(artifact_candidates, list): | |
| raise ValueError("long calibration manifest or artifact is missing candidate records") | |
| manifest_ids = [str(item.get("candidate_id")) for item in manifest_candidates] | |
| artifact_ids = [str(item.get("candidate_id")) for item in artifact_candidates] | |
| if manifest_ids != expected_ids or artifact_ids != expected_ids: | |
| raise ValueError("long calibration finalist candidate records are incomplete or duplicated") | |
| family_ids: dict[str, list[str]] = {"published_constant": [], "independent_constant": []} | |
| manifest_by_id = {str(item["candidate_id"]): item for item in manifest_candidates} | |
| grid_by_id = {str(item["candidate_id"]): item for item in artifact_candidates} | |
| for config in manifest_candidates: | |
| candidate_id = str(config["candidate_id"]) | |
| family = str(config.get("family", "")) | |
| if family not in family_ids: | |
| raise ValueError(f"unknown long calibration candidate family: {family}") | |
| family_ids[family].append(candidate_id) | |
| if (config.get("max_new_tokens") != max_new_tokens | |
| or config.get("max_generation_seconds") != generation_seconds | |
| or config.get("sampling") != dict(sampling)): | |
| raise ValueError(f"long calibration candidate {candidate_id} uses unexpected generation settings") | |
| candidate = grid_by_id.get(candidate_id) | |
| if (candidate is None or candidate.get("family") != family | |
| or candidate.get("coefficients") != config.get("coefficients") | |
| or candidate.get("max_new_tokens") != max_new_tokens | |
| or candidate.get("max_generation_seconds") != generation_seconds | |
| or candidate.get("sampling") != dict(sampling) | |
| or candidate.get("calibration_rows") != expected_calibration_rows): | |
| raise ValueError(f"long calibration artifact configuration differs for {candidate_id}") | |
| if manifest.get("selection_families") != family_ids: | |
| raise ValueError("long calibration selection families do not match its finalist candidates") | |
| expected_keys = sorted((row, 0) for row in expected_calibration_rows) | |
| for candidate_id in expected_ids: | |
| candidate = grid_by_id[candidate_id] | |
| if candidate.get("status") != "complete": | |
| raise ValueError(f"long calibration candidate {candidate_id} is incomplete") | |
| outcomes = candidate.get("prompt_outcomes") | |
| if not isinstance(outcomes, list): | |
| raise ValueError(f"long calibration candidate {candidate_id} is missing prompt outcomes") | |
| keys = sorted((int(item["source_row"]), int(item.get("seed", 0))) for item in outcomes) | |
| if keys != expected_keys or any( | |
| item.get("error") or not isinstance(item.get("score"), Mapping) | |
| or item["score"].get("status") == "error" | |
| for item in outcomes | |
| ): | |
| raise ValueError(f"long calibration candidate {candidate_id} has missing or erroneous outcomes") | |
| selected = artifact.get("selected") | |
| if not isinstance(selected, Mapping) or set(selected) != set(family_ids): | |
| raise ValueError("long calibration artifact has missing family selections") | |
| for family, candidate_ids in family_ids.items(): | |
| chosen = selected[family] | |
| chosen_id = str(chosen.get("candidate_id", "")) | |
| if chosen_id not in candidate_ids: | |
| raise ValueError(f"long calibration selected an unknown candidate for {family}") | |
| if (manifest_by_id[chosen_id].get("selected") is not True | |
| or grid_by_id[chosen_id].get("coefficients") != chosen.get("coefficients")): | |
| raise ValueError(f"long calibration manifest does not mark the selected {family} candidate") | |
| for candidate_id in candidate_ids: | |
| if manifest_by_id[candidate_id].get("selected") is not (candidate_id == chosen_id): | |
| raise ValueError(f"long calibration manifest has inconsistent selected flags for {family}") | |
| if manifest.get("selected_conditions") != selected: | |
| raise ValueError("long calibration manifest and artifact selections do not match") | |
| if manifest.get("heldout_condition_config_ids") != artifact.get("heldout_condition_config_ids"): | |
| raise ValueError("long calibration manifest and artifact heldout config IDs do not match") | |
| expected_config_ids = { | |
| "base": "base", | |
| "edited": "edited", | |
| "published_constant": selected["published_constant"]["candidate_id"], | |
| "independent_constant": selected["independent_constant"]["candidate_id"], | |
| "norm_matched_random": "norm_matched_random__norm_of_published_constant", | |
| "rank1_activation_dependent": "rank1_activation_dependent__rank_one_delta", | |
| } | |
| if artifact.get("heldout_condition_config_ids") != expected_config_ids: | |
| raise ValueError("long calibration heldout condition mapping is incomplete or inconsistent") | |
| selection = artifact.get("selection", {}) | |
| if selection.get("heldout_used") is not False or selection.get("eligible_data") != "calibration prompts only": | |
| raise ValueError("heldout selection metadata does not prove calibration-only selection") | |
| if (manifest.get("heldout_max_new_tokens") != max_new_tokens | |
| or manifest.get("heldout_max_generation_seconds") != heldout_max_generation_seconds | |
| or manifest.get("heldout_sampling") != dict(sampling)): | |
| raise ValueError("long calibration manifest has unexpected heldout generation settings") | |
| if (manifest.get("calibration_max_new_tokens") != max_new_tokens | |
| or manifest.get("calibration_generation_seconds") != generation_seconds): | |
| raise ValueError("long calibration manifest has unexpected finalist generation settings") | |
| def normalize_calibration_manifest_from_artifact( | |
| manifest: Mapping, | |
| artifact: Mapping, | |
| *, | |
| original_manifest_sha256: str, | |
| ) -> dict: | |
| """Bind a legacy stage manifest to the self-hashed artifact and log config drift.""" | |
| normalized = dict(manifest) | |
| artifact_hash = artifact.get("calibration_artifact_sha256") | |
| artifact_payload = dict(artifact) | |
| artifact_payload.pop("calibration_artifact_sha256", None) | |
| artifact_canonical = ( | |
| json.dumps(artifact_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" | |
| ).encode("utf-8") | |
| if not artifact_hash or sha256_bytes(artifact_canonical) != artifact_hash: | |
| raise ValueError("cannot normalize manifest: calibration artifact self-hash is invalid") | |
| for field in ("calibration_artifact_sha256",): | |
| old = normalized.get(field) | |
| if old is not None and old != artifact_hash: | |
| raise ValueError(f"cannot normalize manifest: {field} disagrees with calibration artifact") | |
| for field in ("model", "calibration"): | |
| old = normalized.get(field) | |
| if old is not None and old != artifact.get(field): | |
| raise ValueError(f"cannot normalize manifest: {field} disagrees with calibration artifact") | |
| expected_ids = [str(value) for value in artifact.get("stage2_candidate_ids", [])] | |
| planned_candidates = normalized.get("calibration_candidates") | |
| actual_candidates = artifact.get("grid_candidates") | |
| if not isinstance(planned_candidates, list) or not isinstance(actual_candidates, list): | |
| raise ValueError("cannot normalize manifest: finalist candidate records are missing") | |
| if ([str(item.get("candidate_id")) for item in planned_candidates] != expected_ids | |
| or [str(item.get("candidate_id")) for item in actual_candidates] != expected_ids): | |
| raise ValueError("cannot normalize manifest: finalist candidate IDs differ from artifact") | |
| selected = artifact.get("selected") | |
| if not isinstance(selected, Mapping): | |
| raise ValueError("cannot normalize manifest: artifact has no selected candidates") | |
| actual_by_id = {str(item["candidate_id"]): item for item in actual_candidates} | |
| normalized_candidates = [] | |
| reconciliations = [] | |
| config_fields = ( | |
| "family", "condition", "heldout_condition", "coefficients", | |
| "max_new_tokens", "max_generation_seconds", "sampling", | |
| ) | |
| for planned in planned_candidates: | |
| candidate_id = str(planned["candidate_id"]) | |
| actual = actual_by_id[candidate_id] | |
| family = str(actual.get("family", "")) | |
| if planned.get("family") != family: | |
| raise ValueError(f"cannot normalize manifest: family changed for {candidate_id}") | |
| if family not in selected or selected[family].get("candidate_id") not in expected_ids: | |
| raise ValueError(f"cannot normalize manifest: invalid selected candidate for {family}") | |
| selected_flag = selected[family]["candidate_id"] == candidate_id | |
| differences = [] | |
| for field in config_fields: | |
| planned_value = planned.get(field) | |
| actual_value = actual.get(field) | |
| if planned_value != actual_value: | |
| differences.append({"field": field, "planned": planned_value, "artifact": actual_value}) | |
| planned_selected = planned.get("selected") | |
| if planned_selected is not None and planned_selected is not selected_flag: | |
| differences.append({"field": "selected", "planned": planned_selected, "artifact": selected_flag}) | |
| bound_candidate = dict(planned) | |
| for field in config_fields: | |
| if field in actual: | |
| bound_candidate[field] = actual[field] | |
| bound_candidate["selected"] = selected_flag | |
| normalized_candidates.append(bound_candidate) | |
| reconciliations.append({"candidate_id": candidate_id, "differences": differences}) | |
| if normalized.get("selected_conditions") != selected: | |
| raise ValueError("cannot normalize manifest: selected candidate mapping differs from artifact") | |
| if normalized.get("heldout_condition_config_ids") != artifact.get("heldout_condition_config_ids"): | |
| raise ValueError("cannot normalize manifest: heldout condition mapping differs from artifact") | |
| missing_fields = [field for field in ("calibration_artifact_sha256", "model", "calibration") if field not in normalized] | |
| normalized["calibration_artifact_sha256"] = artifact_hash | |
| normalized["model"] = artifact["model"] | |
| normalized["calibration"] = artifact["calibration"] | |
| normalized["calibration_candidates"] = normalized_candidates | |
| normalized["manifest_reconciliation"] = { | |
| "source": "self-hashed calibration.json grid_candidates; these hold the executed candidate settings", | |
| "original_manifest_sha256": original_manifest_sha256, | |
| "backfilled_fields": missing_fields, | |
| "candidate_configs": reconciliations, | |
| "raw_manifest_path": "manifest_remote_original.json", | |
| "note": "Planned candidate settings remain preserved in the raw remote manifest; differing executed settings are listed per candidate above.", | |
| } | |
| return normalized | |
| def classify_generation_output(state: Mapping, *, finished: bool, has_outputs: bool) -> str: | |
| """Classify a vLLM event while keeping already-finalized requests terminal.""" | |
| if state.get("done"): | |
| return "ignore" | |
| if not has_outputs: | |
| return "error" if finished else "wait" | |
| return "complete" if finished else "update" | |
| def task_result_failure(task: Mapping, result, source_rows: Sequence[int]) -> dict | None: | |
| """Return an auditable failure record for an exception or failed task summary.""" | |
| if isinstance(result, BaseException): | |
| message = f"{type(result).__name__}: {str(result)}" | |
| elif not isinstance(result, Mapping): | |
| message = f"unexpected task result type: {type(result).__name__}" | |
| elif result.get("batch_error") or result.get("blocked_partial") or result.get("blocked_error") or result.get("error_count"): | |
| message = str(result.get("batch_error") or "blocked or error records returned") | |
| else: | |
| return None | |
| return { | |
| "task": dict(task), | |
| "source_rows": [int(row) for row in source_rows], | |
| "error": message, | |
| } | |
| def parse_seeds(value: str | Iterable[int]) -> list[int]: | |
| if isinstance(value, str): | |
| seeds = [int(part.strip()) for part in value.split(",") if part.strip()] | |
| else: | |
| seeds = [int(part) for part in value] | |
| if not seeds or len(seeds) != len(set(seeds)) or any(seed < 0 for seed in seeds): | |
| raise ValueError("seeds must be a non-empty list of unique non-negative integers") | |
| return seeds | |
| def build_task_plan( | |
| questions: Sequence[Mapping], | |
| conditions: Sequence[str], | |
| seeds: Sequence[int], | |
| ) -> list[dict]: | |
| if not questions: | |
| raise ValueError("task plan needs at least one question") | |
| if not conditions or len(set(conditions)) != len(conditions): | |
| raise ValueError("conditions must be a non-empty unique list") | |
| unknown = set(conditions) - (set(CONDITIONS) | set(EXPLORATORY_CONDITIONS)) | |
| if unknown: | |
| raise ValueError(f"unknown condition(s): {sorted(unknown)}") | |
| parsed_seeds = parse_seeds(seeds) | |
| rows = [int(question["source_row"]) for question in questions] | |
| if len(rows) != len(set(rows)): | |
| raise ValueError("questions contain duplicate source_row values") | |
| return [ | |
| { | |
| "condition": condition, | |
| "seed": seed, | |
| "source_rows": rows, | |
| "batch_size": len(questions), | |
| } | |
| for seed in parsed_seeds | |
| for condition in conditions | |
| ] | |
| def resolve_condition_config_id(condition: str, selected_config_ids: Mapping[str, str]) -> str: | |
| """Resolve the immutable calibration config used by a primary or exploratory arm.""" | |
| exploratory_id = EXPLORATORY_CANDIDATE_IDS.get(condition) | |
| if exploratory_id is not None: | |
| return exploratory_id | |
| try: | |
| return str(selected_config_ids[condition]) | |
| except KeyError as exc: | |
| raise ValueError(f"condition {condition!r} has no frozen calibration config") from exc | |
| def calibration_candidate_coefficients(calibration: Mapping, candidate_id: str) -> dict[str, float]: | |
| """Load a frozen finalist's per-layer coefficients without consulting heldout data.""" | |
| matches = [ | |
| candidate for candidate in calibration.get("grid_candidates", []) | |
| if candidate.get("candidate_id") == candidate_id | |
| ] | |
| if len(matches) != 1: | |
| raise ValueError(f"expected exactly one calibration candidate {candidate_id!r}; found {len(matches)}") | |
| coefficients = matches[0].get("coefficients") | |
| layers = calibration.get("layers") | |
| if not isinstance(coefficients, Mapping) or not isinstance(layers, Mapping): | |
| raise ValueError(f"candidate {candidate_id!r} is missing layer coefficients") | |
| if set(coefficients) != set(layers): | |
| raise ValueError(f"candidate {candidate_id!r} layer coefficients do not match calibration layers") | |
| normalized = {str(layer): float(value) for layer, value in coefficients.items()} | |
| if not all(math.isfinite(value) for value in normalized.values()): | |
| raise ValueError(f"candidate {candidate_id!r} has non-finite coefficients") | |
| return normalized | |
| def estimate_worst_case_usd( | |
| task_count: int, | |
| *, | |
| timeout_seconds: int = FUNCTION_TIMEOUT_SECONDS, | |
| blended_usd_per_hour: float = CONSERVATIVE_A10_ALL_IN_USD_PER_HOUR, | |
| ) -> float: | |
| if task_count < 0 or timeout_seconds <= 0 or blended_usd_per_hour <= 0: | |
| raise ValueError("invalid cost estimate inputs") | |
| return task_count * timeout_seconds * blended_usd_per_hour / 3600.0 | |
| def record_key(source_row: int, condition: str, seed: int) -> str: | |
| return f"{int(source_row)}__{condition}__seed{int(seed)}" | |
| def load_json(path: str | Path) -> dict: | |
| return json.loads(Path(path).read_text(encoding="utf-8")) | |
| __all__ = [ | |
| "CONDITIONS", | |
| "EXPLORATORY_CANDIDATE_IDS", | |
| "EXPLORATORY_CONDITIONS", | |
| "EXPLORATORY_PUBLISHED_JOINT_MEAN", | |
| "CONSERVATIVE_A10_ALL_IN_USD_PER_HOUR", | |
| "FUNCTION_TIMEOUT_SECONDS", | |
| "MAX_GENERATION_SECONDS", | |
| "MAX_NEW_TOKENS", | |
| "PRIMARY_SAMPLING", | |
| "build_task_plan", | |
| "calibration_candidate_coefficients", | |
| "estimate_worst_case_usd", | |
| "load_json", | |
| "normalize_calibration_manifest_from_artifact", | |
| "parse_jsonl_bytes", | |
| "parse_seeds", | |
| "resolve_condition_config_id", | |
| "classify_generation_output", | |
| "record_key", | |
| "sha256_bytes", | |
| "validate_manifest", | |
| "validate_heldout_content", | |
| "validate_heldout_rows", | |
| "validate_split_bytes", | |
| "task_result_failure", | |
| ] | |