--- license: apache-2.0 base_model: Qwen/Qwen3-4B-Base language: - en - zh library_name: transformers pipeline_tag: text-generation tags: - qwen3 - recurrent-depth - test-time-compute - latent-reasoning - mechanistic-interpretability - contractive-fixed-point --- # LoopQwen3-Contractive-4B [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#fileId=https://huggingface.co/qdk0901/LoopQwen3-Contractive-4B/resolve/main/demo_colab.ipynb) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE) > **Try it live on a free T4 GPU in 1 click!** Click **Open In Colab** above (or view [demo_colab.ipynb](demo_colab.ipynb)) to test `T=1..6` scaling and the live Self-Locking Gate `s_t` interactive Gradio playground. **Zero-Pretraining Architectural Retrofit of `Qwen/Qwen3-4B-Base` into a Self-Locking Contractive Fixed-Point Recurrent-Depth Transformer** **零从头预训练架构改造:基于信息分层定位的 `Qwen3-4B-Base` 自锁压缩不动点递归推理大模型** --- ## Highlights / 核心亮点 Without pretraining from scratch and by modifying **only 0.254% of parameters** (keeping **28 out of 36 layers bit-for-bit frozen**), we mechanically located the emergent High-Abstraction Reasoning Hub of `Qwen/Qwen3-4B-Base` at **Layers `L21–L28`** (causal peak at `L24` Self-Attention + `L25` MLP) and physically rewired the forward graph into a **Recurrent-Depth Architecture** with a **Self-Locking Contractive Fixed-Point Bridge**: ```text Prelude (L1–L20, 100% Frozen) ──▶ [ ContractiveLoopCore (L21–L28) × T iterations ] (Effective depth = 20 + 8·T + 8) └── m_t = m_{t-1} + s_t · (g_t ⊙ (cand_t - m_{t-1})) ──▶ Coda (L29–L36, 100% Frozen) ``` - **Zero Domain Experts (No MoE / No Task Router)**: One single universal recurrent core works across open-ended coding, math, deductive logic, rule induction, and zero-CoT multi-hop latent reasoning. - **Exact Loop-Aware KV-Cache (`use_cache=True == use_cache=False`)**: Disjoint KV-cache slots per loop step enable full-speed autoregressive generation at any test-time depth $T$ (36L, 44L, 52L, 60L, 68L, 76L effective layers). - **Strictly Non-Regressing Test-Time Compute Scaling**: On identical frozen weights, increasing internal loop depth $T = 1 \to 2 \to 3$ improves zero-CoT Python Code Tracing **`80% → 90% → 100%`** and 50-problem 5-domain general reasoning **`90% → 92% → 94%`** with **0 regressions**, while maintaining **100% (12/12)** pass@1 on executable Python function writing (`exec()` unit tests). - **Learned Self-Locking Stopping Gate ($s_t \in (0, 1)$)**: Automatically locks fixed-point working memory ($m_t = m_{t-1}$) right after reasoning depth $D$ (`D=1 → 1.02×`, `D=2 → 2.12×`, `D=3 → 3.27×`, `D=4 → 3.95×`, unseen `D=5 → 4.72×`, unseen `D=6 → 5.17×`), cutting compute by **44%** while outperforming fixed $T=6$ (`67.9%` vs `65.4%`) and halving $T=1$ calibration error (ECE `40.7% → 18.7%`, AUROC `72.1% → 82.5%`). - **Dual Distribution**: Full standalone `AutoModelForCausalLM(..., trust_remote_code=True)` weights in the repo root **AND** a lightweight **40 MB plug-in** in `plugin/contractive_loop_core.safetensors` for users who already have `Qwen/Qwen3-4B-Base`. --- ## Benchmark Summary / 核心评测结果 All evaluations are strictly held-out (zero training overlap), evaluated on **identical frozen weights** by simply varying the test-time loop switch `model.set_num_loops(T)`: | Benchmark (Held-Out, Zero Leakage) | Original `Qwen3-4B-Base` (36L) | `LoopQwen3` **T=1** (36L) | `LoopQwen3` **T=2** (44L) | `LoopQwen3` **T=3** (52L) | Notes | | :--- | :---: | :---: | :---: | :---: | :--- | | **Zero-CoT Python Code Tracing (N=10)** | 80.0% | 80.0% | **90.0%** | **100.0%** | Strict monotonic scaling (+20% vs T=1 & Base!) | | **Executable Python CodeGen `exec()` Pass@1 (N=12)** | 91.7% (11/12) | **100.0%** | **100.0%** | **100.0%** | 12/12 unit tests pass across all T | | **5-Domain General Reasoning (Exp 12, N=50)** | 74.0% | 90.0% | **92.0%** | **94.0%** | **+2 wins / 0 regressions** (Word 100%, Logic 100%, Code 100%, Cross-Induct 90%, Pattern 80%) | | **OOD Rule & Recursive Closed-Form Folding (Exp 11, N=26)** | 57.7% | **92.3%** | **92.3%** | **92.3%** | Recursive folding **100%**, zero regression | | **General Symbolic Logic Retention** | 100.0% | **100.0%** | — | **100.0%** | Zero catastrophic forgetting | | **Zero-CoT Pure-Latent Multi-Hop (Exp 15, D=1..6, N=240)** | 40.0% (Unseen D5,6: 11.2%) | 37.1% | 62.5% | 66.3% | Autonomous self-halting (`s_t < 0.5`, avg **3.38×** loops): **67.9%** (beats fixed T=6 `65.4%`, D1/D2 **100%/100%**) | --- ## Mechanistic Research Figures / 机理定位与缩放曲线 ### 1. Layer-Wise Information Hierarchy Localization (`Qwen3-4B-Base`, 36 Layers) ![Master Information Hierarchy Map](figures/exp4_master_information_hierarchy.png) ### 2. Self-Locking Contractive Fixed-Point Scaling & Calibrated Halting (Experiment 19B) ![Contractive Fixed-Point Scaling](figures/exp19b_contractive_fixed_point.png) ### 3. Pure-Latent Multi-Hop Staircase Activation Up to Unseen 76 Effective Layers (Experiment 15) ![Pure-Latent Multi-Hop Scaling](figures/exp15_loop_qwen3_v2_scaling.png) *(Full 19-experiment Chinese research report included in [REPORT_Qwen3_4B_Base.md](REPORT_Qwen3_4B_Base.md).)* --- ## Quickstart / 快速上手 ### Option 1: Standard `transformers` Standalone Loading (Recommended) ```python import torch from transformers import AutoModelForCausalLM, AutoTokenizer repo_id = "qdk0901/LoopQwen3-Contractive-4B" tokenizer = AutoTokenizer.from_pretrained(repo_id, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( repo_id, trust_remote_code=True, dtype=torch.float16, device_map="auto", ).eval() # Adjust test-time latent compute depth dynamically on identical frozen weights! model.set_num_loops(3) # T=1 -> 36L, T=2 -> 44L, T=3 -> 52L, T=4 -> 60L ... prompt = ( "What integer does this Python code print?\n" "```python\n" "x = 2\n" "for _ in range(3):\n" " x = x * 2 + 1\n" "print(x)\n" "```\n" "Output: " ) inputs = tokenizer(prompt, return_tensors="pt").to(model.device) with torch.no_grad(): out = model.generate(**inputs, max_new_tokens=16, do_sample=False, use_cache=True) print(tokenizer.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)) ``` ### Inspecting the Self-Locking Thinking Gate $s_t$ (`p_done = 1 - s_t`) ```python model.loop_core.record_halting_trace = True model.set_num_loops(4) with torch.no_grad(): _ = model(**inputs, use_cache=False) # s_t near 1.0 = still thinking; s_t < 0.5 = converged & locked! print([round(s[0, -1, 0].item(), 3) for s in model.loop_core.last_s_trace]) model.loop_core.record_halting_trace = False ``` ### Option 2: Lightweight 40 MB Plug-in (Reuses Official `Qwen/Qwen3-4B-Base`) See `plugin/load_plugin.py` and `plugin/contractive_loop_core.safetensors` (~40 MB). --- ## Acknowledgements & License Built directly atop [Qwen/Qwen3-4B-Base](https://huggingface.co/Qwen/Qwen3-4B-Base) under the **Apache 2.0 License**. All experiments were conducted on a single Tesla T4 (15 GB VRAM) without pretraining from scratch.