메뉴
HN
Hacker News • 4일 전

트랜스포머, 시각적으로 이해하기

IMP
6/10
핵심 요약

트랜스포머(Transformer)는 2017년 논문 'Attention is All You Need'로 소개된 신경망 구조로, GPT·Llama·Gemini 등 주요 생성형 AI 모델의 기반이 되는 핵심 기술입니다. 이 글은 토크나이징, 임베딩, 셀프 어텐션, MLP 등 트랜스포머의 핵심 구성요소를 GPT-2(small) 모델 예시로 시각적으로 설명합니다.

번역된 본문

트랜스포머란 무엇인가?

트랜스포머(Transformer)는 인공지능 접근 방식을 근본적으로 바꾼 신경망 아키텍처입니다. 2017년 발표된 획기적인 논문 "Attention is All You Need"에서 처음 소개된 이후, 딥러닝 모델의 표준 아키텍처로 자리잡았으며 OpenAI의 GPT, Meta의 Llama, Google의 Gemini 같은 텍스트 생성 모델을 구동하고 있습니다. 텍스트를 넘어 오디오 생성, 이미지 인식, 단백질 구조 예측, 심지어 게임 플레이에도 적용되며 다양한 분야에서 그 다재다능함을 입증하고 있습니다.

근본적으로 텍스트 생성 트랜스포머 모델은 다음 토큰 예측(next-token prediction) 원리로 작동합니다. 사용자가 텍스트 프롬프트를 입력하면, 그 입력 다음에 올 가장 확률이 높은 토큰(단어 또는 단어의 일부)은 무엇인지 예측하는 것입니다. 트랜스포머의 핵심 혁신과 강력함은 셀프 어텐션(self-attention) 메커니즘 사용에 있으며, 이를 통해 전체 시퀀스를 처리하고 이전 아키텍처보다 효과적으로 장거리 의존성을 포착할 수 있습니다.

GPT-2 계열 모델은 텍스트 생성 트랜스포머의 대표적인 예입니다. 'Transformer Explainer'는 1억 2,400만 개 파라미터를 가진 GPT-2 (small) 모델로 구동됩니다. 최신이나 가장 강력한 모델은 아니지만, 현재 최고 수준 모델들과 동일한 아키텍처 구성요소와 원리를 많이 공유하고 있어 기초를 이해하기에 이상적인 출발점입니다.

트랜스포머 아키텍처

모든 텍스트 생성 트랜스포머는 다음 세 가지 핵심 구성요소로 이루어져 있습니다:

임베딩(Embedding): 텍스트 입력은 토큰이라 불리는 더 작은 단위(단어 또는 하위 단어)로 나뉩니다. 이 토큰들은 단어의 의미적 의미를 담은 임베딩이라는 수치 벡터로 변환됩니다.

트랜스포머 블록(Transformer Block): 입력 데이터를 처리하고 변환하는 모델의 기본 빌딩 블록입니다. 각 블록은 다음을 포함합니다:

  • 어텐션 메커니즘(Attention Mechanism): 트랜스포머 블록의 핵심 구성요소로, 토큰이 다른 토큰과 소통하여 문맥 정보와 단어 간 관계를 포착할 수 있게 합니다.
  • MLP(다층 퍼셉트론) 계층: 각 토큰을 독립적으로 처리하는 피드포워드 네트워크입니다. 어텐션 계층의 목표가 토큰 간 정보 전달이라면, MLP의 목표는 각 토큰의 표현을 정제하는 것입니다.

출력 확률(Output Probabilities): 마지막 선형(linear) 및 소프트맥스(softmax) 계층이 처리된 임베딩을 확률로 변환하여, 모델이 시퀀스에서 다음 토큰을 예측할 수 있게 합니다.

임베딩

트랜스포머 모델로 텍스트를 생성한다고 가정해 봅시다. "Data visualization empowers users to"(데이터 시각화는 사용자에게 힘을 실어준다)와 같은 프롬프트를 입력합니다. 이 입력은 모델이 이해하고 처리할 수 있는 형식으로 변환되어야 합니다. 여기서 임베딩이 등장합니다. 임베딩은 텍스트를 모델이 다룰 수 있는 수치 표현으로 변환합니다.

프롬프트를 임베딩으로 변환하려면 다음 단계를 거칩니다: 1) 입력 토크나이징, 2) 토큰 임베딩 획득, 3) 위치 정보 추가, 4) 토큰 인코딩과 위치 인코딩을 합산하여 최종 임베딩 획득.

각 단계가 어떻게 이루어지는지 살펴보겠습니다.

그림 1. 임베딩 계층 뷰를 확장하여 입력 프롬프트가 벡터 표현으로 변환되는 과정을 보여줍니다. 이 과정은 (1) 토크나이징, (2) 토큰 임베딩, (3) 위치 인코딩, (4) 최종 임베딩을 포함합니다.

1단계: 토크나이징

토크나이징은 입력 텍스트를 토큰이라 불리는 더 작고 다루기 쉬운 조각으로 나누는 과정입니다. 이 토큰은 단어 또는 하위 단어일 수 있습니다. "Data"와 "visualization"은 각각 고유한 토큰에 해당하지만, "empowers"는 두 개의 토큰으로 나뉩니다. 토큰의 전체 어휘 집합은 모델 학습 전에 결정되며, GPT-2의 어휘는 50,257개의 고유 토큰로 구성되어 있습니다.

이제 입력 텍스트를 고유 ID를 가진 토큰으로 나누었으니, 임베딩에서 이들의 벡터 표현을 얻을 수 있습니다.

2단계: 토큰 임베딩

GPT-2 (small)는 어휘의 각 토큰을 768차원 벡터로 표현합니다. 벡터의 차원은... (원문 여기서 중단)

원문 보기
원문 보기 (영어)
What is a Transformer? Transformer is a neural network architecture that has fundamentally changed the approach to Artificial Intelligence. Transformer was first introduced in the seminal paper "Attention is All You Need" in 2017 and has since become the go-to architecture for deep learning models, powering text-generative models like OpenAI's GPT , Meta's Llama , and Google's Gemini . Beyond text, Transformer is also applied in audio generation , image recognition , protein structure prediction , and even game playing , demonstrating its versatility across numerous domains. Fundamentally, text-generative Transformer models operate on the principle of next-token prediction : given a text prompt from the user, what is the most probable next token (a word or part of a word) that will follow this input? The core innovation and power of Transformers lie in their use of self-attention mechanism, which allows them to process entire sequences and capture long-range dependencies more effectively than previous architectures. GPT-2 family of models are prominent examples of text-generative Transformers. Transformer Explainer is powered by the GPT-2 (small) model which has 124 million parameters. While it is not the latest or most powerful Transformer model, it shares many of the same architectural components and principles found in the current state-of-the-art models making it an ideal starting point for understanding the basics. Transformer Architecture Every text-generative Transformer consists of these three key components : Embedding : Text input is divided into smaller units called tokens, which can be words or subwords. These tokens are converted into numerical vectors called embeddings, which capture the semantic meaning of words. Transformer Block is the fundamental building block of the model that processes and transforms the input data. Each block includes: Attention Mechanism , the core component of the Transformer block. It allows tokens to communicate with other tokens, capturing contextual information and relationships between words. MLP (Multilayer Perceptron) Layer , a feed-forward network that operates on each token independently. While the goal of the attention layer is to route information between tokens, the goal of the MLP is to refine each token's representation. Output Probabilities : The final linear and softmax layers transform the processed embeddings into probabilities, enabling the model to make predictions about the next token in a sequence. Embedding Let's say you want to generate text using a Transformer model. You add the prompt like this one: “Data visualization empowers users to” . This input needs to be converted into a format that the model can understand and process. That is where embedding comes in: it transforms the text into a numerical representation that the model can work with. To convert a prompt into embedding, we need to 1) tokenize the input, 2) obtain token embeddings, 3) add positional information, and finally 4) add up token and position encodings to get the final embedding. Let’s see how each of these steps is done. Figure 1 . Expanding the Embedding layer view, showing how the input prompt is converted to a vector representation. The process involves (1) Tokenization, (2) Token Embedding, (3) Positional Encoding, and (4) Final Embedding. Step 1: Tokenization Tokenization is the process of breaking down the input text into smaller, more manageable pieces called tokens. These tokens can be a word or a subword. The words "Data" and "visualization" correspond to unique tokens, while the word "empowers" is split into two tokens. The full vocabulary of tokens is decided before training the model: GPT-2's vocabulary has 50,257 unique tokens. Now that we split our input text into tokens with distinct IDs, we can obtain their vector representation from embeddings. Step 2. Token Embedding GPT-2 (small) represents each token in the vocabulary as a 768-dimensional vector; the dimension of the vector depends on the model. These embedding vectors are stored in a matrix of shape (50,257, 768) , containing approximately 39 million parameters! This extensive matrix allows the model to assign semantic meaning to each token, in the sense that tokens with similar usage or meaning in language are placed close together in this high-dimensional space, while dissimilar tokens are farther apart. Step 3. Positional Encoding The Embedding layer also encodes information about each token's position in the input prompt. Different models use various methods for positional encoding. GPT-2 trains its own positional encoding matrix from scratch, integrating it directly into the training process. Step 4. Final Embedding Finally, we sum the token and positional encodings to get the final embedding representation. This combined representation captures both the semantic meaning of the tokens and their position in the input sequence. Transformer Block The core of the Transformer's processing lies in the Transformer block, which comprises multi-head self-attention and a Multi-Layer Perceptron layer. Most models consist of multiple such blocks that are stacked sequentially one after the other. The token representations evolve through layers, from the first block to the last one, allowing the model to build up an intricate understanding of each token. This layered approach leads to higher-order representations of the input. The GPT-2 (small) model we are examining consists of 12 such blocks. Multi-Head Self-Attention The self-attention mechanism enables the model to capture relationships among tokens in a sequence, so that each token’s representation is influenced by the others. Multiple attention heads allow the model to consider these relationships from different perspectives; for example, one head may capture short-range syntactic links while another tracks broader semantic context. In the following section, we will walk through how multi-head self-attention is computed step by step. Step 1: Query, Key, and Value Matrices Q K V i j = ( ∑ d = 1 768 Embedding i , d ⋅ Weights d , j ) + Bias j QKV_{ij} = ( \sum_{d=1}^{768} \text{Embedding}_{i,d} \cdot \text{Weights}_{d,j}) + \text{Bias}_j Q K V ij ​ = ( d = 1 ∑ 768 ​ Embedding i , d ​ ⋅ Weights d , j ​ ) + Bias j ​ Figure 2 . Computing Query, Key, and Value matrices from the original embedding. Each token's embedding vector is transformed into three vectors: Query (Q) , Key (K) , and Value (V) . These vectors are derived by multiplying the input embedding matrix with learned weight matrices for Q , K , and V . Here's a web search analogy to help us build some intuition behind these matrices: Query (Q) is the search text you type in the search engine bar. This is the token you want to "find more information about" . Key (K) is the title of each web page in the search result window. It represents the possible tokens the query can attend to. Value (V) is the actual content of web pages shown. Once we matched the appropriate search term (Query) with the relevant results (Key), we want to get the content (Value) of the most relevant pages. By using these QKV values, the model can calculate attention scores, which determine how much focus each token should receive when generating predictions. Step 2: Multi-Head Splitting Query , key , and Value vectors are split into multiple heads—in GPT-2 (small)'s case, into 12 heads. Each head processes a segment of the embeddings independently, capturing different syntactic and semantic relationships. This design facilitates parallel learning of diverse linguistic features, enhancing the model's representational power. Step 3: Masked Self-Attention In each head, we perform masked self-attention calculations. This mechanism allows the model to generate sequences by focusing on relevant parts of the input while preventing access to future tokens. Figure 3 . Using Query, Key, and Value matrices to calculate masked self-attention. Dot Product : The dot product of Query a