Shrinking the Embedding Table in Small On-Device Models: Sizing, Pruning, and Quantization

    When compressing small language models for on-device deployment, the embedding table is often the largest single component yet is frequently left untouched. This guide walks through the three metrics you need to distinguish—parameter count, file size, and runtime memory—shows why quantization tooling commonly skips the embedding layer, and provides a complete, code-backed workflow for vocabulary pruning on vertical-domain tasks, including BPE merge-path closure, ID remapping, and consistency checks.

    First, Align the Definitions: Parameter Count, File Size, and Runtime Memory

    Before discussing embedding table size, distinguish three metrics. Their values are not interchangeable.

    The first is parameter count. The embedding table’s parameter count equals vocabulary size V times hidden dimension d. If the input embedding and output layer share weights (when tie_word_embeddings is true in the config), those parameters are counted only once.

    The second is file size. The approximate formula is: file size ≈ parameter count × bits per parameter ÷ 8, plus overhead from quantization scaling factors, zero points, metadata, and storage alignment.

    The third is runtime memory. It includes weights, activations, the KV cache, and runtime overhead. File size only covers the weight portion and cannot be treated as runtime memory.

    Many papers report memory figures “excluding the embedding layer.” When reading such numbers, first check whether they exclude the largest table. Figures that don’t specify this should not be compared directly against deployment targets.

    Now compute an example with hypothetical parameters: vocabulary size V = 32,000, hidden dimension d = 1,024, shared input/output weights, and roughly 70M parameters in the non-embedding layers. All numbers below use decimal MB and count weights only.

    The embedding table has 32,000 × 1,024 = 32,768,000 parameters.

    Embedding precision Vocabulary size Embedding table size (approx., excluding scaling factors)
    FP16 32,000 65.5 MB
    INT8 32,000 32.8 MB
    INT4 32,000 16.4 MB
    FP16 8,000 (after pruning) 16.4 MB
    INT4 8,000 (after pruning) 4.1 MB

    After ternarizing the non-embedding layers, the theoretical information content is about 1.58 bits per parameter, i.e., 70M × 1.58 ÷ 8 ≈ 13.8 MB. This is a theoretical floor. Practical storage typically uses 2-bit packing with one FP16 scaling factor per 128 weights, giving roughly 70M × 2 ÷ 8 + (70M ÷ 128) × 2 bytes ≈ 17.5 MB + 1.1 MB ≈ 18.6 MB. There is a clear gap between theoretical bit width and actual file size, so compute using the real storage format before deployment.

    These numbers make two points. First, even with 2-bit storage for the main body, an FP16 embedding table (65.5 MB) is still far larger than the body itself. Second, an INT4 embedding table (about 16.4 MB plus scaling overhead) is comparable in size to the body and cannot be ignored. Vocabulary pruning and low-bit embedding quantization each reduce size noticeably, and the two can be combined.

    The following script reproduces the calculations above. It counts only weights and scaling factors, not activations, the KV cache, or runtime overhead.

    1. def size_mb(params, bits, group_size=None, scale_bits=16):
    2. # Returns decimal MB; counts only weights and grouped scaling factors
    3. total_bits = params * bits
    4. if group_size:
    5. total_bits += (params / group_size) * scale_bits
    6. return total_bits / 8 / 1e6
    7. V, d = 32_000, 1024
    8. print(size_mb(V * d, 16)) # FP16, ~65.5
    9. print(size_mb(V * d, 4, group_size=128)) # INT4 group quantization, ~16.9
    10. print(size_mb(8_000 * d, 4, group_size=128)) # INT4 after pruning to 8,000, ~4.2

    For a real model, recalculate using its own config; do not reuse these hypothetical values directly.

    Why Quantization Often Skips the Embedding Layer

    The embedding layer performs row lookups. For an input token, the corresponding row vector is fetched, so quantization error flows directly into that token’s input representation.

    Errors in linear layers pass through matrix multiplication, where errors across multiple input dimensions partially average out. The embedding layer has no such averaging. If the output layer shares weights with the embedding layer, the same errors also propagate to the logits, affecting the probability distribution of the next token. Consequently, the same bit width can cause quality losses on the two types of layers that are hard to judge with the same set of heuristics.

    Another reason is tooling. Many inference frameworks have fairly complete low-bit support for linear layers but much less support for embedding layers. With default configurations, the tool may compress only the linear layers while the embedding table remains FP16. Before deployment, inspect the exported weight format and confirm the embedding table’s actual data type.

    Some low-bit training works keep the embedding layer at higher precision while quantizing the model body. The conclusions of such papers depend on the training method, model scale, and evaluation tasks. Before citing them, verify which parts they compressed beyond the model body. The embedding layer should be evaluated as an independent object, not handled by default along with the body.

    Approach 1: Vocabulary Pruning for Vertical-Domain Tasks

    This approach suits tasks whose vocabulary distribution is narrow, such as local Q&A for a specific industry, specialized code completion, or fixed-format information extraction. If the business must handle extensive multilingual or open-domain text, the UNK risk from pruning is high and this approach is not recommended.

    The core constraint is a strict one-to-one correspondence between the tokenizer and the model weights. Deleting only rows from the embedding matrix shifts all token IDs, invalidating model outputs.

    The steps are as follows.

    1. Count token frequencies. Encode target-domain corpora with the original tokenizer and count occurrences of each old ID. The corpus should come from real user inputs, not a small slice of training data.
    2. Determine the keep set. Special tokens are always kept, including BOS, EOS, PAD, UNK, markers in the chat template, and byte-level fallback tokens (usually 256 byte tokens). Their frequencies count toward the total but are exempt from thresholding.
    3. Select remaining tokens by coverage. Accumulate from high to low frequency until the kept tokens cover the target fraction of total occurrences. The coverage target is a business decision; a reasonable starting point is 99.5%, then tune by scanning.
    4. Close the BPE merge paths. In BPE, a merged token is formed from two sub-tokens. If you keep a merged token but delete its sub-tokens, the merge path cannot be reproduced during encoding and results will drift. The close_bpe function below starts from the keep set and recursively adds sub-tokens along merge relations until the set stops growing.
    5. Rebuild the tokenizer. Delete merge rules where either endpoint is outside the keep set, and update the vocabulary, added tokens, and special-token mappings in sync. Do not modify only the model weights.
    6. Generate the old-to-new ID mapping and slice the input embedding and output layer. If weights are tied, slice only once and verify that the tying still holds afterward.
    7. Update the config. Modify vocab_size in config.json, along with bos_token_id, eos_token_id, pad_token_id, unk_token_id, and decoder_start_token_id. IDs hard-coded in generation_config.json must also be rewritten. If an ID has no corresponding new ID, the script should fail loudly rather than skip silently.
    8. Run consistency checks. On a held-out domain set, measure UNK rate and round-trip failure rate, and compare encodings against the original tokenizer.

    A complete example follows, using PyTorch and Hugging Face Transformers. Verify specific interfaces against your installed versions.

    1. import torch
    2. import torch.nn as nn
    3. def build_keep_ids(freqs, special_ids, coverage=0.995):
    4. """freqs[i] is the occurrence count of old id i. Special tokens are always kept,
    5. but their frequencies count toward the total."""
    6. total = sum(freqs)
    7. keep = set(special_ids)
    8. acc = sum(freqs[i] for i in keep)
    9. order = sorted(range(len(freqs)), key=lambda i: freqs[i], reverse=True)
    10. for i in order:
    11. if acc / total >= coverage:
    12. break
    13. if i in keep:
    14. continue
    15. keep.add(i)
    16. acc += freqs[i]
    17. return sorted(keep)
    18. def build_merge_children(merges, vocab):
    19. """merges: (a, b) string pairs ordered by priority; vocab: string -> id.
    20. For byte-level BPE, vocabulary strings can be concatenated directly."""
    21. table = {}
    22. for a, b in merges:
    23. if a in vocab and b in vocab and (a + b) in vocab:
    24. table[vocab[a + b]] = (vocab[a], vocab[b])
    25. return table
    26. def close_bpe(keep_ids, merge_children):
    27. """Recursively add sub-tokens along merge relations until the keep set is closed."""
    28. keep = set(keep_ids)
    29. stack = list(keep)
    30. while stack:
    31. t = stack.pop()
    32. for child in merge_children.get(t, ()):
    33. if child not in keep:
    34. keep.add(child)
    35. stack.append(child)
    36. return sorted(keep)
    37. def filter_merges(merges, vocab, keep_set):
    38. """Keep only rules where a, b, and the merged result are all in the keep set,
    39. preserving the original priority order."""
    40. out = []
    41. for a, b in merges:
    42. ids = (vocab.get(a), vocab.get(b), vocab.get(a + b))
    43. if all(i is not None and i in keep_set for i in ids):
    44. out.append((a, b))
    45. return out
    46. def prune_model(model, keep_ids):
    47. idx = torch.tensor(keep_ids, dtype=torch.long)
    48. emb = model.get_input_embeddings()
    49. new_emb = nn.Embedding(len(keep_ids), emb.embedding_dim,
    50. dtype=emb.weight.dtype, device=emb.weight.device)
    51. with torch.no_grad():
    52. new_emb.weight.copy_(emb.weight.data[idx.to(emb.weight.device)])
    53. model.set_input_embeddings(new_emb)
    54. if getattr(model.config, "tie_word_embeddings", False):
    55. model.tie_weights()
    56. else:
    57. head = model.get_output_embeddings()
    58. new_head = nn.Linear(head.in_features, len(keep_ids),
    59. bias=head.bias is not None,
    60. dtype=head.weight.dtype, device=head.weight.device)
    61. with torch.no_grad():
    62. new_head.weight.copy_(head.weight.data[idx.to(head.weight.device)])
    63. if head.bias is not None:
    64. new_head.bias.copy_(head.bias.data[idx.to(head.bias.device)])
    65. model.set_output_embeddings(new_head)
    66. model.config.vocab_size = len(keep_ids)
    67. return model
    68. def remap_config_ids(config, old2new):
    69. for key in ["bos_token_id", "eos_token_id", "pad_token_id",
    70. "unk_token_id", "decoder_start_token_id"]:
    71. val = getattr(config, key, None)
    72. if val is None:
    73. continue
    74. vals = val if isinstance(val, list) else [val]
    75. missing = [v for v in vals if v not in old2new]
    76. if missing:
    77. raise ValueError(f"ids {missing} in {key} are not in the keep set")
    78. new = [old2new[v] for v in vals]
    79. setattr(config, key, new if isinstance(val, list) else new[0])

    After building the keep set, proceed with mapping and validation:

    1. keep_ids = close_bpe(build_keep_ids(freqs, special_ids, coverage=0.995),
    2. build_merge_children(merges, vocab))
    3. keep_set = set(keep_ids)
    4. old2new = {old: new for new, old in enumerate(keep_ids)}
    5. def drift_rate(old_tok, new_tok, old2new, texts):
    6. """Count only texts whose original encoding is fully retained.
    7. Their new encoding should exactly match the mapped result."""
    8. eligible, drift = 0, 0
    9. for t in texts:
    10. old_ids = old_tok.encode(t)
    11. if not all(i in old2new for i in old_ids):
    12. continue
    13. eligible += 1
    14. expected = [old2new[i] for i in old_ids]
    15. if new_tok.encode(t) != expected:
    16. drift += 1
    17. return drift / max(eligible, 1)
    18. def check_domains(new_tok, corpus_by_domain, unk_id_new):
    19. report = {}
    20. for domain, texts in corpus_by_domain.items():
    21. n_tok = n_unk = n_fail = 0
    22. for text in texts:
    23. ids = new_tok.encode(text)
    24. n_tok += len(ids)
    25. n_unk += sum(1 for i in ids if i == unk_id_new)
    26. if new_tok.decode(ids, skip_special_tokens=True) != text:
    27. n_fail += 1
    28. report[domain] = {
    29. "unk_rate": n_unk / max(n_tok, 1),
    30. "roundtrip_fail_rate": n_fail / max(sum(len(t) > 0 for t in texts), 1),
    31. }
    32. return report

    drift_rate checks “whether pruning changed encodings it shouldn’t have.” If every token of a text under the original tokenizer is retained, the new encoding must exactly match the mapped result. Any mismatch indicates an error in the merge paths or the mapping—fix it before evaluating gains.

    The round-trip check requires the decoded output to match the original text. Take extra care when texts contain special tokens or chat templates, since decoding behavior around them can cause false failures in this check.