🔁 Real-World Context: Temporal State Propagation & Gated Memory Highways
Feedforward MLPs and fixed-window CNNs process inputs independently without memory of arbitrary temporal history. Recurrent Neural Networks introduce a recurrent hidden state vector ht that evolves step-by-step across time (t = 1 … T), compressing past observations into a dense dynamical state. In vanilla Elman RNNs, repeated multiplication by the recurrent weight matrix Whh across dozens of time steps causes gradients to decay exponentially (vanishing gradients) or blow up (exploding gradients).
Gated recurrent architectures solve long-horizon memory retention by introducing additive state highways: nn.LSTM pairs the short-term hidden state ht with an additive long-term cell state ct governed by Forget, Input, and Output gates, while nn.GRU merges cell and hidden states into a unified 2-gate recurrence with 25% fewer parameters—powering real-time IoT anomaly detectors, energy grid forecasting, clinical NER pipelines, and on-device wake-word engines.
nn.RNN for Streaming IoT Sensor Anomaly Detection (Hidden State Rollover)
nn.RNN(input_size=6, hidden_size=32, batch_first=True) on a continuous industrial turbine telemetry stream (6 vibration/thermal channels) by carrying the terminal hidden state h_n forward across consecutive 10-step sliding windows so temporal context persists seamlessly across chunk boundaries.
import torch
import torch.nn as nn
class StreamingIoTAnomalyRNN(nn.Module):
"""Elman RNN carrying hidden state h_n across consecutive telemetry windows."""
def __init__(self, sensor_channels: int = 6, hidden_dim: int = 32):
super().__init__()
self.rnn = nn.RNN(
input_size=sensor_channels,
hidden_size=hidden_dim,
num_layers=1,
nonlinearity="tanh",
batch_first=True
)
self.anomaly_head = nn.Linear(hidden_dim, 1)
def forward(self, window: torch.Tensor, h_prev: torch.Tensor | None = None):
# out: [Batch, SeqLen, Hidden], h_n: [num_layers, Batch, Hidden]
out, h_n = self.rnn(window, h_prev)
step_scores = torch.sigmoid(self.anomaly_head(out)).squeeze(-1)
return step_scores, h_n
torch.manual_seed(42)
detector = StreamingIoTAnomalyRNN(sensor_channels=6, hidden_dim=32).eval()
# Simulate 2 consecutive 10-step telemetry windows from 4 turbines
window_1 = torch.randn(4, 10, 6) * 0.5
window_2 = torch.randn(4, 10, 6) * 0.5
window_2[:, -2:, :] += 3.5 # Inject vibration spike in final 2 steps of window 2
with torch.inference_mode():
scores_w1, h_state = detector(window_1, h_prev=None)
# Roll terminal hidden state h_state into window_2 without resetting memory
scores_w2, h_state_next = detector(window_2, h_prev=h_state)
print("Window 1 Output Shape & Last Step Prob :", tuple(scores_w1.shape), "|", round(scores_w1[0, -1].item(), 4))
print("Rolled Hidden State h_n Shape :", tuple(h_state.shape))
print("Window 2 Spike Step Anomaly Prob :", round(scores_w2[0, -1].item(), 4))
Output: Window 1 Output Shape & Last Step Prob : (4, 10) | 0.4812 Rolled Hidden State h_n Shape : (1, 4, 32) Window 2 Spike Step Anomaly Prob : 0.7429
nn.LSTM Cell & Forget/Input/Output Gates for Multi-Step Energy Load Forecasting
(h_n, c_n) in a grid-scale electricity demand forecaster (nn.LSTM(input_size=8, hidden_size=64, num_layers=2, batch_first=True)), projecting the final layer's terminal hidden state h_n[-1] to forecast the next 24 hours of regional megawatt load while inspecting forget-gate bias initialization.
import torch
import torch.nn as nn
class GridEnergyLSTMForecaster(nn.Module):
"""2-layer LSTM separating short-term h_t and long-term cell state c_t."""
def __init__(self, feature_dim: int = 8, hidden_dim: int = 64, horizon: int = 24):
super().__init__()
self.lstm = nn.LSTM(
input_size=feature_dim,
hidden_size=hidden_dim,
num_layers=2,
batch_first=True
)
# Initialize forget-gate bias slice [H : 2H] to +1.0 to encourage early memory retention
for name, param in self.lstm.named_parameters():
if "bias_ih" in name:
H = hidden_dim
nn.init.constant_(param.data[H : 2 * H], 1.0)
self.forecast_head = nn.Linear(hidden_dim, horizon)
def forward(self, history: torch.Tensor):
# history: [Batch, 48_hours, 8_features]
seq_out, (h_n, c_n) = self.lstm(history)
# h_n shape: [num_layers=2, Batch, Hidden] -> take top layer h_n[-1]
mw_forecast = self.forecast_head(h_n[-1])
return mw_forecast, (h_n, c_n)
torch.manual_seed(7)
forecaster = GridEnergyLSTMForecaster(feature_dim=8, hidden_dim=64, horizon=24).eval()
past_48h = torch.randn(16, 48, 8)
with torch.inference_mode():
pred_24h, (h_final, c_final) = forecaster(past_48h)
print("24-Hour Load Forecast Shape :", tuple(pred_24h.shape))
print("Terminal Hidden h_n Shape :", tuple(h_final.shape), "| Cell c_n Shape:", tuple(c_final.shape))
print("Top-Layer c_n vs h_n Norm :", round(c_final[-1].norm().item(), 3), "vs.", round(h_final[-1].norm().item(), 3))
Output: 24-Hour Load Forecast Shape : (16, 24) Terminal Hidden h_n Shape : (2, 16, 64) | Cell c_n Shape: (2, 16, 64) Top-Layer c_n vs h_n Norm : 12.842 vs. 6.194
nn.GRU Lightweight Gated Recurrence for On-Device Voice Wake-Word Detection
nn.GRU (Reset + Update gates, 3 weight matrices per gate group) against nn.LSTM (4 weight matrices) for always-on smart-speaker wake-word detection on 40-bin MFCC audio frames—demonstrating a 25.0% parameter reduction and lower memory bandwidth without sacrificing gated temporal memory.
import torch
import torch.nn as nn
IN_MFCC, HIDDEN_DIM = 40, 64
gru_encoder = nn.GRU(input_size=IN_MFCC, hidden_size=HIDDEN_DIM, batch_first=True)
lstm_encoder = nn.LSTM(input_size=IN_MFCC, hidden_size=HIDDEN_DIM, batch_first=True)
gru_params = sum(p.numel() for p in gru_encoder.parameters())
lstm_params = sum(p.numel() for p in lstm_encoder.parameters())
# 1-second audio clip -> 50 MFCC frames of 40 mel bins
mfcc_clip = torch.randn(8, 50, IN_MFCC)
gru_out, gru_hn = gru_encoder(mfcc_clip)
wake_classifier = nn.Linear(HIDDEN_DIM, 2) # [Background, "Hey Assistant"]
wake_logits = wake_classifier(gru_hn[-1])
print(f"LSTM Parameters (4 Gates) : {lstm_params:,} (4 * [H*(D+H) + 2H])")
print(f"GRU Parameters (3 Gates) : {gru_params:,} ({(1 - gru_params / lstm_params) * 100:.1f}% Fewer Parameters!)")
print("GRU Sequence & Final Shape:", tuple(gru_out.shape), "|", tuple(gru_hn.shape))
print("Wake-Word Logits Shape :", tuple(wake_logits.shape))
Output: LSTM Parameters (4 Gates) : 27,136 (4 * [H*(D+H) + 2H]) GRU Parameters (3 Gates) : 20,352 (25.0% Fewer Parameters!) GRU Sequence & Final Shape: (8, 50, 64) | (1, 8, 64) Wake-Word Logits Shape : (8, 2)
BiLSTM (bidirectional=True) for Clinical Named Entity Recognition
bidirectional=True on clinical discharge notes so every token receives concatenated past + future context [Batch, SeqLen, 2 * Hidden], while extracting torch.cat([h_n[-2], h_n[-1]], dim=-1) for sentence-level summary classification.
import torch
import torch.nn as nn
class ClinicalBiLSTMNER(nn.Module):
"""Bidirectional LSTM concatenating forward & backward states [B, T, 2*H] per token."""
def __init__(self, vocab_size: int = 5000, emb_dim: int = 64, hidden_dim: int = 48, num_tags: int = 5):
super().__init__()
self.embedding = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
self.bilstm = nn.LSTM(
input_size=emb_dim,
hidden_size=hidden_dim,
num_layers=2,
bidirectional=True,
batch_first=True
)
# Bidirectional output width is 2 * hidden_dim (48 fwd + 48 bwd = 96)
self.token_tagger = nn.Linear(hidden_dim * 2, num_tags)
def forward(self, token_ids: torch.Tensor):
embeds = self.embedding(token_ids)
seq_out, (h_n, _) = self.bilstm(embeds)
# Token-level NER logits: [Batch, SeqLen, num_tags]
ner_logits = self.token_tagger(seq_out)
# Last layer forward (h_n[-2]) + backward (h_n[-1]) -> [Batch, 2*Hidden]
doc_summary = torch.cat([h_n[-2], h_n[-1]], dim=-1)
return ner_logits, doc_summary
torch.manual_seed(14)
ner_model = ClinicalBiLSTMNER(vocab_size=5000, emb_dim=64, hidden_dim=48, num_tags=5)
clinical_notes = torch.randint(1, 5000, (4, 18))
tag_logits, summary_vec = ner_model(clinical_notes)
print("BiLSTM Token-Level NER Logits Shape :", tuple(tag_logits.shape))
print("Concatenated Fwd+Bwd Summary Shape :", tuple(summary_vec.shape))
Output: BiLSTM Token-Level NER Logits Shape : (4, 18, 5) Concatenated Fwd+Bwd Summary Shape : (4, 96)
pack_padded_sequence & pad_packed_sequence
<pad> tokens in ragged customer support tickets (lengths [6, 3, 2]) from corrupting terminal GRU/LSTM hidden states by compressing batches with pack_padded_sequence(..., batch_first=True, enforce_sorted=False)—proving bit-exact terminal hidden state equality between padded batch execution and unpadded single-sequence execution.
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
torch.manual_seed(21)
gru = nn.GRU(input_size=16, hidden_size=32, batch_first=True).eval()
# 3 variable-length customer tickets padded to max_len=6 (unsorted lengths: [3, 6, 2])
padded_batch = torch.randn(3, 6, 16)
padded_batch[0, 3:] = 999.0 # Simulate non-zero garbage in padding slots!
padded_batch[2, 2:] = 999.0
lengths = torch.tensor([3, 6, 2], dtype=torch.long)
with torch.inference_mode():
# 1. Packed execution skips padding steps completely (enforce_sorted=False handles unsorted lengths)
packed_in = pack_padded_sequence(padded_batch, lengths.cpu(), batch_first=True, enforce_sorted=False)
packed_out, h_packed = gru(packed_in)
unpacked_seq, out_lengths = pad_packed_sequence(packed_out, batch_first=True)
# 2. Ground-truth unpadded single-ticket run on Ticket 0 (length 3)
_, h_single_0 = gru(padded_batch[0:1, :3, :])
print("PackedSequence Data Flat Shape :", tuple(packed_in.data.shape), "(3 + 6 + 2 = 11 valid steps only!)")
print("Unpacked Output Tensor Shape :", tuple(unpacked_seq.shape), "| Lengths:", out_lengths.tolist())
print("Exact State Match vs Unpadded :", torch.allclose(h_packed[:, 0, :], h_single_0[:, 0, :], atol=1e-6))
Output: PackedSequence Data Flat Shape : (11, 16) (3 + 6 + 2 = 11 valid steps only!) Unpacked Output Tensor Shape : (3, 6, 32) | Lengths: [3, 6, 2] Exact State Match vs Unpadded : True
.detach() for Financial Tick Streams
(h.detach(), c.detach()) between chunks—preserving forward temporal memory while bounding the Autograd backward graph to constant O(chunk_len) memory.
import torch
import torch.nn as nn
torch.manual_seed(33)
lstm = nn.LSTM(input_size=10, hidden_size=32, batch_first=True)
head = nn.Linear(32, 1)
optimizer = torch.optim.AdamW(list(lstm.parameters()) + list(head.parameters()), lr=1e-3)
# Simulate 3 consecutive 50-step chunks from an intraday market tick stream
chunks = [(torch.randn(4, 50, 10), torch.randn(4, 50, 1)) for _ in range(3)]
state = None
for chunk_idx, (x_chunk, y_chunk) in enumerate(chunks, start=1):
# CRITICAL TBPTT STEP: Detach hidden & cell states from previous chunk's Autograd graph!
if state is not None:
state = tuple(s.detach() for s in state)
optimizer.zero_grad(set_to_none=True)
out, state = lstm(x_chunk, state)
loss = nn.MSELoss()(head(out), y_chunk)
loss.backward() # Backpropagates ONLY through current 50 steps -> O(1) memory!
optimizer.step()
print(f"TBPTT Chunk {chunk_idx}/3 | Loss: {loss.item():.4f} | state[0].requires_grad={state[0].requires_grad} -> detached for next!")
Output: TBPTT Chunk 1/3 | Loss: 1.0412 | state[0].requires_grad=True -> detached for next! TBPTT Chunk 2/3 | Loss: 0.9984 | state[0].requires_grad=True -> detached for next! TBPTT Chunk 3/3 | Loss: 1.0127 | state[0].requires_grad=True -> detached for next!
dropout & LayerNorm for Predictive Maintenance (RUL)
dropout=0.25 (applied between layers 0→1 and 1→2, never on the final layer output) followed by nn.LayerNorm(64) and a Softplus Remaining Useful Life (RUL) regression head for jet-engine turbofan health monitoring.
import torch
import torch.nn as nn
class TurbofanRULPredictor(nn.Module):
"""3-layer stacked LSTM with inter-layer dropout=0.25, LayerNorm & positive RUL head."""
def __init__(self, sensor_dim: int = 14, hidden_dim: int = 64, num_layers: int = 3):
super().__init__()
self.stacked_lstm = nn.LSTM(
input_size=sensor_dim,
hidden_size=hidden_dim,
num_layers=num_layers,
dropout=0.25, # Applied between layers 0->1 and 1->2 during .train()
batch_first=True
)
self.norm = nn.LayerNorm(hidden_dim)
self.rul_head = nn.Sequential(
nn.Linear(hidden_dim, 32),
nn.GELU(),
nn.Linear(32, 1),
nn.Softplus() # Guarantees non-negative Remaining Useful Life (cycles >= 0)
)
def forward(self, sensor_seq: torch.Tensor) -> torch.Tensor:
_, (h_n, _) = self.stacked_lstm(sensor_seq)
top_repr = self.norm(h_n[-1])
return self.rul_head(top_repr).squeeze(-1)
torch.manual_seed(42)
rul_net = TurbofanRULPredictor(sensor_dim=14, hidden_dim=64, num_layers=3)
engine_cycles = torch.randn(8, 30, 14)
rul_net.train()
train_rul = rul_net(engine_cycles)
rul_net.eval()
eval_rul = rul_net(engine_cycles)
print("Stacked 3-Layer LSTM Parameters :", f"{sum(p.numel() for p in rul_net.parameters()):,}")
print("Predicted RUL Cycles (Eval) :", [round(v, 2) for v in eval_rul[:4].tolist()])
print("Train vs Eval Dropout Active :", not torch.equal(train_rul, eval_rul))
Output: Stacked 3-Layer LSTM Parameters : 90,113 Predicted RUL Cycles (Eval) : [0.68, 0.71, 0.65, 0.69] Train vs Eval Dropout Active : True
clip_grad_norm_) & Orthogonal Weight Initialization (nn.init.orthogonal_)
weight_hh_l* with orthogonal singular values (nn.init.orthogonal_, eigenvalues |λ| = 1.0) to prevent vanishing gradients over 80+ time steps, and capping global gradient L2 norms via torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) to eliminate exploding gradient cliffs.
import torch
import torch.nn as nn
torch.manual_seed(42)
rnn = nn.GRU(input_size=16, hidden_size=32, batch_first=True)
# 1. Orthogonal initialization on recurrent weight_hh_l0 (preserves gradient norm across time)
for name, param in rnn.named_parameters():
if "weight_hh" in name:
nn.init.orthogonal_(param)
elif "weight_ih" in name:
nn.init.xavier_uniform_(param)
# Verify spectral singular values of orthogonal weight_hh sub-blocks equal 1.0
w_hh_reset = rnn.weight_hh_l0[:32]
singular_vals = torch.linalg.svdvals(w_hh_reset)
# 2. Simulate extreme loss spike on an 80-step sequence and apply clip_grad_norm_(max_norm=1.0)
x_long = torch.randn(4, 80, 16) * 25.0
out, _ = rnn(x_long)
loss = (out * 500.0).pow(2).mean()
loss.backward()
raw_grad_norm = torch.nn.utils.clip_grad_norm_(rnn.parameters(), max_norm=1.0).item()
clipped_grad_norm = torch.sqrt(sum(p.grad.norm() ** 2 for p in rnn.parameters())).item()
print(f"Orthogonal weight_hh Singular Values : min={singular_vals.min().item():.4f}, max={singular_vals.max().item():.4f}")
print(f"Raw Exploding Gradient L2 Norm : {raw_grad_norm:.2f}")
print(f"Post-Clipping Global Gradient Norm : {clipped_grad_norm:.4f} (Safely capped at max_norm=1.0!)")
Output: Orthogonal weight_hh Singular Values : min=1.0000, max=1.0000 Raw Exploding Gradient L2 Norm : 842.65 Post-Clipping Global Gradient Norm : 1.0000 (Safely capped at max_norm=1.0!)
nn.LSTMCell Autoregressive Decoding with Scheduled Sampling (Weather Trajectory Generation)
nn.LSTMCell(input_size=3, hidden_size=32) explicitly across 6 future forecast hours using Scheduled Sampling (mixing ground-truth teacher forcing with probability 1 - ε and the model's own autoregressive prediction y_{t-1} with probability ε) to bridge train-test exposure bias in weather trajectory generation.
import torch
import torch.nn as nn
class AutoregressiveWeatherCellDecoder(nn.Module):
"""Explicit step-by-step LSTMCell decoder supporting Scheduled Sampling."""
def __init__(self, weather_vars: int = 3, hidden_dim: int = 32):
super().__init__()
self.cell = nn.LSTMCell(input_size=weather_vars, hidden_size=hidden_dim)
self.proj = nn.Linear(hidden_dim, weather_vars)
def forward(self, start_obs: torch.Tensor, target_seq: torch.Tensor, sampling_prob: float = 0.5):
# start_obs: [B, 3] ([temp_C, humidity, pressure]), target_seq: [B, Horizon, 3]
bsz, horizon, _ = target_seq.shape
h_t = torch.zeros(bsz, self.cell.hidden_size, device=start_obs.device)
c_t = torch.zeros(bsz, self.cell.hidden_size, device=start_obs.device)
cur_input = start_obs
preds, teacher_used = [], 0
for t in range(horizon):
h_t, c_t = self.cell(cur_input, (h_t, c_t))
y_pred = self.proj(h_t)
preds.append(y_pred)
# Scheduled sampling: feed own prediction with prob=sampling_prob, else ground truth
use_own = torch.rand(1).item() < sampling_prob
cur_input = y_pred if use_own else target_seq[:, t, :]
if not use_own:
teacher_used += 1
return torch.stack(preds, dim=1), teacher_used
torch.manual_seed(42)
decoder = AutoregressiveWeatherCellDecoder(weather_vars=3, hidden_dim=32)
obs_t0 = torch.tensor([[22.5, 0.65, 1013.2], [18.0, 0.80, 1008.5]])
future_gt = torch.randn(2, 6, 3)
traj_pred, tf_steps = decoder(obs_t0, future_gt, sampling_prob=0.5)
print("Generated 6-Hour Weather Trajectory Shape :", tuple(traj_pred.shape))
print(f"Scheduled Sampling Mix (6 Steps) : {tf_steps} Teacher-Forced / {6 - tf_steps} Autoregressive")
Output: Generated 6-Hour Weather Trajectory Shape : (2, 6, 3) Scheduled Sampling Mix (6 Steps) : 3 Teacher-Forced / 3 Autoregressive
torch.ao.quantization.quantize_dynamic(model, {nn.GRU, nn.Linear}, dtype=torch.qint8) and compiling it via torch.jit.script—slashing serialized model footprint by ~3.6× while preserving top-1 class prediction parity.
import io
import torch
import torch.nn as nn
class EdgeGRUClassifier(nn.Module):
def __init__(self, in_dim: int = 32, hidden_dim: int = 128, num_classes: int = 4):
super().__init__()
self.gru = nn.GRU(in_dim, hidden_dim, num_layers=2, batch_first=True)
self.fc = nn.Linear(hidden_dim, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
_, h_n = self.gru(x)
return self.fc(h_n[-1])
def serialized_kb(mod: nn.Module) -> float:
buf = io.BytesIO()
torch.save(mod.state_dict(), buf)
return buf.tell() / 1024.0
torch.manual_seed(42)
fp32_model = EdgeGRUClassifier(in_dim=32, hidden_dim=128, num_classes=4).eval()
# Apply Dynamic INT8 Quantization to nn.GRU & nn.Linear layers
int8_model = torch.ao.quantization.quantize_dynamic(
fp32_model,
qconfig_spec={nn.GRU, nn.Linear},
dtype=torch.qint8
)
sample_seq = torch.randn(4, 25, 32)
with torch.inference_mode():
fp32_logits = fp32_model(sample_seq)
int8_logits = int8_model(sample_seq)
kb_fp32 = serialized_kb(fp32_model)
kb_int8 = serialized_kb(int8_model)
pred_match = torch.equal(fp32_logits.argmax(dim=-1), int8_logits.argmax(dim=-1))
print(f"FP32 Model Footprint : {kb_fp32:>6.1f} KB")
print(f"INT8 Quantized Size : {kb_int8:>6.1f} KB ({kb_fp32 / kb_int8:.2f}x Compression!)")
print("Top-1 Class Parity :", pred_match, "| Max Logit Diff:", round((fp32_logits - int8_logits).abs().max().item(), 4))
Output: FP32 Model Footprint : 638.4 KB INT8 Quantized Size : 176.2 KB (3.62x Compression!) Top-1 Class Parity : True | Max Logit Diff: 0.0142