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.
File size: 2,490 Bytes
be1646c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Lightweight 40 MB Plug-in Loader: mount ContractiveLoopCore onto official Qwen/Qwen3-4B-Base."""
import json
import torch
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
from transformers import AutoModelForCausalLM, AutoTokenizer

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from modeling_loop_qwen3 import ContractiveLoopCore, PassThroughLayer


def load_loop_qwen3_plugin(repo_id: str, device: str = "cuda", dtype=torch.float16, num_loops: int = 3):
    cfg_path = hf_hub_download(repo_id, "plugin/plugin_config.json")
    w_path = hf_hub_download(repo_id, "plugin/contractive_loop_core.safetensors")
    meta = json.loads(Path(cfg_path).read_text(encoding="utf-8"))
    tensors = load_file(w_path, device="cpu")

    tokenizer = AutoTokenizer.from_pretrained(meta["base_model"])
    model = AutoModelForCausalLM.from_pretrained(meta["base_model"], dtype=dtype, device_map={"": 0} if device == "cuda" else None)

    # 1) Merge weight-tied Core LoRA directly into L21..L28 (0-based 20..27)
    scale = float(meta["alpha"]) / float(meta["rank"])
    with torch.no_grad():
        for rel_i in range(8):
            blk = model.model.layers[20 + rel_i]
            for pn, cn in [("self_attn","q_proj"),("self_attn","v_proj"),("self_attn","o_proj"),("mlp","gate_proj"),("mlp","up_proj"),("mlp","down_proj")]:
                lin = getattr(getattr(blk, pn), cn)
                A = tensors[f"lora.L{rel_i}.{pn}.{cn}.A"].to(lin.weight.device, dtype=torch.float32)
                B = tensors[f"lora.L{rel_i}.{pn}.{cn}.B"].to(lin.weight.device, dtype=torch.float32)
                lin.weight.add_((scale * (B @ A)).to(dtype=lin.weight.dtype))

    # 2) Wrap L21..L28 with ContractiveLoopCore
    core_layers = [model.model.layers[i] for i in range(20, 28)]
    loop_core = ContractiveLoopCore(
        core_layers=core_layers,
        d_model=model.config.hidden_size,
        bottleneck=meta["bottleneck"],
        gate_rank=meta["gate_rank"],
        halt_rank=meta["halt_rank"],
        default_num_loops=num_loops,
    ).to(device=model.device, dtype=dtype)
    bridge_sd = {k.replace("bridge.", ""): v for k, v in tensors.items() if k.startswith("bridge.")}
    loop_core.load_state_dict(bridge_sd, strict=False)
    model.model.layers[20] = loop_core
    for idx in range(21, 28):
        model.model.layers[idx] = PassThroughLayer()
    model.eval()
    return model, tokenizer, loop_core