Positional encoding
এই পাঠে যা শিখবেন
- কেন self-attention নিজে position সম্পর্কে জানে না
- Sinusoidal positional encoding — গাণিতিক সূত্র ও intuition
- Learned PE vs sinusoidal — trade-offs
- RoPE (Rotary) ও ALiBi — modern context extension
- Long context (128K, 1M tokens) — কীভাবে সম্ভব
১ · Self-attention কেন order-blind
Self-attention-এ — input $X = [x_1, x_2, \ldots, x_T]$। Token-গুলো permute করলে — output-ও একই permutation। Math-এ:
$$\text{Attention}(P X) = P \cdot \text{Attention}(X)$$
যেখানে $P$ permutation matrix। ফলে — "আমি ভাত খাই" বনাম "ভাত আমি খাই" — দু'টোতেই same internal representation। কিন্তু ভাষায় order matters!
RNN-এ order natural — sequential processing। CNN-এ position kernel-এর মাধ্যমে। কিন্তু Transformer-এ attention সব pair সমানভাবে dekhে — তাই position info explicitly inject করতে হয়।
২ · Sinusoidal positional encoding (Vaswani)
Vaswani et al.-এ proposed — fixed sinusoidal pattern। প্রতিটি position $pos$ ও dimension $i$ এর জন্য:
$$PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d}}\right)$$ $$PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d}}\right)$$
এই PE token embedding-এর সাথে যোগ:
$$x'_t = x_t + PE_t$$
Frequency intuition: ছোট dimension index → high frequency (rapid sin oscillation), বড় dimension → low frequency (slow change)। এক type position bit-encoding — কিন্তু continuous, smooth।
৩ · কেন এই formula কাজ করে
- Unique encoding: প্রতিটি $pos$-এর unique vector।
- Bounded: $\sin, \cos \in [-1, 1]$ — embedding magnitude-কে dominate করে না।
- Linear relative position: $PE_{pos+k}$ হলো $PE_{pos}$-এর rotation — relative offset $k$ একটি linear transformation দিয়ে express করা যায়। Attention dot-product-এ এই property useful।
- Extrapolation: training-এ যা position দেখেনি — সেখানেও deterministic formula কাজ করে। Theory-তে।
৪ · Learned positional encoding
BERT, GPT-2, ViT — sinusoidal-এর বদলে trainable position embedding। প্রতিটি position $0, 1, \ldots, T_{max}-1$-এর জন্য একটি learnable $d$-dim vector।
Pros: data থেকে optimal pattern শেখে। Sinusoidal-এর fixed structure-এর বাধা নেই।
Cons: $T_{max}$-এর বাইরে generalize করে না। BERT max ৫১২ token — ৫১৩-এ ভেঙে পড়ে।
৫ · Relative positional encoding
Absolute position-এর বদলে relative offset-এ focus। "আমার পাঁচ token পরে কী?" — এই relation matter করে absolute position-এর চেয়ে।
- Shaw et al. (২০১৮): attention score-এ pair-wise position bias add।
- Transformer-XL (২০১৯): recurrence + relative PE।
- T5: bucketed relative position bias।
৬ · RoPE — Rotary Position Embedding
Su et al. (২০২১) — modern LLM-এর favorite (LLaMA, GPT-NeoX, Qwen)। Idea: query ও key vector-কে position-dependent rotation matrix দিয়ে rotate করো।
$$q'_m = R_m q_m, \quad k'_n = R_n k_n$$
যেখানে $R_m$ একটি 2D rotation $m \theta$ angle-এ। তখন dot product:
$$\langle q'_m, k'_n \rangle = q_m^\top R_{n-m} k_n$$
— শুধু relative position $n-m$-এর function। Beautiful। Long-context extrapolation strong, RoPE scaling tricks (NTK, YaRN) দিয়ে ১২৮K+ context সম্ভব।
৭ · ALiBi — Attention with Linear Biases
Press et al. (২০২২) — সবচেয়ে সরল। PE-ই বাদ — শুধু attention score-এ distance-proportional negative bias:
$$\text{score}_{ij} = q_i \cdot k_j - m \cdot |i-j|$$
$m$ — head-specific slope। Distance যত বেশি — attention তত কম। Train short, test long — extrapolation excellent। BLOOM, MPT-এ ব্যবহৃত।
৮ · PyTorch — sinusoidal PE
import torch
import math
def sinusoidal_pe(seq_len, d_model):
pe = torch.zeros(seq_len, d_model)
pos = torch.arange(0, seq_len).unsqueeze(1).float()
div = torch.exp(
torch.arange(0, d_model, 2).float() *
-(math.log(10000.0) / d_model)
)
pe[:, 0::2] = torch.sin(pos * div)
pe[:, 1::2] = torch.cos(pos * div)
return pe
PE = sinusoidal_pe(seq_len=50, d_model=128)
print(PE.shape) # torch.Size([50, 128])
print(PE[0, :8]) # position 0 (zeros and ones)
print(PE[1, :8]) # position 1
# Add to embedding
x = torch.randn(2, 50, 128) # (B, T, d)
x = x + PE.unsqueeze(0) # broadcast over batch
৯ · Long-context — কীভাবে ১M token সম্ভব
- RoPE scaling: base 10000 → 50000+ — frequency stretch।
- NTK-aware scaling: high-freq preserve, low-freq stretch।
- YaRN: NTK + temperature — Mistral, Qwen-এ।
- ALiBi: training short, inference long — naturally।
- Sliding window + global token: Mistral, Longformer।
- Sparse attention: $O(T \log T)$ instead $O(T^2)$।
ভাবনার প্রশ্ন
প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।
প্র ০১ Sinusoidal PE-এ ১০০০০ base — এই particular সংখ্যা কেন? কী হবে যদি ১০০ বা ১,০০০,০০০ ব্যবহার করা হয়?
১০০০০ — paper-এ arbitrary-ish choice। কিন্তু behind-the-scenes implication বড়।
Frequency range:
- Smallest period (dim 0): $2\pi$।
- Largest period (dim $d-1$): $2\pi \cdot 10000$।
- Geometric progression — $d/2$ frequencies।
If base = 100:
- Largest period $2\pi \cdot 100 \approx 628$।
- Position 1000 — very long sequence — pattern repeats।
- Distinguishability fails।
If base = 1,000,000:
- Largest period very long।
- Short sequence — dim ৩০-৪০-এ change negligible।
- Wasted dimensions — gradient signal weak।
10000 sweet spot for typical $T \sim 512$:
- All position uniquely encoded।
- Each dimension contributes meaningfully।
- Empirical balance।
Long context scaling:
- RoPE-এ base 10000 → larger value।
- "Theta scaling" — context extension trick।
- Code-Llama 16K — base $10^6$।
- Yarn paper — controlled scaling।
Frequency-position mapping:
- Bandwidth $\sim 1$ to $1/10000$।
- Sample positions uniformly visible।
- Aliasing avoidance।
Recent insights:
- Long context training — base scaling required।
- Theta search — empirical tuning।
- Different rotation per head possible।
মূল উপলব্ধি: 10000 — typical sequence length-এর জন্য geometric series spans full range। Long context-এ এই value scale করতে হয়। Math-এ Nyquist-like criterion — সব position distinguishable।
প্র ০২ Learned PE BERT-এ ৫১২ token-এ limit। কেন BERT ১,০২৪ token দিয়ে train হয়নি? Long context handle করতে কী করা যায়?
BERT-এর ৫১২ limit — historical + practical reason।
৫১২ কেন:
- Compute cost $O(T^2)$ — ১,০২৪-এ ৪x cost।
- ২০১৮-র GPU memory limit।
- Training data sentence-pair, not document।
- Empirical — ৫১২ most NLP task-এ যথেষ্ট।
Limit cross করার strategy:
(১) Sliding window:
- Document chunk করে — overlap window।
- Aggregate predictions।
- BERT-as-a-feature extractor।
(২) Hierarchical encoding:
- Sentence-level BERT → document-level model।
- Two-stage encoding।
- HAN (Hierarchical Attention Network) inspired।
(৩) Architecture redesign:
- Longformer (Beltagy ২০২০) — sliding window + global token।
- BigBird — sparse attention।
- $O(T)$ instead $O(T^2)$।
- Up to 4096 / 16K tokens।
(৪) PE replacement:
- RoPE-based BERT variant।
- ALiBi extension।
- Train short, infer long।
(৫) Position interpolation:
- Trained position 0..511 → squeeze to 0..1023।
- Linear interpolation।
- Some accuracy loss।
Modern era:
- BERT-old approach replaced।
- Long-context model standard now।
- LLaMA 3 — 128K context।
- Gemini 1.5 — 1M+ context।
Bangla document scenarios:
- Legal document — দীর্ঘ।
- Academic paper — multi-page।
- Social media thread — context history।
- Long-context model essential।
মূল উপলব্ধি: Learned PE-এর limit production constraint। Modern PE (RoPE, ALiBi) extrapolation strong। Long context — architecture + PE coevolution। Bangla NLP-তে long-context demand বাড়ছে।
প্র ০৩ RoPE — relative position rotation দিয়ে encode। Intuitively — কেন rotation? Complex number-এ কী insight?
RoPE — mathematically elegant। Complex number perspective থেকে দেখলে গভীর insight।
2D rotation matrix:
$$R_\theta = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix}$$
Complex number perspective:
- $(x_1, x_2)$ pair → complex $z = x_1 + i x_2$।
- Rotation $R_\theta z = e^{i\theta} z$।
- Multiplication by $e^{i\theta}$ = rotation by $\theta$।
RoPE for position $m$:
- $q'_m = e^{im\theta} q_m$।
- $k'_n = e^{in\theta} k_n$।
- Inner product: $\langle q'_m, k'_n \rangle = q_m^* e^{-im\theta} e^{in\theta} k_n = q_m^* e^{i(n-m)\theta} k_n$।
- Only depends on $n-m$ — relative position!
Multiple frequencies:
- $d/2$ pair — different $\theta$।
- Same as sinusoidal frequency spectrum।
- Different spatial scale capture।
Why rotation good:
- Norm preserved — $|R_\theta v| = |v|$।
- No magnitude distortion।
- Pure orientation change।
- Linear operation — efficient।
Implementation efficient:
- No additional parameter — fixed frequencies।
- $O(d)$ per token vs $O(d^2)$।
- Drop-in attention modification।
Long context extrapolation:
- Position embedding-এর fixed table নেই।
- Continuous formula — যেকোনো position।
- Theta scaling — long context tuning।
LLaMA family:
- RoPE — default since LLaMA 1।
- Position interpolation extend context।
- Theta scaling 10K → 500K (LLaMA 2 32K)।
- YaRN/ABF — further improvements।
Limitations:
- Pre-RoPE training — adaptation needed।
- Very long context — still empirical tuning।
- Position 1M+ — approximation degraded।
মূল উপলব্ধি: RoPE = rotation by position-dependent angle। Inner product → relative position-only। Complex number — most elegant interpretation। Modern LLM standard। Long context dominant approach। Math beauty + practical performance।
প্র ০৪ Bangladesh-এ একটি team Bangla long-form document understanding model design করছে — কোন PE বাছবেন? কেন?
Practical Bangladesh scenario — Bangla long document model। PE choice critical।
Use case constraints:
- Document length variable — ১K থেকে ৫০K word।
- Limited compute — Bangladesh-এ A100 expensive।
- Open-source preferred।
- Bangla-specific data scarce।
Option analysis:
(১) Learned PE (BERT-style):
- ৫১২ limit — short document only।
- Sliding window required।
- Loss of global context।
- Reject for long-form।
(২) Sinusoidal:
- Theoretically extrapolates।
- Practice — degrades beyond training length।
- Not ideal for very long।
(৩) RoPE:
- Strong extrapolation।
- LLaMA, Qwen — modern base।
- Theta scaling extend context।
- Recommended primary choice।
(৪) ALiBi:
- Train short — test long natural।
- Simple implementation।
- BLOOM, MPT validated।
- Strong alternative।
Recommended approach:
Phase 1 — Foundation:
- Start with mBERT or BanglaBERT (short context)।
- Quick prototype, baseline।
Phase 2 — Scale:
- Fine-tune Llama-3-8B (RoPE) on Bangla।
- Long context capable (8K+ default)।
- Theta scaling for 32K।
Phase 3 — Long doc:
- Position interpolation 32K → 128K।
- YaRN technique।
- Test on document QA।
Implementation tip:
# LLaMA fine-tune with extended context
from transformers import AutoModelForCausalLM, AutoConfig
config = AutoConfig.from_pretrained('meta-llama/Llama-2-7b-hf')
config.max_position_embeddings = 32768
config.rope_theta = 500000 # scaling for long context
model = AutoModelForCausalLM.from_pretrained(
'meta-llama/Llama-2-7b-hf',
config=config,
torch_dtype=torch.bfloat16
)
Compute optimization:
- Flash Attention 2 — memory efficient।
- LoRA fine-tuning — parameter efficient।
- QLoRA — 4-bit quantized।
- Single A100 viable।
Bangla-specific:
- Tokenizer extend — Bangla vocabulary।
- SentencePiece BPE retraining।
- Continued pretraining on Bangla corpus।
- Document-level instruction tuning।
Evaluation:
- Bangla document QA benchmark create।
- Long passage retrieval accuracy।
- Position-attention visualization।
- Human evaluation।
Production:
- vLLM serving — efficient long context।
- KV-cache management critical।
- Batch size constrained।
- Cost monitoring।
মূল উপলব্ধি: Long Bangla document — RoPE-based LLaMA fine-tune practical। ALiBi alternative। Position interpolation key trick। Bangladesh constraint — open-source + small compute। Modern PE — long-context viable। Bangla NLP frontier।
অনুশীলন
-
হাতে হিসাব: $d=4$, $pos=2$ — sinusoidal PE-এর ৪টি value কী? (base ১০০০০)
- $i=0$: $\sin(2/10000^0) = \sin(2) \approx 0.909$।
- $i=0$ (cos): $\cos(2) \approx -0.416$।
- $i=1$: $\sin(2/10000^{0.5}) = \sin(2/100) = \sin(0.02) \approx 0.020$।
- $i=1$ (cos): $\cos(0.02) \approx 1.000$।
- PE_2 ≈ [0.909, -0.416, 0.020, 1.000]।
-
NumPy plot: 50 position × 64 dim PE matrix generate করে heatmap visualize।
import numpy as np import matplotlib.pyplot as plt T, d = 50, 64 pos = np.arange(T)[:, None] i = np.arange(d)[None, :] div = np.exp(-(np.log(10000.0) / d) * (i // 2 * 2)) PE = np.zeros((T, d)) PE[:, 0::2] = np.sin(pos * div[:, 0::2]) PE[:, 1::2] = np.cos(pos * div[:, 1::2]) plt.imshow(PE, aspect='auto') plt.xlabel('dim'); plt.ylabel('pos') plt.colorbar(); plt.show() -
চিন্তা: Permutation-equivariant attention — কেন ছবি (image patch) দিয়ে ViT কাজ করতে পারে? Patch order কীভাবে handle?
ViT-এ — ছবি ১৬×১৬ patch-এ কাটা, প্রতিটি patch token। Patch-গুলোর order (left-to-right, top-to-bottom) inject করা হয় learned 2D positional embedding দিয়ে। Without PE — patch shuffle করলেই output unchanged — যা ভুল।
2D PE = row PE + column PE addition। কখনো sinusoidal 2D extension (Rope-2D)। Modern ViT (DINOv2, SigLIP) — RoPE-2D ব্যবহার, image scale invariance ভালো।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ৩৫ · Autoencoder ও VAE পরবর্তী পাঠ Generative model-এ ফিরে — encode/decode paradigm।
- পাঠ ৩৩ · Transformer architecture আগের পাঠ Encoder-decoder structure — যেখানে PE inject।
- NLP & LLM Track গভীরে যান Long context, RoPE scaling, modern LLM।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।