#!/usr/bin/env python3 import argparse import os from pathlib import Path import numpy as np import torch def _to_numpy(value): if torch.is_tensor(value): return value.detach().cpu().numpy() return np.asarray(value) def _load_matplotlib(): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt return plt def save_heatmap(path, data, title, cmap="viridis"): plt = _load_matplotlib() fig, ax = plt.subplots(figsize=(8, 4.8), dpi=160) im = ax.imshow(data, cmap=cmap, origin="upper") ax.set_title(title) ax.set_xlabel("token x") ax.set_ylabel("token y") fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) fig.tight_layout() fig.savefig(path) plt.close(fig) def save_flow(path, displacement_yx, margin, stride): plt = _load_matplotlib() h, w, _ = displacement_yx.shape yy, xx = np.mgrid[0:h, 0:w] sample = (slice(None, None, stride), slice(None, None, stride)) dx = displacement_yx[..., 1][sample] dy = displacement_yx[..., 0][sample] confidence = margin[sample] fig, ax = plt.subplots(figsize=(9, 5.4), dpi=160) ax.imshow(margin, cmap="Greys", origin="upper", alpha=0.35) quiver = ax.quiver( xx[sample], yy[sample], dx, dy, confidence, angles="xy", scale_units="xy", scale=1, cmap="magma", width=0.0035, ) ax.set_xlim(-0.5, w - 0.5) ax.set_ylim(h - 0.5, -0.5) ax.set_title(f"current token -> previous short token, stride={stride}") ax.set_xlabel("token x") ax.set_ylabel("token y") fig.colorbar(quiver, ax=ax, fraction=0.046, pad=0.04, label="top1 - top2 score") fig.tight_layout() fig.savefig(path) plt.close(fig) def visualize(input_path, output_dir, stride): artifact = torch.load(input_path, map_location="cpu") output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) displacement_yx = _to_numpy(artifact["displacement_yx"]) margin = _to_numpy(artifact["margin"]) magnitude = np.linalg.norm(displacement_yx.astype(np.float32), axis=-1) top1_score = _to_numpy(artifact["top1_score"]) stem = Path(input_path).stem save_flow(output_dir / f"{stem}_flow_quiver.png", displacement_yx, margin, stride) save_heatmap(output_dir / f"{stem}_displacement_heatmap.png", magnitude, "token displacement magnitude") save_heatmap(output_dir / f"{stem}_confidence_heatmap.png", margin, "confidence: top1 - top2 score") save_heatmap(output_dir / f"{stem}_top1_score_heatmap.png", top1_score, "top1 raw score") def main(): parser = argparse.ArgumentParser(description="Visualize short-history attention token matches.") parser.add_argument("input", help="Path to a short_attn_*.pt artifact.") parser.add_argument("--output-dir", default=None, help="Directory for PNG outputs. Defaults next to the artifact.") parser.add_argument("--stride", type=int, default=4, help="Token stride for sparse flow arrows.") args = parser.parse_args() output_dir = args.output_dir or os.path.dirname(os.path.abspath(args.input)) visualize(args.input, output_dir, args.stride) if __name__ == "__main__": main()