| 389 | _load_weights(self, checkpoint_path, prefix) |
| 390 | |
| 391 | def forward_features(self, x, inference_params=None, if_random_cls_token_position=False, if_random_token_rank=False): |
| 392 | # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py |
| 393 | # with slight modifications to add the dist_token |
| 394 | x = self.patch_embed(x) |
| 395 | B, M, _ = x.shape |
| 396 | |
| 397 | if self.if_cls_token: |
| 398 | if self.use_double_cls_token: |
| 399 | cls_token_head = self.cls_token_head.expand(B, -1, -1) |
| 400 | cls_token_tail = self.cls_token_tail.expand(B, -1, -1) |
| 401 | token_position = [0, M + 1] |
| 402 | x = torch.cat((cls_token_head, x, cls_token_tail), dim=1) |
| 403 | M = x.shape[1] |
| 404 | else: |
| 405 | if self.use_middle_cls_token: |
| 406 | cls_token = self.cls_token.expand(B, -1, -1) |
| 407 | token_position = M // 2 |
| 408 | # add cls token in the middle |
| 409 | x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1) |
| 410 | elif if_random_cls_token_position: |
| 411 | cls_token = self.cls_token.expand(B, -1, -1) |
| 412 | token_position = random.randint(0, M) |
| 413 | x = torch.cat((x[:, :token_position, :], cls_token, x[:, token_position:, :]), dim=1) |
| 414 | print("token_position: ", token_position) |
| 415 | else: |
| 416 | cls_token = self.cls_token.expand(B, -1, -1) # stole cls_tokens impl from Phil Wang, thanks |
| 417 | token_position = 0 |
| 418 | x = torch.cat((cls_token, x), dim=1) |
| 419 | M = x.shape[1] # Tokens Number |
| 420 | |
| 421 | if self.if_abs_pos_embed: |
| 422 | # if new_grid_size[0] == self.patch_embed.grid_size[0] and new_grid_size[1] == self.patch_embed.grid_size[1]: |
| 423 | # x = x + self.pos_embed |
| 424 | # else: |
| 425 | # pos_embed = interpolate_pos_embed_online( |
| 426 | # self.pos_embed, self.patch_embed.grid_size, new_grid_size,0 |
| 427 | # ) |
| 428 | x = x + self.pos_embed |
| 429 | x = self.pos_drop(x) |
| 430 | |
| 431 | if if_random_token_rank: |
| 432 | |
| 433 | # 生成随机 shuffle 索引 |
| 434 | shuffle_indices = torch.randperm(M) |
| 435 | |
| 436 | if isinstance(token_position, list): |
| 437 | print("original value: ", x[0, token_position[0], 0], x[0, token_position[1], 0]) |
| 438 | else: |
| 439 | print("original value: ", x[0, token_position, 0]) |
| 440 | print("original token_position: ", token_position) |
| 441 | |
| 442 | # 执行 shuffle |
| 443 | x = x[:, shuffle_indices, :] |
| 444 | |
| 445 | if isinstance(token_position, list): |
| 446 | # 找到 cls token 在 shuffle 之后的新位置 |
| 447 | new_token_position = [torch.where(shuffle_indices == token_position[i])[0].item() for i in range(len(token_position))] |
| 448 | token_position = new_token_position |