Download MedEvalKit/visualize_grounding.py from Master-Shi/ExplainableVQA: direct link, hf CLI and curl.
- Browser
- Download file 5.96 kB
-
https://huggingface.co/datasets/Master-Shi/ExplainableVQA/resolve/main/MedEvalKit/visualize_grounding.py
- Command line
-
hf download hf://datasets/Master-Shi/ExplainableVQA/MedEvalKit/visualize_grounding.py
-
curl -L -o visualize_grounding.py https://huggingface.co/datasets/Master-Shi/ExplainableVQA/resolve/main/MedEvalKit/visualize_grounding.py
5.96 kB
| """ | |
| visualize_grounding.py | |
| Visualize layer-wise mean divergence for grounding ablation experiments, | |
| comparing COCO vs VGMED across models and ablation types. | |
| Usage: | |
| python visualize_grounding.py | |
| python visualize_grounding.py --ablation mask_region | |
| python visualize_grounding.py --q_type attribute | |
| python visualize_grounding.py --output_dir my_plots | |
| """ | |
| import argparse | |
| import os | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| GROUNDING_ROOT = "grounding_results" | |
| MODELS = { | |
| "HuatuoGPT-V-7B": "HuatuoGPT-V-7B/HuatuoGPT-Vision-7B", | |
| "LLaVA-7B": "LLaVA-7B/llava-1.5-7b-hf", | |
| "LLaVA-13B": "LLaVA-13B/llava-1.5-13b-hf", | |
| "LLaVA-Med-7B": "LLaVA-Med-7B/llava-med-v1.5-mistral-7b", | |
| "MedGemma-4B-IT": "MedGemma-4B-IT/medgemma-4b-it", | |
| "Qwen2.5VL-3B": "Qwen2.5VL-3B/Qwen2.5-VL-3B-Instruct", | |
| "Qwen2.5VL-7B": "Qwen2.5VL-7B/Qwen2.5-VL-7B-Instruct", | |
| "Qwen3VL-2B": "Qwen3VL-2B/Qwen3-VL-2B-Instruct", | |
| "Qwen3VL-4B": "Qwen3VL-4B/Qwen3-VL-4B-Instruct", | |
| "Qwen3VL-8B": "Qwen3VL-8B/Qwen3-VL-8B-Instruct", | |
| } | |
| ABLATIONS = { | |
| "mask_region": "Mask Key Regions", | |
| "mask_text": "Mask Key Words", | |
| "diff_region": "Mask Key Regions Compared with Mask Random Regions", | |
| "diff_text": "Mask Key Words Compared with Mask Random Words", | |
| } | |
| Q_TYPES = ["localization", "attribute"] | |
| DATASETS = ["COCO", "VGMED"] | |
| # ββ shared style constants (kept in sync with visualize_attention.py) ββββββββββ | |
| # Each model is saved as its own standalone PNG, so every figure must be readable | |
| # on its own at a small size: large fonts, thick lines, high DPI. | |
| COLORS = {"COCO": "#2196F3", "VGMED": "#F44336"} | |
| DIFF_POS = "#F44336" | |
| DIFF_NEG = "#2196F3" | |
| FIG_WIDTH = 8.0 | |
| ROW_HEIGHT = 5.0 | |
| TITLE_FS = 22 | |
| AXIS_FS = 18 | |
| TICK_FS = 16 | |
| LEGEND_FS = 16 | |
| MARKER = "o" | |
| MARKER_SIZE = 9 | |
| LINE_WIDTH = 3.5 | |
| GRID_ALPHA = 0.3 | |
| DPI = 600 | |
| plt.rcParams["font.weight"] = "bold" | |
| plt.rcParams["axes.labelweight"] = "bold" | |
| plt.rcParams["axes.titleweight"] = "bold" | |
| plt.rcParams["axes.linewidth"] = 1.5 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_pt(path): | |
| data = torch.load(path, map_location="cpu", weights_only=False) | |
| if isinstance(data, torch.Tensor): | |
| return data.numpy() | |
| arr = np.stack(data, axis=0) | |
| return arr.mean(axis=0) | |
| def plot_ablation(ablation_key, ablation_label, q_type, output_dir, grounding_root): | |
| """One standalone PNG per model: top = divergence curves, bottom = VGMED-COCO diff bars.""" | |
| for model_name, model_dir in MODELS.items(): | |
| fig, (ax_top, ax_bot) = plt.subplots( | |
| 2, 1, figsize=(FIG_WIDTH, ROW_HEIGHT * 2), | |
| ) | |
| fig.suptitle( | |
| f"{model_name} β {ablation_label} ({q_type})", | |
| fontsize=TITLE_FS, fontweight="bold", | |
| ) | |
| loaded = {} | |
| for ds in DATASETS: | |
| fname = f"{ds}_{q_type}_mean_divergence_per_layer.pt" | |
| fpath = os.path.join(grounding_root, model_dir, ablation_key, fname) | |
| if not os.path.exists(fpath): | |
| print(f"[skip] {fpath}") | |
| continue | |
| loaded[ds] = load_pt(fpath) | |
| # top: curves | |
| for ds, vals in loaded.items(): | |
| layers = np.arange(len(vals)) | |
| ax_top.plot(layers, vals, label=ds, color=COLORS[ds], | |
| linewidth=LINE_WIDTH, marker=MARKER, markersize=MARKER_SIZE) | |
| ax_top.set_ylabel("Mean Divergence", fontsize=AXIS_FS) | |
| ax_top.tick_params(labelsize=TICK_FS) | |
| ax_top.grid(True, alpha=GRID_ALPHA) | |
| if loaded: | |
| ax_top.legend(fontsize=LEGEND_FS) | |
| # bottom: VGMED β COCO diff bars | |
| if "VGMED" in loaded and "COCO" in loaded: | |
| vgmed = loaded["VGMED"] | |
| coco = loaded["COCO"] | |
| n = min(len(vgmed), len(coco)) | |
| diff = vgmed[:n] - coco[:n] | |
| layers = np.arange(n) | |
| ax_bot.bar(layers, diff, | |
| color=[DIFF_POS if d >= 0 else DIFF_NEG for d in diff], | |
| alpha=0.7, width=0.8) | |
| ax_bot.axhline(0, color="black", linewidth=0.8, linestyle="--") | |
| ax_bot.set_xlabel("Layer", fontsize=AXIS_FS) | |
| ax_bot.set_ylabel("VGMED β COCO", fontsize=AXIS_FS) | |
| ax_bot.tick_params(labelsize=TICK_FS) | |
| ax_bot.grid(True, alpha=GRID_ALPHA, axis="y") | |
| else: | |
| ax_bot.set_visible(False) | |
| plt.tight_layout() | |
| q_type_dir = os.path.join(output_dir, q_type, ablation_key) | |
| os.makedirs(q_type_dir, exist_ok=True) | |
| out_path = os.path.join(q_type_dir, f"{model_name}_{ablation_key}_{q_type}.png") | |
| plt.savefig(out_path, dpi=DPI, bbox_inches="tight") | |
| plt.close() | |
| print(f"Saved: {out_path}") | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--ablation", choices=list(ABLATIONS.keys()), default=None, | |
| help="Plot only one ablation type (default: all)") | |
| parser.add_argument("--q_type", choices=Q_TYPES, default=None, | |
| help="Plot only one q_type (default: all)") | |
| parser.add_argument("--grounding_root", default=GROUNDING_ROOT) | |
| parser.add_argument("--output_dir", default="grounding_plots") | |
| args = parser.parse_args() | |
| ablations = {args.ablation: ABLATIONS[args.ablation]} if args.ablation else ABLATIONS | |
| q_types = [args.q_type] if args.q_type else Q_TYPES | |
| for ablation_key, ablation_label in ablations.items(): | |
| for q_type in q_types: | |
| plot_ablation(ablation_key, ablation_label, q_type, | |
| args.output_dir, args.grounding_root) | |
| if __name__ == "__main__": | |
| main() | |