File size: 9,037 Bytes
44638a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from safetensors.torch import load_model


class ByteAgentTokenizer:
    SPECIAL_TOKENS = [
        "<|pad|>", "<|bos|>", "<|eos|>",
        "<|system|>", "<|/system|>",
        "<|user|>", "<|/user|>",
        "<|assistant|>", "<|/assistant|>",
        "<|img_start|>", "<|img_patch|>", "<|img_end|>",
        "<|tool_call|>", "<|/tool_call|>",
        "<|tool_result|>", "<|/tool_result|>",
        "<|json|>", "<|/json|>",
    ]

    def __init__(self):
        self.special_to_id = {tok: i for i, tok in enumerate(self.SPECIAL_TOKENS)}
        self.id_to_special = {i: tok for i, tok in enumerate(self.SPECIAL_TOKENS)}
        self.byte_offset = len(self.SPECIAL_TOKENS)
        self.vocab_size = 288
        self.pad_id = self.special_to_id["<|pad|>"]
        self.bos_id = self.special_to_id["<|bos|>"]
        self.eos_id = self.special_to_id["<|eos|>"]
        self.img_patch_id = self.special_to_id["<|img_patch|>"]
        self.end_assistant_id = self.special_to_id["<|/assistant|>"]
        self.end_tool_call_id = self.special_to_id["<|/tool_call|>"]

    def encode_text(self, text: str):
        return [self.byte_offset + b for b in text.encode("utf-8")]

    def decode(self, ids, skip_special=False):
        out, buf = [], bytearray()
        for tid in ids:
            tid = int(tid)
            if self.byte_offset <= tid < self.byte_offset + 256:
                buf.append(tid - self.byte_offset)
            else:
                if buf:
                    out.append(buf.decode("utf-8", errors="replace"))
                    buf.clear()
                if not skip_special and tid in self.id_to_special and tid != self.pad_id:
                    out.append(self.id_to_special[tid])
        if buf:
            out.append(buf.decode("utf-8", errors="replace"))
        return "".join(out)

    def build_prompt(self, system_prompt: str, user_prompt: str, has_image: bool = False, n_img_tokens: int = 16):
        ids = [self.bos_id, self.special_to_id["<|system|>"]] + self.encode_text(system_prompt) + [self.special_to_id["<|/system|>"]]
        ids += [self.special_to_id["<|user|>"]] + self.encode_text(user_prompt)
        if has_image:
            ids += [self.special_to_id["<|img_start|>"]] + [self.img_patch_id] * n_img_tokens + [self.special_to_id["<|img_end|>"]]
        ids += [self.special_to_id["<|/user|>"], self.special_to_id["<|assistant|>"]]
        return ids


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

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


def build_rope_cache(seq_len: int, head_dim: int, theta: float = 10000.0):
    inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
    freqs = torch.outer(torch.arange(seq_len, dtype=torch.float32), inv_freq)
    emb = torch.cat([freqs, freqs], dim=-1)
    return emb.cos()[None, None, :, :], emb.sin()[None, None, :, :]


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


def apply_rope(q, k, cos, sin):
    T = q.size(2)
    c, s = cos[:, :, :T, :].to(q.dtype), sin[:, :, :T, :].to(q.dtype)
    return (q * c) + (rotate_half(q) * s), (k * c) + (rotate_half(k) * s)


class CausalSelfAttention(nn.Module):
    def __init__(self, d_model: int, n_heads: int, dropout: float):
        super().__init__()
        self.n_heads = n_heads
        self.head_dim = d_model // n_heads
        self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
        self.out_proj = nn.Linear(d_model, d_model, bias=False)
        self.dropout = dropout

    def forward(self, x, cos, sin):
        B, T, C = x.shape
        q, k, v = self.qkv(x).view(B, T, 3, self.n_heads, self.head_dim).unbind(dim=2)
        q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
        q, k = apply_rope(q, k, cos, sin)
        out = F.scaled_dot_product_attention(q, k, v, dropout_p=self.dropout if self.training else 0.0, is_causal=True)
        return self.out_proj(out.transpose(1, 2).contiguous().view(B, T, C))


class SwiGLUMLP(nn.Module):
    def __init__(self, d_model: int, d_ff: int):
        super().__init__()
        self.w_gate = nn.Linear(d_model, d_ff, bias=False)
        self.w_up = nn.Linear(d_model, d_ff, bias=False)
        self.w_down = nn.Linear(d_ff, d_model, bias=False)

    def forward(self, x):
        return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))


class TransformerBlock(nn.Module):
    def __init__(self, d_model: int, n_heads: int, d_ff: int, dropout: float):
        super().__init__()
        self.norm1 = RMSNorm(d_model)
        self.attn = CausalSelfAttention(d_model, n_heads, dropout)
        self.norm2 = RMSNorm(d_model)
        self.mlp = SwiGLUMLP(d_model, d_ff)

    def forward(self, x, cos, sin):
        x = x + self.attn(self.norm1(x), cos, sin)
        return x + self.mlp(self.norm2(x))


class VisionPatchEncoder(nn.Module):
    def __init__(self, d_model: int, n_img_tokens: int):
        super().__init__()
        self.backbone = nn.Sequential(
            nn.Conv2d(3, 64, 3, stride=2, padding=1), nn.GroupNorm(8, 64), nn.GELU(),
            nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.GroupNorm(16, 128), nn.GELU(),
            nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.GroupNorm(32, 256), nn.GELU(),
            nn.Conv2d(256, 256, 3, stride=2, padding=1), nn.GroupNorm(32, 256), nn.GELU(),
            nn.Conv2d(256, 256, 3, stride=1, padding=1), nn.GroupNorm(32, 256), nn.GELU(),
        )
        self.pos_emb = nn.Parameter(torch.randn(1, n_img_tokens, 256) * 0.02)
        self.projector = nn.Sequential(nn.Linear(256, d_model * 2), nn.GELU(), nn.Linear(d_model * 2, d_model))

    def forward(self, images):
        feat = self.backbone(images).flatten(2).transpose(1, 2) + self.pos_emb
        return self.projector(feat)


class MicroOpsVLM(nn.Module):
    def __init__(self, cfg: dict):
        super().__init__()
        self.cfg = cfg
        vocab_size = cfg.get("vocab_size", 288)
        self.tok_emb = nn.Embedding(vocab_size, cfg["d_model"])
        self.vision = VisionPatchEncoder(cfg["d_model"], cfg["n_img_tokens"])
        self.blocks = nn.ModuleList([
            TransformerBlock(cfg["d_model"], cfg["n_heads"], cfg["d_ff"], cfg.get("dropout", 0.0))
            for _ in range(cfg["n_layers"])
        ])
        self.norm_f = RMSNorm(cfg["d_model"])
        self.lm_head = nn.Linear(cfg["d_model"], vocab_size, bias=False)
        self.lm_head.weight = self.tok_emb.weight
        cos, sin = build_rope_cache(cfg["context_window"], cfg["d_model"] // cfg["n_heads"])
        self.register_buffer("rope_cos", cos, persistent=False)
        self.register_buffer("rope_sin", sin, persistent=False)

    def forward(self, input_ids, images=None):
        x = self.tok_emb(input_ids)
        if images is not None:
            is_img = (input_ids == 10)
            if is_img.any():
                vis = self.vision(images).to(x.dtype)
                img_pos = (is_img.cumsum(dim=1) - 1).clamp(min=0, max=self.cfg["n_img_tokens"] - 1)
                gathered = torch.gather(vis, 1, img_pos.unsqueeze(-1).expand(-1, -1, x.size(-1)))
                x = torch.where(is_img.unsqueeze(-1), gathered, x)
        for blk in self.blocks:
            x = blk(x, self.rope_cos, self.rope_sin)
        return self.lm_head(self.norm_f(x))

    @torch.no_grad()
    def generate_turn(self, prompt_ids, image=None, max_new_tokens=220, temperature=0.0):
        self.eval()
        device = next(self.parameters()).device
        tok = ByteAgentTokenizer()
        stop_ids = {tok.end_tool_call_id, tok.end_assistant_id, tok.eos_id}
        idx = torch.tensor([prompt_ids], dtype=torch.long, device=device)
        img_b = image.unsqueeze(0).to(device) if image is not None else None
        out = []
        for _ in range(min(max_new_tokens, self.cfg["context_window"] - idx.size(1))):
            logits = self(idx, images=img_b)[0, -1, :]
            if temperature <= 0.0:
                nxt = int(torch.argmax(logits).item())
            else:
                nxt = int(torch.multinomial(F.softmax(logits / temperature, dim=-1), 1).item())
            out.append(nxt)
            idx = torch.cat([idx, torch.tensor([[nxt]], dtype=torch.long, device=device)], dim=1)
            if nxt in stop_ids:
                break
        return out


def from_pretrained_hf(repo_id: str = "Newone0/MicroOps-VLM", device: str = "cpu"):
    cfg_path = hf_hub_download(repo_id=repo_id, filename="config.json")
    weights_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors")
    with open(cfg_path) as f:
        cfg = json.load(f)
    model = MicroOpsVLM(cfg)
    load_model(model, weights_path)
    return model.to(device).eval(), ByteAgentTokenizer(), cfg