Run this model with HF Jobs

Run qdk0901/LoopQwen3-Contractive-4B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/qdk0901/LoopQwen3-Contractive-4B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/qdk0901/LoopQwen3-Contractive-4B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/qdk0901/LoopQwen3-Contractive-4B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.

Quantize for lower memory use

Use HF Jobs to create a 4-bit version of https://huggingface.co/qdk0901/LoopQwen3-Contractive-4B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
LoopQwen3-Contractive-4B / modeling_loop_qwen3.py
qdk0901's picture
Initial public release: LoopQwen3-Contractive-4B (Self-Locking Contractive Core + 40 MB Plug-in + Interactive Colab Demo + Full 19-Exp Report)
be1646c verified
Raw History Blame Contribute Delete
8.83 kB
import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import Qwen3ForCausalLM
try:
from .configuration_loop_qwen3 import LoopQwen3Config
except ImportError:
from configuration_loop_qwen3 import LoopQwen3Config
class ContractiveRMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
xf = x.float()
rms = torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + self.eps)
return xf * rms * self.weight.float()
class ContractiveLoopCore(nn.Module):
"""Self-Locking Contractive Fixed-Point Recurrent Core wrapping Layers L21..L28 (0-based 20..27).
Update Law (computed in FP32 for numerical stability across FP16/BF16/FP32 models):
mem_t = mem_{t-1} + s_t * (g_t * (cand_t - mem_{t-1}))
where:
- s_t in (0, 1): learned token-level scalar thinking gate (1 = refine, 0 = LOCK fixed point!)
- g_t in (0, 1)^d: context-aware channel GRU gate
- Exact Loop-Aware KV-Cache assigns disjoint cache slots per loop iteration t.
"""
def __init__(
self,
core_layers,
d_model: int,
bottleneck: int = 384,
gate_rank: int = 96,
halt_rank: int = 128,
base_layer_start: int = 20,
total_model_layers: int = 36,
default_num_loops: int = 3,
):
super().__init__()
self.core_layers = nn.ModuleList(core_layers)
self.base_layer_start = base_layer_start
self.total_model_layers = total_model_layers
self.delta_norm = ContractiveRMSNorm(d_model)
self.ctx_norm = ContractiveRMSNorm(d_model)
self.bridge_down = nn.Linear(d_model, bottleneck, bias=False)
self.bridge_up = nn.Linear(bottleneck, d_model, bias=False)
self.recur_bias = nn.Parameter(torch.zeros((1, 1, d_model)))
self.step_scale = nn.Parameter(torch.tensor(0.15))
self.gate_delta_down = nn.Linear(d_model, gate_rank, bias=False)
self.gate_ctx_down = nn.Linear(d_model, gate_rank, bias=False)
self.gate_up = nn.Linear(gate_rank, d_model, bias=False)
self.gate_bias = nn.Parameter(torch.zeros((1, 1, d_model)))
self.halt_delta = nn.Linear(d_model, halt_rank, bias=False)
self.halt_ctx = nn.Linear(d_model, halt_rank, bias=False)
self.halt_out = nn.Linear(halt_rank, 1, bias=True)
self.num_loops = int(default_num_loops)
self.record_halting_trace = False
self.last_s_trace = []
@staticmethod
def _lin_fp32(x: torch.Tensor, lin: nn.Linear) -> torch.Tensor:
b = lin.bias.float() if lin.bias is not None else None
return F.linear(x, lin.weight.float(), b)
def compute_thinking_prob(self, h_cur: torch.Tensor, h_pre: torch.Tensor, ctx_n: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Returns s_t in (0, 1): probability that more latent loops are needed (p_done = 1 - s_t)."""
if ctx_n is None:
ctx_n = self.ctx_norm(h_pre)
delta_n = self.delta_norm(h_cur - h_pre)
hh = F.silu(self._lin_fp32(delta_n, self.halt_delta) + self._lin_fp32(ctx_n, self.halt_ctx))
return torch.sigmoid(self._lin_fp32(hh, self.halt_out))
def _set_loop_cache_indices(self, t: int, pkv=None):
n_core = len(self.core_layers)
max_slot = 0
for rel_i, layer in enumerate(self.core_layers):
slot = (self.base_layer_start + rel_i) if t == 0 else (self.total_model_layers + (t - 1) * n_core + rel_i)
layer.self_attn.layer_idx = slot
if slot > max_slot:
max_slot = slot
# Compatible with both Transformers v5 DynamicCache (pkv.layers) and v4 DynamicCache (auto-growing key_cache)
if pkv is not None and hasattr(pkv, "layers") and len(pkv.layers) <= max_slot:
layer_cls = type(pkv.layers[0])
while len(pkv.layers) <= max_slot:
pkv.layers.append(layer_cls())
def _run_core_once(self, h_in: torch.Tensor, *args, **kwargs) -> torch.Tensor:
h = h_in
for layer in self.core_layers:
h = layer(h, *args, **kwargs)
if isinstance(h, tuple):
h = h[0]
return h
def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
h_pre = hidden_states
ctx_n = None
mem = None
h = h_pre
self.last_s_trace = []
pkv = kwargs.get("past_key_values", None)
has_cache = pkv is not None
try:
for t in range(self.num_loops):
if has_cache:
self._set_loop_cache_indices(t, pkv)
if t > 0:
if ctx_n is None:
ctx_n = self.ctx_norm(h_pre)
delta_n = self.delta_norm(h - h_pre)
cand_h = F.silu(self._lin_fp32(delta_n, self.bridge_down))
cand = self.step_scale.float() * self._lin_fp32(cand_h, self.bridge_up) + self.recur_bias.float()
g_hid = F.silu(self._lin_fp32(delta_n, self.gate_delta_down) + self._lin_fp32(ctx_n, self.gate_ctx_down))
gate = torch.sigmoid(self._lin_fp32(g_hid, self.gate_up) + self.gate_bias.float())
h_hid = F.silu(self._lin_fp32(delta_n, self.halt_delta) + self._lin_fp32(ctx_n, self.halt_ctx))
s_t = torch.sigmoid(self._lin_fp32(h_hid, self.halt_out))
if self.record_halting_trace:
self.last_s_trace.append(s_t.detach())
mem = (s_t * (gate * cand)) if mem is None else (mem + s_t * (gate * (cand - mem)))
h_in = h_pre + mem.to(dtype=h_pre.dtype)
else:
h_in = h_pre
h = self._run_core_once(h_in, *args, **kwargs)
if self.record_halting_trace:
s_final = self.compute_thinking_prob(h, h_pre, ctx_n)
self.last_s_trace.append(s_final.detach())
finally:
if has_cache:
self._set_loop_cache_indices(0)
return h
class PassThroughLayer(nn.Module):
def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
return hidden_states
class LoopQwen3ForCausalLM(Qwen3ForCausalLM):
"""Qwen3-4B-Base retrofitted with a Self-Locking Contractive Fixed-Point Recurrent Core on Layers L21..L28."""
config_class = LoopQwen3Config
def __init__(self, config: LoopQwen3Config):
super().__init__(config)
s_idx = int(getattr(config, "loop_start_layer", 20))
e_idx = int(getattr(config, "loop_end_layer", 28))
core_layers = [self.model.layers[i] for i in range(s_idx, e_idx)]
loop_core = ContractiveLoopCore(
core_layers=core_layers,
d_model=config.hidden_size,
bottleneck=int(getattr(config, "loop_bottleneck", 384)),
gate_rank=int(getattr(config, "loop_gate_rank", 96)),
halt_rank=int(getattr(config, "loop_halt_rank", 128)),
base_layer_start=s_idx,
total_model_layers=config.num_hidden_layers,
default_num_loops=int(getattr(config, "default_num_loops", 3)),
)
# Register ONLY under self.model.layers[s_idx] so safetensors has zero shared-tensor aliases!
self.model.layers[s_idx] = loop_core
for idx in range(s_idx + 1, e_idx):
self.model.layers[idx] = PassThroughLayer()
@property
def loop_core(self) -> ContractiveLoopCore:
return self.model.layers[int(getattr(self.config, "loop_start_layer", 20))]
def set_num_loops(self, num_loops: int):
"""Set test-time latent reasoning depth T (effective layers = 20 + 8*T + 8). Recommended T in 1..6."""
if num_loops < 1:
raise ValueError("num_loops must be >= 1")
self.loop_core.num_loops = int(num_loops)
return self
def get_num_loops(self) -> int:
return int(self.loop_core.num_loops)
def get_effective_layers(self) -> int:
n_core = len(self.loop_core.core_layers)
return (self.config.num_hidden_layers - n_core) + n_core * self.loop_core.num_loops
def generate_with_loops(self, *args, num_loops: Optional[int] = None, **kwargs):
"""Generate with an explicit test-time loop count T while restoring previous T afterwards."""
prev = self.get_num_loops()
try:
if num_loops is not None:
self.set_num_loops(num_loops)
return self.generate(*args, **kwargs)
finally:
self.set_num_loops(prev)