Transformer
AI
Deep Learning
GPT
BERT
Attention

Transformer Architecture: เทคโนโลยีเบื้องหลัง ChatGPT

ทำความเข้าใจ Transformer สถาปัตยกรรมที่ปฏิวัติวงการ AI ตั้งแต่ Attention Mechanism ไปจนถึง GPT และ BERT

AI Unlocked Team
13/01/2568
Transformer Architecture: เทคโนโลยีเบื้องหลัง ChatGPT

Transformer Architecture: เทคโนโลยีเบื้องหลัง ChatGPT

ในปี 2017 Google เผยแพร่งานวิจัยที่มีชื่อว่า "Attention Is All You Need" ซึ่งนำเสนอสถาปัตยกรรมใหม่ที่เรียกว่า Transformer และมันได้เปลี่ยนโลก AI ไปตลอดกาล

วันนี้ Transformer อยู่เบื้องหลัง ChatGPT, Claude, BERT, และ AI สมัยใหม่แทบทุกตัว

Transformer คืออะไร?

Transformer คือสถาปัตยกรรม Neural Network ที่ใช้กลไก Attention ในการประมวลผลข้อมูล โดยสามารถมองเห็นความสัมพันธ์ระหว่างทุกส่วนของ input พร้อมกัน

ทำไมถึงเป็นการปฏิวัติ?

ก่อน Transformer (RNN/LSTM):

"ฉัน ชอบ กิน ข้าว ผัด กะเพรา"
  ↓     ↓    ↓    ↓    ↓    ↓
  1  →  2  → 3  → 4  → 5  → 6  (ประมวลผลทีละคำ)

ปัญหา:
- ช้า (ต้องรอคำก่อนหน้า)
- ลืมคำที่อยู่ไกล

Transformer:

"ฉัน ชอบ กิน ข้าว ผัด กะเพรา"
   ↑     ↑    ↑    ↑    ↑    ↑
   └─────┴────┴────┴────┴────┘
        (มองเห็นทุกคำพร้อมกัน)

ข้อดี:
- เร็ว (ประมวลผลขนาน)
- จำได้ไกล (Attention)

Attention Mechanism

หัวใจของ Transformer คือ Attention - กลไกที่ให้โมเดลรู้ว่าควร "ใส่ใจ" ส่วนไหนของ input

Self-Attention

ประโยค: "The cat sat on the mat because it was tired"

เมื่อประมวลผลคำว่า "it":
- "it" หมายถึงอะไร?
- Attention จะโฟกัสที่ "cat" (สูง)
- ไม่ใช่ "mat" (ต่ำ)

      The  cat  sat  on  the  mat  because  it  was  tired
       ↑    ↑
       └────┴── Attention score สูง

Query, Key, Value (Q, K, V)

Attention คำนวณจาก 3 องค์ประกอบ:

สำหรับแต่ละคำ:
- Query (Q): "ฉันกำลังหาอะไร?"
- Key (K): "ฉันคืออะไร?"
- Value (V): "ฉันมีข้อมูลอะไร?"

สูตร:
Attention(Q, K, V) = softmax(Q × K^T / √d) × V

d = dimension (ขนาดของ vector)

Multi-Head Attention

ใช้หลาย Attention heads พร้อมกันเพื่อมองหาความสัมพันธ์หลายแบบ:

Head 1: มองหาความสัมพันธ์ทางไวยากรณ์
Head 2: มองหาความหมาย
Head 3: มองหาบริบท
Head 4: มองหาตำแหน่ง
...
Head 8: ...

แล้วรวมผลลัพธ์ทุก heads

โครงสร้าง Transformer

Encoder-Decoder Architecture

┌─────────────────────────────────────────────┐
│                 Transformer                  │
│                                             │
│  ┌─────────────┐      ┌─────────────┐      │
│  │   Encoder   │      │   Decoder   │      │
│  │             │      │             │      │
│  │ ┌─────────┐ │      │ ┌─────────┐ │      │
│  │ │  Attn   │ │ ──── │ │  Attn   │ │      │
│  │ └─────────┘ │      │ └─────────┘ │      │
│  │ ┌─────────┐ │      │ ┌─────────┐ │      │
│  │ │   FFN   │ │      │ │   FFN   │ │      │
│  │ └─────────┘ │      │ └─────────┘ │      │
│  │     ×N      │      │     ×N      │      │
│  └─────────────┘      └─────────────┘      │
│         ↑                    ↓              │
│      Input              Output              │
└─────────────────────────────────────────────┘

Encoder Block

ประมวลผล input ให้เข้าใจความหมาย:

Input Embedding + Positional Encoding
              ↓
┌─────────────────────────────┐
│    Multi-Head Attention     │
│         + Add & Norm        │
└─────────────────────────────┘
              ↓
┌─────────────────────────────┐
│    Feed Forward Network     │
│         + Add & Norm        │
└─────────────────────────────┘
              ↓
           Output

Decoder Block

สร้าง output ทีละคำ:

Output Embedding + Positional Encoding
              ↓
┌─────────────────────────────┐
│  Masked Multi-Head Attn     │  ← ป้องกันดูคำในอนาคต
│       + Add & Norm          │
└─────────────────────────────┘
              ↓
┌─────────────────────────────┐
│  Cross Multi-Head Attn      │  ← ดู Encoder output
│       + Add & Norm          │
└─────────────────────────────┘
              ↓
┌─────────────────────────────┐
│    Feed Forward Network     │
│       + Add & Norm          │
└─────────────────────────────┘
              ↓
           Output

องค์ประกอบสำคัญ

1. Positional Encoding

Transformer ไม่มีความเข้าใจเรื่องลำดับ จึงต้องเพิ่ม positional information:

PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))

pos = ตำแหน่งของคำ
i = มิติ
d = ขนาด embedding

2. Layer Normalization

ทำให้ training เสถียร:

x_norm = (x - mean) / sqrt(variance + ε)
output = γ × x_norm + β

3. Feed Forward Network

MLP 2 ชั้นสำหรับแต่ละ position:

FFN(x) = ReLU(x × W1 + b1) × W2 + b2

# หรือใน GPT ใช้ GELU
FFN(x) = GELU(x × W1 + b1) × W2 + b2

4. Residual Connections

Skip connections ช่วยให้ train deep networks ได้:

output = LayerNorm(x + Sublayer(x))

Transformer Variants

Encoder-Only (BERT)

ใช้แค่ Encoder สำหรับงานเข้าใจภาษา:

ใช้งาน:
- Text Classification
- Named Entity Recognition
- Question Answering
- Sentiment Analysis

โมเดล: BERT, RoBERTa, ALBERT, DistilBERT

Decoder-Only (GPT)

ใช้แค่ Decoder สำหรับงานสร้างข้อความ:

ใช้งาน:
- Text Generation
- Chatbots (ChatGPT, Claude)
- Code Generation
- Translation

โมเดล: GPT-2, GPT-3, GPT-4, LLaMA, Claude

Encoder-Decoder (T5)

ใช้ทั้งคู่สำหรับงาน seq2seq:

ใช้งาน:
- Translation
- Summarization
- Question Answering

โมเดล: T5, BART, mBART

ทำไม Transformer ถึงประสบความสำเร็จ?

1. Parallelization

RNN:  [word1] → [word2] → [word3] → [word4]
        ↓         ↓         ↓         ↓
      (ต้องรอ)  (ต้องรอ)  (ต้องรอ)  output

Transformer: [word1] [word2] [word3] [word4]
                ↓       ↓       ↓       ↓
              (พร้อมกันหมด)
                        ↓
                     output

เร็วกว่ามาก!

2. Long-Range Dependencies

"The cat that sat on the mat near the window was tired"
                                              ↑
Attention ยังเชื่อมกับ "cat" ได้แม้อยู่ไกล

3. Scalability

ยิ่งใหญ่ ยิ่งเก่ง:
- GPT-2: 1.5B parameters
- GPT-3: 175B parameters
- GPT-4: ~1.7T parameters (ประมาณ)

ตัวอย่างโค้ด

Attention ด้วย PyTorch

import torch
import torch.nn as nn
import math

class SelfAttention(nn.Module):
    def __init__(self, embed_size, heads):
        super().__init__()
        self.embed_size = embed_size
        self.heads = heads
        self.head_dim = embed_size // heads

        self.queries = nn.Linear(embed_size, embed_size)
        self.keys = nn.Linear(embed_size, embed_size)
        self.values = nn.Linear(embed_size, embed_size)
        self.fc_out = nn.Linear(embed_size, embed_size)

    def forward(self, x):
        N, seq_len, _ = x.shape

        Q = self.queries(x)
        K = self.keys(x)
        V = self.values(x)

        # Split into heads
        Q = Q.view(N, seq_len, self.heads, self.head_dim)
        K = K.view(N, seq_len, self.heads, self.head_dim)
        V = V.view(N, seq_len, self.heads, self.head_dim)

        # Attention scores
        scores = torch.einsum("nqhd,nkhd->nhqk", Q, K)
        scores = scores / math.sqrt(self.head_dim)

        attention = torch.softmax(scores, dim=-1)
        out = torch.einsum("nhqk,nkhd->nqhd", attention, V)

        out = out.reshape(N, seq_len, self.embed_size)
        return self.fc_out(out)

ใช้ Hugging Face Transformers

from transformers import AutoModel, AutoTokenizer

# โหลด BERT
model = AutoModel.from_pretrained("bert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")

# ใช้งาน
text = "Hello, how are you?"
inputs = tokenizer(text, return_tensors="pt")
outputs = model(**inputs)

# outputs.last_hidden_state = embeddings

การพัฒนาจาก Transformer

Vision Transformer (ViT)

ใช้ Transformer กับรูปภาพ:

ภาพ → แบ่งเป็น patches → Linear Embedding → Transformer

Audio Transformer

ใช้กับเสียง:

Audio → Spectrogram → Patches → Transformer

Multimodal Transformers

รวมหลาย modalities:

GPT-4V: Text + Image → Transformer → Response
Gemini: Text + Image + Audio → Transformer → Response

สรุป

Transformer ปฏิวัติ AI ด้วย:

  • Attention Mechanism: มองเห็นความสัมพันธ์ทุกส่วน
  • Parallelization: ประมวลผลพร้อมกัน
  • Scalability: ยิ่งใหญ่ยิ่งเก่ง

Variants หลัก:

  • Encoder-only (BERT): เข้าใจภาษา
  • Decoder-only (GPT): สร้างข้อความ
  • Encoder-Decoder (T5): แปลง input เป็น output

Transformer คือรากฐานของ AI สมัยใหม่ทั้งหมด!


อ่านเพิ่มเติม:


เขียนโดย

AI Unlocked Team