Prompt Compression
Transformer-based sentiment classification with compressed inputs.
Classify the sentiment of the review.
ProtectedA film that is beautifully made and moving from start to finish.
Positive
It isn’t perfect, but it stays with you.
ProtectedIllustrative text and selection, not a recorded model prediction.
Overview
A collaborative NLP study of the trade-off between prompt length, classification quality, and inference cost. We fine-tuned DistilBERT on SST-2 movie reviews and compared full prompts with random, inverse document frequency (IDF), and learned compression. I rebuilt the implementation and rewrote the research paper; the research itself was shared equally across the team.
Across three seeds, cached IDF compression reached 90.90% accuracy with 28.6% fewer input tokens and 48.8% lower measured warm-GPU pipeline time than full prompts. The most useful finding was broader: preserve the review being classified, measure the compressor itself, and always compare against a simple query-only baseline.
Task and project goals
A controlled classification setting
A formatted prompt can contain instructions, labeled demonstrations, and the actual query. Those pieces play different roles, yet they all contribute to the sequence that a transformer processes. Repeating demonstrations for every review creates a natural question: how much of that context is necessary?
We used supervised sentiment classification to make the question measurable. The task is to predict whether an SST-2 movie review is positive or negative. This is a fine-tuned encoder study, rather than a claim about instruction-following behavior in a large generative model. Accuracy, token count, and complete inference time are evaluated together.
Preserving meaning under a token budget
Measure compression and classification together
A compressor can remove many tokens and still be a poor system. It might delete a negation that reverses sentiment, spend more time choosing words than the classifier saves, or benefit from an easier token budget than a competing method.
We designed matched comparisons around these failure modes. The study separates where compression happens from how tokens are ranked, and separates a shorter input from a faster end-to-end pipeline.
Protect meaning
Keep the query, formatting, negation, and a minimum amount of content in each demonstration.
Compare equal budgets
Give competing rankings the same attainable whole-word token budget, not just the same requested percentage.
Keep simple controls
Compare every method with the full prompt and with the review alone.
Sentence-family data partitions
Split by sentence family
SST-2 includes phrases derived from longer sentences. A random phrase split can put closely related text on both sides of an evaluation boundary. We grouped examples by their original sentence ancestry and excluded ambiguous ancestry before forming training, development, and demonstration-support populations.
The resulting partition contains 56,087 training phrases, 6,432 development phrases, and a separate 32-example support pool. IDF statistics use training and support text only. Checkpoints are selected using internal development accuracy, with the earliest epoch breaking ties.
Final evaluation uses 872 labeled official validation examples. That set had been inspected historically, so it is an evaluation set rather than a newly blind test. Keeping this distinction visible matters when interpreting small differences between methods.
Random, IDF, and learned token selection
Word ranking and budget constraints
Random selection is the control for deleting content without knowing its importance. IDF prioritizes less common words using corpus statistics. The learned method scores tokens from frozen DistilBERT representations and uses those scores to select content.
Selection operates on complete whitespace words and passes retained token IDs directly to the classifier. This avoids breaking a word into inconsistent fragments or changing the budget through a decode-and-retokenize round trip. A dynamic-programming selector resolves attainable whole-word budgets so different rankings can be compared fairly.
We also evaluated soft gates, which change pooling weights while still encoding the full input, and hard selection, which actually removes tokens before a newly fine-tuned classifier. Those are different interventions: low soft weights alone do not reduce the number of tokens processed.
Token-ranking methods
- 01Random
Choose eligible words without an importance signal.
- 02IDF
Prioritize less common words using corpus statistics.
- 03Learned
Score content using frozen encoder representations.
Every ranking → whole-word budget selection → retained token IDs → classifier
DistilBERT encoder and classification head
Processing the retained sequence
The classifier converts retained token IDs into token and position embeddings, then passes them through six transformer encoder blocks. Each block has twelve self-attention heads followed by a feed-forward network. Attention allows each token representation to incorporate information from the other retained tokens.
Residual connections and layer normalization are applied after attention and after the feed-forward network. The final representation of the first token passes through a linear layer, ReLU, dropout, and a two-output classification layer. Those outputs correspond to negative and positive sentiment.
The main sequence-classification models fine-tune the encoder and classification head. The learned gate uses a separate frozen encoder to score content before either weighted pooling or hard token selection.
DistilBERT sequence-classification architecture
Classification pipeline
Special tokens, prompt structure, demonstrations, and query
768 dimensions per token
hidden_state[:, 0]First-token representationLinear → ReLU → dropout → 2 logits
Inside each encoder block
One vector for each input token
Masked attention combines information across the retained sequence.
768 → 3,072 → GELU → 768
Passed to the next encoder block
Model configuration: 6 encoder blocks, 12 attention heads, 768-dimensional hidden states, and a 3,072-dimensional feed-forward layer.
Learned compression: scoring and selection
Contextual representation for each token
Linear 768 → 768 · ReLU · dropout · linear 768 → 1 · sigmoid
Soft weighting
Pool contextual vectors using gate scores
Two sentiment logits; encoder stays frozen
Hard token selection
Apply a matched budget or threshold to eligible content
Pass selected IDs without decoding and retokenizing
A separate DistilBERT classifier processes the shorter input
Soft weighting still encodes the full input. Hard selection shortens the downstream sequence but includes the cost of the first encoder pass.
Experimental comparisons
43 configurations, three seeds
The core comparison varies the demonstration budget across random, IDF, and learned ranking. Three additional studies ask how many demonstrations help, where deletion is safest, and whether a learned gate provides a useful accuracy–compression trade-off.
All configurations are reported across seeds 42, 43, and 44: 129 fits in total. The classification training batch size stays fixed across conditions, and checkpoints are frozen before final evaluation. This makes the result a comparison of input strategies rather than a search for the best-looking final score.
We measured preprocessing, classifier time, and their combined pipeline time at batch sizes 1, 16, and 32. Learned compression includes its additional encoder pass. Robustness slices examine negation, contrast, and review length, helping reveal failures that a single accuracy number can conceal.
Demonstration count
Compare zero, two, four, and six demonstrations under a common prompt format.
Compression location
Delete equal attainable token counts from demonstrations, the query, or both.
Gate penalties and thresholds
Vary budget penalties and hard thresholds, then evaluate the resulting classifiers.
Accuracy, input length, and inference time
Measured results
Cached IDF retained 97.16 input tokens on average, compared with 136.16 for the full prompt. It reached 90.90% mean accuracy and 0.179 ms per example in the warm-GPU, batch-16 pipeline benchmark. The full prompt reached 90.44% and 0.351 ms.
The matched learned compressor retained the same number of tokens but took 0.922 ms per example. Its extra encoder pass outweighed the savings in the classifier. Meanwhile, query-only achieved 90.67% with just 25.16 tokens and 0.147 ms. Demonstrations did not establish a consistent accuracy advantage in this setup.
Mean input tokens · fewer is shorter
Bars start at zero. Accuracy is the mean across three seeds; small differences do not establish superiority.
View all measurements
| Method | Accuracy | Tokens | ms/example |
|---|---|---|---|
| Full prompt | 90.44% | 136.16 | 0.351 |
| Cached IDF | 90.9% | 97.16 | 0.179 |
| Learned | 90.37% | 97.16 | 0.922 |
| Query only | 90.67% | 25.16 | 0.147 |
Accuracy across review types
Look beyond the overall average
Negation, contrast, and review length change the difficulty of the classification task. The saved evaluation separates these slices so each method can be inspected on the same examples, with its variation across three training seeds visible.
Cached IDF reached 87.78% mean accuracy on negation examples and 88.21% on contrast examples, compared with 86.11% and 85.64% for full prompts. These are descriptive differences on overlapping slices, not independent evidence of statistical superiority.
Linguistic robustness
Accuracy beyond the overall average
Means across three seeds on the same examples. Negation and contrast slices can overlap; long reviews contain at least 26 words. These differences are descriptive, with no claim that small gaps establish superiority.
Compare all review slices
| Slice / examples | IDF | Learned | Full prompt | Query only |
|---|---|---|---|---|
| All reviews / 872 | 90.90 ± 0.43 | 90.37 ± 0.23 | 90.44 ± 0.48 | 90.67 ± 0.46 |
| Negation / 180 | 87.78 ± 1.47 | 87.59 ± 0.85 | 86.11 ± 1.47 | 86.48 ± 1.28 |
| Contrast / 130 | 88.21 ± 0.89 | 85.38 ± 0.77 | 85.64 ± 0.89 | 85.13 ± 1.60 |
| Short reviews / 152 | 91.67 ± 1.37 | 92.32 ± 0.76 | 91.45 ± 0.66 | 92.32 ± 1.00 |
| Medium reviews / 495 | 91.38 ± 0.51 | 90.77 ± 0.12 | 90.71 ± 0.53 | 91.31 ± 0.53 |
| Long reviews / 225 | 89.33 ± 0.77 | 88.15 ± 0.26 | 89.19 ± 0.68 | 88.15 ± 0.68 |
Where inference time is spent
Compression has its own cost
A shorter classifier input does not guarantee a faster complete pipeline. Measuring preprocessing and classification separately shows that the learned gate adds an encoder pass before the compressed input reaches the classifier.
The saved benchmarks cover batch sizes 1, 16, and 32. Comparing them shows how time per example changes when work is batched, while keeping the cost of online compression in the measurement.
Complete inference pipeline
How batching changes measured cost
- IDF
- Learned
- Full prompt
- Query only
Saved measurements averaged across three seeds, including online compression and classification. The learned method adds an encoder pass. Batched time per example describes throughput, not individual request latency.
View timing measurements by batch
| Method | Batch 1 | Batch 16 | Batch 32 |
|---|---|---|---|
| IDF | 1.482944 | 0.179495 | 0.148748 |
| Learned | 4.112121 | 0.922345 | 0.831688 |
| Full prompt | 1.641189 | 0.350838 | 0.314056 |
| Query only | 1.454477 | 0.147469 | 0.101434 |
Effect of compression location
The location of deletion matters
At matched total-token deletion counts, demonstration compression achieved 90.18% accuracy while query compression fell to 73.74%. A demonstration can be partly redundant; the review contains the evidence needed for the actual decision.
The project reinforced a practical research habit: start with a strong simple baseline, account for all computation, and distinguish observed differences from reliable improvements. The small accuracy gaps between the best core methods do not establish statistical superiority. The measured speed result is specific to the saved warm-GPU benchmark, not a promise of application cost savings.
Keep the query intact
Remove task-specific evidence