"""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