Skip to content
Language modelsPrototype

Verace Contrast

Differential attention with a symplectic second stream and a context-length gate, with a GPT-2 fine-tuning port that applies it.

Verace Research·2 publications
  1. Adaptive context gate: Scales the subtraction by tanh of sequence length
  2. Short sequences: Behave like standard attention
  3. Long sequences: Receive full cancellation
  4. Sequence length: Current length, passed in and not learned
Figure 1. Adaptive context gate on differential attention in Verace Contrast. Schematic: the adaptive context gate sets how much of the second attention map is subtracted as sequence length grows. The curve follows the design formula and does not plot any recorded run.
Open the simulator on its own pageA gate with a soft edge: an interactive toy model of the principle. You can also try it below

Overview

Verace Contrast is the lab's work on differential attention, a mechanism that subtracts a second softmax attention map from a first to cancel attention mass spread over irrelevant tokens. The lab's papers call the research version UFS-Attention (Unified Fused Symplectic Differential Attention) and present it as an extension of the Differential Transformer, prior work by Wang et al. (2024). The question is whether three changes remove that design's weaknesses: lost rank, constant subtraction at short context, and an extra memory pass. A second part applies the mechanism to GPT-2, OpenAI's 117M model, inside an existing third-party GPT-2 fine-tuning codebase by others. Only the lab's additions are described here.

Standard differential attention splits each head's queries and keys into halves and computes (A1−λA2)V(A_1 - \lambda A_2)V. Here Ai=softmax(QiKi⊤/d/2)A_i = \mathrm{softmax}(Q_i K_i^\top / \sqrt{d/2}) and λ\lambda is learned per head. The lab's design specification makes three changes. The second stream uses QJQJ and KJKJ with a fixed symplectic matrix JJ, J2=−IJ^2 = -I, in place of half-width projections. An adaptive gate λeff(N)=λtanh⁡(N/256)\lambda_{\text{eff}}(N) = \lambda \tanh(N/256) turns subtraction off for short sequences. A fused, SRAM-tiled kernel computes both softmaxes in one streaming pass. The block wraps this in RoPE, SwiGLU and RMSNorm, with RMSNorm applied per head after the subtraction.

The research implementation contains a PyTorch language model that switches between standard and differential attention, the three design variants, toy benchmarks, latency microbenchmarks and figure scripts. The papers report needle retrieval at 16k rising from 31.8% to 89.4% and the W4A4 perplexity penalty falling from 26.18 to 1.34. The lab's code audit found that every plotted figure comes from arrays typed into the plot scripts, with no experiment outputs loaded. It also found that, because JJ is orthogonal, the symplectic stream reproduces the first map exactly. The GPT-2 port adds differential attention, supervised fine-tuning and GRPO but has no recorded evaluation.

Status: plain differential attention, the gated and symplectic variants, the toy benchmarks and the GPT-2 training code are implemented. The fused kernel exists only as a design: the variant named for it computes dense softmax maps in PyTorch. No recorded run supports the retrieval, quantization, latency or ablation figures in the papers, which come from hardcoded data. The symplectic stream adds no information as coded, which contradicts the design's full-rank claim. Whether differential attention helps in the lab's own setting has not been measured. The LiveBench reports test another developer's 4-bit DeepSeek-R1-Distill-Qwen-1.5B model with the lab's GRPO adapter and steering hooks; many outputs are incorrect.

Status

Prototype. The attention variants, toy benchmarks and GPT-2 training code are implemented, but the published figures are hardcoded rather than measured, the fused kernel is not built, no evaluation of the GPT-2 port is recorded, and the only LiveBench evaluation covers a separate harness on a 4-bit DeepSeek-R1-Distill-Qwen-1.5B model with many incorrect outputs.

Simulator

A gate rises from 0 to 1 around a threshold. Two hundred made-up inputs are passed through it: set how steep it is, where its threshold lies and how spread out the inputs are.

  • the inputs (made up): those the gate passes in colour
  • dashed: a hard step at the same threshold
Inputs passed
51%
Inputs left undecided
56%
Width of the undecided band
1.46
Mean output of the gate
0.51

Make the gate steeper and it tends to a hard step: fewer inputs are left undecided. Move the threshold through the inputs.

This simulator is an illustration of the principle, with made-up numbers. It does not run the lab's code or show the lab's data, and nothing in it is a measurement.

Architecture

  1. Differential attention core

    Subtracts a second softmax attention map from the first, scaled by a learned per-head λ\lambda, then applies RMSNorm per head. This follows the Differential Transformer formulation by Wang et al.

  2. Symplectic second stream

    Design change that builds the second attention map from QJQJ and KJKJ with J∈Sp(d,R)J \in \mathrm{Sp}(d,\mathbb{R}), so it is not computed from half-width projections. The design specification presents this as a way to keep full rank dd.

  3. Adaptive context gate

    Scales the subtraction by tanh⁡(N/256)\tanh(N/256) in the sequence length NN. Short sequences therefore behave like standard attention and long sequences receive full cancellation.

  4. Fused FlashDiff kernel design

    A specified single-pass, SRAM-tiled kernel that computes both softmaxes and their difference with O(N)O(N) memory traffic. The design targets FlashAttention-2 latency; no such kernel is implemented.

  5. Comparison language model

    A pre-norm PyTorch transformer with RoPE, RMSNorm and a SiLU MLP. A switch selects standard multi-head attention or differential attention.

  6. Synthetic evaluation suite

    Toy experiments on attention mass at a planted target token, key-value associative recall, attention-sink mass and attention entropy.

  7. Latency microbenchmarks

    FP16 timing of naive standard attention against naive differential attention across sequence lengths.

  8. Paper figure and diagram scripts

    Matplotlib scripts that draw architecture diagrams and result plots for the papers. All plotted result values are written directly into the scripts.

  9. GPT-2 differential attention port

    TensorFlow and PyTorch GPT-2 models with optional differential attention, RMSNorm, fast GELU, RoPE and further lab additions. The design keeps compatibility with the original GPT-2 checkpoints.

  10. SFT and GRPO training pipeline

    Supervised fine-tuning followed by Group Relative Policy Optimization on prompt and response data. A shell script chains the two stages.

  11. Best-of-N inference harness

    Samples several completions at different temperatures and keeps the one a deterministic scorer rates highest. An HTTP chat endpoint exposes the harness.

Implementation

Mechanisms as they are implemented in the source code, with the constants the code uses.

Half-split differential attention
In models.py, each head's QQ and KK are split into halves, giving the output (softmax(Q1K1⊤/d/2)−λ softmax(Q2K2⊤/d/2))V\left(\mathrm{softmax}(Q_1K_1^\top/\sqrt{d/2}) - \lambda\, \mathrm{softmax}(Q_2K_2^\top/\sqrt{d/2})\right)V, followed by per-head RMSNorm in the class MultiHeadDifferentialAttention. This is the published Differential Transformer formulation by other authors, implemented here as the lab's baseline.
Learnable lambda reparameterization
Per head, λ=eλq1⋅λk1−eλq2⋅λk2+λinit\lambda = e^{\lambda_{q1}\cdot\lambda_{k1}} - e^{\lambda_{q2}\cdot\lambda_{k2}} + \lambda_{\text{init}}, with λinit=0.8−0.6 e−0.3l\lambda_{\text{init}} = 0.8 - 0.6\, e^{-0.3 l} for layer index ll. The four vectors are initialized from N(0,0.1)\mathcal{N}(0, 0.1). This parameterization is the published Differential Transformer formulation by other authors, implemented here as the lab's baseline.
Symplectic J stream as coded
In fused_diff_flash_engine.py the second stream applies J=[0−II0]J = \begin{bmatrix} 0 & -I \\ I & 0 \end{bmatrix} to full-width QQ and KK. Because JJ is orthogonal, (QJ)(KJ)⊤=QJJ⊤K⊤=QK⊤(QJ)(KJ)^\top = QJJ^\top K^\top = QK^\top, so A2=A1A_2 = A_1. The output then reduces to (1−λeff)A1V(1-\lambda_{\text{eff}})A_1 V, and the stream contributes no new information.
Scale-adaptive tanh gate
UnifiedScaleAdaptiveDifferentialAttention computes λeff=λtanh⁡(N/Nc)\lambda_{\text{eff}} = \lambda \tanh(N/N_c) with Nc=256N_c = 256, where NN is the current sequence length passed as a Python scalar and not learned. The gate is about 0.12 at N=32N = 32 and about 1 at N≥1024N \geq 1024. A docstring mentions 40Hz gamma rhythms, which have no counterpart in the code.
Fused online variant as written
FusedDifferentialAttentionOnline carries the fused kernel's name but materializes dense softmax maps in ordinary PyTorch. It has no SRAM tiling and no streaming pass.
Interleaved rotary position embedding
Frequencies are θ−2i/d\theta^{-2i/d} with θ=10000\theta = 10000. Their outer product with positions gives cosine and sine tables, which rotate interleaved pairs of query and key channels.
Key-value associative recall task
A sequence interleaves keys drawn from 1 to 49 with values drawn from 51 to 99 and ends with a queried key. The model must output the paired value as the final token. The deeper benchmark uses sequence length 64, 15 pairs, distractor tokens and 400 training steps.
Attention sink and entropy metrics
Sink mass is the mean attention weight on position 0 across queries and heads. Entropy is −∑plog⁡p-\sum p \log p per row, with pp clamped at 10−1210^{-12}. For differential maps, ∣A∣|A| is renormalized to sum to 1 first.
FLOP parity derivation
A comment in clean_kernel_benchmark.py counts two QK⊤QK^\top products at width d/2d/2 plus one AVAV product at width dd. The total is 4BHS2D4BHS^2D FLOPs, equal to standard attention if the extra softmax and subtraction are ignored.
Naive latency benchmarks
One benchmark times FP16 attention on random tensors with fixed λ=0.7\lambda = 0.7, sequence lengths 512 to 4096, and 16 heads of dimension 64. A second uses dmodel=4096d_{\text{model}} = 4096 (32 heads of 128) at sequence lengths 512 to 16384. It computes KV-cache size per token, but the value for differential attention is never printed.
Analytic verification script
verify_solutions.py instantiates the three variants and runs forward passes. The rank and gate values it prints are computed analytically, not measured from the outputs.
Hardcoded figure data
The plot scripts embed literal arrays for retrieval accuracy, INT4 perplexity change, latency, common-mode rejection, kurtosis and ablations. Training loss curves are synthetic exponentials with added noise.
GPT-2 two-stream attention in PyTorch
verace_torch.py reimplements GPT-2 as VeraceGPT2 with UnifiedFusedSymplecticDiffAttention, a two-stream symplectic differential attention. It loads OpenAI's pretrained weights and generates text with top-k, top-p and repetition penalty.
TensorFlow GPT-2 option flags
src/model.py and src/verace_core.py add optional differential attention, RMSNorm, fast GELU, RoPE, symplectic steering and nullspace_orthogonalize() on the embeddings. Training adds a label-smoothed loss, a cosine learning-rate schedule with warmup, and a regularizer the code names topos, whose form is not documented.
Supervised fine-tuning trainers
train_sft.py (TensorFlow) and train_sft_torch.py (PyTorch, mixed precision) train on prompt and response pairs with label smoothing and the topos regularizer. The TensorFlow trainer applies the loss to all tokens, including the prompt.
GRPO trainers
Advantages are rewards standardized within a group of completions for one prompt, A^i=(ri−μG)/σG\hat{A}_i = (r_i - \mu_G)/\sigma_G, so no value critic is needed. train_grpo.py uses a PPO-style clipped surrogate and a heuristic reward. train_grpo_torch.py uses a sequence log-probability policy gradient without ratio clipping, plus the topos regularizer.
Best-of-N selection with truncation
fix_asi.py rewrites the inference query routine to sample 3 trajectories, add a reminder about the prompt format, truncate repeated text, and return the highest-scoring answer.
Quantized comparison harness
compare_bench.py compares a 4-bit DeepSeek-R1-Distill-Qwen-1.5B base model, a model from another developer, with the same model plus a GRPO adapter and steering hooks. The comparison uses 5 LiveBench math questions. full_eval.py runs 2 questions from each of five LiveBench categories.

Results

From the lab's own experiments and records. They have not been independently replicated.

  1. Symplectic stream duplicates the first attention map

    The lab's code audit found that JJ is orthogonal, so (QJ)(KJ)⊤=QK⊤(QJ)(KJ)^\top = QK^\top and the second map equals the first. This contradicts the design specification's claim that the stream adds full-rank information.

  2. Published result figures are hardcoded, not measured

    Every plot script embeds its result arrays directly, and the training loss curves are synthetic exponentials with noise. None of the papers' plotted results is loaded from an experiment output.

  3. Reported retrieval and quantization gains lack recorded runs

    The papers report needle retrieval at 16k rising from 31.8% to 89.4% and the W4A4 perplexity penalty falling from 26.18 to 1.34. No run in the evaluation records produces these figures.

  4. Ablation claims conflict with the code

    The papers report that removing JJ drops rank to 32 and raises perplexity from 8.1 to 8.9. They also report that a fixed gate adds 0.8 short-context perplexity and that an unfused kernel costs 2.5x latency. These come from hardcoded data, and the JJ result cannot hold as coded, since JJ leaves the attention map unchanged.

  5. Fused kernel is a design only

    The variant named for the fused online kernel computes dense softmax maps in PyTorch, and the latency benchmarks compare naive unfused implementations. The FlashAttention-2 latency target is untested.

  6. Verification script reports analytic values

    The smoke test prints rank and gate values computed by formula rather than measured from model outputs, so it confirms that the variants run but not the properties the papers claim for them.

  7. Differential attention has FLOP parity on paper

    A derivation in the benchmark code gives 4BHS2D4BHS^2D FLOPs for both standard and differential attention, ignoring the extra softmax and subtraction.

  8. Comparison harness outputs often incorrect

    The lab's LiveBench evaluation report covers a harness built on a 4-bit DeepSeek-R1-Distill-Qwen-1.5B model from another developer with the lab's GRPO adapter and steering hooks. Its sample outputs across reasoning, coding, data analysis, instruction following and language tasks are often visibly incorrect or truncated. No evaluation of the GPT-2 port itself is recorded.

Concepts

Common-mode attention noise
Softmax gives every token some weight, so irrelevant tokens share a background level of attention. Subtracting two maps that share this background cancels it, by analogy with a differential amplifier.
Differential Transformer
Prior work by Wang et al. (2024) that subtracts two softmax maps computed from channel-split projections. The lab's papers build on it and criticize it for three weaknesses.
Softmax noise floor
A corollary in the lab's papers states that total attention on distractors tends to 1 as sequence length grows. The papers use it to explain why standard attention degrades at long context.
Common-mode rejection theorem
A claim in the lab's papers that with a suitably tuned λ\lambda, distractor weights in the differential map become exactly zero.
Symplectic matrix
A matrix JJ in the symplectic group Sp(d,R)\mathrm{Sp}(d,\mathbb{R}). The one used here satisfies J2=−IJ^2 = -I and is also orthogonal, which is why it leaves inner products unchanged.
Rank of the second stream
The design specification argues that half-width projections reduce attention rank and that the JJ stream keeps full rank dd. The code audit shows the JJ stream recomputes the first map, so the rank claim does not translate into a distinct second map.
Scale-adaptive gate
A gate that scales subtraction strength with sequence length, tanh⁡(N/256)\tanh(N/256). It leaves short inputs close to standard attention.
Head RMSNorm
Root-mean-square normalization applied to each head's output after the subtraction. It bounds the variance that the difference of two maps can produce.
Attention sink
The tendency of attention to pile onto uninformative positions such as the first token. The suite measures it as mean weight on position 0.
Needle-in-a-haystack retrieval
A test in which one relevant fact is planted in a long context and the model must retrieve it. The papers' figures for it are hardcoded.
FlashAttention-style fusion
Computing attention in tiles held in on-chip SRAM, so the full N×NN \times N map is never written to main memory. The fused differential kernel is specified this way but not implemented.
Kurtosis and INT4 quantization
Corollary 4.4 in the papers bounds activation kurtosis by c/(1−λeff)2c/(1-\lambda_{\text{eff}})^2 through sink suppression. The papers argue this permits near-lossless 4-bit quantization.
W4A4 quantization
4-bit weights and 4-bit activations. The papers report the perplexity penalty under this setting; the values come from hardcoded figure data.
Rotary position embedding
Encodes position by rotating pairs of query and key channels by position-dependent angles, so attention scores depend on relative position.
Supervised fine-tuning
Training a pretrained model on prompt and response pairs with a next-token loss. It is the first stage of the GPT-2 pipeline.
Group Relative Policy Optimization
A reinforcement learning method that standardizes each completion's reward against others sampled for the same prompt. This removes the need for a learned value critic.
Best-of-N inference
Drawing several sampled answers and keeping the one a scoring function rates highest. Inference compute is traded for answer quality.
LiveBench
An external benchmark with reasoning, coding, data analysis, instruction following, language and math categories. The lab used a few of its questions to check a comparison harness built on another developer's 4-bit DeepSeek-R1-Distill-Qwen-1.5B model with the lab's GRPO adapter and steering hooks, not the GPT-2 port.

Publications

About this page

Written from the lab's own documents and source code. Figures and results are the lab's measurements as it recorded them at the time, and have not been independently replicated.

Published under the PolyForm Noncommercial License 1.0.0: free for noncommercial use.