Skip to content

Commit c56d826

Browse files
authored
add altclip & ast model (#944)
1 parent 2d0f1bf commit c56d826

25 files changed

+4581
-5
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,9 @@ The table below represents the current support in the library for each of those
100100
| Model | Pynative support | Graph Support |
101101
|-------------------------------|---------------------|---------------|
102102
| ALBERT |||
103+
| ALIGN |||
104+
| AltCLIP |||
105+
| Audio Spectrogram Transformer |||
103106
| Autoformer | ✅ (Inference only)||
104107
| BaiChuan |||
105108
| Bark |||

mindnlp/transformers/models/__init__.py

+9
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
from . import (
1919
albert,
2020
align,
21+
altclip,
22+
audio_spectrogram_transformer,
2123
auto,
24+
autoformer,
2225
bark,
2326
bart,
2427
bert,
@@ -83,7 +86,10 @@
8386

8487
from .albert import *
8588
from .align import *
89+
from .altclip import *
90+
from .audio_spectrogram_transformer import *
8691
from .auto import *
92+
from .autoformer import *
8793
from .bark import *
8894
from .bart import *
8995
from .bert import *
@@ -148,7 +154,10 @@
148154
__all__ = []
149155
__all__.extend(albert.__all__)
150156
__all__.extend(align.__all__)
157+
__all__.extend(altclip.__all__)
158+
__all__.extend(audio_spectrogram_transformer.__all__)
151159
__all__.extend(auto.__all__)
160+
__all__.extend(autoformer.__all__)
152161
__all__.extend(bart.__all__)
153162
__all__.extend(bark.__all__)
154163
__all__.extend(bert.__all__)

mindnlp/transformers/models/align/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2022 Huawei Technologies Co., Ltd
1+
# Copyright 2024 Huawei Technologies Co., Ltd
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2024 Huawei Technologies Co., Ltd
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# ============================================================================
15+
"""Align model."""
16+
from . import configuration_altclip, modeling_altclip, processing_altclip
17+
from .configuration_altclip import *
18+
from .modeling_altclip import *
19+
from .processing_altclip import *
20+
21+
__all__ = []
22+
__all__.extend(configuration_altclip.__all__)
23+
__all__.extend(modeling_altclip.__all__)
24+
__all__.extend(processing_altclip.__all__)

mindnlp/transformers/models/altclip/configuration_altclip.py

+409
Large diffs are not rendered by default.

mindnlp/transformers/models/altclip/modeling_altclip.py

+1,610
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# coding=utf-8
2+
# Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang The HuggingFace Inc. team. All rights reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
# ============================================================================
16+
"""
17+
Image/Text processor class for AltCLIP
18+
"""
19+
import warnings
20+
21+
from ...processing_utils import ProcessorMixin
22+
from ...tokenization_utils_base import BatchEncoding
23+
24+
25+
class AltCLIPProcessor(ProcessorMixin):
26+
r"""
27+
Constructs a AltCLIP processor which wraps a CLIP image processor and a XLM-Roberta tokenizer into a single
28+
processor.
29+
30+
[`AltCLIPProcessor`] offers all the functionalities of [`CLIPImageProcessor`] and [`XLMRobertaTokenizerFast`]. See
31+
the [`~AltCLIPProcessor.__call__`] and [`~AltCLIPProcessor.decode`] for more information.
32+
33+
Args:
34+
image_processor ([`CLIPImageProcessor`], *optional*):
35+
The image processor is a required input.
36+
tokenizer ([`XLMRobertaTokenizerFast`], *optional*):
37+
The tokenizer is a required input.
38+
"""
39+
40+
attributes = ["image_processor", "tokenizer"]
41+
image_processor_class = "CLIPImageProcessor"
42+
tokenizer_class = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast")
43+
44+
def __init__(self, image_processor=None, tokenizer=None, **kwargs):
45+
feature_extractor = None
46+
if "feature_extractor" in kwargs:
47+
warnings.warn(
48+
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
49+
" instead.",
50+
FutureWarning,
51+
)
52+
feature_extractor = kwargs.pop("feature_extractor")
53+
54+
image_processor = image_processor if image_processor is not None else feature_extractor
55+
if image_processor is None:
56+
raise ValueError("You need to specify an `image_processor`.")
57+
if tokenizer is None:
58+
raise ValueError("You need to specify a `tokenizer`.")
59+
60+
super().__init__(image_processor, tokenizer)
61+
62+
def __call__(self, text=None, images=None, return_tensors=None, **kwargs):
63+
"""
64+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
65+
and `kwargs` arguments to XLMRobertaTokenizerFast's [`~XLMRobertaTokenizerFast.__call__`] if `text` is not
66+
`None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
67+
CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
68+
of the above two methods for more information.
69+
70+
Args:
71+
text (`str`, `List[str]`, `List[List[str]]`):
72+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
73+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
74+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
75+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
76+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
77+
tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
78+
number of channels, H and W are image height and width.
79+
80+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
81+
If set, will return tensors of a particular framework. Acceptable values are:
82+
83+
- `'tf'`: Return TensorFlow `tf.constant` objects.
84+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
85+
- `'np'`: Return NumPy `np.ndarray` objects.
86+
- `'jax'`: Return JAX `jnp.ndarray` objects.
87+
88+
Returns:
89+
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
90+
91+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
92+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
93+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
94+
`None`).
95+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
96+
"""
97+
98+
if text is None and images is None:
99+
raise ValueError("You have to specify either text or images. Both cannot be none.")
100+
101+
if text is not None:
102+
encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
103+
104+
if images is not None:
105+
image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
106+
107+
if text is not None and images is not None:
108+
encoding["pixel_values"] = image_features.pixel_values
109+
return encoding
110+
if text is not None:
111+
return encoding
112+
return BatchEncoding(data={**image_features}, tensor_type=return_tensors)
113+
114+
def batch_decode(self, *args, **kwargs):
115+
"""
116+
This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`].
117+
Please refer to the docstring of this method for more information.
118+
"""
119+
return self.tokenizer.batch_decode(*args, **kwargs)
120+
121+
def decode(self, *args, **kwargs):
122+
"""
123+
This method forwards all its arguments to XLMRobertaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please
124+
refer to the docstring of this method for more information.
125+
"""
126+
return self.tokenizer.decode(*args, **kwargs)
127+
128+
@property
129+
def model_input_names(self):
130+
tokenizer_input_names = self.tokenizer.model_input_names
131+
image_processor_input_names = self.image_processor.model_input_names
132+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
133+
134+
__all__ = ["AltCLIPProcessor"]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2024 Huawei Technologies Co., Ltd
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
# ============================================================================
15+
"""Audio Spectrgram Transformer model."""
16+
from . import configuration_audio_spectrogram_transformer, feature_extraction_audio_spectrogram_transformer, modeling_audio_spectrogram_transformer
17+
from .configuration_audio_spectrogram_transformer import *
18+
from .feature_extraction_audio_spectrogram_transformer import *
19+
from .modeling_audio_spectrogram_transformer import *
20+
21+
__all__ = []
22+
__all__.extend(configuration_audio_spectrogram_transformer.__all__)
23+
__all__.extend(feature_extraction_audio_spectrogram_transformer.__all__)
24+
__all__.extend(modeling_audio_spectrogram_transformer.__all__)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
# coding=utf-8
2+
# Copyright 2022 Google AI and The HuggingFace Inc. team. All rights reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
# ============================================================================
16+
""" Audio Spectogram Transformer (AST) model configuration"""
17+
18+
19+
from mindnlp.utils import logging
20+
from ...configuration_utils import PretrainedConfig
21+
22+
23+
logger = logging.get_logger(__name__)
24+
25+
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26+
"MIT/ast-finetuned-audioset-10-10-0.4593": (
27+
"https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json"
28+
),
29+
}
30+
31+
32+
class ASTConfig(PretrainedConfig):
33+
r"""
34+
This is the configuration class to store the configuration of a [`ASTModel`]. It is used to instantiate an AST
35+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
36+
defaults will yield a similar configuration to that of the AST
37+
[MIT/ast-finetuned-audioset-10-10-0.4593](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593)
38+
architecture.
39+
40+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
41+
documentation from [`PretrainedConfig`] for more information.
42+
43+
Args:
44+
hidden_size (`int`, *optional*, defaults to 768):
45+
Dimensionality of the encoder layers and the pooler layer.
46+
num_hidden_layers (`int`, *optional*, defaults to 12):
47+
Number of hidden layers in the Transformer encoder.
48+
num_attention_heads (`int`, *optional*, defaults to 12):
49+
Number of attention heads for each attention layer in the Transformer encoder.
50+
intermediate_size (`int`, *optional*, defaults to 3072):
51+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
52+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
55+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
56+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
58+
The dropout ratio for the attention probabilities.
59+
initializer_range (`float`, *optional*, defaults to 0.02):
60+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
62+
The epsilon used by the layer normalization layers.
63+
patch_size (`int`, *optional*, defaults to 16):
64+
The size (resolution) of each patch.
65+
qkv_bias (`bool`, *optional*, defaults to `True`):
66+
Whether to add a bias to the queries, keys and values.
67+
frequency_stride (`int`, *optional*, defaults to 10):
68+
Frequency stride to use when patchifying the spectrograms.
69+
time_stride (`int`, *optional*, defaults to 10):
70+
Temporal stride to use when patchifying the spectrograms.
71+
max_length (`int`, *optional*, defaults to 1024):
72+
Temporal dimension of the spectrograms.
73+
num_mel_bins (`int`, *optional*, defaults to 128):
74+
Frequency dimension of the spectrograms (number of Mel-frequency bins).
75+
76+
Example:
77+
78+
```python
79+
>>> from transformers import ASTConfig, ASTModel
80+
81+
>>> # Initializing a AST MIT/ast-finetuned-audioset-10-10-0.4593 style configuration
82+
>>> configuration = ASTConfig()
83+
84+
>>> # Initializing a model (with random weights) from the MIT/ast-finetuned-audioset-10-10-0.4593 style configuration
85+
>>> model = ASTModel(configuration)
86+
87+
>>> # Accessing the model configuration
88+
>>> configuration = model.config
89+
```"""
90+
91+
model_type = "audio-spectrogram-transformer"
92+
93+
def __init__(
94+
self,
95+
hidden_size=768,
96+
num_hidden_layers=12,
97+
num_attention_heads=12,
98+
intermediate_size=3072,
99+
hidden_act="gelu",
100+
hidden_dropout_prob=0.0,
101+
attention_probs_dropout_prob=0.0,
102+
initializer_range=0.02,
103+
layer_norm_eps=1e-12,
104+
patch_size=16,
105+
qkv_bias=True,
106+
frequency_stride=10,
107+
time_stride=10,
108+
max_length=1024,
109+
num_mel_bins=128,
110+
**kwargs,
111+
):
112+
super().__init__(**kwargs)
113+
114+
self.hidden_size = hidden_size
115+
self.num_hidden_layers = num_hidden_layers
116+
self.num_attention_heads = num_attention_heads
117+
self.intermediate_size = intermediate_size
118+
self.hidden_act = hidden_act
119+
self.hidden_dropout_prob = hidden_dropout_prob
120+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
121+
self.initializer_range = initializer_range
122+
self.layer_norm_eps = layer_norm_eps
123+
self.patch_size = patch_size
124+
self.qkv_bias = qkv_bias
125+
self.frequency_stride = frequency_stride
126+
self.time_stride = time_stride
127+
self.max_length = max_length
128+
self.num_mel_bins = num_mel_bins
129+
130+
__all__ = [
131+
"AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
132+
"ASTConfig",
133+
]

0 commit comments

Comments
 (0)