cominder commited on
Commit
d1878b8
·
verified ·
1 Parent(s): dff6024

Add Transformers remote code so from_pretrained(trust_remote_code=True) works

Browse files
Files changed (6) hide show
  1. README.md +25 -21
  2. __init__.py +4 -0
  3. config.json +7 -1
  4. configuration_iwin.py +76 -0
  5. modeling_iwin.py +516 -0
  6. preprocessor_config.json +8 -1
README.md CHANGED
@@ -1,41 +1,45 @@
1
  ---
2
  license: mit
 
 
3
  tags:
4
- - vision
5
- - image-classification
6
- - arxiv:2507.18405
7
  datasets:
8
- - imagenet-1k
9
  ---
10
 
 
11
 
12
- # Iwin Transformer (tiny-sized model, imagenet-1k, 224x224)
13
 
14
- <div style="display:flex;justify-content: left">
15
- <a href="https://arxiv.org/abs/2507.18405"><img src="https://img.shields.io/static/v1?label=Paper&message=Arxiv:Iwin&color=red&logo=arxiv"></a> &ensp;
16
- <a href="https://github.com/Cominder/Iwin-Transformer/"><img src="https://img.shields.io/static/v1?label=Repository&message=Github&color=blue&logo=github-pages"></a> &ensp;
17
- </div>
18
 
19
- ## Model Source
20
- Pre-trained Iwin Transformer models on ImageNet-1k and ImageNet-22k. For research purposes, we recommend our Github repository (https://github.com/Cominder/Iwin-Transformer), which is more suitable for both training and inference.
21
 
22
- ## Model Descprition
23
- We introduce Iwin Transformer, a novel positionembedding-free hierarchical vision transformer, which can be fine-tuned directly from low to high resolution, through the
24
- collaboration of innovative interleaved window attention and depthwise separable convolution. This approach uses attention to connect distant tokens and applies convolution to link neighboring tokens, enabling global information exchange within a
25
- single module, overcoming Swin Transformer's limitation of requiring two consecutive blocks to approximate global attention. Extensive experiments on visual benchmarks demonstrate that Iwin Transformer exhibits strong competitiveness in tasks such as image classification (87.4 top-1 accuracy on ImageNet-1K),
26
- semantic segmentation, and video action recognition. We also validate the effectiveness of the core component in Iwin as a standalone module that can seamlessly replace the self-attention module in class-conditional image generation. The concepts
27
- and methods introduced by the Iwin Transformer have the potential to inspire future research, like Iwin 3D Attention in video generation. The code and models are available at
28
- https://github.com/cominder/Iwin-Transformer.
 
 
 
29
 
30
  ## Citation
31
- ```
 
32
  @misc{huo2025iwin,
33
- title={Iwin Transformer: Hierarchical Vision Transformer using Interleaved Windows},
34
  author={Simin Huo and Ning Li},
35
  year={2025},
36
  eprint={2507.18405},
37
  archivePrefix={arXiv},
38
  primaryClass={cs.CV},
39
- url={https://arxiv.org/abs/2507.18405},
40
  }
41
  ```
 
1
  ---
2
  license: mit
3
+ library_name: transformers
4
+ pipeline_tag: image-classification
5
  tags:
6
+ - vision
7
+ - image-classification
8
+ - iwin-transformer
9
  datasets:
10
+ - imagenet-1k
11
  ---
12
 
13
+ # Iwin Transformer (tiny, ImageNet-1K, 224×224)
14
 
15
+ Position-embedding-free hierarchical vision transformer. Paper: [arXiv:2507.18405](https://arxiv.org/abs/2507.18405). All checkpoints: [Iwin Transformer collection](https://huggingface.co/collections/cominder/iwin-transformer).
16
 
17
+ ## Usage
 
 
 
18
 
19
+ ```python
20
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
21
 
22
+ ckpt = "cominder/iwin-tiny-patch4-window7-224"
23
+ processor = AutoImageProcessor.from_pretrained(ckpt)
24
+ model = AutoModelForImageClassification.from_pretrained(ckpt, trust_remote_code=True)
25
+ inputs = processor(images=image, return_tensors="pt")
26
+ print(model.config.id2label[model(**inputs).logits.argmax(-1).item()])
27
+ ```
28
+
29
+ `trust_remote_code=True` is required because Iwin is not in the Transformers core library yet. Training and evaluation code: [Cominder/Iwin-Transformer](https://github.com/Cominder/Iwin-Transformer).
30
+
31
+ Reported ImageNet-1K top-1: **82.0**. The snippet resizes directly to 224.
32
 
33
  ## Citation
34
+
35
+ ```bibtex
36
  @misc{huo2025iwin,
37
+ title={Iwin Transformer: Hierarchical Vision Transformer using Interleaved Windows},
38
  author={Simin Huo and Ning Li},
39
  year={2025},
40
  eprint={2507.18405},
41
  archivePrefix={arXiv},
42
  primaryClass={cs.CV},
43
+ url={https://arxiv.org/abs/2507.18405},
44
  }
45
  ```
__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .configuration_iwin import IwinConfig
2
+ from .modeling_iwin import IwinForImageClassification, IwinModel
3
+
4
+ __all__ = ["IwinConfig", "IwinModel", "IwinForImageClassification"]
config.json CHANGED
@@ -2034,5 +2034,11 @@
2034
  "yurt": 915,
2035
  "zebra": 340,
2036
  "zucchini, courgette": 939
2037
- }
 
 
 
 
 
 
2038
  }
 
2034
  "yurt": 915,
2035
  "zebra": 340,
2036
  "zucchini, courgette": 939
2037
+ },
2038
+ "auto_map": {
2039
+ "AutoConfig": "configuration_iwin.IwinConfig",
2040
+ "AutoModel": "modeling_iwin.IwinModel",
2041
+ "AutoModelForImageClassification": "modeling_iwin.IwinForImageClassification"
2042
+ },
2043
+ "patch_norm": true
2044
  }
configuration_iwin.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Simin Huo and Ning Li. Iwin Transformer.
3
+ # SPDX-License-Identifier: MIT
4
+ """Hugging Face configuration for Iwin Transformer."""
5
+
6
+ from transformers import PretrainedConfig
7
+
8
+
9
+ class IwinConfig(PretrainedConfig):
10
+ r"""
11
+ Configuration for [`IwinModel`] / [`IwinForImageClassification`].
12
+
13
+ Matches the Hub checkpoints under `cominder/iwin-*`. The published
14
+ `config.json` used `path_norm` for patch-embedding LayerNorm; that alias is
15
+ accepted and written back as `patch_norm`.
16
+ """
17
+
18
+ model_type = "iwin"
19
+ attribute_map = {
20
+ "num_attention_heads": "num_heads",
21
+ "num_hidden_layers": "num_layers",
22
+ }
23
+
24
+ def __init__(
25
+ self,
26
+ image_size=224,
27
+ patch_size=4,
28
+ num_channels=3,
29
+ embed_dim=96,
30
+ depths=None,
31
+ num_heads=None,
32
+ window_size=7,
33
+ mlp_ratio=4.0,
34
+ qkv_bias=True,
35
+ hidden_dropout_prob=0.0,
36
+ attention_probs_dropout_prob=0.0,
37
+ drop_path_rate=0.1,
38
+ hidden_act="gelu",
39
+ use_absolute_embeddings=False,
40
+ initializer_range=0.02,
41
+ layer_norm_eps=1e-5,
42
+ patch_norm=None,
43
+ path_norm=None,
44
+ encoder_stride=32,
45
+ **kwargs,
46
+ ):
47
+ super().__init__(**kwargs)
48
+
49
+ if depths is None:
50
+ depths = [2, 2, 6, 2]
51
+ if num_heads is None:
52
+ num_heads = [3, 6, 12, 24]
53
+ if patch_norm is None:
54
+ patch_norm = True if path_norm is None else bool(path_norm)
55
+
56
+ self.image_size = image_size
57
+ self.patch_size = patch_size
58
+ self.num_channels = num_channels
59
+ self.embed_dim = embed_dim
60
+ self.depths = list(depths)
61
+ self.num_layers = len(self.depths)
62
+ self.num_heads = list(num_heads)
63
+ self.window_size = window_size
64
+ self.mlp_ratio = mlp_ratio
65
+ self.qkv_bias = qkv_bias
66
+ self.hidden_dropout_prob = hidden_dropout_prob
67
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
68
+ self.drop_path_rate = drop_path_rate
69
+ self.hidden_act = hidden_act
70
+ self.use_absolute_embeddings = use_absolute_embeddings
71
+ self.initializer_range = initializer_range
72
+ self.layer_norm_eps = layer_norm_eps
73
+ self.patch_norm = bool(patch_norm)
74
+ self.path_norm = self.patch_norm
75
+ self.encoder_stride = encoder_stride
76
+ self.hidden_size = int(embed_dim * 2 ** (len(self.depths) - 1))
modeling_iwin.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 Simin Huo and Ning Li. Iwin Transformer.
3
+ # SPDX-License-Identifier: MIT
4
+ """
5
+ Hugging Face wrapper for Iwin Transformer (https://arxiv.org/abs/2507.18405).
6
+
7
+ Module names match the published Hub `model.safetensors` files
8
+ (`patch_embed`, `layers`, `norm`, `head`, `dwconv.depthwise`), so existing
9
+ checkpoints load with `from_pretrained` without key conversion.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from typing import Optional, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ from torch.nn.init import trunc_normal_
21
+ from transformers import PreTrainedModel
22
+ from transformers.modeling_outputs import (
23
+ BaseModelOutputWithPooling,
24
+ ImageClassifierOutput,
25
+ )
26
+
27
+ try:
28
+ from .configuration_iwin import IwinConfig
29
+ except ImportError:
30
+ from configuration_iwin import IwinConfig
31
+
32
+
33
+ def _to_2tuple(value):
34
+ if isinstance(value, (list, tuple)):
35
+ return tuple(value)
36
+ return (value, value)
37
+
38
+
39
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
40
+ if drop_prob == 0.0 or not training:
41
+ return x
42
+ keep_prob = 1.0 - drop_prob
43
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
44
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
45
+ if keep_prob > 0.0:
46
+ random_tensor.div_(keep_prob)
47
+ return x * random_tensor
48
+
49
+
50
+ class DropPath(nn.Module):
51
+ def __init__(self, drop_prob: float = 0.0):
52
+ super().__init__()
53
+ self.drop_prob = drop_prob
54
+
55
+ def forward(self, x):
56
+ return drop_path(x, self.drop_prob, self.training)
57
+
58
+
59
+ class Mlp(nn.Module):
60
+ def __init__(self, in_features, hidden_features=None, out_features=None, drop=0.0):
61
+ super().__init__()
62
+ out_features = out_features or in_features
63
+ hidden_features = hidden_features or in_features
64
+ self.fc1 = nn.Linear(in_features, hidden_features)
65
+ self.act = nn.GELU()
66
+ self.fc2 = nn.Linear(hidden_features, out_features)
67
+ self.drop = nn.Dropout(drop)
68
+
69
+ def forward(self, x):
70
+ x = self.fc1(x)
71
+ x = self.act(x)
72
+ x = self.drop(x)
73
+ x = self.fc2(x)
74
+ x = self.drop(x)
75
+ return x
76
+
77
+
78
+ def window_partition(x, window_size: int):
79
+ batch, height, width, channels = x.shape
80
+ x = x.view(
81
+ batch,
82
+ height // window_size,
83
+ window_size,
84
+ width // window_size,
85
+ window_size,
86
+ channels,
87
+ )
88
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, channels)
89
+ return windows
90
+
91
+
92
+ def window_reverse(windows, window_size: int, height: int, width: int):
93
+ batch = int(windows.shape[0] / (height * width / window_size / window_size))
94
+ x = windows.view(
95
+ batch,
96
+ height // window_size,
97
+ width // window_size,
98
+ window_size,
99
+ window_size,
100
+ -1,
101
+ )
102
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(batch, height, width, -1)
103
+ return x
104
+
105
+
106
+ def rearrange(x, height_group, width_group):
107
+ batch, height, width, channels = x.shape
108
+ x = x.reshape(batch, -1, height_group, width, channels).transpose(1, 2)
109
+ x = x.reshape(batch, -1, width, channels)
110
+ x = x.reshape(batch, height, -1, width_group, channels).transpose(2, 3)
111
+ x = x.reshape(batch, height, -1, channels)
112
+ return x
113
+
114
+
115
+ def restore(x, height_group, width_group):
116
+ batch, height, width, channels = x.shape
117
+ x = x.reshape(batch, height, width_group, -1, channels).transpose(2, 3)
118
+ x = x.reshape(batch, height, -1, channels)
119
+ x = x.reshape(batch, height_group, -1, width, channels).transpose(1, 2)
120
+ x = x.reshape(batch, -1, width, channels)
121
+ return x
122
+
123
+
124
+ def _window_attention(qkv_unpermuted, scale, dropout_p, training):
125
+ """qkv_unpermuted: (B, N, 3, heads, head_dim)."""
126
+ impl = os.environ.get("ATTN_IMPL", "sdpa")
127
+ if impl == "flash_attn":
128
+ try:
129
+ from flash_attn import flash_attn_qkvpacked_func
130
+
131
+ return flash_attn_qkvpacked_func(
132
+ qkv_unpermuted,
133
+ dropout_p=dropout_p if training else 0.0,
134
+ softmax_scale=scale,
135
+ ).reshape(qkv_unpermuted.shape[0], qkv_unpermuted.shape[1], -1)
136
+ except Exception:
137
+ impl = "sdpa"
138
+
139
+ query, key, value = qkv_unpermuted.permute(2, 0, 3, 1, 4).unbind(0)
140
+ if impl == "sdpa" and hasattr(F, "scaled_dot_product_attention"):
141
+ try:
142
+ out = F.scaled_dot_product_attention(
143
+ query, key, value, dropout_p=dropout_p if training else 0.0, scale=scale
144
+ )
145
+ except TypeError:
146
+ out = F.scaled_dot_product_attention(
147
+ query, key, value, dropout_p=dropout_p if training else 0.0
148
+ )
149
+ return out.transpose(1, 2).reshape(query.shape[0], query.shape[2], -1)
150
+
151
+ query = query * scale
152
+ attn = query @ key.transpose(-2, -1)
153
+ attn = attn.softmax(dim=-1)
154
+ if training and dropout_p > 0.0:
155
+ attn = F.dropout(attn, p=dropout_p)
156
+ out = attn @ value
157
+ return out.transpose(1, 2).reshape(query.shape[0], query.shape[2], -1)
158
+
159
+
160
+ class WindowAttention(nn.Module):
161
+ def __init__(self, dim, window_size, num_heads, qkv_bias=True, attn_drop=0.0, proj_drop=0.0):
162
+ super().__init__()
163
+ self.dim = dim
164
+ self.window_size = window_size
165
+ self.num_heads = num_heads
166
+ head_dim = dim // num_heads
167
+ self.scale = head_dim ** -0.5
168
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
169
+ self.attn_drop = nn.Dropout(attn_drop)
170
+ self.proj = nn.Linear(dim, dim)
171
+ self.proj_drop = nn.Dropout(proj_drop)
172
+
173
+ def forward(self, x):
174
+ batch, tokens, channels = x.shape
175
+ qkv = self.qkv(x).reshape(batch, tokens, 3, self.num_heads, channels // self.num_heads)
176
+ x = _window_attention(qkv, self.scale, self.attn_drop.p, self.training)
177
+ x = self.proj(x)
178
+ x = self.proj_drop(x)
179
+ return x
180
+
181
+
182
+ class DepthwiseConv2d(nn.Module):
183
+ def __init__(self, dim, kernel_size=3, stride=1, padding=1, dilation=1):
184
+ super().__init__()
185
+ self.depthwise = nn.Conv2d(
186
+ dim, dim, kernel_size, stride, padding, dilation, groups=dim
187
+ )
188
+
189
+ def forward(self, x):
190
+ return self.depthwise(x)
191
+
192
+
193
+ class IwinTransformerBlock(nn.Module):
194
+ def __init__(
195
+ self,
196
+ dim,
197
+ input_resolution,
198
+ num_heads,
199
+ window_size=7,
200
+ mlp_ratio=4.0,
201
+ qkv_bias=True,
202
+ drop=0.0,
203
+ attn_drop=0.0,
204
+ drop_path_rate=0.0,
205
+ ):
206
+ super().__init__()
207
+ self.dim = dim
208
+ self.input_resolution = input_resolution
209
+ self.num_heads = num_heads
210
+ self.window_size = window_size
211
+ self.mlp_ratio = mlp_ratio
212
+ if min(self.input_resolution) <= self.window_size:
213
+ self.window_size = min(self.input_resolution)
214
+
215
+ self.norm1 = nn.LayerNorm(dim)
216
+ self.attn = WindowAttention(
217
+ dim,
218
+ window_size=_to_2tuple(self.window_size),
219
+ num_heads=num_heads,
220
+ qkv_bias=qkv_bias,
221
+ attn_drop=attn_drop,
222
+ proj_drop=drop,
223
+ )
224
+ self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
225
+ self.norm2 = nn.LayerNorm(dim)
226
+ mlp_hidden_dim = int(dim * mlp_ratio)
227
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, drop=drop)
228
+ if max(self.input_resolution) / self.window_size <= 1:
229
+ self.dwconv = None
230
+ else:
231
+ self.dwconv = DepthwiseConv2d(dim, kernel_size=3, padding=1)
232
+
233
+ def forward(self, x):
234
+ height, width = self.input_resolution
235
+ batch, length, channels = x.shape
236
+ if length != height * width:
237
+ raise ValueError(
238
+ f"Input feature has wrong size: expected {height * width} tokens, got {length}."
239
+ )
240
+
241
+ shortcut = x
242
+ x = self.norm1(x)
243
+ x = x.view(batch, height, width, channels)
244
+
245
+ x_conv = None
246
+ if self.dwconv is not None:
247
+ x_conv = self.dwconv(x.permute(0, 3, 1, 2).contiguous()).permute(0, 2, 3, 1)
248
+
249
+ x = rearrange(x, height // self.window_size, width // self.window_size)
250
+ x_windows = window_partition(x, self.window_size)
251
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, channels)
252
+ attn_windows = self.attn(x_windows)
253
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, channels)
254
+ x = window_reverse(attn_windows, self.window_size, height, width)
255
+ x = restore(x, height // self.window_size, width // self.window_size)
256
+ if x_conv is not None:
257
+ x = x + x_conv
258
+ x = x.view(batch, height * width, channels)
259
+ x = shortcut + self.drop_path(x)
260
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
261
+ return x
262
+
263
+
264
+ class Downsample2x(nn.Module):
265
+ def __init__(self, input_resolution, dim):
266
+ super().__init__()
267
+ self.input_resolution = input_resolution
268
+ self.dim = dim
269
+ self.norm = nn.LayerNorm(dim)
270
+ self.conv = nn.Conv2d(dim, 2 * dim, kernel_size=3, stride=2, padding=0)
271
+
272
+ def forward(self, x):
273
+ height, width = self.input_resolution
274
+ batch, length, channels = x.shape
275
+ if length != height * width:
276
+ raise ValueError(
277
+ f"Input feature has wrong size: expected {height * width} tokens, got {length}."
278
+ )
279
+ x = self.norm(x)
280
+ x = x.view(batch, height, width, channels).permute(0, 3, 1, 2)
281
+ x = self.conv(F.pad(x, pad=(0, 1, 0, 1), mode="constant", value=0))
282
+ return x.flatten(2).transpose(1, 2)
283
+
284
+
285
+ class BasicLayer(nn.Module):
286
+ def __init__(
287
+ self,
288
+ dim,
289
+ input_resolution,
290
+ depth,
291
+ num_heads,
292
+ window_size,
293
+ mlp_ratio=4.0,
294
+ qkv_bias=True,
295
+ drop=0.0,
296
+ attn_drop=0.0,
297
+ drop_path=0.0,
298
+ downsample=None,
299
+ use_checkpoint=False,
300
+ ):
301
+ super().__init__()
302
+ self.dim = dim
303
+ self.input_resolution = input_resolution
304
+ self.depth = depth
305
+ self.use_checkpoint = use_checkpoint
306
+ if not isinstance(drop_path, list):
307
+ drop_path = [drop_path] * depth
308
+ self.blocks = nn.ModuleList(
309
+ [
310
+ IwinTransformerBlock(
311
+ dim=dim,
312
+ input_resolution=input_resolution,
313
+ num_heads=num_heads,
314
+ window_size=window_size,
315
+ mlp_ratio=mlp_ratio,
316
+ qkv_bias=qkv_bias,
317
+ drop=drop,
318
+ attn_drop=attn_drop,
319
+ drop_path_rate=drop_path[i],
320
+ )
321
+ for i in range(depth)
322
+ ]
323
+ )
324
+ self.downsample = downsample(input_resolution, dim=dim) if downsample is not None else None
325
+
326
+ def forward(self, x):
327
+ for block in self.blocks:
328
+ if self.use_checkpoint and x.requires_grad:
329
+ try:
330
+ x = torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False)
331
+ except TypeError:
332
+ x = torch.utils.checkpoint.checkpoint(block, x)
333
+ else:
334
+ x = block(x)
335
+ if self.downsample is not None:
336
+ x = self.downsample(x)
337
+ return x
338
+
339
+
340
+ class PatchEmbed(nn.Module):
341
+ def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
342
+ super().__init__()
343
+ img_size = _to_2tuple(img_size)
344
+ patch_size = _to_2tuple(patch_size)
345
+ self.img_size = img_size
346
+ self.patch_size = patch_size
347
+ self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
348
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
349
+ self.in_chans = in_chans
350
+ self.embed_dim = embed_dim
351
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
352
+ self.norm = norm_layer(embed_dim) if norm_layer is not None else nn.Identity()
353
+
354
+ def forward(self, x):
355
+ _, _, height, width = x.shape
356
+ if (height, width) != self.img_size:
357
+ raise ValueError(
358
+ f"Input image size ({height}*{width}) doesn't match model "
359
+ f"({self.img_size[0]}*{self.img_size[1]})."
360
+ )
361
+ x = self.proj(x)
362
+ x = x.flatten(2).transpose(1, 2)
363
+ x = self.norm(x)
364
+ return x
365
+
366
+
367
+ class IwinPreTrainedModel(PreTrainedModel):
368
+ config_class = IwinConfig
369
+ base_model_prefix = ""
370
+ main_input_name = "pixel_values"
371
+ supports_gradient_checkpointing = True
372
+ _no_split_modules = ["IwinTransformerBlock"]
373
+
374
+ def _init_weights(self, module):
375
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
376
+ trunc_normal_(module.weight, std=self.config.initializer_range)
377
+ if module.bias is not None:
378
+ nn.init.zeros_(module.bias)
379
+ elif isinstance(module, nn.LayerNorm):
380
+ nn.init.zeros_(module.bias)
381
+ nn.init.ones_(module.weight)
382
+
383
+
384
+ def _build_backbone(module, config, add_head: bool):
385
+ image_size = _to_2tuple(config.image_size)
386
+ patch_size = _to_2tuple(config.patch_size)
387
+ embed_dim = config.embed_dim
388
+ depths = list(config.depths)
389
+ num_heads = list(config.num_heads)
390
+ num_layers = len(depths)
391
+ module.num_classes = config.num_labels
392
+ module.num_layers = num_layers
393
+ module.embed_dim = embed_dim
394
+ module.ape = bool(config.use_absolute_embeddings)
395
+ module.patch_norm = bool(config.patch_norm)
396
+ module.num_features = int(embed_dim * 2 ** (num_layers - 1))
397
+ module.mlp_ratio = config.mlp_ratio
398
+
399
+ module.patch_embed = PatchEmbed(
400
+ img_size=image_size,
401
+ patch_size=patch_size,
402
+ in_chans=config.num_channels,
403
+ embed_dim=embed_dim,
404
+ norm_layer=nn.LayerNorm if module.patch_norm else None,
405
+ )
406
+ num_patches = module.patch_embed.num_patches
407
+ module.patch_grid = module.patch_embed.grid_size
408
+ if module.ape:
409
+ module.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
410
+ trunc_normal_(module.absolute_pos_embed, std=config.initializer_range)
411
+ else:
412
+ module.absolute_pos_embed = None
413
+ module.pos_drop = nn.Dropout(p=config.hidden_dropout_prob)
414
+
415
+ dpr = torch.linspace(0, config.drop_path_rate, sum(depths)).tolist()
416
+ layers = []
417
+ for i_layer in range(num_layers):
418
+ layers.append(
419
+ BasicLayer(
420
+ dim=int(embed_dim * 2**i_layer),
421
+ input_resolution=(
422
+ module.patch_grid[0] // (2**i_layer),
423
+ module.patch_grid[1] // (2**i_layer),
424
+ ),
425
+ depth=depths[i_layer],
426
+ num_heads=num_heads[i_layer],
427
+ window_size=config.window_size,
428
+ mlp_ratio=config.mlp_ratio,
429
+ qkv_bias=config.qkv_bias,
430
+ drop=config.hidden_dropout_prob,
431
+ attn_drop=config.attention_probs_dropout_prob,
432
+ drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
433
+ downsample=Downsample2x if i_layer < num_layers - 1 else None,
434
+ )
435
+ )
436
+ module.layers = nn.Sequential(*layers)
437
+ module.norm = nn.LayerNorm(module.num_features, eps=config.layer_norm_eps)
438
+ module.avgpool = nn.AdaptiveAvgPool1d(1)
439
+ if add_head:
440
+ module.head = (
441
+ nn.Linear(module.num_features, config.num_labels)
442
+ if config.num_labels > 0
443
+ else nn.Identity()
444
+ )
445
+
446
+
447
+ def _encode(module, pixel_values):
448
+ x = module.patch_embed(pixel_values)
449
+ if module.absolute_pos_embed is not None:
450
+ x = x + module.absolute_pos_embed
451
+ x = module.pos_drop(x)
452
+ x = module.layers(x)
453
+ x = module.norm(x)
454
+ return x
455
+
456
+
457
+ def _pool(module, sequence):
458
+ return torch.flatten(module.avgpool(sequence.transpose(1, 2)), 1)
459
+
460
+
461
+ class IwinModel(IwinPreTrainedModel):
462
+ _keys_to_ignore_on_load_unexpected = [r"^head\."]
463
+
464
+ def __init__(self, config: IwinConfig):
465
+ super().__init__(config)
466
+ _build_backbone(self, config, add_head=False)
467
+ self.post_init()
468
+
469
+ def forward(
470
+ self,
471
+ pixel_values: Optional[torch.FloatTensor] = None,
472
+ return_dict: Optional[bool] = None,
473
+ **kwargs,
474
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
475
+ if pixel_values is None:
476
+ raise ValueError("`pixel_values` must be provided.")
477
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
478
+ sequence = _encode(self, pixel_values)
479
+ pooled = _pool(self, sequence)
480
+ if not return_dict:
481
+ return (sequence, pooled)
482
+ return BaseModelOutputWithPooling(last_hidden_state=sequence, pooler_output=pooled)
483
+
484
+
485
+ class IwinForImageClassification(IwinPreTrainedModel):
486
+ def __init__(self, config: IwinConfig):
487
+ super().__init__(config)
488
+ self.num_labels = config.num_labels
489
+ _build_backbone(self, config, add_head=True)
490
+ self.post_init()
491
+
492
+ def forward(
493
+ self,
494
+ pixel_values: Optional[torch.FloatTensor] = None,
495
+ labels: Optional[torch.LongTensor] = None,
496
+ return_dict: Optional[bool] = None,
497
+ **kwargs,
498
+ ) -> Union[tuple, ImageClassifierOutput]:
499
+ if pixel_values is None:
500
+ raise ValueError("`pixel_values` must be provided.")
501
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
502
+ sequence = _encode(self, pixel_values)
503
+ pooled = _pool(self, sequence)
504
+ logits = self.head(pooled)
505
+
506
+ loss = None
507
+ if labels is not None:
508
+ if self.config.num_labels == 1:
509
+ loss = F.mse_loss(logits.squeeze(), labels.squeeze().to(logits.dtype))
510
+ else:
511
+ loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))
512
+
513
+ if not return_dict:
514
+ output = (logits, sequence)
515
+ return ((loss,) + output) if loss is not None else output
516
+ return ImageClassifierOutput(loss=loss, logits=logits, hidden_states=None, attentions=None)
preprocessor_config.json CHANGED
@@ -1,5 +1,7 @@
1
  {
 
2
  "do_normalize": true,
 
3
  "do_resize": true,
4
  "feature_extractor_type": "ViTFeatureExtractor",
5
  "image_mean": [
@@ -7,11 +9,16 @@
7
  0.456,
8
  0.406
9
  ],
 
10
  "image_std": [
11
  0.229,
12
  0.224,
13
  0.225
14
  ],
15
  "resample": 3,
16
- "size": 224
 
 
 
 
17
  }
 
1
  {
2
+ "do_center_crop": false,
3
  "do_normalize": true,
4
+ "do_rescale": true,
5
  "do_resize": true,
6
  "feature_extractor_type": "ViTFeatureExtractor",
7
  "image_mean": [
 
9
  0.456,
10
  0.406
11
  ],
12
+ "image_processor_type": "ViTImageProcessor",
13
  "image_std": [
14
  0.229,
15
  0.224,
16
  0.225
17
  ],
18
  "resample": 3,
19
+ "rescale_factor": 0.00392156862745098,
20
+ "size": {
21
+ "height": 224,
22
+ "width": 224
23
+ }
24
  }