| """Deterministic Qwen3.5-VL prediction for frozen evaluation manifests. |
| |
| GPU libraries remain lazy imports so manifest/scoring tests run on CPU-only |
| machines. The runner is append-resumable by eval ID and never re-hashes model, |
| adapter, or image trees; paths are checked structurally when they are used. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import copy |
| import json |
| import os |
| import time |
| from collections.abc import Mapping, Sequence |
| from pathlib import Path |
| from typing import Any |
|
|
| from ..hashing import canonical_json |
| from ..paths import repo_root |
| from ..training.answers import parse_answer |
| from .core import EvaluationError |
|
|
|
|
| def resolve_asset(root: Path, raw_path: str) -> Path: |
| relative = Path(raw_path) |
| if not raw_path or relative.is_absolute() or ".." in relative.parts or "\\" in raw_path: |
| raise EvaluationError(f"unsafe evaluation image path: {raw_path!r}") |
| resolved_root = root.resolve() |
| resolved = (resolved_root / relative).resolve() |
| try: |
| resolved.relative_to(resolved_root) |
| except ValueError as exc: |
| raise EvaluationError(f"evaluation image escapes asset root: {raw_path!r}") from exc |
| if not resolved.is_file(): |
| raise EvaluationError(f"evaluation image not found: {resolved}") |
| return resolved |
|
|
|
|
| def _question_text(question: str, choices: Sequence[Mapping[str, Any]]) -> str: |
| if not choices: |
| return question |
| rendered: list[str] = [] |
| for choice in choices: |
| if "key" not in choice or "text" not in choice: |
| raise EvaluationError("evaluation choice requires key and text") |
| rendered.append(f"{choice['key']}. {choice['text']}") |
| return question + "\n\nChoices:\n" + "\n".join(rendered) |
|
|
|
|
| def build_messages( |
| row: Mapping[str, Any], |
| *, |
| images: Sequence[Any], |
| ) -> list[dict[str, Any]]: |
| question = row.get("question") |
| choices = row.get("choices") |
| if not isinstance(question, str) or not question: |
| raise EvaluationError("evaluation row has no question") |
| if not isinstance(choices, list) or any(not isinstance(choice, Mapping) for choice in choices): |
| raise EvaluationError("evaluation row choices are malformed") |
| prompt_path = repo_root() / "prompts" / "common_system.txt" |
| try: |
| system = prompt_path.read_text(encoding="utf-8").strip() |
| except OSError as exc: |
| raise EvaluationError(f"cannot read common system prompt: {exc}") from exc |
| content = [{"type": "image", "image": image} for image in images] |
| content.append({"type": "text", "text": _question_text(question, choices)}) |
| return [ |
| {"role": "system", "content": [{"type": "text", "text": system}]}, |
| {"role": "user", "content": content}, |
| ] |
|
|
|
|
| def _load_images(row: Mapping[str, Any], asset_root: Path) -> list[Any]: |
| from PIL import Image |
|
|
| raw_images = row.get("images") |
| if not isinstance(raw_images, list): |
| raise EvaluationError("evaluation row images must be a list") |
| images: list[Any] = [] |
| for raw in raw_images: |
| if not isinstance(raw, Mapping) or not isinstance(raw.get("path"), str): |
| raise EvaluationError("evaluation image record is malformed") |
| path = resolve_asset(asset_root, str(raw["path"])) |
| try: |
| with Image.open(path) as image: |
| images.append(image.convert("RGB").copy()) |
| except (OSError, ValueError) as exc: |
| raise EvaluationError(f"cannot decode evaluation image {path}: {exc}") from exc |
| return images |
|
|
|
|
| def _load_model(base_model: Path, adapter: Path | None) -> tuple[Any, Any]: |
| try: |
| import torch |
| from transformers import AutoModelForMultimodalLM, AutoProcessor |
| except ImportError as exc: |
| raise EvaluationError(f"GPU evaluation dependency is missing: {exc}") from exc |
| if not base_model.is_dir(): |
| raise EvaluationError(f"base model directory not found: {base_model}") |
| processor = AutoProcessor.from_pretrained(str(base_model)) |
| model = AutoModelForMultimodalLM.from_pretrained( |
| str(base_model), |
| dtype=torch.bfloat16, |
| attn_implementation="flash_attention_2", |
| device_map="auto", |
| ) |
| if adapter is not None: |
| if not adapter.is_dir(): |
| raise EvaluationError(f"adapter directory not found: {adapter}") |
| try: |
| from peft import PeftModel |
| except ImportError as exc: |
| raise EvaluationError(f"PEFT is required for adapter evaluation: {exc}") from exc |
| model = PeftModel.from_pretrained(model, str(adapter), is_trainable=False) |
| model.eval() |
| return model, processor |
|
|
|
|
| def _model_device(model: Any) -> Any: |
| device = getattr(model, "device", None) |
| if device is not None: |
| return device |
| try: |
| return next(model.parameters()).device |
| except (AttributeError, StopIteration) as exc: |
| raise EvaluationError("cannot determine evaluation model device") from exc |
|
|
|
|
| def _predict_one( |
| row: Mapping[str, Any], |
| *, |
| asset_root: Path, |
| model: Any, |
| processor: Any, |
| max_prompt_tokens: int, |
| max_new_tokens: int, |
| image_row: Mapping[str, Any] | None = None, |
| question_only: bool = False, |
| ) -> dict[str, Any]: |
| try: |
| import torch |
| from qwen_vl_utils import process_vision_info |
| except ImportError as exc: |
| raise EvaluationError(f"GPU evaluation dependency is missing: {exc}") from exc |
| images = [] if question_only else _load_images(image_row or row, asset_root) |
| messages = build_messages(row, images=images) |
| rendered = processor.apply_chat_template( |
| copy.deepcopy(messages), |
| tokenize=False, |
| add_generation_prompt=True, |
| enable_thinking=False, |
| ) |
| image_inputs, video_inputs = process_vision_info(messages) |
| processor_kwargs: dict[str, Any] = { |
| "text": [rendered], |
| "padding": True, |
| "return_tensors": "pt", |
| } |
| if image_inputs: |
| processor_kwargs["images"] = image_inputs |
| if video_inputs: |
| processor_kwargs["videos"] = video_inputs |
| encoded = processor(**processor_kwargs) |
| prompt_tokens = int(encoded["input_ids"].shape[-1]) |
| if prompt_tokens > max_prompt_tokens: |
| raise EvaluationError( |
| f"{row.get('eval_id')}: prompt has {prompt_tokens} tokens, limit is {max_prompt_tokens}" |
| ) |
| encoded = encoded.to(_model_device(model)) |
| started = time.monotonic() |
| with torch.inference_mode(): |
| generated = model.generate( |
| **encoded, |
| do_sample=False, |
| max_new_tokens=max_new_tokens, |
| stop_strings=["</answer>"], |
| tokenizer=getattr(processor, "tokenizer", processor), |
| ) |
| elapsed = time.monotonic() - started |
| completion_ids = generated[:, encoded["input_ids"].shape[-1] :] |
| response = processor.batch_decode( |
| completion_ids, |
| skip_special_tokens=True, |
| clean_up_tokenization_spaces=False, |
| )[0] |
| token_count = int(completion_ids.shape[-1]) |
| parsed = parse_answer(response) |
| return { |
| "response": response, |
| "prompt_tokens": prompt_tokens, |
| "completion_tokens": token_count, |
| "prompt_truncated": False, |
| "completion_truncated": bool(token_count >= max_new_tokens and not parsed.valid), |
| "latency_seconds": elapsed, |
| } |
|
|
|
|
| def _existing_predictions(path: Path, *, run_id: str) -> dict[str, dict[str, Any]]: |
| if not path.exists(): |
| return {} |
| rows: dict[str, dict[str, Any]] = {} |
| try: |
| with path.open("r", encoding="utf-8") as handle: |
| for line_number, line in enumerate(handle, start=1): |
| if not line.strip(): |
| continue |
| value = json.loads(line) |
| if not isinstance(value, dict): |
| raise EvaluationError(f"{path}:{line_number}: prediction is not an object") |
| if value.get("run_id") != run_id: |
| raise EvaluationError(f"{path}: existing predictions belong to another run") |
| eval_id = value.get("eval_id") |
| if not isinstance(eval_id, str) or not eval_id or eval_id in rows: |
| raise EvaluationError(f"{path}: duplicate or empty existing eval_id") |
| rows[eval_id] = value |
| except (OSError, json.JSONDecodeError) as exc: |
| raise EvaluationError(f"cannot resume prediction file {path}: {exc}") from exc |
| return rows |
|
|
|
|
| def predict_run( |
| rows: Sequence[Mapping[str, Any]], |
| *, |
| run_id: str, |
| base_model: Path, |
| adapter: Path | None, |
| asset_root: Path, |
| output_path: Path, |
| max_prompt_tokens: int = 4096, |
| max_new_tokens: int = 256, |
| limit: int | None = None, |
| input_mode: str = "standard", |
| constant_answer: str | None = None, |
| ) -> dict[str, Any]: |
| """Generate one exact, resumable prediction row per evaluation view.""" |
|
|
| if not run_id: |
| raise EvaluationError("run_id must be non-empty") |
| if max_prompt_tokens <= 0 or max_new_tokens <= 0: |
| raise EvaluationError("evaluation token limits must be positive") |
| if input_mode not in {"standard", "question_only", "full_image_control"}: |
| raise EvaluationError(f"unsupported evaluation input mode: {input_mode!r}") |
| if constant_answer is not None and not parse_answer( |
| f"<answer>{constant_answer}</answer>" |
| ).valid: |
| raise EvaluationError("constant answer cannot be encoded by the public answer schema") |
| selected = list(rows[:limit] if limit is not None else rows) |
| existing = _existing_predictions(output_path, run_id=run_id) |
| if any(row.get("input_mode", "standard") != input_mode for row in existing.values()): |
| raise EvaluationError("existing predictions use another input mode") |
| expected_ids = {str(row.get("eval_id", "")) for row in selected} |
| if not set(existing).issubset(expected_ids): |
| raise EvaluationError("existing prediction file contains IDs outside this evaluation") |
| pending = [row for row in selected if str(row.get("eval_id", "")) not in existing] |
| model: Any | None = None |
| processor: Any | None = None |
| if pending and constant_answer is None: |
| model, processor = _load_model(base_model, adapter) |
| full_by_group: dict[str, Mapping[str, Any]] = {} |
| if input_mode == "full_image_control": |
| for row in selected: |
| if row.get("state") == "FULL": |
| full_by_group[str(row.get("group_id", ""))] = row |
| missing_full = sorted( |
| { |
| str(row.get("group_id", "")) |
| for row in selected |
| if str(row.get("group_id", "")) not in full_by_group |
| } |
| ) |
| if missing_full: |
| raise EvaluationError( |
| f"full-image control lacks FULL rows for groups: {missing_full[:5]}" |
| ) |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| with output_path.open("a", encoding="utf-8") as handle: |
| for index, row in enumerate(pending, start=1): |
| if constant_answer is None: |
| assert model is not None and processor is not None |
| prediction = _predict_one( |
| row, |
| asset_root=asset_root, |
| model=model, |
| processor=processor, |
| max_prompt_tokens=max_prompt_tokens, |
| max_new_tokens=max_new_tokens, |
| image_row=full_by_group.get(str(row.get("group_id", ""))), |
| question_only=input_mode == "question_only", |
| ) |
| else: |
| prediction = { |
| "response": f"<answer>{constant_answer}</answer>", |
| "prompt_tokens": 0, |
| "completion_tokens": 0, |
| "prompt_truncated": False, |
| "completion_truncated": False, |
| "latency_seconds": 0.0, |
| } |
| value = { |
| "schema_version": 1, |
| "run_id": run_id, |
| "eval_id": str(row["eval_id"]), |
| "input_mode": input_mode, |
| **prediction, |
| } |
| handle.write(canonical_json(value) + "\n") |
| handle.flush() |
| if index % 32 == 0: |
| os.fsync(handle.fileno()) |
| if pending: |
| os.fsync(handle.fileno()) |
| all_rows = _existing_predictions(output_path, run_id=run_id) |
| truncated = sum(bool(row.get("completion_truncated")) for row in all_rows.values()) |
| return { |
| "run_id": run_id, |
| "output": str(output_path.resolve()), |
| "expected": len(selected), |
| "predicted": len(all_rows), |
| "new_predictions": len(pending), |
| "completion_truncation_count": truncated, |
| "input_mode": input_mode, |
| "constant_answer": constant_answer, |
| "complete": len(all_rows) == len(selected), |
| } |
|
|