File size: 13,670 Bytes
377e8b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""PyTorch inference implementation of NoTokenLM-ImageGen-Class-2.5.

Re-implementation of the JAX training code (`ntlm_core.py`, shipped in this repo). Parameter names and
shapes are identical to the JAX checkpoint (conv kernels stay in HWIO layout, dense kernels are
(in, out)), so `model.safetensors` is loaded as-is, without any conversion step.

Input : float tensor (N, 3, H, W), RGB, values 0..255 (normalisation happens inside the model);
        H and W must be multiples of 16 (trained at 64 and 128 px).
Output: logits over the 1000 ImageNet-1k classes.
"""
import math
import os
from typing import List, Optional, Sequence, Union

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedModel
from transformers.modeling_outputs import ImageClassifierOutput

from .configuration_ntlm_class25 import NTLMClass25Config

WEIGHTS_NAME = "model.safetensors"
_LN_EPS = 1e-6


# ------------------------------------------------------------------------------ helpers
def _trunc_normal(*shape, std=0.02):
    return nn.Parameter(torch.nn.init.trunc_normal_(torch.empty(*shape), std=std, a=-2 * std, b=2 * std))


def _zeros(*shape):
    return nn.Parameter(torch.zeros(*shape))


def _ones(*shape, value=1.0):
    return nn.Parameter(torch.full(shape, float(value)))


def _ln(x, g, b):
    """LayerNorm over the last dim, computed in fp32 (as in the JAX code)."""
    return F.layer_norm(x.float(), (x.shape[-1],), g.float(), b.float(), _LN_EPS).to(x.dtype)


def _dense(x, w, b):
    return torch.matmul(x, w.to(x.dtype)) + b.to(x.dtype)


def _conv(x, w_hwio, b, stride=1, padding=0, groups=1):
    """x: (N,H,W,C) NHWC, w: HWIO (as in JAX). Returns NHWC."""
    y = F.conv2d(x.permute(0, 3, 1, 2), w_hwio.permute(3, 2, 0, 1).to(x.dtype), b.to(x.dtype),
                 stride=stride, padding=padding, groups=groups)
    return y.permute(0, 2, 3, 1)


def _gelu(x):
    return F.gelu(x, approximate="tanh")


def _space_to_depth(x, r=4):
    n, h, w, c = x.shape
    x = x.reshape(n, h // r, r, w // r, r, c).permute(0, 1, 3, 2, 4, 5)
    return x.reshape(n, h // r, w // r, r * r * c)


# ------------------------------------------------------------------------------ blocks
class _Stem(nn.Module):
    def __init__(self, cout):
        super().__init__()
        self.conv_w, self.conv_b = _trunc_normal(3, 3, 48, cout), _zeros(cout)
        self.ln_g, self.ln_b = _ones(cout), _zeros(cout)

    def forward(self, x):
        x = _conv(_space_to_depth(x, 4), self.conv_w, self.conv_b, padding=1)
        return _ln(x, self.ln_g, self.ln_b)


class _FusedBlock(nn.Module):
    def __init__(self, c, e, ls_init):
        super().__init__()
        self.ln_g, self.ln_b = _ones(c), _zeros(c)
        self.conv_w, self.conv_b = _trunc_normal(3, 3, c, c * e), _zeros(c * e)
        self.pw_w, self.pw_b = _trunc_normal(c * e, c), _zeros(c)
        self.ls = _ones(c, value=ls_init)             # `gamma` in the JAX checkpoint

    def forward(self, x):
        y = _ln(x, self.ln_g, self.ln_b)
        y = _gelu(_conv(y, self.conv_w, self.conv_b, padding=1))
        y = _dense(y, self.pw_w, self.pw_b)
        return x + self.ls.to(x.dtype) * y


class _ConvNeXtBlock(nn.Module):
    def __init__(self, c, r, k, heads, ls_init, attn=False):
        super().__init__()
        self.heads, self.k, self.has_attn = heads, k, attn
        self.dw_w, self.dw_b = _trunc_normal(k, k, 1, c), _zeros(c)
        self.ln_g, self.ln_b = _ones(c), _zeros(c)
        self.pw1_w, self.pw1_b = _trunc_normal(c, c * r), _zeros(c * r)
        self.pw2_w, self.pw2_b = _trunc_normal(c * r, c), _zeros(c)
        self.ls = _ones(c, value=ls_init)             # `gamma`
        if attn:
            self.a_ln_g, self.a_ln_b = _ones(c), _zeros(c)
            self.qkv_w, self.qkv_b = _trunc_normal(c, 3 * c), _zeros(3 * c)
            self.proj_w, self.proj_b = _trunc_normal(c, c), _zeros(c)
            self.a_ls = _ones(c, value=ls_init)       # `a_gamma`

    def _attention(self, x):
        n, h, w, c = x.shape
        hd = c // self.heads
        y = _ln(x, self.a_ln_g, self.a_ln_b).reshape(n, h * w, c)
        qkv = _dense(y, self.qkv_w, self.qkv_b).reshape(n, h * w, 3, self.heads, hd)
        q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
        s = torch.einsum("nqhd,nkhd->nhqk", q, k) * hd ** -0.5
        a = torch.softmax(s.float(), -1).to(y.dtype)
        o = torch.einsum("nhqk,nkhd->nqhd", a, v).reshape(n, h * w, c)
        o = _dense(o, self.proj_w, self.proj_b).reshape(n, h, w, c)
        return x + self.a_ls.to(x.dtype) * o

    def forward(self, x):
        y = _conv(x, self.dw_w, self.dw_b, padding=self.k // 2, groups=x.shape[-1])
        y = _ln(y, self.ln_g, self.ln_b)
        y = _gelu(_dense(y, self.pw1_w, self.pw1_b))
        y = _dense(y, self.pw2_w, self.pw2_b)
        x = x + self.ls.to(x.dtype) * y
        return self._attention(x) if self.has_attn else x


class _Down(nn.Module):
    """Stages 1->2 and 2->3: LN + 2x2 stride-2 conv. Stage 3->4: LN + 1x1 projection (no spatial change)."""
    def __init__(self, cin, cout, conv: bool):
        super().__init__()
        self.is_conv = conv
        self.ln_g, self.ln_b = _ones(cin), _zeros(cin)
        if conv:
            self.conv_w, self.conv_b = _trunc_normal(2, 2, cin, cout), _zeros(cout)
        else:
            self.pw_w, self.pw_b = _trunc_normal(cin, cout), _zeros(cout)

    def forward(self, x):
        x = _ln(x, self.ln_g, self.ln_b)
        if self.is_conv:
            return _conv(x, self.conv_w, self.conv_b, stride=2, padding=0)
        return _dense(x, self.pw_w, self.pw_b)


class _Head(nn.Module):
    def __init__(self, c, hidden, num_classes):
        super().__init__()
        self.ln_g, self.ln_b = _ones(c), _zeros(c)
        self.pw_w, self.pw_b = _trunc_normal(c, hidden), _zeros(hidden)
        self.cls_w, self.cls_b = _trunc_normal(hidden, num_classes), _zeros(num_classes)

    def forward(self, x):
        x = _ln(x.mean((1, 2)), self.ln_g, self.ln_b)
        x = _gelu(_dense(x, self.pw_w, self.pw_b))
        return _dense(x, self.cls_w, self.cls_b)


# ------------------------------------------------------------------------------ preprocessing
ImageLike = Union[str, os.PathLike, "PIL.Image.Image", np.ndarray]


def preprocess_images(images: Union[ImageLike, Sequence[ImageLike]], resolution: int = 128) -> torch.Tensor:
    """Reproduces the training-data pipeline (the `benjamin-paine/imagenet-1k-*` repacks):
    centre-crop to a square on the short side -> Lanczos to 256 -> Lanczos to 128 -> Lanczos to `resolution`.
    Returns a float32 tensor (N, 3, resolution, resolution) with values in 0..255."""
    from PIL import Image

    if isinstance(images, (str, os.PathLike, Image.Image, np.ndarray)):
        images = [images]
    if resolution % 16 != 0:
        raise ValueError(f"resolution must be a multiple of 16 (got {resolution}).")
    out = []
    for im in images:
        if isinstance(im, (str, os.PathLike)):
            im = Image.open(im)
        elif isinstance(im, np.ndarray):
            im = Image.fromarray(im.astype(np.uint8))
        im = im.convert("RGB")
        w, h = im.size
        s = min(w, h)
        left, top = (w - s) // 2, (h - s) // 2
        im = im.crop((left, top, left + s, top + s))
        for r in (256, 128, resolution):
            if im.size != (r, r):
                im = im.resize((r, r), Image.LANCZOS)
        out.append(np.asarray(im, dtype=np.uint8))
    return torch.from_numpy(np.stack(out)).permute(0, 3, 1, 2).float().contiguous()


# ------------------------------------------------------------------------------ model
class NTLMClass25ForImageClassification(PreTrainedModel):
    config_class = NTLMClass25Config
    main_input_name = "pixel_values"
    _supports_sdpa = False

    def __init__(self, config: NTLMClass25Config):
        super().__init__(config)
        w, d, r = config.widths, config.depths, config.ratios
        self.stem = _Stem(w[0])
        self.s1 = nn.ModuleList([_FusedBlock(w[0], r[0], config.ls_init) for _ in range(d[0])])
        for i in (1, 2, 3):
            setattr(self, f"down{i}", _Down(w[i - 1], w[i], conv=(i < 3)))
            setattr(self, f"s{i + 1}", nn.ModuleList([
                _ConvNeXtBlock(w[i], r[i], config.dw_k, config.heads, config.ls_init,
                               attn=(i == 3 and j == d[i] - 1)) for j in range(d[i])]))
        self.head = _Head(w[3], config.head_dim, config.num_classes)
        self.post_init()

    def _init_weights(self, module):          # parameters are initialised in the block constructors
        pass

    # --------------------------------------------------------------- forward
    def forward(self, pixel_values: torch.Tensor, labels: Optional[torch.Tensor] = None, return_dict: Optional[bool] = None):
        if pixel_values.ndim != 4 or pixel_values.shape[1] != 3:
            raise ValueError("pixel_values must have shape (N, 3, H, W), RGB, values 0..255.")
        h, w = pixel_values.shape[-2:]
        if h % 16 or w % 16:
            raise ValueError(f"H and W must be multiples of 16 (got {h}x{w}).")
        dtype = self.stem.conv_w.dtype
        x = pixel_values.permute(0, 2, 3, 1).to(dtype)             # NHWC
        x = (x - 127.5) / 127.5
        x = self.stem(x)
        for blk in self.s1:
            x = blk(x)
        for i in (1, 2, 3):
            x = getattr(self, f"down{i}")(x)
            for blk in getattr(self, f"s{i + 1}"):
                x = blk(x)
        logits = self.head(x).float()
        loss = F.cross_entropy(logits, labels) if labels is not None else None
        if return_dict is False:
            return (loss, logits) if loss is not None else (logits,)
        return ImageClassifierOutput(loss=loss, logits=logits)

    # --------------------------------------------------------------- convenience API
    @staticmethod
    def preprocess(images, resolution: int = 128) -> torch.Tensor:
        """See `preprocess_images`: centre square crop -> Lanczos 256 -> 128 -> `resolution`; float32 (N,3,R,R), 0..255."""
        return preprocess_images(images, resolution)

    @torch.no_grad()
    def predict(self, images, top_k: int = 5, resolution: Optional[int] = None, batch_size: int = 64):
        """Classify PIL images / file paths / HxWx3 uint8 arrays.
        Returns, per image, a list of `top_k` dicts: {"id", "label", "score"} (score = softmax probability)."""
        single = isinstance(images, (str, os.PathLike, np.ndarray)) or hasattr(images, "convert")
        images = [images] if single else list(images)
        res = resolution or self.config.default_resolution
        id2label = self.config.id2label
        k = min(top_k, self.config.num_classes)
        results = []
        was_training = self.training
        self.eval()
        device = next(self.parameters()).device
        for i in range(0, len(images), batch_size):
            x = preprocess_images(images[i:i + batch_size], res).to(device)
            probs = torch.softmax(self(x).logits, -1)
            sc, ix = probs.topk(k, dim=-1)
            for s_row, i_row in zip(sc.tolist(), ix.tolist()):
                results.append([{"id": int(j), "label": id2label.get(int(j), f"LABEL_{j}"), "score": float(s)}
                                for s, j in zip(s_row, i_row)])
        self.train(was_training)
        return results[0] if single else results

    # --------------------------------------------------------------- loading
    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path, *model_args, config=None, dtype=None,
                        torch_dtype=None, **kwargs):
        """Loads `model.safetensors` exactly as exported by the JAX training notebook.

        (The JAX checkpoint names the layer-scale vectors `gamma` / `a_gamma`; `transformers` silently renames
        any key containing "gamma" while loading, which would break a standard load, so this model reads the
        file itself and maps those two names to `ls` / `a_ls`.)"""
        from safetensors.torch import load_file

        hub_kw = {k: kwargs[k] for k in ("cache_dir", "force_download", "proxies", "token", "local_files_only",
                                         "revision", "subfolder") if k in kwargs}
        if "token" not in hub_kw and kwargs.get("use_auth_token") is not None:
            hub_kw["token"] = kwargs["use_auth_token"]
        path = str(pretrained_model_name_or_path)
        if config is None:
            config = cls.config_class.from_pretrained(path, **hub_kw)
        if os.path.isdir(path):
            sub = hub_kw.get("subfolder", "")
            wfile = os.path.join(path, sub, WEIGHTS_NAME)
        elif os.path.isfile(path):
            wfile = path
        else:
            from huggingface_hub import hf_hub_download
            wfile = hf_hub_download(path, WEIGHTS_NAME, **hub_kw)

        model = cls(config)
        own = set(model.state_dict().keys())
        state = {}
        for k, v in load_file(wfile).items():
            state[k if k in own else k.replace("gamma", "ls")] = v
        missing, unexpected = model.load_state_dict(state, strict=False)
        if missing or unexpected:
            raise RuntimeError(f"Checkpoint does not match the model config. missing={missing[:5]} "
                               f"unexpected={unexpected[:5]} (config widths/depths/ratios/head_dim correct?)")
        dt = dtype or torch_dtype
        if isinstance(dt, str) and dt != "auto":
            dt = getattr(torch, dt)
        if isinstance(dt, torch.dtype):
            model = model.to(dt)
        return model.eval()