Zero-Shot Image Classification
Transformers
Safetensors
sentence-transformers
mllama
image-text-to-text
mmeb
text-generation-inference
Instructions to use intfloat/mmE5-mllama-11b-instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use intfloat/mmE5-mllama-11b-instruct with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("zero-shot-image-classification", model="intfloat/mmE5-mllama-11b-instruct") pipe( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png", candidate_labels=["animals", "humans", "landscape"], )# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("intfloat/mmE5-mllama-11b-instruct") model = AutoModelForMultimodalLM.from_pretrained("intfloat/mmE5-mllama-11b-instruct", device_map="auto") - sentence-transformers
How to use intfloat/mmE5-mllama-11b-instruct with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("intfloat/mmE5-mllama-11b-instruct") sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
Finalize Sentence Transformers integration (#3)
Browse files- Finalize Sentence Transformers integration (501f1f440cb512754532cfa281332455bca94268)
- Remove unneeded spaces before texts in image-text setups (211fa5c2e04bd58fd52324c6f57111a69e3037b0)
Files changed (4)
- 1_Pooling/config.jsonAdded+10
- README.md+49-7
- custom_st.py+22-31
- modules.jsonAdded+20
12345678910{ "word_embedding_dimension": 4096, "pooling_mode_cls_token": false, "pooling_mode_mean_tokens": false, "pooling_mode_max_tokens": false, "pooling_mode_mean_sqrt_len_tokens": false, "pooling_mode_weightedmean_tokens": false, "pooling_mode_lasttoken": true, "include_prompt": true }1 unmodified line23456726 unmodified lines34353637383940414243444546474858 unmodified lines1071081091101111121 unmodified linetags:- mmeb- transformerslanguage:- en- ar26 unmodified lines## UsageBelow is an example we adapted from [VLM2Vec](https://huggingface.co/TIGER-Lab/VLM2Vec-Full).First clone github```bashgit clone https://github.com/haon-chen/mmE5.gitpip install -r requirements.txt```Then you can enter the directory to run the following command.```pythonimport torchimport requests58 unmodified lines## <|image|><|begin_of_text|> Represent the given image. = tensor([[0.3887]], device='cuda:0', dtype=torch.bfloat16)```## Citation```@article{chen2025mmE5,1 unmodified line234567826 unmodified lines3536373839404142434458 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541 unmodified linetags:- mmeb- transformers- sentence-transformerslanguage:- en- ar26 unmodified lines## Usage### TransformersBelow is an example we adapted from [VLM2Vec](https://huggingface.co/TIGER-Lab/VLM2Vec-Full).```pythonimport torchimport requests58 unmodified lines## <|image|><|begin_of_text|> Represent the given image. = tensor([[0.3887]], device='cuda:0', dtype=torch.bfloat16)```### Sentence TransformersYou can also use Sentence Transformers, where the majority of the pre- and post-processing has been abstracted.```pythonfrom sentence_transformers import SentenceTransformerimport requests# Load the modelmodel = SentenceTransformer("intfloat/mmE5-mllama-11b-instruct", trust_remote_code=True)# Download an example image of a cat and a dogdog_cat_image_bytes = requests.get('https://github.com/haon-chen/mmE5/blob/main/figures/example.jpg?raw=true', stream=True).raw.read()with open("cat_dog_example.jpg", "wb") as f:f.write(dog_cat_image_bytes)# Image + Text -> Textimage_embeddings = model.encode([{"image": "cat_dog_example.jpg","text": "Represent the given image with the following question: What is in the image",}])text_embeddings = model.encode([{"text": "A cat and a dog"},{"text": "A cat and a tiger"},])similarity = model.similarity(image_embeddings, text_embeddings)print(similarity)# tensor([[0.3967, 0.3090]])# ✅ The first text is most similar to the image# Text -> Imageimage_embeddings = model.encode([{"image": dog_cat_image_bytes, "text": "Represent the given image."},])text_embeddings = model.encode([{"text": "Find me an everyday image that matches the given caption: A cat and a dog."},{"text": "Find me an everyday image that matches the given caption: A cat and a tiger."},])similarity = model.similarity(image_embeddings, text_embeddings)print(similarity)# tensor([[0.4250, 0.3896]])# ✅ The first text is most similar to the image```## Citation```@article{chen2025mmE5,
16 unmodified lines1718192021229 unmodified lines3233343536379 unmodified lines4748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949516 unmodified linessuper().__init__(model_name_or_path, **kwargs)if tokenizer_args is None:tokenizer_args = {}# Initialize processorself.processor = AutoProcessor.from_pretrained(9 unmodified linesis_peft_model: bool,**model_args,) -> None:self.auto_model = MllamaForConditionalGeneration.from_pretrained(model_name_or_path, torch_dtype=torch.bfloat16, cache_dir=cache_dir, **model_args)9 unmodified lines**kwargs)# Apply last pooling and normalizationlast_hidden_state = outputs.hidden_states[-1]attention_mask = features["attention_mask"]sentence_embedding = self._last_pooling(last_hidden_state, attention_mask)features.update({"sentence_embedding": sentence_embedding})return featuresdef _last_pooling(self, last_hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:"""Apply last token pooling and L2 normalization"""sequence_lengths = attention_mask.sum(dim=1) - 1batch_size = last_hidden_state.shape[0]reps = last_hidden_state[torch.arange(batch_size, device=last_hidden_state.device), sequence_lengths]return torch.nn.functional.normalize(reps, p=2, dim=-1)def tokenize(self, texts: List[List[Dict]] | List[str]) -> Dict[str, torch.Tensor]:def process_text_item(item):if isinstance(item, str):return item, []text, images = "", []for sub_item in item:if sub_item["type"] == "text":text += sub_item["content"]elif sub_item["type"] in ["image_bytes", "image_path"]:text += "<|image|>"if sub_item["type"] == "image_bytes":img = Image.open(BytesIO(sub_item["content"])).convert("RGB")else:img = Image.open(sub_item["content"]).convert("RGB")images.append(img)else:raise ValueError(f"Unknown data type {sub_item['type']}")return text, imagesall_texts, all_images = [], []for item in texts:text, images = process_text_item(item)all_texts.append(text)all_images.extend(images)# Process inputs through the processorif all_images:inputs = self.processor(text=all_texts,images=all_images,16 unmodified lines171819202122239 unmodified lines333435363738399 unmodified lines495051525354555657585960616263646566676869707172737475767778798081828384858616 unmodified linessuper().__init__(model_name_or_path, **kwargs)if tokenizer_args is None:tokenizer_args = {}tokenizer_args.pop("trust_remote_code", None)# Initialize processorself.processor = AutoProcessor.from_pretrained(9 unmodified linesis_peft_model: bool,**model_args,) -> None:model_args.pop("trust_remote_code", None)self.auto_model = MllamaForConditionalGeneration.from_pretrained(model_name_or_path, torch_dtype=torch.bfloat16, cache_dir=cache_dir, **model_args)9 unmodified lines**kwargs)features.update({"token_embeddings": outputs.hidden_states[-1]})return featuresdef tokenize(self, texts: List[List[Dict]] | List[str]) -> Dict[str, torch.Tensor]:def process_text_item(item):if isinstance(item, str):return item, Nonetext, img = "", Noneif "image" in item:text += "<|image|>"img = item["image"]if isinstance(img, bytes):img = Image.open(BytesIO(img)).convert("RGB")elif isinstance(img, str):img = Image.open(img).convert("RGB")elif not isinstance(img, Image):raise ValueError(f"Unknown image type {type(img)}")if "text" in item:if text:text += "<|begin_of_text|> "text += item["text"].lstrip()return text, imgall_texts, all_images = [], []for item in texts:text, images = process_text_item(item)all_texts.append(text)all_images.append(images)if all_images != [None] * len(all_images):inputs = self.processor(text=all_texts,images=all_images,
1234567891011121314151617181920[ { "idx": 0, "name": "0", "path": "", "type": "custom_st.MultiModalTransformer" }, { "idx": 1, "name": "1", "path": "1_Pooling", "type": "sentence_transformers.models.Pooling" }, { "idx": 2, "name": "2", "path": "2_Normalize", "type": "sentence_transformers.models.Normalize" }]1_Pooling/config.jsonAdded+10
README.md+49-7
custom_st.py+22-31
modules.jsonAdded+20