Visualize cross attention: `stage_id`th downsampling block, mean over all timesteps starting from step start, `block_id`th Transformer block, second item (conditioned), mean over heads, show each token cross_attention_probs_tensors: One of `cross_attention_probs_down_tensors`, `cross_at
(
token_map,
cross_attention_probs_tensors,
stage_id,
block_id,
visualize_step_start=10,
input_ca_has_condition_only=False,
)
| 113 | |
| 114 | # This function has not been adapted to new `saved_attn`. |
| 115 | def visualize_attn( |
| 116 | token_map, |
| 117 | cross_attention_probs_tensors, |
| 118 | stage_id, |
| 119 | block_id, |
| 120 | visualize_step_start=10, |
| 121 | input_ca_has_condition_only=False, |
| 122 | ): |
| 123 | """ |
| 124 | Visualize cross attention: `stage_id`th downsampling block, mean over all timesteps starting from step start, `block_id`th Transformer block, second item (conditioned), mean over heads, show each token |
| 125 | cross_attention_probs_tensors: |
| 126 | One of `cross_attention_probs_down_tensors`, `cross_attention_probs_mid_tensors`, and `cross_attention_probs_up_tensors` |
| 127 | stage_id: index of downsampling/mid/upsaming block |
| 128 | block_id: index of the transformer block |
| 129 | """ |
| 130 | |
| 131 | plt.figure(figsize=(20, 8)) |
| 132 | |
| 133 | for token_id in range(len(token_map)): |
| 134 | token = token_map[token_id] |
| 135 | plt.subplot(1, len(token_map), token_id + 1) |
| 136 | plt.title(token) |
| 137 | attn = cross_attention_probs_tensors[stage_id][visualize_step_start:].mean( |
| 138 | dim=0 |
| 139 | )[block_id] |
| 140 | |
| 141 | if not input_ca_has_condition_only: |
| 142 | assert ( |
| 143 | attn.shape[0] == 2 |
| 144 | ), f"Expect to have 2 items (uncond and cond), but found {attn.shape[0]} items" |
| 145 | attn = attn[1] |
| 146 | else: |
| 147 | assert ( |
| 148 | attn.shape[0] == 1 |
| 149 | ), f"Expect to have 1 item (cond only), but found {attn.shape[0]} items" |
| 150 | attn = attn[0] |
| 151 | |
| 152 | attn = attn.mean(dim=0)[:, token_id] |
| 153 | H = W = int(math.sqrt(attn.shape[0])) |
| 154 | attn = attn.reshape((H, W)) |
| 155 | plt.imshow(attn.cpu().numpy()) |
| 156 | |
| 157 | plt.show() |
| 158 | |
| 159 | |
| 160 | # This function has not been adapted to new `saved_attn`. |
nothing calls this directly
no outgoing calls
no test coverage detected