"""Build Qwen3.5 text-model decoder layers from the MOSS-Image text_encoder checkpoint, one run of layers at a time.""" import sys import numpy as np import torch sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__))) from common import TE_DIR, ST # noqa: E402 from te_ops import TEPart, patch_linear_attn # noqa: E402 def text_config(): from transformers import AutoConfig cfg = AutoConfig.from_pretrained(TE_DIR).text_config cfg._attn_implementation = "sdpa" return cfg def _load(module, st, prefix, dtype): sd = {} for k in st.keys(): if k.startswith(prefix): sd[k[len(prefix):]] = torch.from_numpy(st.get_f32(k)) res = module.load_state_dict(sd, strict=True) return res def build_layers(idxs, dtype, patch, st=None): from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5DecoderLayer cfg = text_config() st = st or ST(TE_DIR, "model.safetensors.index.json") layers = [] for i in idxs: with torch.device("meta"): layer = Qwen3_5DecoderLayer(cfg, i) layer = layer.to(dtype).to_empty(device="cpu") _load(layer, st, f"language_model.layers.{i}.", dtype) if patch and layer.block_type == "linear_attention": patch_linear_attn(layer) layers.append(layer.eval()) return layers def build_norm(dtype, st=None): from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5RMSNorm cfg = text_config() st = st or ST(TE_DIR, "model.safetensors.index.json") with torch.device("meta"): norm = Qwen3_5RMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) norm = norm.to(dtype).to_empty(device="cpu") norm.load_state_dict({"weight": torch.from_numpy(st.get_f32("language_model.norm.weight"))}, strict=True) return norm.eval() def build_part(k, dtype, patch, st=None, cast_io=False): idxs = list(range(8 * k, 8 * k + 8)) layers = build_layers(idxs, dtype, patch, st) norm = build_norm(dtype, st) if k == 3 else None return TEPart(layers, norm, dtype=dtype, cast_io=cast_io).eval()