RahmaDev commited on
Commit
0e4c246
·
verified ·
1 Parent(s): 9459e4c

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +239 -0
  2. pim_module.py +573 -0
  3. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gdown
2
+ import os
3
+ import torch
4
+ import requests
5
+ import numpy as np
6
+ import numpy.matlib
7
+ import copy
8
+ import cv2
9
+ from PIL import Image
10
+ from typing import List
11
+ import timm
12
+ import gradio as gr
13
+ import torchvision.transforms as transforms
14
+
15
+ from pim_module import PluginMoodel # Assure-toi que ce fichier est présent
16
+
17
+ # === Téléchargement automatique depuis Google Drive ===
18
+ if not os.path.exists("weights.pt"):
19
+ print("Téléchargement des poids depuis Google Drive avec gdown...")
20
+ file_id = "15yqHRLQM_oEfp1Byo_0IpzYqRFRmJlui"
21
+ url = f"https://drive.google.com/uc?id={file_id}"
22
+ gdown.download(url, "weights.pt", quiet=False)
23
+
24
+
25
+
26
+ # === Classes
27
+ classes_list = [
28
+ "Ferrage_Et_Accessoires_Anti_Fausse_Manoeuvre",
29
+ "Ferrage_Et_Accessoires_Busettes",
30
+ "Ferrage_Et_Accessoires_Butees",
31
+ "Ferrage_Et_Accessoires_Chariots",
32
+ "Ferrage_Et_Accessoires_Charniere",
33
+ "Ferrage_Et_Accessoires_Compas_limiteur",
34
+ "Ferrage_Et_Accessoires_Cylindres",
35
+ "Ferrage_Et_Accessoires_Gaches",
36
+ "Ferrage_Et_Accessoires_Renvois_D_Angle",
37
+ "Joints_Et_Consommables_Equerres_Aluminium_Moulees",
38
+ "Joints_Et_Consommables_Visserie_Inox_Alu",
39
+ "Poignee_Carre_7_mm",
40
+ "Poignee_Carre_8_mm",
41
+ "Poignee_Cremone",
42
+ "Poignee_Cuvette",
43
+ "Poignee_De_Tirage",
44
+ "Poignee_Pour_Levant_Coulissant",
45
+ "Serrure_Cremone_Multipoints",
46
+ "Serrure_Cuvette",
47
+ "Serrure_Gaches",
48
+ "Serrure_Loqueteau",
49
+ "Serrure_Pene_Crochet",
50
+ "Serrure_Pour_Porte",
51
+ "Serrure_Tringles"
52
+ ]
53
+
54
+ short_classes_list = [
55
+ "Anti-fausse-manoeuvre",
56
+ "Busettes",
57
+ "Butées",
58
+ "Chariots",
59
+ "Charnière",
60
+ "Compas-limiteur",
61
+ "Renvois d'angle",
62
+ "Cylindres",
63
+ "Gaches",
64
+ "Equerres aluminium moulées",
65
+ "Visserie inox alu",
66
+ "Poignée carré 7 mm",
67
+ "Poignée carré 8 mm",
68
+ "Poignée crémone",
69
+ "Poignée cuvette",
70
+ "Poignée de tirage",
71
+ "Poignée pour levant coulissant",
72
+ "Serrure crémone multipoints",
73
+ "Serrure cuvette",
74
+ "Serrure gaches",
75
+ "Serrure pene crochet",
76
+ "Serrure pour porte",
77
+ "Serrure tringles",
78
+ "Loqueteau",
79
+ ]
80
+
81
+ data_size = 384
82
+ fpn_size = 1536
83
+ num_classes = 23
84
+ num_selects = {'layer1': 256, 'layer2': 128, 'layer3': 64, 'layer4': 32}
85
+ features, grads, module_id_mapper = {}, {}, {}
86
+
87
+ def forward_hook(module, inp_hs, out_hs):
88
+ layer_id = len(features) + 1
89
+ module_id_mapper[module] = layer_id
90
+ features[layer_id] = {"in": inp_hs, "out": out_hs}
91
+
92
+ def backward_hook(module, inp_grad, out_grad):
93
+ layer_id = module_id_mapper[module]
94
+ grads[layer_id] = {"in": inp_grad, "out": out_grad}
95
+
96
+ def build_model(path: str):
97
+ backbone = timm.create_model('swin_large_patch4_window12_384_in22k', pretrained=True)
98
+ model = PluginMoodel(
99
+ backbone=backbone,
100
+ return_nodes=None,
101
+ img_size=data_size,
102
+ use_fpn=True,
103
+ fpn_size=fpn_size,
104
+ proj_type="Linear",
105
+ upsample_type="Conv",
106
+ use_selection=True,
107
+ num_classes=num_classes,
108
+ num_selects=num_selects,
109
+ use_combiner=True,
110
+ comb_proj_size=None
111
+ )
112
+ ckpt = torch.load(path, map_location="cpu", weights_only=False)
113
+ model.load_state_dict(ckpt["model"], strict=False)
114
+ model.eval()
115
+
116
+ for layer in [0, 1, 2, 3]:
117
+ model.backbone.layers[layer].register_forward_hook(forward_hook)
118
+ model.backbone.layers[layer].register_full_backward_hook(backward_hook)
119
+
120
+ for i in range(1, 5):
121
+ getattr(model.fpn_down, f'Proj_layer{i}').register_forward_hook(forward_hook)
122
+ getattr(model.fpn_down, f'Proj_layer{i}').register_full_backward_hook(backward_hook)
123
+ getattr(model.fpn_up, f'Proj_layer{i}').register_forward_hook(forward_hook)
124
+ getattr(model.fpn_up, f'Proj_layer{i}').register_full_backward_hook(backward_hook)
125
+
126
+ return model
127
+
128
+ class ImgLoader:
129
+ def __init__(self, img_size):
130
+ self.transform = transforms.Compose([
131
+ transforms.Resize((510, 510), Image.BILINEAR),
132
+ transforms.CenterCrop((img_size, img_size)),
133
+ transforms.ToTensor(),
134
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
135
+ ])
136
+
137
+ def load(self, input_img):
138
+ if isinstance(input_img, str):
139
+ ori_img = cv2.imread(input_img)
140
+ img = Image.fromarray(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB))
141
+ elif isinstance(input_img, Image.Image):
142
+ img = input_img
143
+ else:
144
+ raise ValueError("Image invalide")
145
+
146
+ if img.mode != "RGB":
147
+ img = img.convert("RGB")
148
+
149
+ return self.transform(img).unsqueeze(0)
150
+
151
+ def cal_backward(out) -> dict:
152
+ target_layer_names = ['layer1', 'layer2', 'layer3', 'layer4',
153
+ 'FPN1_layer1', 'FPN1_layer2', 'FPN1_layer3', 'FPN1_layer4', 'comb_outs']
154
+
155
+ sum_out = None
156
+ for name in target_layer_names:
157
+ tmp_out = out[name].mean(1) if name != "comb_outs" else out[name]
158
+ tmp_out = torch.softmax(tmp_out, dim=-1)
159
+ sum_out = tmp_out if sum_out is None else sum_out + tmp_out
160
+
161
+ with torch.no_grad():
162
+ smax = torch.softmax(sum_out, dim=-1)
163
+ A = np.transpose(np.matlib.repmat(smax[0], num_classes, 1)) - np.eye(num_classes)
164
+ _, _, V = np.linalg.svd(A, full_matrices=True)
165
+ V = V[num_classes - 1, :]
166
+ if V[0] < 0:
167
+ V = -V
168
+ V = np.log(V)
169
+ V = V - min(V)
170
+ V = V / sum(V)
171
+
172
+ top5_indices = np.argsort(-V)[:5]
173
+ top5_scores = -np.sort(-V)[:5]
174
+
175
+ # Construction du dictionnaire pour gr.Label
176
+ top5_dict = {classes_list[int(idx)]: float(f"{score:.4f}") for idx, score in zip(top5_indices, top5_scores)}
177
+ return top5_dict
178
+
179
+ # === Chargement du modèle
180
+ model = build_model("weights.pt")
181
+ img_loader = ImgLoader(data_size)
182
+
183
+
184
+
185
+ def predict_image(image: Image.Image):
186
+ global features, grads, module_id_mapper
187
+ features, grads, module_id_mapper = {}, {}, {}
188
+
189
+ if image is None:
190
+ return {}
191
+ # raise ValueError("Aucune image reçue. Vérifie l'entrée.")
192
+
193
+ if image.mode != "RGB":
194
+ image = image.convert("RGB")
195
+
196
+ image_path = "temp.jpg"
197
+ image.save(image_path)
198
+
199
+ img_tensor = img_loader.load(image_path)
200
+ out = model(img_tensor)
201
+ top5_dict = cal_backward(out) # {classe: score}
202
+
203
+ gallery_outputs = []
204
+ for idx, class_name in enumerate(list(top5_dict.keys())):
205
+ images = [
206
+ (f"imgs/{class_name}/{class_name}_0001.jpg", f"Exemple {class_name} 1"),
207
+ (f"imgs/{class_name}/{class_name}_0002.jpg", f"Exemple {class_name} 2"),
208
+ (f"imgs/{class_name}/{class_name}_0003.jpg", f"Exemple {class_name} 3"),
209
+ ]
210
+ gallery_outputs.append(images)
211
+
212
+ return top5_dict, *gallery_outputs
213
+
214
+
215
+ # === Interface Gradio
216
+ with gr.Blocks(css="""
217
+ .gr-image-upload { display: none !important }
218
+ .gallery-container .gr-box { height: auto !important; padding: 0 !important; }
219
+ """) as demo:
220
+ with gr.Row():
221
+ with gr.Column(scale=1):
222
+ with gr.Tab("Téléversement"):
223
+ image_input_upload = gr.Image(type="pil", label="Image à classer (upload)", sources=["upload"])
224
+ with gr.Tab("Webcam"):
225
+ image_input_webcam = gr.Image(type="pil", label="Image à classer (webcam)", sources=["webcam"])
226
+
227
+ with gr.Column(scale=1.5):
228
+ label_output = gr.Label(label="Prédictions")
229
+ gallery_outputs = [
230
+ gr.Gallery(label=f"", columns=3, height=300, container=True, elem_classes=["gallery-container"])
231
+ for i in range(5)
232
+ ]
233
+
234
+ image_input_upload.change(fn=predict_image, inputs=image_input_upload, outputs=[label_output] + gallery_outputs)
235
+ image_input_webcam.change(fn=predict_image, inputs=image_input_webcam, outputs=[label_output] + gallery_outputs)
236
+
237
+ if __name__ == "__main__":
238
+ demo.launch()
239
+
pim_module.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torchvision.models as models
4
+ import torch.nn.functional as F
5
+ from torchvision.models.feature_extraction import get_graph_node_names
6
+ from torchvision.models.feature_extraction import create_feature_extractor
7
+ from typing import Union
8
+ import copy
9
+
10
+ class GCNCombiner(nn.Module):
11
+
12
+ def __init__(self,
13
+ total_num_selects: int,
14
+ num_classes: int,
15
+ inputs: Union[dict, None] = None,
16
+ proj_size: Union[int, None] = None,
17
+ fpn_size: Union[int, None] = None):
18
+ """
19
+ If building backbone without FPN, set fpn_size to None and MUST give
20
+ 'inputs' and 'proj_size', the reason of these setting is to constrain the
21
+ dimension of graph convolutional network input.
22
+ """
23
+ super(GCNCombiner, self).__init__()
24
+
25
+ assert inputs is not None or fpn_size is not None, \
26
+ "To build GCN combiner, you must give one features dimension."
27
+
28
+ ### auto-proj
29
+ self.fpn_size = fpn_size
30
+ if fpn_size is None:
31
+ for name in inputs:
32
+ if len(name) == 4:
33
+ in_size = inputs[name].size(1)
34
+ elif len(name) == 3:
35
+ in_size = inputs[name].size(2)
36
+ else:
37
+ raise ValusError("The size of output dimension of previous must be 3 or 4.")
38
+ m = nn.Sequential(
39
+ nn.Linear(in_size, proj_size),
40
+ nn.ReLU(),
41
+ nn.Linear(proj_size, proj_size)
42
+ )
43
+ self.add_module("proj_"+name, m)
44
+ self.proj_size = proj_size
45
+ else:
46
+ self.proj_size = fpn_size
47
+
48
+ ### build one layer structure (with adaptive module)
49
+ num_joints = total_num_selects // 64
50
+
51
+ self.param_pool0 = nn.Linear(total_num_selects, num_joints)
52
+
53
+ A = torch.eye(num_joints) / 100 + 1 / 100
54
+ self.adj1 = nn.Parameter(copy.deepcopy(A))
55
+ self.conv1 = nn.Conv1d(self.proj_size, self.proj_size, 1)
56
+ self.batch_norm1 = nn.BatchNorm1d(self.proj_size)
57
+
58
+ self.conv_q1 = nn.Conv1d(self.proj_size, self.proj_size//4, 1)
59
+ self.conv_k1 = nn.Conv1d(self.proj_size, self.proj_size//4, 1)
60
+ self.alpha1 = nn.Parameter(torch.zeros(1))
61
+
62
+ ### merge information
63
+ self.param_pool1 = nn.Linear(num_joints, 1)
64
+
65
+ #### class predict
66
+ self.dropout = nn.Dropout(p=0.1)
67
+ self.classifier = nn.Linear(self.proj_size, num_classes)
68
+
69
+ self.tanh = nn.Tanh()
70
+
71
+ def forward(self, x):
72
+ """
73
+ """
74
+ hs = []
75
+ names = []
76
+ for name in x:
77
+ if "FPN1_" in name:
78
+ continue
79
+ if self.fpn_size is None:
80
+ _tmp = getattr(self, "proj_"+name)(x[name])
81
+ else:
82
+ _tmp = x[name]
83
+ hs.append(_tmp)
84
+ names.append([name, _tmp.size()])
85
+
86
+ hs = torch.cat(hs, dim=1).transpose(1, 2).contiguous() # B, S', C --> B, C, S
87
+ # print(hs.size(), names)
88
+ hs = self.param_pool0(hs)
89
+ ### adaptive adjacency
90
+ q1 = self.conv_q1(hs).mean(1)
91
+ k1 = self.conv_k1(hs).mean(1)
92
+ A1 = self.tanh(q1.unsqueeze(-1) - k1.unsqueeze(1))
93
+ A1 = self.adj1 + A1 * self.alpha1
94
+ ### graph convolution
95
+ hs = self.conv1(hs)
96
+ hs = torch.matmul(hs, A1)
97
+ hs = self.batch_norm1(hs)
98
+ ### predict
99
+ hs = self.param_pool1(hs)
100
+ hs = self.dropout(hs)
101
+ hs = hs.flatten(1)
102
+ hs = self.classifier(hs)
103
+
104
+ return hs
105
+
106
+ class WeaklySelector(nn.Module):
107
+
108
+ def __init__(self, inputs: dict, num_classes: int, num_select: dict, fpn_size: Union[int, None] = None):
109
+ """
110
+ inputs: dictionary contain torch.Tensors, which comes from backbone
111
+ [Tensor1(hidden feature1), Tensor2(hidden feature2)...]
112
+ Please note that if len(features.size) equal to 3, the order of dimension must be [B,S,C],
113
+ S mean the spatial domain, and if len(features.size) equal to 4, the order must be [B,C,H,W]
114
+ """
115
+ super(WeaklySelector, self).__init__()
116
+
117
+ self.num_select = num_select
118
+
119
+ self.fpn_size = fpn_size
120
+ ### build classifier
121
+ if self.fpn_size is None:
122
+ self.num_classes = num_classes
123
+ for name in inputs:
124
+ fs_size = inputs[name].size()
125
+ if len(fs_size) == 3:
126
+ in_size = fs_size[2]
127
+ elif len(fs_size) == 4:
128
+ in_size = fs_size[1]
129
+ m = nn.Linear(in_size, num_classes)
130
+ self.add_module("classifier_l_"+name, m)
131
+
132
+ self.thresholds = {}
133
+ for name in inputs:
134
+ self.thresholds[name] = []
135
+
136
+ # def select(self, logits, l_name):
137
+ # """
138
+ # logits: [B, S, num_classes]
139
+ # """
140
+ # probs = torch.softmax(logits, dim=-1)
141
+ # scores, _ = torch.max(probs, dim=-1)
142
+ # _, ids = torch.sort(scores, -1, descending=True)
143
+ # sn = self.num_select[l_name]
144
+ # s_ids = ids[:, :sn]
145
+ # not_s_ids = ids[:, sn:]
146
+ # return s_ids.unsqueeze(-1), not_s_ids.unsqueeze(-1)
147
+
148
+ def forward(self, x, logits=None):
149
+ """
150
+ x :
151
+ dictionary contain the features maps which
152
+ come from your choosen layers.
153
+ size must be [B, HxW, C] ([B, S, C]) or [B, C, H, W].
154
+ [B,C,H,W] will be transpose to [B, HxW, C] automatically.
155
+ """
156
+ if self.fpn_size is None:
157
+ logits = {}
158
+ selections = {}
159
+ for name in x:
160
+ # print("[selector]", name, x[name].size())
161
+ if "FPN1_" in name:
162
+ continue
163
+ if len(x[name].size()) == 4:
164
+ B, C, H, W = x[name].size()
165
+ x[name] = x[name].view(B, C, H*W).permute(0, 2, 1).contiguous()
166
+ C = x[name].size(-1)
167
+ if self.fpn_size is None:
168
+ logits[name] = getattr(self, "classifier_l_"+name)(x[name])
169
+
170
+ probs = torch.softmax(logits[name], dim=-1)
171
+ sum_probs = torch.softmax(logits[name].mean(1), dim=-1)
172
+ selections[name] = []
173
+ preds_1 = []
174
+ preds_0 = []
175
+ num_select = self.num_select[name]
176
+ for bi in range(logits[name].size(0)):
177
+ _, max_ids = torch.max(sum_probs[bi], dim=-1)
178
+ confs, ranks = torch.sort(probs[bi, :, max_ids], descending=True)
179
+ sf = x[name][bi][ranks[:num_select]]
180
+ nf = x[name][bi][ranks[num_select:]] # calculate
181
+ selections[name].append(sf) # [num_selected, C]
182
+ preds_1.append(logits[name][bi][ranks[:num_select]])
183
+ preds_0.append(logits[name][bi][ranks[num_select:]])
184
+
185
+ if bi >= len(self.thresholds[name]):
186
+ self.thresholds[name].append(confs[num_select]) # for initialize
187
+ else:
188
+ self.thresholds[name][bi] = confs[num_select]
189
+
190
+ selections[name] = torch.stack(selections[name])
191
+ preds_1 = torch.stack(preds_1)
192
+ preds_0 = torch.stack(preds_0)
193
+
194
+ logits["select_"+name] = preds_1
195
+ logits["drop_"+name] = preds_0
196
+
197
+ return selections
198
+
199
+
200
+ class FPN(nn.Module):
201
+
202
+ def __init__(self, inputs: dict, fpn_size: int, proj_type: str, upsample_type: str):
203
+ """
204
+ inputs : dictionary contains torch.Tensor
205
+ which comes from backbone output
206
+ fpn_size: integer, fpn
207
+ proj_type:
208
+ in ["Conv", "Linear"]
209
+ upsample_type:
210
+ in ["Bilinear", "Conv", "Fc"]
211
+ for convolution neural network (e.g. ResNet, EfficientNet), recommand 'Bilinear'.
212
+ for Vit, "Fc". and Swin-T, "Conv"
213
+ """
214
+ super(FPN, self).__init__()
215
+ assert proj_type in ["Conv", "Linear"], \
216
+ "FPN projection type {} were not support yet, please choose type 'Conv' or 'Linear'".format(proj_type)
217
+ assert upsample_type in ["Bilinear", "Conv"], \
218
+ "FPN upsample type {} were not support yet, please choose type 'Bilinear' or 'Conv'".format(proj_type)
219
+
220
+ self.fpn_size = fpn_size
221
+ self.upsample_type = upsample_type
222
+ inp_names = [name for name in inputs]
223
+
224
+ for i, node_name in enumerate(inputs):
225
+ ### projection module
226
+ if proj_type == "Conv":
227
+ m = nn.Sequential(
228
+ nn.Conv2d(inputs[node_name].size(1), inputs[node_name].size(1), 1),
229
+ nn.ReLU(),
230
+ nn.Conv2d(inputs[node_name].size(1), fpn_size, 1)
231
+ )
232
+ elif proj_type == "Linear":
233
+ in_feat = inputs[node_name]
234
+ if isinstance(in_feat, torch.Tensor):
235
+ dim = in_feat.size(-1)
236
+ else:
237
+ raise ValueError(f"Entrée invalide dans FPN: {type(in_feat)} pour node_name={node_name}")
238
+
239
+ m = nn.Sequential(
240
+ nn.Linear(dim, dim),
241
+ nn.ReLU(),
242
+ nn.Linear(dim, fpn_size),
243
+ )
244
+
245
+ self.add_module("Proj_"+node_name, m)
246
+
247
+ ### upsample module
248
+ if upsample_type == "Conv" and i != 0:
249
+ assert len(inputs[node_name].size()) == 3 # B, S, C
250
+ in_dim = inputs[node_name].size(1)
251
+ out_dim = inputs[inp_names[i-1]].size(1)
252
+ # if in_dim != out_dim:
253
+ m = nn.Conv1d(in_dim, out_dim, 1) # for spatial domain
254
+ # else:
255
+ # m = nn.Identity()
256
+ self.add_module("Up_"+node_name, m)
257
+
258
+ if upsample_type == "Bilinear":
259
+ self.upsample = nn.Upsample(scale_factor=2, mode='bilinear')
260
+
261
+ def upsample_add(self, x0: torch.Tensor, x1: torch.Tensor, x1_name: str):
262
+ """
263
+ return Upsample(x1) + x1
264
+ """
265
+ if self.upsample_type == "Bilinear":
266
+ if x1.size(-1) != x0.size(-1):
267
+ x1 = self.upsample(x1)
268
+ else:
269
+ x1 = getattr(self, "Up_"+x1_name)(x1)
270
+ return x1 + x0
271
+
272
+ def forward(self, x):
273
+ """
274
+ x : dictionary
275
+ {
276
+ "node_name1": feature1,
277
+ "node_name2": feature2, ...
278
+ }
279
+ """
280
+ ### project to same dimension
281
+ hs = []
282
+ for i, name in enumerate(x):
283
+ if "FPN1_" in name:
284
+ continue
285
+ x[name] = getattr(self, "Proj_"+name)(x[name])
286
+ hs.append(name)
287
+
288
+ x["FPN1_" + "layer4"] = x["layer4"]
289
+
290
+ for i in range(len(hs)-1, 0, -1):
291
+ x1_name = hs[i]
292
+ x0_name = hs[i-1]
293
+ x[x0_name] = self.upsample_add(x[x0_name],
294
+ x[x1_name],
295
+ x1_name)
296
+ x["FPN1_" + x0_name] = x[x0_name]
297
+
298
+ return x
299
+
300
+
301
+ class FPN_UP(nn.Module):
302
+
303
+ def __init__(self,
304
+ inputs: dict,
305
+ fpn_size: int):
306
+ super(FPN_UP, self).__init__()
307
+
308
+ inp_names = [name for name in inputs]
309
+
310
+ for i, node_name in enumerate(inputs):
311
+ ### projection module
312
+ m = nn.Sequential(
313
+ nn.Linear(fpn_size, fpn_size),
314
+ nn.ReLU(),
315
+ nn.Linear(fpn_size, fpn_size),
316
+ )
317
+ self.add_module("Proj_"+node_name, m)
318
+
319
+ ### upsample module
320
+ if i != (len(inputs) - 1):
321
+ assert len(inputs[node_name].size()) == 3 # B, S, C
322
+ in_dim = inputs[node_name].size(1)
323
+ out_dim = inputs[inp_names[i+1]].size(1)
324
+ m = nn.Conv1d(in_dim, out_dim, 1) # for spatial domain
325
+ self.add_module("Down_"+node_name, m)
326
+ # print("Down_"+node_name, in_dim, out_dim)
327
+ """
328
+ Down_layer1 2304 576
329
+ Down_layer2 576 144
330
+ Down_layer3 144 144
331
+ """
332
+
333
+ def downsample_add(self, x0: torch.Tensor, x1: torch.Tensor, x0_name: str):
334
+ """
335
+ return Upsample(x1) + x1
336
+ """
337
+ # print("[downsample_add] Down_" + x0_name)
338
+ x0 = getattr(self, "Down_" + x0_name)(x0)
339
+ return x1 + x0
340
+
341
+ def forward(self, x):
342
+ """
343
+ x : dictionary
344
+ {
345
+ "node_name1": feature1,
346
+ "node_name2": feature2, ...
347
+ }
348
+ """
349
+ ### project to same dimension
350
+ hs = []
351
+ for i, name in enumerate(x):
352
+ if "FPN1_" in name:
353
+ continue
354
+ x[name] = getattr(self, "Proj_"+name)(x[name])
355
+ hs.append(name)
356
+
357
+ # print(hs)
358
+ for i in range(0, len(hs) - 1):
359
+ x0_name = hs[i]
360
+ x1_name = hs[i+1]
361
+ # print(x0_name, x1_name)
362
+ # print(x[x0_name].size(), x[x1_name].size())
363
+ x[x1_name] = self.downsample_add(x[x0_name],
364
+ x[x1_name],
365
+ x0_name)
366
+ return x
367
+
368
+
369
+
370
+
371
+ class PluginMoodel(nn.Module):
372
+
373
+ def __init__(self,
374
+ backbone: torch.nn.Module,
375
+ return_nodes: Union[dict, None],
376
+ img_size: int,
377
+ use_fpn: bool,
378
+ fpn_size: Union[int, None],
379
+ proj_type: str,
380
+ upsample_type: str,
381
+ use_selection: bool,
382
+ num_classes: int,
383
+ num_selects: dict,
384
+ use_combiner: bool,
385
+ comb_proj_size: Union[int, None]
386
+ ):
387
+ """
388
+ * backbone:
389
+ torch.nn.Module class (recommand pretrained on ImageNet or IG-3.5B-17k(provided by FAIR))
390
+ * return_nodes:
391
+ e.g.
392
+ return_nodes = {
393
+ # node_name: user-specified key for output dict
394
+ 'layer1.2.relu_2': 'layer1',
395
+ 'layer2.3.relu_2': 'layer2',
396
+ 'layer3.5.relu_2': 'layer3',
397
+ 'layer4.2.relu_2': 'layer4',
398
+ } # you can see the example on https://pytorch.org/vision/main/feature_extraction.html
399
+ !!! if using 'Swin-Transformer', please set return_nodes to None
400
+ !!! and please set use_fpn to True
401
+ * feat_sizes:
402
+ tuple or list contain features map size of each layers.
403
+ ((C, H, W)). e.g. ((1024, 14, 14), (2048, 7, 7))
404
+ * use_fpn:
405
+ boolean, use features pyramid network or not
406
+ * fpn_size:
407
+ integer, features pyramid network projection dimension
408
+ * num_selects:
409
+ num_selects = {
410
+ # match user-specified in return_nodes
411
+ "layer1": 2048,
412
+ "layer2": 512,
413
+ "layer3": 128,
414
+ "layer4": 32,
415
+ }
416
+ Note: after selector module (WeaklySelector) , the feature map's size is [B, S', C] which
417
+ contained by 'logits' or 'selections' dictionary (S' is selection number, different layer
418
+ could be different).
419
+ """
420
+ super(PluginMoodel, self).__init__()
421
+
422
+ ### = = = = = Backbone = = = = =
423
+ self.return_nodes = return_nodes
424
+ if return_nodes is not None:
425
+ self.backbone = create_feature_extractor(backbone, return_nodes=return_nodes)
426
+ else:
427
+ self.backbone = backbone
428
+
429
+ ### get hidden feartues size
430
+ rand_in = torch.randn(1, 3, img_size, img_size)
431
+ outs = self.backbone(rand_in)
432
+
433
+ ### just original backbone
434
+ if not use_fpn and (not use_selection and not use_combiner):
435
+ for name in outs:
436
+ fs_size = outs[name].size()
437
+ if len(fs_size) == 3:
438
+ out_size = fs_size.size(-1)
439
+ elif len(fs_size) == 4:
440
+ out_size = fs_size.size(1)
441
+ else:
442
+ raise ValusError("The size of output dimension of previous must be 3 or 4.")
443
+ self.classifier = nn.Linear(out_size, num_classes)
444
+
445
+ ### = = = = = FPN = = = = =
446
+ self.use_fpn = use_fpn
447
+ if self.use_fpn:
448
+ self.fpn_down = FPN(outs, fpn_size, proj_type, upsample_type)
449
+ self.build_fpn_classifier_down(outs, fpn_size, num_classes)
450
+ self.fpn_up = FPN_UP(outs, fpn_size)
451
+ self.build_fpn_classifier_up(outs, fpn_size, num_classes)
452
+
453
+ self.fpn_size = fpn_size
454
+
455
+ ### = = = = = Selector = = = = =
456
+ self.use_selection = use_selection
457
+ if self.use_selection:
458
+ w_fpn_size = self.fpn_size if self.use_fpn else None # if not using fpn, build classifier in weakly selector
459
+ self.selector = WeaklySelector(outs, num_classes, num_selects, w_fpn_size)
460
+
461
+ ### = = = = = Combiner = = = = =
462
+ self.use_combiner = use_combiner
463
+ if self.use_combiner:
464
+ assert self.use_selection, "Please use selection module before combiner"
465
+ if self.use_fpn:
466
+ gcn_inputs, gcn_proj_size = None, None
467
+ else:
468
+ gcn_inputs, gcn_proj_size = outs, comb_proj_size # redundant, fix in future
469
+ total_num_selects = sum([num_selects[name] for name in num_selects]) # sum
470
+ self.combiner = GCNCombiner(total_num_selects, num_classes, gcn_inputs, gcn_proj_size, self.fpn_size)
471
+
472
+ def build_fpn_classifier_up(self, inputs: dict, fpn_size: int, num_classes: int):
473
+ """
474
+ Teh results of our experiments show that linear classifier in this case may cause some problem.
475
+ """
476
+ for name in inputs:
477
+ m = nn.Sequential(
478
+ nn.Conv1d(fpn_size, fpn_size, 1),
479
+ nn.BatchNorm1d(fpn_size),
480
+ nn.ReLU(),
481
+ nn.Conv1d(fpn_size, num_classes, 1)
482
+ )
483
+ self.add_module("fpn_classifier_up_"+name, m)
484
+
485
+ def build_fpn_classifier_down(self, inputs: dict, fpn_size: int, num_classes: int):
486
+ """
487
+ Teh results of our experiments show that linear classifier in this case may cause some problem.
488
+ """
489
+ for name in inputs:
490
+ m = nn.Sequential(
491
+ nn.Conv1d(fpn_size, fpn_size, 1),
492
+ nn.BatchNorm1d(fpn_size),
493
+ nn.ReLU(),
494
+ nn.Conv1d(fpn_size, num_classes, 1)
495
+ )
496
+ self.add_module("fpn_classifier_down_" + name, m)
497
+
498
+ def forward_backbone(self, x):
499
+ return self.backbone(x)
500
+
501
+ def fpn_predict_down(self, x: dict, logits: dict):
502
+ """
503
+ x: [B, C, H, W] or [B, S, C]
504
+ [B, C, H, W] --> [B, H*W, C]
505
+ """
506
+ for name in x:
507
+ if "FPN1_" not in name:
508
+ continue
509
+ ### predict on each features point
510
+ if len(x[name].size()) == 4:
511
+ B, C, H, W = x[name].size()
512
+ logit = x[name].view(B, C, H*W)
513
+ elif len(x[name].size()) == 3:
514
+ logit = x[name].transpose(1, 2).contiguous()
515
+ model_name = name.replace("FPN1_", "")
516
+ logits[name] = getattr(self, "fpn_classifier_down_" + model_name)(logit)
517
+ logits[name] = logits[name].transpose(1, 2).contiguous() # transpose
518
+
519
+ def fpn_predict_up(self, x: dict, logits: dict):
520
+ """
521
+ x: [B, C, H, W] or [B, S, C]
522
+ [B, C, H, W] --> [B, H*W, C]
523
+ """
524
+ for name in x:
525
+ if "FPN1_" in name:
526
+ continue
527
+ ### predict on each features point
528
+ if len(x[name].size()) == 4:
529
+ B, C, H, W = x[name].size()
530
+ logit = x[name].view(B, C, H*W)
531
+ elif len(x[name].size()) == 3:
532
+ logit = x[name].transpose(1, 2).contiguous()
533
+ model_name = name.replace("FPN1_", "")
534
+ logits[name] = getattr(self, "fpn_classifier_up_" + model_name)(logit)
535
+ logits[name] = logits[name].transpose(1, 2).contiguous() # transpose
536
+
537
+ def forward(self, x: torch.Tensor):
538
+
539
+ logits = {}
540
+
541
+ x = self.forward_backbone(x)
542
+
543
+ if self.use_fpn:
544
+ x = self.fpn_down(x)
545
+ # print([name for name in x])
546
+ self.fpn_predict_down(x, logits)
547
+ x = self.fpn_up(x)
548
+ self.fpn_predict_up(x, logits)
549
+
550
+ if self.use_selection:
551
+ selects = self.selector(x, logits)
552
+
553
+ if self.use_combiner:
554
+ comb_outs = self.combiner(selects)
555
+ logits['comb_outs'] = comb_outs
556
+ return logits
557
+
558
+ if self.use_selection or self.fpn:
559
+ return logits
560
+
561
+ ### original backbone (only predict final selected layer)
562
+ for name in x:
563
+ hs = x[name]
564
+
565
+ if len(hs.size()) == 4:
566
+ hs = F.adaptive_avg_pool2d(hs, (1, 1))
567
+ hs = hs.flatten(1)
568
+ else:
569
+ hs = hs.mean(1)
570
+ out = self.classifier(hs)
571
+ logits['ori_out'] = logits
572
+
573
+ return
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gdown
2
+ gradio==4.25.0
3
+ torch
4
+ torchvision
5
+ timm
6
+ opencv-python
7
+ numpy
8
+ pillow
9
+ requests