Token-Free Language Models Using Discrete Codes

#language models #nlp #discrete codes #token-free #model architecture #encoding #decoding #machine learning #deep learning

1. Defining Token-Free Approaches in NLP

1.1 Defining Token-Free Approaches in NLP

Traditional language models rely on tokenization, where input text is segmented into discrete units (tokens) such as words, subwords, or characters. Token-free models bypass this step by operating directly on raw input sequences, typically using discrete codes or latent representations. This paradigm shift eliminates the need for explicit token boundaries, enabling more flexible and efficient processing of variable-length inputs.

Core Principles of Token-Free Modeling

Token-free approaches encode input sequences into fixed-dimensional discrete codes, which serve as compressed representations of the original data. The encoding process can be formulated as:

$$ \mathbf{z} = \text{Encoder}(x_{1:n}) $$

where x1:n represents the raw input sequence and z is the resulting discrete code vector. Unlike token-based methods that process sequences incrementally, token-free models often employ:

Mathematical Foundations

The discrete coding process typically involves vector quantization, where continuous embeddings are mapped to the nearest codebook entries. For a codebook C = {c1, ..., cK} containing K codes, the quantization operation is:

$$ \text{Quantize}(\mathbf{h}) = \arg\min_{c_k \in C} \|\mathbf{h} - c_k\|_2 $$

where h is the continuous hidden representation. The training objective combines reconstruction loss with commitment loss to ensure proper codebook usage:

$$ \mathcal{L} = \|\mathbf{x} - \text{Decoder}(\mathbf{z})\|_2^2 + \beta\|\text{sg}[\mathbf{h}] - \mathbf{z}\|_2^2 + \gamma\|\mathbf{h} - \text{sg}[\mathbf{z}]\|_2^2 $$

where sg[·] denotes the stop-gradient operation, and β, γ are weighting hyperparameters.

Advantages Over Token-Based Methods

Token-free models exhibit several key benefits:

Implementation Considerations

Practical implementations must address several challenges:

$$ \text{Gradients} = \nabla_\theta \mathcal{L}_{\text{recon}} + \nabla_C \mathcal{L}_{\text{commit}} $$

The straight-through estimator is commonly used to approximate gradients through the quantization operation:

$$ \nabla_\theta \mathbf{z} \approx \nabla_\theta \mathbf{h} $$

Modern architectures often employ multi-scale coding hierarchies, where different layers operate at varying levels of abstraction, from fine-grained character patterns to higher-level semantic concepts.

Applications and Performance

Token-free models have demonstrated strong performance in:

1.2 Limitations of Token-Based Models

Token-based language models, such as those using subword tokenization (e.g., Byte Pair Encoding or WordPiece), introduce several fundamental constraints that hinder their performance, efficiency, and generalization capabilities. These limitations stem from their reliance on discrete, predefined vocabularies and the rigid segmentation of input text.

1.2.1 Vocabulary Size and Out-of-Vocabulary (OOV) Problems

Token-based models operate with a fixed vocabulary, typically ranging from 30,000 to 100,000 subword units. This leads to two critical issues:

1.2.2 Context Fragmentation

Tokenization forces arbitrary splits on input sequences, which can disrupt syntactic and semantic relationships. Consider the sentence The quick brown fox jumps over the lazy dog. A tokenizer might split jumps into jump and ##s, decoupling the plural marker from the root verb. This fragmentation:

1.2.3 Computational Overhead

Tokenization adds non-trivial pre- and post-processing steps. The computational cost scales with:

$$ C_{\text{tokenize}} = O(n \log V) $$

where n is the input length and V is the vocabulary size. For large corpora, this overhead becomes significant compared to the actual forward pass of the model.

1.2.4 Multilingual and Cross-Domain Generalization

Token-based models struggle with languages that use non-Latin scripts or rich morphology (e.g., agglutinative languages like Turkish or Finnish). A vocabulary optimized for English may inefficiently represent other languages, leading to:

1.2.5 Information Bottleneck in Embedding Lookup

The embedding layer in token-based models maps discrete tokens to continuous vectors, creating an information bottleneck:

$$ \mathbf{e}_i = \mathbf{E} \mathbf{t}_i $$

where E is the embedding matrix and ti is a one-hot encoded token. This rigid mapping:

1.2.6 Case Study: Byte-Level Performance

Experiments comparing byte-level models (e.g., CANINE) to token-based BERT variants show:

Advantages of Discrete Codes

Discrete codes offer several computational and representational benefits over traditional token-based approaches in language modeling. By mapping continuous embeddings to a finite set of discrete symbols, these models achieve improved efficiency, interpretability, and robustness in sequence processing tasks.

Computational Efficiency

Discrete codes reduce memory and computational overhead by operating on compact integer representations rather than high-dimensional floating-point vectors. The compression ratio can be formalized as:

$$ R = \frac{d \cdot b_{\text{float}}}{k \cdot b_{\text{int}}} $$

where d is the embedding dimension, bfloat is the bits per float (typically 32), k is the codebook size, and bint is the bits per integer index (typically 8). For example, with d=1024 and k=8192, this yields a 16× reduction in memory usage.

Improved Generalization

The discrete bottleneck forces the model to learn compressed, information-dense representations. This acts as an implicit regularizer, preventing overfitting to training data artifacts. The information bottleneck objective can be expressed as:

$$ \mathcal{L}_{\text{IB}} = I(X; C) - \beta I(C; Y) $$

where I denotes mutual information between input X, codes C, and target Y, with β controlling the compression trade-off.

Interpretable Latent Structure

Discrete codes often develop human-meaningful patterns, with specific code indices correlating to syntactic or semantic features. This emerges from the competitive codebook learning process:

$$ \text{code}_i = \underset{j}{\arg\min} \| \mathbf{z} - \mathbf{e}_j \|_2 $$

where z is the continuous latent vector and ej are codebook embeddings. The resulting categorical distribution over codes provides direct insight into model decisions.

Robustness to Noise

The quantization process naturally filters high-frequency noise in the input space. For a noisy input = x + ε, the coding error is bounded by:

$$ \|\text{enc}(\mathbf{\tilde{x}}) - \text{enc}(\mathbf{x})\| \leq L \|\mathbf{\epsilon}\| + \delta $$

where L is the Lipschitz constant of the encoder and δ is the maximum codebook quantization error. This makes discrete representations particularly effective for speech and low-quality text inputs.

Scalability to Long Sequences

Token-free models using discrete codes demonstrate superior scaling to long contexts compared to conventional transformers. The memory complexity for a sequence of length n reduces from O(n2d) to O(nkd), enabling efficient processing of documents exceeding 105 elements. Recent architectures like Compressive Transformers leverage this property for few-shot learning on extended contexts.

2. What Are Discrete Codes?

What Are Discrete Codes?

Discrete codes in language models serve as an alternative to traditional tokenization, representing text as sequences of fixed-length integers derived from a learned or predefined codebook. Unlike token-based approaches that rely on subword segmentation or word-level units, discrete codes operate on a lower-level granularity, often mapping raw input bytes or characters to a compact set of numerical indices. This method eliminates the need for a token vocabulary, enabling more efficient representation and processing of multilingual or domain-specific text.

Mathematical Foundation

Given an input sequence x = (x1, x2, ..., xn), where each xi is a raw byte or character, a discrete code model applies a mapping function f to convert the sequence into fixed-length codes c = (c1, c2, ..., cm), where each cj ∈ {1, 2, ..., K} and K is the size of the codebook. The mapping is typically learned via quantization techniques such as Vector Quantization (VQ) or learned embeddings.

$$ f: x \rightarrow c \quad \text{where} \quad c_j = \arg\min_{k} \|E(x) - e_k\|^2 $$

Here, E is an encoder network that projects the input into a continuous space, and {e1, e2, ..., eK} are the codebook vectors. The decoder D reconstructs the original sequence from the codes:

$$ \hat{x} = D(c) = D(\arg\min_{k} \|E(x) - e_k\|^2) $$

Advantages Over Tokenization

Practical Applications

Discrete codes have been successfully applied in models like ByT5 and CANINE, which process text at the byte level. These models demonstrate competitive performance in multilingual tasks by avoiding the biases introduced by subword tokenization. Additionally, discrete codes enable seamless integration with multimodal architectures, where text and other modalities (e.g., images, audio) can be represented in a unified discrete space.

Challenges and Trade-offs

While discrete codes offer several advantages, they introduce challenges such as increased sequence length (since each byte or character is mapped individually) and the need for robust quantization methods to minimize reconstruction error. Hybrid approaches, combining discrete codes with lightweight tokenization, are an active area of research to balance efficiency and performance.

What Are Discrete Codes? – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the mapping process from raw input bytes to discrete codes via encoder and codebook, then reconstruction via decoder.

2.2 How Discrete Codes Replace Tokens

Token-free language models bypass traditional subword tokenization by operating directly on discrete numerical representations of raw text. Instead of segmenting input into tokens (e.g., via Byte Pair Encoding), these models map character sequences to fixed-length codes through learned embedding functions. The core mechanism involves:

Codebook-Based Embedding

A trainable codebook C ∈ ℝK×d maps discrete indices to dense vectors, where K is the codebook size and d the embedding dimension. Given an input character sequence x1:T, the model:

$$ e_t = \text{Embed}(x_t) \quad \text{(character-level)} $$ $$ z_t = \arg\min_{k \in \{1..K\}} \|e_t - C_k\|_2 \quad \text{(nearest-neighbor lookup)} $$

This replaces token embeddings with quantized codes that preserve linguistic structure while avoiding tokenization artifacts like rare-word fragmentation.

Dynamic Code Assignment

Unlike static vocabularies, discrete codes adapt to context through:

$$ p(z_t=k|x_t) = \frac{\exp(-\|e_t - C_k\|_2/\tau)}{\sum_{j=1}^K \exp(-\|e_t - C_j\|_2/\tau)} $$

Computational Advantages

Discrete codes reduce memory overhead compared to large token vocabularies. For a typical 50K-token BPE vocabulary:

$$ \text{Memory Savings} = 1 - \frac{K \times d}{|\mathcal{V}| \times d} = 1 - \frac{1024}{50000} \approx 98\% $$

where K=1024 codes achieve comparable performance in practice. The tradeoff involves increased compute for nearest-neighbor operations during encoding.

Implementation Example

Modern architectures like ByT5 and CANINE use:

How Discrete Codes Replace Tokens – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the hierarchical quantization process from ASCII characters to morphemes to words, and the nearest-neighbor lookup in the codebook.

2.3 Encoding and Decoding Strategies

Discrete Code Representation

Token-free models operate by mapping raw text to discrete latent codes, bypassing traditional tokenization. Given an input sequence x = (x1, ..., xn), the encoder E produces a sequence of discrete codes z = (z1, ..., zm), where each zi ∈ {1, ..., K} and mn. The compression ratio n/m is a critical hyperparameter balancing reconstruction fidelity with computational efficiency.

$$ z = \text{Quantize}(E(x)), \quad \text{where} \quad \text{Quantize}(v) = \arg\min_{k} \|v - e_k\|_2 $$

Here, {e1, ..., eK} denotes a learned codebook. The decoder D reconstructs the output by mapping codes back to continuous vectors before generating text autoregressively.

Dynamic Code Assignment

Unlike static token vocabularies, discrete codes adapt to input statistics. The Gumbel-Softmax trick enables differentiable sampling during training:

$$ p(z_i = k|x) = \frac{\exp((E(x)_i + g_k)/\tau)}{\sum_{j=1}^K \exp((E(x)_i + g_j)/\tau)} $$

where gk ∼ Gumbel(0,1) and τ is a temperature parameter. As τ → 0, this approaches hard assignment while maintaining gradient flow.

Hierarchical Decoding

Multi-scale codebooks improve expressiveness. A two-level hierarchy first predicts coarse codes zc then detail codes zd:

$$ p(z_i) = p(z_i^c)p(z_i^d|z_i^c) $$

This mirrors wavelet transforms in signal processing, where low-frequency components are encoded first. The computational cost scales as O(Kc + Kd) instead of O(KcKd).

Error Correction

Discrete codes introduce quantization errors. Residual vector quantization (RVQ) mitigates this by iteratively encoding residuals:

$$ r^{(t)} = r^{(t-1)} - \text{Quantize}(r^{(t-1)}), \quad r^{(0)} = E(x) $$

Each stage adds log2K bits of precision. In practice, 2-4 stages achieve near-continuous reconstruction with manageable overhead.

Applications in Efficient Inference

Code-based representations enable:

  • Subword skipping: Low-entropy regions can be represented with fewer codes
  • Early exit: Decoding terminates when residual energy falls below threshold
  • Adaptive compression: Dynamic bit allocation based on content complexity

For example, speech recognition systems using this approach achieve 3× faster inference than conventional transformers at equal WER.

Encoding and Decoding Strategies – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the hierarchical decoding process with coarse and detail codes, illustrating the multi-scale codebook structure and how residuals are iteratively quantized.

3. Model Design Principles

3.1 Model Design Principles

Discrete Code Representation

Token-free models replace traditional subword tokenization with learned discrete codes, enabling variable-length input segmentation. The core idea involves mapping raw text to a sequence of fixed-length codes via a neural encoder, typically a convolutional or transformer-based architecture. Given an input sequence x = (x1, ..., xn), the encoder produces a code sequence z = (z1, ..., zm), where each zi ∈ {1, ..., K} and K is the codebook size. The compression ratio n/m is dynamically adjusted based on input complexity.

$$ z_i = \argmax_{k \in \{1,...,K\}} \langle E(x_{i:i+w}), C_k \rangle $$

Here, E is the encoder, C is the codebook matrix, and w is the local context window. The argmax operation is relaxed during training using Gumbel-Softmax.

Hierarchical Codebook Architecture

Effective models employ multi-level codebooks to capture linguistic structure:

  • Phonetic-level codes for low-level acoustic/orthographic patterns
  • Morpheme-level codes for morphological units
  • Syntax-level codes for grammatical constructions

The hierarchical decomposition allows the model to learn composition rules similar to formal grammars. For example, the probability of a code sequence factors as:

$$ P(z) = \prod_{i=1}^L P(z_i^s | z_{

where superscripts denote syntactic (s), morphological (m), and phonetic (p) code layers.

Dynamic Code Prediction

Unlike fixed tokenization, discrete codes are predicted autoregressively using a latent variable model. The prediction head computes a mixture of logistic distributions over the codebook:

$$ p(z_t=k|z_{

where πi, μi, si are the mixture weights, means, and scales respectively. This formulation enables soft boundary detection between linguistic units.

Training Objectives

The model jointly optimizes:

  • Reconstruction loss: L1 distance between original and decoded text features
  • Code sparsity loss: L0 regularization on code activations
  • Predictive coding loss: Cross-entropy on next-code prediction

The complete objective function becomes:

$$ \mathcal{L} = \mathbb{E}_{x \sim \mathcal{D}} \left[ \|x - D(z)\|_1 + \lambda \|z\|_0 - \sum_{t=1}^T \log p(z_t|z_{

where D is the decoder and λ controls sparsity.

Computational Efficiency

Key optimizations include:

  • Locally banded attention for code sequence modeling (O(n√n) complexity)
  • Differentiable codebook lookup via vector quantization
  • Dynamic batching of variable-length code sequences

This architecture achieves 2-3× faster inference than comparable token-based models while maintaining competitive perplexity on benchmarks like PG-19 and C4.

Model Design Principles – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The hierarchical codebook architecture and dynamic code prediction involve multi-level relationships and mixture distributions that are spatially complex to describe in text alone.

3.2 Key Components and Layers

Discrete Code Embedding Layer

The discrete code embedding layer replaces traditional token embeddings by mapping input sequences to a learned set of discrete codes. Given an input sequence x, the embedding layer applies a quantization function Q to project continuous representations into a discrete latent space:

$$ Q(x) = \arg\min_{c \in C} \|E(x) - c\|_2 $$

where C is a fixed-size codebook of learned embeddings and E is a trainable encoder. This layer enables variable-length input handling without explicit token boundaries.

Hierarchical Convolutional Encoder

A stack of dilated convolutional layers processes the embedded discrete codes at multiple temporal resolutions. The hierarchical structure captures local and global dependencies through increasing receptive fields. For layer l, the convolution operation with dilation rate dl is:

$$ h_l[i] = \sum_{k=1}^K W_l[k] \cdot h_{l-1}[i - d_l \cdot k] $$

where Wl are learnable filters and K is the kernel size. The dilation rates typically follow an exponential progression (1, 2, 4, 8,...) to efficiently expand the context window.

Adaptive Self-Attention Mechanism

The model employs a modified self-attention layer that operates directly on discrete code sequences. Unlike standard attention, it incorporates relative position biases and code-specific attention gates:

$$ \text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}} + B_{ij}\right) \odot G(V) $$

where Bij encodes relative positions between codes i and j, and G is a gating function conditioned on the discrete code values.

Dynamic Code Prediction Head

The output layer predicts probabilities over the codebook space using a mixture of experts approach. For each position, the model selects among M expert networks based on the current context:

$$ P(c_t|x_{

where gm are learned gating weights and Pm are expert-specific distributions. This architecture enables specialized handling of different linguistic patterns while maintaining a compact code representation.

Gradient Estimation for Discrete Latents

Training involves gradient estimation through the discrete operations using straight-through estimators. The forward pass uses hard quantization while the backward pass approximates gradients:

$$ \nabla_\theta Q(x) \approx \nabla_\theta E(x) $$

This allows end-to-end training despite the non-differentiable quantization step. Recent variants employ more sophisticated estimators like REBAR or RELAX for lower variance gradients.

Key Components and Layers – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the hierarchical structure of the convolutional encoder with dilation rates and the flow of discrete codes through the system.

3.3 Training Methodologies

Discrete Codebook Optimization

The training of token-free language models relies on learning a discrete codebook C ∈ ℝK×d, where K is the number of codes and d is the embedding dimension. The model learns to map input sequences to variable-length code sequences through a quantization process. Given an input sequence x1:T, the encoder E produces continuous representations zt = E(xt), which are then quantized to the nearest codebook entry:

$$ \hat{z}_t = \arg\min_{c_k \in C} \|z_t - c_k\|_2 $$

The training objective combines reconstruction loss with commitment loss to ensure the encoder commits to codebook entries:

$$ \mathcal{L} = \|x - D(\hat{z})\|_2^2 + \beta\|z - \text{sg}[\hat{z}]\|_2^2 $$

where D is the decoder, sg[·] denotes the stop-gradient operation, and β controls the commitment strength (typically β = 0.25).

Variable-Length Sequence Modeling

Unlike token-based models that process fixed-length tokens, discrete code models must handle variable-length code sequences. This is achieved through:

  • Dynamic chunking: Inputs are segmented into variable-length chunks using learned boundary predictors
  • Hierarchical pooling: Multi-scale representations are created by pooling codes at different temporal resolutions
  • Relative position embeddings: Allow the model to process codes regardless of absolute positions

The probability of a code sequence c1:N given input x is factorized autoregressively:

$$ p(c_{1:N}|x) = \prod_{i=1}^N p(c_i|c_{

Efficient Training Strategies

Training large-scale discrete code models requires specialized techniques:

Codebook Reinitialization

Periodically reinitialize underutilized codes by:

$$ c_k \leftarrow \mathbb{E}[z_t | \hat{z}_t = c_k] $$

with a threshold for codes used less than γ% of samples (typically γ = 0.1).

Gradient Estimation

Straight-through estimator is used to backpropagate through quantization:

$$ \nabla_\theta \hat{z} \approx \nabla_\theta z $$

Recent variants use learned soft assignments during forward pass while maintaining hard assignments for inference.

Multi-Task Training Objectives

Modern implementations often combine multiple objectives:

  • Reconstruction loss:x - D()‖22 for faithful input reproduction
  • Perceptual loss:Φ(x) - Φ(D())‖22 where Φ is a pretrained feature extractor
  • Adversarial loss: D(D()) to improve sample quality
  • Code diversity loss: -H(p(c)) to prevent code collapse

The complete training objective becomes:

$$ \mathcal{L}_{\text{total}} = \lambda_1\mathcal{L}_{\text{recon}} + \lambda_2\mathcal{L}_{\text{perc}} + \lambda_3\mathcal{L}_{\text{adv}} + \lambda_4\mathcal{L}_{\text{div}} $$

with λi typically determined through validation performance.

Training Methodologies – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the quantization process from continuous encoder outputs to discrete codebook entries, including the reconstruction and commitment loss paths.

4. Use Cases in Machine Translation

4.1 Use Cases in Machine Translation

Efficiency in Cross-Lingual Representation

Token-free models leverage discrete codes to represent subword units, bypassing the need for explicit tokenization. In machine translation (MT), this approach eliminates language-specific tokenizers, enabling a unified representation space. For example, a single sequence of discrete codes can encode both English and Mandarin subword structures, reducing preprocessing overhead. The model learns a shared embedding space where semantically similar units across languages map to proximate code vectors, improving alignment during translation.

Handling Morphologically Rich Languages

Languages with complex morphology (e.g., Finnish, Turkish) benefit from token-free models due to their ability to dynamically segment words into compositional codes. Traditional tokenizers struggle with agglutinative structures, often fragmenting words into impractical subword units. Discrete codes, however, adaptively represent morphemes as combinations of latent symbols. For a Finnish word like "taloissani" ("in my houses"), the model might decompose it into codes for "talo" (house), "i" (plural), "ssa" (inessive case), and "ni" (possessive), preserving grammatical meaning without predefined splits.

$$ \text{Code}(w) = \{c_1, c_2, ..., c_k\}, \quad c_i \in \mathcal{V}_\text{code} $$

where w is a word, c_i are discrete codes, and 𝒱_code is the code vocabulary.

Low-Resource Translation

Token-free models excel in low-resource settings by leveraging transfer learning across languages. Discrete codes act as a pivot representation: a model pretrained on high-resource language pairs (e.g., English-French) can generalize to unseen pairs (e.g., Swahili-Tamil) by aligning their code distributions. This is formalized through cross-entropy minimization over shared code embeddings:

$$ \mathcal{L}_\text{MT} = -\sum_{(x,y)} \log P_\theta(\text{Code}(y) \mid \text{Code}(x)) $$

where x and y are source and target sentences, and θ denotes model parameters.

Case Study: Byte-Level Neural MT

Byte-based models (e.g., ByT5) demonstrate token-free translation by treating raw UTF-8 bytes as discrete codes. A byte sequence for "你好" (nǐ hǎo) might be represented as [0xE4, 0xBD, 0xA0, 0xE5, 0xA5, 0xBD], bypassing CJK tokenization entirely. Benchmarks show competitive BLEU scores with 2–3× faster inference than subword models, as byte sequences eliminate vocabulary lookup steps.

Latency and Memory Trade-offs

While token-free models reduce preprocessing latency, they may increase sequence lengths. For a 10-word English sentence, a subword model might emit 12 tokens, whereas a byte model emits ~40 codes. Transformer self-attention's O(n²) complexity thus becomes a bottleneck. Solutions include:

  • Hierarchical pooling: Aggregating codes into chunks (e.g., 4-byte blocks) before attention.
  • Hybrid approaches: Using discrete codes for training but dynamic tokenization for inference.
Use Cases in Machine Translation – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show how discrete codes dynamically segment a morphologically rich word (e.g., 'taloissani') into compositional morphemes, contrasting with traditional tokenization.

4.2 Text Generation Without Tokens

Traditional language models rely on tokenization, where text is split into subword units or characters before processing. Token-free approaches bypass this step by operating directly on raw bytes or learned discrete codes, enabling more flexible and efficient generation. The core mechanism involves mapping input sequences to a fixed set of codes, which are then processed autoregressively.

Discrete Code Representation

Instead of tokens, the input text x is transformed into a sequence of discrete codes c1, c2, ..., cn using a learned codebook. Each code ci is an integer indexing a high-dimensional embedding vector. The codebook is trained jointly with the model via vector quantization (VQ), minimizing the reconstruction error:

$$ \mathcal{L}_{VQ} = \|x - \text{Decoder}(c)\|^2_2 + \|\text{sg}[E(x)] - e_c\|^2_2 + \|\text{sg}[e_c] - E(x)\|^2_2 $$

where E is the encoder, sg denotes the stop-gradient operation, and ec is the codebook embedding. The first term ensures accurate reconstruction, while the latter two terms align the encoder outputs with the codebook.

Autoregressive Generation

Given a sequence of codes, generation proceeds autoregressively by predicting the next code ct conditioned on previous codes c<t. The model computes a distribution over the codebook:

$$ P(c_t | c_{<t}) = \text{softmax}(W h_t + b) $$

where ht is the hidden state from a transformer or RNN, and W, b are learnable parameters. Sampling strategies like top-k or nucleus filtering can be applied to improve output quality.

Advantages Over Token-Based Models

  • No Out-of-Vocabulary Issues: Since codes are learned from data, there is no fixed vocabulary limit.
  • Multilingual Support: The same codebook can represent multiple languages without explicit tokenization rules.
  • Efficiency: Operating on raw bytes or codes reduces preprocessing overhead and memory usage.

Practical Implementation

Implementing a token-free model requires:

  • A pretrained codebook (e.g., using VQ-VAE or similar methods).
  • An autoregressive architecture (e.g., Transformer) modified to predict discrete codes.
  • Efficient nearest-neighbor search for code assignment during inference.

For example, a transformer-based model can be trained with a cross-entropy loss over the codebook indices, treating code prediction as a classification task. During inference, the generated codes are mapped back to text via the decoder.

Case Study: ByT5

ByT5 demonstrates the effectiveness of token-free approaches by operating directly on UTF-8 bytes. It achieves competitive performance on multilingual tasks without language-specific tokenizers, highlighting the scalability of byte-level modeling.

Text Generation Without Tokens – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the transformation pipeline from raw text to discrete codes, including the encoder, codebook, and decoder interactions.

4.3 Performance Benchmarks

Comparative Analysis Against Token-Based Models

Token-free architectures demonstrate competitive performance across standard NLP benchmarks while offering computational advantages. On the GLUE benchmark suite, discrete code models achieve within 2-3% of BERT's accuracy while reducing sequence length by 40-60%. The compression ratio r between input text and discrete codes follows:

$$ r = \frac{L_{\text{tokens}}}{L_{\text{codes}}} \approx 1.8 \pm 0.3 $$

where L represents sequence length. This compression directly translates to faster attention computation, with theoretical FLOPs scaling as O(rL2) instead of O(L2).

Memory Efficiency Metrics

Discrete code models reduce memory consumption in three key aspects:

  • Embedding tables: 256-1024 codebook entries vs. 30k+ token vocabularies
  • Attention key-value caches: 35-60% smaller for equivalent context windows
  • Gradient buffers: 28% reduction in backpropagation memory

Quantitative measurements on the Pile dataset show memory-per-token ratios:

$$ \frac{M_{\text{code}}}{M_{\text{token}}} = 0.62 \pm 0.08 $$

Latency and Throughput

Autoregressive generation speed improves non-linearly with sequence length due to reduced memory bandwidth pressure. Benchmarks on A100 GPUs show:

Model Type Tokens/sec (1024 ctx) Tokens/sec (4096 ctx) Scaling Factor
Token-based 1420 680 2.09x↓
Discrete Code 1870 1120 1.67x↓

Downstream Task Adaptation

Fine-tuning efficiency improves due to compressed representations. On the SuperGLUE benchmark, discrete code models reach 90% of peak performance with 40% fewer training steps compared to token-based equivalents. The adaptation dynamics follow:

$$ \frac{d\mathcal{L}}{dt} \propto \frac{1}{\sqrt{d_{\text{code}}}} $$

where dcode is the code dimension, typically 64-256 vs. 768-1024 for token embeddings.

Long-Context Performance

The compressed nature of discrete codes enables more effective long-context processing. On the SCROLLS benchmark, code-based models maintain 83% accuracy at 32k context length where token models degrade to 61%, demonstrating superior attention entropy:

$$ H_{\text{attn}} = -\sum_{i=1}^{L}p_i\log p_i $$

with code models showing 18-22% lower entropy at each layer, indicating more focused attention patterns.

5. Scalability Issues

5.1 Scalability Issues

Token-free language models based on discrete codes face unique scalability challenges due to their reliance on learned codebooks and variable-length encoding schemes. Unlike token-based models that operate on fixed vocabularies, these systems must dynamically manage codebook growth while maintaining computational efficiency during training and inference.

Memory and Computational Complexity

The memory requirements for discrete code models scale with both the codebook size K and the sequence length L. The attention mechanism's complexity becomes:

$$ \mathcal{O}(L^2 \cdot d + K \cdot d) $$

where d represents the embedding dimension. This quadratic dependence on sequence length combined with linear codebook scaling creates bottlenecks when processing long documents. Recent work by Tay et al. (2022) shows that hybrid approaches using locality-sensitive hashing can reduce this to O(L log L), but at the cost of increased memory fragmentation.

Codebook Growth and Compression Tradeoffs

As model capacity increases, the optimal codebook size grows sublinearly with training data:

$$ K_{opt} \propto N^\alpha \quad \text{where} \quad \alpha \approx 0.4-0.6 $$

This relationship emerges from the information-theoretic bounds on code efficiency. Practical implementations must balance:

  • Codebook lookup latency: Larger K increases GPU memory bandwidth pressure
  • Compression ratio: More codes enable better sequence compression but require longer training
  • Generalization: Overly large codebooks lead to code underutilization (Zipfian distribution)

Distributed Training Challenges

Data parallelism becomes inefficient when codebook parameters exceed GPU memory capacity. Model parallelism introduces synchronization overhead during code assignment:

$$ \tau_{sync} = \frac{K \cdot d \cdot p}{B} + p \cdot t_{latency} $$

where p is the number of devices and B the interconnect bandwidth. Current solutions employ:

  • Hierarchical codebooks with device-local caching
  • Dynamic code routing using learned importance scores
  • Quantized gradient communication for code updates

Long-Range Dependency Modeling

Discrete codes introduce additional challenges in capturing long-range dependencies compared to token-based models. The effective context window shrinks due to:

$$ L_{eff} = \frac{L}{C} - \Delta_{overlap} $$

where C is the average compression ratio and Δoverlap represents the necessary overlap between encoded segments. Recent architectures address this through:

  • Cross-segment attention with memory banks
  • Recurrent state propagation between code sequences
  • Learned positional interpolation schemes

The computational overhead of these solutions typically scales as O(Leff1.5), creating diminishing returns for very long sequences.

5.2 Handling Rare or Out-of-Distribution Inputs

Token-free language models, which operate on discrete codes rather than traditional subword tokens, face unique challenges when processing rare or out-of-distribution (OOD) inputs. Unlike token-based models that can fall back on subword decomposition, code-based models must rely on their learned discrete representations, making robustness to unseen patterns critical.

Codebook Expansion for Rare Inputs

When encountering rare sequences, the model can dynamically expand its codebook by introducing new codes. Given an input sequence x with low probability under the current codebook C, the model computes:

$$ p(x|c_i) < \tau \quad \forall c_i \in C $$

where τ is a rarity threshold. If this condition holds, the model generates a new code cnew by:

$$ c_{new} = \text{Encoder}(x) $$

and updates the codebook C' = C ∪ {cnew}. This approach maintains the model's ability to represent novel inputs without retraining.

Uncertainty Quantification for OOD Detection

For OOD detection, the model can leverage the code assignment probabilities. Let q(c|x) be the probability of assigning code c to input x. The uncertainty score U(x) is computed as:

$$ U(x) = 1 - \max_{c \in C} q(c|x) $$

High values of U(x) indicate inputs that are poorly represented by existing codes. In practice, models can use this score to trigger fallback mechanisms or human review.

Fallback Strategies

When rare or OOD inputs are detected, several fallback strategies can be employed:

  • Nearest-code projection: Map the input to the most similar existing code using a distance metric in the embedding space.
  • Hierarchical decomposition: Break down the input into constituent parts that may have existing codes.
  • External memory lookup: Query an external database of rare patterns and their associated codes.

Case Study: Robustness in Multilingual Settings

In multilingual models using discrete codes, rare scripts or characters can be handled by:

$$ p_{fallback}(x) = \sum_{c \in C_{base}} p(c|x)p(x|c) $$

where Cbase represents a set of fundamental, script-agnostic codes. This allows the model to maintain functionality even for unseen writing systems while gradually learning new script-specific codes during deployment.

Handling Rare or Out-of-Distribution Inputs – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the dynamic codebook expansion process and fallback strategies with clear visual separation of existing codes, new code generation, and decision thresholds.

Integration with Existing NLP Pipelines

Token-free language models based on discrete codes introduce unique challenges and opportunities when integrated into conventional NLP pipelines. Unlike token-based approaches that rely on predefined vocabularies, these models operate on learned discrete representations that may not align directly with standard preprocessing steps.

Preprocessing Alignment

Traditional NLP pipelines typically include tokenization, stemming, and stopword removal - operations designed for word or subword tokens. For discrete code models, raw text must first be converted into the model's native code sequence format. This requires:

  • A trained encoder to map character sequences to discrete codes
  • Special handling of out-of-vocabulary characters through fallback mechanisms
  • Optional code sequence normalization to match training distribution
$$ E: \mathcal{X} \rightarrow \mathcal{C}^* $$

where E is the encoding function mapping input text 𝒳 to variable-length code sequences 𝒞*.

Pipeline Modifications

Standard NLP components require adaptation to handle code sequences:

  • Embedding layers must be replaced with code-specific lookup tables
  • Attention mechanisms need adjustment for code-based positional encoding
  • Batch processing requires padding/truncation at the code level rather than token level

The dimensional mismatch between code-based representations and traditional word embeddings necessitates careful projection layers when connecting to existing components:

$$ \mathbf{W}_{proj} \in \mathbb{R}^{d_{code} \times d_{embed}} $$

Hybrid Approaches

Some pipelines benefit from hybrid token-code architectures:

  • Using codes for early processing stages where sequence length matters
  • Converting to tokens for downstream tasks requiring interpretability
  • Joint training with both representations through shared latent spaces

The interface between code-based and token-based components can be implemented through:

$$ \mathbf{h}_{token} = \text{MLP}(\text{Pool}(\mathbf{H}_{code})) $$

where Hcode is the code representation matrix and Pool is an adaptive pooling operation.

Performance Considerations

Integration impacts several practical aspects:

  • Memory usage typically decreases due to shorter code sequences compared to tokens
  • Computational efficiency varies by operation - matrix multiplies benefit while certain string operations may suffer
  • Latency profiles change as encoding/decoding overhead replaces tokenization

Empirical measurements show the tradeoff curve between sequence length reduction and computational overhead follows:

$$ t_{total} = t_{encode} + \alpha L_{code} + t_{decode} $$

where Lcode is the code sequence length and α is the per-code processing time.

Integration with Existing NLP Pipelines – Token-Free Language Models Using Discrete Codes – Tutorial Diagram
Diagram Description: The diagram would show the transformation pipeline from raw text to code sequences and how they interface with traditional NLP components, highlighting dimensional mismatches and projection layers.

6. Key Research Papers

6.1 Key Research Papers

  • ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models — Abstract. Most widely used pre-trained language models operate on sequences of tokens corresponding to word or subword units. By comparison, token-free models that operate directly on raw text (bytes or characters) have many benefits: They can process text in any language out of the box, they are more robust to noise, and they minimize technical debt by removing complex and error-prone text ...
  • CL M-TTS: IMPROVING NEURAL CODEC LANGUAGE MODELING FOR Z ... - OpenReview — discrete codes. We interchangeably use c t,1:D with c t. Subsequently, a neural language model p θ(c 1:T|x) is employed, aiming to predict c 1:T from the text transcript x. During the inference phase, the language model generates c 1:Tfor a given text x, which is subsequently transformed into speech through the VAE decoder and a pre-trained ...
  • PDF LiveSpeech: Low-Latency Zero-shot Text-to-Speech via Autoregressive ... — Recent research has demonstrated that zero-shot TTS can be accomplished by harnessing the capabilities of language models on discrete tokens obtained from neural audio codecs [1, 5]. However, due to the high bandwidth nature of audio, a single audio frame is usually represented by multiple codes, which may also be sequentially dependent [6 ...
  • PDF ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models — They can process text in any language out of thebox,theyaremorerobusttonoise,andthey minimize technical debt by removing complex and error-prone text preprocessing pipelines. Because byte or character sequences are longer than token sequences, past work on token-free models has often introduced new model ar-chitectures designed to amortize the ...
  • PDF ByGPT5 : End-to-End Style-conditioned Poetry Generation with Token-free ... — style by a special token which we add to the model vocabulary. We use ByT5 (Xue et al.,2022), a token-free pre-trained encoder-decoder model, as a baseline. For comparison with subword-level approaches, we ne-tune mT5 (Xue et al.,2021b). Decoder-only As the input for encoder-decoder models is a relatively short sequence of styles, this
  • Token Assorted: Mixing Latent and Text Tokens for Improved Language ... — map CoT tokens Cinto discrete latent tokens Z. To enhance abstraction performance, our VQ-VAE is trained on the whole input sequence X, but only applied to Cin the next stage. FollowingJiang et al.(2022;2023), we split Xinto chunks of length Land encode each chunk into L r latent codes, where ris a preset compression rate. More precisely,
  • Token Assorted: Mixing Latent and Text Tokens for - arXiv.org — Reasoning capabilities are increasingly recognized as a critical component of Artificial General Intelligence (AGI) systems. Recent research has demonstrated that Large Language Models (LLMs) can exhibit sophisticated reasoning and planning abilities using chain-of-thought (CoT) methodologies, including prompting LLMs with examples where complex problems are broken down into explicit reasoning ...
  • PDF Undetectable Watermarks for Language Models - IACR — language models. That is, watermarks can be detected only with the knowledge of a secret key; without the secret key, it is computationally intractable to distinguish watermarked outputs from those of the original model. In particular, it is impossible for a user to observe any degradation in the quality of the text.
  • Can Discrete Information Extraction Prompts Generalize Across Language ... — model should meaningfully transfer to another model. Discretizing soft prompt tokens to their near-est vocabulary neighbours in order to overcome these issues does not help either. Khashabi et al. (2021) demonstrated that it is possible to find well-performing soft prompts whose nearest neighbor projections are arbitrarily fixed discrete tokens.
  • ByGPT5: End-to-End Style-conditioned Poetry Generation with Token-free ... — In particular, we successfully pre-train and release ByGPT5, a new token-free decoder-only language model, and fine-tune it on a large custom corpus of English and German quatrains annotated with ...

6.2 Recommended Books and Articles

  • Matthew Dahl Abstract - arXiv.org — sources (e.g., law review articles, books, dic-tionaries); and signals. Each case law task consists of information from ... 6(2). Colleen V. Chien and Miriam Kim. 2025.Generative AI and Legal Aid: Results from a Field Study and ... How Language Models Use Long Contexts. Transactions of the Asso-ciation for Computational Linguistics, 12:157 ...
  • ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models — Abstract. Most widely used pre-trained language models operate on sequences of tokens corresponding to word or subword units. By comparison, token-free models that operate directly on raw text (bytes or characters) have many benefits: They can process text in any language out of the box, they are more robust to noise, and they minimize technical debt by removing complex and error-prone text ...
  • Dissertation - eldorado.tu-dortmund.de — commercial books about language: The language instinct [Pin94]. In linguistics, researchers investigate and study language in all its aspects. Understanding language is the key to understand the history and the development of mankind. From the beginning of language studies, major directions in the field of linguistics have developed.
  • PDF Evaluating Text-to-Speech Synthesis from a Large Discrete Token-based ... — 6466. modelEnCodec(Défossezetal.,2023),whichcom-pressesspeechaudiointo8separatecodebooks eachofsize1024at75Hz.Semantic-to-coarse ...
  • Large language models in medical and healthcare fields: applications ... — Large language models (LLMs) are increasingly recognized for their advanced language capabilities, offering significant assistance in diverse areas like medical communication, patient data optimization, and surgical planning. Our survey meticulously searched for papers with keywords such as "medical," "clinical," "healthcare," and "LLMs" across various databases, including ACM ...
  • PDF ZKPDL: A Language-Based System for Efficient Zero-Knowledge ... - KU — to use these protocols in practice, despite a wealth of po-tential applications. This paper introduces a simple description language, ZKPDL, and an interpreter for this language. ZKPDL implements non-interactive zero-knowledge proofs of knowledge, a primitive which has received much atten-tion in recent years. Using our language, a single pro-
  • Crypto Tokens and Token Systems | Information Systems Frontiers - Springer — Cyptographic tokens are one of the cornerstones of the new blockchain world but the knowledge about these digital objects is still limited. In this research, we argue that crypto tokens, cryptographically secured digital tokens connected to DLT systems, form socio-technical systems through their reciprocal relationship with their foundational DLT systems. We also argue that today's crypto ...
  • Classifiers Guided Controllable Text Generation for Discrete Diffusion ... — Figure 1 illustrates the generation process of the discrete diffusion language model. Starting with a fully masked sequence \(X_T\), the model proceeds through multiple iterations to produce the final generated text \(X_0\).Each iteration comprises two operation: prediction and masking. In the prediction step, the model using the partially masked sequence from the previous iteration to predict ...
  • 402 results in SearchWorks catalog — all catalog, articles, website, & more in one search catalog books, media & more in the Stanford Libraries' collections articles+ journal articles & other e-resources
  • A Retrieval Augmented Approach to Improving Accuracy of Biomedical Term ... — a retrieval augmented approach to improving accuracy of biomedical term normalization by large language models by thanh son do a master's thesis

6.3 Online Resources and Tutorials

  • ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models — Abstract. Most widely used pre-trained language models operate on sequences of tokens corresponding to word or subword units. By comparison, token-free models that operate directly on raw text (bytes or characters) have many benefits: They can process text in any language out of the box, they are more robust to noise, and they minimize technical debt by removing complex and error-prone text ...
  • T-FREE: Tokenizer-Free Generative LLMs via Sparse Representations for ... — Figure 1: Method comparison of classic Tokenization (left) and T-Free (right) for text encoding (top) and decoding (bottom). Classic tokenizers learn a single-label vocabulary, i.e. a token is bijectively mapped into a single entry of the vocabulary. Instead, T-Free uses a bijective multi-label mapping over multiple activations of hashed character trigrams.
  • 9.3. Language Models — Dive into Deep Learning 1.0.3 documentation - D2L — where statistical tools in Section 9.1 can be applied.. Language models are incredibly useful. For instance, an ideal language model should generate natural text on its own, simply by drawing one token at a time \(x_t \sim P(x_t \mid x_{t-1}, \ldots, x_1)\).Quite unlike the monkey using a typewriter, all text emerging from such a model would pass as natural language, e.g., English text.
  • PDF ByT5: Towards a Token-Free Future with Pre-trained Byte-to-Byte Models — token-based model and perform the minimal set of modifications to make it token-free, thereby limiting experimental confounds. We base ByT5 on the recent mT5 model (Xue et al., 2021), which 2Previous work has also developed token-free approaches for specific tasks: Gillick et al. (2016) for span labeling, Li
  • Google AI Gemma open models - Google for Developers — Gemma 3's 128K-token context window lets your applications process and understand vast amounts of information enabling more sophisticated AI capabilities. ... Practical examples & tutorials for Google's open models. Explore notebooks. Hugging Face. ... MATH evaluates a language model's ability to solve complex mathematical word problems ...
  • ByGPT5: End-to-End Style-conditioned Poetry Generation with Token-free ... — In particular, we successfully pre-train and release ByGPT5, a new token-free decoder-only language model, and fine-tune it on a large custom corpus of English and German quatrains annotated with ...
  • NLTK :: Natural Language Toolkit — Natural Language Toolkit¶. NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries, and ...
  • [2406.19223] T-FREE: Tokenizer-Free Generative LLMs via Sparse ... — As such, the benchmark results compare a Unigram model with 1.07 B 1.07 𝐵 1.07B parameter against a T-Free model with 0.84 B 0.84 𝐵 0.84B parameters (for v = 8 k 𝑣 8 𝑘 v=8k). Consequently, we demonstrate that an LLM using T-Free instead of Unigram performs better, despite having over 20% fewer parameters.
  • PDF LiveSpeech: Low-Latency Zero-shot Text-to-Speech via Autoregressive ... — Audio Generation via Discrete Tokens The compression rate and reconstruction quality of RVQ codes inspire a number of works to formulate audio generation as a language model-ing task; however predicting codes sequentially poses a chal-lenge of high inference time. MusicGen [3] proposes reduc-ing the context size by predicting Q codes together ...
  • GitHub - eugeneyan/open-llms: A list of open LLMs available for ... — OpenRAIL-M v1: Allows royalty-free access and flexible downstream use and sharing of the model and modifications of it, and comes with a set of use restrictions (see Attachment A) BSD-3-Clause : This version allows unlimited redistribution for any purpose as long as its copyright notices and the license's disclaimers of warranty are maintained.