Compressing Qwen3-1.7B to 1.24B on a single 16 GB GPU with Relaxed Recursive Transformers
In-place weight sharing, 16 GB Strong-to-Weak distillation from Qwen3-4B int8, 20-hour training curves, downstream benchmarks, and what a same-architecture ablation revealed.
How this project was built: I drove the architectural decisions, experiment design, debugging, and hardware benchmarking while pairing with AI coding agents (spec-driven workflow) to implement the PyTorch/Triton codebase, dashboard, and 82-test suite.
Most LLM compression papers assume an 8×H100 node. I wanted to see how far I could push Relaxed Recursive Transformers (Bae et al., 2024) on a single desktop RTX 4080 (16 GB): compressing Qwen/Qwen3-1.7B down to 1.24B parameters (65.7% of transformer layer weights, cutting inference weight VRAM by 27.6%) and recovering quality through a Strong-to-Weak distillation pipeline against an int8 weight-only Qwen/Qwen3-4B teacher.
Across 20.3 hours and 164.8M tokens, the experiment produced three concrete outcomes: a working single-16 GB multi-stage distillation recipe (12.59 GB peak VRAM at ~2,330 tok/s), a clear picture of how per-depth LoRA specialization recovers capacity, and an unexpected ablation showing where same-architecture self-distillation (Qwen3-1.7B) actually outperforms a larger 4B teacher — and where the multilingual 4B run wins instead.
This post covers the compression architecture and 16 GB memory optimizations, five engineering lessons that made Stage-2 convergence monotonic, the full 4-stage training trajectory, and every number from the final benchmark and ablation suite — including the measurement caveats and failure modes.
1. Architecture & Single-GPU Compression Setup
A strict Recursive Transformer loops a smaller stack of unique Transformer blocks times, saving memory at the cost of representational capacity. Relaxed Recursive Transformers (RRT) keep the shared base weights tied across recursion steps, while attaching lightweight per-recursion LoRA adapters and DoRA-inspired per-channel output scaling vectors (multiplicative post-scaling without per-column norm division):
Using my in-place Hugging Face converter (src/rrt/hf_converter.py), I compress Qwen/Qwen3-1.7B without breaking native per-layer KV cache, SDPA/FlashAttention, activation checkpointing, or generate():
- Sharing schedule:
middle_sequencewith , asymmetric super-weight protection (keep_first=3,keep_last=1), uniformlora_rank=128+ per-channel output scaling. Layers0–2and27stay full-rank; the middle 24 layers collapse into 12 shared blocks looped twice. - Initialization: Condition-bounded diagonal ASVD + exact QR/SVD LoRA factor balancing (), cutting initial weight reconstruction error from
0.673to0.527in29.4s. - Parameter & VRAM budget: Layer parameters drop from
1,409.4Mto925.5M(65.7%); total parameters drop from1.721Bto1.237B(71.9%); inference weight VRAM drops from3.44 GBto2.49 GB(-27.6%).
Fitting the compressed student plus a frozen Qwen3-4B teacher plus gradients and activations inside 16 GB VRAM relied on five systems ingredients (src/rrt/distill.py):
- Stochastic BF16 Adafactor: keeps weights, gradients, and optional momentum in
bfloat16, computes factored second moments and updates infp32one tensor at a time, and writes back with unbiased stochastic rounding so tiny updates do not stall. - Memory-exact chunked logit KL/CE backward: Qwen3’s
151,936-token vocabulary would consume gigabytes if full(B, T, V)fp32logits were materialized at once. Projectinglm_headin 256-token slices computes exactdL/dh_sin constant memory. - Symmetric per-channel
int8weight-only teacher: quantizesQwen/Qwen3-4Bdecoder linears on the fly (< 2%logit relative error), cutting teacher VRAM by ~50%. - Ridge-initialized DSKD hidden projector: maps student interior hidden states (
2048) toQwen3-4B(2560) via training-only linear projections solved in closed form on 4 calibration batches (< 1son GPU) and discarded at inference. - Zero-VRAM CPU Weight EMA: averages deduplicated trainable weights in host RAM during the final 30% of training (WSD plateau + cosine decay) and auto-promotes the soup to
best.ptif it beats the raw checkpoint on validation KL.
2. Getting Stage-2 Distillation to Converge (5 Practical Pitfalls)
Stage 1 (Qwen3-1.7B self-healing) converged smoothly: in 36m (5.07M tokens), WikiText-2 perplexity dropped from 1,711.36 to 56.97 and SmolTalk chat perplexity dropped from 583.67 to 9.71. Yet the first Stage-2 runs against Qwen3-4B int8 degraded validation KL instead of improving on Stage 1. Five concrete changes made Stage-2 convergence monotonic:
1. Reverse-skewed Generalized JSD collapsed compressed capacity
In Stage 2, I initially swapped Forward KL for Generalized Jensen-Shannon Divergence with (skewed toward Reverse KL), motivated by mode-seeking behavior in standard LLM distillation:
What happened: On a structurally compressed RRT student whose shared base weights are still recovering from recursion tying, heavy reverse-KL weighting (beta=0.25) aggressively zeroed out probability mass on secondary plausible tokens. Perplexity spiked and validation Forward KL drifted upward almost immediately.
The fix: Switch Stage 2 back to Forward KL + CE (0.85 KL / 0.15 CE, temperature ). Mode-covering pressure keeps shared weights stable while still transferring Qwen3-4B’s logit distribution (--kl-type jsd stays available as an opt-in flag).
2. On-Policy Distillation was taking independent full-LR steps
To mitigate exposure bias, I added On-Policy Distillation (OPD) rollouts where the student generates short continuations graded only on assistant tokens by the frozen teacher.
What happened: The original implementation ran OPD as an independent optimizer.step() at the full learning rate on tiny 128-token rollouts. A single noisy generation could apply a full-magnitude update and knock the shared weights off their trajectory every few steps.
The fix: Accumulate weighted OPD gradients cleanly into the main optimizer step (--on-policy-weight 0.15) rather than stepping independently, and keep OPD opt-in (--on-policy-every 0) during primary recovery.
3. Aligning the final hidden layer conflicted with the frozen lm_head
Cross-architecture DSKD projects Qwen3-1.7B student hidden states (2048-d) into Qwen3-4B’s teacher hidden space (2560-d) via training-only linear maps (src/rrt/distill.py), optimizing direction (cosine) plus relative norm error:
What happened: My layer matcher included the final layer (layer 28) in . Because the student keeps Qwen3-1.7B’s tied, frozen lm_head, pulling layer 28 toward a projected Qwen3-4B subspace directly conflicted with the logit head’s geometry, hurting next-token logits even while DSKD loss decreased.
The fix: Added include_final=False to compute_matched_layer_pairs() and restricted Stage-2 DSKD (weight=0.25) to 6 interior layer pairs ((4, 5), (8, 10), (12, 15), (16, 21), (20, 26), (24, 31)), leaving layer 28 free to align with the frozen lm_head via logit KL. I also persisted trained projector weights inside checkpoints so --init-from continuations reload them instead of re-solving Ridge from scratch.
# Align interior representations only so layer 28 doesn't fight the frozen lm_head
layer_pairs = compute_matched_layer_pairs(
student_layers=28,
teacher_layers=36,
include_final=False,
)
4. Multi-stage training-state hygiene on --init-from
Auditing the early Stage-2 logs uncovered three compounding state issues:
- Repeated training tokens:
PackedStreamLoaderreused the same base RNG seed when resuming via--init-from, silently replaying Stage 1’s exact token stream instead of fresh data. - Unanchored
best_val_kl: Checkpoint saving initializedbest_val_kl = float("inf"). Even when Stage 2 degraded past the Stage-1 checkpoint, the first eval overwrotebest.ptwith a worse model. - Training-mode leak after eval:
evaluate_student()calledstudent.eval()without restoringstudent.training, leaving dropout/training flags wrong afterward.
The fix: Offset the default stream seed on --init-from and pass distinct --seed values across chained stages (note: because --init-from resets start_step=0, chaining more than two stages still requires changing --seed explicitly), anchor best_val_kl to the step-0 evaluation floor before step 1 runs, and save/restore was_training = student.training inside a try/finally block in evaluate_student().
5. Releasing hidden-state tuples before chunked logit backward
Even with chunked cross-entropy + KL (chunked_kl_ce_backward), Stage 2 peaked at 12.97 GB VRAM and ran at ~1,860 tok/s.
What happened: Python kept references to the full teacher_hidden_states and student_hidden_states tuples (all 28–36 layers) alive while running chunked_kl_ce_backward. Those activations could not be reclaimed until the function returned, forcing smaller logit chunks and extra allocator fragmentation.
The fix: Compute the interior DSKD auxiliary loss first, explicitly del the unused hidden-state tuples before entering chunked_kl_ce_backward, and double default --chunk-tokens from 128 to 256.
| Metric (RTX 4080 16 GB, Stage 2) | Before fix | After fix | Delta |
|---|---|---|---|
| Stage-2 Throughput | ~1,860 tok/s | ~2,330 tok/s | +25% |
| Peak VRAM | 12.97 GB | 12.59 GB | -380 MB |
Default --chunk-tokens |
128 | 256 | 2× chunk size |
3. Full 4-Stage Training Trajectory (164.8M Tokens, 20.3h)
Once all five fixes landed, convergence became completely monotonic. I stitched four stages together on a single RTX 4080 (s1 → s2_4b → s2_long → s2_ext), switching from the English-only elite mix to elite_v2 (35% FineWeb-Edu, 14% SmolTalk, 12% Cosmopedia-v2, 12% OpenCodeInstruct Python, 9% FineMath-4plus, 8% EN Wikipedia, 6% ES Wikipedia, 4% Somos Clean Alpaca ES). For s2_ext, I also reserved held-out Python and Spanish validation splits from the tail of each shard (skip_tail_rows=200, 8 blocks × 512 = 4,096 tokens each; note that the earlier 24.8M-token s2_long stage ran before tail reservation was added, leaving a small ~2–5% chance of overlap on those tail rows).

| Stage | Teacher & Mix | Budget | KL (2d / 4d) | WT-2 / Chat (Val) | Py / ES (Val) |
|---|---|---|---|---|---|
| Step 0 (ASVD) | Qwen3-1.7B | 0m / 0M | 5.388 / — | 1,711 / 584 | — |
Stage 1 (s1, EMA) |
1.7B · elite |
36m / 5.1M | 1.196* / — | 56.97 / 9.71 | — |
Stage 2 (s2_4b, EMA) |
4B · elite |
90m / 12.4M | 1.060 / — | 35.23 / 7.11 | — |
Stage 2 Long (s2_long) |
4B · elite_v2 |
194m / 24.8M | 0.956 / — | 30.79 / 6.84 | — |
Stage 2 Ext (s2_ext) |
4B · elite_v2 |
15h / 122.6M | 0.707 / 0.553 | 23.81 / 5.81 | 2.01 / 10.21 |
| Teacher Ref | 4B int8 | — | 0.000 | 14.60 / 9.92 | 3.38 / 19.07 |
*Stage 1 ran at 10.60 GB peak VRAM (2,444 tok/s) and its 1.1956 KL is measured against Qwen3-1.7B (against Qwen3-4B int8 at Stage-2 step 0, it starts at 1.4473). All Stage-2 runs stayed at 12.59 GB peak VRAM (~2,226–2,330 tok/s). s2_ext logs 4-domain Mean KL across WikiText-2 (0.865), SmolTalk (0.548), Python (0.185), and Spanish (0.612); its 2-domain WT+Chat average (0.7065) is directly comparable to earlier stages.
Why does s2_ext show lower perplexity than Qwen3-4B on Chat, Python, and Spanish? Notice that on out-of-distribution plain text (WikiText-2), the ranking is completely normal (Qwen3-4B: 14.60 < Original 1.7B: 18.40 < v1: 22.33 < s2_ext: 23.81). On Chat, Python, and Spanish, two effects compound: first, s2_ext trains in-distribution on those exact dataset families (SmolTalk, OpenCodeInstruct, Wikipedia ES, and Alpaca-ES) while the frozen teachers are evaluated zero-shot; second, SmolTalk, OpenCodeInstruct, and Alpaca-ES (half of the ES validation split) are formatted with Qwen3’s chat template and enable_thinking=False (<|im_start|>user...<|im_start|>assistant\n<think>\n\n</think>\n\n...). The frozen base models were instruction-tuned with user-turn loss masking and thinking traces, so they assign high surprise to user prompts and empty <think> blocks, whereas our distilled students train with unmasked KL + CE over all tokens. So do not read 2.01 vs 3.38 or 10.21 vs 19.07 as “a 1.24B student beat a 4B teacher” — those validation perplexities are meaningful student-vs-student (where s2_ext avoids v1’s Spanish regression), not student-vs-teacher.
One small detail worth noting on CPU Weight EMA: in both s1 and s2_4b, the zero-VRAM EMA soup beat the best raw checkpoint and was auto-promoted to best.pt. In the 15-hour s2_ext run, the WSD cosine decay (85% → 100%) was still descending cleanly right up to the final step 14,993, so the final raw weights (mean_kl = 0.5527) narrowly edged out the 413-update EMA soup (0.5542, which still averaged slightly earlier, higher-LR points).
4. Downstream Benchmarks — and Three Things the Headline Table Hid
I evaluated every checkpoint with scripts/evaluate.py --n-bench 200 on held-out WikiText-2 and SmolTalk test blocks (32 × 512 = 16,384 tokens each), 200 questions each of ARC-Easy, BoolQ, and HellaSwag, the LoRA OFF ablation on the exact same checkpoint, and the 4,096-token Python/Spanish validation splits.
Evaluation caveat:
scripts/evaluate.pyis a lightweight custom zero-shot harness (per-token mean log-prob, separate prompt/continuation tokenization, raw HellaSwag context without WikiHow markup stripping). Absolute accuracies are therefore not directly comparable to fulllm-eval-harnessnumbers, andn=200carries a binomial standard error of roughly ±3.5 percentage points. Relative comparisons across the three models remain valid because every model is scored identically, and thev1vss2_extEnglish gap holds consistently across all five English metrics simultaneously.
I also evaluated my earlier single-stage baseline v1 (checkpoints/qwen3_1.7b_rrt/best.pt: 1.196B params, keep_first=1, keep_last=1, 10h / 109.6M English-only tokens distilled purely from same-architecture Qwen3-1.7B bf16 with 13 exact 1-to-1 hidden-state taps). Putting all four side by side tells a much more interesting story than s2_ext alone.
English zero-shot benchmarks & LoRA OFF ablation (n=200)
| Variant | Params (VRAM) | WT-2 / Chat (Test) | ARC-Easy | BoolQ (yes/Yes)* | HellaSwag |
|---|---|---|---|---|---|
| Original 1.7B | 1.72B (3.44 GB) | 22.44 / 7.25 | 63.5% | 76.5% / 78.0% | 44.5% |
RRT (LoRA OFF) |
1.24B (2.49 GB) | 1,088 / 524 | 30.5% | — | — |
RRT v1 (1.7B, EN) |
1.20B (2.41 GB) | 29.74 / 4.43 | 51.0% | 50.0% / 63.5% | 44.5% |
RRT s2_ext (4B) |
1.24B (2.49 GB) | 31.71 / 5.14 | 47.0% | 41.5% / 62.0% | 40.0% |
3-benchmark average (ARC-Easy + case-matched BoolQ Yes/No + HellaSwag, computed identically across all models): Original 62.0%, v1 53.0% (85.5% retained), s2_ext 49.7% (80.1% retained; 69.6% on uncalibrated lowercase yes/no).
Multi-domain validation perplexity (English, Python & Spanish)
| Variant | Teacher / Mix | WikiText-2 Val | SmolTalk Val* | Python Val* (4k tok) | Spanish Val* (4k tok) |
|---|---|---|---|---|---|
| Original Qwen3-1.7B | — | 18.40 | 11.48 | 3.75 | 24.64 |
RRT v1 |
1.7B bf16 · EN only | 22.33 | 4.46 | 2.87 | 32.31 (regressed) |
RRT s2_ext |
4B int8 · elite_v2 |
23.81 | 5.81 | 2.01 | 10.21 (3.2× better vs v1) |
*SmolTalk, Python (OpenCodeInstruct), and Spanish (Wikipedia ES + Alpaca-ES) are in-distribution for elite_v2 and use unmasked chat-template distillation loss — compare student-vs-student rather than against the frozen base model (see Section 3).
Surprise 1: LoRA relaxation carries nearly 100% of recovered capacity
Disabling the LoRA adapters (mod.scaling = 0.0, while keeping both the trained shared base weights and the lightweight out_scale vectors intact) on s2_ext/best.pt blows WikiText-2 Test PPL from 31.71 to 1,087.93, drops ARC-Easy to near chance (30.5% vs 25% random across 4 options), and collapses greedy generation to empty output. (Zeroing out_scale as well for pure strict recursion would only degrade it further.)
Looking at mean relative LoRA norm by projection shows where depth specialization concentrates:
| Projection | Mean |
|---|---|
k_proj |
0.658 |
q_proj |
0.619 |
v_proj |
0.588 |
o_proj |
0.553 |
down_proj |
0.461 |
gate_proj |
0.439 |
up_proj |
0.385 |
Attention projections diverge significantly more across recursion depths than MLP projections, matching the intuition that different depths attend to different syntactic and semantic scales over the same shared FFN knowledge store.
Surprise 2: A 20-point BoolQ scoring artifact — and a harsher real takeaway
When scripts/evaluate.py first printed BoolQ = 41.5% alongside HellaSwag = 40.0% (89.9% of original), something looked wrong. Inspecting the raw log-prob predictions immediately exposed a measurement artifact:
eval_boolqappends"Answer:"and compares raw probabilities of lowercase" yes"vs" no".- In the 200-question validation slice, ground truth is
63.5%(127/200) True. - Because
s2_extadoptedQwen3-4B’s capitalized instruction style afterAnswer:, it predicted lowercase" yes"only16/200times (mean(log P(" yes") - log P(" no")) = -0.912). - Scoring capitalized
" Yes"vs" No"identically across all three models balanceds2_ext’s predictions (105/200Yes) and liftedBoolQfrom41.5%to62.0%(zero-mean calibration on lowercase" yes"/" no"independently gives61.0%), moving 3-benchmark retention from69.6%to80.1%.
Importantly, fixing the scoring bias does not rescue the compressed models on BoolQ: at 62.0% (s2_ext) and 63.5% (v1), both sit right at BoolQ’s 63.5% majority-class baseline (down from 78.0% for original Qwen3-1.7B), revealing that yes/no reading comprehension took the heaviest hit from the 34% layer cut. I kept the original script’s raw 41.5% column alongside 62.0% rather than quietly changing the evaluator — just like separating measurement bugs from model improvements in an eval gate, you want both numbers visible.
Surprise 3 (the biggest ML lesson): Why v1 beat s2_ext on English benchmarks
This was the finding I did not expect. Even though v1 had fewer parameters (1.196B vs 1.237B), trained for half the wall-clock time (10h vs 20.3h), and never saw Qwen3-4B, it beat s2_ext on every English-only metric: WikiText-2 (29.74 vs 31.71), ARC-Easy (51.0% vs 47.0%), BoolQ Yes/No (63.5% vs 62.0%), and HellaSwag (44.5% — 100% of original Qwen3-1.7B!). Because multiple variables changed between v1 and s2_ext (teacher, data mix, hidden-state alignment, LR, and stage schedule), this is a pipeline comparison rather than a single-variable teacher ablation — and breaking down what differed points directly to the schedule:
- Exact same-space hidden alignment (
v1) vs cross-architecture projection (s2_ext): Inv1, student and teacher live in the exact same2048-dim residual stream and share the exact same frozenlm_head. Thirteen matched 1-to-1 hidden-state taps (weight=2.0) tell every compressed recursion pair how to reconstructQwen3-1.7B’s exact internal activations. In my Strong-to-Weak pipeline, I cut Stage 1 off after just 36 minutes (5.07Mtokens) and switched toQwen3-4B int8(2560-dim, 36 layers, only 6 projected taps atweight=0.25), forcing the still-damaged student to adapt to a different model’s logit distribution throughQwen3-1.7B’s frozen head. - English token budget & learning rate:
v1trained on109.6M100%-English tokens atlr = 1.5e-4(3×higher LR, and faster at~3,150 tok/s).s2_extspent22%of its tokens on Python (12%) and Spanish (10%) atlr = 5e-5. - The flip side —
v1broke Spanish,s2_extkept Python & Spanish healthy: Look at the rightmost column of the validation table. Even with the chat-template bonus onAlpaca-ES, trainingv1on English alone caused Spanish validation perplexity to degrade from24.64(original) to32.31. Meanwhile,s2_extonelite_v2reached2.01on Python (vs2.87forv1) and10.21on Spanish — 3.2× better thanv1.
The actionable recipe this points to: for single-GPU RRT compression, I allocated my 20 hours backward. Instead of a 36-minute Stage 1 followed by 19+ hours of Stage 2, the stronger recipe is a long Stage 1 (same-architecture self-healing on elite_v2) so 1-to-1 hidden supervision heals the shared residual stream across English, code, and Spanish simultaneously, followed by a shorter Stage 2 (Qwen3-4B int8) polish once the compressed weights are already healthy.
Qualitative sanity check (temperature = 0)
On six deterministic side-by-side prompts (scripts/evaluate.py), s2_ext (82.4 tok/s vs 119.7 tok/s unmerged original) shows clearly both what recovered and where a 34% layer cut still breaks down:
- Factual QA (Penicillin): accurately names Alexander Fleming, 1928, and Penicillium notatum in the opening paragraph, then hallucinates in paragraph 2 (claiming Fleming mixed the mold with “a substance called Penicillin” and previously isolated it from Staphylococcus aureus).
- Python (
is_palindrome): writes a clean, working implementation (''.join(char.lower() for char in s if char.isalnum())), then repeats the function definition under greedy decoding instead of writing the two requestedasserttests. - Instruction following (electric cars): produces readable pros, but ignores the 12-word bullet cap and drops the 3 cons entirely.
- Explanations & Spanish: clear HTTPS explanation and fluent Spanish phrasing, but factual drift shows up on photosynthesis (including “animales” and hallucinating “la luz solar se une a los electrones de los átomos de carbono para producir glucosa, un alcano de azúcar”).
- Multi-step word math (train catch-up): repeats the problem setup instead of solving the rate equation (typical without CoT distillation at ~1.2B).
5. Five Takeaways for Single-GPU Distillation
- Always anchor your step-0 eval floor across multi-stage
--init-fromruns, rotate dataset RNG seeds, and persist auxiliary projectors so a broken stage can never silently overwritebest.pt. - Do not blindly copy losses from full-capacity distillation: reverse-skewed JSD behaves very differently when the student’s weights are structurally tied via recursion.
- Never align the final hidden layer across architectures when
lm_headis frozen: keep cross-architecture DSKD on interior layers only and let logit KL govern the final representation. - Python reference lifetime is VRAM management: explicitly dropping full hidden-state tuples before chunked logit backward gave a free
+25%throughput boost (1,860 -> 2,330 tok/s) and-380 MBpeak VRAM on a 16 GB card. - Inspect raw predictions and run the cheap baseline ablation: checking raw
BoolQpredictions uncovered a 20-point capitalization artifact, and running the exact same suite onv1revealed that same-architecture self-healing should get the lion’s share of compute before Strong-to-Weak transfer.
Reproduce Locally
All code, custom Triton kernels (RMSNorm, zero-copy 2D SwiGLU, Grouped LoRA SGMV), 82 unit tests (41 CPU + 41 CUDA/Triton), evaluation harness, and the zero-dependency live dashboard are open-source:
git clone https://github.com/Reezo912/Relaxed-Recursive-Transformers-implementation.git
cd Relaxed-Recursive-Transformers-implementation
uv sync --python 3.11
# Verify tests (82 tests on CUDA GPU; prefix CUDA_VISIBLE_DEVICES="" for 41 CPU tests)
TRITON_DEFAULT_FP_FUSION=1 uv run pytest -v
# Launch 2-stage Strong-to-Weak distillation + live web dashboard
./scripts/run_2stage_distill.sh
uv run python scripts/dashboard.py --port 7860
# Run full quantitative evaluation + Strict (LoRA OFF) ablation
TRITON_DEFAULT_FP_FUSION=1 uv run python scripts/evaluate.py \
--checkpoint checkpoints/qwen3_1.7b_rrt_s2_ext/best.pt --n-bench 200
If you are working on parameter sharing, single-GPU distillation, or on-device LLM compression and want to compare notes, feel free to reach out on LinkedIn or GitHub.