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
 
 
 
 
 
 
 
 
 
 
 
 
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# coding=utf-8
# Copyright 2025 Simin Huo and Ning Li. Iwin Transformer.
# SPDX-License-Identifier: MIT
"""
Hugging Face wrapper for Iwin Transformer (https://arxiv.org/abs/2507.18405).

Module names match the published Hub `model.safetensors` files
(`patch_embed`, `layers`, `norm`, `head`, `dwconv.depthwise`), so existing
checkpoints load with `from_pretrained` without key conversion.
"""

from __future__ import annotations

import os
from typing import Optional, Union

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import trunc_normal_
from transformers import PreTrainedModel
from transformers.modeling_outputs import (
    BaseModelOutputWithPooling,
    ImageClassifierOutput,
)

try:
    from .configuration_iwin import IwinConfig
except ImportError:
    from configuration_iwin import IwinConfig


def _to_2tuple(value):
    if isinstance(value, (list, tuple)):
        return tuple(value)
    return (value, value)


def drop_path(x, drop_prob: float = 0.0, training: bool = False):
    if drop_prob == 0.0 or not training:
        return x
    keep_prob = 1.0 - drop_prob
    shape = (x.shape[0],) + (1,) * (x.ndim - 1)
    random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
    if keep_prob > 0.0:
        random_tensor.div_(keep_prob)
    return x * random_tensor


class DropPath(nn.Module):
    def __init__(self, drop_prob: float = 0.0):
        super().__init__()
        self.drop_prob = drop_prob

    def forward(self, x):
        return drop_path(x, self.drop_prob, self.training)


class Mlp(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, drop=0.0):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = nn.GELU()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x


def window_partition(x, window_size: int):
    batch, height, width, channels = x.shape
    x = x.view(
        batch,
        height // window_size,
        window_size,
        width // window_size,
        window_size,
        channels,
    )
    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, channels)
    return windows


def window_reverse(windows, window_size: int, height: int, width: int):
    batch = int(windows.shape[0] / (height * width / window_size / window_size))
    x = windows.view(
        batch,
        height // window_size,
        width // window_size,
        window_size,
        window_size,
        -1,
    )
    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(batch, height, width, -1)
    return x


def rearrange(x, height_group, width_group):
    batch, height, width, channels = x.shape
    x = x.reshape(batch, -1, height_group, width, channels).transpose(1, 2)
    x = x.reshape(batch, -1, width, channels)
    x = x.reshape(batch, height, -1, width_group, channels).transpose(2, 3)
    x = x.reshape(batch, height, -1, channels)
    return x


def restore(x, height_group, width_group):
    batch, height, width, channels = x.shape
    x = x.reshape(batch, height, width_group, -1, channels).transpose(2, 3)
    x = x.reshape(batch, height, -1, channels)
    x = x.reshape(batch, height_group, -1, width, channels).transpose(1, 2)
    x = x.reshape(batch, -1, width, channels)
    return x


def _window_attention(qkv_unpermuted, scale, dropout_p, training):
    """qkv_unpermuted: (B, N, 3, heads, head_dim)."""
    impl = os.environ.get("ATTN_IMPL", "sdpa")
    if impl == "flash_attn":
        try:
            from flash_attn import flash_attn_qkvpacked_func

            return flash_attn_qkvpacked_func(
                qkv_unpermuted,
                dropout_p=dropout_p if training else 0.0,
                softmax_scale=scale,
            ).reshape(qkv_unpermuted.shape[0], qkv_unpermuted.shape[1], -1)
        except Exception:
            impl = "sdpa"

    query, key, value = qkv_unpermuted.permute(2, 0, 3, 1, 4).unbind(0)
    if impl == "sdpa" and hasattr(F, "scaled_dot_product_attention"):
        try:
            out = F.scaled_dot_product_attention(
                query, key, value, dropout_p=dropout_p if training else 0.0, scale=scale
            )
        except TypeError:
            out = F.scaled_dot_product_attention(
                query, key, value, dropout_p=dropout_p if training else 0.0
            )
        return out.transpose(1, 2).reshape(query.shape[0], query.shape[2], -1)

    query = query * scale
    attn = query @ key.transpose(-2, -1)
    attn = attn.softmax(dim=-1)
    if training and dropout_p > 0.0:
        attn = F.dropout(attn, p=dropout_p)
    out = attn @ value
    return out.transpose(1, 2).reshape(query.shape[0], query.shape[2], -1)


class WindowAttention(nn.Module):
    def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0.0, proj_drop=0.0):
        super().__init__()
        self.dim = dim
        self.window_size = window_size
        self.num_heads = num_heads
        head_dim = dim // num_heads
        self.scale = head_dim ** -0.5
        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x):
        batch, tokens, channels = x.shape
        qkv = self.qkv(x).reshape(batch, tokens, 3, self.num_heads, channels // self.num_heads)
        x = _window_attention(qkv, self.scale, self.attn_drop.p, self.training)
        x = self.proj(x)
        x = self.proj_drop(x)
        return x


class DepthwiseConv2d(nn.Module):
    def __init__(self, dim, kernel_size=3, stride=1, padding=1, dilation=1):
        super().__init__()
        self.depthwise = nn.Conv2d(
            dim, dim, kernel_size, stride, padding, dilation, groups=dim
        )

    def forward(self, x):
        return self.depthwise(x)


class IwinTransformerBlock(nn.Module):
    def __init__(
        self,
        dim,
        input_resolution,
        num_heads,
        window_size=7,
        mlp_ratio=4.0,
        qkv_bias=True,
        drop=0.0,
        attn_drop=0.0,
        drop_path_rate=0.0,
    ):
        super().__init__()
        self.dim = dim
        self.input_resolution = input_resolution
        self.num_heads = num_heads
        self.window_size = window_size
        self.mlp_ratio = mlp_ratio
        if min(self.input_resolution) <= self.window_size:
            self.window_size = min(self.input_resolution)

        self.norm1 = nn.LayerNorm(dim)
        self.attn = WindowAttention(
            dim,
            window_size=_to_2tuple(self.window_size),
            num_heads=num_heads,
            qkv_bias=qkv_bias,
            attn_drop=attn_drop,
            proj_drop=drop,
        )
        self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
        self.norm2 = nn.LayerNorm(dim)
        mlp_hidden_dim = int(dim * mlp_ratio)
        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, drop=drop)
        if max(self.input_resolution) / self.window_size <= 1:
            self.dwconv = None
        else:
            self.dwconv = DepthwiseConv2d(dim, kernel_size=3, padding=1)

    def forward(self, x):
        height, width = self.input_resolution
        batch, length, channels = x.shape
        if length != height * width:
            raise ValueError(
                f"Input feature has wrong size: expected {height * width} tokens, got {length}."
            )

        shortcut = x
        x = self.norm1(x)
        x = x.view(batch, height, width, channels)

        x_conv = None
        if self.dwconv is not None:
            x_conv = self.dwconv(x.permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1)

        x = rearrange(x, height // self.window_size, width // self.window_size)
        x_windows = window_partition(x, self.window_size)
        x_windows = x_windows.view(-1, self.window_size * self.window_size, channels)
        attn_windows = self.attn(x_windows)
        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, channels)
        x = window_reverse(attn_windows, self.window_size, height, width)
        x = restore(x, height // self.window_size, width // self.window_size)
        if x_conv is not None:
            x = x + x_conv
        x = x.view(batch, height * width, channels)
        x = shortcut + self.drop_path(x)
        x = x + self.drop_path(self.mlp(self.norm2(x)))
        return x


class Downsample2x(nn.Module):
    def __init__(self, input_resolution, dim):
        super().__init__()
        self.input_resolution = input_resolution
        self.dim = dim
        self.norm = nn.LayerNorm(dim)
        self.conv = nn.Conv2d(dim, 2 * dim, kernel_size=3, stride=2, padding=0)

    def forward(self, x):
        height, width = self.input_resolution
        batch, length, channels = x.shape
        if length != height * width:
            raise ValueError(
                f"Input feature has wrong size: expected {height * width} tokens, got {length}."
            )
        x = self.norm(x)
        x = x.view(batch, height, width, channels).permute(0, 3, 1, 2)
        x = self.conv(F.pad(x, pad=(0, 1, 0, 1), mode="constant", value=0))
        return x.flatten(2).transpose(1, 2)


class BasicLayer(nn.Module):
    def __init__(
        self,
        dim,
        input_resolution,
        depth,
        num_heads,
        window_size,
        mlp_ratio=4.0,
        qkv_bias=True,
        drop=0.0,
        attn_drop=0.0,
        drop_path=0.0,
        downsample=None,
        use_checkpoint=False,
    ):
        super().__init__()
        self.dim = dim
        self.input_resolution = input_resolution
        self.depth = depth
        self.use_checkpoint = use_checkpoint
        if not isinstance(drop_path, list):
            drop_path = [drop_path] * depth
        self.blocks = nn.ModuleList(
            [
                IwinTransformerBlock(
                    dim=dim,
                    input_resolution=input_resolution,
                    num_heads=num_heads,
                    window_size=window_size,
                    mlp_ratio=mlp_ratio,
                    qkv_bias=qkv_bias,
                    drop=drop,
                    attn_drop=attn_drop,
                    drop_path_rate=drop_path[i],
                )
                for i in range(depth)
            ]
        )
        self.downsample = downsample(input_resolution, dim=dim) if downsample is not None else None

    def forward(self, x):
        for block in self.blocks:
            if self.use_checkpoint and x.requires_grad:
                try:
                    x = torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False)
                except TypeError:
                    x = torch.utils.checkpoint.checkpoint(block, x)
            else:
                x = block(x)
        if self.downsample is not None:
            x = self.downsample(x)
        return x


class PatchEmbed(nn.Module):
    def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
        super().__init__()
        img_size = _to_2tuple(img_size)
        patch_size = _to_2tuple(patch_size)
        self.img_size = img_size
        self.patch_size = patch_size
        self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
        self.num_patches = self.grid_size[0] * self.grid_size[1]
        self.in_chans = in_chans
        self.embed_dim = embed_dim
        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
        self.norm = norm_layer(embed_dim) if norm_layer is not None else nn.Identity()

    def forward(self, x):
        _, _, height, width = x.shape
        if (height, width) != self.img_size:
            raise ValueError(
                f"Input image size ({height}*{width}) doesn't match model "
                f"({self.img_size[0]}*{self.img_size[1]})."
            )
        x = self.proj(x)
        x = x.flatten(2).transpose(1, 2)
        x = self.norm(x)
        return x


class IwinPreTrainedModel(PreTrainedModel):
    config_class = IwinConfig
    base_model_prefix = ""
    main_input_name = "pixel_values"
    supports_gradient_checkpointing = True
    _no_split_modules = ["IwinTransformerBlock"]

    def _init_weights(self, module):
        if isinstance(module, (nn.Linear, nn.Conv2d)):
            trunc_normal_(module.weight, std=self.config.initializer_range)
            if module.bias is not None:
                nn.init.zeros_(module.bias)
        elif isinstance(module, nn.LayerNorm):
            nn.init.zeros_(module.bias)
            nn.init.ones_(module.weight)


def _build_backbone(module, config, add_head: bool):
    image_size = _to_2tuple(config.image_size)
    patch_size = _to_2tuple(config.patch_size)
    embed_dim = config.embed_dim
    depths = list(config.depths)
    num_heads = list(config.num_heads)
    num_layers = len(depths)
    module.num_classes = config.num_labels
    module.num_layers = num_layers
    module.embed_dim = embed_dim
    module.ape = bool(config.use_absolute_embeddings)
    module.patch_norm = bool(config.patch_norm)
    module.num_features = int(embed_dim * 2 ** (num_layers - 1))
    module.mlp_ratio = config.mlp_ratio

    module.patch_embed = PatchEmbed(
        img_size=image_size,
        patch_size=patch_size,
        in_chans=config.num_channels,
        embed_dim=embed_dim,
        norm_layer=nn.LayerNorm if module.patch_norm else None,
    )
    num_patches = module.patch_embed.num_patches
    module.patch_grid = module.patch_embed.grid_size
    if module.ape:
        module.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
        trunc_normal_(module.absolute_pos_embed, std=config.initializer_range)
    else:
        module.absolute_pos_embed = None
    module.pos_drop = nn.Dropout(p=config.hidden_dropout_prob)

    dpr = torch.linspace(0, config.drop_path_rate, sum(depths)).tolist()
    layers = []
    for i_layer in range(num_layers):
        layers.append(
            BasicLayer(
                dim=int(embed_dim * 2**i_layer),
                input_resolution=(
                    module.patch_grid[0] // (2**i_layer),
                    module.patch_grid[1] // (2**i_layer),
                ),
                depth=depths[i_layer],
                num_heads=num_heads[i_layer],
                window_size=config.window_size,
                mlp_ratio=config.mlp_ratio,
                qkv_bias=config.qkv_bias,
                drop=config.hidden_dropout_prob,
                attn_drop=config.attention_probs_dropout_prob,
                drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
                downsample=Downsample2x if i_layer < num_layers - 1 else None,
            )
        )
    module.layers = nn.Sequential(*layers)
    module.norm = nn.LayerNorm(module.num_features, eps=config.layer_norm_eps)
    module.avgpool = nn.AdaptiveAvgPool1d(1)
    if add_head:
        module.head = (
            nn.Linear(module.num_features, config.num_labels)
            if config.num_labels > 0
            else nn.Identity()
        )


def _encode(module, pixel_values):
    x = module.patch_embed(pixel_values)
    if module.absolute_pos_embed is not None:
        x = x + module.absolute_pos_embed
    x = module.pos_drop(x)
    x = module.layers(x)
    x = module.norm(x)
    return x


def _pool(module, sequence):
    return torch.flatten(module.avgpool(sequence.transpose(1, 2)), 1)


class IwinModel(IwinPreTrainedModel):
    _keys_to_ignore_on_load_unexpected = [r"^head\."]

    def __init__(self, config: IwinConfig):
        super().__init__(config)
        _build_backbone(self, config, add_head=False)
        self.post_init()

    def forward(
        self,
        pixel_values: Optional[torch.FloatTensor] = None,
        return_dict: Optional[bool] = None,
        **kwargs,
    ) -> Union[tuple, BaseModelOutputWithPooling]:
        if pixel_values is None:
            raise ValueError("`pixel_values` must be provided.")
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
        sequence = _encode(self, pixel_values)
        pooled = _pool(self, sequence)
        if not return_dict:
            return (sequence, pooled)
        return BaseModelOutputWithPooling(last_hidden_state=sequence, pooler_output=pooled)


class IwinForImageClassification(IwinPreTrainedModel):
    def __init__(self, config: IwinConfig):
        super().__init__(config)
        self.num_labels = config.num_labels
        _build_backbone(self, config, add_head=True)
        self.post_init()

    def forward(
        self,
        pixel_values: Optional[torch.FloatTensor] = None,
        labels: Optional[torch.LongTensor] = None,
        return_dict: Optional[bool] = None,
        **kwargs,
    ) -> Union[tuple, ImageClassifierOutput]:
        if pixel_values is None:
            raise ValueError("`pixel_values` must be provided.")
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict
        sequence = _encode(self, pixel_values)
        pooled = _pool(self, sequence)
        logits = self.head(pooled)

        loss = None
        if labels is not None:
            if self.config.num_labels == 1:
                loss = F.mse_loss(logits.squeeze(), labels.squeeze().to(logits.dtype))
            else:
                loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

        if not return_dict:
            output = (logits, sequence)
            return ((loss,) + output) if loss is not None else output
        return ImageClassifierOutput(loss=loss, logits=logits, hidden_states=None, attentions=None)