0Pricing
Machine Learning Academy · 강의

트랜스포머 구조: 어텐션, 토큰 및 문맥

학습자는 셀프 어텐션 메커니즘을 따라가고, BERT가 문장을 왼쪽에서 오른쪽으로 읽는 대신 전체 문장을 한 번에 처리하는 방식을 이해하며, CLS와 SEP 특수 토큰을 해석합니다.

트랜스포머 구조: 어텐션, 토큰 및 문맥은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is a Transformer?

The Transformer is a neural network architecture introduced in 2017 that replaced recurrent networks for most NLP tasks. Unlike RNNs that process tokens one at a time, Transformers process the entire sequence in parallel using a mechanism called self-attention. This parallel processing makes training much faster and allows the model to capture long-range dependencies more effectively.

Self-Attention: Relating Every Token

Self-attention allows each token in a sequence to attend to every other token simultaneously. For the sentence 'The bank by the river was steep', the word 'bank' can attend strongly to 'river' to resolve its meaning. Each token produces three vectors: Query (Q), Key (K), and Value (V), which are used to compute weighted relationships between all token pairs.

import torch
import torch.nn.functional as F

# Simplified self-attention for 3 tokens, d_model=4
Q = torch.randn(3, 4)  # queries
K = torch.randn(3, 4)  # keys
V = torch.randn(3, 4)  # values

d_k = Q.shape[-1]
scores = torch.matmul(Q, K.T) / (d_k ** 0.5)  # scaled dot product
weights = F.softmax(scores, dim=-1)  # attention weights
output = torch.matmul(weights, V)    # weighted values
print('Attention weights:', weights)

Scaled Dot-Product Attention

The attention score between token i and token j is computed as the dot product of Q_i and K_j, divided by the square root of the key dimension to prevent vanishingly small gradients. The formula is: Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) * V. The scaling factor sqrt(d_k) keeps gradients stable for large embedding dimensions.

Multi-Head Attention

Instead of one set of Q, K, V projections, Transformers use multi-head attention: h parallel attention heads, each learning different aspects of token relationships. One head might learn syntactic dependencies (subject-verb), another semantic ones (synonyms). The outputs of all heads are concatenated and projected to produce the final representation.

import torch.nn as nn

multihead_attn = nn.MultiheadAttention(
    embed_dim=512,
    num_heads=8,      # 8 heads, each with dim 64
    dropout=0.1,
    batch_first=True
)
# x shape: (batch, seq_len, 512)
# output shape: (batch, seq_len, 512)
output, attn_weights = multihead_attn(x, x, x)

BERT: Bidirectional Context

BERT (Bidirectional Encoder Representations from Transformers) reads the entire sequence at once, attending to both left and right context simultaneously. Earlier models like GPT read left-to-right only. This bidirectionality lets BERT understand that 'bank' in 'river bank' differs from 'bank' in 'bank account' by seeing all surrounding words at once.

Special Tokens: CLS and SEP

BERT introduces two special tokens. The [CLS] (classification) token is prepended to every input; after processing, its final hidden state aggregates sentence-level information and is used for classification tasks. The [SEP] token separates two sentences in tasks like question answering or next-sentence prediction. Understanding these tokens is essential when building BERT pipelines.

# Example tokenised input for BERT sentence-pair
# [CLS] I love Python [SEP] Python is great [SEP]
# token_ids: [101, 1045, 2293, 18750, 102, 18750, 2003, 2307, 102]
# segment_ids: [0,   0,    0,    0,     0,   1,     1,   1,    1  ]
print('CLS token id:', 101)
print('SEP token id:', 102)

Positional Encoding: Order Without Recurrence

Because Transformers process all tokens in parallel, they have no inherent sense of token order. Positional encodings are added to each token embedding to inject position information. BERT uses learned positional embeddings while the original Transformer used sinusoidal functions. Without positional encoding, 'cat bites dog' and 'dog bites cat' would produce identical representations.

import torch.nn as nn

# BERT-style learned positional embedding
pos_embedding = nn.Embedding(512, 768)  # max 512 positions, d_model=768
positions = torch.arange(seq_len).unsqueeze(0)  # (1, seq_len)
pos_enc = pos_embedding(positions)  # (1, seq_len, 768)
# Added to token embeddings before feeding to transformer layers

Encoder Architecture: Layers and Feed-Forward

Each BERT encoder layer consists of two sub-layers: multi-head self-attention followed by a position-wise feed-forward network (two linear layers with a GELU activation). Each sub-layer has a residual connection and layer normalisation. BERT-base stacks 12 such layers; BERT-large uses 24. Deeper stacks capture more abstract linguistic structure.

Token Embeddings: WordPiece Vocabulary

BERT tokenises text using WordPiece subword tokenisation. Rare words are split into frequent sub-units: 'unbelievable' might become ['un', '##believe', '##able']. The ## prefix indicates a continuation subword. This approach handles out-of-vocabulary words gracefully and uses a vocabulary of ~30,000 tokens, balancing coverage and embedding table size.

from transformers import BertTokenizer

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
text = 'unbelievable achievements'
tokens = tokenizer.tokenize(text)
print(tokens)  # ['un', '##believ', '##able', 'achievements']

encoded = tokenizer(text, return_tensors='pt')
print('input_ids:', encoded['input_ids'])
print('attention_mask:', encoded['attention_mask'])

Attention Mask: Handling Padding

When processing batches of variable-length sentences, shorter sentences are padded with [PAD] tokens to match the longest sequence. The attention mask is a binary tensor (1 for real tokens, 0 for padding) that tells the model to ignore padding positions in the attention computation. Without this mask, the model would attend to meaningless padding tokens and corrupt its representations.

from transformers import BertTokenizer

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
batch = ['Short text.', 'This sentence is longer than the first one.']
encoded = tokenizer(batch, padding=True, truncation=True, return_tensors='pt')
print('input_ids shape:', encoded['input_ids'].shape)
print('attention_mask:\n', encoded['attention_mask'])
# Zeros mark padding positions

Pre-Training BERT: MLM and NSP

BERT was pre-trained on two tasks. Masked Language Modelling (MLM) randomly masks 15% of tokens and trains BERT to predict the original token from context, forcing bidirectional understanding. Next Sentence Prediction (NSP) trains BERT to determine whether two sentences are consecutive, helping sentence-pair tasks. Fine-tuning then adapts these rich representations to downstream tasks with minimal additional training.

Quick Check

Test your understanding of Machine Learning with Python concepts from this lesson.

Lesson Recap

In this lesson you learned: Transformers use parallel self-attention instead of sequential recurrence, BERT reads bidirectional context using masked language modelling pre-training, and special tokens [CLS] and [SEP] structure BERT's inputs for classification and sentence-pair tasks. Next up we explore how Hugging Face tokenizers encode raw text into the tensor format BERT expects.

자주 묻는 질문

“트랜스포머 구조: 어텐션, 토큰 및 문맥” 강의는 무료인가요?

네 — “트랜스포머 구조: 어텐션, 토큰 및 문맥” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“트랜스포머 구조: 어텐션, 토큰 및 문맥”에서 뭘 배우나요?

학습자는 셀프 어텐션 메커니즘을 따라가고, BERT가 문장을 왼쪽에서 오른쪽으로 읽는 대신 전체 문장을 한 번에 처리하는 방식을 이해하며, CLS와 SEP 특수 토큰을 해석합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“트랜스포머 구조: 어텐션, 토큰 및 문맥” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 트랜스포머 구조: 어텐션, 토큰 및 문맥
  2. Hugging Face 토크나이저: BERT용 텍스트 인코딩
  3. BertForSequenceClassification 미세 조정
  4. 평가와 추론: 로짓에서 예측 레이블까지
← Machine Learning Academy(으)로 돌아가기