(self)
| 287 | return getattr(self, self.norm1_name) |
| 288 | |
| 289 | def init_weights(self): |
| 290 | if isinstance(self.init_cfg, dict) and self.init_cfg.get("type") == "Pretrained": |
| 291 | logger = get_root_logger() |
| 292 | checkpoint = CheckpointLoader.load_checkpoint( |
| 293 | self.init_cfg["checkpoint"], logger=logger, map_location="cpu" |
| 294 | ) |
| 295 | |
| 296 | if "state_dict" in checkpoint: |
| 297 | state_dict = checkpoint["state_dict"] |
| 298 | else: |
| 299 | state_dict = checkpoint |
| 300 | |
| 301 | if "pos_embed" in state_dict.keys(): |
| 302 | if self.pos_embed.shape != state_dict["pos_embed"].shape: |
| 303 | logger.info( |
| 304 | msg=f"Resize the pos_embed shape from " |
| 305 | f"{state_dict['pos_embed'].shape} to " |
| 306 | f"{self.pos_embed.shape}" |
| 307 | ) |
| 308 | h, w = self.img_size |
| 309 | pos_size = int(math.sqrt(state_dict["pos_embed"].shape[1] - 1)) |
| 310 | state_dict["pos_embed"] = self.resize_pos_embed( |
| 311 | state_dict["pos_embed"], |
| 312 | (h // self.patch_size, w // self.patch_size), |
| 313 | (pos_size, pos_size), |
| 314 | self.interpolate_mode, |
| 315 | ) |
| 316 | |
| 317 | load_state_dict(self, state_dict, strict=False, logger=logger) |
| 318 | elif self.init_cfg is not None: |
| 319 | super(VisionTransformer, self).init_weights() |
| 320 | else: |
| 321 | # We only implement the 'jax_impl' initialization implemented at |
| 322 | # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py#L353 # noqa: E501 |
| 323 | trunc_normal_(self.pos_embed, std=0.02) |
| 324 | trunc_normal_(self.cls_token, std=0.02) |
| 325 | for n, m in self.named_modules(): |
| 326 | if isinstance(m, nn.Linear): |
| 327 | trunc_normal_(m.weight, std=0.02) |
| 328 | if m.bias is not None: |
| 329 | if "ffn" in n: |
| 330 | nn.init.normal_(m.bias, mean=0.0, std=1e-6) |
| 331 | else: |
| 332 | nn.init.constant_(m.bias, 0) |
| 333 | elif isinstance(m, nn.Conv2d): |
| 334 | kaiming_init(m, mode="fan_in", bias=0.0) |
| 335 | elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)): |
| 336 | constant_init(m, val=1.0, bias=0.0) |
| 337 | |
| 338 | def _pos_embeding(self, patched_img, hw_shape, pos_embed): |
| 339 | """Positioning embeding method. |
nothing calls this directly
no test coverage detected