| 328 | |
| 329 | |
| 330 | class Attribute_Classifier(nn.Module): |
| 331 | def __init__(self, dict_attribute, in_dim, projected_dim, norm_type='bn', use_independent_projection=True): |
| 332 | super().__init__() |
| 333 | print(dict_attribute) |
| 334 | self.num_attribute_class = len(dict_attribute.keys()) |
| 335 | self.num_attribute_all = sum([len(v) for v in dict_attribute.values()]) |
| 336 | self.classifier_list = nn.ModuleList() |
| 337 | self._log_softmax = nn.LogSoftmax(dim=1) |
| 338 | if norm_type is None or norm_type == 'none': |
| 339 | use_norm = False |
| 340 | elif norm_type == 'bn': |
| 341 | norm_class = nn.BatchNorm1d |
| 342 | use_norm = True |
| 343 | elif norm_type == 'ln': |
| 344 | norm_class = nn.LayerNorm |
| 345 | use_norm = True |
| 346 | else: |
| 347 | raise NotImplementedError |
| 348 | |
| 349 | if use_independent_projection: |
| 350 | self.shared_projected_layer = None |
| 351 | else: |
| 352 | if use_norm: |
| 353 | self.shared_projected_layer = nn.Sequential(nn.Linear(in_dim, projected_dim * 2), |
| 354 | norm_class(projected_dim * 2), |
| 355 | nn.GELU(), |
| 356 | nn.Linear(projected_dim * 2, projected_dim), |
| 357 | norm_class(projected_dim), |
| 358 | ) |
| 359 | else: |
| 360 | self.shared_projected_layer = nn.Sequential(nn.Linear(in_dim, projected_dim * 2), |
| 361 | nn.GELU(), |
| 362 | nn.Linear(projected_dim * 2, projected_dim) |
| 363 | ) |
| 364 | |
| 365 | for key in dict_attribute.keys(): |
| 366 | if use_independent_projection: |
| 367 | layers = [nn.Linear(in_dim, projected_dim)] |
| 368 | if use_norm: |
| 369 | layers.append(norm_class(projected_dim)) |
| 370 | layers.append(nn.GELU()) |
| 371 | layers.append(nn.Linear(projected_dim, len(dict_attribute[key]) + 1)) # 1 for no present |
| 372 | self.classifier_list.append(nn.Sequential(*layers)) |
| 373 | else: |
| 374 | _classifier = nn.Linear(projected_dim, len(dict_attribute[key]) + 1) # 1 for no present |
| 375 | self.classifier_list.append(_classifier) |
| 376 | self.apply(self._init_weights) |
| 377 | |
| 378 | def _init_weights(self, m): |
| 379 | if isinstance(m, nn.Linear): |
| 380 | trunc_normal_(m.weight, std=.02) |
| 381 | if isinstance(m, nn.Linear) and m.bias is not None: |
| 382 | nn.init.constant_(m.bias, 0) |
| 383 | |
| 384 | def forward(self, x): |
| 385 | probability = [] |
| 386 | if self.shared_projected_layer is None: |
| 387 | attribute_embedding = [] |
nothing calls this directly
no outgoing calls
no test coverage detected