| 40 | |
| 41 | |
| 42 | class TextEncoder(nn.Module): |
| 43 | def __init__(self, clip_model): |
| 44 | super().__init__() |
| 45 | self.transformer = clip_model.transformer |
| 46 | self.positional_embedding = clip_model.positional_embedding |
| 47 | self.ln_final = clip_model.ln_final |
| 48 | self.text_projection = clip_model.text_projection |
| 49 | self.dtype = clip_model.dtype |
| 50 | |
| 51 | def forward(self, prompts, tokenized_prompts): |
| 52 | x = prompts + self.positional_embedding.type(self.dtype) |
| 53 | x = x.permute(1, 0, 2) # NLD -> LND |
| 54 | x = self.transformer(x) |
| 55 | x = x.permute(1, 0, 2) # LND -> NLD |
| 56 | x = self.ln_final(x).type(self.dtype) |
| 57 | |
| 58 | # x.shape = [batch_size, n_ctx, transformer.width] |
| 59 | # take features from the eot embedding (eot_token is the highest number in each sequence) |
| 60 | x = x[torch.arange(x.shape[0]), tokenized_prompts.argmax(dim=-1)] @ self.text_projection |
| 61 | |
| 62 | return x |
| 63 | |
| 64 | |
| 65 | class VLPromptLearner(nn.Module): |