পাঠ ২০ · ২৮-এর মধ্যে · মডিউল ৪
Home / AI Courses / Generative AI / Text generation

Text generation — LLM-এর কাজ

Text generation with LLMs — sampling, decoding, Bangla
৭ মিনিট পড়া মধ্যবর্তী · Intermediate transformers কোডসহ

এই পাঠে যা শিখবেন

  • Autoregressive decoding কী — token by token text generate-এর গণিত
  • Temperature, top-k, top-p sampling — কীভাবে output-এর creativity তুলনা/কমানো
  • Beam search — কখন উপকারী, কখন bland output দেয়
  • HuggingFace transformers দিয়ে বাংলা text generation — Colab-এ চালানোর কোড

১ · LLM-এর মূল কাজ — next token prediction

একটি LLMLarge Language Modelবিলিয়ন প্যারামিটারের transformer যা billion-trillion token-এ pretrain হয়েছে। GPT, Claude, Gemini, Llama সবই LLM। যা করে — শুধু একটাই কাজ। দেওয়া context-এর পরে কোন token সবচেয়ে likely? গাণিতিকভাবে: $P(x_t \mid x_1, x_2, \ldots, x_{t-1})$।

"আমি বাজারে যাচ্ছি ___" — এর পরে "মাছ", "শাক", "তরকারি" — এদের probability বেশি। "চাঁদ" বা "পাহাড়"-এর probability কম। মডেল প্রতিটি সম্ভাব্য token-এর উপর একটি probability distribution দেয় — vocabulary-র সব ৫০,০০০-১,৫০,০০০ token-এর উপর।

Autoregressive loop

১) Input prompt → tokenize → token IDs।
২) Model forward pass → logits → softmax → next-token distribution।
৩) Sampling strategy দিয়ে একটি token বাছুন।
৪) সেই token প্রসঙ্গে যোগ → step ২-এ ফিরে যান।
৫) <eos> token বা max_length পেলে থামুন।

২ · Temperature — randomness-এর dial

Softmax-এ একটি প্যারামিটার $T$ থাকে: $$P(x_i) = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}$$

  • $T \to 0$ — distribution sharp; argmax-এর কাছে যায় (greedy)।
  • $T = 1$ — মূল distribution।
  • $T > 1$ (যেমন ১.৫) — flatter; rare token-গুলোও বেশি chance পায় → creative কিন্তু incoherent।
Temperature = রান্নার আগুন। কম আঁচে নিরাপদ কিন্তু একঘেয়ে। বেশি আঁচে নতুন স্বাদ — কিন্তু পুড়িয়ে ফেলার ঝুঁকি।

৩ · Top-k এবং Top-p (nucleus) sampling

Pure temperature-এ একটা সমস্যা: rare ও silly token কখনও কখনও বেছে নেওয়া হয়। সমাধান — truncated sampling।

  • Top-k: probability-র দিক থেকে top $k$ token রাখুন (যেমন $k=50$), বাকিদের probability শূন্য করে renormalize।
  • Top-p (Holtzman 2019, "The Curious Case of Neural Text Degeneration"): ছোট থেকে বড় token-এর cumulative probability $\geq p$ (যেমন $p=0.9$) যত token লাগে — শুধু সেগুলো রাখুন। Distribution-এর shape অনুযায়ী set size বদলায়।
Production-এ সাধারণত combo: temperature=0.7, top_p=0.9 — moderate creativity, no garbage। OpenAI-র default প্রায় এই।

৪ · Greedy বনাম Beam search

Greedy: প্রতি step-এ argmax token নিন। দ্রুত কিন্তু locally optimal — globally weak।

Beam search: top-$B$ partial sequence একসাথে track করুন (beam width $B$=৪ সাধারণ)। শেষে সর্বোচ্চ joint probability-র একটি বাছুন। Translation, summarization-এ ভাল। কিন্তু creative writing-এ — bland, repetitive ("repetition trap")।

৫ · Repetition penalty ও অন্যান্য কৌশল

  • Repetition penalty (Keskar 2019): already-seen token-এর probability ভাগ করুন (যেমন ১.১ দিয়ে)।
  • No-repeat n-gram: একই $n$-gram দ্বিতীয়বার ব্যান।
  • Min/max length: output bound।
  • Logit bias: নির্দিষ্ট token-কে favour/discourage।
Autoregressive loop — token by token "আমি বাজারে যাচ্ছি ___" Prompt → Tokens [আমি, বাজারে, যাচ্ছি] Transformer LLM forward pass → logits over vocab Softmax distribution মাছ শাক … Sampling strategy temperature=0.7, top_p=0.9 → choose: "মাছ" (or beam, greedy, top-k) Append token → context grows […যাচ্ছি, মাছ] loop until <eos> Final: "আমি বাজারে যাচ্ছি মাছ কিনতে।" প্রতিটি token = এক forward pass + এক sample
Autoregressive decoding — context → logits → sample → append → repeat।

৬ · HuggingFace transformers — বাংলায় text generate

Python · transformers
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

# একটি multilingual model — বাংলা বোঝে
model_name = "google/gemma-2-2b"  # বা "meta-llama/Llama-3.2-3B"
tok = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")

prompt = "ঢাকা শহরের যানজট নিয়ে একটি ছোট কবিতা লিখুন:\n"
inputs = tok(prompt, return_tensors="pt").to(model.device)

# Top-p sampling
out = model.generate(
    **inputs,
    max_new_tokens=120,
    do_sample=True,
    temperature=0.7,
    top_p=0.9,
    repetition_penalty=1.1,
)
print(tok.decode(out[0], skip_special_tokens=True))

    
do_sample=True ছাড়া default greedy। Bangla quality model-ভেদে আলাদা — Gemma, Aya-23, Llama 3 ভাল করে। মাঝারি model Colab T4 GPU-তে চলে।

৭ · Sampling তুলনা — একই prompt, ভিন্ন output

Python · sampling comparison
# একই prompt — তিন সেটিং
configs = [
    {"name": "Greedy",    "do_sample": False},
    {"name": "Low temp",  "do_sample": True, "temperature": 0.3, "top_p": 0.9},
    {"name": "High temp", "do_sample": True, "temperature": 1.3, "top_p": 0.95},
]

prompt = "বাংলাদেশের অর্থনীতি নিয়ে এক বাক্য:\n"
inputs = tok(prompt, return_tensors="pt").to(model.device)

for c in configs:
    name = c.pop("name")
    out = model.generate(**inputs, max_new_tokens=40, **c)
    print(f"[{name}] {tok.decode(out[0], skip_special_tokens=True)}\n")

    
বাংলা LLM-এর tokenization ইংরেজির চেয়ে inefficient — এক বাংলা শব্দ ৩-৫ token নিতে পারে। তাই max_new_tokens পরিমিতভাবে set করুন; cost ও latency দু'টোই বাড়ে।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ Beam search machine translation-এ ভাল কিন্তু creative writing-এ "bland" — কেন? Holtzman et al. 2019-এর "neural text degeneration" পেপার কী আবিষ্কার করেছিল?

Holtzman et al. (২০১৯, ICLR-এ "The Curious Case of Neural Text Degeneration") একটি counter-intuitive তথ্য দেখাল — মানুষের তৈরি text-এ token-গুলো সবসময় "highest-probability" নয়। মানুষ মাঝে মাঝে rare শব্দ ব্যবহার করে।

কেন beam bland হয়:

  • Beam globally high-probability sequence খোঁজে। Probability-র দিক থেকে "নিরাপদ" token-গুলো দিয়ে ভরে।
  • একই ধরনের vocabulary ও phrasing recur — generic, "GPT-2 sounding" output।
  • Long generation-এ beam প্রায় সবসময় repeat — "I am a I am a I am a"।

Translation-এ কেন কাজ করে:

  • Translation-এ valid output-এর space ছোট ও constrained — input meaning নির্দিষ্ট।
  • Beam high-likelihood sequence-গুলোই সেখানে correct হবে।
  • BLEU score-এ greedy-এর চেয়ে beam ১-২ পয়েন্ট ভাল।

Creative writing-এ সমাধান:

  • Top-p (nucleus) sampling — distribution-এর "head" থেকে বাছে কিন্তু variation রাখে।
  • Temperature ০.৭-০.৯ — moderate randomness।
  • Repetition penalty ১.০৫-১.২।

Modern context:

  • ChatGPT/Claude default sampling-ই করে — কখনো beam নয়।
  • Code generation-এ greedy / low-temp ভাল (deterministic দরকার)।
  • ২০২৩-এ "Speculative decoding" — small draft model দিয়ে দ্রুত — কিন্তু output identical to target sampling।
  • ২০২৪-এ "contrastive decoding", "DoLa", "DRY" — repetition কমানোর নতুন কৌশল।

মূল উপলব্ধি: Decoding শুধু engineering নয় — language-এর nature-এর প্রতিফলন। Probability সর্বোচ্চ মানে "best" নয়।

প্র ০২ বাংলা LLM ইংরেজি LLM-এর তুলনায় অনেক পিছিয়ে। কারণ কী — ডেটা, tokenization, scaling laws, না অন্য কিছু? কীভাবে কমানো সম্ভব?

বাংলা ২৭০ মিলিয়ন speaker — বিশ্বের ৬ষ্ঠ। কিন্তু LLM quality-তে বিরাট পার্থক্য। কারণ multifaceted।

(১) Pretraining data scarcity:

  • Common Crawl-এর ~৪৬% English; বাংলা ০.৩%।
  • Wikipedia: ইংরেজি ৬.৭M articles, বাংলা ১৫০K।
  • High-quality বাংলা corpus (Prothom Alo, BBC Bangla) license-restricted।
  • Code, math, scientific বাংলায় nearly absent।

(২) Tokenization inefficiency:

  • BPE/SentencePiece English-centric। বাংলা শব্দ "বাংলাদেশ" → ৩-৫ token; English "Bangladesh" → ১-২ token।
  • Effective context window অর্ধেক।
  • Inference cost ২-৩x বেশি।
  • Pretraining-এ same compute → অর্ধেক "data" pass।

(৩) Scaling laws:

  • Hoffmann (Chinchilla 2022) — performance ∝ data volume। কম ডেটা = কম performance।
  • Cross-lingual transfer সাহায্য করে কিন্তু সমান নয়।

(৪) Evaluation gap:

  • MMLU, HumanEval, GSM8K — সব ইংরেজি।
  • বাংলা benchmark কম: BanglaBERT, BLOOM eval, MIRACL retrieval।
  • Quality measure করতে না পারলে improve করা কঠিন।

সমাধান:

  • Aya (Cohere 2024): ১০১ ভাষায় instruction-tuned — বাংলা চমৎকার।
  • BanglaT5, mT5, NLLB-200: Bangla-specific বা multilingual।
  • Continued pretraining: Llama-3 → বাংলা corpus-এ extra training।
  • Better tokenizer: বাংলা-aware SentencePiece (Tigrinya, Sinhala, Bangla focus)।
  • BUET, IUB, BRAC group-গুলোর কাজ: BanglaBERT, Bangla-LLaMA।
  • Synthetic data: GPT-4 দিয়ে বাংলা instruction generate → smaller model train।

Modern context: Gemini ও Claude ৩+ বাংলায় production-ready। কিন্তু open-source side-এ এখনো gap।

মূল উপলব্ধি: বাংলা LLM-এর সমস্যা শুধু গবেষণা নয় — এটি linguistic equity ও digital sovereignty-র প্রশ্ন।

প্র ০৩ একই prompt, একই sampling settings — তবু GPT-4 প্রতিবার ভিন্ন output দেয়। Reproducibility কীভাবে অর্জন? "Temperature 0" সত্যিই deterministic?

Reproducibility production-এ গুরুত্বপূর্ণ — A/B test, debug, regulatory audit সব এর উপর নির্ভরশীল। কিন্তু LLM stochastic nature ও infrastructure-এর কারণে subtle।

Determinism-এর শর্ত:

  • Temperature 0 + greedy: argmax — তাত্ত্বিকভাবে deterministic।
  • Same model weights, same hardware, same batch size: bit-for-bit identical চাই।

কেন তবু আলাদা:

  • Floating-point non-associativity: $a + b + c \neq c + b + a$ in float32। GPU parallel reduction order data-dependent — batch size বদলালে output বদলায়।
  • Mixed precision (fp16, bf16): rounding error accumulate।
  • Tensor-parallel sharding: different GPU sharding → different reduction order।
  • Provider-side updates: OpenAI/Anthropic silently model swap, weight update, infra change।
  • Tie-breaking: দু'টি token equal logit → deterministic tiebreak প্রয়োজন (ID-order, etc)।

সমাধান:

  • OpenAI seed parameter (২০২৩): "best-effort determinism"। Same seed + same model = reproducible — কিন্তু provider-side change-এ হারায়।
  • system_fingerprint: infrastructure version track।
  • Self-hosted (Llama, Mistral): own hardware → fix batch size, fp32, single GPU → bit-exact reproduce।
  • vLLM, TGI: reproducibility flag আছে।
  • Cache responses: LangChain, Helicone — same prompt → cached output।

Best practice:

  • Test/eval-এ temperature=0 + seed + version pin।
  • Production-এ caching for repeat queries।
  • Critical workflow-এ output-এর hash log রাখুন।
  • Regulator (FDA, EU AI Act) চাইলে — log full input/output/version।

মূল উপলব্ধি: "Deterministic LLM" — পরিবেশ-নির্ভর। Self-host → strong; API → best-effort। Reproducibility design-এর প্রথম ধাপে চিন্তা করুন।

প্র ০৪ Pathao-র জন্য একটি customer service chatbot বানাচ্ছেন — বাংলায়। ChatGPT API, self-hosted Llama, Gemini — কোনটা বাছবেন? Trade-off কী?

Production deployment-এ technical, business, regulatory দিক সব মাথায় রাখতে হয়। সাধারণ "GPT-4 use করুন" — naive answer।

Option A · OpenAI GPT-4o / Claude 3.5 / Gemini API:

  • ✅ Bangla quality top-tier।
  • ✅ Zero infra — দ্রুত ship।
  • ✅ Built-in safety, function calling।
  • ❌ Cost: $0.005-$0.03 per 1K token — ১০K request/day-এ মাসিক $৫০০-$৫০০০।
  • ❌ Latency ১-৩ second — Bangladesh থেকে।
  • ❌ Data privacy — customer PII US server-এ যাচ্ছে।
  • ❌ Rate limit, downtime, model deprecation risk।

Option B · Self-hosted Llama 3 / Mistral / Aya-23:

  • ✅ Cost-predictable — GPU rent ($৩০০-$১৫০০/month)।
  • ✅ Data on-premise — DPA compliance সহজ।
  • ✅ Latency বাংলাদেশ DC-তে ২০০ms সম্ভব।
  • ✅ Customization — Pathao FAQ-তে fine-tune।
  • ❌ Bangla quality GPT-4-এর চেয়ে কম — Aya-23 ৮B ভাল but not parity।
  • ❌ MLOps team লাগবে।
  • ❌ Scale up/down infra burden।

Option C · Hybrid:

  • Common queries → small self-hosted model।
  • Edge cases / complex queries → GPT-4 fallback।
  • Cost ৬০-৮০% কম, quality high।
  • Routing logic + caching দরকার।

আমার সুপারিশ Pathao-র জন্য:

  • Phase 1 (০-৩ মাস): Claude / GPT-4 API + RAG over Pathao FAQ। দ্রুত launch, learning gather।
  • Phase 2 (৩-৬ মাস): Volume বাড়লে — fine-tune Aya-23 বা Llama-3 on logs। Cost ৭০% কমবে।
  • Phase 3 (৬+ মাস): Self-hosted primary, API fallback for hard queries।

Other considerations:

  • Voice: অনেক Bangladeshi আরামে type-এর চেয়ে voice-এ — Whisper + TTS integration।
  • Bangla code-switch: "Pathao ride টা cancel করতে চাই" — model mixed handle করে কি?
  • Hallucination control: RAG + citation + structured output essential।
  • Escalation: uncertain → human agent।
  • Logging + feedback loop: low-rated answers retrain।

মূল কথা: "কোন model" — wrong question। সঠিক question: "কোন architecture (RAG, fine-tune, hybrid) এই use case-এ accuracy/cost/privacy balance করে?"

অনুশীলন

  1. হাতে হিসাব: Logits $z = (2.0, 1.0, 0.5, -1.0)$ — token A, B, C, D।
    • $T=1$-এ softmax probability কত?
    • $T=0.5$-এ A-র probability কত? (sharp হবে কেন?)

    $T=1$: $\exp(z) \approx (7.39, 2.72, 1.65, 0.37)$, sum ≈ ১২.১৩। তাহলে probabilities $\approx (0.61, 0.22, 0.14, 0.03)$।

    $T=0.5$: $z/T = (4, 2, 1, -2)$, $\exp \approx (54.6, 7.39, 2.72, 0.14)$, sum ≈ ৬৪.৮৪। A-র probability $\approx 0.84$ — অনেক sharp।

    Temperature কম → distribution sharp → top token-এর probability বাড়ে।

  2. HuggingFace দিয়ে চেষ্টা: Colab-এ Gemma-2-2b বা Llama-3.2-1B load করে একই বাংলা prompt-এ greedy, top-p=0.9, top-p=0.99 — তিন version output তুলনা।
    for tp in [None, 0.9, 0.99]:
        kwargs = {"do_sample": tp is not None}
        if tp: kwargs["top_p"] = tp; kwargs["temperature"] = 0.8
        out = model.generate(**inputs, max_new_tokens=80, **kwargs)
        print(tp, "→", tok.decode(out[0], skip_special_tokens=True))

    Greedy — repetitive। 0.9 — smooth, on-topic। 0.99 — wild but creative।

  3. ভাবুন: Pathao chatbot-এ temperature কত set করবেন? FAQ answer দেওয়ার জন্য vs casual conversation-এ।
    • FAQ / factual: temperature=0 বা 0.2 — accuracy critical, hallucination নিষিদ্ধ।
    • Greeting / small talk: 0.7-0.9 — natural variation।
    • Apology / empathy: 0.5-0.7 — sincere কিন্তু not robotic।
    • Same chatbot-এ — task-conditional temperature recommend।

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, GPU access সহ।
পূর্ববর্তী পাঠ
পাঠ ১৯ · DreamBooth ও LoRA