File size: 2,119 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
"""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()