পর্ব ২১ · LLM-এর ক্যালকুলাস

ট্রান্সফর্মার অপ্টিমাইজেশন

Attention-এর গ্রেডিয়েন্ট ও স্কেলিং

শেখার লক্ষ্য

  • Self-attention-এর ডেরিভেটিভ
  • Scaled dot-product-এর কারণ
  • AdamW, warmup, weight decay

Self-Attention সংক্ষেপ

\text{Attn}(Q, K, V) = \text{softmax}\!\left(\tfrac{QK^\top}{\sqrt{d_k}}\right) V

Q, K, V ইনপুট থেকে linear projection।

√dₖ স্কেলিং কেন?

Q ও K-এর dot product-এর variance dₖ-এর সঙ্গে বাড়ে। বড় value softmax-কে saturate করে → gradient ~0।

√dₖ দিয়ে ভাগ করে variance ≈ 1 রাখা হয় — gradient flow স্থিতিশীল।

Softmax-এর গ্রেডিয়েন্ট

\frac{\partial s_i}{\partial z_j} = s_i(\delta_{ij} - s_j)

Saturate হলে gradient → 0 (vanishing); তাই scaling গুরুত্বপূর্ণ।

AdamW + Warmup

Transformer-এ Adam-এর L2 ও weight decay coupling ক্ষতিকর — AdamW আলাদা করে।

Linear warmup (প্রথম কয়েক হাজার step) → cosine decay; প্রথমদিকে LayerNorm/embedding stable হওয়া দরকার।

Memory-Efficient Attention

FlashAttention: tiling + online softmax — O(N²) memory → O(N), gradient সহ।

Sequence length বাড়াতে সরাসরি সাহায্য করেছে।