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

Add I-JEPA #33125

Merged
merged 47 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 13 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 @@ -623,6 +623,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 @@ -165,6 +165,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) | ✅ | ❌ | ❌ |
| [ImageGPT](model_doc/imagegpt) | ✅ | ❌ | ❌ |
Expand Down
51 changes: 51 additions & 0 deletions docs/source/en/model_doc/ijepa.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<!--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 [<INSERT PAPER NAME HERE>](<INSERT PAPER LINK HERE>) by <INSERT AUTHORS HERE>.
jmtzt marked this conversation as resolved.
Show resolved Hide resolved
<INSERT SHORT SUMMARY HERE>

The abstract from the paper is the following:

*<INSERT PAPER ABSTRACT HERE>*

Tips:

<INSERT TIPS ABOUT MODEL HERE>

This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/<INSERT YOUR HF USERNAME HERE>).
The original code can be found [here](<INSERT LINK TO GITHUB REPO HERE>).

jmtzt marked this conversation as resolved.
Show resolved Hide resolved

## IJepaConfig

[[autodoc]] IJepaConfig

## IJepaModel

[[autodoc]] IJepaModel
- forward

## IJepaForImageClassification

[[autodoc]] IJepaForImageClassification
- forward

</pt>
<tf>
jmtzt marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions docs/source/en/perf_infer_gpu_one.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ For now, Transformers supports SDPA inference and training for the following arc
* [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)
* [I-JEPA](https://huggingface.co/docs/transformers/model_doc/ijepa#transformers.IJepaModel)
* [JetMoe](https://huggingface.co/docs/transformers/model_doc/jetmoe#transformers.JetMoeModel)
* [Jamba](https://huggingface.co/docs/transformers/model_doc/jamba#transformers.JambaModel)
* [Llama](https://huggingface.co/docs/transformers/model_doc/llama#transformers.LlamaModel)
Expand Down
14 changes: 14 additions & 0 deletions src/transformers/__init__.py
jmtzt marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@
"models.ibert": ["IBertConfig"],
"models.idefics": ["IdeficsConfig"],
"models.idefics2": ["Idefics2Config"],
"models.ijepa": ["IJepaConfig"],
"models.imagegpt": ["ImageGPTConfig"],
"models.informer": ["InformerConfig"],
"models.instructblip": [
Expand Down Expand Up @@ -2381,6 +2382,13 @@
"Idefics2Processor",
]
)
_import_structure["models.ijepa"].extend(
[
"IJepaForImageClassification",
"IJepaModel",
"IJepaPreTrainedModel",
]
)
_import_structure["models.imagegpt"].extend(
[
"ImageGPTForCausalImageModeling",
Expand Down Expand Up @@ -5230,6 +5238,7 @@
IdeficsConfig,
)
from .models.idefics2 import Idefics2Config
from .models.ijepa import IJepaConfig
from .models.imagegpt import ImageGPTConfig
from .models.informer import InformerConfig
from .models.instructblip import (
Expand Down Expand Up @@ -6977,6 +6986,11 @@
Idefics2PreTrainedModel,
Idefics2Processor,
)
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 @@ -113,6 +113,7 @@
ibert,
idefics,
idefics2,
ijepa,
imagegpt,
informer,
instructblip,
Expand Down
2 changes: 2 additions & 0 deletions src/transformers/models/auto/configuration_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@
("ibert", "IBertConfig"),
("idefics", "IdeficsConfig"),
("idefics2", "Idefics2Config"),
("ijepa", "IJepaConfig"),
("imagegpt", "ImageGPTConfig"),
("informer", "InformerConfig"),
("instructblip", "InstructBlipConfig"),
Expand Down Expand Up @@ -420,6 +421,7 @@
("ibert", "I-BERT"),
("idefics", "IDEFICS"),
("idefics2", "Idefics2"),
("ijepa", "I-JEPA"),
("imagegpt", "ImageGPT"),
("informer", "Informer"),
("instructblip", "InstructBLIP"),
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/auto/image_processing_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
("hiera", ("BitImageProcessor",)),
("idefics", ("IdeficsImageProcessor",)),
("idefics2", ("Idefics2ImageProcessor",)),
("ijepa", ("ViTImageProcessor", "ViTImageProcessorFast")),
("imagegpt", ("ImageGPTImageProcessor",)),
("instructblip", ("BlipImageProcessor",)),
("instructblipvideo", ("InstructBlipVideoImageProcessor",)),
Expand Down
3 changes: 3 additions & 0 deletions src/transformers/models/auto/modeling_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
("ibert", "IBertModel"),
("idefics", "IdeficsModel"),
("idefics2", "Idefics2Model"),
("ijepa", "IJepaModel"),
("imagegpt", "ImageGPTModel"),
("informer", "InformerModel"),
("jamba", "JambaModel"),
Expand Down Expand Up @@ -553,6 +554,7 @@
("focalnet", "FocalNetModel"),
("glpn", "GLPNModel"),
("hiera", "HieraModel"),
("ijepa", "IJepaModel"),
("imagegpt", "ImageGPTModel"),
("levit", "LevitModel"),
("mobilenet_v1", "MobileNetV1Model"),
Expand Down Expand Up @@ -629,6 +631,7 @@
("efficientnet", "EfficientNetForImageClassification"),
("focalnet", "FocalNetForImageClassification"),
("hiera", "HieraForImageClassification"),
("ijepa", "IJepaForImageClassification"),
("imagegpt", "ImageGPTForImageClassification"),
(
"levit",
Expand Down
60 changes: 60 additions & 0 deletions src/transformers/models/ijepa/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Copyright 2024 The HuggingFace Team. All rights reserved.
jmtzt marked this conversation as resolved.
Show resolved Hide resolved
#
# 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.
from typing import TYPE_CHECKING

from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)


_import_structure = {"configuration_ijepa": ["IJepaConfig", "IJepaOnnxConfig"]}

try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_ijepa"] = [
"IJepaForImageClassification",
"IJepaModel",
"IJepaPreTrainedModel",
]

if TYPE_CHECKING:
from .configuration_ijepa import IJepaConfig, IJepaOnnxConfig
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
from .configuration_ijepa import IJepaConfig, IJepaOnnxConfig
from .configuration_ijepa import IJepaConfig


try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ijepa import (
IJepaForImageClassification,
IJepaModel,
IJepaPreTrainedModel,
)

else:
import sys

sys.modules[__name__] = _LazyModule(
__name__,
globals()["__file__"],
_import_structure,
module_spec=__spec__,
)
jmtzt marked this conversation as resolved.
Show resolved Hide resolved
137 changes: 137 additions & 0 deletions src/transformers/models/ijepa/configuration_ijepa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# coding=utf-8
# Copyright 2024 The HuggingFace Inc. 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.
"""I-JEPA model configuration"""

from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


logger = logging.get_logger(__name__)


class IJepaConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`IJepaModel`]. It is used to instantiate an IJEPA
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the I-JEPA
[google/ijepa-base-patch16-224](https://huggingface.co/google/ijepa-base-patch16-224) architecture.

Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.


Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
qkv_bias (`bool`, *optional*, defaults to `True`):
Whether to add a bias to the queries, keys and values.

Example:

```python
>>> from transformers import IJepaConfig, IJepaModel

>>> # Initializing a IJEPA ijepa-base-patch16-224 style configuration
>>> configuration = IJepaConfig()

>>> # Initializing a model (with random weights) from the ijepa-base-patch16-224 style configuration
>>> model = IJepaModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```"""

model_type = "ijepa"

def __init__(
self,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-12,
image_size=224,
patch_size=16,
num_channels=3,
qkv_bias=True,
**kwargs,
):
super().__init__(**kwargs)

self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.qkv_bias = qkv_bias


class IJepaOnnxConfig(OnnxConfig):
torch_onnx_minimum_version = version.parse("1.11")

@property
def inputs(self) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
(
"pixel_values",
{0: "batch", 1: "num_channels", 2: "height", 3: "width"},
),
]
)

@property
def atol_for_validation(self) -> float:
return 1e-4
jmtzt marked this conversation as resolved.
Show resolved Hide resolved
Loading