| 79 | |
| 80 | |
| 81 | class Transformer(nn.Module): |
| 82 | def __init__(self, |
| 83 | context_length: int, |
| 84 | vocab_size: int, |
| 85 | width: int, |
| 86 | layers: int, |
| 87 | heads: int, |
| 88 | drop_path: float = 0.0, |
| 89 | autogressive: bool =True): |
| 90 | super().__init__() |
| 91 | |
| 92 | self.token_embedding = nn.Embedding(vocab_size, width) |
| 93 | |
| 94 | self.context_length = context_length |
| 95 | self.positional_embedding = nn.Parameter( |
| 96 | torch.empty(self.context_length, width) |
| 97 | ) |
| 98 | |
| 99 | self.width = width |
| 100 | self.layers = layers |
| 101 | self.autogressive = autogressive |
| 102 | attn_mask = self.build_attention_mask() if autogressive else None |
| 103 | dpr = [x.item() for x in torch.linspace(0, drop_path, layers)] # stochastic depth decay rule |
| 104 | self.resblocks = nn.ModuleList( |
| 105 | [ |
| 106 | ResidualAttentionBlock(width, heads, attn_mask, dpr[i]) |
| 107 | for i in range(layers) |
| 108 | ] |
| 109 | ) |
| 110 | |
| 111 | self.ln_final = LayerNorm(width) |
| 112 | |
| 113 | trunc_normal_(self.positional_embedding, std=.02) |
| 114 | # nn.init.normal_(self.token_embedding, std=.02) |
| 115 | trunc_normal_(self.token_embedding.weight, std=.02) |
| 116 | self.apply(self._init_weights) |
| 117 | |
| 118 | @property |
| 119 | def dim_out(self): |
| 120 | return self.width |
| 121 | |
| 122 | def build_attention_mask(self): |
| 123 | # lazily create causal attention mask, with full attention between the vision tokens |
| 124 | # pytorch uses additive attention mask; fill with -inf |
| 125 | mask = torch.empty(self.context_length, self.context_length) |
| 126 | mask.fill_(float("-inf")) |
| 127 | mask.triu_(1) # zero out the lower diagonal |
| 128 | return mask |
| 129 | |
| 130 | def _init_weights(self, m): |
| 131 | if isinstance(m, (nn.Linear, nn.Conv2d)): |
| 132 | if is_main_process(): |
| 133 | logger.info('=> init weight of Linear/Conv2d from trunc norm') |
| 134 | trunc_normal_(m.weight, std=0.02) |
| 135 | if m.bias is not None: |
| 136 | if is_main_process(): |
| 137 | logger.info('=> init bias of Linear/Conv2d to zeros') |
| 138 | nn.init.constant_(m.bias, 0) |