sosigikiller commited on
Commit
3cce567
·
1 Parent(s): 9ec0c69

initial push

Browse files
.idea/vcs.xml CHANGED
@@ -2,6 +2,5 @@
2
  <project version="4">
3
  <component name="VcsDirectoryMappings">
4
  <mapping directory="" vcs="Git" />
5
- <mapping directory="$PROJECT_DIR$/CSATv2" vcs="Git" />
6
  </component>
7
  </project>
 
2
  <project version="4">
3
  <component name="VcsDirectoryMappings">
4
  <mapping directory="" vcs="Git" />
 
5
  </component>
6
  </project>
CSAT.py DELETED
@@ -1,490 +0,0 @@
1
- import torch
2
- from torch import nn
3
- from einops.layers.torch import Rearrange
4
- from torch.nn.functional import softmax, sigmoid
5
-
6
- class Block(nn.Module):
7
- """ ConvNeXtV2 Block.
8
-
9
- Args:
10
- dim (int): Number of input channels.
11
- drop_path (float): Stochastic depth rate. Default: 0.0
12
- """
13
-
14
- def __init__(self, dim, drop_path=0., img_size=None):
15
- super().__init__()
16
- self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv
17
- self.norm = LayerNorm(dim, eps=1e-6)
18
- self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers
19
- self.act = nn.GELU()
20
- self.grn = GRN(4 * dim)
21
- self.pwconv2 = nn.Linear(4 * dim, dim)
22
- self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
23
- self.attention = Spatial_Attention()
24
- def forward(self, x):
25
- input = x
26
- x = self.dwconv(x)
27
- x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
28
- x = self.norm(x)
29
- x = self.pwconv1(x)
30
- x = self.act(x)
31
- x = self.grn(x)
32
- x = self.pwconv2(x)
33
-
34
- x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
35
- attention = self.attention(x)
36
- x = x * nn.UpsamplingBilinear2d(x.shape[2:])(attention)
37
- x = input + self.drop_path(x)
38
- return x
39
-
40
- class Spatial_Attention(nn.Module):
41
- def __init__(self):
42
- super().__init__()
43
- self.avgpool = nn.AdaptiveAvgPool2d((7,7))
44
- self.conv = nn.Conv2d(2,1, kernel_size=7, padding=3)
45
- self.attention = TransformerBlock(1, 1, heads=1, dim_head=1, img_size=[7,7])
46
-
47
- def forward(self, x):
48
- x_avg = x.mean([1]).unsqueeze(1)
49
- x_max = x.max(dim=1).values.unsqueeze(1)
50
- # x = torch.concat([x_avg,x_max],dim=1)
51
- x = torch.cat([x_avg, x_max], dim=1)
52
- x = self.avgpool(x)
53
- x = self.conv(x)
54
- x = self.attention(x)
55
- return x
56
-
57
- class TransformerBlock(nn.Module):
58
- def __init__(self, inp, oup, heads=8, dim_head=32, img_size=None, downsample=False, dropout=0.):
59
- super().__init__()
60
- hidden_dim = int(inp * 4)
61
-
62
- self.downsample = downsample
63
- self.ih, self.iw = img_size
64
-
65
- if self.downsample:
66
- self.pool1 = nn.MaxPool2d(3, 2, 1)
67
- self.pool2 = nn.MaxPool2d(3, 2, 1)
68
- self.proj = nn.Conv2d(inp, oup, 1, 1, 0, bias=False)
69
-
70
- self.attn = Attention(inp, oup, heads, dim_head, dropout)
71
- self.ff = FeedForward(oup, hidden_dim, dropout)
72
-
73
- self.attn = nn.Sequential(
74
- Rearrange('b c ih iw -> b (ih iw) c'),
75
- PreNorm(inp, self.attn, nn.LayerNorm),
76
- Rearrange('b (ih iw) c -> b c ih iw', ih=self.ih, iw=self.iw)
77
- )
78
-
79
- self.ff = nn.Sequential(
80
- Rearrange('b c ih iw -> b (ih iw) c'),
81
- PreNorm(oup, self.ff, nn.LayerNorm),
82
- Rearrange('b (ih iw) c -> b c ih iw', ih=self.ih, iw=self.iw)
83
- )
84
-
85
- def forward(self, x):
86
- if self.downsample:
87
- x = self.proj(self.pool1(x)) + self.attn(self.pool2(x))
88
- else:
89
- x = x + self.attn(x)
90
- x = x + self.ff(x)
91
- return x
92
-
93
-
94
- class CSAT(nn.Module):
95
- def __init__(self,
96
- img_size=384,
97
- num_classes=1000,
98
- drop_path_rate=0,
99
- head_init_scale=1,
100
- weight = None
101
- ):
102
- super().__init__()
103
- dims = [32, 48, 96, 176]
104
- channel_order = "channels_first"
105
- depths = [2, 2, 6, 4]
106
- dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
107
-
108
- self.stem = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=dims[0], kernel_size=4, stride=4),
109
- LayerNorm(normalized_shape=dims[0], data_format=channel_order))
110
-
111
- self.stages1 = nn.Sequential(
112
- Block(dim=dims[0], drop_path=dp_rates[0], img_size=[int(img_size / 4), int(img_size / 4)]),
113
- Block(dim=dims[0], drop_path=dp_rates[1], img_size=[int(img_size / 4), int(img_size / 4)]),
114
- LayerNorm(dims[0], eps=1e-6, data_format=channel_order),
115
- nn.Conv2d(dims[0], dims[0 + 1], kernel_size=2, stride=2),
116
- )
117
-
118
- self.stages2 = nn.Sequential(
119
- Block(dim=dims[1], drop_path=dp_rates[0], img_size=[int(img_size / 8), int(img_size / 8)]),
120
- Block(dim=dims[1], drop_path=dp_rates[1], img_size=[int(img_size / 8), int(img_size / 8)]),
121
- LayerNorm(dims[1], eps=1e-6, data_format=channel_order),
122
- nn.Conv2d(dims[1], dims[1 + 1], kernel_size=2, stride=2),
123
- )
124
-
125
- self.stages3 = nn.Sequential(
126
- Block(dim=dims[2], drop_path=dp_rates[0], img_size=[int(img_size / 16), int(img_size / 16)]),
127
- Block(dim=dims[2], drop_path=dp_rates[1], img_size=[int(img_size / 16), int(img_size / 16)]),
128
- Block(dim=dims[2], drop_path=dp_rates[2], img_size=[int(img_size / 16), int(img_size / 16)]),
129
- Block(dim=dims[2], drop_path=dp_rates[3], img_size=[int(img_size / 16), int(img_size / 16)]),
130
- Block(dim=dims[2], drop_path=dp_rates[4], img_size=[int(img_size / 16), int(img_size / 16)]),
131
- Block(dim=dims[2], drop_path=dp_rates[5], img_size=[int(img_size / 16), int(img_size / 16)]),
132
- TransformerBlock(inp=dims[2], oup=dims[2], img_size=[int(img_size / 16), int(img_size / 16)]),
133
- TransformerBlock(inp=dims[2], oup=dims[2], img_size=[int(img_size / 16), int(img_size / 16)]),
134
- LayerNorm(dims[2], eps=1e-6, data_format=channel_order),
135
- nn.Conv2d(dims[2], dims[2 + 1], kernel_size=2, stride=2),
136
- )
137
-
138
- self.stages4 = nn.Sequential(
139
- Block(dim=dims[3], drop_path=dp_rates[0], img_size=[int(img_size / 32), int(img_size / 32)]),
140
- Block(dim=dims[3], drop_path=dp_rates[1], img_size=[int(img_size / 32), int(img_size / 32)]),
141
- Block(dim=dims[3], drop_path=dp_rates[2], img_size=[int(img_size / 32), int(img_size / 32)]),
142
- Block(dim=dims[3], drop_path=dp_rates[3], img_size=[int(img_size / 32), int(img_size / 32)]),
143
- TransformerBlock(inp=dims[3], oup=dims[3], img_size=[int(img_size / 32), int(img_size / 32)]),
144
- TransformerBlock(inp=dims[3], oup=dims[3], img_size=[int(img_size / 32), int(img_size / 32)]),
145
- )
146
-
147
- self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer
148
- self.head = nn.Linear(dims[-1], num_classes)
149
-
150
- self.apply(self._init_weights)
151
- self.head.weight.data.mul_(head_init_scale)
152
- self.head.bias.data.mul_(head_init_scale)
153
-
154
- if weight != None:
155
- self.load_checkpoint(checkpoint=weight)
156
- self.freeze_weight()
157
-
158
- def _init_weights(self, m):
159
- if isinstance(m, (nn.Conv2d, nn.Linear)):
160
- trunc_normal_(m.weight, std=.02)
161
- try:
162
- nn.init.constant_(m.bias, 0)
163
- except: # transformer layers
164
- pass
165
- # print("transformer layer can't initialize")
166
-
167
- def freeze_weight(self):
168
- for name, param in self.named_parameters():
169
- if param.requires_grad and 'pos_embed' in name:
170
- param.requires_grad = False
171
-
172
- def load_checkpoint(self, checkpoint=None):
173
- state = torch.load(checkpoint, map_location='cpu')
174
- if 'state_dict' in state:
175
- state_dict = state['state_dict']
176
- elif 'model' in state:
177
- state_dict = state['model']
178
- for key in list(state_dict.keys()):
179
- state_dict[key.replace('module.', '')] = state_dict.pop(key)
180
- elif 'q_state_dict' in state:
181
- state_dict = state['q_state_dict']
182
-
183
- for key in list(state_dict.keys()):
184
- state_dict[key.replace('backbone.', '')] = state_dict.pop(key)
185
-
186
- model_dict = self.state_dict()
187
- weights = {k: v for k, v in state_dict.items() if k in model_dict}
188
-
189
- model_dict.update(weights)
190
- del model_dict['head.weight']
191
- del model_dict['head.bias']
192
- self.load_state_dict(model_dict, strict=False)
193
-
194
- def forward(self, x):
195
- outputs = self.encoder(x)
196
- # x, low_level, mid_level, high_level = self.seg_encoder(x)
197
- return outputs
198
-
199
- def encoder(self, x):
200
- x = self.stem(x)
201
- for _, layer in enumerate(self.stages1):
202
- if _ == len(self.stages1) - 1:
203
- x1 = x
204
- x = layer(x)
205
-
206
- for _, layer in enumerate(self.stages2):
207
- if _ == len(self.stages2) - 1:
208
- x2 = x
209
- x = layer(x)
210
-
211
- for _, layer in enumerate(self.stages3):
212
- if _ == len(self.stages3) - 1:
213
- x3 = x
214
- x = layer(x)
215
-
216
- x = self.stages4(x)
217
- x = self.norm(x.mean([-2, -1]))
218
- x = self.head(x)
219
- return x
220
-
221
- def seg_encoder(self, x):
222
- org_img = x
223
- x = self.stem(x)
224
- for _, layer in enumerate(self.stages1):
225
- if _ == len(self.stages1) - 2:
226
- low_level = x
227
- x = layer(x)
228
-
229
- x = self.stages2(x)
230
-
231
- for _, layer in enumerate(self.stages3):
232
- if _ == len(self.stages3) - 2:
233
- mid_level = x
234
- x = layer(x)
235
-
236
- for _, layer in enumerate(self.stages4):
237
- x = layer(x)
238
- high_level = x
239
-
240
- return org_img, low_level, mid_level, high_level
241
-
242
- import torch
243
- import torch.nn as nn
244
- import torch.nn.functional as F
245
- from einops import rearrange
246
- import math
247
- import warnings
248
-
249
- class LayerNorm(nn.Module):
250
- """ LayerNorm that supports two data formats: channels_last (default) or channels_first.
251
- The ordering of the dimensions in the inputs. channels_last corresponds to inputs with
252
- shape (batch_size, height, width, channels) while channels_first corresponds to inputs
253
- with shape (batch_size, channels, height, width).
254
- """
255
-
256
- def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
257
- super().__init__()
258
- self.weight = nn.Parameter(torch.ones(normalized_shape))
259
- self.bias = nn.Parameter(torch.zeros(normalized_shape))
260
- self.eps = eps
261
- self.data_format = data_format
262
- if self.data_format not in ["channels_last", "channels_first"]:
263
- raise NotImplementedError
264
- self.normalized_shape = (normalized_shape,)
265
-
266
- def forward(self, x):
267
- if self.data_format == "channels_last":
268
- return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
269
- elif self.data_format == "channels_first":
270
- u = x.mean(1, keepdim=True)
271
- s = (x - u).pow(2).mean(1, keepdim=True)
272
- x = (x - u) / torch.sqrt(s + self.eps)
273
- x = self.weight[:, None, None] * x + self.bias[:, None, None]
274
- return x
275
-
276
-
277
- class GRN(nn.Module):
278
- """ GRN (Global Response Normalization) layer
279
- """
280
-
281
- def __init__(self, dim):
282
- super().__init__()
283
- self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
284
- self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
285
-
286
- def forward(self, x):
287
- Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
288
- Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6)
289
- return self.gamma * (x * Nx) + self.beta + x
290
-
291
- def drop_path(x, drop_prob: float = 0., training: bool = False):
292
- """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
293
-
294
- This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
295
- the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
296
- See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
297
- changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
298
- 'survival rate' as the argument.
299
-
300
- """
301
- if drop_prob == 0. or not training:
302
- return x
303
- keep_prob = 1 - drop_prob
304
- shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
305
- random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
306
- random_tensor.floor_() # binarize
307
- output = x.div(keep_prob) * random_tensor
308
- return output
309
-
310
-
311
- class DropPath(nn.Module):
312
- """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
313
- """
314
- def __init__(self, drop_prob=None):
315
- super(DropPath, self).__init__()
316
- self.drop_prob = drop_prob
317
-
318
- def forward(self, x):
319
- return drop_path(x, self.drop_prob, self.training)
320
-
321
- class FeedForward(nn.Module):
322
- def __init__(self, dim, hidden_dim, dropout=0.):
323
- super().__init__()
324
- self.net = nn.Sequential(
325
- nn.Linear(dim, hidden_dim),
326
- nn.GELU(),
327
- nn.Dropout(dropout),
328
- nn.Linear(hidden_dim, dim),
329
- nn.Dropout(dropout)
330
- )
331
-
332
- def forward(self, x):
333
- return self.net(x)
334
-
335
- class PreNorm(nn.Module):
336
- def __init__(self, dim, fn, norm):
337
- super().__init__()
338
- self.norm = norm(dim)
339
- self.fn = fn
340
-
341
- def forward(self, x, **kwargs):
342
- return self.fn(self.norm(x), **kwargs)
343
-
344
- class Attention(nn.Module):
345
- def __init__(self, inp, oup, heads=8, dim_head=32, dropout=0.):
346
- super().__init__()
347
- inner_dim = dim_head * heads
348
- project_out = not (heads == 1 and dim_head == inp)
349
-
350
- # self.ih, self.iw = image_size
351
- self.heads = heads
352
- self.scale = dim_head ** -0.5
353
-
354
- self.attend = nn.Softmax(dim=-1)
355
- self.to_qkv = nn.Linear(inp, inner_dim * 3, bias=False)
356
-
357
- self.to_out = nn.Sequential(
358
- nn.Linear(inner_dim, oup),
359
- nn.Dropout(dropout)
360
- ) if project_out else nn.Identity()
361
- self.pos_embed = PosCNN(in_chans=inp)
362
-
363
- def forward(self, x):
364
- x = self.pos_embed(x)
365
- qkv = self.to_qkv(x).chunk(3, dim=-1)
366
- q, k, v = map(lambda t: rearrange(
367
- t, 'b n (h d) -> b h n d', h=self.heads), qkv)
368
- dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
369
- attn = self.attend(dots)
370
- out = torch.matmul(attn, v)
371
- out = rearrange(out, 'b h n d -> b n (h d)')
372
- out = self.to_out(out)
373
- return out
374
-
375
- # PEG from https://arxiv.org/abs/2102.10882
376
- class PosCNN(nn.Module):
377
- def __init__(self, in_chans):
378
- super(PosCNN, self).__init__()
379
- self.proj = nn.Conv2d(in_chans, in_chans, kernel_size=3, stride = 1, padding=1, bias=True, groups=in_chans)
380
-
381
- def forward(self, x):
382
- B, N, C = x.shape
383
- feat_token = x
384
- H, W = int(N**0.5), int(N**0.5)
385
- cnn_feat = feat_token.transpose(1, 2).view(B, C, H, W)
386
- x = self.proj(cnn_feat) + cnn_feat
387
- x = x.flatten(2).transpose(1, 2)
388
- return x
389
-
390
- def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
391
- # type: (Tensor, float, float, float, float) -> Tensor
392
- r"""Fills the input Tensor with values drawn from a truncated
393
- normal distribution. The values are effectively drawn from the
394
- normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
395
- with values outside :math:`[a, b]` redrawn until they are within
396
- the bounds. The method used for generating the random values works
397
- best when :math:`a \leq \text{mean} \leq b`.
398
- Args:
399
- tensor: an n-dimensional `torch.Tensor`
400
- mean: the mean of the normal distribution
401
- std: the standard deviation of the normal distribution
402
- a: the minimum cutoff value
403
- b: the maximum cutoff value
404
- Examples:
405
- >>> w = torch.empty(3, 5)
406
- >>> nn.init.trunc_normal_(w)
407
- """
408
- return _no_grad_trunc_normal_(tensor, mean, std, a, b)
409
-
410
- def _no_grad_trunc_normal_(tensor, mean, std, a, b):
411
- # Cut & paste from PyTorch official master until it's in a few official releases - RW
412
- # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
413
- def norm_cdf(x):
414
- # Computes standard normal cumulative distribution function
415
- return (1. + math.erf(x / math.sqrt(2.))) / 2.
416
-
417
- if (mean < a - 2 * std) or (mean > b + 2 * std):
418
- warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
419
- "The distribution of values may be incorrect.",
420
- stacklevel=2)
421
-
422
- with torch.no_grad():
423
- # Values are generated by using a truncated uniform distribution and
424
- # then using the inverse CDF for the normal distribution.
425
- # Get upper and lower cdf values
426
- l = norm_cdf((a - mean) / std)
427
- u = norm_cdf((b - mean) / std)
428
-
429
- # Uniformly fill tensor with values from [l, u], then translate to
430
- # [2l-1, 2u-1].
431
- tensor.uniform_(2 * l - 1, 2 * u - 1)
432
-
433
- # Use inverse cdf transform for normal distribution to get truncated
434
- # standard normal
435
- tensor.erfinv_()
436
-
437
- # Transform to proper mean, std
438
- tensor.mul_(std * math.sqrt(2.))
439
- tensor.add_(mean)
440
-
441
- # Clamp to ensure it's in the proper range
442
- tensor.clamp_(min=a, max=b)
443
- return tensor
444
-
445
- class DoubleConv(nn.Module):
446
- """(convolution => [BN] => ReLU) * 2"""
447
-
448
- def __init__(self, in_channels, out_channels, mid_channels=None):
449
- super().__init__()
450
- if not mid_channels:
451
- mid_channels = out_channels
452
- self.double_conv = nn.Sequential(
453
- nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),
454
- nn.BatchNorm2d(mid_channels),
455
- nn.ReLU(inplace=True),
456
- nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),
457
- nn.BatchNorm2d(out_channels),
458
- nn.ReLU(inplace=True)
459
- )
460
-
461
- def forward(self, x):
462
- return self.double_conv(x)
463
-
464
- class Up(nn.Module):
465
- """Upscaling then double conv"""
466
-
467
- def __init__(self, in_channels, out_channels, bilinear=True):
468
- super().__init__()
469
-
470
- # if bilinear, use the normal convolutions to reduce the number of channels
471
- if bilinear:
472
- self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
473
- self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)
474
- else:
475
- self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
476
- self.conv = DoubleConv(in_channels, out_channels)
477
-
478
- def forward(self, x1, x2):
479
- x1 = self.up(x1)
480
- # input is CHW
481
- diffY = x2.size()[2] - x1.size()[2]
482
- diffX = x2.size()[3] - x1.size()[3]
483
-
484
- x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
485
- diffY // 2, diffY - diffY // 2])
486
- # if you have padding issues, see
487
- # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a
488
- # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd
489
- x = torch.cat([x2, x1], dim=1)
490
- return self.conv(x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ResNet18.py DELETED
@@ -1,9 +0,0 @@
1
- import torchvision
2
-
3
- class ResNet18(torchvision.models.ResNet):
4
- def __init__(self, num_classes=1000, weight=None):
5
- super(ResNet18, self).__init__(block=torchvision.models.resnet.BasicBlock, layers=[2, 2, 2, 2], num_classes=num_classes)
6
- self.zero_init_residual = True
7
-
8
- def forward(self, x):
9
- return self._forward_impl(x)
 
 
 
 
 
 
 
 
 
 
__pycache__/test_imagenet_10.cpython-311-pytest-8.4.1.pyc ADDED
Binary file (4.08 kB). View file
 
convert_and_push.py DELETED
File without changes
example.py CHANGED
@@ -1,33 +1,24 @@
1
  import torch
2
- from model.ResNet18 import ResNet18
3
- from model.CSAT import CSAT
4
- from model.CSATv2 import CSATv2
5
- from torch import nn
6
 
7
- img_size = 224
8
- path = r'./CSAT_ImageNet.pth.tar' #or CSAT_RCKD.pth.tar <- for pathological image analysis
9
- model = CSAT(img_size=img_size)
10
- state = torch.load(path, map_location='cpu')
11
- model.load_state_dict(state)
12
- data = torch.zeros((1, 3, img_size, img_size)) #b, c, h, w = 1, 3, 224, 224
13
- model.head = nn.Identity()
14
- output = model(data)#b, c = 1, 176
15
- print(output.shape)
16
 
17
- path = r'./ResNet18_RCKD.pth.tar'
18
- model = ResNet18()
19
- state = torch.load(path, map_location='cpu')
20
- model.load_state_dict(state)
21
- data = torch.zeros((1, 3, img_size, img_size)) #b, c, h, w = 1, 3, 224, 224
22
- model.fc = nn.Identity()
23
- output = model(data)#b, c = 1, 512
24
- print(output.shape)
25
 
26
- path = r'./CSAT_v2_ImageNet.pth.tar'
27
- model = CSATv2(img_size=img_size)
28
- state = torch.load(path, map_location='cpu')
29
- model.load_state_dict(state['state_dict'])
30
- data = torch.zeros((1, 3, img_size, img_size)) #b, c, h, w = 1, 3, 512, 512
31
- model.fc = nn.Identity()
32
- output = model(data)#b, c = 1, 512
33
- print(output.shape)
 
 
 
 
 
 
1
  import torch
2
+ from datasets import load_dataset
3
+ from transformers import AutoImageProcessor, AutoModelForImageClassification
 
 
4
 
5
+ # 예시 데이터: 고양이 이미지
6
+ dataset = load_dataset("huggingface/cats-image")
7
+ image = dataset["test"]["image"][0]
 
 
 
 
 
 
8
 
9
+ # 👉 CSATv2 모델로 교체
10
+ model_name = "Hyunil/CSATv2"
 
 
 
 
 
 
11
 
12
+ # Preprocessor + Model 로드
13
+ processor = AutoImageProcessor.from_pretrained(model_name, trust_remote_code=True)
14
+ model = AutoModelForImageClassification.from_pretrained(model_name, trust_remote_code=True)
15
+
16
+ # 전처리
17
+ inputs = processor(image, return_tensors="pt")
18
+
19
+ # 추론
20
+ with torch.no_grad():
21
+ logits = model(**inputs).logits
22
+
23
+ pred = logits.argmax(-1).item()
24
+ print("Predicted label:", model.config.id2label[pred])
example_2.py DELETED
@@ -1,16 +0,0 @@
1
- from transformers import AutoImageProcessor, AutoModelForImageClassification
2
- from PIL import Image
3
- import requests
4
-
5
- processor = AutoImageProcessor.from_pretrained("Hyunil/CSATv2", trust_remote_code=True)
6
- model = AutoModelForImageClassification.from_pretrained("Hyunil/CSATv2", trust_remote_code=True)
7
-
8
- url = "https://images.unsplash.com/photo-1516116216624-53e697fedbea"
9
- image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
10
-
11
- inputs = processor(image, return_tensors="pt")
12
- outputs = model(**inputs)
13
- probs = outputs.logits.softmax(dim=-1)
14
-
15
- top_prob, top_idx = probs.topk(5)
16
- print(top_idx, top_prob)