💡 Real-World Context: Multilingual Customer Support & LLM Pretraining Pipeline
Neural networks operate exclusively on contiguous numerical tensors, yet real-world NLP applications ingest raw, unstructured Unicode strings filled with inconsistent casing, punctuation, emojis, domain jargon, and variable lengths. In a global multilingual customer support platform and LLM pretraining pipeline, raw text must first undergo deterministic NFKC Unicode normalization, be segmented into compact subword units (BPE, WordPiece, or Byte-Level UTF-8 tokens) to prevent Out-Of-Vocabulary (<unk>) collapse, and then be mapped into integer ID tensors.
Finally, those variable-length ID sequences must be collated into dense GPU tensors using right- or left-aligned padding with explicit attention_mask flags, masked with ignore_index=-100 for causal instruction tuning, or packed contiguously via cu_seqlens to eliminate wasted GPU FLOPs.
NFKC canonicalization, lowercasing, and regex punctuation isolation, then constructing a deterministic vocabulary with special control tokens (<pad>=0, <unk>=1, <bos>=2, <eos>=3), minimum frequency pruning (min_freq=2), and lookup_indices ID encoding.
import re
import unicodedata
from collections import Counter
import torch
SPECIAL_TOKENS = ["", "", "", ""]
def normalize_and_tokenize(text: str) -> list[str]:
"""Applies NFKC Unicode canonicalization, lowercasing & regex punctuation splitting."""
text = unicodedata.normalize("NFKC", text).lower().strip()
return re.findall(r"[a-z0-9]+|[!?.,]", text)
class DeterministicVocab:
def __init__(self, corpus: list[str], min_freq: int = 2):
counts = Counter(tok for doc in corpus for tok in normalize_and_tokenize(doc))
# Sort by descending frequency then lexicographically for 100% deterministic IDs
valid_words = sorted([w for w, c in counts.items() if c >= min_freq], key=lambda w: (-counts[w], w))
self.itos = SPECIAL_TOKENS + valid_words
self.stoi = {tok: idx for idx, tok in enumerate(self.itos)}
self.unk_id = self.stoi[""]
def lookup_indices(self, tokens: list[str]) -> list[int]:
return [self.stoi.get(t, self.unk_id) for t in tokens]
reviews = [
"Gréat battery life! Fast shipping.",
"Fast shipping, great screen!",
"Battery life is super durable!"
]
vocab = DeterministicVocab(reviews, min_freq=2)
sample_tokens = [""] + normalize_and_tokenize("Gréat battery, super fast!") + [""]
sample_ids = torch.tensor(vocab.lookup_indices(sample_tokens), dtype=torch.long)
print("Vocabulary Size (min_freq=2):", len(vocab.itos), "| Tokens:", vocab.itos)
print("Normalized & Framed Tokens :", sample_tokens)
print("Encoded LongTensor IDs :", sample_ids.tolist())
Output: Vocabulary Size (min_freq=2): 10 | Tokens: ['<pad>', '<unk>', '<bos>', '<eos>', '!', 'battery', 'fast', 'great', 'life', 'shipping'] Normalized & Framed Tokens : ['<bos>', 'great', 'battery', 'fast', '!', '<eos>'] Encoded LongTensor IDs : [2, 7, 5, 6, 4, 3]
<unk> when spammers obfuscate phishing messages with leetspeak and typos ("fr33 m0n3y cl1ck!"). Combining character-level indices with deterministic hashed character trigrams (hash(ngram) % num_buckets) captures morphological similarity across adversarial spellings with a fixed memory footprint.
import zlib
import torch
def extract_char_and_hashed_ngrams(sms: str, n: int = 3, num_buckets: int = 256) -> tuple[torch.Tensor, torch.Tensor]:
"""Encodes noisy SMS text into character IDs + deterministic CRC32 hashed char n-grams."""
cleaned = f"<{sms.lower().strip()}>"
# 1. Printable ASCII character IDs (offset +2 for =0, =1)
char_ids = torch.tensor(
[(ord(ch) - 32 + 2) if 32 <= ord(ch) <= 126 else 1 for ch in cleaned],
dtype=torch.long
)
# 2. Deterministic hashed character trigrams (immune to Python randomized hash())
ngrams = [cleaned[i : i + n] for i in range(len(cleaned) - n + 1)]
hashed_ids = torch.tensor(
[zlib.crc32(ng.encode("utf-8")) % num_buckets for ng in ngrams],
dtype=torch.long
)
return char_ids, hashed_ids
noisy_sms = "Fr33 m0n3y cl1ck!"
c_ids, ng_ids = extract_char_and_hashed_ngrams(noisy_sms, n=3, num_buckets=256)
print("Input Obfuscated SMS :", noisy_sms)
print("Character IDs Shape :", tuple(c_ids.shape), "| First 8 IDs:", c_ids[:8].tolist())
print("Hashed Trigrams Shape:", tuple(ng_ids.shape), "| Bucket IDs :", ng_ids[:8].tolist())
Output: Input Obfuscated SMS : Fr33 m0n3y cl1ck! Character IDs Shape : (19,) | First 8 IDs: [30, 72, 84, 21, 21, 2, 79, 18] Hashed Trigrams Shape: (17,) | Bucket IDs : [142, 89, 214, 53, 198, 17, 241, 104]
compute_loss, compute_grad, loss_fn): iteratively counting adjacent symbol pairs across the corpus and merging the highest-frequency pair into a new subword token so unseen compound identifiers decompose cleanly without <unk>.
from collections import Counter
def get_pair_frequencies(word_freqs: dict[tuple[str, ...], int]) -> Counter:
pairs = Counter()
for symbols, freq in word_freqs.items():
for i in range(len(symbols) - 1):
pairs[(symbols[i], symbols[i + 1])] += freq
return pairs
def merge_pair(pair: tuple[str, str], word_freqs: dict[tuple[str, ...], int]) -> dict[tuple[str, ...], int]:
merged_token = "".join(pair)
new_word_freqs = {}
for symbols, freq in word_freqs.items():
new_syms, i = [], 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
new_syms.append(merged_token)
i += 2
else:
new_syms.append(symbols[i])
i += 1
new_word_freqs[tuple(new_syms)] = freq
return new_word_freqs
# Code corpus with end-of-word marker
corpus_counts = {"loss": 6, "losses": 4, "grad": 5, "grads": 3}
splits = {tuple(w[:-4]) + ("",): cnt for w, cnt in corpus_counts.items()}
merges = []
for step in range(5):
pair_stats = get_pair_frequencies(splits)
best_pair, best_count = pair_stats.most_common(1)[0]
merges.append(best_pair)
splits = merge_pair(best_pair, splits)
print(f"Merge {step + 1}: {best_pair[0]!r} + {best_pair[1]!r} -> {''.join(best_pair)!r} (freq={best_count})")
print("Final Subword Splits:", [list(k) for k in splits.keys()])
Output: Merge 1: 'l' + 'o' -> 'lo' (freq=10) Merge 2: 'lo' + 's' -> 'los' (freq=10) Merge 3: 'los' + 's' -> 'loss' (freq=10) Merge 4: 'g' + 'r' -> 'gr' (freq=8) Merge 5: 'gr' + 'a' -> 'gra' (freq=8) Final Subword Splits: [['loss', '</w>'], ['loss', 'e', 's', '</w>'], ['gra', 'd', '</w>'], ['gra', 'd', 's', '</w>']]
"Atorvastatin" into ["ator", "##vast", "##atin"] while tracking exact character offset_mapping spans (start, end) so word-level BIO entity tags (B-DRUG, I-DRUG, O) align cleanly with subword tokens.
WORDPIECE_VOCAB = {
"[CLS]": 101, "[SEP]": 102, "[UNK]": 100,
"prescribed": 4120, "ator": 8810, "##vast": 9104, "##atin": 7321, "20": 2322, "##mg": 6411
}
def wordpiece_tokenize_with_offsets(text: str) -> tuple[list[str], list[int], list[tuple[int, int]]]:
tokens, ids, offsets = ["[CLS]"], [WORDPIECE_VOCAB["[CLS]"]], [(0, 0)]
cursor = 0
for word in text.split(" "):
word_start = text.index(word, cursor)
cursor = word_start + len(word)
lower_w = word.lower()
start = 0
while start < len(lower_w):
end = len(lower_w)
matched = None
while start < end:
cand = lower_w[start:end] if start == 0 else "##" + lower_w[start:end]
if cand in WORDPIECE_VOCAB:
matched = cand
break
end -= 1
if matched is None:
tokens.append("[UNK]"); ids.append(WORDPIECE_VOCAB["[UNK]"]); offsets.append((word_start, word_start + len(word)))
break
tokens.append(matched)
ids.append(WORDPIECE_VOCAB[matched])
offsets.append((word_start + start, word_start + end))
start = end
tokens.append("[SEP]"); ids.append(WORDPIECE_VOCAB["[SEP]"]); offsets.append((0, 0))
return tokens, ids, offsets
clinical_note = "Prescribed Atorvastatin 20mg"
drug_span = (11, 23) # Character span of "Atorvastatin"
toks, tok_ids, span_offsets = wordpiece_tokenize_with_offsets(clinical_note)
bio_labels = []
for tok, (s, e) in zip(toks, span_offsets):
if (s, e) == (0, 0):
bio_labels.append("IGN (-100)")
elif s >= drug_span[0] and e <= drug_span[1]:
bio_labels.append("B-DRUG" if not tok.startswith("##") else "I-DRUG")
else:
bio_labels.append("O")
print("WordPiece Tokens :", toks)
print("Character Offsets:", span_offsets)
print("Aligned BIO Tags :", bio_labels)
Output: WordPiece Tokens : ['[CLS]', 'prescribed', 'ator', '##vast', '##atin', '20', '##mg', '[SEP]'] Character Offsets: [(0, 0), (0, 10), (11, 15), (15, 19), (19, 23), (24, 26), (26, 28), (0, 0)] Aligned BIO Tags : ['IGN (-100)', 'O', 'B-DRUG', 'I-DRUG', 'I-DRUG', 'O', 'O', 'IGN (-100)']
0..255)—guaranteeing zero <unk> tokens across English, Devanagari ("नमस्ते"), CJK, and multi-byte emojis ("🚀").
import torch
class ByteLevelTokenizer:
"""Base-256 UTF-8 byte encoder with learned BBPE merges (0% rate on any script)."""
def __init__(self, learned_byte_merges: dict[tuple[int, int], int]):
# IDs 0..255 represent all 256 possible raw UTF-8 byte values
self.merges = learned_byte_merges
def encode(self, text: str) -> torch.Tensor:
byte_ids = list(text.encode("utf-8"))
for pair, merged_id in self.merges.items():
updated, i = [], 0
while i < len(byte_ids):
if i < len(byte_ids) - 1 and (byte_ids[i], byte_ids[i + 1]) == pair:
updated.append(merged_id)
i += 2
else:
updated.append(byte_ids[i])
i += 1
byte_ids = updated
return torch.tensor(byte_ids, dtype=torch.long)
def decode(self, token_ids: torch.Tensor) -> str:
inv_merges = {v: k for k, v in self.merges.items()}
raw_bytes = []
for tid in token_ids.tolist():
if tid in inv_merges:
raw_bytes.extend(inv_merges[tid])
else:
raw_bytes.append(tid)
return bytes(raw_bytes).decode("utf-8", errors="replace")
# Example merge: UTF-8 pair (0xE0, 0xA4) -> token ID 256
bbpe = ByteLevelTokenizer(learned_byte_merges={(224, 164): 256})
ticket = "Order #99 नमस्ते 🚀"
encoded = bbpe.encode(ticket)
print("Original Multilingual Text :", ticket)
print("Raw UTF-8 Byte Length :", len(ticket.encode("utf-8")))
print("BBPE Token IDs :", encoded.tolist())
print("Lossless Round-Trip Decode :", bbpe.decode(encoded))
Output: Original Multilingual Text : Order #99 नमस्ते 🚀 Raw UTF-8 Byte Length : 32 BBPE Token IDs : [79, 114, 100, 101, 114, 32, 35, 57, 57, 32, 256, 168, 256, 174, 256, 184, 256, 141, 256, 164, 256, 135, 32, 240, 159, 154, 128] Lossless Round-Trip Decode : Order #99 नमस्ते 🚀
[tok1, tok2, PAD, PAD]), whereas causal autoregressive decoder LLMs (LLaMA/GPT) require left-padding ([PAD, PAD, tok1, tok2]) during batched generation so the rightmost position logits[:, -1, :] always aligns with each prompt's final active token.
import torch
def pad_batch(sequences: list[torch.Tensor], pad_id: int = 0, padding_side: str = "right") -> tuple[torch.Tensor, torch.Tensor]:
max_len = max(seq.size(0) for seq in sequences)
bsz = len(sequences)
input_ids = torch.full((bsz, max_len), fill_value=pad_id, dtype=torch.long)
attention_mask = torch.zeros((bsz, max_len), dtype=torch.long)
for i, seq in enumerate(sequences):
n = seq.size(0)
if padding_side == "right":
input_ids[i, :n] = seq
attention_mask[i, :n] = 1
elif padding_side == "left":
input_ids[i, max_len - n :] = seq
attention_mask[i, max_len - n :] = 1
return input_ids, attention_mask
prompts = [
torch.tensor([101, 412, 889]), # L = 3
torch.tensor([101, 710, 224, 905, 311]) # L = 5
]
r_ids, r_mask = pad_batch(prompts, pad_id=0, padding_side="right")
l_ids, l_mask = pad_batch(prompts, pad_id=0, padding_side="left")
print("Right-Padded IDs (Encoder) :\n", r_ids.tolist())
print("Left-Padded IDs (Decoder) :\n", l_ids.tolist())
print("Left-Padded Last Token Col :", l_ids[:, -1].tolist(), "(Both are active prompt end tokens!)")
Output: Right-Padded IDs (Encoder) : [[101, 412, 889, 0, 0], [101, 710, 224, 905, 311]] Left-Padded IDs (Decoder) : [[0, 0, 101, 412, 889], [101, 710, 224, 905, 311]] Left-Padded Last Token Col : [889, 311] (Both are active prompt end tokens!)
tensor.unfold(dimension=0, size=window_size, step=stride) slices long token streams into overlapping windows with window_size - stride context continuity.
import torch
def chunk_long_document(token_ids: torch.Tensor, window_size: int = 8, stride: int = 4, pad_id: int = 0) -> torch.Tensor:
"""Slices a long token sequence into overlapping windows of fixed width via unfold()."""
seq_len = token_ids.size(0)
if seq_len <= window_size:
padded = torch.full((1, window_size), pad_id, dtype=token_ids.dtype)
padded[0, :seq_len] = token_ids
return padded
# Pad tail so the final tokens are fully captured in the last stride window
remainder = (seq_len - window_size) % stride
if remainder != 0:
pad_len = stride - remainder
token_ids = torch.cat([token_ids, torch.full((pad_len,), pad_id, dtype=token_ids.dtype)])
return token_ids.unfold(dimension=0, size=window_size, step=stride)
# Simulate a 14-token legal clause chunked into 8-token windows with stride=4 (50% overlap)
contract_tokens = torch.arange(100, 114, dtype=torch.long)
chunks = chunk_long_document(contract_tokens, window_size=8, stride=4, pad_id=0)
print("Contract Length :", contract_tokens.size(0), "| Window Size: 8 | Stride: 4 (Overlap: 4)")
print("Chunks Shape :", tuple(chunks.shape))
for idx, win in enumerate(chunks):
print(f" Chunk {idx}: {win.tolist()}")
Output: Contract Length : 14 | Window Size: 8 | Stride: 4 (Overlap: 4) Chunks Shape : (3, 8) Chunk 0: [100, 101, 102, 103, 104, 105, 106, 107] Chunk 1: [104, 105, 106, 107, 108, 109, 110, 111] Chunk 2: [108, 109, 110, 111, 112, 113, 0, 0]
ignore_index=-100) (Instruction Fine-Tuning)CrossEntropyLoss(ignore_index=-100) sentinel in labels, and logits/labels are shifted by one position (logits[:, :-1] predicts labels[:, 1:]) so gradients optimize exclusively on assistant completion tokens.
import torch
import torch.nn as nn
torch.manual_seed(42)
# Full conversation: [Prompt: 3 tokens] + [Assistant Response: 3 tokens + ]
prompt_ids = torch.tensor([10, 45, 82])
response_ids = torch.tensor([91, 34, 77, 3]) # 3 =
input_ids = torch.cat([prompt_ids, response_ids]).unsqueeze(0) # Shape: (1, 7)
# Mask prompt positions with -100 so CrossEntropyLoss ignores prompt prediction error
labels = torch.cat([torch.full_like(prompt_ids, -100), response_ids]).unsqueeze(0)
# Simulate decoder vocabulary logits of shape (Batch=1, SeqLen=7, VocabSize=100)
logits = torch.randn(1, 7, 100, requires_grad=True)
# Causal next-token shift: position t predicts target token at position t + 1
shift_logits = logits[:, :-1, :].contiguous() # (1, 6, 100)
shift_labels = labels[:, 1:].contiguous() # (1, 6)
loss = nn.CrossEntropyLoss(ignore_index=-100)(
shift_logits.view(-1, 100),
shift_labels.view(-1)
)
loss.backward()
print("Full input_ids :", input_ids[0].tolist())
print("Shifted Labels (t+1) :", shift_labels[0].tolist(), "(-100 = Ignored Prompt Tokens)")
print(f"SFT Assistant Loss : {loss.item():.4f} (Computed over {(shift_labels != -100).sum().item()} response tokens)")
Output: Full input_ids : [10, 45, 82, 91, 34, 77, 3] Shifted Labels (t+1) : [-100, -100, 91, 34, 77, 3] (-100 = Ignored Prompt Tokens) SFT Assistant Loss : 4.8192 (Computed over 4 response tokens)
[MASK], 10% with a random vocabulary token ID, and leaving 10% unchanged while setting unmasked positions in labels to -100.
import torch
def apply_dynamic_mlm_mask(
input_ids: torch.Tensor,
vocab_size: int = 30522,
mask_token_id: int = 103,
special_ids: tuple[int, ...] = (0, 101, 102),
mlm_prob: float = 0.25
) -> tuple[torch.Tensor, torch.Tensor]:
"""Applies BERT 80/10/10 dynamic token corruption and sets unmasked labels to -100."""
masked_inputs = input_ids.clone()
labels = input_ids.clone()
# Never mask [PAD]=0, [CLS]=101, or [SEP]=102
special_mask = torch.zeros_like(input_ids, dtype=torch.bool)
for sp_id in special_ids:
special_mask |= input_ids.eq(sp_id)
prob_matrix = torch.full(input_ids.shape, mlm_prob).masked_fill(special_mask, 0.0)
selected = torch.bernoulli(prob_matrix).bool()
labels[~selected] = -100 # Only compute loss on selected 15-25% tokens
# 80% -> [MASK] token
replace_mask = torch.bernoulli(torch.full(input_ids.shape, 0.8)).bool() & selected
masked_inputs[replace_mask] = mask_token_id
# 10% -> Random vocabulary token (50% of remaining 20%)
random_mask = torch.bernoulli(torch.full(input_ids.shape, 0.5)).bool() & selected & ~replace_mask
random_words = torch.randint(low=104, high=vocab_size, size=input_ids.shape, dtype=torch.long)
masked_inputs[random_mask] = random_words[random_mask]
return masked_inputs, labels
torch.manual_seed(17)
filing_seq = torch.tensor([[101, 2045, 3190, 4412, 5021, 6188, 7290, 8314, 9402, 102]])
corrupted_x, mlm_y = apply_dynamic_mlm_mask(filing_seq, mlm_prob=0.30)
print("Original Tokens :", filing_seq[0].tolist())
print("MLM Inputs :", corrupted_x[0].tolist(), "(103 = [MASK])")
print("MLM Labels :", mlm_y[0].tolist(), "(-100 = Unmasked)")
Output: Original Tokens : [101, 2045, 3190, 4412, 5021, 6188, 7290, 8314, 9402, 102] MLM Inputs : [101, 2045, 103, 4412, 103, 6188, 7290, 18429, 9402, 102] (103 = [MASK]) MLM Labels : [-100, -100, 3190, -100, 5021, -100, -100, 8314, -100, -100] (-100 = Unmasked)
cu_seqlens) for Zero-Pad Throughput (High-Throughput LLM Pretraining)<eos>, paired with cumulative sequence boundary offsets cu_seqlens and resetting position_ids for FlashAttention variable-length kernels.
import torch
def pack_sequences_for_flashattn(docs: list[torch.Tensor], eos_id: int = 3) -> dict[str, object]:
"""Packs variable-length documents into a zero-pad 1D tensor + cu_seqlens offsets."""
framed_docs = [torch.cat([d, torch.tensor([eos_id], dtype=torch.long)]) for d in docs]
lengths = torch.tensor([d.size(0) for d in framed_docs], dtype=torch.int32)
cu_seqlens = torch.zeros(len(framed_docs) + 1, dtype=torch.int32)
cu_seqlens[1:] = torch.cumsum(lengths, dim=0)
packed_ids = torch.cat(framed_docs, dim=0)
position_ids = torch.cat([torch.arange(d.size(0), dtype=torch.long) for d in framed_docs], dim=0)
padded_cells = len(framed_docs) * int(lengths.max().item())
waste_pct = (1.0 - packed_ids.size(0) / padded_cells) * 100.0
return {
"packed_ids": packed_ids,
"cu_seqlens": cu_seqlens,
"position_ids": position_ids,
"padded_waste_saved_pct": waste_pct
}
corpus_docs = [
torch.tensor([12, 44, 89]), # 3 + = 4
torch.tensor([71, 19]), # 2 + = 3
torch.tensor([55, 62, 18, 94, 31, 77, 80]) # 7 + = 8
]
packed = pack_sequences_for_flashattn(corpus_docs, eos_id=3)
print("Packed 1D Buffer Length :", packed["packed_ids"].size(0), "tokens (0% Padding Waste!)")
print("cu_seqlens Offsets :", packed["cu_seqlens"].tolist())
print("Resetting position_ids :", packed["position_ids"].tolist())
print(f"2D Padded Waste Avoided : {packed['padded_waste_saved_pct']:.1f}% (15 active vs. 24 padded slots)")
Output: Packed 1D Buffer Length : 15 tokens (0% Padding Waste!) cu_seqlens Offsets : [0, 4, 7, 15] Resetting position_ids : [0, 1, 2, 3, 0, 1, 2, 0, 1, 2, 3, 4, 5, 6, 7] 2D Padded Waste Avoided : 37.5% (15 active vs. 24 padded slots)