🤖 AI/ML

BERT

Bidirectional Encoder Representations from Transformers

Google's bidirectional language model. Excellent at understanding context. Revolutionized NLP benchmarks. Along with GPT, a forerunner of modern LLMs.

📖 Detailed Explanation

BERT (Bidirectional Encoder Representations from Transformers) is a pre-trained language model announced by Google in 2018 that understands text by considering bidirectional context simultaneously. Unlike earlier unidirectional models, it grasps the meaning of a word by using both the preceding and following context of a sentence.

Immediately after its release in October 2018, BERT achieved SOTA on 11 NLP benchmarks, bringing about a paradigm shift in the field of NLP. Since then, numerous variants such as RoBERTa, ALBERT, and DistilBERT have emerged, and Korean-specific models such as KoBERT and KoELECTRA have also been developed.

The core principle is two pre-training tasks: Masked Language Model (MLM) and Next Sentence Prediction (NSP). MLM masks 15% of the input tokens with [MASK] and has the model predict them, enabling bidirectional context learning. NSP learns relationships between sentences by determining whether two sentences are consecutive.

In practice, BERT is mainly used for NLU (natural language understanding) tasks such as text classification, named entity recognition (NER), question answering (QA), and sentence similarity measurement. Fine-tuning a pre-trained BERT for a specific task can achieve high performance even with a small amount of data, which has made it a standard approach in industry.

💻 Code Example

# BERT를 활용한 감정 분류 Fine-tuning 예제
from transformers import BertTokenizer, BertForSequenceClassification
from transformers import Trainer, TrainingArguments
from datasets import load_dataset
import torch

# 1. 모델과 토크나이저 로드
model_name = "bert-base-uncased"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(
    model_name,
    num_labels=2  # 긍정/부정 이진 분류
)

# 2. 데이터셋 로드 및 전처리
dataset = load_dataset("imdb")

def tokenize_function(examples):
    return tokenizer(
        examples["text"],
        padding="max_length",
        truncation=True,
        max_length=512
    )

tokenized_datasets = dataset.map(tokenize_function, batched=True)

# 3. 학습 설정
training_args = TrainingArguments(
    output_dir="./bert-imdb",
    num_train_epochs=3,
    per_device_train_batch_size=8,
    per_device_eval_batch_size=16,
    warmup_steps=500,
    learning_rate=2e-5,  # BERT 권장 학습률
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True
)

# 4. Trainer로 Fine-tuning
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"]
)

trainer.train()

# 5. 추론 예제
def predict_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
    with torch.no_grad():
        outputs = model(**inputs)
    probs = torch.softmax(outputs.logits, dim=-1)
    return "긍정" if probs[0][1] > 0.5 else "부정"

🗣️ Examples of Practical Conversations

At an NLP project model selection meeting

"Sentiment classification hinges on understanding context, so a BERT-family model is a good fit. Since it's Korean, I suggest starting with KoBERT or KoELECTRA, and if there's enough data, scaling up to RoBERTa-large. GPT is better suited to generation tasks."

In a discussion of fine-tuning performance issues

"In BERT fine-tuning, if the learning rate is too high, catastrophic forgetting occurs. It's safer to keep it between 2e-5 and 5e-5 and give warmup about 10% of the total steps. If the current setting is 1e-4, that's too high."

In a technical interview

"The reason BERT's MLM enables bidirectional learning is that, when predicting a masked token, it can see both the left and right context. With next-token prediction like GPT, it can't see the right side, so it becomes unidirectional. This difference is the fundamental reason BERT is strong at NLU."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

📊 BERT Model Spec Comparison

Model Parameter Layers Hidden Use case
BERT-base 110M 12 768 🏆 General Use (Recommended)
BERT-large 340M 24 1024 When high accuracy is needed
DistilBERT 66M 6 768 💨 Fast Inference (40% lighter)
KoBERT 92M 12 768 🇰🇷 Korean-Specific

💡 Practical tip: BERT-base is sufficient in most cases. Use DistilBERT when production speed matters. For Korean, KoBERT or KoELECTRA is recommended. GPU memory required for fine-tuning: 8GB or more for base, 16GB or more for large.

⚠️ Cautions

1
512-Token Limit

BERT-base can process a maximum of only 512 tokens. For long documents, use chunking or a long-context model such as Longformer or BigBird. Simple truncation causes loss of important information.

2
Unsuitable for Generation Tasks

BERT is an encoder-only model and is not suitable for text generation. For summarization, translation, dialogue generation, and the like, use a GPT-family model or an encoder-decoder model such as T5.

3
Domain Mismatch

Applying a BERT pre-trained on a general domain directly to specialized domains such as medicine or law degrades performance. Use a domain-specific model such as BioBERT or LegalBERT, or perform additional pre-training on domain data.

🔗 Related Terms

📚 Learn More