/* Route-Critical (index, V6 §3.6.3 — erzeugt von tools/generate_critical_css.mjs) */ .collapse:not(.show){display:none}.navbar{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between}.navbar>.container-fluid{display:flex;flex-wrap:inherit;align-items:center;justify-content:space-between}.mydraft-svg-icon{display:inline-block;vertical-align:middle;color:currentcolor;flex-shrink:0;transition:color var(--duration-fast, 150ms) ease,stroke var(--duration-fast, 150ms) ease,fill var(--duration-fast, 150ms) ease}.mydraft-svg-icon circle,.mydraft-svg-icon line,.mydraft-svg-icon path,.mydraft-svg-icon polygon,.mydraft-svg-icon polyline,.mydraft-svg-icon rect{transition:stroke var(--duration-fast, 150ms) ease,fill var(--duration-fast, 150ms) ease}@layer components{.live-pulse-dot{width:8px;height:8px}}.min-w-0{min-width:0}@layer overrides{.live-radar-header-badge{background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.35);color:#fca5a5;font-size:.75rem;font-weight:700;transition:.25s;cursor:pointer}}@layer overrides{.live-pulse-dot{width:8px;height:8px;background-color:var(--threat-critical,#ef4444);border-radius:50%;display:inline-block;box-shadow:rgba(239,68,68,.7) 0 0 0 0}}@layer overrides{body.light .live-radar-header-badge,html[data-bs-theme=light] .live-radar-header-badge{background:#fbd9dd;border-color:#eeb2b8;color:#8a1723!important}}.isharestuff-live-ticker{color:var(--color-text-body,#f8fafc);backdrop-filter:none;flex-wrap:wrap;row-gap:.3rem;background:var(--color-surface,rgba(15,23,42,.85))!important;border:1px solid var(--color-border,rgba(255,255,255,.12))!important;padding:.45rem .5rem!important;margin-bottom:.75rem!important}.ticker-content{mask-image:linear-gradient(to right,transparent 0px,rgb(0,0,0) 14px,rgb(0,0,0) calc(100% - 14px),transparent 100%);touch-action:pan-y;cursor:grab;user-select:none;-webkit-tap-highlight-color:transparent;order:1;width:100%;max-width:100%;flex:0 0 100%!important}.isharestuff-live-ticker .ticker-lead-group{order:2;width:100%;justify-content:space-between;margin-right:0!important}.ticker-track{display:flex;align-items:center;white-space:nowrap;will-change:transform;transform:translate3d(0,0,0);--ticker-speed:1;animation-name:isharestuffTicker;animation-timing-function:linear;animation-iteration-count:infinite;animation-duration:calc(26s / var(--ticker-speed, 1))}.ticker-link{max-width:min(78vw,340px);font-size:.82rem;display:inline-block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:baseline;transition:color .2s;color:var(--color-text-heading,#f8fafc)!important}.isharestuff-live-ticker .ticker-ctrl-btn{min-width:44px;height:44px;font-size:.78rem;-webkit-tap-highlight-color:transparent}.ticker-controls-bar{gap:.4rem}.ticker-counter{font-family:var(--bs-font-monospace, ui-monospace, monospace);font-size:.72rem;line-height:1;color:var(--color-text-secondary,#94a3b8);min-width:3.4em;text-align:center;user-select:none;white-space:nowrap;margin-left:auto}.ticker-item{font-size:.82rem}.ticker-item .ticker-date{font-size:.72rem;vertical-align:baseline}.ticker-text-group{display:inline-flex;align-items:baseline}.ticker-badge-live-btn{border:0;cursor:pointer;text-decoration:none!important}.ticker-badge{font-size:.78rem!important;min-height:44px!important;min-width:44px!important;padding:6px 12px!important;display:inline-flex!important;align-items:center!important;justify-content:center!important}@media (min-width:992px){.navbar-expand-lg{flex-wrap:nowrap;justify-content:flex-start}.navbar-expand-lg .navbar-toggler{display:none}}@media (prefers-reduced-motion:reduce){@layer overrides{#news-popup,#news-toast-banner,.animate-pulse,.live-pulse-dot,.live-pulsing-dot,.news-item-card{animation:none;transition:none}}.ticker-track{animation:none!important}.ticker-content{cursor:default}}@media (min-width:768px){.isharestuff-live-ticker{flex-wrap:nowrap;row-gap:0;backdrop-filter:blur(12px);padding:.5rem!important;margin-bottom:1rem!important}.isharestuff-live-ticker .ticker-content{order:0;width:auto;max-width:none;flex:1 1 auto!important}.isharestuff-live-ticker .ticker-lead-group{order:0;width:auto;justify-content:flex-start;margin-right:1rem!important}.ticker-controls-bar{gap:.3rem}.isharestuff-live-ticker .ticker-ctrl-btn{min-width:30px;height:auto;font-size:inherit}.ticker-counter{font-size:.66rem;margin-left:0}.ticker-track{animation-duration:calc(40s / var(--ticker-speed, 1))}.ticker-link{max-width:340px;font-size:.85rem}.ticker-item{font-size:.85rem}.ticker-badge{font-size:inherit!important;min-height:0!important;min-width:0!important;padding:.5rem 1rem!important}}@media (max-width:359.98px){.ticker-counter{display:none}.ticker-controls-bar{gap:.3rem}.ticker-badge{padding:6px 9px!important}} 🔒 BYTE PAIR ENCODING | Sichere Programmierung – TSECURITY.DE Zum Hauptinhalt springen
IT NachrichtenICANN vows to work faster, improve transparency(19.10.2026 um 05:28 Uhr)
••••••••
IT NachrichtenSo funktioniert eine Inselanlage(19.10.2026 um 07:21 Uhr)
••
IT NachrichtenICANN vows to work faster, improve transparency(19.10.2026 um 05:28 Uhr)
••••••••
IT NachrichtenSo funktioniert eine Inselanlage(19.10.2026 um 07:21 Uhr)
••
Intelligence View
⚡ tsecurity.de Intelligence

BYTE PAIR ENCODING

Understanding Byte Pair Encoding (BPE) by Building It From Scratch Introduction: Why Tokenization Exists When working with Large Language Models (LLMs) like…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Social ReaktionenReagiere als Erste:r — dein Feedback zählt!




Understanding Byte Pair Encoding (BPE) by Building It From Scratch






Introduction: Why Tokenization Exists



When working with Large Language Models (LLMs) like GPT, LLaMA, or Mistral, one of the first hidden steps is tokenization.



LLMs do not read raw text. Instead, text must first be converted into tokens — numerical representations that the model can process.



One of the most important tokenization techniques used in modern NLP systems is Byte Pair Encoding (BPE).



In this article, I’ll break it down from intuition to implementation, and show how I built BPE from scratch in Python.



We’ll cover:




  • Why tokenization is needed

  • Why word-level and character-level tokenization fail

  • How BPE solves this trade-off

  • How BPE is implemented step-by-step

  • Training vs inference behavior

  • Strengths and limitations









The Problem With Word-Level Tokenization



A naive approach is to split text by words:




I love machine learning






becomes:




["I", "love", "machine", "learning"]






This seems reasonable — until you realize a major issue.



What happens when the model sees:




machinelearning






or:




hyperlearning






If these words were never in the training data, they become Out-Of-Vocabulary (OOV) tokens.



This is a serious limitation: language is constantly evolving, and we cannot store every possible word.









The Problem With Character-Level Tokenization



To solve OOV, we could split everything into characters:




learning






becomes:




["l", "e", "a", "r", "n", "i", "n", "g"]






This eliminates OOV completely.



However, it introduces new problems:




  • Sequences become very long

  • Training becomes inefficient

  • The model loses meaningful word structure



So we have a trade-off:




















Approach Problem
Word-level OOV issues
Character-level Too long sequences


We need something in between.









The Idea Behind Byte Pair Encoding (BPE)



BPE solves this by learning common patterns in text.



Instead of choosing words or characters, it builds subword units.



The idea is simple:




  1. Start with characters

  2. Find the most frequent adjacent pair

  3. Merge it into a new token

  4. Repeat



Over time, frequent patterns become single tokens.









Example Intuition



Given:




l o w
l o w e r
l o w e s t






BPE might learn:




lo
low
lowe






depending on frequency patterns.









Step 1: Build a Vocabulary



We start with word frequencies:




{
"low": 1,
"lower": 1,
"lowest": 1
}






Then we convert each word into characters and add an end-of-word marker:




{
('l', 'o', 'w', '</w>'): 1,
('l', 'o', 'w', 'e', 'r', '</w>'): 1,
('l', 'o', 'w', 'e', 's', 't', '</w>'): 1
}






The </w> marker helps distinguish word boundaries.









Step 2: Count Adjacent Pairs



We scan all words and count adjacent symbol pairs.



For example:




l o w </w>






produces:




(l, o)
(o, w)
(w, </w>)






Each pair is counted weighted by word frequency.



This gives us a global frequency table of all pairs in the corpus.









Step 3: Select the Most Frequent Pair



We select the most frequent adjacent pair:




('l', 'o')






This becomes a merge rule:




(l, o) → lo












Step 4: Merge Across the Entire Vocabulary



We replace every occurrence of:




l o






with:




lo






So:




('l','o','w','</w>')






becomes:




('lo','w','</w>')












Step 5: Repeat the Process



We recompute pair frequencies and continue merging:




(l,o) → lo
(lo,w) → low
(low,e) → lowe






Each iteration builds more complex tokens from simpler ones.









Training vs Tokenization (CRITICAL CONCEPT)



This is where many people get confused.






During Training



BPE:




  • Counts pair frequencies

  • Learns merge rules

  • Builds a vocabulary



Example:




(l,o) → lo
(lo,w) → low












During Tokenization (Inference)



The tokenizer:




  • Does NOT learn anything

  • Does NOT count frequencies

  • ONLY applies learned merge rules



Example:



Input:




lowly






Start:




l o w l y






Apply merges:




(l,o) → lo
(lo,w) → low






Result:




low l y






No learning happens here — only rule application.









Why BPE Works So Well






1. Solves OOV Problem



Even unseen words can be represented:




playfulness → play + ful + ness












2. Smaller Vocabulary



Instead of storing full words:




play
playing
player
played






we reuse:




play
ing
er












3. Better Generalization



Words with shared roots reuse tokens:




play
playing
player






This allows models to share meaning across related words.









Limitations of BPE



Despite its power, BPE has limitations:




  • Sensitive to training corpus

  • Greedy merging strategy

  • Weak for multilingual balance

  • Does not “understand” language — only frequency patterns



Because of this, modern LLMs often use:




  • Byte-level BPE (GPT-style tokenizers)

  • WordPiece (BERT)

  • SentencePiece Unigram (LLaMA, T5)









My Python Implementation (From Scratch)



Below is my simplified BPE implementation:




import sys

def main(av: list[str]) -> int:
ac = len(av)

# Step 1: Build word frequencies
vocab = {}

for i in range(1, ac):
vocab[av[i]] = vocab.get(av[i], 0) + 1

# Step 2: Split into characters
word_dict = {
tuple(word) + ('</w>',): freq
for word, freq in vocab.items()
}

# BPE training loop
num_merges = 200

for merge_step in range(num_merges):

# Step 3: Count pairs
pair_count = {}

for word, freq in word_dict.items():
symbols = list(word)

for i in range(len(symbols) - 1):
pair = (symbols[i], symbols[i + 1])
pair_count[pair] = pair_count.get(pair, 0) + freq

if not pair_count:
break

# Step 4: Best pair
best_pair = max(pair_count, key=pair_count.get)

if pair_count[best_pair] < 2:
break

merged_symbol = ''.join(best_pair)

print(f"Merge {merge_step + 1}: {best_pair} -> {merged_symbol}")

# Step 5: Merge vocabulary
new_word_dict = {}

for word, freq in word_dict.items():
symbols = list(word)
new_symbols = []

i = 0
while i < len(symbols):
if (
i < len(symbols) - 1 and
(symbols[i], symbols[i + 1]) == best_pair
):
new_symbols.append(merged_symbol)
i += 2
else:
new_symbols.append(symbols[i])
i += 1

new_word_dict[tuple(new_symbols)] = freq

word_dict = new_word_dict

print("\nFinal vocabulary:")
print(word_dict)

return 0


if __name__ == "__main__":
sys.exit(main(sys.argv))







This implementation:




  • Builds vocabulary

  • Computes pair frequencies

  • Learns merge rules

  • Iteratively updates tokens









Key Insight



BPE is surprisingly simple:




It does not understand language — it only learns which character pairs appear together most frequently.




Yet this simple idea is powerful enough to be used in all modern LLMs.









Conclusion



Byte Pair Encoding sits at the core of modern NLP systems.



It provides a balance between:




  • Word-level tokenization (too rigid)

  • Character-level tokenization (too long)



By learning frequent subword patterns, BPE allows models to efficiently represent both common and unseen words.



Understanding BPE is one of the best entry points into understanding how LLMs actually process language.

🔍 CTI & Forensik

Cyber Threat Intelligence & Forensik

ATT&CK-Navigator · IoC-Radar · Exploit-Belege
CTI Threat Relationship Graph
Akteure · Techniken · Beziehungen
2 Knoten · 1 Relationen
CVE / Incident Threat Actor Software MITRE ATT&CK CWE Weakness IoC
Intelligence Digest — free The top security news daily · unsubscribe anytime
Community Rating & Social Proof
⭐ Leser-Wertung
–
Ø / 5.0
No reader ratings yet
Was this page helpful?
0
Jetzt Bewertung abgeben
🟢 Niedrig (1-3.9) 🟡 Mittel (4.0-6.9) 🔴 Hoch (7.0-8.9) Kritisch (9.0-10.0)

Related story clusters & sources (vector AI)

Similar posts
🔍 Verwandte News

Auch interessante Nachrichten BYTE PAIR ENCODING

Thematisch verwandte Begriffe: BYTE, PAIR, ENCODING · 6 Treffer

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

Laden...

Loading posts ...

Laden...

Loading videos ...

💬 Loading comments…
Pull to refresh
Nächster Beitrag