File size: 7,752 Bytes
6eaaa7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# -*- coding: utf-8 -*-
"""TinyCustomEmbed 的 sentence-transformers 自包含模块(由 export_sentence_transformers.py 生成)。"""
from __future__ import annotations

import json
import os

import torch
from torch import nn


class RMSNorm(nn.Module):
    def __init__(self, hidden_size: int, eps: float = 1e-6):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.eps = eps

    def forward(self, x):
        rms = x.float().pow(2).mean(-1, keepdim=True)
        return (x * torch.rsqrt(rms + self.eps)).to(x.dtype) * self.weight


class RotaryEmbedding(nn.Module):
    def __init__(self, dim: int, theta: float = 10000.0):
        super().__init__()
        inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
        self.register_buffer("inv_freq", inv_freq, persistent=False)

    @torch.no_grad()
    def forward(self, seq_len, device, dtype):
        t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype)
        freqs = torch.outer(t, self.inv_freq)
        return freqs.cos().to(dtype), freqs.sin().to(dtype)


def _rotate_half(x):
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat((-x2, x1), dim=-1)


def _apply_rope(x, cos, sin):
    seq_len = x.shape[-3]
    cos = cos[:seq_len].unsqueeze(0).unsqueeze(2)
    sin = sin[:seq_len].unsqueeze(0).unsqueeze(2)
    return x * cos + _rotate_half(x) * sin


class _Attn(nn.Module):
    def __init__(self, hidden, heads, window, qk_norm, full):
        super().__init__()
        self.heads, self.head_dim = heads, hidden // heads
        self.window, self.full = window, full
        self.q_proj = nn.Linear(hidden, hidden, bias=False)
        self.k_proj = nn.Linear(hidden, hidden, bias=False)
        self.v_proj = nn.Linear(hidden, hidden, bias=False)
        self.o_proj = nn.Linear(hidden, hidden, bias=False)
        self.q_norm = RMSNorm(self.head_dim) if qk_norm else None
        self.k_norm = RMSNorm(self.head_dim) if qk_norm else None

    def forward(self, x, cos, sin, pad_mask):
        B, L, _ = x.shape
        q = self.q_proj(x).view(B, L, self.heads, self.head_dim)
        k = self.k_proj(x).view(B, L, self.heads, self.head_dim)
        v = self.v_proj(x).view(B, L, self.heads, self.head_dim)
        if cos is not None:
            q, k = _apply_rope(q, cos, sin), _apply_rope(k, cos, sin)
        if self.q_norm is not None:
            q, k = self.q_norm(q), self.k_norm(k)
        qh, kh, vh = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
        use_win = (self.window > 0) and (not self.full) and L > self.window
        keep = pad_mask.bool()[:, None, :].expand(B, L, L).clone()
        if use_win:
            half = self.window // 2
            idx = torch.arange(L, device=x.device)
            keep &= (idx[:, None] - idx[None, :]).abs().le(half)[None]
        pos = torch.arange(L, device=x.device)
        keep |= (pos[None, :] == pos[:, None])[None]
        out = torch.nn.functional.scaled_dot_product_attention(qh, kh, vh,
                                                               attn_mask=keep[:, None])
        return self.o_proj(out.transpose(1, 2).reshape(B, L, -1))


class _GeGLU(nn.Module):
    def __init__(self, hidden, inter, bias=False):
        super().__init__()
        self.gate_proj = nn.Linear(hidden, inter, bias=bias)
        self.up_proj = nn.Linear(hidden, inter, bias=bias)
        self.down_proj = nn.Linear(inter, hidden, bias=bias)

    def forward(self, x):
        return self.down_proj(torch.nn.functional.gelu(self.gate_proj(x)) * self.up_proj(x))


class _Layer(nn.Module):
    def __init__(self, hidden, inter, heads, window, qk_norm, full):
        super().__init__()
        self.pre_attn_norm, self.post_attn_norm = RMSNorm(hidden), RMSNorm(hidden)
        self.self_attn = _Attn(hidden, heads, window, qk_norm, full)
        self.ffn = _GeGLU(hidden, inter)

    def forward(self, x, cos, sin, pad_mask, is_global):
        x = x + self.self_attn(self.pre_attn_norm(x), cos, sin, pad_mask)  # full/window 在 _Attn 构造时已定
        return x + self.ffn(self.post_attn_norm(x))


class TinyEmbedTransformer(nn.Module):
    """ST Transformer 模块:加载 TinyCustomEmbed 权重并输出 token_embeddings。"""

    def __init__(self, model_path: str = ".", max_length: int = 512, **kwargs):
        super().__init__()
        with open(os.path.join(model_path, "config.json"), encoding="utf-8") as f:
            c = json.load(f)
        self.config = c
        H = c["hidden_size"]
        self.token_embedding = nn.Embedding(c["vocab_size"], H)
        # 只建 num_unique_layers 个真实层(与原模型 state_dict 一致),
        # forward 按 li % num_unique_layers 复用(权重共享语义)
        uniq = c["num_unique_layers"]
        self.num_unique_layers = uniq
        self.layers = nn.ModuleList([
            _Layer(H, c["intermediate_size"], c["num_attention_heads"],
                   c["sliding_window"], c.get("use_qk_norm", True),
                   ui in (0, uniq - 1))
            for ui in range(uniq)])
        self.final_norm = RMSNorm(H)
        self.rope = (RotaryEmbedding(c["head_dim"] * 2, c.get("rope_theta", 10000.0))
                     if c.get("positional_encoding", "rope") == "rope" else None)
        self.position_embedding = (nn.Embedding(c["max_position_embeddings"], H)
                       if c.get("positional_encoding") == "abs" else None)
        if self.position_embedding is not None and os.path.exists(os.path.join(model_path, "pytorch_model.bin")):
            pass  # 权重统一由 load_state_dict 装载
        # loop_embedding / pos_adapters / layer_gates 如存在则按 config 重建
        self.loop_embedding = (nn.Embedding(c["effective_num_layers"], H)
                               if c.get("loop_index_embedding") else None)
        r = c.get("pos_adapter_rank", 0)
        self.pos_adapters = None
        self._model_path = model_path
        self.max_seq_length = max_length
        from transformers import AutoTokenizer

        self.tokenizer = AutoTokenizer.from_pretrained(model_path)

    def tokenize(self, texts, **kwargs):
        return self.tokenizer(list(texts), padding=True, truncation=True,
                              max_length=self.max_seq_length, return_tensors="pt", **kwargs)

    def forward(self, features):
        ids = features["input_ids"]
        am = features["attention_mask"]
        h = self.token_embedding(ids)
        if self.position_embedding is not None:
            h = h + self.position_embedding(torch.arange(ids.shape[1], device=ids.device))
        cos = sin = None
        if self.rope is not None:
            cos, sin = self.rope(ids.shape[1], ids.device, h.dtype)
        uniq = self.num_unique_layers
        for li in range(self.config["effective_num_layers"]):
            if self.loop_embedding is not None:
                h = h + self.loop_embedding.weight[li].to(h.dtype)
            ui = li % uniq
            h = self.layers[ui](h, cos, sin, am, ui in (0, uniq - 1))
        features["token_embeddings"] = self.final_norm(h)
        return features

    def save(self, output_path, *args, **kwargs):
        torch.save(self.state_dict(), os.path.join(output_path, "pytorch_model.bin"))

    @staticmethod
    def load(input_path):
        module = TinyEmbedTransformer(model_path=input_path)
        # ST 对远程代码模块不会自动装载权重,必须在 load() 里自己完成
        state = torch.load(os.path.join(input_path, "pytorch_model.bin"),
                           map_location="cpu")
        module.load_state_dict(state, strict=True)
        return module

    def get_word_embedding_dimension(self):
        return self.config["hidden_size"]