Spaces:
Build error
Build error
| # coding=utf-8 | |
| # Copyright 2022 the Big Science Workshop and 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. | |
| """ VBloom configuration""" | |
| import os | |
| from typing import Tuple, Union | |
| from transformers import AutoConfig | |
| from transformers.configuration_utils import PretrainedConfig | |
| from transformers.utils import logging | |
| logger = logging.get_logger(__name__) | |
| BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP = { | |
| "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json", | |
| "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json", | |
| "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json", | |
| "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json", | |
| "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json", | |
| "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json", | |
| } | |
| class VBloomConfig(PretrainedConfig): | |
| """ | |
| This is the configuration class to store the configuration of a [`BloomModel`]. It is used to instantiate a Bloom | |
| model according to the specified arguments, defining the model architecture. Instantiating a configuration with the | |
| defaults will yield a similar configuration to the Bloom architecture | |
| [bigscience/bloom](https://huggingface.co/bigscience/bloom). | |
| Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the | |
| documentation from [`PretrainedConfig`] for more information. | |
| TODO: this doc is completely out of sync with the actual args | |
| Args: | |
| vocab_size (`int`, *optional*, defaults to 50257): | |
| Vocabulary size of the Bloom model. Defines the number of different tokens that can be represented by the | |
| `inputs_ids` passed when calling [`BloomModel`]. | |
| additional_vocab_size (`int`, *optional`, defaults to 0): | |
| Additional vocabulary size of the model, typically for the special "<img>" token. Additional vocab tokens | |
| are always trainable whereas regular vocab tokens can be frozen or not. | |
| hidden_size (`int`, *optional*, defaults to 768): | |
| Dimensionality of the embeddings and hidden states. | |
| n_layer (`int`, *optional*, defaults to 12): | |
| Number of hidden layers in the Transformer encoder. | |
| n_head (`int`, *optional*, defaults to 12): | |
| Number of attention heads for each attention layer in the Transformer encoder. | |
| attn_pdrop (`float`, *optional*, defaults to 0.1): | |
| The dropout ratio for the attention. | |
| layer_norm_epsilon (`float`, *optional*, defaults to 1e-5): | |
| The epsilon to use in the layer normalization layers. | |
| initializer_range (`float`, *optional*, defaults to 0.02): | |
| The standard deviation of the truncated_normal_initializer for initializing all weight matrices. | |
| alpha_initializer (`str`, *optional*, defaults to `"ones"`): | |
| Initialization type for the alphas. | |
| alphas_initializer_range (`float`, *optional*, defaults to 0.0): | |
| The standard deviation of the truncated_normal_initializer for initializing the alphas in the Gated Cross Attention. | |
| alpha_type (`str`, *optional*, defaults to `"vector"`): | |
| Whether the gating alphas should be vectors or single floats. | |
| apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`): | |
| If enabled, use the layer norm of the hidden states as the residual in the transformer blocks | |
| skip_bias_add (`bool`, *optional*, defaults to `True`): | |
| If set to `True`, it will skip bias add for each linear layer in the transformer blocks | |
| skip_bias_add_qkv (`bool`, *optional*, defaults to `False`): | |
| If set to `True`, it will skip bias add for the first linear layer in the transformer blocks | |
| hidden_dropout (`float`, *optional*, defaults to 0.1): | |
| Dropout rate of the dropout function on the bias dropout. | |
| attention_dropout (`float`, *optional*, defaults to 0.1): | |
| Dropout rate applied to the attention probs | |
| use_cache (`bool`, *optional*, defaults to `True`): | |
| Whether or not the model should return the last key/values attentions (not used by all models). | |
| pretraining_tp (`int`, *optional*, defaults to `1`): | |
| Experimental feature. Tensor parallelism rank used during pretraining with Megatron. Please refer to [this | |
| document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is | |
| necessary to ensure exact reproducibility of the pretraining results. Please refer to [this | |
| issue](https://github.com/pytorch/pytorch/issues/76232). Note also that this is enabled only when | |
| `slow_but_exact=True`. | |
| slow_but_exact (`bool`, *optional*, defaults to `False`): | |
| Experimental feature. Whether to use slow but exact implementation of the attention mechanism. While | |
| merging the TP rank tensors, due to slicing operations the results may be slightly different between the | |
| model trained on Megatron and our model. Please refer to [this | |
| issue](https://github.com/pytorch/pytorch/issues/76232). A solution to obtain more accurate results is to | |
| enable this feature. Enabling this will hurt the computational time of the inference. Will be probably | |
| resolved in the future once the main model has been fine-tuned with TP_rank=1. | |
| Example: | |
| ```python | |
| >>> from transformers import BloomModel, BloomConfig | |
| >>> # Initializing a Bloom configuration | |
| >>> configuration = BloomConfig() | |
| >>> # Initializing a model from the configuration | |
| >>> model = BloomModel(configuration) | |
| >>> # Accessing the model configuration | |
| >>> configuration = model.config | |
| ```""" | |
| model_type = "vbloom" | |
| keys_to_ignore_at_inference = ["past_key_values"] | |
| attribute_map = { | |
| "num_hidden_layers": "n_layer", | |
| "num_attention_heads": "n_head", | |
| } | |
| def __init__( | |
| self, | |
| vocab_size=250880, | |
| additional_vocab_size=0, | |
| hidden_size=64, | |
| n_layer=2, | |
| n_head=8, | |
| layer_norm_epsilon=1e-5, | |
| initializer_range=0.02, | |
| alpha_initializer="ones", | |
| alphas_initializer_range=0.0, | |
| alpha_type="vector", | |
| use_cache=False, | |
| bos_token_id=1, | |
| eos_token_id=2, | |
| apply_residual_connection_post_layernorm=False, | |
| hidden_dropout=0.0, | |
| attention_dropout=0.0, | |
| pretraining_tp=1, # TP rank used when training with megatron | |
| slow_but_exact=False, | |
| cross_layer_interval=1, | |
| tie_word_embeddings=False, | |
| freeze_text_layers=True, | |
| freeze_lm_head=False, | |
| freeze_vision_layers=True, | |
| vision_model_name="google/vit-base-patch16-224", | |
| vision_model_params="{}", | |
| vision_embed_dim=768, | |
| image_token_index=250880, | |
| use_resampler=False, | |
| resampler_n_latents=64, | |
| resampler_depth=6, | |
| resampler_n_heads=16, | |
| resampler_head_dim=96, | |
| **kwargs, | |
| ): | |
| self.vocab_size = vocab_size | |
| self.additional_vocab_size = additional_vocab_size | |
| # Backward compatibility with n_embed kwarg | |
| n_embed = kwargs.pop("n_embed", None) | |
| self.hidden_size = hidden_size if n_embed is None else n_embed | |
| self.n_layer = n_layer | |
| self.n_head = n_head | |
| self.layer_norm_epsilon = layer_norm_epsilon | |
| self.initializer_range = initializer_range | |
| self.alpha_initializer = alpha_initializer | |
| self.alphas_initializer_range = alphas_initializer_range | |
| self.alpha_type = alpha_type | |
| self.use_cache = use_cache | |
| self.pretraining_tp = pretraining_tp | |
| self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm | |
| self.hidden_dropout = hidden_dropout | |
| self.attention_dropout = attention_dropout | |
| self.bos_token_id = bos_token_id | |
| self.eos_token_id = eos_token_id | |
| self.slow_but_exact = slow_but_exact | |
| self.cross_layer_interval = cross_layer_interval | |
| self.freeze_vision_layers = freeze_vision_layers | |
| self.vision_model_name = vision_model_name | |
| self.vision_model_params = vision_model_params | |
| self.tie_word_embeddings = tie_word_embeddings | |
| self.freeze_text_layers = freeze_text_layers | |
| self.freeze_lm_head = freeze_lm_head | |
| self.image_token_index = image_token_index | |
| self.vision_embed_dim = vision_embed_dim | |
| # Resampler params | |
| self.use_resampler = use_resampler | |
| self.resampler_n_latents = resampler_n_latents | |
| self.resampler_depth = resampler_depth | |
| self.resampler_n_heads = resampler_n_heads | |
| self.resampler_head_dim = resampler_head_dim | |
| # IMPORTANT: Do not do any __init__ args-based checks in the constructor, since | |
| # PretrainedConfig.from_dict first instantiates the class with the config dict and only then | |
| # updates the config object with `kwargs` from from_pretrained, so during the instantiation | |
| # of this object many attributes have default values and haven't yet been overridden. | |
| # Do any required checks inside `from_pretrained` once the superclass' `from_pretrained` was run. | |
| super().__init__( | |
| bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs | |
| ) | |
| def check_compatibilities(self): | |
| if self.tie_word_embeddings and (self.freeze_text_layers != self.freeze_lm_head): | |
| raise ValueError( | |
| "if `tie_word_embeddings` is True, then `freeze_lm_head` and `freeze_text_layers` must be equal." | |
| ) | |
| vision_model_params = eval(self.vision_model_params) | |
| config = AutoConfig.from_pretrained(self.vision_model_name, **vision_model_params) | |
| if hasattr(config, "vision_config"): | |
| vison_config = config.vision_config | |
| else: | |
| vison_config = config | |
| vision_embed_dim = vison_config.hidden_size | |
| if self.vision_embed_dim != vision_embed_dim: | |
| raise ValueError( | |
| f"vision_embed_dim ({self.vision_embed_dim}) must match the hidden size of the vision model" | |
| f" ({vision_embed_dim})" | |
| ) | |
| def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig": | |
| outputs = super(VBloomConfig, cls).from_pretrained(pretrained_model_name_or_path, **kwargs) | |
| if isinstance(outputs, Tuple): | |
| # When called with return_unused_kwargs=True, the first item will be the config | |
| outputs[0].check_compatibilities() | |
| else: | |
| outputs.check_compatibilities() | |
| return outputs | |