Skip to content

Commit

Permalink
Patch clip model for ONNX compatibility
Browse files Browse the repository at this point in the history
Changes to use INT32 for tokenization, since ONNX doesn't yet support ArgMax(INT64)
Use explicit dimension for norm
  • Loading branch information
chajath committed Feb 18, 2022
1 parent 40f5484 commit 1937532
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions clip/clip.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def patch_float(module):
return model, _transform(model.input_resolution.item())


def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor:
def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.IntTensor:
"""
Returns the tokenized representation of given input string(s)
Expand All @@ -217,7 +217,7 @@ def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: b
sot_token = _tokenizer.encoder["<|startoftext|>"]
eot_token = _tokenizer.encoder["<|endoftext|>"]
all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts]
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
result = torch.zeros(len(all_tokens), context_length, dtype=torch.int)

for i, tokens in enumerate(all_tokens):
if len(tokens) > context_length:
Expand Down
4 changes: 2 additions & 2 deletions clip/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,8 +356,8 @@ def forward(self, image, text):
text_features = self.encode_text(text)

# normalized features
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
image_features = image_features / image_features.norm(dim=1, keepdim=True)
text_features = text_features / text_features.norm(dim=1, keepdim=True)

# cosine similarity as logits
logit_scale = self.logit_scale.exp()
Expand Down

0 comments on commit 1937532

Please sign in to comment.