Datasets:
Download code/src/pvr_eval/harness/variants.py from wenjieshu/solveedit_benchmark_2728: direct link, hf CLI and curl.
- Browser
- Download file 9.41 kB
-
https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/harness/variants.py
- Command line
-
hf download hf://datasets/wenjieshu/solveedit_benchmark_2728/code/src/pvr_eval/harness/variants.py
-
curl -L -o variants.py https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/harness/variants.py
9.41 kB
| """Equal-call-budget planner controls and ablations for SolveEdit-Harness.""" | |
| from __future__ import annotations | |
| import json | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| from .planner import ( | |
| PlannerError, | |
| inspection_prompt, | |
| make_crops, | |
| request_chat, | |
| resolution_prompt, | |
| ) | |
| from .schema import find_forbidden_keys, validate_inspection, validate_plan, validate_planner_input | |
| VARIANTS = { | |
| "text_only_rewrite", | |
| "generic_vision_rewrite", | |
| "harness_lite_no_contrast", | |
| "harness_lite_no_preservation", | |
| } | |
| def _request_validated( | |
| *, | |
| base_url: str, | |
| api_key: str, | |
| model: str, | |
| prompt: str, | |
| images: list[Path], | |
| timeout: int, | |
| max_tokens: int, | |
| retries: int, | |
| validator, | |
| ) -> tuple[dict[str, Any], dict[str, Any]]: | |
| last_error = "" | |
| for attempt in range(1, retries + 1): | |
| try: | |
| candidate, meta = request_chat( | |
| base_url=base_url, | |
| api_key=api_key, | |
| model=model, | |
| prompt=prompt, | |
| images=images, | |
| timeout=timeout, | |
| max_tokens=max_tokens, | |
| ) | |
| issues = validator(candidate) | |
| if issues: | |
| raise PlannerError(f"schema: {issues}") | |
| return candidate, meta | |
| except Exception as exc: # noqa: BLE001 - persist provider/schema failures. | |
| last_error = f"{type(exc).__name__}: {exc}" | |
| if attempt < retries: | |
| time.sleep(2 ** (attempt - 1)) | |
| raise PlannerError(last_error or "planner request failed") | |
| def _rewrite_schema(uid: str, stage: str) -> dict[str, Any]: | |
| return { | |
| "schema_version": f"solveedit.generic_rewrite_{stage}.v1", | |
| "uid": uid, | |
| "rewrite_notes": ["brief editing-model instruction improvement"], | |
| "compiled_instruction": "concise instruction ending in Output only the final image.", | |
| } | |
| def _validate_rewrite(value: dict[str, Any], uid: str) -> list[str]: | |
| issues = [f"forbidden_key:{path}" for path in find_forbidden_keys(value)] | |
| if value.get("uid") != uid: | |
| issues.append("uid_mismatch") | |
| if not isinstance(value.get("rewrite_notes"), list): | |
| issues.append("rewrite_notes_must_be_list") | |
| instruction = str(value.get("compiled_instruction") or "").strip() | |
| if not instruction: | |
| issues.append("compiled_instruction_missing") | |
| if len(instruction.split()) > 180: | |
| issues.append("compiled_instruction_over_180_words") | |
| if instruction and not instruction.endswith("Output only the final image."): | |
| issues.append("compiled_instruction_bad_ending") | |
| return issues | |
| def _rewrite_prompt(record: dict[str, Any], *, stage: str, draft: dict[str, Any] | None, vision: bool) -> str: | |
| visual = ( | |
| "The source image is supplied. You may use visible content only to make the request clearer for an image editor. " | |
| if vision | |
| else "No source image is supplied. Use only the user's words. " | |
| ) | |
| prior = f"\nFirst rewrite: {json.dumps(draft, ensure_ascii=False)}\n" if draft else "" | |
| return ( | |
| f"You are a generic image-edit prompt rewriter ({stage} pass). {visual}" | |
| "Rewrite the request into a concise, executable instruction. Do not use a benchmark-specific reasoning " | |
| "procedure, evidence ledger, candidate-transition search, contrastive challenge, rubric, reference answer, " | |
| "or hidden annotation. Do not invent details that are not stated or plainly visible. Preserve the user's " | |
| "intent. The instruction must be <=180 words and end exactly with 'Output only the final image.' " | |
| "Return exactly one JSON object.\n\n" | |
| f"Case ID: {record['case_id']}\nUID: {record['uid']}\n" | |
| f"User request: {record['instruction']}\n{prior}\n" | |
| f"Required schema:\n{json.dumps(_rewrite_schema(str(record['uid']), stage), ensure_ascii=False, indent=2)}" | |
| ) | |
| def _inspection_without_preservation(record: dict[str, Any]) -> str: | |
| return inspection_prompt(record).replace( | |
| " and preservation evidence", " evidence" | |
| ).replace( | |
| "\"preservation_hypotheses\": [\n \"content likely outside the edit scope\"\n ]", | |
| "\"preservation_hypotheses\": []", | |
| ) + "\nAblation: do not analyze or infer preservation constraints; return preservation_hypotheses as an empty list." | |
| def _resolution_for_ablation( | |
| record: dict[str, Any], inspection: dict[str, Any], crop_labels: list[str], variant: str | |
| ) -> str: | |
| prompt = resolution_prompt(record, inspection, crop_labels) | |
| if variant == "harness_lite_no_contrast": | |
| return prompt + ( | |
| "\nAblation: do not generate or perform a contrastive challenge. Set contrastive_challenge to " | |
| "{\"alternative_transition_id\": \"\", \"question\": \"\", " | |
| "\"discriminating_claim_ids\": [], \"outcome\": \"not_applicable\"}." | |
| ) | |
| return prompt + ( | |
| "\nAblation: do not infer preservation obligations. Keep every candidate transition's preserve list " | |
| "empty, do not include preservation claims, and do not add preservation items to self_contract or " | |
| "compiled_instruction." | |
| ) | |
| def run_variant_case( | |
| *, | |
| record: dict[str, Any], | |
| case_dir: Path, | |
| base_url: str, | |
| api_key: str, | |
| model: str, | |
| variant: str, | |
| timeout: int, | |
| retries: int, | |
| ) -> dict[str, Any]: | |
| """Run exactly two planner calls for one control or harness ablation.""" | |
| if variant not in VARIANTS: | |
| raise PlannerError(f"unknown variant: {variant}") | |
| issues = validate_planner_input(record) | |
| if issues: | |
| raise PlannerError(f"invalid planner input: {issues}") | |
| image_path = Path(record["input_image"]).resolve() | |
| case_dir.mkdir(parents=True, exist_ok=True) | |
| if variant in {"text_only_rewrite", "generic_vision_rewrite"}: | |
| vision = variant == "generic_vision_rewrite" | |
| images = [image_path] if vision else [] | |
| draft, first_meta = _request_validated( | |
| base_url=base_url, | |
| api_key=api_key, | |
| model=model, | |
| prompt=_rewrite_prompt(record, stage="draft", draft=None, vision=vision), | |
| images=images, | |
| timeout=timeout, | |
| max_tokens=3000, | |
| retries=retries, | |
| validator=lambda value: _validate_rewrite(value, str(record["uid"])), | |
| ) | |
| (case_dir / "rewrite_draft.json").write_text( | |
| json.dumps(draft, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| plan, second_meta = _request_validated( | |
| base_url=base_url, | |
| api_key=api_key, | |
| model=model, | |
| prompt=_rewrite_prompt(record, stage="refine", draft=draft, vision=vision), | |
| images=images, | |
| timeout=timeout, | |
| max_tokens=3000, | |
| retries=retries, | |
| validator=lambda value: _validate_rewrite(value, str(record["uid"])), | |
| ) | |
| plan.update( | |
| { | |
| "planner_model": model, | |
| "planner_variant": variant, | |
| "planner_call_budget": 2, | |
| "planner_vision_call_budget": 2 if vision else 0, | |
| "original_instruction": record["instruction"], | |
| "draft_path": str((case_dir / "rewrite_draft.json").resolve()), | |
| } | |
| ) | |
| meta = {"draft": first_meta, "refine": second_meta} | |
| else: | |
| inspect_prompt = ( | |
| _inspection_without_preservation(record) | |
| if variant == "harness_lite_no_preservation" | |
| else inspection_prompt(record) | |
| ) | |
| inspection, first_meta = _request_validated( | |
| base_url=base_url, | |
| api_key=api_key, | |
| model=model, | |
| prompt=inspect_prompt, | |
| images=[image_path], | |
| timeout=timeout, | |
| max_tokens=5000, | |
| retries=retries, | |
| validator=lambda value: validate_inspection(value, str(record["uid"])), | |
| ) | |
| (case_dir / "inspection.json").write_text( | |
| json.dumps(inspection, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| crops, crop_labels = make_crops(image_path, inspection, case_dir / "crops") | |
| plan, second_meta = _request_validated( | |
| base_url=base_url, | |
| api_key=api_key, | |
| model=model, | |
| prompt=_resolution_for_ablation(record, inspection, crop_labels, variant), | |
| images=[image_path, *crops], | |
| timeout=timeout, | |
| max_tokens=9000, | |
| retries=retries, | |
| validator=lambda value: validate_plan(value, str(record["uid"])), | |
| ) | |
| plan.update( | |
| { | |
| "planner_model": model, | |
| "planner_variant": variant, | |
| "planner_call_budget": 2, | |
| "planner_vision_call_budget": 2, | |
| "original_instruction": record["instruction"], | |
| "inspection_path": str((case_dir / "inspection.json").resolve()), | |
| } | |
| ) | |
| meta = {"inspect": first_meta, "resolve": second_meta} | |
| (case_dir / "plan.json").write_text( | |
| json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| (case_dir / "response_meta.json").write_text( | |
| json.dumps(meta, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| return plan | |