Comparing Architecture Families Fairly › Worked Example
Language AI HandbookAll chapters The experiment below uses a synthetic corpus to check the reporting units. The cost model uses an analytical approximation. The quality curves and retrieval probabilities come from specified functions. There is no trained model or accelerator measurement behind the numbers.
Fix the text and workload
Create 2,400 synthetic records and split them into 1,920 training and 480 test records by identity. Their repeated phrases supply a fixture for byte counting and resampling. The quality surface uses no trained model or validation split. A real evaluation should group related records and reserve test data for final evaluation.
The cost calculation assumes four bytes per subword position or one byte per byte position. The quoted ratios are scenario inputs. A real study would tokenize the exact workload for every family. Each training sequence uses the same byte-length workload as the evaluation context in this example. Separate the two lengths when your training and evaluation workloads differ.
PythonIn [9]Expand
SPEC = {
"Dense attention": {
"bytes_per_token": 4,
"attn_frac": 1.0,
"window": None,
"floor": 1.20,
"data_scale": 0.30,
"length_penalty": 0.00,
},
"Windowed 4k": {
"bytes_per_token": 4,
"attn_frac": 1.0,
"window": 4096,
"floor": 1.25,
"data_scale": 0.31,
"length_penalty": 0.018,
},
"Selective SSM": {
"bytes_per_token": 4,
"attn_frac": 0.0,
"window": None,
"floor": 1.28,
"data_scale": 0.33,
"length_penalty": 0.016,
},
"Hybrid 1:7": {
"bytes_per_token": 4,
"attn_frac": 1 / 8,
"window": None,
"floor": 1.23,
"data_scale": 0.31,
"length_penalty": 0.006,
},
"Byte-level": {
"bytes_per_token": 1,
"attn_frac": 1.0,
"window": None,
"floor": 0.96,
"data_scale": 0.46,
"length_penalty": 0.00,
},
}
FAMILY_NAMES = tuple(SPEC)
TRAIN_FLOP_MULTIPLIER = 3.0
def model_shape(n_params):
"""Smooth width and layer-count proxies for this toy stack."""
d_model = (128.0 * n_params / 12.0) ** (1.0 / 3.0)
return d_model, d_model / 128.0
def average_causal_keys(sequence_positions, window):
"""Mean count of allowed keys, including the current position."""
active_window = (
sequence_positions
if window is None
else min(sequence_positions, window)
)
return active_window - active_window * (active_window - 1) / (
2.0 * sequence_positions
)
def fwd_flops_per_token(family, n_params, ctx_bytes):
"""Estimate matmul work per position during a causal prefill."""
d_model, n_layers = model_shape(n_params)
spec = SPEC[family]
positions = max(1, round(ctx_bytes / spec["bytes_per_token"]))
attended = average_causal_keys(positions, spec["window"])
attention_work = spec["attn_frac"] * 4.0 * attended * d_model
return n_layers * (24.0 * d_model**2 + attention_work)
def train_flops(family, n_params, train_bytes, ctx_bytes):
train_tokens = train_bytes / SPEC[family]["bytes_per_token"]
return (
TRAIN_FLOP_MULTIPLIER
* train_tokens
* fwd_flops_per_token(family, n_params, ctx_bytes)
)
def bpb_true(family, n_params, train_bytes, ctx_bytes):
"""Synthetic quality surface. Coefficients are assumptions, not estimates."""
spec = SPEC[family]
cap_term = 0.22 * (7e9 / n_params) ** 0.30
data_term = spec["data_scale"] * (8e10 / train_bytes) ** 0.50
length_term = spec["length_penalty"] * max(0.0, np.log2(ctx_bytes / 4096))
return spec["floor"] + cap_term + data_term + length_term
topics = [
"The spare part arrived on Tuesday.",
"La pièce de rechange est arrivée mardi.",
"代替部品は火曜日に届きました。",
"El repuesto llegó el martes.",
]
rng = np.random.default_rng(20261117)
documents = [
(f"Record {i:04d}. " + (topics[i % len(topics)] + " ") * repeats).strip()
for i, repeats in enumerate(rng.integers(2, 70, size=2400))
]
training_ids, test_ids = np.split(rng.permutation(len(documents)), [1920])
train_bytes = np.array(
[len(documents[i].encode("utf-8")) for i in training_ids]
)
test_bytes = np.array([len(documents[i].encode("utf-8")) for i in test_ids])
assert len(set(training_ids).intersection(test_ids)) == 0
assert len(test_bytes) == 480 and np.min(test_bytes) > 0The Synthetic Quality Surface
The synthetic loss adds four terms: a family floor, a capacity term that falls with parameter count, a data term that falls with training bytes, and a family-specific context term based on log context bytes above 4 KiB. The context coefficient is zero for both full-attention fixtures.
Synthetic retrieval declines with context at fixed parameter count. The two full-attention fixtures have smaller length coefficients. A separate factor approaches one as the parameter count increases.
PythonIn [10]Expand
RETRIEVAL = {
"Dense attention": (4.0, 0.05),
"Windowed 4k": (1.0, 0.60),
"Selective SSM": (1.5, 0.50),
"Hybrid 1:7": (2.5, 0.35),
"Byte-level": (3.6, 0.08),
}
def retrieval_accuracy(family, n_params, ctx_bytes):
"""Synthetic long-range retrieval accuracy: deliberately not the average loss."""
k, slope = RETRIEVAL[family]
z = k - slope * np.log2(ctx_bytes / 4096.0)
capacity_gate = 1.0 - np.exp(-n_params / 3e8)
return capacity_gate / (1.0 + np.exp(-z))The two metrics are constructed to disagree. A competitive aggregate loss can coexist with poor retrieval.
Step 6: the reference configuration
Evaluate every family at the same parameter count and amount of text: 7B parameters, 80 GB of training text, and 128 KiB of context. The resulting training FLOPs can differ.
PythonIn [11]Expand
REF_N = 7e9
REF_BYTES = 8e10
REF_CTX = 131072
reference_rows = []
for fam in FAMILY_NAMES:
reference_rows.append(
dict(
family=fam,
bytes_per_token=SPEC[fam]["bytes_per_token"],
tokens_for_ref_ctx=int(REF_CTX / SPEC[fam]["bytes_per_token"]),
bpb=bpb_true(fam, REF_N, REF_BYTES, REF_CTX),
retrieval=retrieval_accuracy(fam, REF_N, REF_CTX),
train_flops=train_flops(fam, REF_N, REF_BYTES, REF_CTX),
)
)
reference_df = pd.DataFrame(reference_rows).set_index("family")| bytes_per_token | tokens_for_ref_ctx | bpb | retrieval | train_flops | |
|---|---|---|---|---|---|
| family | |||||
| Dense attention | 4.0 | 32,768 | 1.720 | 0.98 | 1.38e+21 |
| Windowed 4k | 4.0 | 32,768 | 1.870 | 0.12 | 9.68e+20 |
| Selective SSM | 4.0 | 32,768 | 1.910 | 0.27 | 8.40e+20 |
| Hybrid 1:7 | 4.0 | 32,768 | 1.790 | 0.68 | 9.08e+20 |
| Byte-level | 1.0 | 131,072 | 1.640 | 0.96 | 1.21e+22 |
Read the table in two passes. First the denominator: a 128 KiB document is 32,768 tokens for the subword families and 131,072 for the byte model, a fourfold difference in sequence length for identical text. Second the two metrics: the dense model and the byte model post nearly identical retrieval scores, the hybrid sits in the middle, and the windowed and constant-state models fall far behind at this length, even though their bits-per-byte numbers are only modestly worse.
That gap between "modestly worse average" and "much worse capability" is the single most important thing to report, and it is invisible if you publish only the loss column.
Step 7: iso-token versus iso-byte
Now the first real comparison, and the one where the answer flips cleanly. Hold the parameter count at 7B and hold the token budget fixed at 20 billion tokens. Every subword family sees 80 GB of text. The byte model sees 20 GB.
PythonIn [13]Expand
FIXED_TOKENS = 2e10
FIXED_BYTES = 8e10
COMPARE_CTX = 131072
iso_token_rows = []
iso_byte_rows = []
for fam in FAMILY_NAMES:
bpt = SPEC[fam]["bytes_per_token"]
iso_token_rows.append(
dict(
family=fam,
bpb=bpb_true(fam, REF_N, FIXED_TOKENS * bpt, COMPARE_CTX),
train_flops=train_flops(
fam, REF_N, FIXED_TOKENS * bpt, COMPARE_CTX
),
)
)
iso_byte_rows.append(
dict(
family=fam,
bpb=bpb_true(fam, REF_N, FIXED_BYTES, COMPARE_CTX),
train_flops=train_flops(fam, REF_N, FIXED_BYTES, COMPARE_CTX),
)
)
iso_token_df = pd.DataFrame(iso_token_rows).set_index("family")
iso_byte_df = pd.DataFrame(iso_byte_rows).set_index("family")| bpb @ iso-token | bpb @ iso-byte | TFLOPs @ iso-token | TFLOPs @ iso-byte | |
|---|---|---|---|---|
| family | ||||
| Dense attention | 1.72 | 1.72 | 1.384735e+09 | 1.384735e+09 |
| Windowed 4k | 1.87 | 1.87 | 9.676706e+08 | 9.676706e+08 |
| Selective SSM | 1.91 | 1.91 | 8.400000e+08 | 8.400000e+08 |
| Hybrid 1:7 | 1.79 | 1.79 | 9.080919e+08 | 9.080919e+08 |
| Byte-level | 2.10 | 1.64 | 3.018892e+09 | 1.207557e+10 |
In these synthetic curves the byte model scores 2.10 bits per byte under the matched-token budget and 1.64 under the matched-byte budget. Matching tokens gives it one-quarter as many raw bytes. Matching raw bytes gives it four times as many positions as the subword model and increases attention work per position for the same text.
This is why the protocol insists on stating whether the fixed budget is in tokens or bytes. "We matched the data budget" is not a specification until you say which units.
Step 8: iso-compute
Iso-compute asks a harder question: fix total training FLOPs, and let each family choose its own parameter count and data budget. That requires a search, because the optimum is different for each family.
PythonIn [15]Expand
N_GRID = np.logspace(8.0, 11.5, 30)
B_GRID = np.logspace(8.7, 11.5, 30)
def iso_compute_point(family, budget, ctx_bytes):
"""Best (N, train_bytes) for a family at a fixed training-FLOPs budget."""
fwd = np.array([fwd_flops_per_token(family, n, ctx_bytes) for n in N_GRID])
train_b = (
budget * SPEC[family]["bytes_per_token"] / (TRAIN_FLOP_MULTIPLIER * fwd)
)
scores = np.array(
[bpb_true(family, n, b, ctx_bytes) for n, b in zip(N_GRID, train_b)]
)
i = int(np.argmin(scores))
return dict(
n_params=float(N_GRID[i]),
train_bytes=float(train_b[i]),
bpb=float(scores[i]),
)PythonIn [16]Expand
BUDGET = 1e22
iso_compute_rows = []
for fam in FAMILY_NAMES:
point = iso_compute_point(fam, BUDGET, COMPARE_CTX)
iso_compute_rows.append(
dict(
family=fam,
n_params=point["n_params"],
train_bytes=point["train_bytes"],
bpb=point["bpb"],
retrieval=retrieval_accuracy(fam, point["n_params"], COMPARE_CTX),
)
)
iso_compute_df = pd.DataFrame(iso_compute_rows).set_index("family")| n_params_B | train_GB | bpb | retrieval | |
|---|---|---|---|---|
| family | ||||
| Dense attention | 11.265 | 380.982 | 1.528 | 0.977 |
| Windowed 4k | 11.265 | 523.868 | 1.652 | 0.119 |
| Selective SSM | 11.265 | 591.813 | 1.672 | 0.269 |
| Hybrid 1:7 | 11.265 | 553.524 | 1.569 | 0.679 |
| Byte-level | 1.610 | 197.773 | 1.594 | 0.956 |
At this budget several subword families choose the same coarse grid point, around 11.3 billion parameters, with different training byte budgets. The model with one byte per position chooses a smaller grid point. These allocations are outcomes of the chosen synthetic functions and the grid.
The dense and byte configurations exceed 0.90 on the synthetic retrieval metric. The other three configurations fall below that target even where their corpus-level loss is competitive. A study for an application that retrieves distant evidence would need a task metric that actually measures that use case.
Let's make that concrete by asking for the cheapest configuration that hits a quality target, and seeing how the answer changes with the target.
PythonIn [18]Expand
def min_compute_for_target(family, target, ctx_bytes):
"""Cheapest (N, train_bytes) reaching a bits-per-byte target."""
best = None
for n in N_GRID:
fwd = fwd_flops_per_token(family, n, ctx_bytes)
for b in B_GRID:
value = bpb_true(family, n, b, ctx_bytes)
if value <= target:
cost = (
TRAIN_FLOP_MULTIPLIER
* fwd
* b
/ SPEC[family]["bytes_per_token"]
)
if best is None or cost < best["train_flops"]:
best = dict(
n_params=float(n),
train_bytes=float(b),
bpb=float(value),
train_flops=float(cost),
)
return best
def min_params_for_retrieval(family, target, ctx_bytes):
"""Smallest parameter count reaching the retrieval target on this grid."""
for n in N_GRID:
if retrieval_accuracy(family, n, ctx_bytes) >= target:
return float(n)
return NonePythonIn [19]Expand
BPB_TARGET = 1.85
RETRIEVAL_TARGET = 0.90
RETRIEVAL_REPORT_BYTES = REF_BYTES
target_rows = []
for fam in FAMILY_NAMES:
bpb_point = min_compute_for_target(fam, BPB_TARGET, COMPARE_CTX)
retrieval_n = min_params_for_retrieval(fam, RETRIEVAL_TARGET, COMPARE_CTX)
target_rows.append(
dict(
family=fam,
flops_for_bpb=None
if bpb_point is None
else bpb_point["train_flops"],
retrieval_at_bpb_target=(
None
if bpb_point is None
else retrieval_accuracy(fam, bpb_point["n_params"], COMPARE_CTX)
),
params_for_retrieval=retrieval_n,
bpb_at_retrieval_target=(
None
if retrieval_n is None
else bpb_true(
fam, retrieval_n, RETRIEVAL_REPORT_BYTES, COMPARE_CTX
)
),
)
)
target_df = pd.DataFrame(target_rows).set_index("family")| zettaflops_for_bpb | retrieval_at_bpb_target | params_for_retrieval_B | bpb_at_retrieval_target | |
|---|---|---|---|---|
| family | ||||
| Dense attention | 0.408 | 0.882 | 0.924 | 1.904 |
| Windowed 4k | 0.793 | 0.119 | NaN | NaN |
| Selective SSM | 1.009 | 0.269 | NaN | NaN |
| Hybrid 1:7 | 0.340 | 0.668 | NaN | NaN |
| Byte-level | 2.304 | 0.868 | 0.924 | 1.824 |
On this grid, hybrid attention reaches 1.85 bits per byte with the least modeled training compute. The retrieval search minimizes parameter count. Only dense subword and dense byte reach 0.90. Their companion BPB assumes the reference 80 GB text budget because the retrieval function does not depend on training bytes. An empty result means no point on the grid met the target.
Name the target metric and the resource being minimized. Report the companion metric at the selected configuration with its workload assumptions.
Step 9: make the budget visible
The plot below shows the same cost model as a continuous function of context length. Log-log axes, because the interesting difference is a ratio, and the y-axis is expressed per byte of text rather than per token so that the tokenizer cannot hide.
VisualizationOut [21]Expand

Dense attention’s modeled prefill work per byte rises as sequence length increases. For windowed attention, the mean number of eligible keys approaches the window width as positions with shorter prefixes make up less of the sequence. The constant-state fixture’s projection cost per position is flat across the plotted lengths.
The byte model in this example uses dense attention and four times as many positions for the same raw byte count. Both the linear work per byte and the attention work per byte are higher than in the four-bytes-per-position dense example. A real byte model can change the attention graph by grouping neighboring positions into patches.
Matched Tokens and Matched Bytes
The chart below makes the disagreement explicit. Each family is bar-plotted under two different budget conventions, and the bars are annotated so the value is readable without consulting the axis.
VisualizationOut [22]Expand

Step 11: iso-compute frontiers
This budget sweep solves for training bytes at each tested parameter count. The earlier BPB target search uses a finite grid in both parameters and training bytes. Its minimum is a separate search result.
VisualizationOut [23]Expand

At a stated budget, a vertical gap measures quality difference. At a stated quality, compare costs where both plotted curves reach the target. This reading depends on the sweep's feasible set and resolution.
The vertical and horizontal differences in this figure are outcomes of the synthetic cost and quality functions. Interpret an empirical frontier within its measured workload, implementation and quality criteria.
Measure Uncertainty at the Document Level
Compare two models on the same documents. For document , multiply the difference in document-level bits per byte by its byte count . These differences in total bits sum in the numerator. Dividing by gives the difference in corpus-level bits per byte. The arithmetic mean of per-document differences answers a separate question about the typical document. Both can be reported if you name the weighting.
Resample document pairs with replacement and recompute the ratio in every bootstrap sample. Independent documents are the assumed sampling units in this demonstration. Cluster by a higher-level unit such as source or conversation when documents share content or collection conditions.
PythonIn [24]Expand
unc_rng = np.random.default_rng(4242)
def paired_bootstrap_ci(diff, byte_counts, n_boot=5000):
"""Return the corpus-level estimate and its percentile interval."""
idx = unc_rng.integers(0, len(diff), size=(n_boot, len(diff)))
bits = diff * byte_counts
estimates = bits[idx].sum(axis=1) / byte_counts[idx].sum(axis=1)
lo, hi = np.percentile(estimates, (2.5, 97.5))
return bits.sum() / byte_counts.sum(), lo, hi
def simulate_document_scores(true_bpb, shared_difficulty, doc_bytes):
interaction = unc_rng.normal(0.0, 0.03, size=len(doc_bytes))
measurement = unc_rng.normal(0.0, 0.55 / np.sqrt(doc_bytes))
return true_bpb + shared_difficulty + interaction + measurement
shared_difficulty = unc_rng.normal(0.0, 0.10, size=len(test_bytes))
baseline_point = iso_compute_point("Dense attention", BUDGET, COMPARE_CTX)
baseline_scores = simulate_document_scores(
baseline_point["bpb"], shared_difficulty, test_bytes
)
forest_rows = []
for family in FAMILY_NAMES:
if family == "Dense attention":
continue
point = iso_compute_point(family, BUDGET, COMPARE_CTX)
comparison_scores = simulate_document_scores(
point["bpb"], shared_difficulty, test_bytes
)
diff = comparison_scores - baseline_scores
mean, lo, hi = paired_bootstrap_ci(diff, test_bytes)
mean_small, lo_small, hi_small = paired_bootstrap_ci(
diff[:40], test_bytes[:40]
)
forest_rows.append(
{
"family": family,
"mean": mean,
"lo": lo,
"hi": hi,
"mean_small": mean_small,
"lo_small": lo_small,
"hi_small": hi_small,
}
)
forest_df = pd.DataFrame(forest_rows).set_index("family")VisualizationOut [25]Expand

Pairing cancels shared document difficulty in the simulator. The contrasts reuse the same realized dense-baseline scores, and the intervals describe each contrast separately under the document-sampling assumptions. Report model selection and leakage controls separately.
Step 13: inference budgets
The serving proxy takes the larger of modeled compute and memory time. It charges one weight read per batch and models the full 60 MB per-sequence activation reserve as traffic once per step. Measure resident footprint and traffic separately on a real serving system.
PythonIn [26]Expand
HBM_BYTES = 80e9
HBM_BW = 3.35e12
PEAK_FLOPS = 9.89e14
EFF_BW = 0.60
EFF_FLOPS = 0.45
WEIGHT_BYTES = 2.0
KV_SHARE = 0.25
ACT_BYTES_PER_SEQ = 6e7
def attn_context(family, ctx_tokens):
window = SPEC[family]["window"]
return ctx_tokens if window is None else min(ctx_tokens, window)
def kv_bytes_per_token(family, n_params):
d_model, n_layers = model_shape(n_params)
return 4.0 * n_layers * d_model * SPEC[family]["attn_frac"] * KV_SHARE
def state_bytes_per_seq(family, n_params):
d_model, n_layers = model_shape(n_params)
return 64.0 * n_layers * (1.0 - SPEC[family]["attn_frac"]) * d_model
def bytes_per_sequence(family, n_params, ctx_tokens):
attended = attn_context(family, ctx_tokens)
return (
kv_bytes_per_token(family, n_params) * attended
+ state_bytes_per_seq(family, n_params)
+ ACT_BYTES_PER_SEQ
)
def decode_step(family, n_params, ctx_tokens, batch):
d_model, n_layers = model_shape(n_params)
attended = attn_context(family, ctx_tokens)
a = SPEC[family]["attn_frac"]
per_seq = bytes_per_sequence(family, n_params, ctx_tokens)
bytes_moved = WEIGHT_BYTES * n_params + batch * per_seq
flops = (
batch
* n_layers
* (
a * (24.0 * d_model**2 + 4.0 * attended * d_model)
+ (1.0 - a) * 24.0 * d_model**2
)
)
t_mem = bytes_moved / (HBM_BW * EFF_BW)
t_flop = flops / (PEAK_FLOPS * EFF_FLOPS)
return dict(
step_seconds=max(t_mem, t_flop),
bytes_moved=bytes_moved,
flops=flops,
intensity=flops / bytes_moved,
)
def max_batch(family, n_params, ctx_tokens, usable=0.85):
free = HBM_BYTES * usable - WEIGHT_BYTES * n_params
per_seq = bytes_per_sequence(family, n_params, ctx_tokens)
return max(0, int(free // per_seq))
def prefill_seconds(family, n_params, ctx_tokens):
d_model, n_layers = model_shape(n_params)
attended = average_causal_keys(ctx_tokens, SPEC[family]["window"])
a = SPEC[family]["attn_frac"]
flops = (
ctx_tokens
* n_layers
* (
a * (24.0 * d_model**2 + 4.0 * attended * d_model)
+ (1.0 - a) * 24.0 * d_model**2
)
)
return max(
flops / (PEAK_FLOPS * EFF_FLOPS),
WEIGHT_BYTES * n_params / (HBM_BW * EFF_BW),
)PythonIn [27]Expand
CTX_BYTES_GRID = np.array([2048, 8192, 32768, 131072, 524288, 1048576])
serving_rows = []
for fam in FAMILY_NAMES:
for ctx_bytes in CTX_BYTES_GRID:
ctx_tokens = ctx_bytes / SPEC[fam]["bytes_per_token"]
batch = max_batch(fam, REF_N, ctx_tokens)
step = decode_step(fam, REF_N, ctx_tokens, batch) if batch else None
tokens_per_s = batch / step["step_seconds"] if step else float("nan")
serving_rows.append(
dict(
family=fam,
ctx_bytes=int(ctx_bytes),
ctx_tokens=int(ctx_tokens),
prefill_estimate_s=prefill_seconds(fam, REF_N, ctx_tokens)
if batch
else float("nan"),
max_seqs=batch,
decode_bytes_per_s=tokens_per_s * SPEC[fam]["bytes_per_token"],
intensity=step["intensity"] if step else float("nan"),
)
)
serving_df = pd.DataFrame(serving_rows)| ctx_tokens | prefill_estimate_s | max_seqs | decode_bytes_per_s | intensity | |
|---|---|---|---|---|---|
| family | |||||
| Dense attention | 32768 | 1.699 | 11 | 1369.198 | 5.476 |
| Windowed 4k | 32768 | 1.187 | 86 | 10174.560 | 20.589 |
| Selective SSM | 32768 | 1.031 | 784 | 92708.960 | 161.434 |
| Hybrid 1:7 | 32768 | 1.114 | 85 | 10051.521 | 20.340 |
| Byte-level | 131072 | 14.818 | 2 | 79.707 | 3.435 |
At 128 KiB of context the serving proxy admits 11 dense subword sequences, 2 dense byte sequences and 784 recurrent sequences under its simplified memory budget. These are capacity estimates before serving-system overhead. The throughput column reports the modeled aggregate decode rate at each admitted batch.
The effective ridge is about 221 FLOP per byte, above the intensity of every admitted decode case in this grid. At 128 KiB, the windowed, recurrent and hybrid fixtures fit 86, 784 and 85 sequences, respectively. Their single-sequence prefill estimates are 1.19, 1.03 and 1.11 seconds. Check the one-second time-to-first-token target by measuring complete requests at the intended serving concurrency.
VisualizationOut [29]Expand

VisualizationOut [30]Expand

Bytes per second aligns the output units. Per-position throughput can also be interpreted with the measured byte-per-position rate and the stated workload.
Step 14: the denominator trap, made visible
Consider the same 400-byte text on two canonical paths, one with 100 subword tokens and one with 400 byte tokens. Give each path 1,000 bits of total surprisal. This sets equal path BPB. Marginalizing over alternative tokenizations can give a different string-level likelihood.
PythonIn [31]Expand
TEXT_BYTES = 400
TOTAL_BITS = 1000.0
scenarios = [
dict(name="Subword (4 B/token)", n_tokens=100, vocab=32_000),
dict(name="Byte-level (1 B/token)", n_tokens=400, vocab=256),
]
denominator_rows = []
for s in scenarios:
bits_per_token = TOTAL_BITS / s["n_tokens"]
denominator_rows.append(
dict(
tokenizer=s["name"],
n_tokens=s["n_tokens"],
bits_per_token=bits_per_token,
per_token_perplexity=2.0**bits_per_token,
bits_per_byte=TOTAL_BITS / TEXT_BYTES,
)
)
uniform_rows = []
for s in scenarios:
bits_per_token = np.log2(s["vocab"])
uniform_rows.append(
dict(
tokenizer="Uniform over vocab: " + s["name"],
bits_per_token=bits_per_token,
per_token_perplexity=2.0**bits_per_token,
bits_per_byte=bits_per_token * s["n_tokens"] / TEXT_BYTES,
)
)
denominator_df = pd.DataFrame(denominator_rows + uniform_rows).set_index(
"tokenizer"
)| n_tokens | bits_per_token | per_token_perplexity | bits_per_byte | |
|---|---|---|---|---|
| tokenizer | ||||
| Subword (4 B/token) | 100.0 | 10.00 | 1024.00 | 2.50 |
| Byte-level (1 B/token) | 400.0 | 2.50 | 5.66 | 2.50 |
| Uniform over vocab: Subword (4 B/token) | NaN | 14.97 | 32000.00 | 3.74 |
| Uniform over vocab: Byte-level (1 B/token) | NaN | 8.00 | 256.00 | 8.00 |
The two paths score 2.5 bits per byte. Their token perplexities are 1,024 and about 5.66, a ratio of about 181.
For the same fixture, a uniform distribution over 32,000 subword symbols incurs about 3.74 bits per byte at four bytes per position. A uniform distribution over 256 byte symbols uses 8 bits per byte. The numbers describe these token sequences and scenario assumptions, including the contribution of the segmentation rule.
VisualizationOut [33]Expand

The middle group ranks these token paths differently even though the two scored paths for the same 400 bytes incur the same total surprisal. The bits-per-byte group shows that equivalence. Read each axis group in its own units.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!