Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

# Pass Image color channels information to Transformers #2846

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion sentence_transformers/SentenceTransformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from .models import Normalize, Pooling, Transformer
from .quantization import quantize_embeddings
from .util import (
ImageChannelDimension,
batch_to_device,
get_device_name,
import_from_string,
Expand Down Expand Up @@ -367,6 +368,7 @@ def encode(
convert_to_tensor: Literal[False] = ...,
device: str = ...,
normalize_embeddings: bool = ...,
input_data_format: str = ImageChannelDimension.LAST,
) -> Tensor: ...

@overload
Expand All @@ -383,6 +385,7 @@ def encode(
convert_to_tensor: Literal[False] = ...,
device: str = ...,
normalize_embeddings: bool = ...,
input_data_format: str = ImageChannelDimension.LAST,
) -> np.ndarray: ...

@overload
Expand All @@ -399,6 +402,7 @@ def encode(
convert_to_tensor: Literal[True] = ...,
device: str = ...,
normalize_embeddings: bool = ...,
input_data_format: str = ImageChannelDimension.LAST,
) -> Tensor: ...

@overload
Expand All @@ -415,6 +419,7 @@ def encode(
convert_to_tensor: Literal[False] = ...,
device: str = ...,
normalize_embeddings: bool = ...,
input_data_format: str = ImageChannelDimension.LAST,
) -> list[Tensor]: ...

def encode(
Expand All @@ -430,6 +435,7 @@ def encode(
convert_to_tensor: bool = False,
device: str = None,
normalize_embeddings: bool = False,
input_data_format: str = ImageChannelDimension.LAST,
davychxn marked this conversation as resolved.
Show resolved Hide resolved
) -> list[Tensor] | np.ndarray | Tensor:
"""
Computes sentence embeddings.
Expand Down Expand Up @@ -491,6 +497,9 @@ def encode(
self.is_hpu_graph_enabled = True

self.eval()
# Will be used in Image Tokenizer
self.input_data_format = input_data_format

if show_progress_bar is None:
show_progress_bar = logger.getEffectiveLevel() in (logging.INFO, logging.DEBUG)

Expand Down Expand Up @@ -991,7 +1000,7 @@ def tokenize(self, texts: list[str] | list[dict] | list[tuple[str, str]]) -> dic
Dict[str, Tensor]: A dictionary of tensors with the tokenized texts. Common keys are "input_ids",
"attention_mask", and "token_type_ids".
"""
return self._first_module().tokenize(texts)
return self._first_module().tokenize(texts, input_data_format=self.input_data_format)

def get_sentence_features(self, *features) -> dict[Literal["sentence_embedding"], torch.Tensor]:
return self._first_module().get_sentence_features(*features)
Expand Down
5 changes: 3 additions & 2 deletions sentence_transformers/models/CLIPModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import transformers
from PIL import Image
from torch import nn
from ..util import ImageChannelDimension


class CLIPModel(nn.Module):
Expand Down Expand Up @@ -51,7 +52,7 @@ def forward(self, features: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:

return features

def tokenize(self, texts, padding: str | bool = True) -> dict[str, torch.Tensor]:
def tokenize(self, texts, padding: str | bool = True, input_data_format: str = ImageChannelDimension.LAST) -> dict[str, torch.Tensor]:
images = []
texts_values = []
image_text_info = []
Expand All @@ -69,7 +70,7 @@ def tokenize(self, texts, padding: str | bool = True) -> dict[str, torch.Tensor]
encoding = self.processor.tokenizer(texts_values, return_tensors="pt", padding=padding)

if len(images):
image_features = self.processor.image_processor(images, return_tensors="pt")
image_features = self.processor.image_processor(images, return_tensors="pt", input_data_format=input_data_format)
encoding["pixel_values"] = image_features.pixel_values

encoding["image_text_info"] = image_text_info
Expand Down
6 changes: 6 additions & 0 deletions sentence_transformers/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@
from sentence_transformers.cross_encoder.CrossEncoder import CrossEncoder
from sentence_transformers.SentenceTransformer import SentenceTransformer

class ImageChannelDimension():
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be an Enum

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class is copied from Transformers' repo. It is defined like this there. Because the string defined in the class is needed by Transformers' image-processor. If we use Enum, I think, we'll get integer values? And we need to convert to string before passing to Transformers?

"""
Defines the color channels' position in an Image's shape
"""
FIRST = "channels_first"
LAST = "channels_last"

def _convert_to_tensor(a: list | np.ndarray | Tensor) -> Tensor:
"""
Expand Down