theia / code /VLM_inference /run_ft_eval_ablation.py
overmach's picture
Camera-ready release
148072e verified
Raw History Blame Contribute Delete
74.1 kB
#!/usr/bin/env python3 # ----------------------------------------------------------------------------- # Ablation-study evaluator for LoRA fine-tuned adapters (custom inference path). # # Typical workflow: # 1) Fine-tune adapters for multiple (task, perc) splits with VLM_finetune. # 2) Use THIS script to evaluate each adapter on its matching test split. # # What this script discovers and evaluates: # - Dataset splits live under: <splits-root>/task_*/perc_*/test/*.json # - LoRA adapters live under: <adapter-root>/task_*/perc_*/ # # Outputs (written into each split's results directory): # - <base>.jsonl per-sample records (prompt/gt/pred/scoring + metadata) # - <base>_summary.json per-split aggregate metrics + args # - <base>_accuracy_summary.txt human-readable per-circuit + global accuracy # # Notes: # - This is a "custom" evaluator: it loads the base model + adapter via Transformers/PEFT and # runs the model's chat-style inference (not lmdeploy). # - Task types differ: # - choice tasks (a1/b1/c1) are scored by extracting A-F letters from model output # - box tasks (b2/c2) are scored by parsing coordinate tuples / bounding boxes # ----------------------------------------------------------------------------- import argparse import datetime as _dt import json import os import random import re from typing import Any, Dict, List, Optional, Sequence, Tuple # ---- Minimal evaluation utilities ---- # The regexes below are deliberately conservative: many VLMs produce verbose text and we # want to avoid accidentally extracting choice letters from unrelated prose. # Some datasets use A-D, others (base circuits) can use A-F. # NOTE: Don't use a naive "\bA\b" match for predictions; many models emit prose # containing standalone 'A' tokens (e.g. 'A breakdown...'), which would create # false positives. We keep a strict token matcher and add higher-priority patterns. CHOICE_TOKEN_RE = re.compile(r"\b([A-F])\s*(?:[\.,\)])") CHOICE_LABEL_RE = re.compile( r"(?i)(?:^|\b)(?:final\s*answer|final|answer|choice)\s*[:\-]?\s*([A-F])\s*(?:[\.,\)]|\b)" ) CHOICE_CORRECT_RE = re.compile(r"(?i)(?:the\s+)?correct\s+answer\s+is\s*([A-F])\s*(?:[\.,\)]|\b)") CHOICE_LINE_RE = re.compile(r"^\s*([A-F])\s*(?:[\.,\)]\s*)?$") CHOICE_COORDS_LINE_RE = re.compile(r"^\s*([A-F])\s*,\s*(?:coordinates?|bbox|boxes?)\b", re.IGNORECASE) BOX_RE = re.compile(r"\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)\s*-\s*\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)") INT_RE = re.compile(r"-?\d+") def _now_tag() -> str: return _dt.datetime.now().strftime("%Y%m%d_%H%M%S") def _assert_deps() -> None: missing: List[str] = [] for name in ["torch", "transformers", "peft", "PIL"]: try: __import__(name) except Exception: missing.append(name) if missing: raise SystemExit( "Missing required packages: " + ", ".join(missing) + "\nActivate your environment first, e.g.:\n" + " source mydata/<USER>/conda/anaconda3/etc/profile.d/conda.sh\n" + " conda activate VLM-ft\n" ) def _parse_csv(value: str | None) -> list[str] | None: if value is None: return None items = [v.strip() for v in value.split(",") if v.strip()] return items or None def _normalize_task_token(token: str) -> str: t = token.strip() if not t: raise ValueError("Empty task token") if t.startswith("task_"): return t return f"task_{t}" def _normalize_perc_token(token: str) -> str: t = token.strip() if not t: raise ValueError("Empty perc token") if t.startswith("perc_"): return t if t.isdigit(): return f"perc_{int(t):03d}" raise ValueError(f"Unrecognized perc token: {token!r} (expected e.g. 25 or perc_025)") def _perc_key(name: str) -> int: m = re.search(r"perc_(\d+)", name) return int(m.group(1)) if m else 10**9 def _task_short(task_dir: str) -> str: return task_dir[len("task_") :] if task_dir.startswith("task_") else task_dir def _iter_random_items(items: Sequence[Dict[str, Any]], n: int, seed: int) -> List[Dict[str, Any]]: rng = random.Random(seed) idxs = list(range(len(items))) rng.shuffle(idxs) if n < 0 or n >= len(items): selected = idxs else: selected = idxs[:n] return [items[i] for i in selected] def _find_single_json(dir_path: str) -> str: if not os.path.isdir(dir_path): raise FileNotFoundError(f"Missing directory: {dir_path}") cands = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if f.endswith(".json")] cands = [p for p in cands if os.path.isfile(p)] cands.sort() if len(cands) != 1: raise RuntimeError(f"Expected exactly 1 .json in {dir_path}, found {len(cands)}: {cands}") return cands[0] def discover_ablation_runs( *, splits_root: str, adapter_root: str, tasks_filter: Optional[List[str]], percs_filter: Optional[List[str]], ) -> List[Dict[str, str]]: """Discover runs under ablation_splits/task_*/perc_*. Returns dicts with keys: task_dir, perc_dir, task, perc, test_path, adapter_path, results_dir. """ # Each discovered run corresponds to one (task, perc) split. # We compute the matching adapter and results directory paths by convention. if not os.path.isdir(splits_root): raise FileNotFoundError(f"splits_root not found: {splits_root}") runs: List[Dict[str, str]] = [] for task_dir in sorted( d for d in os.listdir(splits_root) if os.path.isdir(os.path.join(splits_root, d)) and d.startswith("task_") ): if tasks_filter is not None and task_dir not in tasks_filter: continue task = _task_short(task_dir) task_path = os.path.join(splits_root, task_dir) perc_dirs = sorted( ( d for d in os.listdir(task_path) if os.path.isdir(os.path.join(task_path, d)) and d.startswith("perc_") ), key=_perc_key, ) for perc_dir in perc_dirs: if percs_filter is not None and perc_dir not in percs_filter: continue m = re.search(r"perc_(\d+)", perc_dir) perc = m.group(1) if m else perc_dir test_path = _find_single_json(os.path.join(task_path, perc_dir, "test")) adapter_path = os.path.join(adapter_root, task_dir, perc_dir) results_dir = os.path.join(task_path, perc_dir, "results") runs.append( { "task_dir": task_dir, "perc_dir": perc_dir, "task": task, "perc": perc, "test_path": test_path, "adapter_path": adapter_path, "results_dir": results_dir, } ) return runs def load_json(path: str) -> List[Dict[str, Any]]: with open(path, "r", encoding="utf-8") as f: data = json.load(f) if not isinstance(data, list): raise ValueError(f"Expected list in {path}, got {type(data)}") return data def ensure_dir(path: str) -> None: os.makedirs(path, exist_ok=True) def pick_unique_result_base(results_dir: str, base_name: str) -> str: """Return a base name that won't overwrite existing result files. We treat a run as a trio of files: - <base>.jsonl - <base>_summary.json - <base>_accuracy_summary.txt If any of those already exist, append a suffix: <base>_r2, <base>_r3, ... """ # This avoids overwriting results when re-running with the same run tag or settings. def exists_for(stem: str) -> bool: return any( os.path.exists(os.path.join(results_dir, stem + ext)) for ext in (".jsonl", "_summary.json", "_accuracy_summary.txt") ) if not exists_for(base_name): return base_name for k in range(2, 10_000): cand = f"{base_name}_r{k}" if not exists_for(cand): return cand raise RuntimeError(f"Could not find an available output name in {results_dir} for base={base_name}") def write_split_accuracy_summary_txt(*, summary: Dict[str, Any], out_path: str) -> None: """Write a human-readable accuracy summary for ONE evaluated split. The split is identified by (task, perc) and contains a per-circuit breakdown. """ lines: List[str] = [] lines.append(f"Task: {summary.get('task')}") lines.append(f"Split: {summary.get('perc')}") lines.append(f"Test: {summary.get('test_file')}") lines.append(f"Adapter: {summary.get('adapter')}") lines.append(f"Effective adapter: {summary.get('effective_adapter')}") lines.append(f"Seed: {summary.get('seed')}") lines.append("") num_selected = int(summary.get("num_selected") or 0) num_scored = int(summary.get("num_scored") or 0) num_errors = int(summary.get("num_errors") or 0) correct = int(summary.get("correct") or 0) wrong = int(summary.get("wrong") or 0) acc = summary.get("accuracy") lines.append(f"Counts: selected={num_selected} scored={num_scored} errors={num_errors}") if acc is None: lines.append("GLOBAL: n_scored=0") else: lines.append(f"GLOBAL: acc={float(acc):.4f} ({correct}/{max(num_scored, 1)}), wrong={wrong}") lines.append("") lines.append("BY_CIRCUIT:") by_circuit = summary.get("by_circuit") or {} if not isinstance(by_circuit, dict) or not by_circuit: lines.append("- (none)") else: for circuit in sorted(by_circuit.keys()): v = by_circuit.get(circuit) or {} c_correct = int(v.get("correct") or 0) c_scored = int(v.get("scored") or 0) c_errors = int(v.get("errors") or 0) c_acc = v.get("accuracy") if c_acc is None and c_scored: c_acc = c_correct / c_scored if c_acc is None: lines.append(f"- {circuit}: n_scored=0, errors={c_errors}") else: lines.append(f"- {circuit}: acc={float(c_acc):.4f} ({c_correct}/{c_scored}), errors={c_errors}") with open(out_path, "w", encoding="utf-8") as f: f.write("\n".join(lines) + "\n") def extract_prompt(item: Dict[str, Any]) -> str: conversations = item.get("conversations") or [] if not conversations: return "" user_turn = conversations[0] prompt = str(user_turn.get("value", "")) prompt = prompt.replace("<ImageHere>", "").strip() prompt = re.sub(r"\s+", " ", prompt).strip() return prompt def extract_ground_truth(item: Dict[str, Any]) -> str: conversations = item.get("conversations") or [] if len(conversations) < 2: return "" return str(conversations[-1].get("value", "")).strip() def parse_choice_letter(text: str) -> Optional[str]: if not text: return None t = str(text).strip() if not t: return None # 1) Highest confidence: explicitly labeled answer. for rx in (CHOICE_LABEL_RE, CHOICE_CORRECT_RE): m = rx.search(t) if m: return m.group(1).upper() # 2) Next: check last/first non-empty lines for a bare "A" or "A.". lines = [ln.strip() for ln in t.splitlines() if ln.strip()] for ln in reversed(lines[-8:]): m = CHOICE_COORDS_LINE_RE.match(ln) if m: return m.group(1).upper() m = CHOICE_LINE_RE.match(ln.upper()) if m: return m.group(1).upper() for ln in lines[:8]: m = CHOICE_COORDS_LINE_RE.match(ln) if m: return m.group(1).upper() m = CHOICE_LINE_RE.match(ln.upper()) if m: return m.group(1).upper() # 3) Fallback: find the last strict token like "A." or "A," and ignore # likely option-list echoes (e.g., "A. ... B. ... C. ..."). tu = t.upper() matches = list(CHOICE_TOKEN_RE.finditer(tu)) for m in reversed(matches): letter = m.group(1).upper() start = m.start() window = tu[start : start + 120] if any(x in window for x in (" B.", " C.", " D.", " E.", " F.")): continue return letter return None def infer_allowed_choice_letters(prompt: str) -> str: """Infer allowed choice letters from the prompt. Heuristic: - If prompt mentions options up to E/F (e.g., "E." or "F."), allow A-F. - Otherwise default to A-D. This keeps a1-like tasks constrained to A-D while allowing circuit-ID prompts (A-F). """ p = (prompt or "").upper() if "F." in p or " F " in p: return "ABCDEF" if "E." in p or " E " in p: return "ABCDEF" return "ABCD" def _choice_token_id_candidates(tokenizer: Any, letters: str) -> List[int]: """Return token ids that can represent a single-letter answer. We try a small set of common string forms and only accept those that encode into exactly one token. """ out: List[int] = [] seen: set[int] = set() for ch in letters: for s in (ch, f" {ch}", f"\n{ch}"): try: ids = tokenizer.encode(s, add_special_tokens=False) except Exception: continue if isinstance(ids, list) and len(ids) == 1: tid = int(ids[0]) if tid not in seen: seen.add(tid) out.append(tid) return out def infer_custom_chat_constrained_choice( *, model: Any, tokenizer: Any, prompt: str, image_path: str, hd_num: int, allowed_letters: str, max_new_tokens: int = 1, ) -> str: """Force the model to output exactly one token from allowed letter tokens. This is a last-resort fallback for choice tasks when the model keeps producing whitespace-only outputs (e.g. "\n") and immediately ending. """ allowed_token_ids = _choice_token_id_candidates(tokenizer, allowed_letters) if not allowed_token_ids: # Can't constrain safely; fall back to normal inference. return infer_custom_chat( model=model, tokenizer=tokenizer, prompt=prompt, image_path=image_path, hd_num=hd_num, max_new_tokens=max_new_tokens, do_sample=False, num_beams=1, ) def prefix_allowed_tokens_fn(batch_id: int, input_ids: Any) -> List[int]: # Only allow the letter tokens as the *next* generated token. return allowed_token_ids # Ensure we generate exactly one token and don't early-stop on EOS. try: return infer_custom_chat( model=model, tokenizer=tokenizer, prompt=prompt, image_path=image_path, hd_num=hd_num, max_new_tokens=int(max_new_tokens), do_sample=False, num_beams=1, # These are forwarded through model.chat(..., **kwargs) to generate(). prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, min_new_tokens=1, ) except TypeError: # If the underlying generate/chat doesn't accept these kwargs, fall back. return infer_custom_chat( model=model, tokenizer=tokenizer, prompt=prompt, image_path=image_path, hd_num=hd_num, max_new_tokens=int(max_new_tokens), do_sample=False, num_beams=1, ) def parse_boxes(text: str) -> List[Tuple[int, int, int, int]]: if not text: return [] boxes: List[Tuple[int, int, int, int]] = [] for m in BOX_RE.finditer(text): boxes.append((int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))) if not boxes: ints = [int(x) for x in INT_RE.findall(text)] if len(ints) >= 4 and len(ints) % 4 == 0: boxes = [tuple(ints[i : i + 4]) for i in range(0, len(ints), 4)] # type: ignore[misc] return boxes def circuit_from_image_path(image_path: str) -> Optional[str]: parts = image_path.strip().split("?")[0].strip("/").split("/") if "dataset_tasks_mc" in parts: i = parts.index("dataset_tasks_mc") if i + 1 < len(parts): return parts[i + 1] if len(parts) >= 3: return parts[-3] return None def task_mode(task: str) -> str: task = task.lower() if task in {"a1", "b1", "c1"}: return "choice" if task in {"b2", "c2"}: return "boxes" raise ValueError(f"Unknown task: {task}") def validate_task_circuit(task: str, circuit: str) -> None: task = task.lower() if task in {"c1", "c2"} and circuit != "mixed": raise SystemExit("For tasks c1/c2 the circuit must be 'mixed'.") def iter_selected_items(items: Sequence[Dict[str, Any]], circuit: str, n: int, seed: int) -> List[Dict[str, Any]]: filtered = [] for it in items: img = (it.get("image") or [None])[0] if not isinstance(img, str): continue c = circuit_from_image_path(img) if c == circuit: filtered.append(it) rng = random.Random(seed) rng.shuffle(filtered) if n < 0 or n >= len(filtered): return filtered return filtered[:n] def score_item(task: str, gt: str, pred: str) -> Dict[str, Any]: mode = task_mode(task) if mode == "choice": gt_letter = parse_choice_letter(gt) pred_letter = parse_choice_letter(pred) correct = (gt_letter is not None) and (pred_letter == gt_letter) return { "mode": mode, "gt_letter": gt_letter, "pred_letter": pred_letter, "correct": bool(correct), } if mode == "boxes": # b2/c2 are evaluated primarily as localization tasks. # Some legacy datasets may also include a choice letter, so we parse it for diagnostics, # but correctness is based on boxes. gt_letter = parse_choice_letter(gt) pred_letter = parse_choice_letter(pred) gt_boxes = parse_boxes(gt) pred_boxes = parse_boxes(pred) gt_boxes_sorted = sorted(gt_boxes) pred_boxes_sorted = sorted(pred_boxes) boxes_ok = bool(gt_boxes) and (pred_boxes == gt_boxes) boxes_unordered_ok = bool(gt_boxes) and (pred_boxes_sorted == gt_boxes_sorted) # Main metric: order-insensitive exact match of all boxes. # (If you later want IoU/tolerance, this is the place to change it.) correct = boxes_unordered_ok return { "mode": mode, "gt_letter": gt_letter, "pred_letter": pred_letter, "gt_boxes": gt_boxes, "pred_boxes": pred_boxes, "gt_boxes_sorted": gt_boxes_sorted, "pred_boxes_sorted": pred_boxes_sorted, "correct": bool(correct), "boxes_exact_correct": bool(boxes_ok), "boxes_unordered_correct": bool(boxes_unordered_ok), } raise RuntimeError("Unhandled mode") def _apply_hf_cache_dir(cache_dir: Optional[str]) -> None: """Best-effort: route HF downloads/caches to a user-specified directory. Transformers/huggingface_hub honor these env vars. """ if not cache_dir: return os.makedirs(cache_dir, exist_ok=True) os.environ["HF_HOME"] = cache_dir os.environ["HF_HUB_CACHE"] = cache_dir # Common additional cache env vars used by transformers/datasets. os.environ["TRANSFORMERS_CACHE"] = cache_dir os.environ["HF_DATASETS_CACHE"] = os.path.join(cache_dir, "datasets") def resolve_test_json_path(dataset_dir: str, *, circuit: str, task: str) -> str: """Resolve test set JSON for either the old or reorganized dataset layout. Old layout: <dataset_dir>/vlm_conversations_task_<task>_test.json New layout: <dataset_dir>/<circuit>/vlm_conversations_task_<task>_test.json """ fname = f"vlm_conversations_task_{task}_test.json" # Prefer new layout if it exists. cand_new = os.path.join(dataset_dir, circuit, fname) if os.path.exists(cand_new): return cand_new cand_old = os.path.join(dataset_dir, fname) if os.path.exists(cand_old): return cand_old # Provide a helpful error message. raise FileNotFoundError( "Could not find test JSON. Tried:\n" f"- {cand_new}\n" f"- {cand_old}\n" "If you are using the reorganized test sets, pass the parent directory (the one that contains circuit folders)." ) _TEST_JSON_RE = re.compile(r"^vlm_conversations_task_(a1|b1|b2|c1|c2)_test\.json$") def discover_test_sets(dataset_dir: str) -> List[Dict[str, str]]: """Discover available test sets in the reorganized layout. Expected layout: <dataset_dir>/<circuit>/vlm_conversations_task_<task>_test.json Returns a list of dicts with keys: circuit, task, path. """ out: List[Dict[str, str]] = [] try: circuits = sorted( d for d in os.listdir(dataset_dir) if os.path.isdir(os.path.join(dataset_dir, d)) and not d.startswith(".") ) except FileNotFoundError: return out for circuit in circuits: cdir = os.path.join(dataset_dir, circuit) try: files = os.listdir(cdir) except Exception: continue for fname in files: m = _TEST_JSON_RE.match(fname) if not m: continue task = m.group(1) out.append({"circuit": circuit, "task": task, "path": os.path.join(cdir, fname)}) # Sort in a stable, human-friendly order. task_order = {"a1": 0, "b1": 1, "b2": 2, "c1": 3, "c2": 4} out.sort(key=lambda d: (d["circuit"], task_order.get(d["task"], 999))) return out def extract_prompt_custom(item: Dict[str, Any]) -> str: """Prompt for InternLM-XComposer2 `model.chat()`. Unlike the lmdeploy evaluator, we must preserve/add the '<ImageHere>' token. """ conversations = item.get("conversations") or [] if not conversations: return "<ImageHere>" user_turn = conversations[0] prompt = str(user_turn.get("value", "")).strip() prompt = re.sub(r"\s+", " ", prompt).strip() if "<ImageHere>" not in prompt: prompt = "<ImageHere> " + prompt return prompt def _is_adapter_folder(path: str) -> bool: return os.path.exists(os.path.join(path, "adapter_config.json")) def _has_adapter_weights(path: str) -> bool: return any( os.path.exists(os.path.join(path, fname)) for fname in ("adapter_model.safetensors", "adapter_model.bin") ) def _try_parse_checkpoint_step(name: str) -> Optional[int]: # checkpoint-2999 -> 2999 if not name.startswith("checkpoint-"): return None tail = name[len("checkpoint-") :] try: return int(tail) except Exception: return None def resolve_adapter_path(path: str) -> str: """Resolve a user-provided adapter path to the folder that contains adapter weights. Some training runs save a top-level adapters directory containing checkpoint-* subfolders where the actual adapter weights live. """ if not _is_adapter_folder(path): raise ValueError(f"Adapter path must contain adapter_config.json. Got: {path}") if _has_adapter_weights(path): return path # Search for the latest checkpoint-* that has adapter weights. best_step: Optional[int] = None best_path: Optional[str] = None try: for entry in os.listdir(path): step = _try_parse_checkpoint_step(entry) if step is None: continue cand = os.path.join(path, entry) if not os.path.isdir(cand): continue if not _is_adapter_folder(cand): continue if not _has_adapter_weights(cand): continue if best_step is None or step > best_step: best_step = step best_path = cand except FileNotFoundError: pass if best_path is None: raise ValueError( "Adapter folder does not contain adapter weights (adapter_model.*), " "and no checkpoint-* subfolder with weights was found. " f"Path: {path}" ) return best_path def resolve_user_adapter_arg(adapter: Optional[str], *, adapter_root: str) -> Optional[str]: """Resolve --adapter, allowing relative paths under --adapter-root.""" if not adapter: return None adapter = os.path.expanduser(adapter) if not os.path.isabs(adapter): adapter = os.path.join(adapter_root, adapter) return adapter def build_custom_chat_model( *, model_path: str, adapter_path: Optional[str], tokenizer_path: str, max_length: int, cache_dir: Optional[str], disable_vit_post_layernorm: bool, ): import torch from transformers import AutoModel, AutoTokenizer from types import MethodType from peft import PeftModel torch.set_grad_enabled(False) # transformers>=4.57 deprecates torch_dtype in favor of dtype. # Keep a compatibility fallback for older installs. try: base = AutoModel.from_pretrained( model_path, cache_dir=cache_dir, dtype=torch.bfloat16, trust_remote_code=True, ).cuda().eval() except TypeError: base = AutoModel.from_pretrained( model_path, cache_dir=cache_dir, torch_dtype=torch.bfloat16, trust_remote_code=True, ).cuda().eval() # If provided, apply LoRA adapters in-memory (no merge/save to disk). # IMPORTANT: we merge the adapter into the base weights (merge_and_unload) # so the resulting object remains the original model class with a stable # `.chat()` implementation. if adapter_path: adapter_path = resolve_adapter_path(adapter_path) model = PeftModel.from_pretrained(base, adapter_path).merge_and_unload().cuda().eval() else: model = base # Mitigation for the base-model warning: # Some HF snapshots load with missing vision post_layernorm weights, which then # get randomly initialized. If you want deterministic behavior that avoids # depending on those random init weights, you can disable the module. if disable_vit_post_layernorm: try: pln = model.vit.vision_tower.vision_model.post_layernorm # type: ignore[attr-defined] if pln is not None: model.vit.vision_tower.vision_model.post_layernorm = torch.nn.Identity() # type: ignore[attr-defined] except Exception: pass # Inference-time settings (from your Cell 15C). model.max_length = max_length model.config.max_length = max_length model.config.use_cache = False if hasattr(model, "generation_config") and model.generation_config is not None: model.generation_config.max_length = max_length model.generation_config.use_cache = False def _safe_prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, im_mask=None, infer_mode='base', **kwargs): pkv = past_key_values if pkv is not None and hasattr(pkv, 'to_legacy_cache'): try: pkv = pkv.to_legacy_cache() except Exception: pass if isinstance(pkv, (list, tuple)): all_none = True for layer in pkv: if layer is None: continue if isinstance(layer, (list, tuple)): for state in layer: if state is not None: all_none = False break if not all_none: break else: all_none = False break if all_none: pkv = None if isinstance(pkv, list): pkv = tuple(tuple(x for x in layer) if isinstance(layer, (list, tuple)) else layer for layer in pkv) elif isinstance(pkv, tuple): pkv = tuple(tuple(x for x in layer) if isinstance(layer, (list, tuple)) else layer for layer in pkv) past_length = 0 if isinstance(pkv, (list, tuple)): first_valid_state = None for layer in pkv: if not isinstance(layer, (list, tuple)): continue for state in layer: if state is not None and hasattr(state, 'shape') and len(state.shape) >= 3: first_valid_state = state break if first_valid_state is not None: break if first_valid_state is not None and first_valid_state.shape[2] > 0: past_length = int(first_valid_state.shape[2]) if past_length > 0: if input_ids.shape[1] > past_length: remove_prefix_length = past_length else: remove_prefix_length = max(input_ids.shape[1] - 1, 0) if remove_prefix_length: input_ids = input_ids[:, remove_prefix_length:] position_ids = kwargs.get('position_ids', None) if attention_mask is not None and position_ids is None: position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if pkv is not None: position_ids = position_ids[:, -input_ids.shape[1]:] if inputs_embeds is not None and (pkv is None or past_length == 0): model_inputs = {'inputs_embeds': inputs_embeds} else: model_inputs = {'input_ids': input_ids} model_inputs.update({ 'position_ids': position_ids, 'past_key_values': pkv, 'use_cache': kwargs.get('use_cache'), 'attention_mask': attention_mask, 'im_mask': im_mask, 'infer_mode': infer_mode, }) return model_inputs model.prepare_inputs_for_generation = MethodType(_safe_prepare_inputs_for_generation, model) tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, trust_remote_code=True, cache_dir=cache_dir) # IMPORTANT: # Do NOT auto-add a new "[PAD]" token at inference time. # For this model, adding a new special token forces a resize with random init. # We observed the model emitting that token inside answers (e.g. between coordinates), # and since we decode with skip_special_tokens=True, it gets stripped, appearing as # "truncation". # # Instead, keep the tokenizer as-is and (if needed) set pad_token_id to eos_token_id. # For batch=1 generation this is typically fine. try: if getattr(tokenizer, "pad_token_id", None) is None and getattr(tokenizer, "eos_token_id", None) is not None: tokenizer.pad_token = tokenizer.eos_token except Exception: pass # Keep generation config consistent with tokenizer. try: if hasattr(model, "generation_config") and model.generation_config is not None: model.generation_config.pad_token_id = getattr(tokenizer, "pad_token_id", None) model.generation_config.eos_token_id = getattr(tokenizer, "eos_token_id", None) # Reduce noisy warnings about unused sampling params when do_sample=False. if hasattr(model.generation_config, "top_p"): model.generation_config.top_p = None if hasattr(model.generation_config, "temperature"): model.generation_config.temperature = None except Exception: pass return model, tokenizer def infer_custom_chat( *, model: Any, tokenizer: Any, prompt: str, image_path: str, hd_num: int, max_new_tokens: int = 16384, do_sample: bool = False, num_beams: int = 1, temperature: Optional[float] = None, top_p: Optional[float] = None, ) -> str: import torch # Prefer the non-deprecated autocast API when available. try: autocast = torch.amp.autocast # type: ignore[attr-defined] with autocast("cuda", dtype=torch.bfloat16): try: out = model.chat( tokenizer, query=prompt, image=image_path, hd_num=hd_num, history=[], do_sample=bool(do_sample), num_beams=int(num_beams), use_cache=False, max_new_tokens=max_new_tokens, temperature=(float(temperature) if temperature is not None else 1.0), top_p=(float(top_p) if top_p is not None else 0.8), ) except TypeError: # Some InternLM-XComposer chat() variants don't accept max_new_tokens. # Best-effort: set generation_config, then call chat() again. if max_new_tokens is not None and hasattr(model, "generation_config") and model.generation_config is not None: try: model.generation_config.max_new_tokens = int(max_new_tokens) except Exception: pass out = model.chat( tokenizer, query=prompt, image=image_path, hd_num=hd_num, history=[], do_sample=bool(do_sample), num_beams=int(num_beams), use_cache=False, ) except Exception: try: out = model.chat( tokenizer, query=prompt, image=image_path, hd_num=hd_num, history=[], do_sample=bool(do_sample), num_beams=int(num_beams), use_cache=False, max_new_tokens=max_new_tokens, temperature=(float(temperature) if temperature is not None else 1.0), top_p=(float(top_p) if top_p is not None else 0.8), ) except TypeError: if max_new_tokens is not None and hasattr(model, "generation_config") and model.generation_config is not None: try: model.generation_config.max_new_tokens = int(max_new_tokens) except Exception: pass out = model.chat( tokenizer, query=prompt, image=image_path, hd_num=hd_num, history=[], do_sample=bool(do_sample), num_beams=int(num_beams), use_cache=False, ) # Some chat() implementations return (resp, history), others return resp. resp: Any if isinstance(out, tuple) and len(out) >= 1: resp = out[0] else: resp = out if resp is None: raise RuntimeError("model.chat() returned None") return str(resp) def _safe_int(x: Any) -> Optional[int]: try: return int(x) except Exception: return None def debug_generate_custom_chat( *, model: Any, tokenizer: Any, prompt: str, image_path: Optional[str], hd_num: int, max_new_tokens: int, do_sample: bool, num_beams: int, temperature: Optional[float], top_p: Optional[float], repetition_penalty: Optional[float] = None, ) -> tuple[str, Dict[str, Any]]: """Run a generate() call similar to model.chat(), but return deep debug info. This helps diagnose early stopping (EOS), max-length clamping, and tokenization issues. """ import torch dbg: Dict[str, Any] = {} dbg["max_new_tokens"] = int(max_new_tokens) dbg["do_sample"] = bool(do_sample) dbg["num_beams"] = int(num_beams) dbg["temperature"] = float(temperature) if temperature is not None else None dbg["top_p"] = float(top_p) if top_p is not None else None dbg["hd_num"] = int(hd_num) eos_id = getattr(tokenizer, "eos_token_id", None) pad_id = getattr(tokenizer, "pad_token_id", None) dbg["tokenizer"] = { "eos_token_id": _safe_int(eos_id), "pad_token_id": _safe_int(pad_id), "pad_equals_eos": (pad_id is not None and eos_id is not None and int(pad_id) == int(eos_id)), } # InternLM-XComposer2 chat() adds [UNUSED_TOKEN_145] as an EOS to stop at end-of-assistant. unused_145_id: Optional[int] = None try: unused_145_id = int(tokenizer.convert_tokens_to_ids(["[UNUSED_TOKEN_145]"])[0]) except Exception: unused_145_id = None dbg["unused_token_145_id"] = unused_145_id # Build model inputs similarly to model.chat(), but keep the whole vision path # under autocast to avoid dtype mismatches (Float vs BFloat16). history: list[tuple[str, str]] = [] meta_instruction: Optional[str] = None autocast = torch.amp.autocast # type: ignore[attr-defined] with autocast("cuda", dtype=torch.bfloat16): if image_path: # Use the model's own helpers to ensure im_mask and image embeddings match its expectations. img = model.encode_img(image_path, hd_num=int(hd_num)) inputs, im_mask = model.interleav_wrap_chat(tokenizer, prompt, img, history, meta_instruction) dbg["mode"] = "image" else: inputs = model.build_inputs(tokenizer, prompt, history, meta_instruction) im_mask = torch.zeros(inputs["input_ids"].shape[:2]).cuda().bool() dbg["mode"] = "text" # Move to device inputs = {k: v.to(model.device) for k, v in inputs.items() if torch.is_tensor(v)} input_ids = inputs.get("input_ids") attention_mask = inputs.get("attention_mask") dbg["input"] = { "input_ids_len": int(input_ids.shape[1]) if input_ids is not None else None, "has_attention_mask": attention_mask is not None, "attention_mask_sum": int(attention_mask.sum().item()) if attention_mask is not None else None, "im_mask_sum": int(im_mask.sum().item()) if im_mask is not None else None, } # Effective length controls (best-effort introspection) dbg["model_lengths"] = { "model_max_length_attr": _safe_int(getattr(model, "max_length", None)), "config_max_length": _safe_int(getattr(getattr(model, "config", None), "max_length", None)), "config_max_position_embeddings": _safe_int(getattr(getattr(model, "config", None), "max_position_embeddings", None)), "generation_config_max_length": _safe_int(getattr(getattr(model, "generation_config", None), "max_length", None)), "generation_config_max_new_tokens": _safe_int(getattr(getattr(model, "generation_config", None), "max_new_tokens", None)), } eos_token_id = [eos_id] if eos_id is not None else [] if unused_145_id is not None: eos_token_id.append(unused_145_id) dbg["eos_token_id"] = [int(x) for x in eos_token_id if x is not None] gen_kwargs: Dict[str, Any] = { "max_new_tokens": int(max_new_tokens), "num_beams": int(num_beams), "do_sample": bool(do_sample), "temperature": float(temperature) if temperature is not None else 1.0, "top_p": float(top_p) if top_p is not None else 0.8, "eos_token_id": eos_token_id, "im_mask": im_mask, "return_dict_in_generate": True, "output_scores": True, } if repetition_penalty is not None: gen_kwargs["repetition_penalty"] = float(repetition_penalty) out = model.generate(**inputs, **gen_kwargs) sequences = out.sequences seq0 = sequences[0].detach().cpu().tolist() dbg["output"] = { "sequences_len": int(sequences.shape[1]), "first_token_ids": seq0[: min(48, len(seq0))], "last_token_ids": seq0[max(len(seq0) - 48, 0) :], } # Locate early-stop tokens in the produced sequence. stop_positions: Dict[str, Optional[int]] = {} if eos_id is not None: try: stop_positions["eos_token_id_pos"] = seq0.index(int(eos_id)) except ValueError: stop_positions["eos_token_id_pos"] = None if unused_145_id is not None: try: stop_positions["unused_145_pos"] = seq0.index(int(unused_145_id)) except ValueError: stop_positions["unused_145_pos"] = None dbg["stop_positions"] = stop_positions # Decode a window around the end to spot what got emitted right before stopping. try: tail_ids = seq0[max(len(seq0) - 80, 0) :] dbg["decoded_tail"] = tokenizer.decode(tail_ids, skip_special_tokens=False) except Exception: dbg["decoded_tail"] = None # Produce a response string in the same spirit as chat(): strip at end-of-assistant token. decoded = tokenizer.decode(seq0, skip_special_tokens=True) if "[UNUSED_TOKEN_145]" in decoded: decoded = decoded.split("[UNUSED_TOKEN_145]")[0] return str(decoded), dbg def main() -> int: _assert_deps() # CLI entrypoint: # - selects which (task, perc) combinations to evaluate # - builds the base model + optional adapter # - runs inference for each item and writes JSONL + summaries ap = argparse.ArgumentParser( description=( "Run inference+evaluation for ablation-study fine-tuned LoRA adapters saved under an adapter root, " "evaluated on the corresponding ablation_splits/<task>/<perc>/test JSON files." ) ) ap.add_argument( "--splits-root", default="/users/<USER>/ablation_study_dataset_c1/ablation_splits", help="Root of ablation splits (contains task_*/perc_*).", ) ap.add_argument( "--adapter-root", default="mydata/ablation_study_outputs/finetune_lora", help="Root directory where LoRA adapters are saved (contains task_*/perc_*).", ) # Selection: tasks + percentages # These flags filter which folders are visited under <splits-root>/task_*/perc_*. ap.add_argument( "--task", action="append", default=None, help="Task short-name or folder name (e.g. a1 or task_a1). Can be repeated.", ) ap.add_argument( "--tasks", type=str, default=None, help="Comma-separated tasks (e.g. a1,b1 or task_a1,task_b1). Default: all.", ) ap.add_argument( "--perc", action="append", default=None, help="Dataset percentage (e.g. 25 or perc_025). Can be repeated.", ) ap.add_argument( "--percs", type=str, default=None, help="Comma-separated percentages (e.g. 25,50,75 or perc_025,perc_050). Default: all.", ) ap.add_argument( "--num-samples", type=int, default=-1, help="How many samples to run from each test file (-1 = all). Default: -1 (all)", ) ap.add_argument("--seed", type=int, default=1337) ap.add_argument( "--skip-missing-adapter", action="store_true", help="If set, skip runs where the adapter folder does not exist.", ) ap.add_argument( "--cache-dir", default="mydata/VLM_cache", help=( "Cache directory for Transformers/HuggingFace downloads (base model + tokenizer). " "If set, also exports HF_HOME/HF_HUB_CACHE/TRANSFORMERS_CACHE to this value for the process." ), ) # Fine-tuned model sources # - original-base-model is the HF id used during LoRA training (tokenizer defaults to this). # - adapter allows evaluating exactly one adapter path. ap.add_argument( "--original-base-model", default="internlm/internlm-xcomposer2-4khd-7b", help="HF model id/path for the ORIGINAL base model used for LoRA training (used for merging + tokenizer by default).", ) ap.add_argument( "--adapter", default=None, help=( "Optional override: evaluate a single adapter path (contains adapter_config.json). " "If set, task/perc selection is ignored and only this adapter is evaluated using the matching test split." ), ) ap.add_argument( "--no-adapter", action="store_true", help=( "Disable LoRA adapter loading and run inference on the base model only. " "This ignores --adapter and does not require adapter folders to exist." ), ) # NOTE: This script is custom-only. It does not merge/save models, and does not use lmdeploy. # custom chat settings # These control the InternLM-XComposer2 "custom chat" inference path. ap.add_argument("--tokenizer", default=None, help="Tokenizer path/id for custom chat (default: --original-base-model).") ap.add_argument("--max-length", type=int, default=16384, help="custom chat model max_length") ap.add_argument("--hd-num", type=int, default=6, help="custom chat hd_num") ap.add_argument( "--max-new-tokens-choice", type=int, default=1024, help="Generation budget for choice-only tasks (a1/b1/c1).", ) # Robustness helpers for choice tasks: # - retry_empty_choice: rerun inference when output contains no parsable A-F letter # - force_choice_letter_fallback: last-resort constrained decode to get a single letter ap.add_argument( "--retry-empty-choice", type=int, default=0, help=( "If >0, retry inference up to N times for choice tasks when the model output contains no parsable choice letter. " "This is useful when the model sometimes returns an empty/newline-only response (e.g., '\\n'). Default: 0 (disabled)." ), ) ap.add_argument( "--retry-empty-choice-max-new-tokens", type=int, default=None, help=( "Optional override: max_new_tokens to use for retry attempts on choice tasks. " "If not set, uses max(--max-new-tokens-choice, 16)." ), ) ap.add_argument( "--force-choice-letter-fallback", action="store_true", help=( "If set, and a choice-task prediction still has no parsable letter after retries, " "run a final constrained 1-token decode restricted to the allowed option letters. " "This prevents whitespace-only outputs like '\\n'." ), ) # Box-task decoding controls. Box tasks tend to require longer generations. ap.add_argument( "--max-new-tokens-boxes", type=int, default=16384, help="Generation budget for box tasks (b2/c2).", ) ap.add_argument( "--boxes-do-sample", action="store_true", help="Enable sampling for box tasks (b2/c2). Useful to test greedy early-stopping.", ) ap.add_argument( "--boxes-temperature", type=float, default=0.7, help="Sampling temperature for box tasks when --boxes-do-sample is set.", ) ap.add_argument( "--boxes-top-p", type=float, default=0.9, help="Top-p for box tasks when --boxes-do-sample is set.", ) ap.add_argument( "--boxes-num-beams", type=int, default=1, help="Beam count for box tasks (b2/c2). Set >1 to try beam search (do_sample stays False unless --boxes-do-sample).", ) ap.add_argument( "--disable-vit-post-layernorm", action="store_true", help=( "Set vision_tower.vision_model.post_layernorm = Identity after loading. " "Useful if the base snapshot reports missing post_layernorm weights and you want to avoid random-init impact." ), ) ap.add_argument("--run-tag", default=None) ap.add_argument("--dry-run", action="store_true") # Debugging: # If enabled, attach extra generate()-level diagnostics to the first items. ap.add_argument( "--debug-generate", action="store_true", help=( "If set, run an additional low-level generate() pass for the first few samples of each split and store " "detailed token/EOS diagnostics under rec['debug_generation']." ), ) ap.add_argument( "--debug-generate-max-items", type=int, default=3, help="Max number of items per split to attach debug_generation info for (default: 3).", ) args = ap.parse_args() run_tag = args.run_tag or _now_tag() # Normalize selection filters. task_inputs: list[str] | None = None if args.task: task_inputs = list(args.task) if args.tasks: task_inputs = (task_inputs or []) + [args.tasks] perc_inputs: list[str] | None = None if args.perc: perc_inputs = list(args.perc) if args.percs: perc_inputs = (perc_inputs or []) + [args.percs] tasks_filter: Optional[List[str]] = None if task_inputs: toks: List[str] = [] for v in task_inputs: for piece in v.split(","): piece = piece.strip() if piece: toks.append(_normalize_task_token(piece)) tasks_filter = sorted(set(toks)) or None percs_filter: Optional[List[str]] = None if perc_inputs: toks2: List[str] = [] for v in perc_inputs: for piece in v.split(","): piece = piece.strip() if piece: toks2.append(_normalize_perc_token(piece)) percs_filter = sorted(set(toks2), key=_perc_key) or None # Optional single-adapter override. adapter_override: Optional[str] = None if bool(args.no_adapter) and args.adapter: raise SystemExit("--no-adapter cannot be used together with --adapter") if args.adapter: adapter_override = resolve_user_adapter_arg(str(args.adapter), adapter_root=str(args.adapter_root)) if adapter_override is None: raise SystemExit("--adapter was provided but could not be resolved") # If task/perc not explicitly selected, try to infer from the adapter path. if tasks_filter is None or percs_filter is None: m_task = re.search(r"(?:^|/)(task_[^/]+)(?:/|$)", adapter_override) m_perc = re.search(r"(?:^|/)(perc_\d+)(?:/|$)", adapter_override) if (tasks_filter is None and m_task is None) or (percs_filter is None and m_perc is None): raise SystemExit( "When using --adapter, also pass --task/--perc (or include task_*/perc_* in the adapter path)." ) if tasks_filter is None and m_task is not None: tasks_filter = [m_task.group(1)] if percs_filter is None and m_perc is not None: percs_filter = [m_perc.group(1)] if tasks_filter is None or percs_filter is None or len(tasks_filter) != 1 or len(percs_filter) != 1: raise SystemExit("--adapter override requires selecting exactly one task and one perc") # Discover which ablation runs to execute. runs = discover_ablation_runs( splits_root=str(args.splits_root), adapter_root=str(args.adapter_root), tasks_filter=tasks_filter, percs_filter=percs_filter, ) if not runs: raise SystemExit("No ablation runs matched your selection (task/perc filters).") if adapter_override is not None: # Replace adapter path for the single selected run. runs = runs[:1] runs[0]["adapter_path"] = adapter_override if bool(args.no_adapter): # Evaluate the base model only (no LoRA merge). Keep split discovery the same. for r in runs: r["adapter_path"] = None # type: ignore[assignment] print(f"Planned ablation runs: {len(runs)}") for i, r in enumerate(runs, start=1): print(f"[{i}/{len(runs)}] {r['task_dir']}/{r['perc_dir']}") print(f" test: {r['test_path']}") print(f" adapter: {r.get('adapter_path') or '(none)'}") print(f" results: {r['results_dir']}") if args.dry_run: shown = 0 for r in runs: items = load_json(r["test_path"]) selected = _iter_random_items(items, n=min(args.num_samples, 5), seed=args.seed) print(f"- Split: task={r['task']} perc={r['perc']} file={r['test_path']}") for it in selected[: min(5, len(selected))]: img = (it.get("image") or [None])[0] print(" ", it.get("id"), img, extract_prompt(it)[:120]) shown += 1 if shown >= 10: break if shown >= 10: break print("Dry-run complete.") return 0 _apply_hf_cache_dir(args.cache_dir) # capture versions for reproducibility try: import transformers # type: ignore transformers_version = getattr(transformers, "__version__", None) except Exception: transformers_version = None try: import peft # type: ignore peft_version = getattr(peft, "__version__", None) except Exception: peft_version = None try: import torch # type: ignore torch_version = getattr(torch, "__version__", None) except Exception: torch_version = None model_path = str(args.original_base_model) tok_path = str(args.tokenizer or args.original_base_model) # Aggregate accuracy across percs for each task # Structure: # agg_by_task[task] = { # correct, scored, errors, # by_circuit: {circuit: {correct, scored, errors}}, # by_perc: {perc_dir: {correct, scored, errors, by_circuit: {...}}} # } agg_by_task: Dict[str, Dict[str, Any]] = {} for run_idx, r in enumerate(runs, start=1): task = r["task"] perc_dir = r["perc_dir"] test_path = r["test_path"] adapter_path = r.get("adapter_path") results_dir = r["results_dir"] effective_adapter: Optional[str] = None if not bool(args.no_adapter): if not isinstance(adapter_path, str) or not adapter_path: raise SystemExit("Internal error: adapter_path missing for a run (expected a string)") if not os.path.isdir(adapter_path): msg = f"Missing adapter folder: {adapter_path}" if args.skip_missing_adapter: print(f"[SKIP] {msg}") continue raise SystemExit(msg) effective_adapter = resolve_adapter_path(adapter_path) ensure_dir(results_dir) # Keep filenames stable and avoid duplication like 'perc-perc_025'. perc_label = perc_dir if perc_label.startswith("perc_"): perc_label = perc_label[len("perc_") :] base_name = f"{run_tag}_eval_task-{task}_perc-{perc_label}_impl-custom" + ("_base" if bool(args.no_adapter) else "") base_name = pick_unique_result_base(results_dir, base_name) out_jsonl = os.path.join(results_dir, base_name + ".jsonl") out_summary = os.path.join(results_dir, base_name + "_summary.json") out_acc_txt = os.path.join(results_dir, base_name + "_accuracy_summary.txt") print(f"\n[{run_idx}/{len(runs)}] Evaluating task={task} perc={perc_dir}") print(f"Test: {test_path}") print(f"Adapter: {adapter_path or '(none)'}") print(f"Out: {out_jsonl}") custom_model, custom_tokenizer = build_custom_chat_model( model_path=model_path, adapter_path=effective_adapter, tokenizer_path=tok_path, max_length=int(args.max_length), cache_dir=str(args.cache_dir) if args.cache_dir else None, disable_vit_post_layernorm=bool(args.disable_vit_post_layernorm), ) items = load_json(test_path) selected = _iter_random_items(items, n=int(args.num_samples), seed=int(args.seed)) correct = 0 wrong = 0 errors: List[Dict[str, Any]] = [] by_circuit: Dict[str, Dict[str, int]] = {} # JSONL output schema: # - one line per evaluated item # - includes metadata (task/perc/circuit, model/adapter, versions) # - includes prompt+gt+prediction and a scoring object with open(out_jsonl, "w", encoding="utf-8") as f: for idx, it in enumerate(selected, start=1): img_path = (it.get("image") or [None])[0] circuit = circuit_from_image_path(img_path) if isinstance(img_path, str) else None circuit = circuit or "unknown" # rec is the canonical per-item record written to JSONL. rec: Dict[str, Any] = { "task": task, "perc": perc_dir, "circuit": circuit, "index": idx, "id": it.get("id"), "inference_impl": "custom", "base_model": args.original_base_model, "adapter": adapter_path, "effective_adapter": effective_adapter, "cache_dir": args.cache_dir, "versions": { "transformers": transformers_version, "peft": peft_version, "torch": torch_version, }, "disable_vit_post_layernorm": bool(args.disable_vit_post_layernorm), } if not isinstance(img_path, str): rec["error"] = "missing_image_path" errors.append(rec) f.write(json.dumps(rec, ensure_ascii=False) + "\n") continue prompt = extract_prompt(it) prompt_for_model = extract_prompt_custom(it) gt = extract_ground_truth(it) rec.update( {"image": img_path, "prompt": prompt, "prompt_for_model": prompt_for_model, "ground_truth": gt} ) # Inference+scoring: # - infer_custom_chat produces raw model text # - score_item parses and scores depending on task mode (choice vs boxes) try: gen_budget = ( int(args.max_new_tokens_choice) if task_mode(task) == "choice" else int(args.max_new_tokens_boxes) ) boxes_mode = task_mode(task) == "boxes" pred_text = infer_custom_chat( model=custom_model, tokenizer=custom_tokenizer, prompt=prompt_for_model, image_path=img_path, hd_num=int(args.hd_num), max_new_tokens=gen_budget, do_sample=bool(args.boxes_do_sample and boxes_mode), num_beams=int(args.boxes_num_beams) if boxes_mode else 1, temperature=(args.boxes_temperature if (boxes_mode and args.boxes_do_sample) else None), top_p=(args.boxes_top_p if (boxes_mode and args.boxes_do_sample) else None), ) if bool(args.debug_generate) and idx <= int(args.debug_generate_max_items): try: dbg_pred, dbg = debug_generate_custom_chat( model=custom_model, tokenizer=custom_tokenizer, prompt=prompt_for_model, image_path=img_path, hd_num=int(args.hd_num), max_new_tokens=int(gen_budget), do_sample=bool(args.boxes_do_sample and boxes_mode), num_beams=int(args.boxes_num_beams) if boxes_mode else 1, temperature=(args.boxes_temperature if (boxes_mode and args.boxes_do_sample) else None), top_p=(args.boxes_top_p if (boxes_mode and args.boxes_do_sample) else None), ) rec["debug_generation"] = { "debug_pred": dbg_pred, "debug": dbg, } except Exception as e: rec["debug_generation"] = { "error": f"debug_generate_failed: {type(e).__name__}: {e}", } # Optional robustness: if we cannot parse a choice letter at all, retry with a stricter instruction. # This helps when the model occasionally returns a whitespace-only answer. if task_mode(task) == "choice": pred_letter = parse_choice_letter(pred_text) if pred_letter is None and int(args.retry_empty_choice) > 0: attempts: List[Dict[str, Any]] = [] retry_budget = ( int(args.retry_empty_choice_max_new_tokens) if args.retry_empty_choice_max_new_tokens is not None else max(int(gen_budget), 16) ) for attempt_idx in range(1, int(args.retry_empty_choice) + 1): strict_prompt = ( f"{prompt_for_model}\n\n" "Return ONLY the letter (A, B, C, or D). No other text." ) retry_text = infer_custom_chat( model=custom_model, tokenizer=custom_tokenizer, prompt=strict_prompt, image_path=img_path, hd_num=int(args.hd_num), max_new_tokens=retry_budget, do_sample=False, num_beams=1, ) attempts.append( { "attempt": attempt_idx, "max_new_tokens": retry_budget, "prediction": retry_text, } ) if parse_choice_letter(retry_text) is not None: pred_text = retry_text break if attempts: rec["retry_empty_choice_attempts"] = attempts # If still no parsable letter, optionally force a single-token choice. if ( parse_choice_letter(pred_text) is None and bool(args.force_choice_letter_fallback) ): allowed_letters = infer_allowed_choice_letters(prompt_for_model) forced = infer_custom_chat_constrained_choice( model=custom_model, tokenizer=custom_tokenizer, prompt=strict_prompt, image_path=img_path, hd_num=int(args.hd_num), allowed_letters=allowed_letters, max_new_tokens=1, ) rec["force_choice_letter_fallback"] = { "allowed_letters": allowed_letters, "prediction": forced, } pred_text = forced rec["prediction"] = pred_text scoring = score_item(task, gt=gt, pred=pred_text) rec["scoring"] = scoring by_circuit.setdefault(circuit, {"correct": 0, "wrong": 0, "errors": 0}) if scoring.get("correct"): correct += 1 by_circuit[circuit]["correct"] += 1 else: wrong += 1 by_circuit[circuit]["wrong"] += 1 except Exception as e: rec["error"] = f"inference_failed: {type(e).__name__}: {e}" errors.append(rec) by_circuit.setdefault(circuit, {"correct": 0, "wrong": 0, "errors": 0}) by_circuit[circuit]["errors"] += 1 f.write(json.dumps(rec, ensure_ascii=False) + "\n") if idx % 50 == 0: print(f"Progress: {idx}/{len(selected)}") scored = correct + wrong run_summary: Dict[str, Any] = { "mode": "ablation", "task": task, "perc": perc_dir, "test_file": test_path, "adapter": adapter_path, "effective_adapter": effective_adapter, "cache_dir": args.cache_dir, "seed": args.seed, "num_selected": len(selected), "num_scored": scored, "num_errors": len(errors), "correct": correct, "wrong": wrong, "accuracy": (correct / scored) if scored else None, "by_circuit": { c: { **v, "scored": int(v["correct"] + v["wrong"]), "accuracy": (v["correct"] / (v["correct"] + v["wrong"])) if (v["correct"] + v["wrong"]) else None, } for c, v in sorted(by_circuit.items()) }, "output_jsonl": out_jsonl, "args": { "max_length": int(args.max_length), "hd_num": int(args.hd_num), "max_new_tokens_choice": int(args.max_new_tokens_choice), "max_new_tokens_boxes": int(args.max_new_tokens_boxes), "boxes_do_sample": bool(args.boxes_do_sample), "boxes_temperature": float(args.boxes_temperature), "boxes_top_p": float(args.boxes_top_p), "boxes_num_beams": int(args.boxes_num_beams), "retry_empty_choice": int(args.retry_empty_choice), "retry_empty_choice_max_new_tokens": ( int(args.retry_empty_choice_max_new_tokens) if args.retry_empty_choice_max_new_tokens is not None else None ), "force_choice_letter_fallback": bool(args.force_choice_letter_fallback), "debug_generate": bool(args.debug_generate), "debug_generate_max_items": int(args.debug_generate_max_items), }, } with open(out_summary, "w", encoding="utf-8") as fsum: json.dump(run_summary, fsum, ensure_ascii=False, indent=2) write_split_accuracy_summary_txt(summary=run_summary, out_path=out_acc_txt) print(f"Done split: acc={run_summary['accuracy']} (correct={correct}, wrong={wrong}, errors={len(errors)})") print(f"Summary: {out_summary}") print(f"Accuracy summary: {out_acc_txt}") # Update per-task aggregation bucket = agg_by_task.setdefault( task, {"correct": 0, "scored": 0, "errors": 0, "by_circuit": {}, "by_perc": {}}, ) bucket["correct"] += int(correct) bucket["scored"] += int(scored) bucket["errors"] += int(len(errors)) perc_bucket = bucket["by_perc"].setdefault( perc_dir, {"correct": 0, "scored": 0, "errors": 0, "by_circuit": {}}, ) perc_bucket["correct"] += int(correct) perc_bucket["scored"] += int(scored) perc_bucket["errors"] += int(len(errors)) for c, v in by_circuit.items(): cb = bucket["by_circuit"].setdefault(c, {"correct": 0, "scored": 0, "errors": 0}) cb["correct"] += int(v.get("correct", 0)) cb["scored"] += int(v.get("correct", 0) + v.get("wrong", 0)) cb["errors"] += int(v.get("errors", 0)) pcb = perc_bucket["by_circuit"].setdefault(c, {"correct": 0, "scored": 0, "errors": 0}) pcb["correct"] += int(v.get("correct", 0)) pcb["scored"] += int(v.get("correct", 0) + v.get("wrong", 0)) pcb["errors"] += int(v.get("errors", 0)) # Print/write accuracy summary per task for task, b in sorted(agg_by_task.items()): scored = int(b["scored"]) correct2 = int(b["correct"]) acc = (correct2 / scored) if scored else None print(f"\nTASK SUMMARY: {task}") if acc is None: print("- global: n_scored=0") else: print(f"- global: acc={acc:.4f} ({correct2}/{scored}), errors={int(b['errors'])}") print("- by_circuit:") for c, cv in sorted(b["by_circuit"].items()): s2 = int(cv["scored"]) c2 = int(cv["correct"]) a2 = (c2 / s2) if s2 else None if a2 is None: print(f" - {c}: n_scored=0") else: print(f" - {c}: acc={a2:.4f} ({c2}/{s2}), errors={int(cv['errors'])}") # Also show per-perc breakdown so it's clear where errors come from. by_perc = b.get("by_perc") or {} if isinstance(by_perc, dict) and by_perc: print("- by_perc:") for perc_dir in sorted(by_perc.keys(), key=_perc_key): pv = by_perc.get(perc_dir) or {} ps = int(pv.get("scored") or 0) pc = int(pv.get("correct") or 0) pe = int(pv.get("errors") or 0) pa = (pc / ps) if ps else None if pa is None: print(f" - {perc_dir}: n_scored=0, errors={pe}") else: print(f" - {perc_dir}: acc={pa:.4f} ({pc}/{ps}), errors={pe}") # Save the same summary into each task folder (once per task) task_dir = os.path.join(str(args.splits_root), f"task_{task}") task_results_dir = os.path.join(task_dir, "results") ensure_dir(task_results_dir) out_txt = os.path.join(task_results_dir, f"{run_tag}_accuracy_summary_task-{task}.txt") lines: List[str] = [] lines.append(f"Task: {task}") lines.append(f"Run tag: {run_tag}") lines.append(f"Splits root: {args.splits_root}") lines.append(f"Adapter root: {args.adapter_root}") lines.append(f"Cache dir: {args.cache_dir}") lines.append("") if acc is None: lines.append("GLOBAL: n_scored=0") else: lines.append(f"GLOBAL: acc={acc:.4f} ({correct2}/{scored}), errors={int(b['errors'])}") lines.append("") lines.append("BY_CIRCUIT:") for c, cv in sorted(b["by_circuit"].items()): s2 = int(cv["scored"]) c2 = int(cv["correct"]) a2 = (c2 / s2) if s2 else None if a2 is None: lines.append(f"- {c}: n_scored=0") else: lines.append(f"- {c}: acc={a2:.4f} ({c2}/{s2}), errors={int(cv['errors'])}") by_perc = b.get("by_perc") or {} if isinstance(by_perc, dict) and by_perc: lines.append("") lines.append("BY_PERC:") for perc_dir in sorted(by_perc.keys(), key=_perc_key): pv = by_perc.get(perc_dir) or {} ps = int(pv.get("scored") or 0) pc = int(pv.get("correct") or 0) pe = int(pv.get("errors") or 0) pa = (pc / ps) if ps else None if pa is None: lines.append(f"- {perc_dir}: n_scored=0, errors={pe}") else: lines.append(f"- {perc_dir}: acc={pa:.4f} ({pc}/{ps}), errors={pe}") # Detailed per-circuit for this perc. pbc = pv.get("by_circuit") or {} if isinstance(pbc, dict) and pbc: for circuit in sorted(pbc.keys()): cv = pbc.get(circuit) or {} s2 = int(cv.get("scored") or 0) c2 = int(cv.get("correct") or 0) e2 = int(cv.get("errors") or 0) a2 = (c2 / s2) if s2 else None if a2 is None: lines.append(f" - {circuit}: n_scored=0, errors={e2}") else: lines.append(f" - {circuit}: acc={a2:.4f} ({c2}/{s2}), errors={e2}") with open(out_txt, "w", encoding="utf-8") as ftxt: ftxt.write("\n".join(lines) + "\n") print(f"Saved: {out_txt}") return 0 if __name__ == "__main__": raise SystemExit(main())
#!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Ablation-study evaluator for LoRA fine-tuned adapters (custom inference path).
#
# Typical workflow:
# 1) Fine-tune adapters for multiple (task, perc) splits with VLM_finetune.
# 2) Use THIS script to evaluate each adapter on its matching test split.
#
# What this script discovers and evaluates:
# - Dataset splits live under: <splits-root>/task_*/perc_*/test/*.json
# - LoRA adapters live under: <adapter-root>/task_*/perc_*/
#
# Outputs (written into each split's results directory):
# - <base>.jsonl per-sample records (prompt/gt/pred/scoring + metadata)
# - <base>_summary.json per-split aggregate metrics + args
# - <base>_accuracy_summary.txt human-readable per-circuit + global accuracy
#
# Notes:
# - This is a "custom" evaluator: it loads the base model + adapter via Transformers/PEFT and
# runs the model's chat-style inference (not lmdeploy).
# - Task types differ:
# - choice tasks (a1/b1/c1) are scored by extracting A-F letters from model output
# - box tasks (b2/c2) are scored by parsing coordinate tuples / bounding boxes
# -----------------------------------------------------------------------------
import argparse
import datetime as _dt
import json
import os
import random
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple
# ---- Minimal evaluation utilities ----
# The regexes below are deliberately conservative: many VLMs produce verbose text and we
# want to avoid accidentally extracting choice letters from unrelated prose.
# Some datasets use A-D, others (base circuits) can use A-F.
# NOTE: Don't use a naive "\bA\b" match for predictions; many models emit prose
# containing standalone 'A' tokens (e.g. 'A breakdown...'), which would create
# false positives. We keep a strict token matcher and add higher-priority patterns.
CHOICE_TOKEN_RE = re.compile(r"\b([A-F])\s*(?:[\.,\)])")
CHOICE_LABEL_RE = re.compile(
r"(?i)(?:^|\b)(?:final\s*answer|final|answer|choice)\s*[:\-]?\s*([A-F])\s*(?:[\.,\)]|\b)"
)
CHOICE_CORRECT_RE = re.compile(r"(?i)(?:the\s+)?correct\s+answer\s+is\s*([A-F])\s*(?:[\.,\)]|\b)")
CHOICE_LINE_RE = re.compile(r"^\s*([A-F])\s*(?:[\.,\)]\s*)?$")
CHOICE_COORDS_LINE_RE = re.compile(r"^\s*([A-F])\s*,\s*(?:coordinates?|bbox|boxes?)\b", re.IGNORECASE)
BOX_RE = re.compile(r"\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)\s*-\s*\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)")
INT_RE = re.compile(r"-?\d+")
def _now_tag() -> str:
return _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
def _assert_deps() -> None:
missing: List[str] = []
for name in ["torch", "transformers", "peft", "PIL"]:
try:
__import__(name)
except Exception:
missing.append(name)
if missing:
raise SystemExit(
"Missing required packages: "
+ ", ".join(missing)
+ "\nActivate your environment first, e.g.:\n"
+ " source mydata/<USER>/conda/anaconda3/etc/profile.d/conda.sh\n"
+ " conda activate VLM-ft\n"
)
def _parse_csv(value: str | None) -> list[str] | None:
if value is None:
return None
items = [v.strip() for v in value.split(",") if v.strip()]
return items or None
def _normalize_task_token(token: str) -> str:
t = token.strip()
if not t:
raise ValueError("Empty task token")
if t.startswith("task_"):
return t
return f"task_{t}"
def _normalize_perc_token(token: str) -> str:
t = token.strip()
if not t:
raise ValueError("Empty perc token")
if t.startswith("perc_"):
return t
if t.isdigit():
return f"perc_{int(t):03d}"