File size: 12,389 Bytes
3404d44 | 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 | """
pca_new.py - Generate single-panel PCA visualizations from existing NPZ files.
Accepts a path argument pointing to either:
- A single model directory (e.g. .../results_short_answer/nvila)
- A parent directory containing multiple model directories (e.g. .../results_short_answer)
Use --3d to extract the rightmost panel from pca_3d/ plots β saves to pca_3d_new/.
Use --2d to extract the rightmost panel from pca/ plots β saves to pca_new/.
Only the "Delta Vectors by Category" panel is produced (previously the rightmost of 3).
'under' has been renamed 'below' throughout.
Usage:
python pca_new.py --3d /data/shared/Qwen/experiments/swap_analysis/results_short_answer
python pca_new.py --3d /data/shared/Qwen/experiments/swap_analysis/results_short_answer/nvila
python pca_new.py --2d /data/shared/Qwen/experiments/swap_analysis/results_short_answer
python pca_new.py --2d /data/shared/Qwen/experiments/swap_analysis/results_short_answer/nvila
"""
import argparse
import os
import re
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from sklearn.decomposition import PCA
# ββ Label / colour config βββββββββββββββββββββββββββββββββββββββββββββββββββββ
CATEGORY_ORDER = ['left', 'right', 'above', 'below', 'far', 'close']
GROUP_ORDER = ['horizontal', 'vertical', 'distance']
CAT_COLORS = {
'above': '#2ca02c', 'below': '#98df8a', # horizontal β green
'left': '#ff7f0e', 'right': '#ffbb78', # vertical β orange (was 'under')
'far': '#9467bd', 'close': '#c5b0d5', # distance β purple
}
GROUP_COLORS = {
'horizontal': '#2ca02c',
'vertical': '#ff7f0e',
'distance': '#9467bd',
}
# ββ Font / marker sizes βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
TITLE_FS = 22 # subplot title
AXIS_FS = 18 # axis labels (PC1 / PC2 / PC3)
TICK_FS = 14 # tick labels
LEGEND_FS = 16 # legend text
SUPTITLE_FS = 24 # figure-level suptitle
SCATTER_S = 30 # marker size
def _normalise_label(raw):
"""Map 'under' β 'below'; everything else passes through unchanged."""
return 'below' if str(raw) == 'under' else str(raw)
def scatter3d(ax, xs, ys, zs, c, label, alpha=0.55, s=SCATTER_S, marker='o'):
ax.scatter(xs, ys, zs, c=c, label=label, alpha=alpha, s=s, marker=marker)
def plot_pca_3d(vectors_npz_path, scale, model_type, save_dir):
"""Generate single-panel 3D PCA figure (Delta Vectors by Category) per layer."""
data = np.load(vectors_npz_path, allow_pickle=True)
layer_keys = [k for k in data.files if k.startswith('orig_L')]
layers = sorted([int(k.replace('orig_L', '')) for k in layer_keys])
if not layers:
print(f" [skip] No orig_L* keys found in {vectors_npz_path}")
return
os.makedirs(save_dir, exist_ok=True)
for layer in layers:
deltas = data.get(f'delta_L{layer}')
cats = data.get(f'categories_L{layer}')
has_delta = (deltas is not None and len(deltas) >= 3)
if not has_delta:
print(f" [skip] Layer {layer}: no delta vectors")
continue
# ββ PCA on delta vectors ββββββββββββββββββββββββββββββββββββββββββββββ
pca_d = PCA(n_components=3)
delta_proj = pca_d.fit_transform(deltas)
ev = pca_d.explained_variance_ratio_
# ββ Figure ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fig = plt.figure(figsize=(13, 10))
ax = fig.add_subplot(111, projection='3d')
if cats is not None:
for cat in CATEGORY_ORDER:
# support both 'under' (legacy) and 'below' in stored labels
mask = np.array([_normalise_label(c) == cat for c in cats])
if not mask.any():
continue
scatter3d(ax,
delta_proj[mask, 0],
delta_proj[mask, 1],
delta_proj[mask, 2],
c=CAT_COLORS.get(cat, 'gray'),
label=cat)
ax.set_title('Delta Vectors by Category', fontsize=TITLE_FS, pad=12)
ax.set_xlabel(f'PC1 ({ev[0]:.1%})', fontsize=AXIS_FS, labelpad=25)
ax.set_ylabel(f'PC2 ({ev[1]:.1%})', fontsize=AXIS_FS, labelpad=25)
# set_zlabel is unreliable in 3D β use fig.text for guaranteed visibility
ax.set_zlabel('')
ax.tick_params(axis='both', labelsize=TICK_FS)
ax.legend(fontsize=LEGEND_FS, ncol=2, loc='upper right')
# ax.legend(fontsize=LEGEND_FS, ncol=1, loc='upper left',
# bbox_to_anchor=(1.02, 1.0), borderaxespad=0)
# ββ Draw everything so we can read accurate bbox positions ββββββββββββ
fig.canvas.draw()
ax_pos = ax.get_position() # Bbox in figure-fraction coords
# PC3 label: place with a bit of gap (0.04) from the axes right edge
pc3_x = ax_pos.x1 + 0.04
fig.text(
pc3_x,
(ax_pos.y0 + ax_pos.y1) / 2,
f'PC3 ({ev[2]:.1%})',
fontsize=AXIS_FS,
va='center', ha='center',
rotation=90,
)
# Centre both titles over the axes area (not the full figure width)
ax_cx = (ax_pos.x0 + ax_pos.x1) / 2
fig.suptitle(
f'{model_type.upper()} ({scale}) β L{layer}',
fontsize=SUPTITLE_FS, fontweight='bold',
x=ax_cx, y=1.01,
)
# Re-centre the axes title (set_title is relative to axes, already centred;
# but the axes itself may be off-centre in the figure, so suptitle fix is enough)
out_path = os.path.join(save_dir, f'pca_{scale}_L{layer}.png')
plt.savefig(out_path, dpi=200, bbox_inches='tight', pad_inches=0.5)
plt.close()
print(f" Saved {out_path}")
def plot_pca_2d(vectors_npz_path, scale, model_type, save_dir):
"""Generate single-panel 2D PCA figure (Delta Vectors by Category) per layer."""
data = np.load(vectors_npz_path, allow_pickle=True)
layer_keys = [k for k in data.files if k.startswith('orig_L')]
layers = sorted([int(k.replace('orig_L', '')) for k in layer_keys])
if not layers:
print(f" [skip] No orig_L* keys found in {vectors_npz_path}")
return
os.makedirs(save_dir, exist_ok=True)
for layer in layers:
deltas = data.get(f'delta_L{layer}')
cats = data.get(f'categories_L{layer}')
has_delta = (deltas is not None and len(deltas) >= 2)
if not has_delta:
print(f" [skip] Layer {layer}: no delta vectors")
continue
# ββ PCA on delta vectors ββββββββββββββββββββββββββββββββββββββββββββββ
pca_d = PCA(n_components=2)
delta_proj = pca_d.fit_transform(deltas)
ev = pca_d.explained_variance_ratio_
# ββ Figure ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fig, ax = plt.subplots(figsize=(10, 8))
if cats is not None:
for cat in CATEGORY_ORDER:
mask = np.array([_normalise_label(c) == cat for c in cats])
if not mask.any():
continue
ax.scatter(delta_proj[mask, 0], delta_proj[mask, 1],
c=CAT_COLORS.get(cat, 'gray'),
label=cat, alpha=0.55, s=SCATTER_S)
ax.set_title('Delta Vectors by Category', fontsize=TITLE_FS, pad=12)
ax.set_xlabel(f'PC1 ({ev[0]:.1%})', fontsize=AXIS_FS)
ax.set_ylabel(f'PC2 ({ev[1]:.1%})', fontsize=AXIS_FS)
ax.tick_params(axis='both', labelsize=TICK_FS)
ax.legend(fontsize=LEGEND_FS, ncol=2, loc='upper right')
ax.grid(True, alpha=0.2)
fig.suptitle(
f'{model_type.upper()} ({scale}) β L{layer}',
fontsize=SUPTITLE_FS, fontweight='bold',
)
plt.tight_layout()
out_path = os.path.join(save_dir, f'pca_{scale}_L{layer}.png')
plt.savefig(out_path, dpi=200, bbox_inches='tight', pad_inches=0.3)
plt.close()
print(f" Saved {out_path}")
def scale_from_npz_name(name):
"""'vectors_80k.npz' -> '80k'"""
m = re.match(r'vectors_(.+)\.npz$', name)
return m.group(1) if m else None
def is_model_dir(path):
"""Return True if path looks like a single model directory (has npz/ sub-dir)."""
return os.path.isdir(os.path.join(path, 'npz'))
def process_model(model_dir, mode):
"""Process all scales for a single model directory.
mode: '3d' β pca_3d/ β pca_3d_new/ (3D single-panel)
'2d' β pca/ β pca_new/ (2D single-panel)
"""
model = os.path.basename(model_dir)
npz_dir = os.path.join(model_dir, 'npz')
plots_dir = os.path.join(model_dir, 'plots')
if not os.path.isdir(npz_dir):
print(f"[{model}] no npz/ dir, skipping")
return
if not os.path.isdir(plots_dir):
print(f"[{model}] no plots/ dir, skipping")
return
npz_files = sorted(
f for f in os.listdir(npz_dir)
if f.startswith('vectors_') and f.endswith('.npz')
)
if not npz_files:
print(f"[{model}] no vectors_*.npz files, skipping")
return
if mode == '3d':
ref_dir_name = 'pca_3d'
new_dir_name = 'pca_3d_new'
plot_fn = plot_pca_3d
else:
ref_dir_name = 'pca'
new_dir_name = 'pca_new'
plot_fn = plot_pca_2d
# Locate ref dirs to mirror structure into new sibling dir
ref_dirs = []
for dirpath, dirnames, _ in os.walk(plots_dir):
if os.path.basename(dirpath) == ref_dir_name:
ref_dirs.append(dirpath)
if not ref_dirs:
print(f"[{model}] no {ref_dir_name}/ dirs found under plots/, skipping")
return
for npz_file in npz_files:
scale = scale_from_npz_name(npz_file)
if scale is None:
continue
npz_path = os.path.join(npz_dir, npz_file)
for ref_dir in ref_dirs:
parent = os.path.dirname(ref_dir) # e.g. plots/all
out_dir = os.path.join(parent, new_dir_name)
print(f"[{model}] scale={scale} -> {out_dir}")
plot_fn(npz_path, scale, model, out_dir)
def main():
parser = argparse.ArgumentParser(
description='Generate single-panel PCA plots (rightmost panel) from existing NPZ files.')
parser.add_argument('path', help='Model directory or parent directory containing model dirs')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--3d', dest='mode', action='store_const', const='3d',
help='Extract from pca_3d/ β pca_3d_new/ (3D Delta Vectors by Category)')
group.add_argument('--2d', dest='mode', action='store_const', const='2d',
help='Extract from pca/ β pca_new/ (2D Delta Vectors by Category)')
args = parser.parse_args()
root = args.path.rstrip('/')
mode = args.mode
if not os.path.isdir(root):
print(f"Error: '{root}' is not a directory.")
raise SystemExit(1)
if is_model_dir(root):
# Single model directory supplied
process_model(root, mode)
else:
# Parent directory: iterate over sub-directories
processed = 0
for name in sorted(os.listdir(root)):
sub = os.path.join(root, name)
if os.path.isdir(sub) and is_model_dir(sub):
process_model(sub, mode)
processed += 1
if processed == 0:
print(f"No model directories (with npz/ sub-dir) found under '{root}'.")
if __name__ == '__main__':
main() |