SDoyez commited on
Commit
ad21764
·
1 Parent(s): 0d21685

add my segformer to HF

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ ---
4
+
5
+ # SegFormer (rebuilt the architecture + loading weights from NVIDIA + finetuning):
6
+
7
+ SegFormer trained on the dataset , by using the OpenMLCore framework.
8
+ The based Pytorch Code is available in model.py
9
+
10
+ ---
11
+
12
+ ## 📌 Results
13
+
14
+ ### Visualisations:
15
+ There are some results after the training on Cells_one_hot_encoding dataset.
16
+
17
+ #### Cells Multiclass:
18
+ | Result 1 | Result 2 |
19
+ | :---: | :---: |
20
+ | ![Description Image 1](Result_Cells_monoclass/Figure_1.png) | ![Description Image 2](Result_Cells_monoclass/Figure_3.png) |
21
+
22
+ ---
23
+
24
+ ## 📊 Metrics & Performances (Validation)
25
+
26
+ ### Performance on Cells detection dataset:
27
+ Please note that, SegFormer is a Vision Transformer, so by definition, it is hard to make converge properly and easy to make it overfit. I added some drop out, Data augmenntation, weight decay et regularization.
28
+ | Model / Configuration | Accuracy | IoU | Precision | Recall | F1-Score |
29
+ | :--- | :---: | :---: | :---: | :---: | :---: |
30
+ | Modèle V1(Cells monoclass dataset) | 0.9496 | 0.7006 | 0.8410 | 0.7719 | 0.8026 |
31
+
32
+ ---
33
+
34
+ ## ⚙️ Model training:
35
+
36
+ I used my personal Framework ( a wrapper of PyTorch) to train the model.
37
+
38
+ ### Install the framework:
39
+ ```bash
40
+ git clone https://github.com/sebastien-doyez2812/OpenML-core.git
41
+ cd OpenML-core
Result_Cells_monoclass/Figure_1.png ADDED

Git LFS Details

  • SHA256: 2ad3b49fc4e9da3454171f523d0607d3d57ab611f165c9d082d93fec2a3c605b
  • Pointer size: 131 Bytes
  • Size of remote file: 183 kB
Result_Cells_monoclass/Figure_2.png ADDED

Git LFS Details

  • SHA256: 0c1673a89d75c65e3c8f45d8ea7ff9ad73d3a600a6b17295daaf1df312a5e265
  • Pointer size: 131 Bytes
  • Size of remote file: 212 kB
Result_Cells_monoclass/Figure_3.png ADDED

Git LFS Details

  • SHA256: d4caa353c1c6fe53539303bf18f83b350d370792132ec7fe33f01f06250716e7
  • Pointer size: 131 Bytes
  • Size of remote file: 283 kB
Result_Cells_monoclass/Figure_4.png ADDED

Git LFS Details

  • SHA256: 3b1ddac21aca6fd5e889a30bf9d92874ccfc605cd19b8676ae9d1fe8aeda5dcd
  • Pointer size: 131 Bytes
  • Size of remote file: 249 kB
Result_Cells_monoclass/Figure_5.png ADDED

Git LFS Details

  • SHA256: f534fc4058ce1aa64482526da9bf1190e13d5fdb8887e5b3c40904461348159e
  • Pointer size: 131 Bytes
  • Size of remote file: 308 kB
Result_Cells_monoclass/Figure_6.png ADDED

Git LFS Details

  • SHA256: 200fc99c39686e35a55ef01661227f7f4ff0b1b38673cfca496ece379d8554ed
  • Pointer size: 131 Bytes
  • Size of remote file: 225 kB
Result_Cells_monoclass/Figure_7.png ADDED

Git LFS Details

  • SHA256: 10b1f9435ee548257d05bad66de9e21c71e111dd22dfbc6039940062dd4c0e07
  • Pointer size: 131 Bytes
  • Size of remote file: 208 kB
Result_Cells_monoclass/Figure_8.png ADDED

Git LFS Details

  • SHA256: 2a26639836646bf0da87ecaf136f85059284b49640951bb1b2f47e66009533a8
  • Pointer size: 131 Bytes
  • Size of remote file: 198 kB
model.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from huggingface_hub import hf_hub_download
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import math
6
+
7
+ class EfficientSelfAttention(nn.Module):
8
+ def __init__(self, dim, num_heads = 8, reduction_ratio = 1, dropout_p = 0.1):
9
+ super().__init__()
10
+ self.dim = dim # = C in the article
11
+ self.num_heads = num_heads
12
+ self.head_dim = dim // num_heads
13
+ self.scale = 1.0 / math.sqrt(self.head_dim)
14
+ self.reduction_ratio = reduction_ratio
15
+
16
+ self.W_q = nn.Linear(dim, dim)
17
+ if reduction_ratio > 1:
18
+ self.sr = nn.Conv2d(dim, dim, kernel_size=reduction_ratio, stride=reduction_ratio)
19
+ self.norm = nn.LayerNorm(dim)
20
+ else:
21
+ self.sr = None
22
+ self.norm = None
23
+
24
+ self.W_k = nn.Linear(dim, dim)
25
+ self.W_v = nn.Linear(dim, dim)
26
+ self.proj = nn.Linear(dim, dim)
27
+
28
+ self.attn_drop = nn.Dropout(dropout_p)
29
+ self.proj_drop = nn.Dropout(dropout_p)
30
+
31
+ def forward(self, X, H, W):
32
+ B, N, C = X.shape # N = h * W
33
+ # (B, N, C) -> (B, N, heads, head_dim) -> (B, heads, N, head_dim)
34
+ q = self.W_q(X).reshape(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
35
+ if self.sr is not None:
36
+ x_spatial = X.permute(0, 2, 1). reshape(B, C, H, W)
37
+ x_spatial = self.sr(x_spatial)
38
+ x_spatial = x_spatial.flatten(2) # B, C, H*W
39
+ x_spatial = x_spatial.permute(0, 2, 1)
40
+ x_spatial = self.norm(x_spatial)
41
+
42
+ k = self.W_k(x_spatial).reshape(B, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
43
+ v = self.W_v(x_spatial).reshape(B, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
44
+ else:
45
+ # Classical Attention
46
+ k = self.W_k(X).reshape(B, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
47
+ v = self.W_v(X).reshape(B, -1, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
48
+
49
+ attn_value = (q @ k.transpose(-2, -1)) * self.scale
50
+ attn_value = attn_value.softmax(dim=-1)
51
+ attn_value = self.attn_drop(attn_value)
52
+
53
+ # (B, heads, N, N_reduced) @ v: (B, heads, N_reduced, head_dim) -> (B, heads, N, head_dim)
54
+ X_out = attn_value @ v
55
+ X_out = X_out.permute(0, 2, 1, 3). reshape(B, N, C)
56
+ proj = self.proj(X_out)
57
+ proj = self.proj_drop(proj)
58
+ return proj
59
+
60
+ class OverlapPatchMerging(nn.Module):
61
+ def __init__(self, in_channels, out_channels, kernel_size=3, stride=2, padding=1):
62
+ super().__init__()
63
+ self.conv = nn.Conv2d(in_channels=in_channels,
64
+ out_channels=out_channels,
65
+ kernel_size=kernel_size,
66
+ stride=stride,
67
+ padding=padding
68
+ )
69
+ self.norm = nn.LayerNorm(out_channels)
70
+ def forward(self, X):
71
+ # B, C, H, W
72
+ X = self.conv(X)
73
+ B, C, H_new, W_new = X.shape
74
+
75
+ X = X.flatten(2). transpose(2, 1) # B, N, C
76
+ X = self.norm(X)
77
+ return X, H_new, W_new
78
+
79
+
80
+ class TransformerSegFormer(nn.Module):
81
+ def __init__(self, N, C_in, C_out, num_heads, reduction_ratio = 1, intermediate_channel = 256, H = 256, W = 256, patch_kernel = 3, stride = 2, padding = 1):
82
+ super().__init__()
83
+
84
+ self.efficient_self_attns = nn.ModuleList()
85
+ self.mix_FFNs = nn.ModuleList()
86
+ self.N = N
87
+
88
+ for i in range(N):
89
+ self.efficient_self_attns.append(EfficientSelfAttention(dim = C_out, num_heads= num_heads, reduction_ratio= reduction_ratio))
90
+ target_H = H // stride
91
+ target_W = W // stride
92
+ self.mix_FFNs.append(MixFFN(C_out, intermediate_channel))
93
+
94
+ self.overlap_patch_merging = OverlapPatchMerging(C_in, C_out,patch_kernel, stride = stride, padding = padding)
95
+
96
+ def forward(self, X):
97
+ X, H_new, W_new = self.overlap_patch_merging(X)
98
+
99
+ for idx in range(self.N):
100
+ X = self.efficient_self_attns[idx](X, H_new, W_new) + X
101
+ X = self.mix_FFNs[idx](X, H_new, W_new)
102
+
103
+ return X, H_new, W_new
104
+
105
+ class MixFFN(nn.Module):
106
+ def __init__(self, in_channels, intermediate_channels, dropout_p = 0.1):
107
+ super().__init__()
108
+ self.MLP1 = nn.Linear(in_features=in_channels, out_features=intermediate_channels)
109
+ self.gelu = nn.GELU()
110
+ self.conv33 = nn.Conv2d(in_channels=intermediate_channels, out_channels=intermediate_channels, kernel_size=3, padding=1, groups=intermediate_channels) # Note: Conv 3x3 depthwise dans l'original
111
+ self.MLP2 = nn.Linear(in_features=intermediate_channels, out_features=in_channels)
112
+ self.dropout = nn.Dropout(dropout_p)
113
+ def forward(self, X, H, W):
114
+ skipped_X = X
115
+ B, N, C = X.shape
116
+
117
+ X = self.MLP1(X)
118
+ X = self.gelu(X)
119
+ X = self.dropout(X)
120
+
121
+ # Spatial reshape dynamique avec H et W passés en paramètre
122
+ X = X.transpose(1, 2).view(B, -1, H, W)
123
+ X = self.conv33(X)
124
+ X = X.flatten(2).transpose(1, 2)
125
+
126
+ X = self.MLP2(X)
127
+ X = self.dropout(X)
128
+ return X + skipped_X
129
+
130
+
131
+
132
+
133
+ class MLPLayers(nn.Module):
134
+ def __init__(self, i, input_channels, embbeding_channels, dropout = 0.1, H = 256, W = 256):
135
+ super().__init__()
136
+ # Keep the same dimension but project on the number of channels:
137
+ self.linear_project = nn.Conv2d(in_channels= input_channels, out_channels= embbeding_channels, kernel_size=1)
138
+
139
+ self.dropout = nn.Dropout(dropout)
140
+ self.current_H = H // (2**(i + 2))
141
+ self.current_W = W // (2**(i + 2))
142
+ self.target_H = H // 4
143
+ self.target_W = W // 4
144
+
145
+ self.linear_spatial = nn.Linear((self.current_H * self.current_W), self.target_H * self.target_W)
146
+
147
+ def forward(self, X):
148
+ # B, Ci, H/2**(i+1), W/2**(i+1)
149
+ B, _, _, _ = X.shape
150
+
151
+ # Projection on C:
152
+ # B, C, H/2**(i+1), W/2**(i+1)
153
+ # C is embbeding channels:
154
+ X = self.linear_project(X)
155
+
156
+ # B, C, H/2**(i+1)* W/2**(i+1)
157
+ X = X.flatten(2)
158
+
159
+ # B, C, H/4* W/4
160
+ X = self.linear_spatial(X)
161
+
162
+ X = self.dropout(X)
163
+ # B, C, H/4, W/4
164
+ X = X.view(B, -1, self.target_H, self.target_W)
165
+ return X
166
+
167
+
168
+ class SegFormerTorch(nn.Module):
169
+ def __init__(self, depth = 4, input_channels=1, output_channels=1, initial_filters=64, dropout_p = 0.1, H=256, W= 256):
170
+ super().__init__()
171
+ self.depth = depth
172
+ self.channels = [32, 64, 160, 256]
173
+ # self.channels = [initial_filters*2**i for i in range(self.depth)]
174
+ self.num_heads = [1, 2, 5, 8]
175
+ reduction_ratios = [8, 4, 2, 1]
176
+
177
+ self.transformers = nn.ModuleList()
178
+ current_in_channels = input_channels
179
+
180
+ current_H, current_W = H, W
181
+
182
+ for i in range(self.depth):
183
+ patch_kernel = 7 if i == 0 else 3
184
+ patch_stride = 4 if i == 0 else 2
185
+ patch_padding = 3 if i == 0 else 1
186
+
187
+
188
+ self.transformers.append(TransformerSegFormer(
189
+ N=2, # Nombre de blocs Attention+MixFFN par niveau
190
+ C_in=current_in_channels,
191
+ C_out=self.channels[i],
192
+ num_heads=self.num_heads[i],
193
+ reduction_ratio=reduction_ratios[i],
194
+ intermediate_channel=self.channels[i] * 4,
195
+ H=current_H,
196
+ W=current_W,
197
+ patch_kernel=patch_kernel,
198
+ stride=patch_stride,
199
+ padding=patch_padding
200
+ )
201
+ )
202
+ current_in_channels = self.channels[i]
203
+ current_H //= patch_stride
204
+ current_W //= patch_stride
205
+ self.embedding_dim = 256
206
+
207
+ self.mlp_layers = nn.ModuleList()
208
+ for i in range(self.depth):
209
+ self.mlp_layers.append(
210
+ MLPLayers(i=i, input_channels=self.channels[i], embbeding_channels=self.embedding_dim, H=H, W=W)
211
+ )
212
+ self.linear_fuse = nn.Conv2d(self.embedding_dim * self.depth, self.embedding_dim, kernel_size=1)
213
+ self.linear_pred = nn.Conv2d(self.embedding_dim, output_channels, kernel_size=1)
214
+
215
+ self.dropout = nn.Dropout(dropout_p)
216
+
217
+ def forward(self, X):
218
+ orig_H, orig_W = X.shape[-2], X.shape[-1]
219
+ features = []
220
+ for idx in range(self.depth):
221
+ X, H_new, W_new = self.transformers[idx](X)
222
+ X_spatial = X.transpose(1, 2).view(X.shape[0], -1, H_new, W_new).contiguous()
223
+ features.append(X_spatial)
224
+ X = X_spatial
225
+
226
+ decoder_output = []
227
+ for idx in range(self.depth):
228
+ decoder_output.append(self.mlp_layers[idx](features[idx]))
229
+
230
+ out = torch.cat(decoder_output, dim = 1)
231
+ out = self.linear_fuse(out)
232
+ out = F.gelu(out)
233
+ out = self.dropout(out)
234
+ out = self.linear_pred(out)
235
+ # To get the same dimension as the input:
236
+ out = F.interpolate(out, size=(orig_H, orig_W), mode='bilinear', align_corners=False)
237
+
238
+ return out
239
+
240
+
241
+ def load_nvidia_weights_into_custom_model(model, model_name="nvidia/mit-b0"):
242
+ try:
243
+ weights_path = hf_hub_download(repo_id=model_name, filename="pytorch_model.bin")
244
+ official_dict = torch.load(weights_path, map_location="cpu")
245
+ except Exception:
246
+ from safetensors.torch import load_file
247
+ weights_path = hf_hub_download(repo_id=model_name, filename="model.safetensors")
248
+ official_dict = load_file(weights_path)
249
+
250
+ custom_dict = model.state_dict()
251
+ new_state_dict = {}
252
+
253
+ for stage_idx in range(4):
254
+ src_prefix = f"segformer.encoder.patch_embeddings.{stage_idx}"
255
+ dst_prefix = f"transformers.{stage_idx}.overlap_patch_merging"
256
+
257
+ if f"{src_prefix}.proj.weight" in official_dict:
258
+ new_state_dict[f"{dst_prefix}.conv.weight"] = official_dict[f"{src_prefix}.proj.weight"]
259
+ new_state_dict[f"{dst_prefix}.conv.bias"] = official_dict[f"{src_prefix}.proj.bias"]
260
+ new_state_dict[f"{dst_prefix}.norm.weight"] = official_dict[f"{src_prefix}.layer_norm.weight"]
261
+ new_state_dict[f"{dst_prefix}.norm.bias"] = official_dict[f"{src_prefix}.layer_norm.bias"]
262
+ for block_idx in range(2):
263
+ src_block = f"segformer.encoder.block.{stage_idx}.{block_idx}"
264
+
265
+ # Efficient Self-Attention
266
+ dst_attn = f"transformers.{stage_idx}.efficient_self_attns.{block_idx}"
267
+ new_state_dict[f"{dst_attn}.W_q.weight"] = official_dict[f"{src_block}.attention.self.query.weight"]
268
+ new_state_dict[f"{dst_attn}.W_q.bias"] = official_dict[f"{src_block}.attention.self.query.bias"]
269
+ new_state_dict[f"{dst_attn}.W_k.weight"] = official_dict[f"{src_block}.attention.self.key.weight"]
270
+ new_state_dict[f"{dst_attn}.W_k.bias"] = official_dict[f"{src_block}.attention.self.key.bias"]
271
+ new_state_dict[f"{dst_attn}.W_v.weight"] = official_dict[f"{src_block}.attention.self.value.weight"]
272
+ new_state_dict[f"{dst_attn}.W_v.bias"] = official_dict[f"{src_block}.attention.self.value.bias"]
273
+ new_state_dict[f"{dst_attn}.proj.weight"] = official_dict[f"{src_block}.attention.output.dense.weight"]
274
+ new_state_dict[f"{dst_attn}.proj.bias"] = official_dict[f"{src_block}.attention.output.dense.bias"]
275
+
276
+ # Spatial Reduction (SR)
277
+ if f"{src_block}.attention.self.sr.weight" in official_dict:
278
+ new_state_dict[f"{dst_attn}.sr.weight"] = official_dict[f"{src_block}.attention.self.sr.weight"]
279
+ new_state_dict[f"{dst_attn}.sr.bias"] = official_dict[f"{src_block}.attention.self.sr.bias"]
280
+ new_state_dict[f"{dst_attn}.norm.weight"] = official_dict[f"{src_block}.attention.self.layer_norm.weight"]
281
+ new_state_dict[f"{dst_attn}.norm.bias"] = official_dict[f"{src_block}.attention.self.layer_norm.bias"]
282
+
283
+ # MixFFN
284
+ dst_ffn = f"transformers.{stage_idx}.mix_FFNs.{block_idx}"
285
+ new_state_dict[f"{dst_ffn}.MLP1.weight"] = official_dict[f"{src_block}.mlp.dense1.weight"]
286
+ new_state_dict[f"{dst_ffn}.MLP1.bias"] = official_dict[f"{src_block}.mlp.dense1.bias"]
287
+ new_state_dict[f"{dst_ffn}.conv33.weight"] = official_dict[f"{src_block}.mlp.dwconv.dwconv.weight"]
288
+ new_state_dict[f"{dst_ffn}.conv33.bias"] = official_dict[f"{src_block}.mlp.dwconv.dwconv.bias"]
289
+ new_state_dict[f"{dst_ffn}.MLP2.weight"] = official_dict[f"{src_block}.mlp.dense2.weight"]
290
+ new_state_dict[f"{dst_ffn}.MLP2.bias"] = official_dict[f"{src_block}.mlp.dense2.bias"]
291
+
292
+ missing, unexpected = model.load_state_dict(new_state_dict, strict=False)
293
+ print(f"Loading successful ! Missing keys : {len(missing)}, Weird keys : {len(unexpected)}")
294
+ return model
segformer_model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:15fed130b8abb2b5237462e757344ed1e6a32c392bdaf834a23583b2f52c7b48
3
+ size 104157724
segformer_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9b8d94674b9b6f8b85dcf53cd8fe68037077e1d82f2e461f7758a91884ad96f
3
+ size 104098826