# AttentionViz: A Global View of Transformer Attention

AttentionViz: 트랜스포머 어텐션의 전역적 관점

Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg · arXiv · 2023년 5월 4일

- **연구 문제** Transformer 어텐션을 한 입력씩이 아니라 여러 입력과 여러 헤드에 걸쳐 전역적으로 살펴보기 어렵습니다.
- **연구 방법** 각 어텐션 헤드의 query와 key 벡터를 t-SNE, UMAP, PCA로 함께 투영하고, 어텐션 값을 바꾸지 않는 Key Translation과 Scaling으로 거리와 내적의 관계를 맞춥니다.
- **주요 결과** Wiki-Auto에서 BERT의 거리-내적 평균 상관은 -0.938, GPT는 -0.792였고 COCO에서 ViT-32와 ViT-16은 각각 -0.873, -0.884였습니다. GPT-2에서는 query와 key norm의 큰 차이가 관찰되었습니다.

## 기존 어텐션 시각화의 한계

Transformer는 NLP와 컴퓨터 비전 전반에 쓰이지만, 내부 동작은 여전히 잘 알려지지 않았습니다. 특히 self-attention은 시퀀스 원소 사이의 관계를 학습하는 핵심 메커니즘인데, 기존 시각화 기법은 대개 한 번에 하나의 입력 시퀀스(한 문장 또는 한 이미지)의 어텐션 가중치만 보여 줍니다. 이분 그래프나 히트맵이 대표적이며, 여러 입력에 걸친 공통 패턴을 찾으려면 분석자가 입력을 하나씩 바꿔 확인해야 합니다.

AttentionViz는 이 문제를 여러 입력 시퀀스와 여러 어텐션 헤드의 패턴을 한 번에 살펴보는 전역적 관점으로 다룹니다. 이 논문의 주된 기술적 변경은 각 어텐션 헤드의 query 벡터와 key 벡터를 함께 저차원 공간에 투영하는 공동 임베딩을 만드는 데 있습니다.

![Figure 1: AttentionViz, our interactive visualization tool, allows users to explore transformer self-attention at scale by creating a joint embedding space for…](https://refivu.com/papers/070e8eaa-a548-44ca-8077-3ab478512ec5/figures/figure-7e44e07bdaddc0ffd69062b6ac4b29be.png?thumb=512)

**Fig. 1** : AttentionViz, our interactive visualization tool, allows users to explore transformer self-attention at scale by creating a joint embedding space for queries and keys. (a) In language transformers, these visualizations reveal striking visual traces that can be linked to attention patterns. Each point in the scatterplot represents the query or key version of a word, as denoted by point color. Users can explore individual attention heads (left) or zoom out for a “global” view of attention (right). (b) Our visualizations also divulge interesting insights in vision transformers, such as attention heads that group image patches by hue and brightness. Border color denotes query embeddings of a patch (green) or key embeddings (pink). (c) Sample input sentences (from \[23\]) and (d) images (synthetic dataset) are provided for reference.

[원문](https://arxiv.org/abs/2305.03210v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg · AttentionViz: A Global View of Transformer Attention · 원문 그림 인용 · 원본 PDF 1쪽에서 그림 영역을 추출했습니다.

## Query-key 공동 임베딩의 구성

이 방법은 어텐션 헤드마다 query 벡터와 key 벡터를 만든 뒤, 두 벡터를 같은 저차원 공간에 투영합니다. 어텐션 값은 query와 key의 내적에 의해 결정되므로, 투영된 산점도에서 두 점이 가까울수록 높은 어텐션이 나타날 것이라는 가정을 시각화의 근거로 삼습니다.

![Figure 2: Creating a joint query-key embedding space for a single atten- tion head. In the NLP case, given an input sentence, we first transform each token int…](https://refivu.com/papers/070e8eaa-a548-44ca-8077-3ab478512ec5/figures/figure-6d80d61a465c4de8f2818de91c8c5f02.png?thumb=512)

**Fig. 2** : Creating a joint query-key embedding space for a single atten- tion head. In the NLP case, given an input sentence, we first transform each token into its corresponding query and key vector. Then, we use t- SNE/UMAP/PCA to project these 1 × d vectors into 2D/3D scatterplot coordinates. For the BERT, GPT-2, and ViT models used,d = 64.

[원문](https://arxiv.org/abs/2305.03210v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg · AttentionViz: A Global View of Transformer Attention · 원문 그림 인용 · 원본 PDF 3쪽에서 그림 영역을 추출했습니다.

원문은 투영 방법으로 t-SNE, UMAP, PCA 세 가지를 제시하며, 각 점은 하나의 query 또는 key 토큰(ViT에서는 이미지 패치)을 나타냅니다. 차원 축소 전에 두 가지 정규화를 적용합니다. 첫째, Key Translation은 softmax의 translation invariance를 이용해 모든 key 벡터를 같은 벡터만큼 이동시켜 query와 key의 중심을 맞춥니다. 어텐션 값은 바뀌지 않습니다. 둘째, Scaling은 query 벡터에는 c, key 벡터에는 c^-1을 곱하며 c는 가중 상관을 최대화하도록 고릅니다. 이 배율 조정도 어텐션 값을 유지하지만, 저자들은 코사인 거리가 단독으로는 변하지 않고 Key Translation과 함께 적용될 때 영향이 생긴다고 밝힙니다.

![Figure 3: Left: original queries and keys in joint embedding space.Right: Increased overlap after translating keys to align query and key centroids](https://refivu.com/papers/070e8eaa-a548-44ca-8077-3ab478512ec5/figures/figure-aebc07fe11124e5e0a123dcfb630bee4.png?thumb=512)

**Fig. 3** : Left: original queries and keys in joint embedding space.Right: Increased overlap after translating keys to align query and key centroids.

[원문](https://arxiv.org/abs/2305.03210v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg · AttentionViz: A Global View of Transformer Attention · 원문 그림 인용 · 원본 PDF 4쪽에서 그림 영역을 추출했습니다.

## 거리와 어텐션의 상관 검증

저자들은 이 시각화가 거리를 어텐션의 대리 지표로 쓸 수 있는지 확인하기 위해, 각 어텐션 헤드마다 코사인 거리와 내적 사이의 Spearman 순위 상관을 계산했습니다. 이상적으로는 내적이 큰 query-key 쌍이 더 가깝게 놓이므로 거리와 내적은 음의 상관을 가져야 합니다.

![Figure 4: (a) Ideal distance-attention relationship, where query-key pairs with higher dot products are closer in the joint embedding space. (b) Example attent…](https://refivu.com/papers/070e8eaa-a548-44ca-8077-3ab478512ec5/figures/figure-085b63aef758768f5b93d95164466b02.png?thumb=512)

**Fig. 4** : (a) Ideal distance-attention relationship, where query-key pairs with higher dot products are closer in the joint embedding space. (b) Example attention head with a strong, negative correlation ( -0.983) between query-key distance and dot product in BERT.

[원문](https://arxiv.org/abs/2305.03210v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg · AttentionViz: A Global View of Transformer Attention · 원문 그림 인용 · 원본 PDF 4쪽에서 그림 영역을 추출했습니다.

Wiki-Auto 데이터에서 평균 상관은 BERT에서 -0.938, GPT에서 -0.792였습니다. COCO 이미지에서는 ViT-32에서 -0.873, ViT-16에서 -0.884였습니다. 이 수치는 해당 데이터셋과 모델에서 계산된 평균이며, 다른 데이터나 모델로 일반화된 결과가 아닙니다. 또한 Euclidean 거리를 사용한 t-SNE와 UMAP 투영은 일반적으로 더 약한 상관을 보였다고 보고되었습니다.

## GPT-2의 norm 불일치 관찰

AttentionViz를 GPT-2에서 살펴보았을 때, 초기 층의 많은 헤드에서 query와 key 군집이 key translation 이후에도 잘 분리되어 보였습니다. 저자들은 이 현상을 query norm과 key norm의 큰 차이로 분석했습니다. 정규화 단계 이전의 norm으로 측정하면, GPT-2에서 평균 query norm - key norm은 -4.59이었고 BERT에서 평균 차이는 0.41이었습니다.

![Figure 12: Anomalies in GPT-2. (a) In early model layers, we witness a significant disparity between query-key norms for many attention heads (e.g., L1 H8 prio…](https://refivu.com/papers/070e8eaa-a548-44ca-8077-3ab478512ec5/figures/figure-36e5068baef6727a4814a43417f915ec.png?thumb=512)

**Fig. 12** : Anomalies in GPT-2. (a) In early model layers, we witness a significant disparity between query-key norms for many attention heads (e.g., L1 H8 prior to norm scaling). (b) Example of the prevalent “attend to first” pattern in later layers. Sentence View reveals latent attention behavior after hiding the first token.

[원문](https://arxiv.org/abs/2305.03210v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg · AttentionViz: A Global View of Transformer Attention · 원문 그림 인용 · 원본 PDF 8쪽에서 그림 영역을 추출했습니다.

이 관찰은 GPT-2의 헤드들에서 query와 key의 크기가 크게 다르다는 사실을 보여 줍니다. 원문은 이 현상을 설명하는 가설을 제시하지 않으며, 본 연구의 Scaling 정규화가 이 관찰에서 영감을 받았다고 밝힙니다.

## 적용 범위와 남은 제약

AttentionViz는 큰 데이터의 사전 계산 시간과 메모리 요구량 때문에 현재 제약을 받습니다. 원문은 충분히 큰 무작위 샘플이 전역 현상을 드러내기에 충분하다고 보고하지만, 더 큰 데이터와 모델에서 추가적인 의미 정보가 드러날 가능성도 함께 언급합니다.

또한 t-SNE와 UMAP 투영은 왜곡을 일으킬 수 있으므로 시각적 패턴을 실제 개입 실험과 연결해야 한다는 전문가 우려가 있었습니다. 이 점은 시각화가 탐색 도구이며 가설 검증은 별도의 절차가 필요함을 보여 줍니다.

## 논문 정보

- **저자**: Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg
- **학회·저널**: arXiv · 프리프린트
- **최초 공개일**: 2023년 5월 4일
- **등록일**: 2026년 11월 6일
- **수정일**: 2023년 8월 9일
- **버전**: v2
- **arXiv**: 2305.03210
- **분류**: cs.HC · cs.CL · cs.CV · cs.LG
- **원문 이용 조건**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **제공 범위**: 논문 정보, 해설, 허용된 원문 그림

[논문 원문 ↗](https://arxiv.org/abs/2305.03210v2) · [원문 PDF ↗](https://arxiv.org/pdf/2305.03210v2)

AI 해설은 논문 원문과 별개의 설명이며 오류가 있을 수 있습니다. 원문과 그림은 각 출처의 이용 조건과 따로 표시된 권리를 따릅니다.

## 초록

Transformer models are revolutionizing machine learning, but their inner workings remain mysterious. In this work, we present a new visualization technique designed to help researchers understand the self-attention mechanism in transformers that allows these models to learn rich, contextual relationships between elements of a sequence. The main idea behind our method is to visualize a joint embedding of the query and key vectors used by transformer models to compute attention. Unlike previous attention visualization techniques, our approach enables the analysis of global patterns across multiple input sequences. We create an interactive visualization tool, AttentionViz (demo: http://attentionviz.com), based on these joint query-key embeddings, and use it to study attention mechanisms in both language and vision transformers. We demonstrate the utility of our approach in improving model understanding and offering new insights about query-key interactions through several application scenarios and expert feedback.

## 원문 인용

Catherine Yeh, Yida Chen, Aoyu Wu, Cynthia Chen, Fernanda Viégas, Martin Wattenberg (2023). AttentionViz: A Global View of Transformer Attention. arXiv:2305.03210v2. https://arxiv.org/abs/2305.03210v2

**BibTeX**

```
@misc{yeh2023attentionviz,
  title = {{AttentionViz: A Global View of Transformer Attention}},
  author = {Catherine Yeh and Yida Chen and Aoyu Wu and Cynthia Chen and Fernanda Viégas and Martin Wattenberg},
  year = {2023},
  eprint = {2305.03210},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2305.03210v2}
}
```

## 이 논문의 용어

- [BERT](https://refivu.com/terms/45b639a1d317-bert)
- [COCO](https://refivu.com/terms/41f3215c4f4a-coco)
- [t-SNE](https://refivu.com/terms/488ecf7dbbcf-t-sne)
- [PCA](https://refivu.com/terms/2f4628e32ef5-pca)
- [GPT-2](https://refivu.com/terms/3c130f2029b4-gpt-2)
- [cosine distance](https://refivu.com/terms/e6f2fa77e243-cosine-distance)
- [ViT](https://refivu.com/terms/c041b72c53b8-vit)
- [Spearman rank correlation](https://refivu.com/terms/7c7873bbcf11-spearman-rank-correlation)
- [UMAP](https://refivu.com/terms/aeb869edc5de-umap)
- [self-attention mechanism](https://refivu.com/terms/a86abb2cdf86-self-attention-mechanism)

## 다른 논문 해설

- [An Overview of Backdoor Attacks Against Deep Neural Networks and Possible Defences](https://refivu.com/papers/40fecf2b-a3fb-4971-934f-d8e78a4188a7-an-overview-of-backdoor-attacks-against-deep-neural.md)
- [Investigating the fidelity of explainable artificial intelligence methods for applications of convolutional neural networks in geoscience](https://refivu.com/papers/6fc26172-2105-4bd7-b7b3-31bc6947ab05-investigating-the-fidelity-of-explainable-artificial.md)
- [Handwritten Arabic Character Recognition for Children Writ-ing Using Convolutional Neural Network and Stroke Identification](https://refivu.com/papers/92f857b2-4ffd-4e92-ab59-6f78dfce886d-handwritten-arabic-character-recognition-for-children-writ.md)
- [Optical flow estimation from event-based cameras and spiking neural networks](https://refivu.com/papers/5c10815d-4f31-48d6-9029-4c9015150169-optical-flow-estimation-from-event-based-cameras-and.md)
- [FedTP: Federated Learning by Transformer Personalization](https://refivu.com/papers/fd89ac79-f476-41f1-a530-fe73b0b36237-fedtp-federated-learning-by-transformer-personalization.md)
- [Policies for elementary links in a quantum network](https://refivu.com/papers/d57f8c18-a2ae-4514-9f2f-1e58422e4fd6-policies-for-elementary-links-in-a-quantum-network.md)
- [V3D: Video Diffusion Models are Effective 3D Generators](https://refivu.com/papers/7ac7016e-0685-4edf-a818-3baccf2777ee-v3d-video-diffusion-models-are-effective-3d-generators.md)
- [Fine-grained Visual-Text Prompt-Driven Self-Training for Open-Vocabulary Object Detection](https://refivu.com/papers/0c7a18dd-b942-4cf0-b81d-b217e1d3d405-fine-grained-visual-text-prompt-driven-self-training.md)
- [End-to-end example-based sim-to-real RL policy transfer based on neural stylisation with application to robotic cutting](https://refivu.com/papers/5bae8ece-b412-4f6d-80fc-777e1a09b780-end-to-end-example-based-sim-to-real.md)
- [A Deep Dive into Large Language Models for Automated Bug Localization and Repair](https://refivu.com/papers/ab6d1397-3512-4f4f-a702-f5c1882590b5-a-deep-dive-into-large-language-models-for.md)
- [A Novel Incremental Learning Driven Instance Segmentation Framework to Recognize Highly Cluttered Instances of the Contraband Items](https://refivu.com/papers/5c05a20b-3290-43be-85ab-d7d378250990-a-novel-incremental-learning-driven-instance-segmentation.md)
- [IMITATE: Clinical Prior Guided Hierarchical Vision-Language Pre-training](https://refivu.com/papers/3b5c87ee-36ef-4925-a42d-40e276bdd963-imitate-clinical-prior-guided-hierarchical-vision-language.md)

---

AI 해설에는 오류가 있을 수 있습니다. [Refivu](https://refivu.com/papers/070e8eaa-a548-44ca-8077-3ab478512ec5-attentionviz-a-global-view-of-transformer-attention)
