Buckets:
| # ALIGN | |
| ## 概要 | |
| ALIGNモデルは、「[Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision](https://huggingface.co/papers/2102.05918)」という論文でChao Jia、Yinfei Yang、Ye Xia、Yi-Ting Chen、Zarana Parekh、Hieu Pham、Quoc V. Le、Yunhsuan Sung、Zhen Li、Tom Duerigによって提案されました。ALIGNはマルチモーダルな視覚言語モデルです。これは画像とテキストの類似度や、ゼロショット画像分類に使用できます。ALIGNは[EfficientNet](efficientnet)を視覚エンコーダーとして、[BERT](bert)をテキストエンコーダーとして搭載したデュアルエンコーダー構造を特徴とし、対照学習によって視覚とテキストの表現を整合させることを学びます。それまでの研究とは異なり、ALIGNは巨大でノイジーなデータセットを活用し、コーパスのスケールを利用して単純な方法ながら最先端の表現を達成できることを示しています。 | |
| 論文の要旨は以下の通りです: | |
| *事前学習された表現は、多くの自然言語処理(NLP)および知覚タスクにとって重要になっています。NLPにおける表現学習は、人間のアノテーションのない生のテキストでの学習へと移行していますが、視覚および視覚言語の表現は依然として精巧な学習データセットに大きく依存しており、これは高価であったり専門知識を必要としたりします。視覚アプリケーションの場合、ImageNetやOpenImagesのような明示的なクラスラベルを持つデータセットを使用して学習されることがほとんどです。視覚言語の場合、Conceptual Captions、MSCOCO、CLIPなどの人気のあるデータセットはすべて、それぞれ無視できないデータ収集(およびクリーニング)プロセスを含みます。このコストのかかるキュレーションプロセスはデータセットのサイズを制限し、訓練されたモデルのスケーリングを妨げます。本論文では、Conceptual Captionsデータセットの高価なフィルタリングや後処理ステップなしで得られた、10億を超える画像alt-textペアのノイズの多いデータセットを活用します。シンプルなデュアルエンコーダーアーキテクチャは、対照損失を使用して画像とテキストペアの視覚的および言語的表現を整合させることを学習します。我々は、コーパスの規模がそのノイズを補い、このような単純な学習スキームでも最先端の表現につながることを示します。我々の視覚表現は、ImageNetやVTABなどの分類タスクへの転移において強力な性能を発揮します。整合した視覚的および言語的表現は、ゼロショット画像分類を可能にし、また、より洗練されたクロスアテンションモデルと比較しても、Flickr30KおよびMSCOCO画像テキスト検索ベンチマークにおいて新たな最先端の結果を達成します。また、これらの表現は、複雑なテキストおよびテキスト+画像のクエリを用いたクロスモーダル検索を可能にします。* | |
| このモデルは[Alara Dirik](https://huggingface.co/adirik)により提供されました。 | |
| オリジナルのコードは公開されておらず、この実装は元論文に基づいたKakao Brainの実装をベースにしています。 | |
| ## 使用例 | |
| ALIGNはEfficientNetを使用して視覚的特徴を、BERTを使用してテキスト特徴を取得します。テキストと視覚の両方の特徴は、同一の次元を持つ潜在空間に射影されます。射影された画像とテキスト特徴間のドット積が類似度スコアとして使用されます。 | |
| [AlignProcessor](/docs/transformers/main/ja/model_doc/align#transformers.AlignProcessor)は、テキストのエンコードと画像の前処理を両方行うために、`EfficientNetImageProcessor`と[BertTokenizer](/docs/transformers/main/ja/model_doc/bert#transformers.BertTokenizer)を単一のインスタンスにラップします。以下の例は、[AlignProcessor](/docs/transformers/main/ja/model_doc/align#transformers.AlignProcessor)と[AlignModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignModel)を使用して画像-テキスト類似度スコアを取得する方法を示しています。 | |
| ```python | |
| import requests | |
| import torch | |
| from PIL import Image | |
| from transformers import AlignProcessor, AlignModel | |
| processor = AlignProcessor.from_pretrained("kakaobrain/align-base") | |
| model = AlignModel.from_pretrained("kakaobrain/align-base") | |
| url = "http://images.cocodataset.org/val2017/000000039769.jpg" | |
| image = Image.open(requests.get(url, stream=True).raw) | |
| candidate_labels = ["an image of a cat", "an image of a dog"] | |
| inputs = processor(text=candidate_labels, images=image, return_tensors="pt") | |
| with torch.no_grad(): | |
| outputs = model(**inputs) | |
| # this is the image-text similarity score | |
| logits_per_image = outputs.logits_per_image | |
| # we can take the softmax to get the label probabilities | |
| probs = logits_per_image.softmax(dim=1) | |
| print(probs) | |
| ``` | |
| ## 参考資料 | |
| ALIGNの使用を開始するのに役立つ公式のHugging Faceとコミュニティ(🌎で示されている)の参考資料の一覧です。 | |
| - [ALIGNとCOYO-700Mデータセット](https://huggingface.co/blog/vit-align)に関するブログ投稿。 | |
| - ゼロショット画像分類[デモ](https://huggingface.co/spaces/adirik/ALIGN-zero-shot-image-classification)。 | |
| - `kakaobrain/align-base` モデルの[モデルカード](https://huggingface.co/kakaobrain/align-base)。 | |
| ここに参考資料を提出したい場合は、気兼ねなくPull Requestを開いてください。私たちはそれをレビューいたします!参考資料は、既存のものを複製するのではなく、何か新しいことを示すことが理想的です。 | |
| ## AlignConfig[[transformers.AlignConfig]] | |
| #### transformers.AlignConfig[[transformers.AlignConfig]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/configuration_align.py#L157) | |
| This is the configuration class to store the configuration of a AlignModel. It is used to instantiate a Align | |
| 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 [kakaobrain/align-base](https://huggingface.co/kakaobrain/align-base) | |
| Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the | |
| documentation from [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) for more information. | |
| Example: | |
| ```python | |
| >>> from transformers import AlignConfig, AlignModel | |
| >>> # Initializing a AlignConfig with kakaobrain/align-base style configuration | |
| >>> configuration = AlignConfig() | |
| >>> # Initializing a AlignModel (with random weights) from the kakaobrain/align-base style configuration | |
| >>> model = AlignModel(configuration) | |
| >>> # Accessing the model configuration | |
| >>> configuration = model.config | |
| >>> # We can also initialize a AlignConfig from a AlignTextConfig and a AlignVisionConfig | |
| >>> from transformers import AlignTextConfig, AlignVisionConfig | |
| >>> # Initializing ALIGN Text and Vision configurations | |
| >>> config_text = AlignTextConfig() | |
| >>> config_vision = AlignVisionConfig() | |
| >>> config = AlignConfig(text_config=config_text, vision_config=config_vision) | |
| ``` | |
| **Parameters:** | |
| text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *optional*) : The config object or dictionary of the text backbone. | |
| vision_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *optional*) : The config object or dictionary of the vision backbone. | |
| projection_dim (`int`, *optional*, defaults to `640`) : Dimensionality of text and vision projection layers. | |
| temperature_init_value (`float`, *optional*, defaults to 1.0) : The initial value of the *temperature* parameter. Default is used as per the original ALIGN implementation. | |
| initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices. | |
| ## AlignTextConfig[[transformers.AlignTextConfig]] | |
| #### transformers.AlignTextConfig[[transformers.AlignTextConfig]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/configuration_align.py#L27) | |
| This is the configuration class to store the configuration of a AlignModel. It is used to instantiate a Align | |
| 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 [kakaobrain/align-base](https://huggingface.co/kakaobrain/align-base) | |
| Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the | |
| documentation from [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) for more information. | |
| Example: | |
| ```python | |
| >>> from transformers import AlignTextConfig, AlignTextModel | |
| >>> # Initializing a AlignTextConfig with kakaobrain/align-base style configuration | |
| >>> configuration = AlignTextConfig() | |
| >>> # Initializing a AlignTextModel (with random weights) from the kakaobrain/align-base style configuration | |
| >>> model = AlignTextModel(configuration) | |
| >>> # Accessing the model configuration | |
| >>> configuration = model.config | |
| ``` | |
| **Parameters:** | |
| vocab_size (`int`, *optional*, defaults to `30522`) : Vocabulary size of the model. Defines the number of different tokens that can be represented by the `input_ids`. | |
| hidden_size (`int`, *optional*, defaults to `768`) : Dimension of the hidden representations. | |
| num_hidden_layers (`int`, *optional*, defaults to `12`) : Number of hidden layers in the Transformer decoder. | |
| num_attention_heads (`int`, *optional*, defaults to `12`) : Number of attention heads for each attention layer in the Transformer decoder. | |
| intermediate_size (`int`, *optional*, defaults to `3072`) : Dimension of the MLP representations. | |
| hidden_act (`str`, *optional*, defaults to `gelu`) : The non-linear activation function (function or string) in the decoder. For example, `"gelu"`, `"relu"`, `"silu"`, etc. | |
| hidden_dropout_prob (`Union[float, int]`, *optional*, defaults to `0.1`) : The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. | |
| attention_probs_dropout_prob (`Union[float, int]`, *optional*, defaults to `0.1`) : The dropout ratio for the attention probabilities. | |
| max_position_embeddings (`int`, *optional*, defaults to `512`) : The maximum sequence length that this model might ever be used with. | |
| type_vocab_size (`int`, *optional*, defaults to `2`) : The vocabulary size of the `token_type_ids`. | |
| 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. | |
| pad_token_id (`int`, *optional*, defaults to `0`) : Token id used for padding in the vocabulary. | |
| bos_token_id (`int`, *optional*) : Token id used for beginning-of-stream in the vocabulary. | |
| eos_token_id (`Union[int, list[int]]`, *optional*) : Token id used for end-of-stream in the vocabulary. | |
| ## AlignVisionConfig[[transformers.AlignVisionConfig]] | |
| #### transformers.AlignVisionConfig[[transformers.AlignVisionConfig]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/configuration_align.py#L66) | |
| This is the configuration class to store the configuration of a AlignModel. It is used to instantiate a Align | |
| 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 [kakaobrain/align-base](https://huggingface.co/kakaobrain/align-base) | |
| Configuration objects inherit from [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the | |
| documentation from [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) for more information. | |
| Example: | |
| ```python | |
| >>> from transformers import AlignVisionConfig, AlignVisionModel | |
| >>> # Initializing a AlignVisionConfig with kakaobrain/align-base style configuration | |
| >>> configuration = AlignVisionConfig() | |
| >>> # Initializing a AlignVisionModel (with random weights) from the kakaobrain/align-base style configuration | |
| >>> model = AlignVisionModel(configuration) | |
| >>> # Accessing the model configuration | |
| >>> configuration = model.config | |
| ``` | |
| **Parameters:** | |
| num_channels (`int`, *optional*, defaults to `3`) : The number of input channels. | |
| image_size (`Union[int, list[int], tuple[int, int]]`, *optional*, defaults to `600`) : The size (resolution) of each image. | |
| width_coefficient (`float`, *optional*, defaults to 2.0) : Scaling coefficient for network width at each stage. | |
| depth_coefficient (`float`, *optional*, defaults to 3.1) : Scaling coefficient for network depth at each stage. | |
| depth_divisor (`int`, *optional*, defaults to 8) : A unit of network width. | |
| kernel_sizes (`list[int]`, *optional*, defaults to `[3, 3, 5, 3, 5, 5, 3]`) : List of kernel sizes to be used in each block. | |
| in_channels (`list[int]`, *optional*, defaults to `[32, 16, 24, 40, 80, 112, 192]`) : List of input channel sizes to be used in each block for convolutional layers. | |
| out_channels (`list[int]`, *optional*, defaults to `[16, 24, 40, 80, 112, 192, 320]`) : List of output channel sizes to be used in each block for convolutional layers. | |
| depthwise_padding (`list[int]`, *optional*, defaults to `[]`) : List of block indices with square padding. | |
| strides (`list[int]`, *optional*, defaults to `[1, 2, 2, 2, 1, 2, 1]`) : List of stride sizes to be used in each block for convolutional layers. | |
| num_block_repeats (`list[int]`, *optional*, defaults to `[1, 2, 2, 3, 3, 4, 1]`) : List of the number of times each block is to repeated. | |
| expand_ratios (`list[int]`, *optional*, defaults to `[1, 6, 6, 6, 6, 6, 6]`) : List of scaling coefficient of each block. | |
| squeeze_expansion_ratio (`float`, *optional*, defaults to 0.25) : Squeeze expansion ratio. | |
| hidden_act (`str`, *optional*, defaults to `swish`) : The non-linear activation function (function or string) in the decoder. For example, `"gelu"`, `"relu"`, `"silu"`, etc. | |
| hidden_dim (`int`, *optional*, defaults to 1280) : The hidden dimension of the layer before the classification head. | |
| pooling_type (`str` or `function`, *optional*, defaults to `"mean"`) : Type of final pooling to be applied before the dense classification head. Available options are [`"mean"`, `"max"`] | |
| initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices. | |
| batch_norm_eps (`float`, *optional*, defaults to `0.001`) : The epsilon used by the batch normalization layers. | |
| batch_norm_momentum (`float`, *optional*, defaults to 0.99) : The momentum used by the batch normalization layers. | |
| drop_connect_rate (`float`, *optional*, defaults to 0.2) : The drop rate for skip connections. | |
| ## AlignProcessor[[transformers.AlignProcessor]] | |
| #### transformers.AlignProcessor[[transformers.AlignProcessor]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/processing_align.py#L33) | |
| Constructs a AlignProcessor which wraps a image processor and a tokenizer into a single processor. | |
| [AlignProcessor](/docs/transformers/main/ja/model_doc/align#transformers.AlignProcessor) offers all the functionalities of `EfficientNetImageProcessor` and [BertTokenizer](/docs/transformers/main/ja/model_doc/bert#transformers.BertTokenizer). See the | |
| `~EfficientNetImageProcessor` and [~BertTokenizer](/docs/transformers/main/ja/model_doc/bert#transformers.BertTokenizer) for more information. | |
| **Parameters:** | |
| image_processor (`EfficientNetImageProcessor`) : The image processor is a required input. | |
| tokenizer (`BertTokenizer`) : The tokenizer is a required input. | |
| ## AlignModel[[transformers.AlignModel]] | |
| #### transformers.AlignModel[[transformers.AlignModel]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L1008) | |
| The bare Align Model outputting raw hidden-states without any specific head on top. | |
| This model inherits from [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the | |
| library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads | |
| etc.) | |
| This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. | |
| Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage | |
| and behavior. | |
| forwardtransformers.AlignModel.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L1104[{"name": "input_ids", "val": ": torch.LongTensor | None = None"}, {"name": "pixel_values", "val": ": torch.FloatTensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "token_type_ids", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.Tensor | None = None"}, {"name": "inputs_embeds", "val": ": torch.Tensor | None = None"}, {"name": "return_loss", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- **input_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Indices of input sequence tokens in the vocabulary. Padding will be ignored by default. | |
| Indices can be obtained using [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and | |
| [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details. | |
| [What are input IDs?](../glossary#input-ids) | |
| - **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`, *optional*) -- | |
| The tensors corresponding to the input images. Pixel values can be obtained using | |
| `EfficientNetImageProcessor`. See `EfficientNetImageProcessor.__call__()` for details ([AlignProcessor](/docs/transformers/main/ja/model_doc/align#transformers.AlignProcessor) uses | |
| `EfficientNetImageProcessor` for processing images). | |
| - **attention_mask** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: | |
| - 1 for tokens that are **not masked**, | |
| - 0 for tokens that are **masked**. | |
| [What are attention masks?](../glossary#attention-mask) | |
| - **token_type_ids** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: | |
| - 0 corresponds to a *sentence A* token, | |
| - 1 corresponds to a *sentence B* token. | |
| [What are token type IDs?](../glossary#token-type-ids) | |
| - **position_ids** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. | |
| [What are position IDs?](../glossary#position-ids) | |
| - **inputs_embeds** (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) -- | |
| Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This | |
| is useful if you want more control over how to convert `input_ids` indices into associated vectors than the | |
| model's internal embedding lookup matrix. | |
| - **return_loss** (`bool`, *optional*) -- | |
| Whether or not to return the contrastive loss.0`AlignOutput` or `tuple(torch.FloatTensor)`A `AlignOutput` or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| The [AlignModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignModel) forward method, overrides the `__call__` special method. | |
| Although the recipe for forward pass needs to be defined within this function, one should call the `Module` | |
| instance afterwards instead of this since the former takes care of running the pre and post processing steps while | |
| the latter silently ignores them. | |
| - **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`) -- Contrastive loss for image-text similarity. | |
| - **logits_per_image** (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`) -- The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text | |
| similarity scores. | |
| - **logits_per_text** (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`) -- The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image | |
| similarity scores. | |
| - **text_embeds** (`torch.FloatTensor` of shape `(batch_size, output_dim`) -- The text embeddings obtained by applying the projection layer to the pooled output of [AlignTextModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignTextModel). | |
| - **image_embeds** (`torch.FloatTensor` of shape `(batch_size, output_dim`) -- The output of [AlignVisionModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignVisionModel). | |
| - **text_model_output** (`~modeling_outputs.BaseModelOutputWithPooling`, defaults to `None`) -- The output of the [AlignTextModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignTextModel). | |
| - **vision_model_output** (`~modeling_outputs.BaseModelOutputWithPoolingAndNoAttention`, defaults to `None`) -- The output of the [AlignVisionModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignVisionModel). | |
| Examples: | |
| ```python | |
| >>> import torch | |
| >>> from transformers import AutoProcessor, AlignModel | |
| >>> from transformers.image_utils import load_image | |
| >>> model = AlignModel.from_pretrained("kakaobrain/align-base") | |
| >>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base") | |
| >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" | |
| >>> image = load_image(url) | |
| >>> inputs = processor( | |
| ... images=image, text=["a photo of a cat", "a photo of a dog"], return_tensors="pt", padding=True | |
| ... ) | |
| >>> with torch.inference_mode(): | |
| ... outputs = model(**inputs) | |
| >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score | |
| >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities | |
| ``` | |
| **Parameters:** | |
| config ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights. | |
| **Returns:** | |
| ``AlignOutput` or `tuple(torch.FloatTensor)`` | |
| A `AlignOutput` or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| #### get_text_features[[transformers.AlignModel.get_text_features]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L1041) | |
| - **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model. | |
| - **pooler_output** (`torch.FloatTensor` of shape `(batch_size, hidden_size)`) -- Last layer hidden-state of the first token of the sequence (classification token) after further processing | |
| through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns | |
| the classification token after processing through a linear layer and a tanh activation function. The linear | |
| layer weights are trained from the next sentence prediction (classification) objective during pretraining. | |
| - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. | |
| Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. | |
| - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, | |
| sequence_length)`. | |
| Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads. | |
| Examples: | |
| ```python | |
| >>> import torch | |
| >>> from transformers import AutoTokenizer, AlignModel | |
| >>> model = AlignModel.from_pretrained("kakaobrain/align-base") | |
| >>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base") | |
| >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") | |
| >>> with torch.inference_mode(): | |
| ... text_features = model.get_text_features(**inputs) | |
| ``` | |
| **Parameters:** | |
| input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of input sequence tokens in the vocabulary. Padding will be ignored by default. Indices can be obtained using [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](../glossary#input-ids) | |
| attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) | |
| token_type_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) | |
| position_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) : Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) | |
| inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. | |
| **Returns:** | |
| `[BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`` | |
| A [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| #### get_image_features[[transformers.AlignModel.get_image_features]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L1079) | |
| - **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model. | |
| - **pooler_output** (`torch.FloatTensor` of shape `(batch_size, hidden_size)`) -- Last layer hidden-state of the first token of the sequence (classification token) after further processing | |
| through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns | |
| the classification token after processing through a linear layer and a tanh activation function. The linear | |
| layer weights are trained from the next sentence prediction (classification) objective during pretraining. | |
| - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. | |
| Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. | |
| - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, | |
| sequence_length)`. | |
| Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads. | |
| Examples: | |
| ```python | |
| >>> import torch | |
| >>> from transformers import AutoProcessor, AlignModel | |
| >>> from transformers.image_utils import load_image | |
| >>> model = AlignModel.from_pretrained("kakaobrain/align-base") | |
| >>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base") | |
| >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" | |
| >>> image = load_image(url) | |
| >>> inputs = processor(images=image, return_tensors="pt") | |
| >>> with torch.inference_mode(): | |
| ... image_features = model.get_image_features(**inputs) | |
| ``` | |
| **Parameters:** | |
| pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`) : The tensors corresponding to the input images. Pixel values can be obtained using `EfficientNetImageProcessor`. See `EfficientNetImageProcessor.__call__()` for details ([AlignProcessor](/docs/transformers/main/ja/model_doc/align#transformers.AlignProcessor) uses `EfficientNetImageProcessor` for processing images). | |
| **Returns:** | |
| `[BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`` | |
| A [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| ## AlignTextModel[[transformers.AlignTextModel]] | |
| #### transformers.AlignTextModel[[transformers.AlignTextModel]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L825) | |
| The text model from ALIGN without any head or projection on top. | |
| This model inherits from [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the | |
| library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads | |
| etc.) | |
| This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. | |
| Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage | |
| and behavior. | |
| forwardtransformers.AlignTextModel.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L856[{"name": "input_ids", "val": ": torch.Tensor | None = None"}, {"name": "attention_mask", "val": ": torch.Tensor | None = None"}, {"name": "token_type_ids", "val": ": torch.Tensor | None = None"}, {"name": "position_ids", "val": ": torch.Tensor | None = None"}, {"name": "inputs_embeds", "val": ": torch.Tensor | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- **input_ids** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Indices of input sequence tokens in the vocabulary. Padding will be ignored by default. | |
| Indices can be obtained using [AutoTokenizer](/docs/transformers/main/ja/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and | |
| [PreTrainedTokenizer.__call__()](/docs/transformers/main/ja/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details. | |
| [What are input IDs?](../glossary#input-ids) | |
| - **attention_mask** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: | |
| - 1 for tokens that are **not masked**, | |
| - 0 for tokens that are **masked**. | |
| [What are attention masks?](../glossary#attention-mask) | |
| - **token_type_ids** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: | |
| - 0 corresponds to a *sentence A* token, | |
| - 1 corresponds to a *sentence B* token. | |
| [What are token type IDs?](../glossary#token-type-ids) | |
| - **position_ids** (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*) -- | |
| Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. | |
| [What are position IDs?](../glossary#position-ids) | |
| - **inputs_embeds** (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) -- | |
| Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This | |
| is useful if you want more control over how to convert `input_ids` indices into associated vectors than the | |
| model's internal embedding lookup matrix.0[BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`A [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| The [AlignTextModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignTextModel) forward method, overrides the `__call__` special method. | |
| Although the recipe for forward pass needs to be defined within this function, one should call the `Module` | |
| instance afterwards instead of this since the former takes care of running the pre and post processing steps while | |
| the latter silently ignores them. | |
| - **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model. | |
| - **pooler_output** (`torch.FloatTensor` of shape `(batch_size, hidden_size)`) -- Last layer hidden-state of the first token of the sequence (classification token) after further processing | |
| through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns | |
| the classification token after processing through a linear layer and a tanh activation function. The linear | |
| layer weights are trained from the next sentence prediction (classification) objective during pretraining. | |
| - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. | |
| Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. | |
| - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, | |
| sequence_length)`. | |
| Attentions weights after the attention softmax, used to compute the weighted average in the self-attention | |
| heads. | |
| Examples: | |
| ```python | |
| >>> from transformers import AutoTokenizer, AlignTextModel | |
| >>> model = AlignTextModel.from_pretrained("kakaobrain/align-base") | |
| >>> tokenizer = AutoTokenizer.from_pretrained("kakaobrain/align-base") | |
| >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt") | |
| >>> outputs = model(**inputs) | |
| >>> last_hidden_state = outputs.last_hidden_state | |
| >>> pooled_output = outputs.pooler_output # pooled (EOS token) states | |
| ``` | |
| **Parameters:** | |
| config ([AlignTextConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignTextConfig)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights. | |
| add_pooling_layer (`bool`, *optional*, defaults to `True`) : Whether to add a pooling layer | |
| **Returns:** | |
| `[BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or `tuple(torch.FloatTensor)`` | |
| A [BaseModelOutputWithPooling](/docs/transformers/main/ja/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPooling) or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| ## AlignVisionModel[[transformers.AlignVisionModel]] | |
| #### transformers.AlignVisionModel[[transformers.AlignVisionModel]] | |
| [Source](https://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L931) | |
| The vision model from ALIGN without any head or projection on top. | |
| This model inherits from [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel). Check the superclass documentation for the generic methods the | |
| library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads | |
| etc.) | |
| This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. | |
| Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage | |
| and behavior. | |
| forwardtransformers.AlignVisionModel.forwardhttps://github.com/huggingface/transformers/blob/main/src/transformers/models/align/modeling_align.py#L959[{"name": "pixel_values", "val": ": torch.FloatTensor | None = None"}, {"name": "**kwargs", "val": ": typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs]"}]- **pixel_values** (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`, *optional*) -- | |
| The tensors corresponding to the input images. Pixel values can be obtained using | |
| `EfficientNetImageProcessor`. See `EfficientNetImageProcessor.__call__()` for details ([AlignProcessor](/docs/transformers/main/ja/model_doc/align#transformers.AlignProcessor) uses | |
| `EfficientNetImageProcessor` for processing images).0`BaseModelOutputWithPoolingAndNoAttention` or `tuple(torch.FloatTensor)`A `BaseModelOutputWithPoolingAndNoAttention` or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
| The [AlignVisionModel](/docs/transformers/main/ja/model_doc/align#transformers.AlignVisionModel) forward method, overrides the `__call__` special method. | |
| Although the recipe for forward pass needs to be defined within this function, one should call the `Module` | |
| instance afterwards instead of this since the former takes care of running the pre and post processing steps while | |
| the latter silently ignores them. | |
| - **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`) -- Sequence of hidden-states at the output of the last layer of the model. | |
| - **pooler_output** (`torch.FloatTensor` of shape `(batch_size, hidden_size)`) -- Last layer hidden-state after a pooling operation on the spatial dimensions. | |
| - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + | |
| one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. | |
| Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. | |
| Examples: | |
| ```python | |
| >>> from PIL import Image | |
| >>> import httpx | |
| >>> from io import BytesIO | |
| >>> from transformers import AutoProcessor, AlignVisionModel | |
| >>> model = AlignVisionModel.from_pretrained("kakaobrain/align-base") | |
| >>> processor = AutoProcessor.from_pretrained("kakaobrain/align-base") | |
| >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" | |
| >>> with httpx.stream("GET", url) as response: | |
| ... image = Image.open(BytesIO(response.read())) | |
| >>> inputs = processor(images=image, return_tensors="pt") | |
| >>> outputs = model(**inputs) | |
| >>> last_hidden_state = outputs.last_hidden_state | |
| >>> pooled_output = outputs.pooler_output # pooled CLS states | |
| ``` | |
| **Parameters:** | |
| config ([AlignVisionConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignVisionConfig)) : Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights. | |
| **Returns:** | |
| ``BaseModelOutputWithPoolingAndNoAttention` or `tuple(torch.FloatTensor)`` | |
| A `BaseModelOutputWithPoolingAndNoAttention` or a tuple of | |
| `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various | |
| elements depending on the configuration ([AlignConfig](/docs/transformers/main/ja/model_doc/align#transformers.AlignConfig)) and inputs. | |
Xet Storage Details
- Size:
- 44.7 kB
- Xet hash:
- 796377853fed1d2391c7ac562155d4abada6435a4ff9b33203c339d58f23cf22
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.