পাঠ ২৮ · ৪০-এর মধ্যে · মডিউল ৪

GRU — সরল বিকল্প

Gated Recurrent Unit
৬ মিনিট পড়া মাঝারি · Intermediate PyTorch hands-on

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

  • GRU-এর ২ gate — reset ও update
  • LSTM-এর সাথে তুলনা — কী simplify হয়েছে
  • GRU equations — হাতে-কলমে
  • PyTorch nn.GRU — production code
  • কখন GRU vs কখন LSTM — practical guideline
  • Bangladesh-এ mobile NLP — GRU-এর সুবিধা

১ · GRU-এর জন্ম

Cho et al. (২০১৪) — একটি Korean group machine translation-এর কাজ করছিল। LSTM ব্যবহারে inference slow, train slow। তারা ভাবল — সব gate কি দরকার? Output gate-এর কী দরকার যদি hidden state সরাসরি output হয়? Forget ও input gate কি merge করা যায়?

ফলে GRU — Gated Recurrent Unit। মাত্র ২ gate, কোনো আলাদা cell state নেই। Performance তবু LSTM-এর কাছাকাছি। ২০১৪-২০১৭-এ NLP-তে dominant ছিল।

GRU simplification

৩ gate → ২ gate: reset + update। cell state + hidden state → শুধু hidden state। Coupled forget-input — $z_t$ ও $1 - z_t$ দিয়ে complement।

২ · GRU equations

Reset gate — পুরনো $h_{t-1}$-এর কতটা "ভুলে" নতুন candidate compute করব:

$$r_t = \sigma(W_r [h_{t-1}, x_t] + b_r)$$

Update gate — পুরনো vs নতুন-এর interpolation:

$$z_t = \sigma(W_z [h_{t-1}, x_t] + b_z)$$

Candidate hidden state — reset-এ filtered পুরনো + নতুন input:

$$\tilde{h}_t = \tanh(W_h [r_t \odot h_{t-1}, x_t] + b_h)$$

Final hidden state — interpolate:

$$h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t$$

লক্ষণীয়: $z_t$ ০-এর কাছে হলে $h_t \approx h_{t-1}$ — পুরনো state preserve। ১-এর কাছে হলে — পুরো নতুন। Forget ও input এক gate-এ merged।

৩ · GRU vs LSTM — তুলনা

  • Gates: LSTM ৩ (forget, input, output), GRU ২ (reset, update)।
  • State: LSTM ২ (cell + hidden), GRU ১ (hidden)।
  • Parameters: GRU ~৭৫% LSTM (one set of weights fewer)।
  • Speed: GRU ১০-২৫% faster training।
  • Accuracy: empirically similar — task ও data depend।
  • Long-range: LSTM theoretically slight edge (separate cell state)।
GRU vs LSTM — architectural comparison GRU: simpler, fewer params, similar performance LSTM 3 gates + 2 states • Forget gate (f_t) • Input gate (i_t) • Output gate (o_t) • Cell state (c_t) • Hidden state (h_t) Parameters: 4 × (H + I) × H Long-range: Excellent Speed: Baseline Year: 1997 GRU 2 gates + 1 state • Reset gate (r_t) • Update gate (z_t) • Hidden state (h_t) (no separate cell) Parameters: 3 × (H + I) × H Long-range: Good Speed: ~25% faster Year: 2014
LSTM vs GRU — GRU-এ কম gate, single state। Parameter কম, speed বেশি, accuracy similar।

৪ · PyTorch nn.GRU

Python · PyTorch
import torch
import torch.nn as nn

gru = nn.GRU(
    input_size=128,
    hidden_size=256,
    num_layers=2,
    bidirectional=True,
    dropout=0.2,
    batch_first=True
)

x = torch.randn(8, 50, 128)
out, h = gru(x)

print(f"Output: {out.shape}")  # (8, 50, 512)
print(f"Hidden: {h.shape}")     # (4, 8, 256)

# Parameter count
lstm = nn.LSTM(128, 256, num_layers=2, bidirectional=True)
print(f"\nGRU params:  {sum(p.numel() for p in gru.parameters()):,}")
print(f"LSTM params: {sum(p.numel() for p in lstm.parameters()):,}")

    
GRU-এর parameter count LSTM-এর প্রায় ৭৫%। Inference latency-ও proportionally কম। Mobile/embedded deployment-এ এই সাশ্রয় matter করে।

৫ · Manual GRU cell

Python · Manual GRU
import torch
import torch.nn as nn

class ManualGRUCell(nn.Module):
    def __init__(self, input_size, hidden_size):
        super().__init__()
        self.hidden_size = hidden_size
        # 3 transformations: r, z, h_tilde
        self.W_xr = nn.Linear(input_size, hidden_size)
        self.W_hr = nn.Linear(hidden_size, hidden_size)
        self.W_xz = nn.Linear(input_size, hidden_size)
        self.W_hz = nn.Linear(hidden_size, hidden_size)
        self.W_xh = nn.Linear(input_size, hidden_size)
        self.W_hh = nn.Linear(hidden_size, hidden_size)

    def forward(self, x, h):
        r = torch.sigmoid(self.W_xr(x) + self.W_hr(h))
        z = torch.sigmoid(self.W_xz(x) + self.W_hz(h))
        h_tilde = torch.tanh(self.W_xh(x) + self.W_hh(r * h))
        h_new = (1 - z) * h + z * h_tilde
        return h_new

cell = ManualGRUCell(input_size=10, hidden_size=20)
x = torch.randn(4, 10)
h = torch.zeros(4, 20)
h = cell(x, h)
print(h.shape)  # (4, 20)

    

৬ · কখন GRU vs কখন LSTM

GRU choose করুন যদি:

  • Compute-constrained — mobile, embedded, edge deployment।
  • Small/medium dataset — fewer parameter, less overfit risk।
  • Faster training-এর দরকার — prototype, hyperparameter search।
  • Sequence moderately long (~১০০ token)।

LSTM choose করুন যদি:

  • Very long sequence — cell state-এর highway পুরোপুরি কাজে।
  • Large dataset + compute available।
  • Subtle long-range dependency critical।
  • Production system যেখানে marginal accuracy gain গুরুত্বপূর্ণ।

সাধারণ pragmatic guideline:

  • Default — GRU। Faster experimentation।
  • If accuracy ceiling reach — try LSTM।
  • If both fail — Transformer।
  • For mobile NLP in Bangladesh — GRU প্রায়ই winner।

৭ · Bangladesh-এ practical GRU usecase

  • Mobile keyboard prediction: next word predict — small model, low latency।
  • SMS spam: light-weight, on-device।
  • Chatbot intent classification: Bangla NLU-এ standard।
  • IoT time-series: sensor data — limited compute।
  • Voice command: wake-word detection — battery-friendly।
"GRU vs LSTM" — religion আকারে discussion আছে। Truth — empirically similar বহু task-এ। আপনার specific task-এ test করে decide করুন। Premature optimization এড়ান।

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

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

প্র ০১ GRU-তে cell state কেন বাদ? LSTM-এর "highway" property কি GRU-তেও আছে?

এটি GRU-এর design genius। Cell state বাদ — কিন্তু gradient highway property সংরক্ষিত। কীভাবে?

GRU-এর update equation:

$h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t$

$\partial h_t / \partial h_{t-1} \approx 1 - z_t$ (যখন $\tilde{h}_t$-এ $h_{t-1}$ dependence ignore)।

Highway property:

  • $z_t \approx 0$ — $h_t \approx h_{t-1}$, gradient flow $\approx 1$।
  • Long-range gradient preserve।
  • LSTM-এর forget gate-এর equivalent।

LSTM cell state-এর role:

  • "Linear" memory — output gate দিয়ে selective expose।
  • Bigger capacity — separate variable।
  • Long-range storage explicit।

GRU-এ trade-off:

  • Hidden state ও memory একত্রে।
  • Output ও memory same — selective output capability কম।
  • Capacity LSTM-এর চেয়ে slightly limited।

Mathematical equivalence (paper analysis):

  • Greff et al. (২০১৫) — extensive comparison।
  • GRU = LSTM minus output gate (approximately)।
  • Most task-এ negligible difference।
  • Specific task যেখানে output gate matter — LSTM win।

When output gate matters:

  • Memory store information necessary later, but not exposed each step।
  • Counting tasks (count digits in sequence)।
  • Long context task with sparse retrieval।

Empirical observations:

  • NLP — GRU very competitive, often winner small data।
  • Speech — LSTM slight edge generally।
  • Time-series — both comparable।
  • Music — LSTM long-term structure better।

Modern perspective:

  • Transformer dominate language tasks।
  • State-space models (Mamba) — GRU-like simple update।
  • RWKV — RNN renaissance, GRU-inspired।

Cell state mathematical preservation:

  • LSTM-এ $c_t$ unbounded, additive।
  • GRU-এ $h_t$ tanh-bounded।
  • LSTM-এ longer-range possible theoretically।
  • Practice-এ similar।

Bangladesh deployment context:

  • Mobile inference — GRU faster, smaller।
  • Battery — fewer ops।
  • Memory — important for low-end Android।
  • Production — GRU acceptable trade-off।

মূল উপলব্ধি: GRU cell state বাদ — কিন্তু update gate-এর through gradient highway সংরক্ষিত। $(1 - z_t) \odot h_{t-1}$ — same effect। LSTM-এর marginally more capacity — output gate। Practice-এ similar performance। Simple architecture often sufficient। Bangladesh-এ mobile NLP — GRU practical winner।

প্র ০২ Update gate $z_t$ — পুরনো ও নতুন-এর interpolation। Why convex combination ($z$ ও $1-z$)? Why two independent gate না?

Convex combination GRU-এর elegant design choice। Two independent gate (LSTM-এর forget + input) থেকে কেন এটা better?

Convex combination property:

  • $h_t = (1 - z_t) \cdot h_{t-1} + z_t \cdot \tilde{h}_t$।
  • $z_t \in [0, 1]$।
  • Output bounded — max norm preserved।
  • "Information conservation" — কিছু রাখি, কিছু update।

Two independent gate alternative:

  • $h_t = f_t \cdot h_{t-1} + i_t \cdot \tilde{h}_t$ (LSTM-style)।
  • $f_t, i_t$ independently $\in [0, 1]$।
  • Possible — both ০ (forget all, write nothing → $h_t = 0$)।
  • Possible — both ১ (keep all, write all → unbounded growth)।

Coupled gate benefit:

  • State magnitude bounded।
  • Easier to reason about।
  • Single decision — "কতটুকু update"।
  • One less hyperparameter।

Independent gate benefit:

  • More expressive — separate forget vs add।
  • Empirically সামান্য better long-range task।
  • LSTM-এর foundation।

Empirical study:

  • Cho et al. (২০১৪) — coupled gate equivalent performance।
  • Greff et al. (২০১৫) — coupled vs independent — small difference।
  • Coupled — fewer parameter, similar accuracy।
  • Modern convention — coupled in GRU।

Probabilistic interpretation:

  • $z_t$ = "probability of update"।
  • $h_t$ = expected value under update decision।
  • Soft gate — differentiable।
  • Hard gate (binary) — non-differentiable, not used।

Geometric interpretation:

  • Hidden state space-এ — convex combination = line segment।
  • $h_t$ — $h_{t-1}$ ও $\tilde{h}_t$-এর মধ্যে কোথাও।
  • Smooth interpolation।
  • Stability promote।

Numerical stability:

  • Bounded state — gradient explosion কম likely।
  • Normalization-এ আলাদা concern নেই।
  • Long sequence training stable।

Modern parallels:

  • Highway networks — convex combination input/transform।
  • Residual connection — addition without coupling।
  • Mixture-of-experts — gate-based routing।

মূল উপলব্ধি: Coupled gate ($z, 1-z$) — single decision "কতটুকু update"। Bounded state, simpler reasoning, fewer params। LSTM-এর independent gate marginally more expressive। Empirically similar। GRU-এর elegance — minimal sufficient mechanism। Architecture design — simplicity vs expressivity balance।

প্র ০৩ Mobile keyboard-এ next-word prediction — Bangla GRU model। Memory budget ১০MB, latency ১০ms। Architecture কী?

Mobile NLP — Bangladesh-এর জন্য huge opportunity। Bangla input এখনো অনেক users-এর কঠিন। Predictive keyboard — UX revolution।

Constraint analysis:

  • Memory: ১০MB — model + vocab embedding।
  • Latency: ১০ms — perceived instant।
  • Battery: minimal CPU/GPU usage।
  • Offline — no internet dependency।

Vocabulary strategy:

  • Top ৩০K-৫০K word — coverage ৯০%।
  • Embedding ৬৪-D (small)।
  • Subword for rare — ৫K subword।
  • Total vocab embedding — ~৩MB at FP32।

Architecture:

import torch
import torch.nn as nn

class MobileGRU(nn.Module):
    def __init__(self, vocab=30000, embed=64,
                 hidden=128, num_layers=2):
        super().__init__()
        self.embed = nn.Embedding(vocab, embed)
        self.gru = nn.GRU(embed, hidden,
                          num_layers=num_layers,
                          batch_first=True)
        self.fc = nn.Linear(hidden, vocab)

    def forward(self, x, h=None):
        emb = self.embed(x)
        out, h = self.gru(emb, h)
        logits = self.fc(out[:, -1, :])
        return logits, h

Parameter budget:

  • Embedding: ৩০K × ৬৪ = ১.৯২M।
  • GRU layer 1: ৩(৬৪+১২৮)১২৮ = ৭৩K।
  • GRU layer 2: ৩(১২৮+১২৮)১২৮ = ৯৮K।
  • Output: ১২৮ × ৩০K = ৩.৮৪M।
  • Total: ~৬M parameter, ২৪MB FP32।

Optimization techniques:

  • Quantization: INT8 — size ¼। ৬MB।
  • Weight tying: input ও output embedding share। Save ৩.৮M param।
  • Smaller vocab: ১৫K — common word coverage ৮৫%।
  • Adaptive softmax: common word fast, rare slow।

Final model size:

  • Tied weights + INT8 + ১৫K vocab।
  • ~১.৫M parameter → ১.৫MB।
  • Comfortable under ১০MB budget।

Inference optimization:

  • ONNX export — cross-platform।
  • TensorFlow Lite — Android native।
  • Pruning — sparse weight।
  • Flash attention-style memory layout।

Latency breakdown:

  • Embedding lookup: <১ms।
  • GRU forward: ~৩ms।
  • Softmax + top-k: ~৪ms।
  • Total: ~৮ms — comfortable।

Training data:

  • Bangla Wikipedia, news, social media।
  • Crowdsource — actual typed text।
  • Privacy concern — federated learning option।
  • Personalization — user history fine-tune।

Bangla-specific challenges:

  • Code-mix — English + Bangla।
  • Multiple keyboard layout (Bijoy, Avro)।
  • Phonetic input — "ami" → "আমি"।
  • Conjuncts (যুক্তাক্ষর) handling।

Personalization:

  • User-specific fine-tune — top layer।
  • On-device learning।
  • Privacy-preserving।
  • Differential privacy if cloud sync।

Beam search / top-k:

def predict_top_k(model, context, k=3):
    with torch.no_grad():
        logits, _ = model(context)
        probs = torch.softmax(logits, dim=-1)
        top_k = torch.topk(probs, k=k, dim=-1)
    return top_k.indices, top_k.values

UX design:

  • ৩ suggestion above keyboard।
  • Auto-complete on tap।
  • Smart correction।
  • Emoji integration।

Evaluation metrics:

  • Top-1 accuracy — exact match।
  • Top-3 accuracy — usable suggestion।
  • Keystroke savings — actual UX metric।
  • User retention — long-term।

Modern alternative:

  • Distilled BERT mobile — accuracy higher, size larger।
  • Hybrid — GRU + retrieval।
  • On-device transformer (DistilBERT)।
  • Trade-off accuracy vs deployment।

Bangladesh market potential:

  • ~১৭ কোটি Bangla speaker।
  • Smartphone penetration ~৫০%।
  • Bangla typing pain point।
  • Native solution missing — opportunity।

মূল উপলব্ধি: Mobile next-word — GRU ideal। ১০MB budget, ১০ms latency comfortably achievable। Quantization + weight tying — model compress ১.৫MB। Training Bangla corpus + user personalization। Bangladesh-এ market huge — ১৭ কোটি potential user। Mobile NLP — practical AI deployment-এর shining example।

প্র ০৪ "GRU vs LSTM" empirical study — কোন task-এ কোনটা win? Decision framework কী?

১০+ বছর empirical study — pattern emerge হয়েছে। Decision framework নিচে।

Major studies:

  • Chung et al. (২০১৪): GRU vs LSTM same performance। Music, speech।
  • Greff et al. (২০১৫): "LSTM Search Space Odyssey" — variants comparison।
  • Jozefowicz et al. (২০১৫): ১০K architecture search। GRU/LSTM near-optimal।
  • Bai et al. (২০১৮): TCN > both for many tasks।

Task-specific findings:

NLP — text classification:

  • GRU often slight winner (small data)।
  • LSTM larger data tie।
  • Bi-directional both work well।

Language modeling:

  • LSTM slight edge — long context।
  • Cell state benefit।
  • Difference smaller post-attention।

Machine translation:

  • ২০১৪-২০১৭ — LSTM dominate।
  • GRU competitive small dataset।
  • Now Transformer।

Speech recognition:

  • LSTM historical preference।
  • Long acoustic sequence — cell state helpful।
  • Modern Conformer/Transformer।

Time-series forecast:

  • Both comparable।
  • Domain expertise > model choice।
  • Feature engineering matter more।

Music generation:

  • LSTM long-term structure better।
  • Counting বার, motif return।
  • Cell state explicit memory helpful।

Reinforcement learning:

  • GRU faster training — ablate quickly।
  • LSTM partial observability complex tasks।

Decision framework:

Step 1 — Compute budget:

  • Limited (mobile, embedded) → GRU।
  • Generous (server, cloud) → either।

Step 2 — Sequence length:

  • Short (<৫০) → GRU sufficient।
  • Medium (৫০-৫০০) → either।
  • Long (৫০০+) → LSTM advantage।

Step 3 — Data size:

  • Small (<১০K) → GRU (less overfit)।
  • Medium (১০K-১M) → either।
  • Large (১M+) → consider Transformer।

Step 4 — Task complexity:

  • Simple (classification) → GRU।
  • Complex (counting, retrieval) → LSTM।

Step 5 — Validation:

  • Both implement, A/B test।
  • Statistical significance check।
  • Training time, inference time include।

Modern context:

  • NLP — Transformer dominant।
  • RNN niches — long sequence, edge, online।
  • State-space models — RNN renaissance।
  • Mamba — Transformer competitor।

When neither — Transformer:

  • Pretrained available (BERT, GPT)।
  • Long-range context critical।
  • Compute available।
  • Parallelization required।

Bangladesh practical recommendation:

  • Default — GRU (compute, simplicity)।
  • Critical accuracy task — try LSTM।
  • Production NLP — BanglaBERT fine-tune।
  • Edge deployment — quantized GRU।

Hyperparameter sensitivity:

  • LSTM more — forget bias, gate init।
  • GRU less — fewer hyperparameters।
  • GRU faster experimentation।

Reproducibility:

  • Random seed effect significant।
  • Multiple runs average।
  • ৫% variation common — small difference noise।

মূল উপলব্ধি: GRU vs LSTM — task-dependent, marginal difference often। Decision framework — compute, sequence length, data size, complexity। Default GRU, escalate LSTM if needed। Modern Transformer dominant — কিন্তু RNN renaissance state-space models। Bangladesh — pragmatic GRU। ML-এ "best architecture" নেই — context-dependent। Empirical experimentation crucial।

অনুশীলন

  1. Compute by hand: $h_{t-1} = (1, 0)$, $\tilde{h}_t = (0, 1)$, $z_t = (0.3, 0.7)$। $h_t$ কত?

    $h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t$।

    • $(1 - 0.3) \cdot 1 + 0.3 \cdot 0 = 0.7$।
    • $(1 - 0.7) \cdot 0 + 0.7 \cdot 1 = 0.7$।
    • $h_t = (0.7, 0.7)$।
  2. Parameter count: $H = 256$, $I = 128$ — GRU vs LSTM-এর parameter সংখ্যা।

    GRU: $3 \cdot (H + I) \cdot H + 3 H = 3 \cdot 384 \cdot 256 + 768 \approx 295K$।

    LSTM: $4 \cdot (H + I) \cdot H + 4 H \approx 393K$।

    GRU LSTM-এর ~৭৫%।

  3. Mobile deployment: Bangla SMS spam — GRU vs LSTM। Trade-off আলোচনা।

    SMS short (~৩০ token), data ১ লক্ষ — GRU ideal:

    • Mobile inference latency ৭৫% LSTM।
    • Memory ৭৫%।
    • Accuracy similar (small data, short sequence)।
    • Battery save।

    LSTM choose হবে যদি — accuracy critical, server-side inference, data ১M+।

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

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ২৭ · LSTM