All projects

Prompt Compression

Transformer-based sentiment classification with compressed inputs.

Instruction

Classify the sentiment of the review.

Protected
Demonstration

A film that is beautifully made and moving from start to finish.
Positive

Compress
Query

It isn’t perfect, but it stays with you.

Protected
Retained tokensDistilBERTSentiment

Illustrative text and selection, not a recorded model prediction.

Overview

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.

Context

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.

The Problem

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.

01

Protect meaning

Keep the query, formatting, negation, and a minimum amount of content in each demonstration.

02

Compare equal budgets

Give competing rankings the same attainable whole-word token budget, not just the same requested percentage.

03

Keep simple controls

Compare every method with the full prompt and with the review alone.

Data & Splits

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.

56,087Training phrases
6,432Development phrases
32Support examples
872Final evaluation examples
02 — Training, development, and demonstration support are sentence-family disjoint. The official validation set is reported separately.
Compression 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

  1. 01Random

    Choose eligible words without an importance signal.

  2. 02IDF

    Prioritize less common words using corpus statistics.

  3. 03Learned

    Score content using frozen encoder representations.

Every ranking → whole-word budget selection → retained token IDs → classifier

03 — Random, IDF, and learned ranking share the same selection constraints. Only hard removal shortens the downstream input.
Transformer architecture

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

Retained token IDs + attention mask

Special tokens, prompt structure, demonstrations, and query

Token + position embeddings

768 dimensions per token

Encoder 1Self-attention + feed-forward
Encoder 2Self-attention + feed-forward
Encoder 3Self-attention + feed-forward
Encoder 4Self-attention + feed-forward
Encoder 5Self-attention + feed-forward
Encoder 6Self-attention + feed-forward
hidden_state[:, 0]First-token representation
Classification head

Linear → ReLU → dropout → 2 logits

Negative
Positive

Inside each encoder block

Hidden states

One vector for each input token

QueryKeyValue
12-head self-attention

Masked attention combines information across the retained sequence.

Residual connection + layer norm
Feed-forward network

768 → 3,072 → GELU → 768

Residual connection + layer norm
Updated hidden states

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.

The architecture follows the loaded DistilBERT configuration and sequence-classification implementation.

Learned compression: scoring and selection

Complete formatted prompt
Frozen DistilBERT encoder

Contextual representation for each token

Trainable token gate

Linear 768 → 768 · ReLU · dropout · linear 768 → 1 · sigmoid

Protect query, scaffold, and negation

Soft weighting

Weighted content pooling

Pool contextual vectors using gate scores

Trainable classification head

Two sentiment logits; encoder stays frozen

Hard token selection

Whole-word selection

Apply a matched budget or threshold to eligible content

Retained token IDs

Pass selected IDs without decoding and retokenizing

Fine-tuned classifier

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.

The learned gate has a separate scoring pass. Soft pooling and hard token removal follow different paths after the scores are computed.
Study Design

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.

01

Demonstration count

Compare zero, two, four, and six demonstrations under a common prompt format.

02

Compression location

Delete equal attainable token counts from demonstrations, the query, or both.

03

Gate penalties and thresholds

Vary budget penalties and hard thresholds, then evaluate the resulting classifiers.

Results

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

Full prompt
136.16
Cached IDF
97.16
Learned
97.16
Query only
25.16

Bars start at zero. Accuracy is the mean across three seeds; small differences do not establish superiority.

View all measurements
Three-seed means, warm GPU batch size 16
MethodAccuracyTokensms/example
Full prompt90.44%136.160.351
Cached IDF90.9%97.160.179
Learned90.37%97.160.922
Query only90.67%25.160.147
04 — Saved study measurements, averaged across three seeds. Time includes online compression and classification at warm GPU batch size 16; it is not a production latency guarantee.
Robustness

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

3 seeds per method
Negation180 examples · mean accuracy ± seed SD
IDF
87.78%±1.47
Learned
87.59%±0.85
Full prompt
86.11%±1.47
Query only
86.48%±1.28
0%50%100%

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
Accuracy (%) averaged across three seeds; ± is seed standard deviation
Slice / examplesIDFLearnedFull promptQuery only
All reviews / 87290.90 ± 0.4390.37 ± 0.2390.44 ± 0.4890.67 ± 0.46
Negation / 18087.78 ± 1.4787.59 ± 0.8586.11 ± 1.4786.48 ± 1.28
Contrast / 13088.21 ± 0.8985.38 ± 0.7785.64 ± 0.8985.13 ± 1.60
Short reviews / 15291.67 ± 1.3792.32 ± 0.7691.45 ± 0.6692.32 ± 1.00
Medium reviews / 49591.38 ± 0.5190.77 ± 0.1290.71 ± 0.5391.31 ± 0.53
Long reviews / 22589.33 ± 0.7788.15 ± 0.2689.19 ± 0.6888.15 ± 0.68
Source data
Three-seed mean accuracy with seed variability and sample counts. Negation and contrast slices can overlap with the length groups.
Pipeline measurements

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

Warm GPU
  • IDF
  • Learned
  • Full prompt
  • Query only
Warm GPU pipeline time by batch size. Pipeline milliseconds per example by Batch size. Exact values follow in the data table.Pipeline milliseconds per example0.001.132.253.384.5011632Batch sizeIDF: Batch size 1, 1.48 Pipeline milliseconds per exampleIDF: Batch size 16, 0.18 Pipeline milliseconds per exampleIDF: Batch size 32, 0.15 Pipeline milliseconds per exampleLearned: Batch size 1, 4.11 Pipeline milliseconds per exampleLearned: Batch size 16, 0.92 Pipeline milliseconds per exampleLearned: Batch size 32, 0.83 Pipeline milliseconds per exampleFull prompt: Batch size 1, 1.64 Pipeline milliseconds per exampleFull prompt: Batch size 16, 0.35 Pipeline milliseconds per exampleFull prompt: Batch size 32, 0.31 Pipeline milliseconds per exampleQuery only: Batch size 1, 1.45 Pipeline milliseconds per exampleQuery only: Batch size 16, 0.15 Pipeline milliseconds per exampleQuery only: Batch size 32, 0.10 Pipeline milliseconds per example
IDF0.179 msper example
Learned0.922 msper example
Full prompt0.351 msper example
Query only0.147 msper example

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
Pipeline milliseconds per example, mean across three seeds
MethodBatch 1Batch 16Batch 32
IDF1.4829440.1794950.148748
Learned4.1121210.9223450.831688
Full prompt1.6411890.3508380.314056
Query only1.4544770.1474690.101434
Source data
Warm-GPU time per example, averaged across three seeds. Batched throughput measurements are not single-request latency guarantees.
What Mattered

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.

Compress demonstrations90.18%

Keep the query intact

Compress the query73.74%

Remove task-specific evidence

05 — H2 matched-deletion comparison. Preserving the query was more important than preserving repeated demonstration text.
Next projectMachine Learning for Poker Opponent Modeling