1 import numpy as np; from _utils.palette_maps import palette_cmap, palette_stops, contrast_text
   2 import matplotlib.pyplot as plt
   3 import matplotlib.gridspec as gridspec
   4 import seaborn as sns
   5 from scipy.cluster.hierarchy import dendrogram, linkage
   6 from scipy.spatial.distance import pdist
   7 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS
   8 setup_style()
   9 
  10 np.random.seed(42)
  11 tokens = ['[CLS]', 'The', 'model', 'learns', 'to', 'attend', 'key', 'features', '[SEP]']
  12 n = len(tokens)
  13 attn = np.random.dirichlet(np.ones(n) * 0.5, size=n)
  14 attn += np.eye(n) * 0.3
  15 attn[0, 5:8] += 0.2
  16 attn[3, 6:8] += 0.15
  17 attn = attn / attn.sum(axis=1, keepdims=True)
  18 
  19 fig = plt.figure(figsize=(8, 7))
  20 gs = gridspec.GridSpec(2, 2, width_ratios=[1, 6], height_ratios=[1, 6],
  21                        wspace=0.02, hspace=0.02)
  22 
  23 # Top dendrogram
  24 ax_dtop = fig.add_subplot(gs[0, 1])
  25 Z_col = linkage(pdist(attn.T), method='ward')
  26 dendrogram(Z_col, ax=ax_dtop, no_labels=True, color_threshold=0,
  27            above_threshold_color=PALETTE[0])
  28 ax_dtop.set_xticks([])
  29 ax_dtop.set_yticks([])
  30 for spine in ax_dtop.spines.values():
  31     spine.set_visible(False)
  32 
  33 # Left dendrogram
  34 ax_dleft = fig.add_subplot(gs[1, 0])
  35 Z_row = linkage(pdist(attn), method='ward')
  36 dendrogram(Z_row, ax=ax_dleft, orientation='left', no_labels=True,
  37            color_threshold=0, above_threshold_color=PALETTE[0])
  38 ax_dleft.set_xticks([])
  39 ax_dleft.set_yticks([])
  40 for spine in ax_dleft.spines.values():
  41     spine.set_visible(False)
  42 
  43 # Main heatmap
  44 ax_heat = fig.add_subplot(gs[1, 1])
  45 im = ax_heat.imshow(attn, cmap=palette_cmap('sequential'), aspect='auto')
  46 ax_heat.set_xticks(range(n))
  47 ax_heat.set_xticklabels(tokens, rotation=45, ha='right', fontsize=8)
  48 ax_heat.set_yticks(range(n))
  49 ax_heat.set_yticklabels(tokens, fontsize=8)
  50 ax_heat.set_xlabel('Key', fontsize=10)
  51 ax_heat.set_ylabel('Query', fontsize=10)
  52 
  53 # Value annotations (only > 0.12)
  54 for i in range(n):
  55     for j in range(n):
  56         if attn[i, j] > 0.12:
  57             ax_heat.text(j, i, f'{attn[i, j]:.2f}', ha='center', va='center',
  58                          fontsize=6.5, color=contrast_text(im.cmap(im.norm(attn[i, j]))))
  59 
  60 # Attention entropy annotation (right side)
  61 entropy = -np.sum(attn * np.log(attn + 1e-10), axis=1)
  62 for i, (tok, h) in enumerate(zip(tokens, entropy)):
  63     ax_heat.text(n + 0.3, i, f'H={h:.2f}', fontsize=6.5, va='center', color=COLORS['ref_line'])
  64 
  65 fig.colorbar(im, ax=ax_heat, shrink=0.6, label='Attention Weight', pad=0.12)
  66 fig.tight_layout()
  67 save_fig(fig, 'figures/fig_attention.pdf')