Published on

Day 14: Transformer Architecture

Authors

Mục tiêu học tập

Sau bài này, bạn cần làm được 5 việc:

  • Vẽ được luồng dữ liệu của một Transformer từ text input đến output.
  • Giải thích được encoder, decoder, encoder-only, decoder-only và encoder-decoder khác nhau ở mask, objective và output.
  • Hiểu vai trò của positional encoding, RoPE, LayerNorm, FFN và residual connection.
  • Chọn được kiến trúc phù hợp cho semantic search, classification, chatbot và summarization theo latency, cost, data privacy và license.
  • Trả lời được câu hỏi production: dùng được không, dùng trong điều kiện nào, cần monitor gì.

TL;DR

Transformer là kiến trúc xử lý sequence bằng cách lặp nhiều Transformer block. Mỗi block thường có self-attention để trộn thông tin giữa các token, FFN để biến đổi representation của từng token, residual connection để giữ đường đi ổn định cho gradient và LayerNorm để ổn định activation. Encoder-only model như BERT/PhoBERT mạnh cho classification, embedding và reranking. Decoder-only model như GPT, LLaMA, Qwen mạnh cho generation, chat và tool calling. Encoder-decoder model như T5 mạnh cho sequence-to-sequence task như translation và summarization có input rõ ràng.

Trong production, không chọn kiến trúc theo độ nổi tiếng của model. Hãy chọn theo task, latency target, context length, memory/VRAM, KV cache, throughput, data privacy, license và khả năng vận hành.

1. Transformer nối tiếp Day 13 như thế nào?

Day 13 tập trung vào attention: Query, Key, Value, scaled dot-product attention, self-attention, causal mask và multi-head attention.

Day 14 đặt attention vào một kiến trúc đầy đủ:

Text
  -> tokenizer
  -> token ids
  -> token embedding
  -> cộng hoặc áp positional information
  -> nhiều Transformer blocks
  -> task head hoặc language modeling head
  -> output

Attention chỉ là một phần. Một Transformer production còn cần tokenizer đúng version, embedding table, positional strategy, LayerNorm placement, FFN, residual path, output head, decoding strategy, serving runtime và monitoring.

2. Luồng dữ liệu tổng quát

Ví dụ input:

"Khách hàng muốn hoàn tiền vì đơn giao chậm"

Sau tokenization:

[<cls>, "Khách", "hàng", "muốn", "hoàn", "tiền", "vì", "đơn", "giao", "chậm", <sep>]

Luồng qua Transformer encoder classifier:

token ids
  -> token embedding:        [batch, seq_len, hidden_dim]
  -> positional information: [batch, seq_len, hidden_dim]
  -> block 1
  -> block 2
  -> ...
  -> block N
  -> lấy vector <cls>
  -> classification head
  -> label: "refund_request"

Luồng qua decoder-only chatbot:

prompt tokens
  -> token embedding + position
  -> causal Transformer blocks
  -> logits cho token kế tiếp
  -> sample/greedy/beam
  -> append token mới
  -> lặp đến khi gặp stop token hoặc max_tokens

Khác biệt quan trọng: encoder xử lý toàn bộ input một lượt để tạo contextual vector; decoder-only sinh output từng token, nên latency tăng theo số output token.

3. Transformer block gồm những gì?

Một block hiện đại thường dùng dạng Pre-LN:

                 +-----------------------------+
                 |                             |
x -------------- + --------------------------> + -> x1
|                |                             ^
|                v                             |
|          LayerNorm -> Multi-Head Attention ->|
|
|                +-----------------------------+
|                |                             |
x1 ------------- + --------------------------> + -> x2
                 |                             ^
                 v                             |
            LayerNorm -> FFN -> Dropout -------+

Dạng công thức:

x1 = x + Attention(LayerNorm(x))
x2 = x1 + FFN(LayerNorm(x1))

Các thành phần chính:

Thành phầnVai tròĐiều cần nhớ
Token embeddingBiến token id thành vectorLà input representation học được
Positional informationCho model biết thứ tự tokenSelf-attention tự thân không biết vị trí
Multi-head attentionTrộn thông tin giữa các tokenChi phí tăng mạnh theo sequence length
Residual connectionGiữ đường đi trực tiếp cho signalGiúp train network sâu ổn định hơn
LayerNormỔn định activation theo hidden dimensionPre-LN thường ổn định hơn với model sâu
FFNBiến đổi representation từng tokenKhông mix token; attention mới mix token
DropoutRegularization khi trainingThường tắt trong inference

4. Encoder

Encoder nhận toàn bộ input và cho mỗi token attend đến các token khác trong cùng sequence. Đây là bidirectional context.

Input tokens: [t1, t2, t3, t4]

Token t1 thấy: t1, t2, t3, t4
Token t2 thấy: t1, t2, t3, t4
Token t3 thấy: t1, t2, t3, t4
Token t4 thấy: t1, t2, t3, t4

Encoder phù hợp khi output không cần sinh từng token tự do:

  • Text classification: sentiment, intent, category, priority.
  • Token classification: NER, POS tagging.
  • Semantic embedding: biến text thành vector để search.
  • Reranking: score relevance giữa query và document.
  • Feature extraction: tạo representation cho downstream model.

Trong BERT-style classifier, vector [CLS] thường được đưa vào classification head:

[CLS] tôi cần hoàn tiền [SEP]
  -> BERT encoder
  -> hidden state của [CLS]
  -> Linear layer
  -> label probabilities

Điểm mạnh:

  • Hiểu context hai chiều tốt.
  • Inference một lượt cho input cố định.
  • Thường rẻ hơn decoder-only cho classification ngắn.

Điểm yếu:

  • Không tự nhiên cho open-ended generation.
  • Max length thường cố định và ngắn hơn LLM hiện đại.
  • Cần fine-tune hoặc train head cho task cụ thể.

5. Decoder

Decoder trong Transformer gốc có 2 attention:

  • Masked self-attention trên output đã sinh.
  • Cross-attention sang encoder output.

Trong decoder-only LLM hiện đại, ta thường nói đến stack chỉ có causal self-attention:

Token i chỉ được nhìn các token <= i

Causal mask:

        attend to
        t1 t2 t3 t4
from t1  1  0  0  0
from t2  1  1  0  0
from t3  1  1  1  0
from t4  1  1  1  1

Training objective phổ biến:

Input:  "Hà Nội là thủ đô của"
Target: "Việt Nam"

Model học predict next token. Khi inference, model lặp:

prompt -> logits token kế tiếp -> chọn token -> append -> chạy tiếp

Điểm mạnh:

  • Sinh text linh hoạt.
  • Hợp với chatbot, reasoning, tool calling, code generation.
  • Có thể làm nhiều task bằng prompt mà không cần train head riêng.

Điểm yếu:

  • Latency phụ thuộc output length.
  • Cần KV cache để inference hiệu quả.
  • Tốn memory cho weights và KV cache.
  • Dễ phát sinh hallucination, prompt injection, output không ổn định nếu không có guardrails/eval.

6. Encoder-only: BERT, PhoBERT

Encoder-only model dùng bidirectional attention và thường được pretrain bằng masked language modeling hoặc biến thể tương tự.

"Tôi muốn [MASK] tiền"
  -> model dự đoán token bị mask: "hoàn"

BERT/PhoBERT phù hợp với:

  • Classification tiếng Việt.
  • Intent detection.
  • Sentiment analysis.
  • Named Entity Recognition.
  • Embedding hoặc reranking, tùy model/head.

Decision rule:

Nếu output là label, score hoặc vector -> ưu tiên encoder-only.
Nếu output là đoạn văn dài -> không ưu tiên encoder-only.

Production note:

  • Model encoder nhỏ có thể chạy CPU nếu latency không quá chặt.
  • GPU hoặc ONNX/quantization hữu ích khi throughput cao.
  • Cần version chặt giữa tokenizer, model config và label mapping.
  • Với tiếng Việt, kiểm tra tokenizer/preprocessing vì word segmentation có thể ảnh hưởng mạnh.

7. Decoder-only: GPT, LLaMA, Qwen

Decoder-only model dùng causal attention và next-token prediction. GPT, LLaMA, Qwen, Mistral và nhiều chat model hiện đại thuộc nhóm này.

Phù hợp với:

  • Chatbot.
  • General assistant.
  • Code assistant.
  • RAG generation.
  • Tool/function calling.
  • Drafting, rewriting, summarization bằng prompt.

Điểm production cần hiểu:

total latency ~= prefill latency + decode latency * output_tokens
  • Prefill: xử lý prompt/context ban đầu. Chi phí attention tăng theo context length.
  • Decode: sinh từng token. KV cache giúp không tính lại K/V cũ.
  • KV cache: tăng tốc decoding nhưng tốn VRAM theo batch, layers, heads, head_dim và context length.

Khi dùng decoder-only cho classification:

  • Có thể prompt để model trả label.
  • Nhưng nếu SLA chặt, label space ổn định và volume lớn, encoder-only fine-tuned thường rẻ và nhanh hơn.

8. Encoder-decoder: T5

Encoder-decoder có 2 phần:

source text
  -> encoder tạo source representation
  -> decoder sinh target text, vừa nhìn target đã sinh vừa cross-attend sang encoder output

Luồng chi tiết:

Input document
  -> encoder self-attention bidirectional
  -> encoder hidden states
  -> decoder masked self-attention trên output prefix
  -> decoder cross-attention vào encoder hidden states
  -> output token kế tiếp

T5 biến nhiều NLP task thành text-to-text:

"summarize: <document>" -> "<summary>"
"translate English to Vietnamese: <text>" -> "<translation>"
"classify sentiment: <text>" -> "positive"

Phù hợp với:

  • Translation.
  • Summarization có input rõ.
  • Data-to-text.
  • Text normalization.
  • Task sequence-to-sequence với format tương đối ổn định.

Trade-off:

  • Có thể mạnh và gọn cho seq2seq chuyên biệt.
  • Serving phức tạp hơn encoder-only vì vẫn phải decode token.
  • Với chatbot tổng quát, decoder-only thường phổ biến hơn do ecosystem và instruction tuning.

9. Positional encoding

Self-attention nhìn một set token và tính similarity giữa Query/Key. Nếu không thêm thông tin vị trí, model khó phân biệt:

"chó cắn người"
"người cắn chó"

Hai câu có token giống nhau nhưng ý nghĩa khác do thứ tự khác.

Các cách phổ biến:

CáchÝ tưởngƯu điểmHạn chế
Sinusoidal positional encodingCộng vector sin/cos theo vị tríKhông cần học thêm parameter, giải thích đượcKhông phải lựa chọn chính của nhiều LLM hiện đại
Learned absolute positionHọc embedding riêng cho từng vị tríĐơn giản, hiệu quả trong max length đã trainKhó extrapolate vượt max position
Relative position biasThêm bias theo khoảng cách tương đốiTốt cho quan hệ gần/xaCần implementation đúng với architecture
RoPERotate Query/Key theo vị tríPhổ biến trong decoder-only LLM, hỗ trợ relative position tốtContext extension cần cấu hình cẩn thận
ALiBiThêm bias tuyến tính theo khoảng cáchCó thể extrapolate tốt trong một số settingKhông phải mặc định của mọi model

10. RoPE

RoPE là Rotary Position Embedding. Thay vì cộng position vector vào embedding, RoPE xoay các chiều của Query và Key theo vị trí token.

Trực giác:

Q(token, position i) được xoay theo i
K(token, position j) được xoay theo j
Dot product giữa Q_i và K_j chứa thông tin khoảng cách i - j

Vì sao RoPE quan trọng trong LLM hiện đại:

  • Giúp attention nhận biết vị trí tương đối.
  • Phù hợp với causal decoder.
  • Được dùng rộng rãi trong LLaMA/Qwen-style model.
  • Có nhiều kỹ thuật context extension dựa trên RoPE scaling.

Production note:

  • Không tự đổi RoPE config nếu không hiểu model đã train thế nào.
  • Context extension bằng RoPE scaling cần eval riêng; model có thể chạy được nhưng quality giảm ở đoạn dài.
  • Khi load model, tokenizer, config và RoPE parameters phải đi cùng version.

11. LayerNorm

LayerNorm normalize activation theo hidden dimension của từng token:

token vector x -> normalize mean/variance -> scale + bias

Tác dụng:

  • Ổn định training.
  • Giảm activation quá lớn hoặc quá lệch giữa layers.
  • Giúp optimizer làm việc dễ hơn với network sâu.

Post-LN trong Transformer gốc:

x -> sublayer -> residual add -> LayerNorm

Pre-LN phổ biến trong nhiều model hiện đại:

x -> LayerNorm -> sublayer -> residual add

Trade-off:

  • Pre-LN thường ổn định hơn khi train model sâu.
  • Post-LN có thể cho behavior khác về gradient và final representation.
  • Khi dùng pretrained model, không thay đổi placement của LayerNorm; đó là một phần architecture đã train.

12. FFN

FFN trong Transformer thường là MLP áp dụng độc lập cho từng token:

FFN(x) = Linear(hidden_dim -> intermediate_dim)
       -> activation, thường GELU/SwiGLU
       -> Linear(intermediate_dim -> hidden_dim)

FFN không mix thông tin giữa các token. Attention đã làm việc đó. FFN xử lý từng token sau khi token đã nhận context.

Trực giác:

attention: token này cần lấy gì từ token khác?
FFN: sau khi có context, biến đổi feature của token này như thế nào?

Production note:

  • FFN thường chiếm phần lớn parameter và compute trong nhiều Transformer.
  • Một số LLM dùng gated FFN như SwiGLU thay vì GELU MLP đơn giản.
  • Quantization ảnh hưởng mạnh đến cả attention projection và FFN weights; phải eval chất lượng sau quantization.

13. Residual connection

Residual connection cộng input ban đầu vào output của sublayer:

x_next = x + sublayer(x)

Tác dụng:

  • Cho signal và gradient có đường đi ngắn hơn qua nhiều layers.
  • Cho layer học phần delta thay vì học lại toàn bộ representation.
  • Giảm rủi ro model sâu bị degrade khi thêm layers.

Nếu bỏ residual connection, Transformer sâu thường khó train hơn nhiều.

14. So sánh architecture

ArchitectureMaskObjective phổ biếnOutput tự nhiênVí dụNên dùng khi
Encoder-onlyBidirectionalMasked LM, classification fine-tuneVector, label, scoreBERT, PhoBERTClassification, embedding, reranking
Decoder-onlyCausalNext-token predictionText sinh tự doGPT, LLaMA, QwenChat, RAG answer, tool calling, code
Encoder-decoderEncoder bidirectional, decoder causal + cross-attentionSeq2seq text-to-textText targetT5Translation, summarization, text normalization

15. Latency, memory, KV cache và context length

Encoder-only latency

Encoder xử lý input trong một forward pass:

latency ~= tokenization + encoder_forward + head

Nếu seq_len tăng, attention cost tăng gần bậc hai. Nhưng với classification, output chỉ là label nên không có decode loop.

Decoder-only latency

Decoder-only có 2 pha:

prefill: xử lý prompt/context ban đầu
decode: sinh từng token output

Nếu prompt dài, prefill chậm. Nếu output dài, decode chậm.

request latency ~= prefill(context_tokens) + output_tokens * per_token_decode

KV cache

Khi sinh token thứ 100, nếu không cache, model phải tính lại Key/Value cho 99 token trước. KV cache lưu K/V cũ để token mới chỉ cần tính phần mới.

Trade-off:

  • Tăng tốc generation.
  • Tốn VRAM theo batch size, number of layers, number of heads, head dimension và context length.
  • Với nhiều concurrent users, KV cache có thể là bottleneck chính, không phải weights.

Context length

Context dài không miễn phí:

  • Attention memory/compute tăng mạnh.
  • KV cache tăng theo sequence length.
  • Long prompt làm p95/p99 latency xấu.
  • Model có thể bị lost-in-the-middle, không dùng tốt thông tin ở giữa context.

Production guidance:

  • Đặt token budget theo use case, không default max context.
  • Với RAG, ưu tiên retrieval/chunking/reranking tốt hơn là nhét mọi tài liệu vào context.
  • Monitor token distribution, truncation rate, p95 latency, VRAM usage và OOM.

16. Chọn kiến trúc cho bài toán gần production

Case A: semantic search nội bộ

Yêu cầu:

  • Query tiếng Việt.
  • Search tài liệu công ty.
  • Latency p95 dưới 300 ms cho retrieval.
  • Dữ liệu có thể có thông tin nội bộ.

Khuyến nghị:

embedding model: encoder-only hoặc bi-encoder sentence embedding
reranker: encoder cross-encoder nếu cần quality cao
generator: không cần nếu chỉ search; dùng decoder-only nếu có RAG answer

Trade-off:

  • Bi-encoder nhanh vì precompute document embedding.
  • Cross-encoder reranker chất lượng cao hơn nhưng chậm hơn vì phải score từng cặp query-document.
  • Self-host nếu data privacy không cho gửi query/document ra external API.

Case B: ticket classification

Yêu cầu:

  • Gán label: billing, refund, shipping, account.
  • 200 requests/second.
  • Label ổn định.
  • Chi phí thấp.

Khuyến nghị:

baseline: TF-IDF + Logistic Regression
production v1: encoder-only fine-tuned BERT/PhoBERT
không ưu tiên: decoder-only prompt classification nếu volume lớn và SLA chặt

Trade-off:

  • Encoder-only nhanh, output ổn định, dễ đo F1/confusion matrix.
  • Decoder-only dễ prototype nhưng tốn token, latency cao hơn và output cần parse/validate.
  • Nếu data nhạy cảm, self-host encoder nhỏ dễ hơn self-host LLM lớn.

Case C: chatbot CSKH có RAG

Yêu cầu:

  • Trả lời tự nhiên.
  • Có citation từ knowledge base.
  • Có tool lookup order.
  • Cần guardrails.

Khuyến nghị:

retrieval embedding: encoder model
reranking: encoder cross-encoder hoặc lightweight reranker
generator: decoder-only instruction/chat model
tool calling: controlled schema + allowlist

Trade-off:

  • Decoder-only cần KV cache, streaming và rate limit.
  • RAG giảm hallucination nhưng không loại bỏ hoàn toàn.
  • External model nhanh triển khai nhưng cần kiểm tra data policy.
  • Self-host tăng privacy/control nhưng cần GPU, autoscaling, monitoring và on-call.

Case D: summarization tài liệu pháp lý

Yêu cầu:

  • Input dài.
  • Output có format: facts, obligations, risks.
  • Không được bịa.
  • Có thể chạy batch qua đêm.

Khuyến nghị:

option 1: encoder-decoder/T5-style model fine-tuned nếu domain và format rất ổn định
option 2: decoder-only long-context model + chunked summarization + verification nếu cần linh hoạt

Trade-off:

  • Encoder-decoder tốt cho seq2seq cố định nhưng ecosystem serving có thể ít tiện hơn decoder-only chat model.
  • Decoder-only linh hoạt hơn nhưng phải kiểm soát hallucination, citation và output schema.
  • Với tài liệu dài, dùng hierarchical summarization thay vì nhét toàn bộ context nếu latency/cost cao.

17. Dùng được trong production không?

Có, Transformer dùng được trong production và thực tế đang là nền tảng của nhiều hệ thống NLP/LLM. Nhưng điều kiện tối thiểu là:

  • Chọn architecture theo task, không chọn theo hype.
  • Có eval set đại diện dữ liệu thật, gồm cả edge cases và negative cases.
  • Có baseline đơn giản để so sánh, ví dụ rule/TF-IDF/logistic trước khi fine-tune model lớn.
  • Pin version tokenizer, model weights, config, label mapping và prompt/template.
  • Kiểm tra license model cho commercial/internal use.
  • Có policy cho PII, retention, logging và data residency.
  • Benchmark latency, throughput, memory/VRAM, context length và cost/request trên hardware thật.
  • Có monitoring: p50/p95/p99 latency, error rate, token usage, OOM, truncation rate, output quality, user feedback.
  • Có rollback path khi model upgrade làm giảm quality.
  • Có guardrails nếu model sinh text, gọi tool hoặc đọc dữ liệu không tin cậy.

Không nên đưa vào production nếu:

  • Chưa rõ license.
  • Chưa có eval set.
  • Chưa biết tokenizer/model version nào đang chạy.
  • Chưa đo latency/memory trên traffic thật.
  • Chưa có cách rollback.
  • Với LLM generation, chưa có output validation, safety policy hoặc human escalation cho case rủi ro cao.

18. Checklist đọc paper/tài liệu

Khi đọc "Attention Is All You Need", "The Illustrated Transformer" hoặc model paper mới, dùng checklist này:

  • Architecture thuộc encoder-only, decoder-only hay encoder-decoder?
  • Input/output contract là gì?
  • Attention mask là bidirectional, causal, sliding window hay biến thể khác?
  • Positional strategy là sinusoidal, learned, relative bias, RoPE hay ALiBi?
  • LayerNorm là Pre-LN hay Post-LN?
  • FFN dùng GELU, SwiGLU hay MoE?
  • Context length lúc train là bao nhiêu?
  • Training objective là masked LM, next-token prediction, seq2seq hay instruction tuning?
  • Model size, number of layers, hidden size, heads, vocab size là bao nhiêu?
  • Dataset/language/domain có khớp use case không?
  • License có cho phép mục tiêu sử dụng không?
  • Serving yêu cầu GPU/CPU/TPU, memory, quantization, KV cache như thế nào?
  • Paper report metric nào, có metric nào gần production use case của mình không?
  • Failure modes hoặc limitations được tác giả nêu là gì?

19. Tự kiểm tra nhanh

  1. Vì sao self-attention cần positional information?
  2. Encoder-only và decoder-only khác nhau ở mask và training objective nào?
  3. FFN làm gì nếu nó không mix token?
  4. Residual connection giúp gì khi stack nhiều Transformer blocks?
  5. KV cache giải quyết vấn đề gì và đổi lại tốn gì?
  6. Khi nào classification bằng BERT/PhoBERT hợp lý hơn prompt GPT-style model?
  7. Khi nào T5/encoder-decoder đáng cân nhắc hơn decoder-only?
  8. Vì sao long context không thay thế retrieval design tốt?

20. Kết nối sang Day 15 và Day 16

Day 15 sẽ dùng HuggingFace ecosystem để load tokenizer/model, đọc model card, chạy inference và kiểm tra license/intended use. Day 16 sẽ fine-tune PhoBERT/BERT classifier. Vì vậy sau Day 14, bạn nên đã có quyết định rõ:

Task Day 16 là classification -> ưu tiên encoder-only -> BERT/PhoBERT-style model.

Decoder-only vẫn quan trọng cho các ngày sau về LLM application, RAG, tool calling và agent workflow.


Tài liệu

File này dùng như tài liệu tra cứu nhanh sau khi đã đọc lession.md.

1. Từ attention đến Transformer

Một attention layer trả lời câu hỏi:

Mỗi token nên lấy thông tin từ token nào, với trọng số bao nhiêu?

Một Transformer block trả lời câu hỏi lớn hơn:

Sau khi token lấy context từ token khác, representation của từng token nên được biến đổi và ổn định như thế nào?

Một Transformer model là stack nhiều block:

embedding -> position -> block x N -> output head

2. Shape mental model

Giả sử:

batch_size = B
sequence_length = T
hidden_dim = H
num_heads = A
head_dim = D = H / A

Shape thường gặp:

TensorShapeÝ nghĩa
input_ids[B, T]Token ids
token_embeddings[B, T, H]Vector input
Q/K/V[B, A, T, D]Query/Key/Value theo head
attention_scores[B, A, T, T]Mỗi token attend đến token khác
attention_output[B, T, H]Contextual vectors
FFN intermediate[B, T, 4H] hoặc biến thểHidden mở rộng
logits classifier[B, num_labels]Output classification
logits LM[B, T, vocab_size]Output language modeling

3. Encoder-only reference

input_ids
  -> embedding + position
  -> bidirectional self-attention blocks
  -> pooled output hoặc token outputs
  -> task head

Đặc điểm:

  • Mọi token thấy mọi token trong input, trừ padding.
  • Output là vector contextual.
  • Thường cần task-specific head.

Use cases:

  • Classification.
  • Embedding.
  • Reranking.
  • NER.
  • Similarity scoring.

Rủi ro:

  • Dùng sai tokenizer làm quality giảm mạnh.
  • Truncate input làm mất thông tin quyết định.
  • Dùng model multilingual/tiếng Việt không phù hợp domain.
  • Deploy không pin label mapping gây đảo nhãn.

4. Decoder-only reference

prompt tokens
  -> embedding + positional strategy, thường RoPE
  -> causal self-attention blocks
  -> language modeling head
  -> next-token logits
  -> decoding loop

Đặc điểm:

  • Token chỉ thấy quá khứ.
  • Output tự nhiên là text.
  • Inference sinh token tuần tự.

Use cases:

  • Chat.
  • RAG generation.
  • Tool/function calling.
  • Code generation.
  • Summarization linh hoạt.

Rủi ro:

  • Output không deterministic nếu sampling.
  • Prompt injection khi input có nội dung không tin cậy.
  • Token cost tăng theo input và output.
  • KV cache làm VRAM tăng theo concurrent sessions.
  • Long context có thể làm latency và cost vượt SLA.

5. Encoder-decoder reference

source tokens
  -> encoder bidirectional blocks
  -> encoder hidden states
target prefix tokens
  -> decoder causal self-attention
  -> cross-attention to encoder hidden states
  -> next target token

Đặc điểm:

  • Encoder hiểu input nguồn.
  • Decoder sinh output target.
  • Cross-attention nối output đang sinh với source representation.

Use cases:

  • Translation.
  • Summarization.
  • Data-to-text.
  • Text normalization.
  • Structured text generation cho domain ổn định.

Rủi ro:

  • Serving vẫn có decode loop.
  • Fine-tune cần cặp input-output tốt.
  • Với chatbot tổng quát, decoder-only instruction model thường có ecosystem mạnh hơn.

6. Positional strategies

StrategyCách hoạt độngKhi gặp trong thực tếGhi chú production
SinusoidalCộng sin/cos vector vào embeddingTransformer gốc, bài họcDễ hiểu, ít dùng trực tiếp trong LLM mới
Learned absoluteHọc vector cho từng vị tríBERT-style modelKhông vượt max length tùy tiện
Relative position biasBias theo khoảng cáchT5-style hoặc biến thểCần đúng implementation
RoPERotate Q/K theo positionLLaMA/Qwen-style LLMContext scaling cần eval
ALiBiBias tuyến tính theo khoảng cáchMột số long-context modelHữu ích cho extrapolation trong vài setting

7. LayerNorm placement

Post-LN:

x -> sublayer -> residual add -> LayerNorm

Pre-LN:

x -> LayerNorm -> sublayer -> residual add

Khi dùng pretrained model:

  • Không đổi Pre-LN/Post-LN.
  • Không đổi epsilon hoặc norm type nếu không có lý do và eval.
  • Một số LLM dùng RMSNorm thay vì LayerNorm; vai trò vẫn là ổn định activation.

8. FFN variants

FFN cổ điển:

Linear -> GELU/ReLU -> Linear

Gated FFN:

Linear gate + Linear up -> activation/gating -> Linear down

MoE FFN:

router chọn một vài expert FFN cho mỗi token

Trade-off:

  • FFN lớn tăng capacity nhưng tăng memory/latency.
  • Gated FFN thường mạnh hơn MLP đơn giản nhưng tốn compute.
  • MoE tăng parameter tổng nhưng có thể giữ activated parameters thấp; serving phức tạp hơn.

9. Inference constraints

Latency

TaskKiến trúc thường hợpLatency driver
ClassificationEncoder-onlyInput length, batch size, device
Embedding searchEncoder/bi-encoderQuery encode + vector DB latency
RerankingEncoder cross-encoderSố candidate cần rerank
ChatDecoder-onlyContext length + output tokens
SummarizationDecoder-only hoặc encoder-decoderInput length + output tokens

Memory

Memory gồm:

  • Model weights.
  • Activation khi training.
  • KV cache khi decoder inference.
  • Batch buffers.
  • Runtime overhead.

Approximation thường dùng:

FP16 weights memory ~= parameters * 2 bytes
7B params FP16 ~= 14 GB chỉ riêng weights

KV cache có thể vượt weights bottleneck khi:

  • Context dài.
  • Batch/concurrency cao.
  • Số layer/head lớn.
  • Session streaming lâu.

Context length

Context dài giúp nhét nhiều thông tin hơn nhưng:

  • Attention/prefill đắt hơn.
  • KV cache lớn hơn.
  • Dễ mất thông tin ở giữa.
  • Cost tăng.
  • Debug khó hơn.

Rule thực dụng:

RAG tốt + context vừa đủ thường production-friendly hơn long context không kiểm soát.

10. Architecture decision matrix

Use caseDefault architectureVì saoKhi đổi hướng
Semantic searchEncoder embedding modelPrecompute document vectors, query nhanhThêm cross-encoder reranker nếu relevance chưa đủ
Ticket classificationEncoder-only classifierNhanh, output ổn định, dễ đo metricDùng decoder-only khi label thay đổi liên tục và volume thấp
ChatbotDecoder-only chat modelSinh text tự nhiên, hỗ trợ instruction/toolDùng nhỏ hơn/hosted nếu cost hoặc ops là bottleneck
Summarization batchEncoder-decoder hoặc decoder-onlySeq2seq rõ ràng hoặc prompt linh hoạtChunk/hierarchical nếu document dài
RAG assistantEncoder retrieval + decoder generationTách retrieval và generationRerank nếu citation sai hoặc recall thấp
NEREncoder-only token classifierCần vector từng tokenLLM extraction chỉ khi schema thay đổi và volume thấp

11. Production readiness checklist

  • Task và output contract đã rõ.
  • Baseline đơn giản đã có.
  • Architecture được chọn theo latency/cost/privacy/license, không theo hype.
  • Dataset/eval set có dữ liệu thật và edge cases.
  • Metric chính đã rõ: accuracy, F1, MRR, nDCG, ROUGE, factuality, latency hoặc cost.
  • Tokenizer/model/config được pin version.
  • License model được xác nhận.
  • Data privacy policy rõ: input nào được gửi ra ngoài, input nào phải self-host.
  • Token budget và max context được cấu hình.
  • Với decoder-only, có KV cache strategy, streaming và timeout.
  • Có observability: model version, token count, truncation, latency, errors, quality feedback.
  • Có rollback plan.
  • Có human review cho high-risk output.

12. Common failure modes

Failure modeThường gặp ởDấu hiệuCách giảm rủi ro
Mask saiTraining custom TransformerData leakage, metric quá đẹpUnit test mask
Tokenizer mismatchTất cảQuality giảm khó hiểuPin tokenizer cùng model
Label mapping saiClassificationLabel đảo hoặc sai ngẫu nhiênLưu id2label/label2id trong artifact
Context quá dàiDecoder-only/RAGp99 cao, OOM, cost tăngToken budget, retrieval, truncation policy
KV cache OOMChat servingRequest lỗi khi concurrency tăngLimit sessions, batching, paged KV cache runtime
License không rõModel Hub/public weightsKhông deploy được commercialReview model card/license trước
Prompt injectionRAG/tool chatbotTool gọi sai, lộ dataInstruction hierarchy, tool allowlist, input isolation
HallucinationGenerationCâu trả lời không có nguồnCitation, retrieval eval, refusal policy

13. Glossary

Thuật ngữGiải thích ngắn
EmbeddingVector biểu diễn token
Hidden dimensionKích thước vector nội bộ
HeadMột attention subspace
Multi-head attentionNhiều attention head song song
Causal maskMask không cho token nhìn tương lai
Bidirectional attentionToken thấy cả trái và phải trong input
Cross-attentionDecoder attend vào encoder output
Positional encodingCách thêm thứ tự token
RoPERotary Position Embedding
LayerNormNormalize activation theo hidden dimension
FFNFeed-forward network áp dụng từng token
Residual connectionCộng input với output sublayer
KV cacheCache Key/Value cũ trong decoder inference
PrefillPha xử lý prompt/context ban đầu
DecodePha sinh từng token output
Context lengthSố token tối đa model có thể xử lý
Token budgetGiới hạn token thiết kế cho request

14. Tài liệu nên đọc

  • "Attention Is All You Need": đọc architecture, scaled dot-product attention, multi-head attention, positional encoding và encoder-decoder stack.
  • "The Illustrated Transformer": đọc để hình dung luồng dữ liệu.
  • "The Annotated Transformer": đọc nếu muốn mapping công thức sang code.
  • Model cards của BERT/PhoBERT/LLaMA/Qwen/T5 trước khi dùng trong dự án thật.

Khi đọc, không chỉ hỏi "model có mạnh không". Hãy hỏi:

Model này có đúng task, đúng dữ liệu, đúng license, đúng latency và đúng vận hành không?

Bài tập

Cách làm

Làm theo thứ tự. Mục tiêu không phải nhớ tên architecture, mà là ra quyết định kỹ thuật hợp lý cho production.

Phần 1: Quiz nhanh

Trả lời ngắn, mỗi câu 2-4 dòng.

  1. Vì sao Transformer cần positional encoding hoặc positional strategy?
  2. Encoder-only khác decoder-only ở attention mask như thế nào?
  3. Vì sao decoder-only model sinh text chậm hơn khi output dài?
  4. KV cache lưu gì? Nó giảm compute nào và tăng chi phí nào?
  5. FFN trong Transformer làm gì nếu attention mới là nơi mix token?
  6. Residual connection giúp gì cho gradient flow?
  7. Khi nào BERT/PhoBERT hợp lý hơn GPT/LLaMA/Qwen?
  8. Khi nào T5 hoặc encoder-decoder hợp lý hơn decoder-only?
  9. Vì sao context dài không tự động làm RAG tốt hơn?
  10. Trước khi dùng model open-weight trong công ty, cần check license và data privacy như thế nào?

Phần 2: Vẽ lại Transformer block

Vẽ lại bằng ASCII diagram một block Pre-LN gồm:

  • Input x.
  • LayerNorm.
  • Multi-head self-attention.
  • Residual connection.
  • LayerNorm.
  • FFN.
  • Residual connection.
  • Output.

Mẫu khởi đầu:

x
|\
| LayerNorm -> Attention -> ...
|___________________________+

Sau khi vẽ, giải thích từng mũi tên bằng 1 câu.

Phần 3: Điền bảng architecture

Điền bảng sau cho 6 bài toán:

Bài toánArchitecture chọnLý doKhông chọn gìRủi ro production
Sentiment classification tiếng Việt
Semantic search tài liệu nội bộ
Rerank top 50 documents trong RAG
Chatbot CSKH có tool tra cứu đơn hàng
Summarize hợp đồng dài 80 trang
Extract NER từ ticket support

Gợi ý:

  • Output label/vector/score thường nghiêng về encoder.
  • Output text tự do thường nghiêng về decoder-only hoặc encoder-decoder.
  • Seq2seq input-output rõ ràng có thể nghiêng về encoder-decoder.

Phần 4: Case study production decision

Bạn là AI Engineer cho một công ty thương mại điện tử. Team cần 4 tính năng:

  1. Classify ticket thành refund, shipping, payment, account.
  2. Semantic search trong policy nội bộ.
  3. Chatbot trả lời khách hàng dựa trên policy và trạng thái đơn hàng.
  4. Summarize cuộc hội thoại dài thành ghi chú cho nhân viên CSKH.

Ràng buộc:

  • 1 triệu ticket/tháng.
  • p95 latency cho classification dưới 150 ms.
  • Chatbot được phép p95 first token dưới 2 giây và stream sau đó.
  • Dữ liệu đơn hàng có PII, không được gửi sang provider nếu chưa có DPA.
  • Budget GPU hạn chế.
  • Cần audit được model version và prompt version.

Hãy viết một Architecture Decision Record ngắn theo mẫu:

# ADR: Chọn Transformer architecture cho hệ thống CSKH

## Context
...

## Decision
- Classification:
- Semantic search:
- Chatbot:
- Summarization:

## Trade-offs
- Latency:
- Cost:
- Data privacy:
- License:
- Quality:

## Production conditions
- Eval:
- Serving:
- Monitoring:
- Rollback:
- Security:

Điểm cần có trong câu trả lời:

  • Classification không nên mặc định dùng decoder-only nếu encoder đáp ứng tốt hơn về latency/cost.
  • Semantic search nên tách embedding retrieval và optional reranker.
  • Chatbot nên dùng decoder-only nhưng phải có RAG, tool allowlist, output policy và streaming.
  • Summarization có thể dùng decoder-only hoặc encoder-decoder tùy format ổn định và hạ tầng.
  • Phải nêu điều kiện production rõ ràng.

Phần 5: Token budget và serving constraints

Tính nhẩm và ghi nhận xét.

Giả sử chatbot dùng decoder-only model:

system prompt: 500 tokens
conversation history: 1,500 tokens
retrieved context: 3 chunks x 700 tokens = 2,100 tokens
tool result: 400 tokens
expected answer: 500 tokens
  1. Tổng input tokens trước khi sinh output là bao nhiêu?
  2. Tổng tokens gồm cả output dự kiến là bao nhiêu?
  3. Nếu p95 latency vượt SLA, bạn sẽ giảm phần nào trước?
  4. Nếu answer hay thiếu citation, bạn sẽ tăng context hay cải thiện retrieval/reranking trước? Vì sao?
  5. Nếu VRAM OOM khi concurrency tăng, KV cache liên quan thế nào?

Gợi ý trả lời:

  • Đừng chỉ tăng context length.
  • Kiểm tra token distribution và truncation rate.
  • Ưu tiên chunk quality, reranking, dedup và prompt ngắn gọn.
  • Limit conversation history bằng summary hoặc memory policy.

Phần 6: Checklist đọc paper/model card

Chọn một model bất kỳ trong 3 nhóm:

  • Encoder-only: BERT, RoBERTa, PhoBERT hoặc embedding model.
  • Decoder-only: GPT-style, LLaMA, Qwen hoặc Mistral-style model.
  • Encoder-decoder: T5 hoặc BART-style model.

Điền checklist:

Model name:
Architecture group:
Training objective:
Supported language/domain:
Context length:
Positional strategy:
License:
Intended use:
Limitations:
Hardware/serving notes:
Production fit for my use case:
Risks:
Decision: use / evaluate further / reject

Phần 7: Đáp án tham khảo ngắn

Không đọc phần này trước khi tự làm.

  1. Transformer cần positional information vì self-attention không tự biết thứ tự token; cùng tập token nhưng thứ tự khác có thể đổi nghĩa.
  2. Encoder-only dùng bidirectional attention; decoder-only dùng causal mask để không nhìn future tokens.
  3. Decoder-only sinh từng token tuần tự; output càng dài thì decode loop càng dài.
  4. KV cache lưu Key/Value của token trước trong các layer; giảm việc tính lại K/V nhưng tốn VRAM.
  5. FFN biến đổi representation từng token sau khi attention đã đưa context vào.
  6. Residual connection giúp signal và gradient đi qua nhiều layer dễ hơn, layer học delta thay vì học lại toàn bộ.
  7. BERT/PhoBERT hợp lý hơn cho classification, embedding, NER, reranking khi cần latency/cost tốt và output ổn định.
  8. T5/encoder-decoder hợp lý cho translation/summarization/text normalization khi input-output rõ ràng và format ổn định.
  9. Context dài tăng cost/latency và có thể lost-in-the-middle; retrieval/reranking tốt thường hiệu quả hơn.
  10. Cần kiểm tra license commercial/internal use, data policy, PII, retention, provider DPA, model version và audit trail.

Phần 8: Tiêu chí hoàn thành

Bạn hoàn thành Day 14 khi:

  • Vẽ được Transformer block không cần nhìn tài liệu.
  • Phân biệt được encoder-only, decoder-only và encoder-decoder theo mask/objective/output.
  • Giải thích được positional encoding, RoPE, LayerNorm, FFN và residual connection.
  • Viết được ADR chọn architecture cho ít nhất 2 use cases.
  • Trả lời rõ "Dùng được trong production không? Nếu có thì cần điều kiện gì?".
  • Chuẩn bị được quyết định cho Day 16: classification tiếng Việt nên bắt đầu bằng baseline đơn giản rồi encoder-only BERT/PhoBERT-style model.