"""Locating a checkpoint and loading its text backbone. A checkpoint is a ``Qwen3_5Model`` package (``language_model.*`` text weights plus a vision tower this package never uses). Only the text backbone is loaded. """ from __future__ import annotations import json from pathlib import Path import torch from safetensors import safe_open PREFIXES = ("language_model.", "model.language_model.") def resolve(name_or_path: str, revision: str | None = None) -> Path: """A local directory, or a Hugging Face Hub repo id downloaded to the local cache.""" path = Path(name_or_path) if path.is_dir(): return path from huggingface_hub import snapshot_download return Path(snapshot_download(name_or_path, revision=revision)) def _weight_files(root: Path) -> dict[str, Path]: index = root / "model.safetensors.index.json" if index.exists(): return {k: root / v for k, v in json.loads(index.read_text())["weight_map"].items()} with safe_open(str(root / "model.safetensors"), "pt") as f: return {k: root / "model.safetensors" for k in f.keys()} def load_text_model(root: Path, dtype: torch.dtype = torch.bfloat16): """-> ``Qwen3_5TextModel`` on the CPU with the checkpoint's text-backbone weights.""" from transformers import AutoConfig from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5TextModel, Qwen3_5TextRotaryEmbedding config = AutoConfig.from_pretrained(str(root)) text_config = getattr(config, "text_config", config) files = _weight_files(root) prefix = next((p for p in PREFIXES if any(k.startswith(p) for k in files)), None) if prefix is None: raise ValueError(f"no text-backbone weights under any of {PREFIXES}") state = {} for path in sorted(set(files.values())): with safe_open(str(path), "pt") as f: for key in f.keys(): if key.startswith(prefix): state[key[len(prefix):]] = f.get_tensor(key).to(dtype) with torch.device("meta"): lm = Qwen3_5TextModel(text_config) lm.load_state_dict(state, strict=True, assign=True) lm.rotary_emb = Qwen3_5TextRotaryEmbedding(text_config) # non-persistent buffers, lost on the meta device return lm