Skip to content
Merged
Show file tree
Hide file tree
Changes from 43 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
3f53abd
first draft
jmtzt Aug 22, 2024
b9d7c03
add IJepaEmbeddings class
jmtzt Aug 22, 2024
7af8961
fix copy-from for IJepa model
jmtzt Aug 22, 2024
a4c8eec
add weight conversion script
jmtzt Aug 25, 2024
bf70f98
update attention class names in IJepa model
jmtzt Aug 25, 2024
64f2208
style changes
jmtzt Aug 25, 2024
1dd4e7d
Add push_to_hub option to convert_ijepa_checkpoint function
jmtzt Aug 25, 2024
9826f99
add initial tests for I-JEPA
jmtzt Aug 25, 2024
d78e468
minor style changes to conversion script
jmtzt Aug 25, 2024
7a64b83
make fixup related
jmtzt Aug 25, 2024
66773ee
rename conversion script
jmtzt Aug 25, 2024
9b7e8b4
Add I-JEPA to sdpa docs
jmtzt Aug 25, 2024
edd2ac9
Merge branch 'huggingface:main' into add_ijepa
jmtzt Aug 26, 2024
40cf528
minor fixes
jmtzt Aug 28, 2024
2bae64a
adjust conversion script
jmtzt Aug 28, 2024
4ccf28c
update conversion script
jmtzt Aug 28, 2024
851ed7e
adjust sdpa docs
jmtzt Aug 28, 2024
b7a027c
[run_slow] ijepa
jmtzt Aug 28, 2024
552e800
[run-slow] ijepa
jmtzt Aug 30, 2024
f2f7eb8
[run-slow] ijepa
jmtzt Aug 31, 2024
51b950d
Merge branch 'main' of github.com:huggingface/transformers into add_i…
jmtzt Sep 2, 2024
f24ef12
[run-slow] ijepa
jmtzt Sep 2, 2024
6f9acc9
[run-slow] ijepa
jmtzt Sep 2, 2024
d663ea3
[run-slow] ijepa
jmtzt Sep 2, 2024
5c80f00
Merge branch 'main' of github.com:huggingface/transformers into add_i…
jmtzt Nov 16, 2024
7da705b
formatting issues
jmtzt Nov 16, 2024
52f2173
adjust modeling to modular code
jmtzt Nov 16, 2024
b13a24e
add IJepaModel to objects to ignore in docstring checks
jmtzt Nov 16, 2024
2b154ce
[run-slow] ijepa
jmtzt Nov 16, 2024
3f0c027
fix formatting issues
jmtzt Nov 18, 2024
2ea53eb
add usage instruction snippet to docs
jmtzt Nov 18, 2024
13ccd82
change pos encoding, add checkpoint for doc
jmtzt Nov 18, 2024
10cbda2
add verify logits for all models
jmtzt Nov 18, 2024
0ccd96e
[run-slow] ijepa
jmtzt Nov 18, 2024
d2d47d4
update docs to include image feature extraction instructions
jmtzt Nov 18, 2024
8e8df55
remove pooling layer from IJepaModel in image classification class
jmtzt Nov 18, 2024
50f93d4
[run-slow] ijepa
jmtzt Nov 18, 2024
db79009
remove pooling layer from IJepaModel constructor
jmtzt Nov 18, 2024
57e5407
update docs
jmtzt Nov 19, 2024
8236816
[run-slow] ijepa
jmtzt Nov 19, 2024
ce6499f
[run-slow] ijepa
jmtzt Nov 19, 2024
81a6e66
small changes
jmtzt Nov 19, 2024
7a0fc39
[run-slow] ijepa
jmtzt Nov 19, 2024
37a38f9
style adjustments
jmtzt Nov 26, 2024
491d5a5
update copyright in init file
jmtzt Nov 26, 2024
2afaba0
adjust modular ijepa
jmtzt Nov 26, 2024
db4dfc0
[run-slow] ijepa
jmtzt Nov 26, 2024
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
2 changes: 2 additions & 0 deletions docs/source/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,8 @@
title: GLPN
- local: model_doc/hiera
title: Hiera
- local: model_doc/ijepa
title: I-JEPA
- local: model_doc/imagegpt
title: ImageGPT
- local: model_doc/levit
Expand Down
1 change: 1 addition & 0 deletions docs/source/en/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ Flax), PyTorch, and/or TensorFlow.
| [Hiera](model_doc/hiera) | ✅ | ❌ | ❌ |
| [Hubert](model_doc/hubert) | ✅ | ✅ | ❌ |
| [I-BERT](model_doc/ibert) | ✅ | ❌ | ❌ |
| [I-JEPA](model_doc/ijepa) | ✅ | ❌ | ❌ |
| [IDEFICS](model_doc/idefics) | ✅ | ✅ | ❌ |
| [Idefics2](model_doc/idefics2) | ✅ | ❌ | ❌ |
| [Idefics3](model_doc/idefics3) | ✅ | ❌ | ❌ |
Expand Down
78 changes: 78 additions & 0 deletions docs/source/en/model_doc/ijepa.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<!--Copyright 2024 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->

# I-JEPA

## Overview

The I-JEPA model was proposed in [Image-based Joint-Embedding Predictive Architecture](https://arxiv.org/pdf/2301.08243.pdf) by Mahmoud Assran, Quentin Duval, Ishan Misra, Piotr Bojanowski, Pascal Vincent, Michael Rabbat, Yann LeCun, Nicolas Ballas.
I-JEPA is a self-supervised learning method that predicts the representations of one part of an image based on other parts of the same image. This approach focuses on learning semantic features without relying on pre-defined invariances from hand-crafted data transformations, which can bias specific tasks, or on filling in pixel-level details, which often leads to less meaningful representations.

The abstract from the paper is the following:

This paper demonstrates an approach for learning highly semantic image representations without relying on hand-crafted data-augmentations. We introduce the Image- based Joint-Embedding Predictive Architecture (I-JEPA), a non-generative approach for self-supervised learning from images. The idea behind I-JEPA is simple: from a single context block, predict the representations of various target blocks in the same image. A core design choice to guide I-JEPA towards producing semantic representations is the masking strategy; specifically, it is crucial to (a) sample tar- get blocks with sufficiently large scale (semantic), and to (b) use a sufficiently informative (spatially distributed) context block. Empirically, when combined with Vision Transform- ers, we find I-JEPA to be highly scalable. For instance, we train a ViT-Huge/14 on ImageNet using 16 A100 GPUs in under 72 hours to achieve strong downstream performance across a wide range of tasks, from linear classification to object counting and depth prediction.

This model was contributed by [jmtzt](https://huggingface.co/jmtzt).
The original code can be found [here](https://github.com/facebookresearch/ijepa).

Comment thread
jmtzt marked this conversation as resolved.
## How to use

Here is how to use this model for image feature extraction:

```python
import requests
import torch
from PIL import Image
from torch.nn.functional import cosine_similarity

from transformers import AutoModel, AutoProcessor

url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
url_2 = "http://images.cocodataset.org/val2017/000000219578.jpg"
image_1 = Image.open(requests.get(url_1, stream=True).raw)
image_2 = Image.open(requests.get(url_2, stream=True).raw)

model_id = "jmtzt/ijepa_vith14_1k"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModel.from_pretrained(model_id)

@torch.no_grad()
def infer(image):
Comment thread
jmtzt marked this conversation as resolved.
inputs = processor(image, return_tensors="pt")
outputs = model(**inputs)
return outputs.last_hidden_state.mean(dim=1)


embed_1 = infer(image_1)
embed_2 = infer(image_2)

similarity = cosine_similarity(embed_1, embed_2)
print(similarity)
```
Comment thread
jmtzt marked this conversation as resolved.

## IJepaConfig

[[autodoc]] IJepaConfig

## IJepaModel

[[autodoc]] IJepaModel
- forward

## IJepaForImageClassification

[[autodoc]] IJepaForImageClassification
- forward
3 changes: 2 additions & 1 deletion docs/source/en/perf_infer_gpu_one.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,14 +234,15 @@ For now, Transformers supports SDPA inference and training for the following arc
* [Falcon](https://huggingface.co/docs/transformers/model_doc/falcon#transformers.FalconModel)
* [Gemma](https://huggingface.co/docs/transformers/model_doc/gemma#transformers.GemmaModel)
* [Gemma2](https://huggingface.co/docs/transformers/model_doc/gemma2#transformers.Gemma2Model)
* [Granite](https://huggingface.co/docs/transformers/model_doc/granite#transformers.GraniteModel)
* [GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2)
* [GPTBigCode](https://huggingface.co/docs/transformers/model_doc/gpt_bigcode#transformers.GPTBigCodeModel)
* [GPTNeoX](https://huggingface.co/docs/transformers/model_doc/gpt_neox#transformers.GPTNeoXModel)
* [Hubert](https://huggingface.co/docs/transformers/model_doc/hubert#transformers.HubertModel)
* [Idefics](https://huggingface.co/docs/transformers/model_doc/idefics#transformers.IdeficsModel)
* [Idefics2](https://huggingface.co/docs/transformers/model_doc/idefics2#transformers.Idefics2Model)
* [Idefics3](https://huggingface.co/docs/transformers/model_doc/idefics3#transformers.Idefics3Model)
* [Granite](https://huggingface.co/docs/transformers/model_doc/granite#transformers.GraniteModel)
* [I-JEPA](https://huggingface.co/docs/transformers/model_doc/ijepa#transformers.IJepaModel)
* [GraniteMoe](https://huggingface.co/docs/transformers/model_doc/granitemoe#transformers.GraniteMoeModel)
* [JetMoe](https://huggingface.co/docs/transformers/model_doc/jetmoe#transformers.JetMoeModel)
* [Jamba](https://huggingface.co/docs/transformers/model_doc/jamba#transformers.JambaModel)
Expand Down
14 changes: 14 additions & 0 deletions src/transformers/__init__.py
Comment thread
jmtzt marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@
"models.idefics": ["IdeficsConfig"],
"models.idefics2": ["Idefics2Config"],
"models.idefics3": ["Idefics3Config"],
"models.ijepa": ["IJepaConfig"],
"models.imagegpt": ["ImageGPTConfig"],
"models.informer": ["InformerConfig"],
"models.instructblip": [
Expand Down Expand Up @@ -2456,6 +2457,13 @@
"Idefics3Processor",
]
)
_import_structure["models.ijepa"].extend(
[
"IJepaForImageClassification",
"IJepaModel",
"IJepaPreTrainedModel",
]
)
_import_structure["models.imagegpt"].extend(
[
"ImageGPTForCausalImageModeling",
Expand Down Expand Up @@ -5355,6 +5363,7 @@
)
from .models.idefics2 import Idefics2Config
from .models.idefics3 import Idefics3Config
from .models.ijepa import IJepaConfig
from .models.imagegpt import ImageGPTConfig
from .models.informer import InformerConfig
from .models.instructblip import (
Expand Down Expand Up @@ -7166,6 +7175,11 @@
Idefics3PreTrainedModel,
Idefics3Processor,
)
from .models.ijepa import (
IJepaForImageClassification,
IJepaModel,
IJepaPreTrainedModel,
)
from .models.imagegpt import (
ImageGPTForCausalImageModeling,
ImageGPTForImageClassification,
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
idefics,
idefics2,
idefics3,
ijepa,
imagegpt,
informer,
instructblip,
Expand Down
23 changes: 19 additions & 4 deletions src/transformers/models/auto/configuration_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
from typing import List, Union

from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...dynamic_module_utils import (
get_class_from_dynamic_module,
resolve_trust_remote_code,
)
from ...utils import CONFIG_NAME, logging


Expand Down Expand Up @@ -135,6 +138,7 @@
("idefics", "IdeficsConfig"),
("idefics2", "Idefics2Config"),
("idefics3", "Idefics3Config"),
("ijepa", "IJepaConfig"),
("imagegpt", "ImageGPTConfig"),
("informer", "InformerConfig"),
("instructblip", "InstructBlipConfig"),
Expand Down Expand Up @@ -439,6 +443,7 @@
("idefics", "IDEFICS"),
("idefics2", "Idefics2"),
("idefics3", "Idefics3"),
("ijepa", "I-JEPA"),
("imagegpt", "ImageGPT"),
("informer", "Informer"),
("instructblip", "InstructBLIP"),
Expand Down Expand Up @@ -877,7 +882,11 @@ def docstring_decorator(fn):
indent = re.search(r"^(\s*)List options\s*$", lines[i]).groups()[0]
if use_model_types:
indent = f"{indent} "
lines[i] = _list_model_options(indent, config_to_class=config_to_class, use_model_types=use_model_types)
lines[i] = _list_model_options(
Comment thread
jmtzt marked this conversation as resolved.
Outdated
indent,
config_to_class=config_to_class,
use_model_types=use_model_types,
)
docstrings = "\n".join(lines)
else:
raise ValueError(
Expand Down Expand Up @@ -1018,13 +1027,19 @@ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
has_remote_code = "auto_map" in config_dict and "AutoConfig" in config_dict["auto_map"]
has_local_code = "model_type" in config_dict and config_dict["model_type"] in CONFIG_MAPPING
trust_remote_code = resolve_trust_remote_code(
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
trust_remote_code,
pretrained_model_name_or_path,
has_local_code,
has_remote_code,
)

if has_remote_code and trust_remote_code:
class_ref = config_dict["auto_map"]["AutoConfig"]
config_class = get_class_from_dynamic_module(
class_ref, pretrained_model_name_or_path, code_revision=code_revision, **kwargs
class_ref,
pretrained_model_name_or_path,
code_revision=code_revision,
**kwargs,
)
if os.path.isdir(pretrained_model_name_or_path):
config_class.register_for_auto_class()
Expand Down
24 changes: 19 additions & 5 deletions src/transformers/models/auto/image_processing_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...dynamic_module_utils import (
get_class_from_dynamic_module,
resolve_trust_remote_code,
)
from ...image_processing_utils import BaseImageProcessor, ImageProcessingMixin
from ...image_processing_utils_fast import BaseImageProcessorFast
from ...utils import (
Expand Down Expand Up @@ -90,6 +93,7 @@
("idefics", ("IdeficsImageProcessor",)),
("idefics2", ("Idefics2ImageProcessor",)),
("idefics3", ("Idefics3ImageProcessor",)),
("ijepa", ("ViTImageProcessor", "ViTImageProcessorFast")),
("imagegpt", ("ImageGPTImageProcessor",)),
("instructblip", ("BlipImageProcessor",)),
("instructblipvideo", ("InstructBlipVideoImageProcessor",)),
Expand Down Expand Up @@ -165,7 +169,10 @@
else:
fast_image_processor_class = fast_image_processor_class[0]

IMAGE_PROCESSOR_MAPPING_NAMES[model_type] = (slow_image_processor_class, fast_image_processor_class)
IMAGE_PROCESSOR_MAPPING_NAMES[model_type] = (
slow_image_processor_class,
fast_image_processor_class,
)

IMAGE_PROCESSOR_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)

Expand Down Expand Up @@ -433,7 +440,9 @@ def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
if image_processor_class is None and image_processor_auto_map is None:
if not isinstance(config, PretrainedConfig):
config = AutoConfig.from_pretrained(
pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs
pretrained_model_name_or_path,
trust_remote_code=trust_remote_code,
**kwargs,
)
# It could be in `config.image_processor_type``
image_processor_class = getattr(config, "image_processor_type", None)
Expand All @@ -452,7 +461,10 @@ def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
has_remote_code = image_processor_auto_map is not None
has_local_code = image_processor_class is not None or type(config) in IMAGE_PROCESSOR_MAPPING
trust_remote_code = resolve_trust_remote_code(
trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code
trust_remote_code,
pretrained_model_name_or_path,
has_local_code,
has_remote_code,
)

if image_processor_auto_map is not None and not isinstance(image_processor_auto_map, tuple):
Expand Down Expand Up @@ -553,5 +565,7 @@ def register(
fast_image_processor_class = existing_fast

IMAGE_PROCESSOR_MAPPING.register(
config_class, (slow_image_processor_class, fast_image_processor_class), exist_ok=exist_ok
config_class,
(slow_image_processor_class, fast_image_processor_class),
exist_ok=exist_ok,
)
30 changes: 23 additions & 7 deletions src/transformers/models/auto/modeling_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
("idefics", "IdeficsModel"),
("idefics2", "Idefics2Model"),
("idefics3", "Idefics3Model"),
("ijepa", "IJepaModel"),
("imagegpt", "ImageGPTModel"),
("informer", "InformerModel"),
("jamba", "JambaModel"),
Expand Down Expand Up @@ -576,6 +577,7 @@
("focalnet", "FocalNetModel"),
("glpn", "GLPNModel"),
("hiera", "HieraModel"),
("ijepa", "IJepaModel"),
("imagegpt", "ImageGPTModel"),
("levit", "LevitModel"),
("mllama", "MllamaVisionModel"),
Expand Down Expand Up @@ -639,7 +641,10 @@
("data2vec-vision", "Data2VecVisionForImageClassification"),
(
"deit",
("DeiTForImageClassification", "DeiTForImageClassificationWithTeacher"),
(
"DeiTForImageClassification",
"DeiTForImageClassificationWithTeacher",
),
),
("dinat", "DinatForImageClassification"),
("dinov2", "Dinov2ForImageClassification"),
Expand All @@ -653,10 +658,14 @@
("efficientnet", "EfficientNetForImageClassification"),
("focalnet", "FocalNetForImageClassification"),
("hiera", "HieraForImageClassification"),
("ijepa", "IJepaForImageClassification"),
("imagegpt", "ImageGPTForImageClassification"),
(
"levit",
("LevitForImageClassification", "LevitForImageClassificationWithTeacher"),
(
"LevitForImageClassification",
"LevitForImageClassificationWithTeacher",
),
),
("mobilenet_v1", "MobileNetV1ForImageClassification"),
("mobilenet_v2", "MobileNetV2ForImageClassification"),
Expand Down Expand Up @@ -991,7 +1000,10 @@
("reformer", "ReformerForSequenceClassification"),
("rembert", "RemBertForSequenceClassification"),
("roberta", "RobertaForSequenceClassification"),
("roberta-prelayernorm", "RobertaPreLayerNormForSequenceClassification"),
(
"roberta-prelayernorm",
"RobertaPreLayerNormForSequenceClassification",
),
("roc_bert", "RoCBertForSequenceClassification"),
("roformer", "RoFormerForSequenceClassification"),
("squeezebert", "SqueezeBertForSequenceClassification"),
Expand Down Expand Up @@ -1437,7 +1449,8 @@
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
CONFIG_MAPPING_NAMES,
MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES,
)
MODEL_FOR_IMAGE_SEGMENTATION_MAPPING = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES
Expand Down Expand Up @@ -1677,7 +1690,8 @@ class AutoModelForZeroShotImageClassification(_BaseAutoModelClass):


AutoModelForZeroShotImageClassification = auto_class_update(
AutoModelForZeroShotImageClassification, head_doc="zero-shot image classification"
AutoModelForZeroShotImageClassification,
head_doc="zero-shot image classification",
)


Expand Down Expand Up @@ -1778,7 +1792,8 @@ class AutoModelForSpeechSeq2Seq(_BaseAutoModelClass):


AutoModelForSpeechSeq2Seq = auto_class_update(
AutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
AutoModelForSpeechSeq2Seq,
head_doc="sequence-to-sequence speech-to-text modeling",
)


Expand All @@ -1787,7 +1802,8 @@ class AutoModelForAudioFrameClassification(_BaseAutoModelClass):


AutoModelForAudioFrameClassification = auto_class_update(
AutoModelForAudioFrameClassification, head_doc="audio frame (token) classification"
AutoModelForAudioFrameClassification,
head_doc="audio frame (token) classification",
)


Expand Down
Loading