Image Segmentation
Transformers
grounding
instance-segmentation
polygon-prediction
baseline
research-code
Instructions to use royguw/ft_qwen3_5 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use royguw/ft_qwen3_5 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-segmentation", model="royguw/ft_qwen3_5")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("royguw/ft_qwen3_5", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download outdated/run_eval.py from royguw/ft_qwen3_5: direct link, hf CLI and curl.
- Browser
- Download file 31.1 kB
-
https://huggingface.co/royguw/ft_qwen3_5/resolve/main/outdated/run_eval.py
- Command line
-
hf download hf://royguw/ft_qwen3_5/outdated/run_eval.py
-
curl -L -o run_eval.py https://huggingface.co/royguw/ft_qwen3_5/resolve/main/outdated/run_eval.py
31.1 kB
| """ | |
| Standalone evaluation for FT Qwen3.5 autoregressive baseline. | |
| Supports two modes: | |
| - generate: actual autoregressive generation (model.generate()) | |
| - teacher_forced: forward pass + argmax at target positions (fast sanity check) | |
| Computes pixel-level metrics identical to ground_qwen35's eval for fair comparison. | |
| Usage: | |
| cd /weka-mm/royg/ft_qwen3_5 | |
| python -m ft_qwen35.eval_scripts.run_eval \ | |
| /weka-mm/royg/ground_ckpts/ft_qwen3_5/mar_15_g2_8192/step50000 \ | |
| --output_dir ./eval_results \ | |
| --cache_dir ./eval_cache \ | |
| --batch_size 4 \ | |
| --num_workers 4 \ | |
| --datasets refcoco refcoco_plus coconut_pos_neg ade20k_pos_neg lvis_pos_neg refcocog_baseline grefcoco_baseline coconut_pancap_baseline \ | |
| --mode generate \ | |
| --max_new_tokens 4096 \ | |
| --seed 42 | |
| """ | |
| import argparse | |
| import json | |
| import logging | |
| import os | |
| import sys | |
| import time | |
| from typing import Dict, List, Optional, Tuple | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import DataLoader | |
| from tqdm import tqdm | |
| from transformers import AutoTokenizer, AutoProcessor, Qwen3_5ForConditionalGeneration | |
| from ..config import FTQwen35Config | |
| from ..data.collator import FTCollator | |
| from ..data.preprocessor import FTExamplePreprocessor | |
| from ..data.dataset import EvalFTDataset | |
| from ..eval_metrics import ( | |
| polygons_to_mask, | |
| ) | |
| # Import ground_qwen35's metric functions for fair comparison | |
| sys.path.insert(0, "/weka-mm/royg/ground_qwen3_5") | |
| from ground_qwen35.caption_eval import ( | |
| compute_caption_metrics_for_image, | |
| compute_mask_iou_matrix, | |
| hungarian_match_sim, | |
| ) | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| logger = logging.getLogger(__name__) | |
| REFCOCO_EVAL_DATASETS = ["refcoco", "refcoco_plus"] | |
| HUNGARIAN_EVAL_DATASETS = ["coconut_pos_neg", "ade20k_pos_neg", "lvis_pos_neg"] | |
| CAPTION_BASELINE_EVAL_DATASETS = ["refcocog_baseline", "grefcoco_baseline", "coconut_pancap_baseline"] | |
| PRECISION_THRESHOLDS = (0.5, 0.6, 0.7, 0.8, 0.9) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Robust Text Parsing | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def parse_generated_text(text: str, coord_range: int = 1000) -> List[dict]: | |
| """Parse generated text into structured instances, tolerating malformed output. | |
| More lenient than parse_target_text(): handles odd coords, non-integers, | |
| missing semicolons, truncated lines, etc. | |
| Returns: | |
| List of dicts with 'polygons' (list of [[x,y],...]) and 'char_spans' (list of [s,e]) | |
| """ | |
| max_coord = coord_range - 1 | |
| instances = [] | |
| for line in text.strip().split("\n"): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| # Split on ';' to separate polygon part from span part | |
| parts = line.split(";") | |
| poly_str = parts[0].strip() | |
| span_str = parts[1].strip() if len(parts) >= 2 else "" | |
| # Parse polygon segments (separated by '|') | |
| polygons = [] | |
| for seg_str in poly_str.split("|"): | |
| seg_str = seg_str.strip() | |
| if not seg_str: | |
| continue | |
| # Parse individual tokens, skipping non-integers | |
| int_values = [] | |
| for tok in seg_str.split(): | |
| try: | |
| int_values.append(int(tok)) | |
| except ValueError: | |
| continue | |
| # Drop last value if odd number (make even pairs) | |
| if len(int_values) % 2 != 0: | |
| int_values = int_values[:-1] | |
| # Build (x, y) points with clamping | |
| points = [] | |
| for j in range(0, len(int_values), 2): | |
| x = max(0, min(int_values[j], max_coord)) | |
| y = max(0, min(int_values[j + 1], max_coord)) | |
| points.append([x, y]) | |
| # Need >= 3 points for a valid polygon segment | |
| if len(points) >= 3: | |
| polygons.append(points) | |
| # Parse char spans | |
| char_spans = [] | |
| if span_str: | |
| span_vals = [] | |
| for tok in span_str.split(): | |
| try: | |
| span_vals.append(int(tok)) | |
| except ValueError: | |
| continue | |
| # Drop last value if odd number | |
| if len(span_vals) % 2 != 0: | |
| span_vals = span_vals[:-1] | |
| for j in range(0, len(span_vals), 2): | |
| s = max(0, span_vals[j]) | |
| e = max(0, span_vals[j + 1]) | |
| if s < e: | |
| char_spans.append([s, e]) | |
| if polygons or char_spans: | |
| instances.append({"polygons": polygons, "char_spans": char_spans}) | |
| return instances | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Model Loading | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_model(checkpoint_path: str, device: torch.device): | |
| """Load FT Qwen3.5 model from checkpoint. | |
| Returns: | |
| (model, tokenizer, image_processor, config, device) | |
| """ | |
| # Load train state to get config | |
| train_dir = os.path.join(checkpoint_path, "train") | |
| rank_path = os.path.join(train_dir, "rank0.pt") | |
| if not os.path.isfile(rank_path): | |
| rank_path = os.path.join(checkpoint_path, "train_state.pt") | |
| if not os.path.isfile(rank_path): | |
| raise FileNotFoundError(f"No train state found in {checkpoint_path}") | |
| train_state = torch.load(rank_path, map_location="cpu", weights_only=False) | |
| config_dict = train_state["config"] | |
| config = FTQwen35Config(**config_dict) | |
| logger.info(f"Loaded config: coord_range={config.coord_range}, " | |
| f"max_poly_points={config.max_poly_points}, max_seq_len={config.max_seq_len}") | |
| # Load base model | |
| logger.info(f"Loading base model from {config.pretrained_path}...") | |
| model = Qwen3_5ForConditionalGeneration.from_pretrained( | |
| config.pretrained_path, | |
| torch_dtype=torch.bfloat16, | |
| ) | |
| # Load finetuned weights | |
| model_path = os.path.join(checkpoint_path, "model.pt") | |
| if os.path.isfile(model_path): | |
| state_dict = torch.load(model_path, map_location=device, weights_only=True) | |
| model.load_state_dict(state_dict) | |
| logger.info(f"Loaded model weights from {model_path}") | |
| else: | |
| raise FileNotFoundError(f"No model.pt found at {model_path}") | |
| model = model.to(device) | |
| model.eval() | |
| # Processor (handles tokenization + image processing + mm_token_type_ids) | |
| processor = AutoProcessor.from_pretrained(config.pretrained_path) | |
| tokenizer = processor.tokenizer | |
| return model, tokenizer, processor, config | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Pixel Value Extraction Helper | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _extract_sample_pixel_values(pixel_values, image_grid_thw, sample_idx): | |
| """Extract pixel_values for a single sample from concatenated batch tensor. | |
| pixel_values: (total_patches, dim) β concatenated across batch | |
| image_grid_thw: (B, 3) β [T, H, W] per sample | |
| """ | |
| n_patches = (image_grid_thw[:, 0] * image_grid_thw[:, 1] * image_grid_thw[:, 2]).tolist() | |
| start = sum(n_patches[:sample_idx]) | |
| end = start + n_patches[sample_idx] | |
| return pixel_values[start:end] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Inference: Generation Mode | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_generation_inference( | |
| model, | |
| tokenizer, | |
| dataloader, | |
| device, | |
| max_new_tokens: int = 4096, | |
| ) -> List[List[str]]: | |
| """Run batched autoregressive generation. | |
| Left-pads prompts so the entire batch can be processed in a single | |
| model.generate() call for GPU parallelism. | |
| Returns list of lists of predicted text strings (one list per batch). | |
| """ | |
| eos_token_id = tokenizer.eos_token_id | |
| pad_token_id = tokenizer.pad_token_id | |
| if pad_token_id is None or pad_token_id == eos_token_id: | |
| # Use a different token for padding so generate() can distinguish | |
| # pad from eos. <|endoftext|> (248044) is safe β never in prompts. | |
| pad_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>") | |
| all_predictions = [] | |
| for batch_idx, batch in enumerate(tqdm(dataloader, desc="Generating")): | |
| input_ids = batch["input_ids"] # (B, seq_len) | |
| labels = batch["labels"] # (B, seq_len) | |
| pixel_values = batch["pixel_values"] | |
| image_grid_thw = batch["image_grid_thw"] | |
| B = input_ids.shape[0] | |
| # Find prompt boundary per sample: first position where labels != -100 | |
| prompt_lens = [] | |
| for b in range(B): | |
| target_positions = torch.where(labels[b] != -100)[0] | |
| if len(target_positions) == 0: | |
| prompt_lens.append(0) | |
| else: | |
| prompt_lens.append(target_positions[0].item()) | |
| max_prompt_len = max(prompt_lens) if prompt_lens else 0 | |
| if max_prompt_len == 0: | |
| all_predictions.append([""] * B) | |
| continue | |
| # Left-pad prompts to same length for batched generation | |
| prompt_ids = torch.full((B, max_prompt_len), pad_token_id, dtype=input_ids.dtype) | |
| attn_mask = torch.zeros((B, max_prompt_len), dtype=torch.long) | |
| for b in range(B): | |
| plen = prompt_lens[b] | |
| if plen > 0: | |
| prompt_ids[b, max_prompt_len - plen:] = input_ids[b, :plen] | |
| attn_mask[b, max_prompt_len - plen:] = 1 | |
| prompt_ids = prompt_ids.to(device) | |
| attn_mask = attn_mask.to(device) | |
| if pixel_values is not None: | |
| pixel_values = pixel_values.to(device, dtype=torch.bfloat16) | |
| if image_grid_thw is not None: | |
| image_grid_thw = image_grid_thw.to(device) | |
| # Left-pad mm_token_type_ids to match left-padded prompts | |
| mm_token_type_ids = batch.get("mm_token_type_ids") | |
| prompt_mm_type = None | |
| if mm_token_type_ids is not None: | |
| prompt_mm_type = torch.zeros((B, max_prompt_len), dtype=torch.int) | |
| for b in range(B): | |
| plen = prompt_lens[b] | |
| if plen > 0: | |
| prompt_mm_type[b, max_prompt_len - plen:] = mm_token_type_ids[b, :plen] | |
| prompt_mm_type = prompt_mm_type.to(device) | |
| try: | |
| model.model.rope_deltas = None | |
| outputs = model.generate( | |
| input_ids=prompt_ids, | |
| attention_mask=attn_mask, | |
| pixel_values=pixel_values, | |
| image_grid_thw=image_grid_thw, | |
| mm_token_type_ids=prompt_mm_type, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=False, | |
| pad_token_id=pad_token_id, | |
| eos_token_id=eos_token_id, | |
| ) | |
| # Decode generated tokens (after prompt) per sample | |
| batch_preds = [] | |
| for b in range(B): | |
| generated_ids = outputs[b, max_prompt_len:] | |
| pred_text = tokenizer.decode(generated_ids, skip_special_tokens=True) | |
| batch_preds.append(pred_text) | |
| except Exception as e: | |
| logger.warning(f"Generation failed for batch {batch_idx}: {e}") | |
| batch_preds = [""] * B | |
| all_predictions.append(batch_preds) | |
| return all_predictions | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Caching | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def save_cache(predictions, cache_path, mode, batch_size, n_batches): | |
| """Save predictions to cache file.""" | |
| os.makedirs(os.path.dirname(cache_path), exist_ok=True) | |
| torch.save({ | |
| "batch_size": batch_size, | |
| "n_batches": n_batches, | |
| "mode": mode, | |
| "predictions": predictions, | |
| }, cache_path) | |
| logger.info(f"Saved cache to {cache_path}") | |
| def load_cache(cache_path, mode): | |
| """Load predictions from cache file. Returns None if not found or mode mismatch.""" | |
| if not os.path.isfile(cache_path): | |
| return None | |
| data = torch.load(cache_path, map_location="cpu", weights_only=False) | |
| if data.get("mode") != mode: | |
| logger.info(f"Cache mode mismatch ({data.get('mode')} vs {mode}), re-running inference") | |
| return None | |
| logger.info(f"Loaded cache from {cache_path} ({data['n_batches']} batches)") | |
| return data["predictions"] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GT Instance Building | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def build_ordered_gt_instances(gt_instances_data, gt_instance_order): | |
| """Build ordered GT instances from metadata.""" | |
| gt_ordered = [] | |
| if gt_instance_order is not None: | |
| for idx in gt_instance_order: | |
| if idx < len(gt_instances_data): | |
| gt_ordered.append(gt_instances_data[idx]) | |
| else: | |
| gt_ordered = gt_instances_data | |
| return gt_ordered | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # RefCOCO Metrics (pixel-level Hungarian matching) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def compute_refcoco_metrics( | |
| all_predictions: List[List[str]], | |
| dataloader: DataLoader, | |
| coord_range: int, | |
| ) -> dict: | |
| """Compute RefCOCO-style pixel-level metrics using ground_qwen35's functions.""" | |
| agg = { | |
| "iou_sum": 0.0, | |
| "inter_sum": 0.0, | |
| "union_sum": 0.0, | |
| "total": 0, | |
| } | |
| for t in PRECISION_THRESHOLDS: | |
| agg[f"P@{t}_count"] = 0.0 | |
| n_samples = 0 | |
| n_empty_predictions = 0 | |
| n_parse_failures = 0 | |
| for batch_idx, batch in enumerate(dataloader): | |
| if batch_idx >= len(all_predictions): | |
| break | |
| batch_preds = all_predictions[batch_idx] | |
| B = len(batch_preds) | |
| orig_h_list = batch.get("orig_h", [None] * B) | |
| orig_w_list = batch.get("orig_w", [None] * B) | |
| gt_instances_list = batch.get("gt_instances_data", [None] * B) | |
| gt_order_list = batch.get("gt_instance_order", [None] * B) | |
| for b in range(B): | |
| orig_h = orig_h_list[b] if orig_h_list else None | |
| orig_w = orig_w_list[b] if orig_w_list else None | |
| gt_instances_data = gt_instances_list[b] if gt_instances_list else None | |
| gt_order = gt_order_list[b] if gt_order_list else None | |
| if orig_h is None or orig_w is None or gt_instances_data is None: | |
| continue | |
| # Parse prediction | |
| try: | |
| pred_instances = parse_generated_text(batch_preds[b], coord_range) | |
| except Exception as e: | |
| logger.warning(f"Parse failure: {e}") | |
| pred_instances = [] | |
| n_parse_failures += 1 | |
| if not pred_instances: | |
| n_empty_predictions += 1 | |
| # Build ordered GT | |
| gt_ordered = build_ordered_gt_instances(gt_instances_data, gt_order) | |
| if not gt_ordered: | |
| continue | |
| # Build GT masks | |
| gt_masks = [] | |
| for inst in gt_ordered: | |
| polys = inst.get("polygons", []) | |
| if polys: | |
| gt_masks.append(polygons_to_mask(polys, orig_h, orig_w, coord_range)) | |
| else: | |
| gt_masks.append(np.zeros((orig_h, orig_w), dtype=np.uint8)) | |
| # Build pred masks | |
| pred_masks = [] | |
| for inst in pred_instances: | |
| polys = inst.get("polygons", []) | |
| if polys: | |
| pred_masks.append(polygons_to_mask(polys, orig_h, orig_w, coord_range)) | |
| else: | |
| pred_masks.append(np.zeros((orig_h, orig_w), dtype=np.uint8)) | |
| n_gt = len(gt_masks) | |
| n_pred = len(pred_masks) | |
| agg["total"] += n_gt | |
| n_samples += 1 | |
| if n_pred == 0: | |
| # No predictions β all GT get IoU=0 | |
| for gt_m in gt_masks: | |
| agg["union_sum"] += float(gt_m.sum()) | |
| continue | |
| # Compute IoU matrix using ground_qwen35's function | |
| iou_matrix = compute_mask_iou_matrix(gt_masks, pred_masks) | |
| # Hungarian matching | |
| matches, unmatched_gt, _ = hungarian_match_sim(iou_matrix) | |
| for gi, pi in matches: | |
| iou_val = iou_matrix[gi, pi] | |
| agg["iou_sum"] += iou_val | |
| inter = np.logical_and(gt_masks[gi] > 0, pred_masks[pi] > 0).sum() | |
| union = np.logical_or(gt_masks[gi] > 0, pred_masks[pi] > 0).sum() | |
| agg["inter_sum"] += float(inter) | |
| agg["union_sum"] += float(union) | |
| for t in PRECISION_THRESHOLDS: | |
| if iou_val >= t: | |
| agg[f"P@{t}_count"] += 1.0 | |
| # Unmatched GT instances contribute to union only | |
| for gi in unmatched_gt: | |
| agg["union_sum"] += float(gt_masks[gi].sum()) | |
| # Finalize | |
| total = agg["total"] | |
| metrics = {} | |
| metrics["mIoU"] = agg["iou_sum"] / max(total, 1) | |
| metrics["oIoU"] = agg["inter_sum"] / max(agg["union_sum"], 1e-8) | |
| for t in PRECISION_THRESHOLDS: | |
| metrics[f"P@{t}"] = agg[f"P@{t}_count"] / max(total, 1) | |
| metrics["n_samples"] = n_samples | |
| metrics["n_instances"] = total | |
| metrics["n_empty_predictions"] = n_empty_predictions | |
| metrics["n_parse_failures"] = n_parse_failures | |
| return metrics | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Caption Baseline Metrics (3-case, 22 metrics) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def compute_caption_metrics( | |
| all_predictions: List[List[str]], | |
| dataloader: DataLoader, | |
| coord_range: int, | |
| ) -> dict: | |
| """Compute caption baseline metrics using ground_qwen35's compute_caption_metrics_for_image.""" | |
| accum = {} | |
| n_valid = 0 | |
| n_empty_predictions = 0 | |
| n_parse_failures = 0 | |
| for batch_idx, batch in enumerate(dataloader): | |
| if batch_idx >= len(all_predictions): | |
| break | |
| batch_preds = all_predictions[batch_idx] | |
| B = len(batch_preds) | |
| orig_h_list = batch.get("orig_h", [None] * B) | |
| orig_w_list = batch.get("orig_w", [None] * B) | |
| gt_instances_list = batch.get("gt_instances_data", [None] * B) | |
| gt_order_list = batch.get("gt_instance_order", [None] * B) | |
| for b in range(B): | |
| orig_h = orig_h_list[b] if orig_h_list else None | |
| orig_w = orig_w_list[b] if orig_w_list else None | |
| gt_instances_data = gt_instances_list[b] if gt_instances_list else None | |
| gt_order = gt_order_list[b] if gt_order_list else None | |
| if orig_h is None or orig_w is None or gt_instances_data is None: | |
| continue | |
| # Parse prediction | |
| try: | |
| pred_instances = parse_generated_text(batch_preds[b], coord_range) | |
| except Exception as e: | |
| logger.warning(f"Parse failure: {e}") | |
| pred_instances = [] | |
| n_parse_failures += 1 | |
| if not pred_instances: | |
| n_empty_predictions += 1 | |
| # Build ordered GT | |
| gt_ordered = build_ordered_gt_instances(gt_instances_data, gt_order) | |
| if not gt_ordered: | |
| continue | |
| # Build GT masks and spans | |
| gt_masks = [] | |
| gt_char_spans = [] | |
| for inst in gt_ordered: | |
| polys = inst.get("polygons", []) | |
| if polys: | |
| gt_masks.append(polygons_to_mask(polys, orig_h, orig_w, coord_range)) | |
| else: | |
| gt_masks.append(np.zeros((orig_h, orig_w), dtype=np.uint8)) | |
| gt_char_spans.append(inst.get("char_spans", [])) | |
| # Build pred masks and spans | |
| pred_masks = [] | |
| pred_char_spans = [] | |
| for inst in pred_instances: | |
| polys = inst.get("polygons", []) | |
| if polys: | |
| pred_masks.append(polygons_to_mask(polys, orig_h, orig_w, coord_range)) | |
| else: | |
| pred_masks.append(np.zeros((orig_h, orig_w), dtype=np.uint8)) | |
| pred_char_spans.append(inst.get("char_spans", [])) | |
| if not gt_masks: | |
| continue | |
| # Use ground_qwen35's metric function | |
| try: | |
| image_metrics = compute_caption_metrics_for_image( | |
| gt_char_spans, pred_char_spans, gt_masks, pred_masks, | |
| ) | |
| for k, v in image_metrics.items(): | |
| accum[k] = accum.get(k, 0.0) + v | |
| n_valid += 1 | |
| except Exception as e: | |
| logger.warning(f"Metric computation error: {e}") | |
| continue | |
| # Average across valid samples | |
| if n_valid == 0: | |
| metrics = {} | |
| else: | |
| metrics = {k: v / n_valid for k, v in accum.items()} | |
| metrics["n_samples"] = n_valid | |
| metrics["n_empty_predictions"] = n_empty_predictions | |
| metrics["n_parse_failures"] = n_parse_failures | |
| return metrics | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Main Evaluation Loop | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def evaluate_dataset( | |
| ds_name: str, | |
| model, | |
| tokenizer, | |
| processor, | |
| config: FTQwen35Config, | |
| device: torch.device, | |
| mode: str, | |
| batch_size: int, | |
| num_workers: int, | |
| max_new_tokens: int, | |
| seed: int, | |
| cache_dir: Optional[str], | |
| force_recompute: bool, | |
| max_samples: int = 0, | |
| ) -> dict: | |
| """Run evaluation on a single dataset. Returns metrics dict.""" | |
| is_refcoco = ds_name in REFCOCO_EVAL_DATASETS | |
| is_hungarian = ds_name in HUNGARIAN_EVAL_DATASETS | |
| is_caption = ds_name in CAPTION_BASELINE_EVAL_DATASETS | |
| logger.info(f"=== Evaluating {ds_name} (mode={mode}) ===") | |
| # Build dataset + dataloader | |
| # Override max_seq_len to disable truncation during eval | |
| orig_max_seq_len = config.max_seq_len | |
| config.max_seq_len = 0 | |
| preprocessor = FTExamplePreprocessor(processor, config) | |
| collator = FTCollator(pad_token_id=tokenizer.pad_token_id) | |
| dataset = EvalFTDataset(ds_name, preprocessor, split="val", seed=seed) | |
| # Truncate dataset if max_samples is set | |
| if max_samples > 0 and max_samples < len(dataset): | |
| dataset.dataset.dataset.data = dataset.dataset.dataset.data[:max_samples] | |
| logger.info(f"Truncated dataset to {max_samples} samples") | |
| dataloader = DataLoader( | |
| dataset, | |
| batch_size=batch_size, | |
| shuffle=False, | |
| drop_last=False, | |
| num_workers=num_workers, | |
| collate_fn=collator, | |
| pin_memory=False, | |
| ) | |
| # Restore config | |
| config.max_seq_len = orig_max_seq_len | |
| logger.info(f"Dataset size: {len(dataset)}, Batches: {len(dataloader)}") | |
| # Check cache | |
| all_predictions = None | |
| cache_path = None | |
| if cache_dir is not None: | |
| cache_path = os.path.join(cache_dir, f"{ds_name}_{mode}_cache.pt") | |
| if not force_recompute: | |
| all_predictions = load_cache(cache_path, mode) | |
| # Run inference if not cached | |
| if all_predictions is None: | |
| t0 = time.time() | |
| all_predictions = run_generation_inference( | |
| model, tokenizer, dataloader, device, max_new_tokens | |
| ) | |
| elapsed = time.time() - t0 | |
| logger.info(f"Inference took {elapsed:.1f}s for {ds_name}") | |
| # Save cache | |
| if cache_path is not None: | |
| save_cache(all_predictions, cache_path, mode, batch_size, len(dataloader)) | |
| # Compute metrics | |
| logger.info(f"Computing metrics for {ds_name}...") | |
| if is_refcoco or is_hungarian: | |
| metrics = compute_refcoco_metrics(all_predictions, dataloader, config.coord_range) | |
| elif is_caption: | |
| metrics = compute_caption_metrics(all_predictions, dataloader, config.coord_range) | |
| else: | |
| logger.warning(f"Unknown dataset type: {ds_name}, using RefCOCO-style metrics") | |
| metrics = compute_refcoco_metrics(all_predictions, dataloader, config.coord_range) | |
| metrics["_mode"] = mode | |
| metrics["_dataset"] = ds_name | |
| metrics["_dataset_size"] = len(dataset) | |
| return metrics | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Evaluate FT Qwen3.5 autoregressive baseline") | |
| parser.add_argument("checkpoint", type=str, help="Path to checkpoint directory") | |
| parser.add_argument("--output_dir", type=str, default="./eval_results", | |
| help="Output directory for metrics JSON files") | |
| parser.add_argument("--cache_dir", type=str, default="./eval_cache", | |
| help="Cache directory for predictions") | |
| parser.add_argument("--batch_size", type=int, default=4) | |
| parser.add_argument("--num_workers", type=int, default=4) | |
| parser.add_argument("--datasets", nargs="+", | |
| default=REFCOCO_EVAL_DATASETS + HUNGARIAN_EVAL_DATASETS + CAPTION_BASELINE_EVAL_DATASETS, | |
| help="Datasets to evaluate") | |
| parser.add_argument("--mode", type=str, default="generate", | |
| choices=["generate"], | |
| help="Inference mode") | |
| parser.add_argument("--max_new_tokens", type=int, default=10240, | |
| help="Max tokens to generate (generate mode only)") | |
| parser.add_argument("--force_recompute", action="store_true", | |
| help="Force re-running inference even if cache exists") | |
| parser.add_argument("--max_samples", type=int, default=0, | |
| help="Max samples per dataset (0 = full dataset)") | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args() | |
| # Device | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| logger.info(f"Using device: {device}") | |
| # Load model | |
| model, tokenizer, processor, config = load_model(args.checkpoint, device) | |
| # Evaluate each dataset | |
| all_results = {} | |
| for ds_name in args.datasets: | |
| try: | |
| metrics = evaluate_dataset( | |
| ds_name=ds_name, | |
| model=model, | |
| tokenizer=tokenizer, | |
| processor=processor, | |
| config=config, | |
| device=device, | |
| mode=args.mode, | |
| batch_size=args.batch_size, | |
| num_workers=args.num_workers, | |
| max_new_tokens=args.max_new_tokens, | |
| seed=args.seed, | |
| cache_dir=args.cache_dir, | |
| force_recompute=args.force_recompute, | |
| max_samples=args.max_samples, | |
| ) | |
| all_results[ds_name] = metrics | |
| # Print summary | |
| logger.info(f"\n--- {ds_name} ---") | |
| for k, v in sorted(metrics.items()): | |
| if not k.startswith("_"): | |
| if isinstance(v, float): | |
| logger.info(f" {k}: {v:.4f}") | |
| else: | |
| logger.info(f" {k}: {v}") | |
| # Save per-dataset JSON | |
| out_dir = os.path.join(args.output_dir, ds_name) | |
| os.makedirs(out_dir, exist_ok=True) | |
| out_path = os.path.join(out_dir, "metrics.json") | |
| with open(out_path, "w") as f: | |
| json.dump(metrics, f, indent=2, default=str) | |
| logger.info(f"Saved metrics to {out_path}") | |
| except Exception as e: | |
| logger.error(f"Failed to evaluate {ds_name}: {e}", exc_info=True) | |
| continue | |
| # Print final summary | |
| logger.info("\n" + "=" * 60) | |
| logger.info("FINAL SUMMARY") | |
| logger.info("=" * 60) | |
| for ds_name, metrics in all_results.items(): | |
| is_refcoco = ds_name in REFCOCO_EVAL_DATASETS or ds_name in HUNGARIAN_EVAL_DATASETS | |
| if is_refcoco: | |
| logger.info(f" {ds_name}: mIoU={metrics.get('mIoU', 0):.4f} " | |
| f"oIoU={metrics.get('oIoU', 0):.4f} " | |
| f"P@0.5={metrics.get('P@0.5', 0):.4f} " | |
| f"P@0.7={metrics.get('P@0.7', 0):.4f} " | |
| f"P@0.9={metrics.get('P@0.9', 0):.4f}") | |
| else: | |
| logger.info(f" {ds_name}: " | |
| f"MaskF1@0.5={metrics.get('MaskF1@0.5', 0):.4f} " | |
| f"TextF1@0.5={metrics.get('TextF1@0.5', 0):.4f} " | |
| f"JointF1@0.5={metrics.get('JointF1@0.5', 0):.4f} " | |
| f"mMaskIoU={metrics.get('mMaskIoU', 0):.4f}") | |
| if __name__ == "__main__": | |
| main() | |