Large collections of DNA, protein, and text are extremely repetitive: a pangenome, a transposable-element library, or a news archive contains the same long stretches many times over. Grammar compression stores such a collection as a small set of rewriting rules, each saying "this symbol stands for that pair of symbols." The total number of rules, $g$, can be far smaller than the raw length $N$. Algorithms that work directly on these rules can answer search questions in time that depends on $g$ instead of $N$. Machine learning has mostly not benefited from this. The one direct attempt, Learning Directly from Grammar Compressed Text, trains a small neural "composer" that builds an embedding for each rule from the embeddings of its two parts. It is faster than reading the raw text, but it loses accuracy: error on Sogou News rises from 4.18% to 5.14%, and DNA accuracy drops by up to 5 points. We believe the loss has a specific structural cause. The composer is not associative, so one substring gets a different embedding depending on how the compressor happened to split it. Repeats of a period ($B$ repeated $k$ times) get no algebraic treatment at all.
We propose a sequence model whose embedding of any substring is a fixed function of that substring alone, no matter which grammar produced it. The model is a recurrence whose steps compose associatively, so rule embeddings are exact summaries. Under it, a run of $k$ copies of a period collapses to a closed-form expression costing $O(1)$. Training and inference then cost $O(g)$, and the output is provably identical, up to floating-point rounding, to running the same model on the decompressed text. On a balanced run-length grammar, the embedding of any window $T[i..j]$ can be read off in $O(\log n)$ time. That makes sliding-window annotation of a whole genome cheap. A probabilistic label tree, a classifier that routes each input down a tree of label groups so that only about $\log K$ of the $K$ labels are scored, sits on top and handles large repeat-family taxonomies.
Core Claim
Consider a diagonal affine recurrence $h_t = a(x_t)\odot h_{t-1} + b(x_t)$, where $x_t$ is the $t$-th symbol, $h_t\in\mathbb{R}^d$ is the hidden state, and $a(\cdot), b(\cdot)$ are learned per-symbol vectors. For classification we also want a pooled summary, the sum of hidden states over a fragment. Each fragment $F$ can then be summarized by four vectors $(\alpha_F,\beta_F,\sigma_F,\tau_F)$. Here $\alpha_F,\beta_F$ give the state after $F$ as $\alpha_F\odot h + \beta_F$ from entry state $h$, and $\sigma_F,\tau_F$ give the pooled sum as $\sigma_F\odot h+\tau_F$. These summaries compose exactly for a rule $A\to BC$:
$$\alpha_A=\alpha_C\alpha_B,\quad \beta_A=\alpha_C\beta_B+\beta_C,\quad \sigma_A=\sigma_B+\sigma_C\alpha_B,\quad \tau_A=\tau_B+\sigma_C\beta_B+\tau_C,$$
with all products elementwise. Because this composition is associative, every parse of a string yields the same summary. That is the property the composer of Sasaki et al. lacks.
For a run rule $A\to B^k$, the summary is a geometric series in $\alpha_B$:
$$\alpha_A=\alpha_B^{k},\qquad \beta_A=\beta_B\,\frac{1-\alpha_B^{k}}{1-\alpha_B},$$
with similar sums for $\sigma_A$ and $\tau_A$. This is the learning-side counterpart of the string-combinatorics fact used in Logarithmic-Time Internal Pattern Matching Queries in Compressed and Dynamic Texts and Compressed consecutive pattern matching: overlapping occurrences of a pattern form an arithmetic progression, so the whole progression can be handled as one object. Here a whole periodic cluster becomes one closed-form evaluation, regardless of $k$.
The pooled summary of the full sequence feeds a nonlinear readout and a label tree. The central claim has three parts. First, this model loses nothing to compression relative to its own uncompressed execution. Second, it runs in time proportional to $g$. Third, the remaining question is the expressiveness of the model class, which we test directly, not the effect of compression.
Research Program
The work has three components.
Exact compressed learner. The first component is the learner itself. We build run-length grammars by recompression, as in Duyster and Polak. Rule summaries are computed bottom-up, level by level on the GPU, reusing the depth-stratified rule batching of Sasaki et al.. Gradients flow through the composition rules and the closed-form run rules.
The model has one hard limitation. Making $a$ and $b$ depend on the hidden state, or stacking a second recurrent layer on the first layer's outputs, breaks the per-symbol property that makes compression exact. We address expressiveness in two ways. We use many independent heads, each with its own $a$ and $b$. We also let terminals be short $q$-grams rather than single characters, which trades grammar size against context. The deep nonlinearity sits only in the readout.
Window queries. The second component turns the grammar into a static index over fragments. Each node of the balanced parse tree stores its summary, so any window $T[i..j]$ decomposes into $O(\log n)$ canonical nodes plus boundary pieces. Its embedding is then the composition of those stored summaries.
This deliberately avoids the design of the β-window search tree in Approximate Nearest Neighbor Search with Window Filters. That method also decomposes a range into $O(\log N)$ tree nodes, but it duplicates a full index at every node and pays 3x to 14x more memory. Our per-node payload is a constant number of $d$-vectors per rule, so the space stays $O(gd)$. This also addresses a limitation noted for Compressed consecutive pattern matching: that method re-traverses the grammar for every query, whereas ours is built once and queried repeatedly.
Label side. The third component is the classifier over labels. Transposable-element families form a deep taxonomy. CREATE handles it with nine hand-placed classifiers at the parent nodes, using uncompressed $k$-mer counts and features from the sequence ends. We instead train a probabilistic label tree in the style of Liu et al. on the pooled compressed embeddings. We test both the curated taxonomy and a learned clustering of the families. PLTs are known to fall behind flat classifiers as trees deepen: on ImageNet10K the tree reached about 21% against 24.84% for flat LIBLINEAR. So we treat the tree as a speed device whose cost in accuracy must be measured, not assumed away.
Decayed repeats, with substitutions and indels as handled by ULTRA, do not threaten correctness here. They only shorten runs and enlarge $g$. Noise therefore affects speed but never the output, and we measure that speed effect explicitly.
Baselines
Decompress, then run the same model. The naive reference point decompresses each sequence and runs the identical recurrence with a parallel scan over all $N$ symbols. This is the decompress-then-classify pipeline. It uses the same parameters, so its predictions must match ours up to floating-point rounding. Any disagreement larger than rounding is a bug. The comparison is purely in wall-clock time, peak memory, and energy on the same GPU. Beating it means lower cost at equal output on collections whose compression ratio $N/g$ exceeds a crossover point, which we report.
Sasaki et al. on the same grammars. The closest existing compressed learner is the Dual-GRU/MLP composer of Learning Directly from Grammar Compressed Text. We rerun it on the same grammars with the same hyperparameter search budget. Its reported Sogou News error is 5.14%, against 4.18% for an uncompressed Bi-LSTM. On histone DNA it reports a drop of under 5 points with a 3x speedup. Beating it means closing most of that 0.96-point gap at equal or better throughput.
Uncompressed Bi-LSTM. The 4.18% Sogou figure from the same paper sets the accuracy bar for our model class. If we cannot approach it, the limitation lies in the model class, not in compression.
CREATE for transposable elements. For TE classification, the strongest existing method is CREATE. It reports MCC above 0.850 on Dataset 1, beating TERL by up to 0.172, and an hF margin of 0.045 on Dataset 2. We use its released splits and compare to its reported numbers. Matching its MCC while operating on the compressed library counts as success. Exceeding it is not required.
Flat softmax versus tree on the label side. We compare a flat softmax with the PLT on identical embeddings. That isolates how much the tree costs in accuracy and what it saves in time.
Ablations isolating the key ingredient. Two ablations remove the run closed form while keeping associativity. One expands $B^k$ by repeated squaring. The other uses plain pair grammars without run rules. A third ablation replaces the associative composition with a non-associative MLP on otherwise identical grammars. If parse dependence is what causes Sasaki's accuracy loss, this variant should reproduce that loss.
Why not just…?
Why not just decompress and use a fast parallel scan? This is a real threat. A GPU scan on $N$ symbols is fast, and on modestly repetitive text like Sogou News the ratio $N/g$ may be too small for $O(g)$ work to matter. Our answer is empirical, not argued. We plot speedup against measured compression ratio across Sogou, histone DNA, TE libraries, and the T2T-CHM13 assembly.
The scan has no answer for repeated window queries. Annotating every window of a 3.2 Gb genome by decompress-and-scan costs time proportional to window length per window. Our index costs $O(\log n)$ per window. If the crossover occurs only at compression ratios that real corpora never reach, we will report that and narrow the claim to window querying.
Why not just compute $k$-mer counts and feed a classifier, as CREATE does? $k$-mer counts can themselves be computed from a grammar in time roughly proportional to $g$ times $k$, so compression does not favor our model over them. The case for our model rests on order sensitivity. CREATE itself reports that global $k$-mers fail on Class II DNA transposons and that local terminal-end structure is needed. Our recurrence sees order, and window queries can extract end-region summaries directly. The experiment that settles this is a grammar-computed $k$-mer baseline with the same label tree, evaluated per TE class. If it matches us on Class II, our order-sensitivity argument fails.
Why not just add run-length rules to Sasaki's composer? That would remove redundant work on runs. It would still leave parse dependence, because two grammars, or two positions in one grammar, can encode the same substring with different trees and get different embeddings. Our non-associative-MLP ablation on run-length grammars is exactly this alternative. If it matches our accuracy, the associativity argument is wrong, and the contribution reduces to the speed gained from closed-form runs.
Why not just a flat classifier over labels? For a few thousand families a flat softmax is affordable, and Liu et al. show trees cost accuracy. The tree earns its place only in genome-wide window annotation, where label scoring is repeated millions of times. We report both and recommend flat scoring wherever the tree's accuracy cost outweighs its speed benefit.
Proposed Experiments
Exactness check. On 3-Fibonacci strings up to $2^{32}$ symbols, the setting where Duyster and Polak report $O(\log n)$ query scaling and under 6KB of structure at $2^{20}$, we verify two things. Compressed and decompressed summaries must agree to floating-point tolerance. Window-query time must grow logarithmically. Failure on either point invalidates the approach.
Accuracy gap test. On Sogou News and histone DNA, we ask whether our compressed model, its uncompressed twin, Sasaki's composer, and the Bi-LSTM order as predicted. The twin must equal ours exactly. The non-associative ablation should land near Sasaki's 5.14%. Our open question is how far the model class itself sits from 4.18%.
Transposable elements. On CREATE Datasets 1 and 2, we report MCC and hF for ours, CREATE's reported figures, and the grammar-computed $k$-mer baseline, broken down by TE class. We also measure throughput when the full Repbase-derived library is held as one shared grammar.
Genome-wide window annotation. On T2T-CHM13 we run sliding-window TE-family labeling and report wall time, memory, and agreement with decompressed scanning. For context, ULTRA reports 4.8 minutes with 16 threads for tandem-repeat labeling, a different but adjacent task.
Robustness to decay. We inject substitutions and indels at rates up to 20% into synthetic repeats. We then measure how grammar size and speedup degrade, confirming that predictions stay identical to the uncompressed twin throughout.
References
- Learning Directly from Grammar Compressed Text
- Logarithmic-Time Internal Pattern Matching Queries in Compressed and Dynamic Texts
- Compressed consecutive pattern matching
- Approximate Nearest Neighbor Search with Window Filters
- CREATE: a novel attention-based framework for efficient classification of transposable elements
- Probabilistic Label Trees for Efficient Large Scale Image Classification
- ULTRA-Effective Labeling of Repetitive Genomic Sequence