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
File size: 31,144 Bytes
ce88b75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | """
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
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@torch.no_grad()
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()
|