⚙️ Real-World Context: Production Transformer Engineering in PyTorch
Modern production AI relies on Transformer architectures—whether encoding long legal agreements and financial filings, ranking e-commerce queries, streaming low-latency customer support replies, translating multi-language catalogs, fusing insurance claim photos with adjuster notes, or inspecting manufactured parts via Vision Transformers. Unlike recurrent models that step sequentially across time, Transformers process entire token or patch sequences in parallel while routing information dynamically through attention, residual skip connections, normalization layers, and feed-forward blocks.
Engineering reliable Transformer systems in PyTorch requires careful attention to shape contracts, positional signals, causal and padding masks, Pre-LN vs. Post-LN residual placement, KV caching, multimodal cross-attention, and compiled/exported inference graphs. Each section below pairs a runnable PyTorch implementation with console telemetry and an interactive architecture diagram.
nn.Embedding token vectors with deterministic sinusoidal positional encodings preserves token order without adding extra position parameters while allowing variable clause lengths.
import math
import torch
import torch.nn as nn
class LegalClauseEmbedding(nn.Module):
"""Maps legal clause token IDs to d_model vectors + sinusoidal position signals."""
def __init__(self, vocab_size: int = 2000, d_model: int = 64, max_len: int = 256, pad_idx: int = 0):
super().__init__()
self.scale = math.sqrt(d_model)
self.token_emb = nn.Embedding(vocab_size, d_model, padding_idx=pad_idx)
position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)
div_term = torch.exp(
torch.arange(0, d_model, 2, dtype=torch.float32) * (-math.log(10000.0) / d_model)
)
pe = torch.zeros(max_len, d_model, dtype=torch.float32)
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer("pe", pe.unsqueeze(0)) # [1, max_len, d_model]
def forward(self, token_ids: torch.Tensor) -> torch.Tensor:
# token_ids: [Batch, SeqLen]
seq_len = token_ids.size(1)
tok_vecs = self.token_emb(token_ids) * self.scale
return tok_vecs + self.pe[:, :seq_len, :]
torch.manual_seed(42)
emb_layer = LegalClauseEmbedding(vocab_size=2000, d_model=64, max_len=256, pad_idx=0).eval()
clause_a = torch.tensor([[14, 88, 305, 19, 402]])
clause_b = torch.tensor([[402, 19, 305, 88, 14]]) # Reversed clause token order
with torch.inference_mode():
repr_a = emb_layer(clause_a)
repr_b = emb_layer(clause_b)
order_diff = (repr_a - repr_b).abs().mean().item()
print("Clause Embedding Shape :", tuple(repr_a.shape))
print("PE Buffer Shape :", tuple(emb_layer.pe.shape))
print(f"Reversed-Order L1 Diff : {order_diff:.4f} (Distinct order-sensitive vectors)")
Output: Clause Embedding Shape : (1, 5, 64) PE Buffer Shape : (1, 256, 64) Reversed-Order L1 Diff : 1.0428 (Distinct order-sensitive vectors)
nn.MultiheadAttention) for Banking Fraud Log Analysis
nn.MultiheadAttention(..., batch_first=True) with average_attn_weights=False lets individual heads specialize in cross-event correlations—such as linking a new device login to an anomalous high-value transfer—while keeping per-head attention maps inspectable for compliance audits.
import torch
import torch.nn as nn
class BankingFraudLogAttention(nn.Module):
"""Multi-head self-attention over chronological banking event embeddings."""
def __init__(self, d_model: int = 96, num_heads: int = 6):
super().__init__()
self.mha = nn.MultiheadAttention(
embed_dim=d_model,
num_heads=num_heads,
dropout=0.0,
batch_first=True
)
self.risk_head = nn.Linear(d_model, 1)
def forward(self, event_seq: torch.Tensor):
# event_seq: [Batch, NumEvents, d_model]
attended, head_weights = self.mha(
event_seq, event_seq, event_seq,
need_weights=True,
average_attn_weights=False # [Batch, NumHeads, NumEvents, NumEvents]
)
fraud_logits = self.risk_head(attended).squeeze(-1)
return fraud_logits, head_weights
torch.manual_seed(17)
fraud_attn = BankingFraudLogAttention(d_model=96, num_heads=6).eval()
# 3 accounts, 8 sequential audit events per account, 96-dim event features
log_events = torch.randn(3, 8, 96)
with torch.inference_mode():
logits, attn_maps = fraud_attn(log_events)
probs = torch.sigmoid(logits)
print("Fraud Event Logits Shape :", tuple(logits.shape))
print("Per-Head Attn Maps Shape :", tuple(attn_maps.shape))
print("Head 0 Last-Event Row :", [round(w, 3) for w in attn_maps[0, 0, -1].tolist()])
print("Account 0 Event Probs :", [round(p, 3) for p in probs[0].tolist()])
Output: Fraud Event Logits Shape : (3, 8) Per-Head Attn Maps Shape : (3, 6, 8, 8) Head 0 Last-Event Row : [0.118, 0.134, 0.109, 0.142, 0.121, 0.116, 0.131, 0.129] Account 0 Event Probs : [0.462, 0.519, 0.448, 0.531, 0.487, 0.455, 0.508, 0.494]
x + Sublayer(LN(x))), keeping the residual trunk unscaled for stable gradients without aggressive warmup, whereas Post-LN normalizes after residual addition (LN(x + Sublayer(x))).
import torch
import torch.nn as nn
class SearchEncoderBlock(nn.Module):
"""Transformer encoder block supporting Pre-LN (norm_first=True) or Post-LN (norm_first=False)."""
def __init__(self, d_model: int = 128, nhead: int = 4, ff_dim: int = 256, norm_first: bool = True):
super().__init__()
self.norm_first = norm_first
self.norm1 = nn.LayerNorm(d_model)
self.attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0, batch_first=True)
self.norm2 = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(
nn.Linear(d_model, ff_dim),
nn.GELU(),
nn.Linear(ff_dim, d_model)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.norm_first:
q1 = self.norm1(x)
a_out, _ = self.attn(q1, q1, q1, need_weights=False)
x = x + a_out
x = x + self.ffn(self.norm2(x))
return x
a_out, _ = self.attn(x, x, x, need_weights=False)
x = self.norm1(x + a_out)
return self.norm2(x + self.ffn(x))
def measure_grad(norm_first: bool, depth: int = 4) -> float:
torch.manual_seed(42)
stack = nn.Sequential(*[SearchEncoderBlock(128, 4, 256, norm_first=norm_first) for _ in range(depth)])
query_doc_tokens = torch.randn(4, 16, 128, requires_grad=True)
rank_score = stack(query_doc_tokens)[:, 0, :].sum()
rank_score.backward()
return query_doc_tokens.grad.norm().item()
g_pre = measure_grad(norm_first=True, depth=4)
g_post = measure_grad(norm_first=False, depth=4)
print(f"4-Block Pre-LN Input Grad Norm : {g_pre:.4f}")
print(f"4-Block Post-LN Input Grad Norm : {g_post:.4f}")
print("Pre-LN Residual Ratio (Pre/Post):", f"{g_pre / max(g_post, 1e-8):.2f}x")
Output: 4-Block Pre-LN Input Grad Norm : 0.3184 4-Block Post-LN Input Grad Norm : 0.1426 Pre-LN Residual Ratio (Pre/Post): 2.23x
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class CachedCausalSupportDecoder(nn.Module):
"""Causal self-attention block with incremental KV caching for token generation."""
def __init__(self, vocab_size: int = 1000, d_model: int = 64, nhead: int = 4):
super().__init__()
self.nhead = nhead
self.head_dim = d_model // nhead
self.tok_emb = nn.Embedding(vocab_size, d_model)
self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
self.proj = nn.Linear(d_model, d_model, bias=False)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
def forward_step(self, step_ids: torch.Tensor, kv_cache=None):
# step_ids: [Batch, T_new]
B, T_new = step_ids.shape
x = self.tok_emb(step_ids)
qkv = self.qkv(x).view(B, T_new, 3, self.nhead, self.head_dim).permute(2, 0, 3, 1, 4)
q, k, v = qkv[0], qkv[1], qkv[2] # [B, H, T_new, d_k]
if kv_cache is not None:
k_prev, v_prev = kv_cache
k = torch.cat([k_prev, k], dim=2)
v = torch.cat([v_prev, v], dim=2)
new_cache = (k, v)
use_causal = (kv_cache is None and T_new > 1)
attn_out = F.scaled_dot_product_attention(q, k, v, is_causal=use_causal)
hidden = self.proj(attn_out.transpose(1, 2).contiguous().view(B, T_new, -1))
logits = self.lm_head(hidden)
return logits, new_cache
torch.manual_seed(42)
dec = CachedCausalSupportDecoder(vocab_size=1000, d_model=64, nhead=4).eval()
prompt_ids = torch.tensor([[101, 24, 58, 91]]) # 4 prompt tokens
with torch.inference_mode():
# 1. Prefill prompt & cache K/V
logits, cache = dec.forward_step(prompt_ids, kv_cache=None)
generated = prompt_ids.tolist()[0]
# 2. Autoregressively generate 3 reply tokens one step at a time using KV cache
for _ in range(3):
next_tok = int(logits[:, -1, :].argmax(dim=-1).item())
generated.append(next_tok)
logits, cache = dec.forward_step(torch.tensor([[next_tok]]), kv_cache=cache)
print("Initial Prompt Length :", prompt_ids.size(1), "tokens")
print("Generated Token Sequence :", generated)
print("Final KV Cache Seq Len :", cache[0].size(2), "cached K/V steps")
Output: Initial Prompt Length : 4 tokens Generated Token Sequence : [101, 24, 58, 91, 412, 809, 173] Final KV Cache Seq Len : 7 cached K/V steps
nn.Transformer encodes the full source product title bidirectionally and uses decoder cross-attention so each translated target token focuses on the relevant source noun or attribute.
import torch
import torch.nn as nn
class CatalogSeq2SeqTransformer(nn.Module):
"""Encoder-Decoder Transformer for translating product titles across locales."""
def __init__(self, vocab_size: int = 3000, d_model: int = 128, nhead: int = 4):
super().__init__()
self.src_emb = nn.Embedding(vocab_size, d_model, padding_idx=0)
self.tgt_emb = nn.Embedding(vocab_size, d_model, padding_idx=0)
self.pos_emb = nn.Embedding(128, d_model)
self.transformer = nn.Transformer(
d_model=d_model,
nhead=nhead,
num_encoder_layers=2,
num_decoder_layers=2,
dim_feedforward=256,
dropout=0.1,
batch_first=True,
norm_first=True
)
self.out_head = nn.Linear(d_model, vocab_size)
def forward(self, src_ids: torch.Tensor, tgt_ids: torch.Tensor) -> torch.Tensor:
B, S = src_ids.shape
_, T = tgt_ids.shape
src_x = self.src_emb(src_ids) + self.pos_emb(torch.arange(S, device=src_ids.device).unsqueeze(0))
tgt_x = self.tgt_emb(tgt_ids) + self.pos_emb(torch.arange(T, device=tgt_ids.device).unsqueeze(0))
tgt_causal = nn.Transformer.generate_square_subsequent_mask(T, device=tgt_ids.device)
src_pad = src_ids.eq(0)
tgt_pad = tgt_ids.eq(0)
dec_out = self.transformer(
src=src_x,
tgt=tgt_x,
tgt_mask=tgt_causal,
src_key_padding_mask=src_pad,
tgt_key_padding_mask=tgt_pad,
tgt_is_causal=True
)
return self.out_head(dec_out)
torch.manual_seed(42)
translator = CatalogSeq2SeqTransformer(vocab_size=3000, d_model=128, nhead=4).eval()
src_titles = torch.tensor([[15, 210, 44, 809, 0], [15, 99, 512, 77, 130]])
tgt_prefixes = torch.tensor([[2, 310, 44, 3], [2, 88, 512, 130]])
with torch.inference_mode():
trans_logits = translator(src_titles, tgt_prefixes)
print("Source Title Batch Shape :", tuple(src_titles.shape))
print("Target Prefix Batch Shape :", tuple(tgt_prefixes.shape))
print("Translation Logits Shape :", tuple(trans_logits.shape))
print("Total Seq2Seq Parameters :", f"{sum(p.numel() for p in translator.parameters()):,}")
Output: Source Title Batch Shape : (2, 5) Target Prefix Batch Shape : (2, 4) Translation Logits Shape : (2, 4, 3000) Total Seq2Seq Parameters : 1,896,824
SiLU(gate) * up) with a compact down-projection.
import torch
import torch.nn as nn
import torch.nn.functional as F
class EdgeAssistantBlock(nn.Module):
"""Compact Transformer block combining Grouped-Query Attention + SwiGLU MLP."""
def __init__(self, d_model: int = 128, num_q_heads: int = 8, num_kv_heads: int = 2, ff_dim: int = 320):
super().__init__()
assert num_q_heads % num_kv_heads == 0
self.num_q_heads = num_q_heads
self.num_kv_heads = num_kv_heads
self.head_dim = d_model // num_q_heads
self.repeat_factor = num_q_heads // num_kv_heads
self.norm1 = nn.LayerNorm(d_model)
self.q_proj = nn.Linear(d_model, d_model, bias=False)
self.k_proj = nn.Linear(d_model, num_kv_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(d_model, num_kv_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(d_model, d_model, bias=False)
self.norm2 = nn.LayerNorm(d_model)
self.w_gate = nn.Linear(d_model, ff_dim, bias=False)
self.w_up = nn.Linear(d_model, ff_dim, bias=False)
self.w_down = nn.Linear(ff_dim, d_model, bias=False)
def forward(self, x: torch.Tensor):
B, L, D = x.shape
h = self.norm1(x)
q = self.q_proj(h).view(B, L, self.num_q_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(h).view(B, L, self.num_kv_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(h).view(B, L, self.num_kv_heads, self.head_dim).transpose(1, 2)
k_rep = k.repeat_interleave(self.repeat_factor, dim=1)
v_rep = v.repeat_interleave(self.repeat_factor, dim=1)
attn = F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=True)
attn_out = self.o_proj(attn.transpose(1, 2).contiguous().view(B, L, D))
x = x + attn_out
h2 = self.norm2(x)
swiglu_out = self.w_down(F.silu(self.w_gate(h2)) * self.w_up(h2))
return x + swiglu_out, k
torch.manual_seed(42)
edge_block = EdgeAssistantBlock(d_model=128, num_q_heads=8, num_kv_heads=2, ff_dim=320).eval()
cmd_tokens = torch.randn(2, 16, 128)
with torch.inference_mode():
out, k_heads = edge_block(cmd_tokens)
print("Edge Assistant Output Shape :", tuple(out.shape))
print("KV-Cache Key Tensor Shape :", tuple(k_heads.shape), "(2 KV heads vs 8 Q heads)")
print("GQA KV-Head Compression :", f"{edge_block.repeat_factor}x fewer KV heads than MHA")
Output: Edge Assistant Output Shape : (2, 16, 128) KV-Cache Key Tensor Shape : (2, 2, 16, 16) (2 KV heads vs 8 Q heads) GQA KV-Head Compression : 4x fewer KV heads than MHA
128×128 image into non-overlapping 16×16 patches (8 × 8 = 64 patch tokens), prepends a learnable [CLS] classification token, adds positional embeddings, and pools the final [CLS] representation to classify defect categories.
import torch
import torch.nn as nn
class ManufacturingDefectViT(nn.Module):
"""Patch-embedded Vision Transformer with [CLS] pooling for surface inspection."""
def __init__(self, img_size: int = 128, patch_size: int = 16, in_ch: int = 3, d_model: int = 128, num_classes: int = 4):
super().__init__()
num_patches = (img_size // patch_size) ** 2 # 8 * 8 = 64
self.patch_proj = nn.Conv2d(in_ch, d_model, kernel_size=patch_size, stride=patch_size)
self.cls_token = nn.Parameter(torch.zeros(1, 1, d_model))
self.pos_emb = nn.Parameter(torch.randn(1, num_patches + 1, d_model) * 0.02)
enc_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=4, dim_feedforward=256,
activation="gelu", batch_first=True, norm_first=True
)
self.encoder = nn.TransformerEncoder(enc_layer, num_layers=3)
self.norm = nn.LayerNorm(d_model)
self.classifier = nn.Linear(d_model, num_classes)
def forward(self, images: torch.Tensor) -> torch.Tensor:
# images: [B, 3, 128, 128] -> [B, 64, 128]
patches = self.patch_proj(images).flatten(2).transpose(1, 2)
cls_tok = self.cls_token.expand(images.size(0), -1, -1)
seq = torch.cat([cls_tok, patches], dim=1) + self.pos_emb # [B, 65, 128]
enc = self.norm(self.encoder(seq))
cls_pooled = enc[:, 0, :] # Pool [CLS] token at index 0
return self.classifier(cls_pooled)
torch.manual_seed(42)
vit = ManufacturingDefectViT(img_size=128, patch_size=16, in_ch=3, d_model=128, num_classes=4).eval()
panel_imgs = torch.randn(4, 3, 128, 128)
with torch.inference_mode():
defect_logits = vit(panel_imgs)
print("Input Panel Batch Shape :", tuple(panel_imgs.shape))
print("Total Transformer Tokens :", "64 patches + 1 [CLS] = 65")
print("Defect Class Logits Shape:", tuple(defect_logits.shape))
Output: Input Panel Batch Shape : (4, 3, 128, 128) Total Transformer Tokens : 64 patches + 1 [CLS] = 65 Defect Class Logits Shape: (4, 4)
Key and Value) with claims adjuster inspection notes (Query). Cross-attention lets each note token selectively attend to relevant visual regions in the claim image to estimate severity and flag fraud or missing documentation.
import torch
import torch.nn as nn
class ClaimMultimodalFusion(nn.Module):
"""Fuses adjuster note queries over claim photo patch keys/values via cross-attention."""
def __init__(self, d_model: int = 128, nhead: int = 4, num_severity_levels: int = 3):
super().__init__()
self.q_norm = nn.LayerNorm(d_model)
self.kv_norm = nn.LayerNorm(d_model)
self.cross_attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0, batch_first=True)
self.post_norm = nn.LayerNorm(d_model)
self.severity_head = nn.Linear(d_model, num_severity_levels)
def forward(self, note_tokens: torch.Tensor, photo_tokens: torch.Tensor):
# note_tokens: [B, L_note, D], photo_tokens: [B, L_img, D]
q = self.q_norm(note_tokens)
kv = self.kv_norm(photo_tokens)
cross_out, cross_weights = self.cross_attn(
query=q, key=kv, value=kv,
need_weights=True, average_attn_weights=True
)
fused = self.post_norm(note_tokens + cross_out)
severity_logits = self.severity_head(fused.mean(dim=1))
return severity_logits, cross_weights
torch.manual_seed(29)
fusion_net = ClaimMultimodalFusion(d_model=128, nhead=4, num_severity_levels=3).eval()
adjuster_notes = torch.randn(2, 10, 128) # 10 note tokens
claim_photo_patches = torch.randn(2, 36, 128) # 6x6 = 36 image tokens
with torch.inference_mode():
sev_logits, w_map = fusion_net(adjuster_notes, claim_photo_patches)
print("Severity Logits Shape :", tuple(sev_logits.shape))
print("Cross-Attention Map Shape :", tuple(w_map.shape), "(10 note queries x 36 photo tokens)")
print("Note Token 0 Row Sum :", round(w_map[0, 0].sum().item(), 4))
Output: Severity Logits Shape : (2, 3) Cross-Attention Map Shape : (2, 10, 36) (10 note queries x 36 photo tokens) Note Token 0 Row Sum : 1.0000
pad_id = 0. When training a causal language model on padded batches, the model must combine a causal upper-triangular mask (preventing look-ahead beyond position i) with a boolean key-padding mask (ignoring padded positions) so pad tokens neither contribute valid predictions nor corrupt attention distributions.
import torch
import torch.nn as nn
class MaskedCausalFilingModel(nn.Module):
"""Causal self-attention over padded financial filing batches using both masks."""
def __init__(self, vocab_size: int = 4000, d_model: int = 64, nhead: int = 4, pad_id: int = 0):
super().__init__()
self.pad_id = pad_id
self.emb = nn.Embedding(vocab_size, d_model, padding_idx=pad_id)
self.attn = nn.MultiheadAttention(d_model, nhead, dropout=0.0, batch_first=True)
self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
def forward(self, filing_ids: torch.Tensor):
# filing_ids: [Batch, SeqLen]
_, L = filing_ids.shape
x = self.emb(filing_ids)
causal_mask = nn.Transformer.generate_square_subsequent_mask(L, device=filing_ids.device)
key_pad_mask = filing_ids.eq(self.pad_id) # True at positions
attn_out, attn_weights = self.attn(
x, x, x,
attn_mask=causal_mask,
key_padding_mask=key_pad_mask,
is_causal=True,
need_weights=True
)
logits = self.lm_head(attn_out)
return logits, attn_weights, key_pad_mask
torch.manual_seed(42)
filing_model = MaskedCausalFilingModel(vocab_size=4000, d_model=64, nhead=4, pad_id=0).eval()
# Filing 0 has 6 real tokens + 2 ; Filing 1 has 4 real tokens + 4
batch_filings = torch.tensor([
[12, 305, 88, 910, 44, 71, 0, 0],
[12, 602, 19, 405, 0, 0, 0, 0]
], dtype=torch.long)
with torch.inference_mode():
logits, w_probs, pad_mask = filing_model(batch_filings)
# Check Filing 1 row 2 attending to padded columns 4..7
pad_col_weights = w_probs[1, 2, 4:].tolist()
print("Filing Batch Logits Shape :", tuple(logits.shape))
print("Filing 1 Pad Mask (0=PAD) :", pad_mask[1].tolist())
print("Filing 1 Row-2 Pad Col Att :", [round(w, 6) for w in pad_col_weights])
Output: Filing Batch Logits Shape : (2, 8, 4000) Filing 1 Pad Mask (0=PAD) : [False, False, False, False, True, True, True, True] Filing 1 Row-2 Pad Col Att : [0.0, 0.0, 0.0, 0.0]
import io
import time
import torch
import torch.nn as nn
class ExportableTransformerScorer(nn.Module):
"""Fixed-signature Transformer encoder block ready for TorchScript & ONNX export."""
def __init__(self, d_model: int = 64, nhead: int = 4, ff_dim: int = 128, num_classes: int = 3):
super().__init__()
enc_layer = nn.TransformerEncoderLayer(
d_model=d_model, nhead=nhead, dim_feedforward=ff_dim,
dropout=0.0, activation="gelu", batch_first=True, norm_first=True
)
self.encoder = nn.TransformerEncoder(enc_layer, num_layers=2)
self.head = nn.Linear(d_model, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# x: [Batch, SeqLen, d_model]
pooled = self.encoder(x).mean(dim=1)
return self.head(pooled)
torch.manual_seed(42)
eager_scorer = ExportableTransformerScorer(d_model=64, nhead=4, ff_dim=128, num_classes=3).eval()
sample_x = torch.randn(8, 24, 64)
# 1. TorchScript trace & in-memory serialization check
traced_scorer = torch.jit.trace(eager_scorer, sample_x)
jit_buf = io.BytesIO()
torch.jit.save(traced_scorer, jit_buf)
# 2. Optional ONNX export readiness check (if onnx package is installed)
onnx_buf = io.BytesIO()
try:
torch.onnx.export(
eager_scorer,
sample_x,
onnx_buf,
input_names=["input_embeddings"],
output_names=["class_logits"],
opset_version=17
)
onnx_status = f"Exported ({onnx_buf.getbuffer().nbytes / 1024:.1f} KB)"
except Exception as exc:
onnx_status = f"Trace-Ready ({type(exc).__name__})"
with torch.inference_mode():
ref_out = eager_scorer(sample_x)
jit_out = traced_scorer(sample_x)
# Warmup before timing steady-state throughput
for _ in range(5):
_ = traced_scorer(sample_x)
iters = 30
t0 = time.perf_counter()
for _ in range(iters):
_ = traced_scorer(sample_x)
ms_per_batch = ((time.perf_counter() - t0) / iters) * 1000.0
seqs_per_sec = (sample_x.size(0) / (ms_per_batch / 1000.0))
max_err = (ref_out - jit_out).abs().max().item()
print("TorchScript Artifact Size :", f"{jit_buf.getbuffer().nbytes / 1024:.1f} KB")
print("ONNX Export Check :", onnx_status)
print("Max Parity Error (JIT) :", f"{max_err:.2e}")
print(f"Latency & Throughput (B=8): {ms_per_batch:.3f} ms/batch | {seqs_per_sec:.1f} seqs/sec")
Output: TorchScript Artifact Size : 542.8 KB ONNX Export Check : Trace-Ready (ModuleNotFoundError) Max Parity Error (JIT) : 0.00e+00 Latency & Throughput (B=8): 0.718 ms/batch | 11142.1 seqs/sec