ZTWHHH commited on
Commit
5acb76b
·
verified ·
1 Parent(s): 3caaa6e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-310.pyc +0 -0
  2. vllm/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-310.pyc +0 -0
  3. vllm/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__init__.py +29 -0
  5. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/__init__.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_flax_encoder_decoder.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_tf_encoder_decoder.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/configuration_encoder_decoder.py +111 -0
  11. vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/modeling_encoder_decoder.py +689 -0
  12. vllm/lib/python3.10/site-packages/transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py +144 -0
  14. vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__init__.py +27 -0
  15. vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__pycache__/__init__.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/transformers/models/granitemoe/configuration_granitemoe.py +194 -0
  19. vllm/lib/python3.10/site-packages/transformers/models/granitemoe/modeling_granitemoe.py +1402 -0
  20. vllm/lib/python3.10/site-packages/transformers/models/ibert/__init__.py +27 -0
  21. vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/__init__.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/configuration_ibert.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/modeling_ibert.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/quant_modules.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/transformers/models/ibert/configuration_ibert.py +142 -0
  26. vllm/lib/python3.10/site-packages/transformers/models/ibert/modeling_ibert.py +1366 -0
  27. vllm/lib/python3.10/site-packages/transformers/models/ibert/quant_modules.py +820 -0
  28. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/__init__.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/configuration_llava_next_video.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/image_processing_llava_next_video.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/modeling_llava_next_video.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/modular_llava_next_video.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/processing_llava_next_video.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/configuration_llava_next_video.py +165 -0
  35. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/image_processing_llava_next_video.py +399 -0
  36. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/modeling_llava_next_video.py +881 -0
  37. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/modular_llava_next_video.py +594 -0
  38. vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/processing_llava_next_video.py +288 -0
  39. vllm/lib/python3.10/site-packages/transformers/models/mamba/__init__.py +27 -0
  40. vllm/lib/python3.10/site-packages/transformers/models/mamba/__pycache__/__init__.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/transformers/models/mamba/__pycache__/configuration_mamba.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/transformers/models/mamba/__pycache__/modeling_mamba.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/transformers/models/mamba/configuration_mamba.py +160 -0
  44. vllm/lib/python3.10/site-packages/transformers/models/mamba/modeling_mamba.py +813 -0
  45. vllm/lib/python3.10/site-packages/transformers/models/mistral3/__init__.py +28 -0
  46. vllm/lib/python3.10/site-packages/transformers/models/mistral3/__pycache__/modular_mistral3.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/transformers/models/mistral3/configuration_mistral3.py +137 -0
  48. vllm/lib/python3.10/site-packages/transformers/models/mistral3/modular_mistral3.py +286 -0
  49. vllm/lib/python3.10/site-packages/transformers/models/oneformer/__init__.py +29 -0
  50. vllm/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (693 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-310.pyc ADDED
Binary file (53.4 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-310.pyc ADDED
Binary file (49.3 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_encoder_decoder import *
22
+ from .modeling_encoder_decoder import *
23
+ from .modeling_flax_encoder_decoder import *
24
+ from .modeling_tf_encoder_decoder import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (643 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-310.pyc ADDED
Binary file (4.06 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-310.pyc ADDED
Binary file (25.7 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_flax_encoder_decoder.cpython-310.pyc ADDED
Binary file (31.5 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_tf_encoder_decoder.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/configuration_encoder_decoder.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+ from ..auto import AutoConfig
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class EncoderDecoderConfig(PretrainedConfig):
27
+ r"""
28
+ [`EncoderDecoderConfig`] is the configuration class to store the configuration of a [`EncoderDecoderModel`]. It is
29
+ used to instantiate an Encoder Decoder model according to the specified arguments, defining the encoder and decoder
30
+ configs.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ kwargs (*optional*):
37
+ Dictionary of keyword arguments. Notably:
38
+
39
+ - **encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
40
+ the encoder config.
41
+ - **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
42
+ the decoder config.
43
+
44
+ Examples:
45
+
46
+ ```python
47
+ >>> from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel
48
+
49
+ >>> # Initializing a BERT google-bert/bert-base-uncased style configuration
50
+ >>> config_encoder = BertConfig()
51
+ >>> config_decoder = BertConfig()
52
+
53
+ >>> config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
54
+
55
+ >>> # Initializing a Bert2Bert model (with random weights) from the google-bert/bert-base-uncased style configurations
56
+ >>> model = EncoderDecoderModel(config=config)
57
+
58
+ >>> # Accessing the model configuration
59
+ >>> config_encoder = model.config.encoder
60
+ >>> config_decoder = model.config.decoder
61
+ >>> # set decoder config to causal lm
62
+ >>> config_decoder.is_decoder = True
63
+ >>> config_decoder.add_cross_attention = True
64
+
65
+ >>> # Saving the model, including its configuration
66
+ >>> model.save_pretrained("my-model")
67
+
68
+ >>> # loading model and config from pretrained folder
69
+ >>> encoder_decoder_config = EncoderDecoderConfig.from_pretrained("my-model")
70
+ >>> model = EncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)
71
+ ```"""
72
+
73
+ model_type = "encoder-decoder"
74
+ sub_configs = {"encoder": AutoConfig, "decoder": AutoConfig}
75
+ is_composition = True
76
+
77
+ def __init__(self, **kwargs):
78
+ super().__init__(**kwargs)
79
+ if "encoder" not in kwargs or "decoder" not in kwargs:
80
+ raise ValueError(
81
+ f"A configuraton of type {self.model_type} cannot be instantiated because "
82
+ f"both `encoder` and `decoder` sub-configurations were not passed, only {kwargs}"
83
+ )
84
+ encoder_config = kwargs.pop("encoder")
85
+ encoder_model_type = encoder_config.pop("model_type")
86
+ decoder_config = kwargs.pop("decoder")
87
+ decoder_model_type = decoder_config.pop("model_type")
88
+
89
+ self.encoder = AutoConfig.for_model(encoder_model_type, **encoder_config)
90
+ self.decoder = AutoConfig.for_model(decoder_model_type, **decoder_config)
91
+ self.is_encoder_decoder = True
92
+
93
+ @classmethod
94
+ def from_encoder_decoder_configs(
95
+ cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs
96
+ ) -> PretrainedConfig:
97
+ r"""
98
+ Instantiate a [`EncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and
99
+ decoder model configuration.
100
+
101
+ Returns:
102
+ [`EncoderDecoderConfig`]: An instance of a configuration object
103
+ """
104
+ logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config")
105
+ decoder_config.is_decoder = True
106
+ decoder_config.add_cross_attention = True
107
+
108
+ return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
109
+
110
+
111
+ __all__ = ["EncoderDecoderConfig"]
vllm/lib/python3.10/site-packages/transformers/models/encoder_decoder/modeling_encoder_decoder.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team.
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
+ """Classes to support Encoder-Decoder architectures"""
16
+
17
+ import gc
18
+ import inspect
19
+ import os
20
+ import tempfile
21
+ import warnings
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import CrossEntropyLoss
27
+
28
+ from ...configuration_utils import PretrainedConfig
29
+ from ...generation import GenerationMixin
30
+ from ...modeling_outputs import BaseModelOutput, Seq2SeqLMOutput
31
+ from ...modeling_utils import PreTrainedModel
32
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from ..auto.configuration_auto import AutoConfig
34
+ from ..auto.modeling_auto import AutoModel, AutoModelForCausalLM
35
+ from .configuration_encoder_decoder import EncoderDecoderConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CONFIG_FOR_DOC = "EncoderDecoderConfig"
41
+
42
+ DEPRECATION_WARNING = (
43
+ "Version v4.12.0 introduces a better way to train encoder-decoder models by computing the loss inside the"
44
+ " encoder-decoder framework rather than in the decoder itself. You may observe training discrepancies if"
45
+ " fine-tuning a model trained with versions anterior to 4.12.0. The decoder_input_ids are now created based on the"
46
+ " labels, no need to pass them yourself anymore."
47
+ )
48
+
49
+ ENCODER_DECODER_START_DOCSTRING = r"""
50
+ This class can be used to initialize a sequence-to-sequence model with any pretrained autoencoding model as the
51
+ encoder and any pretrained autoregressive model as the decoder. The encoder is loaded via
52
+ [`~AutoModel.from_pretrained`] function and the decoder is loaded via [`~AutoModelForCausalLM.from_pretrained`]
53
+ function. Cross-attention layers are automatically added to the decoder and should be fine-tuned on a downstream
54
+ generative task, like summarization.
55
+
56
+ The effectiveness of initializing sequence-to-sequence models with pretrained checkpoints for sequence generation
57
+ tasks was shown in [Leveraging Pre-trained Checkpoints for Sequence Generation
58
+ Tasks](https://arxiv.org/abs/1907.12461) by Sascha Rothe, Shashi Narayan, Aliaksei Severyn. Michael Matena, Yanqi
59
+ Zhou, Wei Li, Peter J. Liu.
60
+
61
+ After such an Encoder Decoder model has been trained/fine-tuned, it can be saved/loaded just like any other models
62
+ (see the examples for more information).
63
+
64
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
65
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
66
+ etc.)
67
+
68
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
69
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
70
+ and behavior.
71
+
72
+ Parameters:
73
+ config ([`EncoderDecoderConfig`]): Model configuration class with all the parameters of the model.
74
+ Initializing with a config file does not load the weights associated with the model, only the
75
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
76
+ """
77
+
78
+ ENCODER_DECODER_INPUTS_DOCSTRING = r"""
79
+ Args:
80
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
81
+ Indices of input sequence tokens in the vocabulary.
82
+
83
+ Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
84
+ [`PreTrainedTokenizer.__call__`] for details.
85
+
86
+ [What are input IDs?](../glossary#input-ids)
87
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
88
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
89
+
90
+ - 1 for tokens that are **not masked**,
91
+ - 0 for tokens that are **masked**.
92
+
93
+ [What are attention masks?](../glossary#attention-mask)
94
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
95
+ Indices of decoder input sequence tokens in the vocabulary.
96
+
97
+ Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
98
+ [`PreTrainedTokenizer.__call__`] for details.
99
+
100
+ [What are input IDs?](../glossary#input-ids)
101
+
102
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
103
+ `past_key_values`).
104
+
105
+ For training, `decoder_input_ids` are automatically created by the model by shifting the `labels` to the
106
+ right, replacing -100 by the `pad_token_id` and prepending them with the `decoder_start_token_id`.
107
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
108
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
109
+ be used by default.
110
+ encoder_outputs (`tuple(torch.FloatTensor)`, *optional*):
111
+ This tuple must consist of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
112
+ `last_hidden_state` (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) is a tensor
113
+ of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the
114
+ decoder.
115
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
116
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
117
+
118
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
119
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
120
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
121
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
122
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
123
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
124
+ model's internal embedding lookup matrix.
125
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
126
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
127
+ representation. This is useful if you want more control over how to convert `decoder_input_ids` indices
128
+ into associated vectors than the model's internal embedding lookup matrix.
129
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
130
+ Labels for computing the masked language modeling loss for the decoder. Indices should be in `[-100, 0,
131
+ ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
132
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
133
+ use_cache (`bool`, *optional*):
134
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
135
+ `past_key_values`).
136
+ output_attentions (`bool`, *optional*):
137
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
138
+ tensors for more detail.
139
+ output_hidden_states (`bool`, *optional*):
140
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
141
+ more detail.
142
+ return_dict (`bool`, *optional*):
143
+ If set to `True`, the model will return a [`~utils.Seq2SeqLMOutput`] instead of a plain tuple.
144
+ kwargs (*optional*): Remaining dictionary of keyword arguments. Keyword arguments come in two flavors:
145
+
146
+ - Without a prefix which will be input as `**encoder_kwargs` for the encoder forward function.
147
+ - With a *decoder_* prefix which will be input as `**decoder_kwargs` for the decoder forward function.
148
+ """
149
+
150
+
151
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
152
+ """
153
+ Shift input ids one token to the right.
154
+ """
155
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
156
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
157
+ if decoder_start_token_id is None:
158
+ raise ValueError("Make sure to set the decoder_start_token_id attribute of the model's configuration.")
159
+ shifted_input_ids[:, 0] = decoder_start_token_id
160
+
161
+ if pad_token_id is None:
162
+ raise ValueError("Make sure to set the pad_token_id attribute of the model's configuration.")
163
+ # replace possible -100 values in labels by `pad_token_id`
164
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
165
+
166
+ return shifted_input_ids
167
+
168
+
169
+ @add_start_docstrings(ENCODER_DECODER_START_DOCSTRING)
170
+ class EncoderDecoderModel(PreTrainedModel, GenerationMixin):
171
+ r"""
172
+ [`EncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with one
173
+ of the base model classes of the library as encoder and another one as decoder when created with the
174
+ :meth*~transformers.AutoModel.from_pretrained* class method for the encoder and
175
+ :meth*~transformers.AutoModelForCausalLM.from_pretrained* class method for the decoder.
176
+ """
177
+
178
+ config_class = EncoderDecoderConfig
179
+ base_model_prefix = "encoder_decoder"
180
+ main_input_name = "input_ids"
181
+ supports_gradient_checkpointing = True
182
+ _supports_param_buffer_assignment = False
183
+ _supports_flash_attn_2 = True
184
+ _supports_sdpa = True
185
+
186
+ def __init__(
187
+ self,
188
+ config: Optional[PretrainedConfig] = None,
189
+ encoder: Optional[PreTrainedModel] = None,
190
+ decoder: Optional[PreTrainedModel] = None,
191
+ ):
192
+ if config is None and (encoder is None or decoder is None):
193
+ raise ValueError("Either a configuration or an encoder and a decoder has to be provided.")
194
+ if config is None:
195
+ config = EncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config)
196
+ else:
197
+ if not isinstance(config, self.config_class):
198
+ raise ValueError(f"Config: {config} has to be of type {self.config_class}")
199
+
200
+ if config.decoder.cross_attention_hidden_size is not None:
201
+ if config.decoder.cross_attention_hidden_size != config.encoder.hidden_size:
202
+ raise ValueError(
203
+ "If `cross_attention_hidden_size` is specified in the decoder's configuration, it has to be equal"
204
+ f" to the encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for"
205
+ f" `config.decoder.cross_attention_hidden_size` and {config.encoder.hidden_size} for"
206
+ " `config.encoder.hidden_size`."
207
+ )
208
+
209
+ # initialize with config
210
+ super().__init__(config)
211
+
212
+ if encoder is None:
213
+ from ..auto.modeling_auto import AutoModel
214
+
215
+ encoder = AutoModel.from_config(config.encoder)
216
+
217
+ if decoder is None:
218
+ from ..auto.modeling_auto import AutoModelForCausalLM
219
+
220
+ decoder = AutoModelForCausalLM.from_config(config.decoder)
221
+
222
+ self.encoder = encoder
223
+ self.decoder = decoder
224
+
225
+ if self.encoder.config.to_dict() != self.config.encoder.to_dict():
226
+ logger.warning(
227
+ f"Config of the encoder: {self.encoder.__class__} is overwritten by shared encoder config:"
228
+ f" {self.config.encoder}"
229
+ )
230
+ if self.decoder.config.to_dict() != self.config.decoder.to_dict():
231
+ logger.warning(
232
+ f"Config of the decoder: {self.decoder.__class__} is overwritten by shared decoder config:"
233
+ f" {self.config.decoder}"
234
+ )
235
+
236
+ # make sure that the individual model's config refers to the shared config
237
+ # so that the updates to the config will be synced
238
+ # update `_attn_implementation` because the attn is set in a deepcopied config within PreTrainedModel
239
+ self.config.encoder._attn_implementation = self.encoder.config._attn_implementation
240
+ self.config.decoder._attn_implementation = self.decoder.config._attn_implementation
241
+ self.encoder.config = self.config.encoder
242
+ self.decoder.config = self.config.decoder
243
+
244
+ # encoder outputs might need to be projected to different dimension for decoder
245
+ if (
246
+ self.encoder.config.hidden_size != self.decoder.config.hidden_size
247
+ and self.decoder.config.cross_attention_hidden_size is None
248
+ ):
249
+ self.enc_to_dec_proj = nn.Linear(self.encoder.config.hidden_size, self.decoder.config.hidden_size)
250
+
251
+ if self.encoder.get_output_embeddings() is not None:
252
+ raise ValueError(
253
+ f"The encoder {self.encoder} should not have a LM Head. Please use a model without LM Head"
254
+ )
255
+
256
+ decoder_signature = set(inspect.signature(self.decoder.forward).parameters.keys())
257
+ if "encoder_hidden_states" not in decoder_signature:
258
+ raise ValueError(
259
+ "The selected decoder is not prepared for the encoder hidden states to be passed. Please see the "
260
+ "following discussion on GitHub: https://github.com/huggingface/transformers/issues/23350"
261
+ )
262
+
263
+ # tie encoder, decoder weights if config set accordingly
264
+ self.tie_weights()
265
+
266
+ def tie_weights(self):
267
+ # tie encoder & decoder if needed
268
+ if self.config.tie_encoder_decoder:
269
+ # tie encoder and decoder base model
270
+ decoder_base_model_prefix = self.decoder.base_model_prefix
271
+ tied_weights = self._tie_encoder_decoder_weights(
272
+ self.encoder,
273
+ self.decoder._modules[decoder_base_model_prefix],
274
+ self.decoder.base_model_prefix,
275
+ "encoder",
276
+ )
277
+ # Setting a dynamic variable instead of `_tied_weights_keys` because it's a class
278
+ # attributed not an instance member, therefore modifying it will modify the entire class
279
+ # Leading to issues on subsequent calls by different tests or subsequent calls.
280
+ self._dynamic_tied_weights_keys = tied_weights
281
+
282
+ def get_encoder(self):
283
+ return self.encoder
284
+
285
+ def get_decoder(self):
286
+ return self.decoder
287
+
288
+ def get_input_embeddings(self):
289
+ return self.encoder.get_input_embeddings()
290
+
291
+ def get_output_embeddings(self):
292
+ return self.decoder.get_output_embeddings()
293
+
294
+ def set_output_embeddings(self, new_embeddings):
295
+ return self.decoder.set_output_embeddings(new_embeddings)
296
+
297
+ @classmethod
298
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
299
+ r"""
300
+ Example:
301
+
302
+ ```python
303
+ >>> from transformers import EncoderDecoderModel
304
+
305
+ >>> model = EncoderDecoderModel.from_pretrained("patrickvonplaten/bert2bert-cnn_dailymail-fp16")
306
+ ```"""
307
+
308
+ from_tf = kwargs.pop("from_tf", False)
309
+ if from_tf:
310
+ from transformers import TFEncoderDecoderModel
311
+
312
+ # a workaround to load from tensorflow checkpoint
313
+ # Using `_tf_model` won't work, because the weight names in the encoder/decoder of `_tf_model` get
314
+ # extended before saving those components. For example, The name of `_tf_model.encoder.vit` is
315
+ # `[top model name]/encoder/vit`, but the name of `tf_model.encoder.vit` is `[top model name]/vit`. The
316
+ # [top model name] is handled (stripped) by the conversion method, and the former case gets extra `encoder`,
317
+ # which should not occur when we want to save the components alone.
318
+ # There was a (very) ugly potential fix, which wasn't integrated to `transformers`: see
319
+ # https://github.com/huggingface/transformers/pull/13222/commits/dbb3c9de76eee235791d2064094654637c99f36d#r697304245
320
+ # (the change in `src/transformers/modeling_tf_utils.py`)
321
+ _tf_model = TFEncoderDecoderModel.from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
322
+ config = _tf_model.config
323
+
324
+ # Using `tf_model` instead
325
+ encoder = _tf_model.encoder.__class__(_tf_model.config.encoder)
326
+ decoder = _tf_model.decoder.__class__(_tf_model.config.decoder)
327
+ # Make sure models are built
328
+ encoder(encoder.dummy_inputs)
329
+ decoder(decoder.dummy_inputs)
330
+
331
+ # Get the variable correspondence between `_tf_model` and `encoder` and `decoder`
332
+ encoder_variables = {}
333
+ for v in encoder.trainable_variables + encoder.non_trainable_variables:
334
+ encoder_variables["/".join(v.name.split("/")[1:])] = v
335
+ decoder_variables = {}
336
+ for v in decoder.trainable_variables + decoder.non_trainable_variables:
337
+ decoder_variables["/".join(v.name.split("/")[1:])] = v
338
+
339
+ _encoder_variables = {}
340
+ for v in _tf_model.encoder.trainable_variables + _tf_model.encoder.non_trainable_variables:
341
+ _encoder_variables["/".join(v.name.split("/")[2:])] = v
342
+ _decoder_variables = {}
343
+ for v in _tf_model.decoder.trainable_variables + _tf_model.decoder.non_trainable_variables:
344
+ _decoder_variables["/".join(v.name.split("/")[2:])] = v
345
+
346
+ # assign weight values to `encoder` and `decoder` from `_tf_model`
347
+ for name, v in encoder_variables.items():
348
+ v.assign(_encoder_variables[name])
349
+ for name, v in decoder_variables.items():
350
+ v.assign(_decoder_variables[name])
351
+
352
+ tf_model = TFEncoderDecoderModel(encoder=encoder, decoder=decoder)
353
+
354
+ # Deal with `enc_to_dec_proj`
355
+ if hasattr(_tf_model, "enc_to_dec_proj"):
356
+ tf_model(tf_model.dummy_inputs)
357
+ tf_model.enc_to_dec_proj.kernel.assign(_tf_model.enc_to_dec_proj.kernel)
358
+ tf_model.enc_to_dec_proj.bias.assign(_tf_model.enc_to_dec_proj.bias)
359
+
360
+ with tempfile.TemporaryDirectory() as tmpdirname:
361
+ encoder_dir = os.path.join(tmpdirname, "encoder")
362
+ decoder_dir = os.path.join(tmpdirname, "decoder")
363
+ tf_model.encoder.save_pretrained(encoder_dir)
364
+ tf_model.decoder.save_pretrained(decoder_dir)
365
+
366
+ if hasattr(tf_model, "enc_to_dec_proj"):
367
+ enc_to_dec_proj_weight = torch.transpose(
368
+ torch.from_numpy(tf_model.enc_to_dec_proj.kernel.numpy()), 1, 0
369
+ )
370
+ enc_to_dec_proj_bias = torch.from_numpy(tf_model.enc_to_dec_proj.bias.numpy())
371
+
372
+ del _tf_model
373
+ del tf_model
374
+ gc.collect()
375
+
376
+ model = EncoderDecoderModel.from_encoder_decoder_pretrained(
377
+ encoder_dir, decoder_dir, encoder_from_tf=True, decoder_from_tf=True
378
+ )
379
+ # This is only for copying some specific attributes of this particular model.
380
+ model.config = config
381
+
382
+ if hasattr(model, "enc_to_dec_proj"):
383
+ model.enc_to_dec_proj.weight.data = enc_to_dec_proj_weight.contiguous()
384
+ model.enc_to_dec_proj.bias.data = enc_to_dec_proj_bias.contiguous()
385
+
386
+ return model
387
+
388
+ # At the moment fast initialization is not supported for composite models
389
+ if kwargs.get("_fast_init", False):
390
+ logger.warning(
391
+ "Fast initialization is currently not supported for EncoderDecoderModel. "
392
+ "Falling back to slow initialization..."
393
+ )
394
+ kwargs["_fast_init"] = False
395
+
396
+ return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
397
+
398
+ @classmethod
399
+ def from_encoder_decoder_pretrained(
400
+ cls,
401
+ encoder_pretrained_model_name_or_path: str = None,
402
+ decoder_pretrained_model_name_or_path: str = None,
403
+ *model_args,
404
+ **kwargs,
405
+ ) -> PreTrainedModel:
406
+ r"""
407
+ Instantiate an encoder and a decoder from one or two base classes of the library from pretrained model
408
+ checkpoints.
409
+
410
+
411
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
412
+ the model, you need to first set it back in training mode with `model.train()`.
413
+
414
+ Params:
415
+ encoder_pretrained_model_name_or_path (`str`, *optional*):
416
+ Information necessary to initiate the encoder. Can be either:
417
+
418
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
419
+ - A path to a *directory* containing model weights saved using
420
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
421
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
422
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
423
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
424
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
425
+
426
+ decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
427
+ Information necessary to initiate the decoder. Can be either:
428
+
429
+ - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
430
+ - A path to a *directory* containing model weights saved using
431
+ [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
432
+ - A path or url to a *tensorflow index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In
433
+ this case, `from_tf` should be set to `True` and a configuration object should be provided as
434
+ `config` argument. This loading path is slower than converting the TensorFlow checkpoint in a
435
+ PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards.
436
+
437
+ model_args (remaining positional arguments, *optional*):
438
+ All remaining positional arguments will be passed to the underlying model's `__init__` method.
439
+
440
+ kwargs (remaining dictionary of keyword arguments, *optional*):
441
+ Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
442
+ `output_attentions=True`).
443
+
444
+ - To update the encoder configuration, use the prefix *encoder_* for each configuration parameter.
445
+ - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter.
446
+ - To update the parent model configuration, do not use a prefix for each configuration parameter.
447
+
448
+ Behaves differently depending on whether a `config` is provided or automatically loaded.
449
+
450
+ Example:
451
+
452
+ ```python
453
+ >>> from transformers import EncoderDecoderModel
454
+
455
+ >>> # initialize a bert2bert from two pretrained BERT models. Note that the cross-attention layers will be randomly initialized
456
+ >>> model = EncoderDecoderModel.from_encoder_decoder_pretrained("google-bert/bert-base-uncased", "google-bert/bert-base-uncased")
457
+ >>> # saving model after fine-tuning
458
+ >>> model.save_pretrained("./bert2bert")
459
+ >>> # load fine-tuned model
460
+ >>> model = EncoderDecoderModel.from_pretrained("./bert2bert")
461
+ ```"""
462
+
463
+ kwargs_encoder = {
464
+ argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_")
465
+ }
466
+
467
+ kwargs_decoder = {
468
+ argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
469
+ }
470
+
471
+ # remove encoder, decoder kwargs from kwargs
472
+ for key in kwargs_encoder.keys():
473
+ del kwargs["encoder_" + key]
474
+ for key in kwargs_decoder.keys():
475
+ del kwargs["decoder_" + key]
476
+
477
+ # Load and initialize the encoder and decoder
478
+ # The distinction between encoder and decoder at the model level is made
479
+ # by the value of the flag `is_decoder` that we need to set correctly.
480
+ encoder = kwargs_encoder.pop("model", None)
481
+ if encoder is None:
482
+ if encoder_pretrained_model_name_or_path is None:
483
+ raise ValueError(
484
+ "If `encoder_model` is not defined as an argument, a `encoder_pretrained_model_name_or_path` has "
485
+ "to be defined."
486
+ )
487
+
488
+ if "config" not in kwargs_encoder:
489
+ encoder_config, kwargs_encoder = AutoConfig.from_pretrained(
490
+ encoder_pretrained_model_name_or_path, **kwargs_encoder, return_unused_kwargs=True
491
+ )
492
+
493
+ if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True:
494
+ logger.info(
495
+ f"Initializing {encoder_pretrained_model_name_or_path} as a encoder model "
496
+ "from a decoder model. Cross-attention and casual mask are disabled."
497
+ )
498
+ encoder_config.is_decoder = False
499
+ encoder_config.add_cross_attention = False
500
+
501
+ kwargs_encoder["config"] = encoder_config
502
+
503
+ encoder = AutoModel.from_pretrained(encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder)
504
+
505
+ decoder = kwargs_decoder.pop("model", None)
506
+ if decoder is None:
507
+ if decoder_pretrained_model_name_or_path is None:
508
+ raise ValueError(
509
+ "If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has "
510
+ "to be defined."
511
+ )
512
+
513
+ if "config" not in kwargs_decoder:
514
+ decoder_config, kwargs_decoder = AutoConfig.from_pretrained(
515
+ decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True
516
+ )
517
+
518
+ if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False:
519
+ logger.info(
520
+ f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention"
521
+ f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if"
522
+ f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers."
523
+ )
524
+ decoder_config.is_decoder = True
525
+ decoder_config.add_cross_attention = True
526
+
527
+ kwargs_decoder["config"] = decoder_config
528
+
529
+ if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False:
530
+ logger.warning(
531
+ f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. "
532
+ f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, "
533
+ "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` "
534
+ "passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a "
535
+ "`decoder_config` to `.from_encoder_decoder_pretrained(...)`"
536
+ )
537
+
538
+ decoder = AutoModelForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder)
539
+
540
+ # instantiate config with corresponding kwargs
541
+ config = EncoderDecoderConfig.from_encoder_decoder_configs(encoder.config, decoder.config, **kwargs)
542
+ return cls(encoder=encoder, decoder=decoder, config=config)
543
+
544
+ @add_start_docstrings_to_model_forward(ENCODER_DECODER_INPUTS_DOCSTRING)
545
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
546
+ def forward(
547
+ self,
548
+ input_ids: Optional[torch.LongTensor] = None,
549
+ attention_mask: Optional[torch.FloatTensor] = None,
550
+ decoder_input_ids: Optional[torch.LongTensor] = None,
551
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
552
+ encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
553
+ past_key_values: Tuple[Tuple[torch.FloatTensor]] = None,
554
+ inputs_embeds: Optional[torch.FloatTensor] = None,
555
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
556
+ labels: Optional[torch.LongTensor] = None,
557
+ use_cache: Optional[bool] = None,
558
+ output_attentions: Optional[bool] = None,
559
+ output_hidden_states: Optional[bool] = None,
560
+ return_dict: Optional[bool] = None,
561
+ **kwargs,
562
+ ) -> Union[Tuple, Seq2SeqLMOutput]:
563
+ r"""
564
+ Returns:
565
+
566
+ Examples:
567
+
568
+ ```python
569
+ >>> from transformers import EncoderDecoderModel, BertTokenizer
570
+ >>> import torch
571
+
572
+ >>> tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
573
+ >>> model = EncoderDecoderModel.from_encoder_decoder_pretrained(
574
+ ... "google-bert/bert-base-uncased", "google-bert/bert-base-uncased"
575
+ ... ) # initialize Bert2Bert from pre-trained checkpoints
576
+
577
+ >>> # training
578
+ >>> model.config.decoder_start_token_id = tokenizer.cls_token_id
579
+ >>> model.config.pad_token_id = tokenizer.pad_token_id
580
+ >>> model.config.vocab_size = model.config.decoder.vocab_size
581
+
582
+ >>> input_ids = tokenizer("This is a really long text", return_tensors="pt").input_ids
583
+ >>> labels = tokenizer("This is the corresponding summary", return_tensors="pt").input_ids
584
+ >>> outputs = model(input_ids=input_ids, labels=labels)
585
+ >>> loss, logits = outputs.loss, outputs.logits
586
+
587
+ >>> # save and load from pretrained
588
+ >>> model.save_pretrained("bert2bert")
589
+ >>> model = EncoderDecoderModel.from_pretrained("bert2bert")
590
+
591
+ >>> # generation
592
+ >>> generated = model.generate(input_ids)
593
+ ```"""
594
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
595
+
596
+ kwargs_encoder = {argument: value for argument, value in kwargs.items() if not argument.startswith("decoder_")}
597
+
598
+ kwargs_decoder = {
599
+ argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_")
600
+ }
601
+ if "num_items_in_batch" in kwargs_encoder:
602
+ kwargs_decoder["num_items_in_batch"] = kwargs_encoder.pop("num_items_in_batch", None)
603
+
604
+ if encoder_outputs is None:
605
+ encoder_outputs = self.encoder(
606
+ input_ids=input_ids,
607
+ attention_mask=attention_mask,
608
+ inputs_embeds=inputs_embeds,
609
+ output_attentions=output_attentions,
610
+ output_hidden_states=output_hidden_states,
611
+ return_dict=return_dict,
612
+ **kwargs_encoder,
613
+ )
614
+ elif isinstance(encoder_outputs, tuple):
615
+ encoder_outputs = BaseModelOutput(*encoder_outputs)
616
+
617
+ encoder_hidden_states = encoder_outputs[0]
618
+
619
+ # optionally project encoder_hidden_states
620
+ if (
621
+ self.encoder.config.hidden_size != self.decoder.config.hidden_size
622
+ and self.decoder.config.cross_attention_hidden_size is None
623
+ ):
624
+ encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states)
625
+
626
+ if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None):
627
+ decoder_input_ids = shift_tokens_right(
628
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
629
+ )
630
+ if decoder_attention_mask is None:
631
+ decoder_attention_mask = decoder_input_ids.new_tensor(decoder_input_ids != self.config.pad_token_id)
632
+
633
+ # Decode
634
+ decoder_outputs = self.decoder(
635
+ input_ids=decoder_input_ids,
636
+ attention_mask=decoder_attention_mask,
637
+ encoder_hidden_states=encoder_hidden_states,
638
+ encoder_attention_mask=attention_mask,
639
+ inputs_embeds=decoder_inputs_embeds,
640
+ output_attentions=output_attentions,
641
+ output_hidden_states=output_hidden_states,
642
+ use_cache=use_cache,
643
+ past_key_values=past_key_values,
644
+ return_dict=return_dict,
645
+ **kwargs_decoder,
646
+ )
647
+
648
+ # Compute loss independent from decoder (as some shift the logits inside them)
649
+ loss = None
650
+ if labels is not None:
651
+ warnings.warn(DEPRECATION_WARNING, FutureWarning)
652
+ logits = decoder_outputs.logits if return_dict else decoder_outputs[0]
653
+ loss_fct = CrossEntropyLoss()
654
+ loss = loss_fct(logits.reshape(-1, self.decoder.config.vocab_size), labels.view(-1))
655
+
656
+ if not return_dict:
657
+ if loss is not None:
658
+ return (loss,) + decoder_outputs + encoder_outputs
659
+ else:
660
+ return decoder_outputs + encoder_outputs
661
+
662
+ return Seq2SeqLMOutput(
663
+ loss=loss,
664
+ logits=decoder_outputs.logits,
665
+ past_key_values=decoder_outputs.past_key_values,
666
+ decoder_hidden_states=decoder_outputs.hidden_states,
667
+ decoder_attentions=decoder_outputs.attentions,
668
+ cross_attentions=decoder_outputs.cross_attentions,
669
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
670
+ encoder_hidden_states=encoder_outputs.hidden_states,
671
+ encoder_attentions=encoder_outputs.attentions,
672
+ )
673
+
674
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
675
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
676
+
677
+ def resize_token_embeddings(self, *args, **kwargs):
678
+ raise NotImplementedError(
679
+ "Resizing the embedding layers via the EncoderDecoderModel directly is not supported. Please use the"
680
+ " respective methods of the wrapped objects (model.encoder.resize_token_embeddings(...) or"
681
+ " model.decoder.resize_token_embeddings(...))"
682
+ )
683
+
684
+ def _reorder_cache(self, past_key_values, beam_idx):
685
+ # apply decoder cache reordering here
686
+ return self.decoder._reorder_cache(past_key_values, beam_idx)
687
+
688
+
689
+ __all__ = ["EncoderDecoderModel"]
vllm/lib/python3.10/site-packages/transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-310.pyc ADDED
Binary file (35.8 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The BigCode team and HuggingFace Inc. team.
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
+ """GPTBigCode configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class GPTBigCodeConfig(PretrainedConfig):
25
+ """
26
+ This is the configuration class to store the configuration of a [`GPTBigCodeModel`]. It is used to instantiate a
27
+ GPTBigCode model according to the specified arguments, defining the model architecture. Instantiating a
28
+ configuration with the defaults will yield a similar configuration to that of the GPTBigCode
29
+ [gpt_bigcode](https://huggingface.co/gpt_bigcode) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 50257):
37
+ Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`GPTBigCodeModel`].
39
+ n_positions (`int`, *optional*, defaults to 1024):
40
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
41
+ just in case (e.g., 512 or 1024 or 2048).
42
+ n_embd (`int`, *optional*, defaults to 768):
43
+ Dimensionality of the embeddings and hidden states.
44
+ n_layer (`int`, *optional*, defaults to 12):
45
+ Number of hidden layers in the Transformer encoder.
46
+ n_head (`int`, *optional*, defaults to 12):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ n_inner (`int`, *optional*, defaults to None):
49
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
50
+ activation_function (`str`, *optional*, defaults to `"gelu_pytorch_tanh"`):
51
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new",
52
+ "gelu_pytorch_tanh"]`.
53
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
54
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
55
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
56
+ The dropout ratio for the embeddings.
57
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for the attention.
59
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
60
+ The epsilon to use in the layer normalization layers.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
64
+ Scale attention weights by dividing by sqrt(hidden_size)..
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models).
67
+ attention_softmax_in_fp32 (`bool`, *optional*, defaults to `True`):
68
+ Whether to call the fused softmax in float32.
69
+ scale_attention_softmax_in_fp32 (`bool`, *optional*, defaults to `True`):
70
+ Whether to scale the attention softmax in float32.
71
+ attention_type (`bool`, *optional*, defaults to `True`):
72
+ Whether to use Multi-Query Attion (`True`) or Multi-Head Attention (`False`).
73
+ Example:
74
+
75
+ ```python
76
+ >>> from transformers import GPTBigCodeConfig, GPTBigCodeModel
77
+
78
+ >>> # Initializing a GPTBigCode configuration
79
+ >>> configuration = GPTBigCodeConfig()
80
+
81
+ >>> # Initializing a model (with random weights) from the configuration
82
+ >>> model = GPTBigCodeModel(configuration)
83
+
84
+ >>> # Accessing the model configuration
85
+ >>> configuration = model.config
86
+ ```"""
87
+
88
+ model_type = "gpt_bigcode"
89
+ keys_to_ignore_at_inference = ["past_key_values"]
90
+ attribute_map = {
91
+ "hidden_size": "n_embd",
92
+ "max_position_embeddings": "n_positions",
93
+ "num_attention_heads": "n_head",
94
+ "num_hidden_layers": "n_layer",
95
+ }
96
+
97
+ def __init__(
98
+ self,
99
+ vocab_size=50257,
100
+ n_positions=1024,
101
+ n_embd=768,
102
+ n_layer=12,
103
+ n_head=12,
104
+ n_inner=None,
105
+ activation_function="gelu_pytorch_tanh",
106
+ resid_pdrop=0.1,
107
+ embd_pdrop=0.1,
108
+ attn_pdrop=0.1,
109
+ layer_norm_epsilon=1e-5,
110
+ initializer_range=0.02,
111
+ scale_attn_weights=True,
112
+ use_cache=True,
113
+ bos_token_id=50256,
114
+ eos_token_id=50256,
115
+ attention_softmax_in_fp32=True,
116
+ scale_attention_softmax_in_fp32=True,
117
+ multi_query=True,
118
+ **kwargs,
119
+ ):
120
+ self.vocab_size = vocab_size
121
+ self.n_positions = n_positions
122
+ self.n_embd = n_embd
123
+ self.n_layer = n_layer
124
+ self.n_head = n_head
125
+ self.n_inner = n_inner
126
+ self.activation_function = activation_function
127
+ self.resid_pdrop = resid_pdrop
128
+ self.embd_pdrop = embd_pdrop
129
+ self.attn_pdrop = attn_pdrop
130
+ self.layer_norm_epsilon = layer_norm_epsilon
131
+ self.initializer_range = initializer_range
132
+ self.scale_attn_weights = scale_attn_weights
133
+ self.use_cache = use_cache
134
+ self.attention_softmax_in_fp32 = attention_softmax_in_fp32
135
+ self.scale_attention_softmax_in_fp32 = scale_attention_softmax_in_fp32
136
+ self.multi_query = multi_query
137
+
138
+ self.bos_token_id = bos_token_id
139
+ self.eos_token_id = eos_token_id
140
+
141
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
142
+
143
+
144
+ __all__ = ["GPTBigCodeConfig"]
vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_granitemoe import *
22
+ from .modeling_granitemoe import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (548 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-310.pyc ADDED
Binary file (7.78 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-310.pyc ADDED
Binary file (42.8 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/granitemoe/configuration_granitemoe.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """GraniteMoe model configuration"""
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...modeling_rope_utils import rope_config_validation
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class GraniteMoeConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`GraniteMoeModel`]. It is used to instantiate an GraniteMoe
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the GraniteMoe-3B.
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 32000):
42
+ Vocabulary size of the GraniteMoe model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`GraniteMoeModel`]
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 11008):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
63
+ The maximum sequence length that this model might ever be used with.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*):
72
+ Padding token id.
73
+ bos_token_id (`int`, *optional*, defaults to 1):
74
+ Beginning of stream token id.
75
+ eos_token_id (`int`, *optional*, defaults to 2):
76
+ End of stream token id.
77
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
78
+ Whether to tie weight embeddings
79
+ rope_theta (`float`, *optional*, defaults to 10000.0):
80
+ The base period of the RoPE embeddings.
81
+ rope_scaling (`Dict`, *optional*):
82
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
83
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
84
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
85
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
86
+ these scaling strategies behave:
87
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
88
+ experimental feature, subject to breaking API changes in future versions.
89
+ attention_bias (`bool`, *optional*, defaults to `False`):
90
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
91
+ attention_dropout (`float`, *optional*, defaults to 0.0):
92
+ The dropout ratio for the attention probabilities.
93
+ embedding_multiplier (`float`, *optional*, defaults to 1.0): embedding multiplier
94
+ logits_scaling (`float`, *optional*, defaults to 1.0): divisor for output logits
95
+ residual_multiplier (`float`, *optional*, defaults to 1.0): residual multiplier
96
+ attention_multiplier (`float`, *optional*, defaults to 1.0): attention multiplier
97
+ num_local_experts (`int`, *optional*, defaults to 8): total number of experts
98
+ num_experts_per_tok (`int`, *optional*, defaults to 2): number of experts per token
99
+ output_router_logits (`bool`, *optional*, defaults to `False`):
100
+ Whether or not the router logits should be returned by the model. Enabeling this will also
101
+ allow the model to output the auxiliary loss.
102
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001): router auxialiary loss coefficient
103
+
104
+ ```python
105
+ >>> from transformers import GraniteMoeModel, GraniteMoeConfig
106
+
107
+ >>> # Initializing a GraniteMoe granitemoe-3b style configuration
108
+ >>> configuration = GraniteMoeConfig()
109
+
110
+ >>> # Initializing a model from the granitemoe-7b style configuration
111
+ >>> model = GraniteMoeModel(configuration)
112
+
113
+ >>> # Accessing the model configuration
114
+ >>> configuration = model.config
115
+ ```"""
116
+
117
+ model_type = "granitemoe"
118
+ keys_to_ignore_at_inference = ["past_key_values"]
119
+
120
+ def __init__(
121
+ self,
122
+ vocab_size=32000,
123
+ hidden_size=4096,
124
+ intermediate_size=11008,
125
+ num_hidden_layers=32,
126
+ num_attention_heads=32,
127
+ num_key_value_heads=None,
128
+ hidden_act="silu",
129
+ max_position_embeddings=2048,
130
+ initializer_range=0.02,
131
+ rms_norm_eps=1e-6,
132
+ use_cache=True,
133
+ pad_token_id=None,
134
+ bos_token_id=1,
135
+ eos_token_id=2,
136
+ tie_word_embeddings=False,
137
+ rope_theta=10000.0,
138
+ rope_scaling=None,
139
+ attention_bias=False,
140
+ attention_dropout=0.0,
141
+ embedding_multiplier=1.0,
142
+ logits_scaling=1.0,
143
+ residual_multiplier=1.0,
144
+ attention_multiplier=1.0,
145
+ num_local_experts=8,
146
+ num_experts_per_tok=2,
147
+ output_router_logits=False,
148
+ router_aux_loss_coef=0.001,
149
+ **kwargs,
150
+ ):
151
+ self.vocab_size = vocab_size
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.hidden_size = hidden_size
154
+ self.intermediate_size = intermediate_size
155
+ self.num_hidden_layers = num_hidden_layers
156
+ self.num_attention_heads = num_attention_heads
157
+
158
+ # for backward compatibility
159
+ if num_key_value_heads is None:
160
+ num_key_value_heads = num_attention_heads
161
+
162
+ self.num_key_value_heads = num_key_value_heads
163
+ self.hidden_act = hidden_act
164
+ self.initializer_range = initializer_range
165
+ self.rms_norm_eps = rms_norm_eps
166
+ self.use_cache = use_cache
167
+ self.rope_theta = rope_theta
168
+ self.rope_scaling = rope_scaling
169
+
170
+ self.attention_bias = attention_bias
171
+ self.attention_dropout = attention_dropout
172
+
173
+ self.embedding_multiplier = embedding_multiplier
174
+ self.logits_scaling = logits_scaling
175
+ self.residual_multiplier = residual_multiplier
176
+ self.attention_multiplier = attention_multiplier
177
+
178
+ self.num_local_experts = num_local_experts
179
+ self.num_experts_per_tok = num_experts_per_tok
180
+ self.output_router_logits = output_router_logits
181
+ self.router_aux_loss_coef = router_aux_loss_coef
182
+
183
+ super().__init__(
184
+ pad_token_id=pad_token_id,
185
+ bos_token_id=bos_token_id,
186
+ eos_token_id=eos_token_id,
187
+ tie_word_embeddings=tie_word_embeddings,
188
+ **kwargs,
189
+ )
190
+
191
+ rope_config_validation(self)
192
+
193
+
194
+ __all__ = ["GraniteMoeConfig"]
vllm/lib/python3.10/site-packages/transformers/models/granitemoe/modeling_granitemoe.py ADDED
@@ -0,0 +1,1402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache, StaticCache
25
+ from ...generation import GenerationMixin
26
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
27
+ from ...modeling_flash_attention_utils import _flash_attention_forward
28
+ from ...modeling_outputs import (
29
+ BaseModelOutputWithPast,
30
+ MoeCausalLMOutputWithPast,
31
+ MoeModelOutputWithPast,
32
+ )
33
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...pytorch_utils import ALL_LAYERNORM_LAYERS
36
+ from ...utils import (
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ is_flash_attn_greater_or_equal_2_10,
40
+ is_torch_flex_attn_available,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+ from .configuration_granitemoe import GraniteMoeConfig
45
+
46
+
47
+ if is_torch_flex_attn_available():
48
+ from torch.nn.attention.flex_attention import BlockMask
49
+
50
+ from ...integrations.flex_attention import make_flex_block_causal_mask
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "GraniteMoeConfig"
56
+
57
+
58
+ # Copied from transformers.models.jetmoe.modeling_jetmoe.load_balancing_loss_func
59
+ def load_balancing_loss_func(
60
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
61
+ num_experts: Optional[int] = None,
62
+ top_k=2,
63
+ attention_mask: Optional[torch.Tensor] = None,
64
+ ) -> Union[torch.Tensor, int]:
65
+ r"""
66
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
67
+
68
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
69
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
70
+ experts is too unbalanced.
71
+
72
+ Args:
73
+ gate_logits:
74
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
75
+ shape [batch_size X sequence_length, num_experts].
76
+ num_experts:
77
+ Number of experts
78
+ top_k:
79
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
80
+ parameter.
81
+ attention_mask (`torch.Tensor`, *optional*):
82
+ The attention_mask used in forward function
83
+ shape [batch_size X sequence_length] if not None.
84
+
85
+ Returns:
86
+ The auxiliary loss.
87
+ """
88
+ if gate_logits is None or not isinstance(gate_logits, tuple):
89
+ return 0
90
+
91
+ if isinstance(gate_logits, tuple):
92
+ compute_device = gate_logits[0].device
93
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
94
+
95
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
96
+
97
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
98
+
99
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
100
+
101
+ if attention_mask is None:
102
+ # Compute the percentage of tokens routed to each experts
103
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
104
+
105
+ # Compute the average probability of routing to these experts
106
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
107
+ else:
108
+ batch_size, sequence_length = attention_mask.shape
109
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
110
+
111
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
112
+ expert_attention_mask = (
113
+ attention_mask[None, :, :, None, None]
114
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
115
+ .reshape(-1, top_k, num_experts)
116
+ .to(compute_device)
117
+ )
118
+
119
+ # Compute the percentage of tokens routed to each experts
120
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
121
+ expert_attention_mask, dim=0
122
+ )
123
+
124
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
125
+ router_per_expert_attention_mask = (
126
+ attention_mask[None, :, :, None]
127
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
128
+ .reshape(-1, num_experts)
129
+ .to(compute_device)
130
+ )
131
+
132
+ # Compute the average probability of routing to these experts
133
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
134
+ router_per_expert_attention_mask, dim=0
135
+ )
136
+
137
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
138
+ return overall_loss * num_experts
139
+
140
+
141
+ # Copied from transformers.models.granite.modeling_granite.GraniteRMSNorm with Granite->GraniteMoe
142
+ class GraniteMoeRMSNorm(nn.Module):
143
+ def __init__(self, hidden_size, eps=1e-6):
144
+ """
145
+ GraniteMoeRMSNorm is equivalent to T5LayerNorm
146
+ """
147
+ super().__init__()
148
+ self.weight = nn.Parameter(torch.ones(hidden_size))
149
+ self.variance_epsilon = eps
150
+
151
+ def forward(self, hidden_states):
152
+ input_dtype = hidden_states.dtype
153
+ hidden_states = hidden_states.to(torch.float32)
154
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
155
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
156
+ return self.weight * hidden_states.to(input_dtype)
157
+
158
+ def extra_repr(self):
159
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
160
+
161
+
162
+ ALL_LAYERNORM_LAYERS.append(GraniteMoeRMSNorm)
163
+
164
+
165
+ # Copied from transformers.models.granite.modeling_granite.GraniteRotaryEmbedding with Granite->GraniteMoe
166
+ class GraniteMoeRotaryEmbedding(nn.Module):
167
+ def __init__(self, config: GraniteMoeConfig, device=None):
168
+ super().__init__()
169
+ # BC: "rope_type" was originally "type"
170
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
171
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
172
+ else:
173
+ self.rope_type = "default"
174
+ self.max_seq_len_cached = config.max_position_embeddings
175
+ self.original_max_seq_len = config.max_position_embeddings
176
+
177
+ self.config = config
178
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
179
+
180
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
181
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
182
+ self.original_inv_freq = self.inv_freq
183
+
184
+ def _dynamic_frequency_update(self, position_ids, device):
185
+ """
186
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
187
+ 1 - growing beyond the cached sequence length (allow scaling)
188
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
189
+ """
190
+ seq_len = torch.max(position_ids) + 1
191
+ if seq_len > self.max_seq_len_cached: # growth
192
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
193
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
194
+ self.max_seq_len_cached = seq_len
195
+
196
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
197
+ # This .to() is needed if the model has been moved to a device after being initialized (because
198
+ # the buffer is automatically moved, but not the original copy)
199
+ self.original_inv_freq = self.original_inv_freq.to(device)
200
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
201
+ self.max_seq_len_cached = self.original_max_seq_len
202
+
203
+ @torch.no_grad()
204
+ def forward(self, x, position_ids):
205
+ if "dynamic" in self.rope_type:
206
+ self._dynamic_frequency_update(position_ids, device=x.device)
207
+
208
+ # Core RoPE block
209
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
210
+ position_ids_expanded = position_ids[:, None, :].float()
211
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
212
+ device_type = x.device.type
213
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
214
+ with torch.autocast(device_type=device_type, enabled=False):
215
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
216
+ emb = torch.cat((freqs, freqs), dim=-1)
217
+ cos = emb.cos()
218
+ sin = emb.sin()
219
+
220
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
221
+ cos = cos * self.attention_scaling
222
+ sin = sin * self.attention_scaling
223
+
224
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
225
+
226
+
227
+ # Copied from transformers.models.granite.modeling_granite.rotate_half with Granite->GraniteMoe
228
+ def rotate_half(x):
229
+ """Rotates half the hidden dims of the input."""
230
+ x1 = x[..., : x.shape[-1] // 2]
231
+ x2 = x[..., x.shape[-1] // 2 :]
232
+ return torch.cat((-x2, x1), dim=-1)
233
+
234
+
235
+ # Copied from transformers.models.granite.modeling_granite.apply_rotary_pos_emb with Granite->GraniteMoe
236
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
237
+ """Applies Rotary Position Embedding to the query and key tensors.
238
+
239
+ Args:
240
+ q (`torch.Tensor`): The query tensor.
241
+ k (`torch.Tensor`): The key tensor.
242
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
243
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
244
+ position_ids (`torch.Tensor`, *optional*):
245
+ Deprecated and unused.
246
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
247
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
248
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
249
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
250
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
251
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
252
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
253
+ Returns:
254
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
255
+ """
256
+ cos = cos.unsqueeze(unsqueeze_dim)
257
+ sin = sin.unsqueeze(unsqueeze_dim)
258
+ q_embed = (q * cos) + (rotate_half(q) * sin)
259
+ k_embed = (k * cos) + (rotate_half(k) * sin)
260
+ return q_embed, k_embed
261
+
262
+
263
+ # Copied from transformers.models.jetmoe.modeling_jetmoe.JetMoeParallelExperts with JetMoe->GraniteMoe
264
+ class GraniteMoeParallelExperts(nn.Module):
265
+ def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
266
+ """
267
+ Initialize the GraniteMoeParallelExperts module.
268
+ The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's comptible with
269
+ many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
270
+ [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
271
+ [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
272
+ used in vllm.
273
+ Args:
274
+ num_experts (int):
275
+ Number of experts.
276
+ input_size (int):
277
+ Size of the input.
278
+ output_size (int):
279
+ Size of the output.
280
+ """
281
+ super().__init__()
282
+ self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
283
+ self.num_experts = num_experts
284
+ self.input_size = input_size
285
+ self.output_size = output_size
286
+
287
+ def forward(self, inputs, expert_size):
288
+ """
289
+ Forward pass of the GraniteMoeParallelExperts module.
290
+ Args:
291
+ inputs (Tensor):
292
+ Input tensor.
293
+ expert_size:
294
+ Expert size information.
295
+ Returns:
296
+ Tensor: Output tensor.
297
+ """
298
+ input_list = inputs.split(expert_size, dim=0)
299
+ output_list = []
300
+ for i in range(self.num_experts):
301
+ output_list.append(F.linear(input_list[i], self.weight[i]))
302
+ results = torch.cat(output_list, dim=0)
303
+ return results
304
+
305
+
306
+ # Copied from transformers.models.jetmoe.modeling_jetmoe.JetMoeTopKGating with JetMoe->GraniteMoe
307
+ class GraniteMoeTopKGating(nn.Module):
308
+ def __init__(self, input_size: int, num_experts: int, top_k: int):
309
+ """
310
+ Initialize the top-k gating mechanism.
311
+ Args:
312
+ input_size (`int`):
313
+ Size of the input.
314
+ num_experts (`int`):
315
+ Number of experts.
316
+ top_k (`int`):
317
+ Number of top experts to select.
318
+ """
319
+ super().__init__()
320
+
321
+ self.num_experts = num_experts
322
+ self.input_size = input_size
323
+ self.top_k = top_k
324
+
325
+ self.layer = nn.Linear(input_size, num_experts, bias=False)
326
+
327
+ def forward(self, hidden_states):
328
+ # compute the top_k routing decision
329
+ logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
330
+ top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
331
+ top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
332
+
333
+ # compute number of input given to each expert
334
+ zeros = torch.zeros(
335
+ [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
336
+ ) # [num_tokens, num_experts]
337
+ gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
338
+ expert_size = gates.long().sum(0) # [num_experts,]
339
+ # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
340
+ # (and `DataDependentOutputException`)
341
+ expert_size = expert_size.tolist()
342
+
343
+ # sort and group input tokens according to expert assignment
344
+ top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
345
+ _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
346
+ batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
347
+
348
+ # gather the gate values for grouped input tokens
349
+ top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
350
+ batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
351
+
352
+ return index_sorted_experts, batch_index, batch_gates, expert_size, logits
353
+
354
+
355
+ class GraniteMoeMoE(nn.Module):
356
+ """
357
+ A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
358
+
359
+ Args:
360
+ config:
361
+ Configuration object with model hyperparameters.
362
+ """
363
+
364
+ def __init__(self, config: GraniteMoeConfig):
365
+ super(GraniteMoeMoE, self).__init__()
366
+
367
+ self.input_size = config.hidden_size
368
+ self.hidden_size = config.intermediate_size
369
+ self.activation = ACT2FN[config.hidden_act]
370
+ self.input_linear = GraniteMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size * 2)
371
+ self.output_linear = GraniteMoeParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)
372
+
373
+ self.router = GraniteMoeTopKGating(
374
+ input_size=self.input_size,
375
+ num_experts=config.num_local_experts,
376
+ top_k=config.num_experts_per_tok,
377
+ )
378
+
379
+ def forward(self, layer_input):
380
+ """
381
+ Forward pass of the mixture of experts layer.
382
+
383
+ Args:
384
+ layer_input (Tensor):
385
+ Input tensor.
386
+
387
+ Returns:
388
+ Tensor:
389
+ Output tensor.
390
+ Tensor:
391
+ Router logits.
392
+ """
393
+ bsz, length, emb_size = layer_input.size()
394
+ layer_input = layer_input.reshape(-1, emb_size)
395
+ _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
396
+
397
+ expert_inputs = layer_input[batch_index]
398
+ hidden_states = self.input_linear(expert_inputs, expert_size)
399
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
400
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
401
+ expert_outputs = self.output_linear(hidden_states, expert_size)
402
+
403
+ expert_outputs = expert_outputs * batch_gates[:, None]
404
+
405
+ zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
406
+ layer_output = zeros.index_add(0, batch_index, expert_outputs)
407
+ layer_output = layer_output.view(bsz, length, self.input_size)
408
+ return layer_output, router_logits
409
+
410
+
411
+ # Copied from transformers.models.granite.modeling_granite.repeat_kv with Granite->GraniteMoe
412
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
413
+ """
414
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
415
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
416
+ """
417
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
418
+ if n_rep == 1:
419
+ return hidden_states
420
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
421
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
422
+
423
+
424
+ # copied from transformers.models.granite.modeling_granite.GraniteAttention with Granite->GraniteMoe
425
+ # no longer copied after attention refactors
426
+ class GraniteMoeAttention(nn.Module):
427
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
428
+
429
+ def __init__(self, config: GraniteMoeConfig, layer_idx: Optional[int] = None):
430
+ super().__init__()
431
+ self.config = config
432
+ self.layer_idx = layer_idx
433
+ if layer_idx is None:
434
+ logger.warning_once(
435
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
436
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
437
+ "when creating this class."
438
+ )
439
+
440
+ self.attention_dropout = config.attention_dropout
441
+ self.hidden_size = config.hidden_size
442
+ self.num_heads = config.num_attention_heads
443
+ self.head_dim = self.hidden_size // self.num_heads
444
+ self.num_key_value_heads = config.num_key_value_heads
445
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
446
+ self.is_causal = True
447
+
448
+ self.scaling = config.attention_multiplier
449
+
450
+ if (self.head_dim * self.num_heads) != self.hidden_size:
451
+ raise ValueError(
452
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
453
+ f" and `num_heads`: {self.num_heads})."
454
+ )
455
+
456
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
457
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
458
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
459
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
460
+
461
+ def forward(
462
+ self,
463
+ hidden_states: torch.Tensor,
464
+ attention_mask: Optional[torch.Tensor] = None,
465
+ position_ids: Optional[torch.LongTensor] = None,
466
+ past_key_value: Optional[Cache] = None,
467
+ output_attentions: bool = False,
468
+ use_cache: bool = False,
469
+ cache_position: Optional[torch.LongTensor] = None,
470
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
471
+ **kwargs,
472
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
473
+ bsz, q_len, _ = hidden_states.size()
474
+
475
+ query_states = self.q_proj(hidden_states)
476
+ key_states = self.k_proj(hidden_states)
477
+ value_states = self.v_proj(hidden_states)
478
+
479
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
480
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
481
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
482
+
483
+ cos, sin = position_embeddings
484
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
485
+
486
+ if past_key_value is not None:
487
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
488
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
489
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
490
+
491
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
492
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
493
+
494
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
495
+
496
+ if attention_mask is not None: # no matter the length, we just slice it
497
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
498
+ attn_weights = attn_weights + causal_mask
499
+
500
+ # upcast attention to fp32
501
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
502
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
503
+ attn_output = torch.matmul(attn_weights, value_states)
504
+
505
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
506
+ raise ValueError(
507
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
508
+ f" {attn_output.size()}"
509
+ )
510
+
511
+ attn_output = attn_output.transpose(1, 2).contiguous()
512
+
513
+ attn_output = attn_output.view(bsz, q_len, -1)
514
+ attn_output = self.o_proj(attn_output)
515
+
516
+ if not output_attentions:
517
+ attn_weights = None
518
+
519
+ return attn_output, attn_weights, past_key_value
520
+
521
+
522
+ # NO LONGER EXIST Copied from transformers.models.granite.modeling_granite.GraniteFlashAttention2 with Granite->GraniteMoe
523
+ # TODO cyril: modular
524
+ class GraniteMoeFlashAttention2(GraniteMoeAttention):
525
+ """
526
+ GraniteMoe flash attention module. This module inherits from `GraniteMoeAttention` as the weights of the module stays
527
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
528
+ flash attention and deal with padding tokens in case the input contains any of them.
529
+ """
530
+
531
+ def __init__(self, *args, **kwargs):
532
+ super().__init__(*args, **kwargs)
533
+
534
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
535
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
536
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
537
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
538
+
539
+ def forward(
540
+ self,
541
+ hidden_states: torch.Tensor,
542
+ attention_mask: Optional[torch.LongTensor] = None,
543
+ position_ids: Optional[torch.LongTensor] = None,
544
+ past_key_value: Optional[Cache] = None,
545
+ output_attentions: bool = False,
546
+ use_cache: bool = False,
547
+ cache_position: Optional[torch.LongTensor] = None,
548
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
549
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
550
+ output_attentions = False
551
+
552
+ bsz, q_len, _ = hidden_states.size()
553
+
554
+ query_states = self.q_proj(hidden_states)
555
+ key_states = self.k_proj(hidden_states)
556
+ value_states = self.v_proj(hidden_states)
557
+
558
+ # Flash attention requires the input to have the shape
559
+ # batch_size x seq_length x head_dim x hidden_dim
560
+ # therefore we just need to keep the original shape
561
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
562
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
563
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
564
+
565
+ cos, sin = position_embeddings
566
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
567
+
568
+ if past_key_value is not None:
569
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
570
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
571
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
572
+
573
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
574
+ # to be able to avoid many of these transpose/reshape/view.
575
+ query_states = query_states.transpose(1, 2)
576
+ key_states = key_states.transpose(1, 2)
577
+ value_states = value_states.transpose(1, 2)
578
+
579
+ dropout_rate = self.attention_dropout if self.training else 0.0
580
+
581
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
582
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
583
+ # cast them back in the correct dtype just to be sure everything works as expected.
584
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
585
+ # in fp32. (GraniteMoeRMSNorm handles it correctly)
586
+
587
+ input_dtype = query_states.dtype
588
+ if input_dtype == torch.float32:
589
+ if torch.is_autocast_enabled():
590
+ target_dtype = torch.get_autocast_gpu_dtype()
591
+ # Handle the case where the model is quantized
592
+ elif hasattr(self.config, "_pre_quantization_dtype"):
593
+ target_dtype = self.config._pre_quantization_dtype
594
+ else:
595
+ target_dtype = self.q_proj.weight.dtype
596
+
597
+ logger.warning_once(
598
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
599
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
600
+ f" {target_dtype}."
601
+ )
602
+
603
+ query_states = query_states.to(target_dtype)
604
+ key_states = key_states.to(target_dtype)
605
+ value_states = value_states.to(target_dtype)
606
+
607
+ attn_output = _flash_attention_forward(
608
+ query_states,
609
+ key_states,
610
+ value_states,
611
+ attention_mask,
612
+ q_len,
613
+ position_ids=position_ids,
614
+ dropout=dropout_rate,
615
+ softmax_scale=self.scaling,
616
+ sliding_window=getattr(self, "sliding_window", None),
617
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
618
+ is_causal=self.is_causal,
619
+ )
620
+
621
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
622
+ attn_output = self.o_proj(attn_output)
623
+
624
+ if not output_attentions:
625
+ attn_weights = None
626
+
627
+ return attn_output, attn_weights, past_key_value
628
+
629
+
630
+ # NO LONGER EXIST Copied from transformers.models.granite.modeling_granite.GraniteSdpaAttention with Granite->GraniteMoe
631
+ # TODO cyril: modular
632
+ class GraniteMoeSdpaAttention(GraniteMoeAttention):
633
+ """
634
+ GraniteMoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
635
+ `GraniteMoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
636
+ SDPA API.
637
+ """
638
+
639
+ # Adapted from GraniteMoeAttention.forward
640
+ def forward(
641
+ self,
642
+ hidden_states: torch.Tensor,
643
+ attention_mask: Optional[torch.Tensor] = None,
644
+ position_ids: Optional[torch.LongTensor] = None,
645
+ past_key_value: Optional[Cache] = None,
646
+ output_attentions: bool = False,
647
+ use_cache: bool = False,
648
+ cache_position: Optional[torch.LongTensor] = None,
649
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
650
+ **kwargs,
651
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
652
+ if output_attentions:
653
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
654
+ logger.warning_once(
655
+ "GraniteMoeModel is using GraniteMoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
656
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
657
+ )
658
+ return super().forward(
659
+ hidden_states=hidden_states,
660
+ attention_mask=attention_mask,
661
+ position_ids=position_ids,
662
+ past_key_value=past_key_value,
663
+ output_attentions=output_attentions,
664
+ use_cache=use_cache,
665
+ cache_position=cache_position,
666
+ position_embeddings=position_embeddings,
667
+ )
668
+
669
+ bsz, q_len, _ = hidden_states.size()
670
+
671
+ query_states = self.q_proj(hidden_states)
672
+ key_states = self.k_proj(hidden_states)
673
+ value_states = self.v_proj(hidden_states)
674
+
675
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
676
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
677
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
678
+
679
+ cos, sin = position_embeddings
680
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
681
+
682
+ if past_key_value is not None:
683
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
684
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
685
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
686
+
687
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
688
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
689
+
690
+ causal_mask = attention_mask
691
+ if attention_mask is not None:
692
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
693
+
694
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
695
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
696
+ if query_states.device.type == "cuda" and causal_mask is not None:
697
+ query_states = query_states.contiguous()
698
+ key_states = key_states.contiguous()
699
+ value_states = value_states.contiguous()
700
+
701
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
702
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
703
+ is_causal = True if causal_mask is None and q_len > 1 else False
704
+
705
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
706
+ query_states,
707
+ key_states,
708
+ value_states,
709
+ attn_mask=causal_mask,
710
+ dropout_p=self.attention_dropout if self.training else 0.0,
711
+ is_causal=is_causal,
712
+ scale=self.scaling,
713
+ )
714
+
715
+ attn_output = attn_output.transpose(1, 2).contiguous()
716
+ attn_output = attn_output.view(bsz, q_len, -1)
717
+
718
+ attn_output = self.o_proj(attn_output)
719
+
720
+ return attn_output, None, past_key_value
721
+
722
+
723
+ GRANITEMOE_ATTENTION_CLASSES = {
724
+ "eager": GraniteMoeAttention,
725
+ "flash_attention_2": GraniteMoeFlashAttention2,
726
+ "sdpa": GraniteMoeSdpaAttention,
727
+ }
728
+
729
+
730
+ class GraniteMoeDecoderLayer(nn.Module):
731
+ def __init__(self, config: GraniteMoeConfig, layer_idx: int):
732
+ super().__init__()
733
+ self.hidden_size = config.hidden_size
734
+
735
+ self.self_attn = GRANITEMOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
736
+
737
+ self.block_sparse_moe = GraniteMoeMoE(config)
738
+ self.input_layernorm = GraniteMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
739
+ self.post_attention_layernorm = GraniteMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
740
+
741
+ self.residual_multiplier = config.residual_multiplier
742
+
743
+ def forward(
744
+ self,
745
+ hidden_states: torch.Tensor,
746
+ attention_mask: Optional[torch.Tensor] = None,
747
+ position_ids: Optional[torch.LongTensor] = None,
748
+ past_key_value: Optional[Cache] = None,
749
+ output_attentions: Optional[bool] = False,
750
+ use_cache: Optional[bool] = False,
751
+ cache_position: Optional[torch.LongTensor] = None,
752
+ output_router_logits: Optional[bool] = False,
753
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
754
+ **kwargs,
755
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
756
+ """
757
+ Args:
758
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
759
+ attention_mask (`torch.FloatTensor`, *optional*):
760
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
761
+ query_sequence_length, key_sequence_length)` if default attention is used.
762
+ output_attentions (`bool`, *optional*):
763
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
764
+ returned tensors for more detail.
765
+ use_cache (`bool`, *optional*):
766
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
767
+ (see `past_key_values`).
768
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
769
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
770
+ Indices depicting the position of the input sequence tokens in the sequence
771
+ output_router_logits (`bool`, *optional*):
772
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
773
+ should not be returned during inference.
774
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
775
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
776
+ with `head_dim` being the embedding dimension of each attention head.
777
+ kwargs (`dict`, *optional*):
778
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
779
+ into the model
780
+ """
781
+ residual = hidden_states
782
+
783
+ hidden_states = self.input_layernorm(hidden_states)
784
+
785
+ # Self Attention
786
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
787
+ hidden_states=hidden_states,
788
+ attention_mask=attention_mask,
789
+ position_ids=position_ids,
790
+ past_key_value=past_key_value,
791
+ output_attentions=output_attentions,
792
+ use_cache=use_cache,
793
+ cache_position=cache_position,
794
+ position_embeddings=position_embeddings,
795
+ **kwargs,
796
+ )
797
+
798
+ hidden_states = residual + hidden_states * self.residual_multiplier
799
+
800
+ # Fully Connected
801
+ residual = hidden_states
802
+ hidden_states = self.post_attention_layernorm(hidden_states)
803
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
804
+
805
+ hidden_states = residual + hidden_states * self.residual_multiplier
806
+
807
+ outputs = (hidden_states,)
808
+
809
+ if output_attentions:
810
+ outputs += (self_attn_weights,)
811
+
812
+ if use_cache:
813
+ outputs += (present_key_value,)
814
+
815
+ if output_router_logits:
816
+ outputs += (router_logits,)
817
+
818
+ return outputs
819
+
820
+
821
+ GRANITEMOE_START_DOCSTRING = r"""
822
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
823
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
824
+ etc.)
825
+
826
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
827
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
828
+ and behavior.
829
+
830
+ Parameters:
831
+ config ([`GraniteMoeConfig`]):
832
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
833
+ load the weights associated with the model, only the configuration. Check out the
834
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
835
+ """
836
+
837
+
838
+ @add_start_docstrings(
839
+ "The bare GraniteMoe Model outputting raw hidden-states without any specific head on top.",
840
+ GRANITEMOE_START_DOCSTRING,
841
+ )
842
+ class GraniteMoePreTrainedModel(PreTrainedModel):
843
+ config_class = GraniteMoeConfig
844
+ base_model_prefix = "model"
845
+ supports_gradient_checkpointing = True
846
+ _no_split_modules = ["GraniteMoeDecoderLayer"]
847
+ _skip_keys_device_placement = ["past_key_values"]
848
+ _supports_flash_attn_2 = True
849
+ _supports_sdpa = True
850
+ _supports_cache_class = True
851
+ _supports_quantized_cache = True
852
+ _supports_static_cache = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
853
+
854
+ def _init_weights(self, module):
855
+ std = self.config.initializer_range
856
+ if isinstance(module, nn.Linear):
857
+ module.weight.data.normal_(mean=0.0, std=std)
858
+ if module.bias is not None:
859
+ module.bias.data.zero_()
860
+ elif isinstance(module, nn.Embedding):
861
+ module.weight.data.normal_(mean=0.0, std=std)
862
+ if module.padding_idx is not None:
863
+ module.weight.data[module.padding_idx].zero_()
864
+ elif isinstance(module, nn.LayerNorm):
865
+ module.bias.data.zero_()
866
+ module.weight.data.fill_(1.0)
867
+ elif isinstance(module, GraniteMoeParallelExperts):
868
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
869
+
870
+
871
+ GRANITEMOE_INPUTS_DOCSTRING = r"""
872
+ Args:
873
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
874
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
875
+ it.
876
+
877
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
878
+ [`PreTrainedTokenizer.__call__`] for details.
879
+
880
+ [What are input IDs?](../glossary#input-ids)
881
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
882
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
883
+
884
+ - 1 for tokens that are **not masked**,
885
+ - 0 for tokens that are **masked**.
886
+
887
+ [What are attention masks?](../glossary#attention-mask)
888
+
889
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
890
+ [`PreTrainedTokenizer.__call__`] for details.
891
+
892
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
893
+ `past_key_values`).
894
+
895
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
896
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
897
+ information on the default strategy.
898
+
899
+ - 1 indicates the head is **not masked**,
900
+ - 0 indicates the head is **masked**.
901
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
902
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
903
+ config.n_positions - 1]`.
904
+
905
+ [What are position IDs?](../glossary#position-ids)
906
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
907
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
908
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
909
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
910
+
911
+ Two formats are allowed:
912
+ - a [`~cache_utils.Cache`] instance;
913
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
914
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
915
+ cache format.
916
+
917
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
918
+ legacy cache format will be returned.
919
+
920
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
921
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
922
+ of shape `(batch_size, sequence_length)`.
923
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
924
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
925
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
926
+ model's internal embedding lookup matrix.
927
+ use_cache (`bool`, *optional*):
928
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
929
+ `past_key_values`).
930
+ output_attentions (`bool`, *optional*):
931
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
932
+ tensors for more detail.
933
+ output_hidden_states (`bool`, *optional*):
934
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
935
+ more detail.
936
+ return_dict (`bool`, *optional*):
937
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
938
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
939
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
940
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
941
+ the complete sequence length.
942
+ """
943
+
944
+
945
+ @add_start_docstrings(
946
+ "The bare GraniteMoe Model outputting raw hidden-states without any specific head on top.",
947
+ GRANITEMOE_START_DOCSTRING,
948
+ )
949
+ class GraniteMoeModel(GraniteMoePreTrainedModel):
950
+ """
951
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GraniteMoeDecoderLayer`]
952
+
953
+ Args:
954
+ config: GraniteMoeConfig
955
+ """
956
+
957
+ def __init__(self, config: GraniteMoeConfig):
958
+ super().__init__(config)
959
+ self.padding_idx = config.pad_token_id
960
+ self.vocab_size = config.vocab_size
961
+
962
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
963
+ self.layers = nn.ModuleList(
964
+ [GraniteMoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
965
+ )
966
+ self.norm = GraniteMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
967
+ self.gradient_checkpointing = False
968
+
969
+ self.embedding_multiplier = config.embedding_multiplier
970
+ self.hidden_size = config.hidden_size
971
+ self.num_heads = config.num_attention_heads
972
+ self.head_dim = self.hidden_size // self.num_heads
973
+ self.max_position_embeddings = config.max_position_embeddings
974
+ self.rope_theta = config.rope_theta
975
+
976
+ # rope
977
+ self.rotary_emb = GraniteMoeRotaryEmbedding(config)
978
+
979
+ # Initialize weights and apply final processing
980
+ self.post_init()
981
+
982
+ def get_input_embeddings(self):
983
+ return self.embed_tokens
984
+
985
+ def set_input_embeddings(self, value):
986
+ self.embed_tokens = value
987
+
988
+ @add_start_docstrings_to_model_forward(GRANITEMOE_INPUTS_DOCSTRING)
989
+ def forward(
990
+ self,
991
+ input_ids: torch.LongTensor = None,
992
+ attention_mask: Optional[torch.Tensor] = None,
993
+ position_ids: Optional[torch.LongTensor] = None,
994
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
995
+ inputs_embeds: Optional[torch.FloatTensor] = None,
996
+ use_cache: Optional[bool] = None,
997
+ output_attentions: Optional[bool] = None,
998
+ output_hidden_states: Optional[bool] = None,
999
+ output_router_logits: Optional[bool] = None,
1000
+ return_dict: Optional[bool] = None,
1001
+ cache_position: Optional[torch.LongTensor] = None,
1002
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1003
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1004
+ output_hidden_states = (
1005
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1006
+ )
1007
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1008
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1009
+
1010
+ if (input_ids is None) ^ (inputs_embeds is not None):
1011
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1012
+
1013
+ if self.gradient_checkpointing and self.training and use_cache:
1014
+ logger.warning_once(
1015
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1016
+ )
1017
+ use_cache = False
1018
+
1019
+ if inputs_embeds is None:
1020
+ inputs_embeds = self.embed_tokens(input_ids)
1021
+
1022
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
1023
+
1024
+ return_legacy_cache = False
1025
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
1026
+ return_legacy_cache = True
1027
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1028
+ logger.warning_once(
1029
+ "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1030
+ "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
1031
+ )
1032
+
1033
+ if cache_position is None:
1034
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1035
+ cache_position = torch.arange(
1036
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1037
+ )
1038
+ if position_ids is None:
1039
+ position_ids = cache_position.unsqueeze(0)
1040
+
1041
+ causal_mask = self._update_causal_mask(
1042
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1043
+ )
1044
+
1045
+ # embed positions
1046
+ hidden_states = inputs_embeds
1047
+
1048
+ # create position embeddings to be shared across the decoder layers
1049
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1050
+
1051
+ # decoder layers
1052
+ all_hidden_states = () if output_hidden_states else None
1053
+ all_self_attns = () if output_attentions else None
1054
+ all_router_logits = () if output_router_logits else None
1055
+ next_decoder_cache = None
1056
+
1057
+ for decoder_layer in self.layers:
1058
+ if output_hidden_states:
1059
+ all_hidden_states += (hidden_states,)
1060
+
1061
+ if self.gradient_checkpointing and self.training:
1062
+ layer_outputs = self._gradient_checkpointing_func(
1063
+ decoder_layer.__call__,
1064
+ hidden_states,
1065
+ causal_mask,
1066
+ position_ids,
1067
+ past_key_values,
1068
+ output_attentions,
1069
+ use_cache,
1070
+ cache_position,
1071
+ output_router_logits,
1072
+ position_embeddings,
1073
+ )
1074
+ else:
1075
+ layer_outputs = decoder_layer(
1076
+ hidden_states,
1077
+ attention_mask=causal_mask,
1078
+ position_ids=position_ids,
1079
+ past_key_value=past_key_values,
1080
+ output_attentions=output_attentions,
1081
+ use_cache=use_cache,
1082
+ cache_position=cache_position,
1083
+ output_router_logits=output_router_logits,
1084
+ position_embeddings=position_embeddings,
1085
+ )
1086
+
1087
+ hidden_states = layer_outputs[0]
1088
+
1089
+ if use_cache:
1090
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1091
+
1092
+ if output_attentions:
1093
+ all_self_attns += (layer_outputs[1],)
1094
+
1095
+ if output_router_logits:
1096
+ all_router_logits += (layer_outputs[-1],)
1097
+
1098
+ hidden_states = self.norm(hidden_states)
1099
+
1100
+ # add hidden states from the last decoder layer
1101
+ if output_hidden_states:
1102
+ all_hidden_states += (hidden_states,)
1103
+
1104
+ next_cache = next_decoder_cache if use_cache else None
1105
+ if return_legacy_cache:
1106
+ next_cache = next_cache.to_legacy_cache()
1107
+
1108
+ if not return_dict:
1109
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1110
+ return MoeModelOutputWithPast(
1111
+ last_hidden_state=hidden_states,
1112
+ past_key_values=next_cache,
1113
+ hidden_states=all_hidden_states,
1114
+ attentions=all_self_attns,
1115
+ router_logits=all_router_logits,
1116
+ )
1117
+
1118
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
1119
+ def _update_causal_mask(
1120
+ self,
1121
+ attention_mask: torch.Tensor,
1122
+ input_tensor: torch.Tensor,
1123
+ cache_position: torch.Tensor,
1124
+ past_key_values: Cache,
1125
+ output_attentions: bool = False,
1126
+ ):
1127
+ if self.config._attn_implementation == "flash_attention_2":
1128
+ if attention_mask is not None and (attention_mask == 0.0).any():
1129
+ return attention_mask
1130
+ return None
1131
+ if self.config._attn_implementation == "flex_attention":
1132
+ if isinstance(attention_mask, torch.Tensor):
1133
+ attention_mask = make_flex_block_causal_mask(attention_mask)
1134
+ if isinstance(attention_mask, BlockMask):
1135
+ return attention_mask
1136
+
1137
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1138
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1139
+ # to infer the attention mask.
1140
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1141
+ using_static_cache = isinstance(past_key_values, StaticCache)
1142
+
1143
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1144
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1145
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1146
+ attention_mask,
1147
+ inputs_embeds=input_tensor,
1148
+ past_key_values_length=past_seen_tokens,
1149
+ is_training=self.training,
1150
+ ):
1151
+ return None
1152
+
1153
+ dtype, device = input_tensor.dtype, input_tensor.device
1154
+ sequence_length = input_tensor.shape[1]
1155
+ if using_static_cache:
1156
+ target_length = past_key_values.get_max_cache_shape()
1157
+ else:
1158
+ target_length = (
1159
+ attention_mask.shape[-1]
1160
+ if isinstance(attention_mask, torch.Tensor)
1161
+ else past_seen_tokens + sequence_length + 1
1162
+ )
1163
+
1164
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1165
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1166
+ attention_mask,
1167
+ sequence_length=sequence_length,
1168
+ target_length=target_length,
1169
+ dtype=dtype,
1170
+ device=device,
1171
+ cache_position=cache_position,
1172
+ batch_size=input_tensor.shape[0],
1173
+ )
1174
+
1175
+ if (
1176
+ self.config._attn_implementation == "sdpa"
1177
+ and attention_mask is not None
1178
+ and attention_mask.device.type in ["cuda", "xpu"]
1179
+ and not output_attentions
1180
+ ):
1181
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1182
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1183
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1184
+ min_dtype = torch.finfo(dtype).min
1185
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1186
+
1187
+ return causal_mask
1188
+
1189
+ @staticmethod
1190
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
1191
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1192
+ attention_mask: torch.Tensor,
1193
+ sequence_length: int,
1194
+ target_length: int,
1195
+ dtype: torch.dtype,
1196
+ device: torch.device,
1197
+ cache_position: torch.Tensor,
1198
+ batch_size: int,
1199
+ **kwargs,
1200
+ ):
1201
+ """
1202
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1203
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1204
+
1205
+ Args:
1206
+ attention_mask (`torch.Tensor`):
1207
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1208
+ `(batch_size, 1, query_length, key_value_length)`.
1209
+ sequence_length (`int`):
1210
+ The sequence length being processed.
1211
+ target_length (`int`):
1212
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1213
+ to account for the 0 padding, the part of the cache that is not filled yet.
1214
+ dtype (`torch.dtype`):
1215
+ The dtype to use for the 4D attention mask.
1216
+ device (`torch.device`):
1217
+ The device to place the 4D attention mask on.
1218
+ cache_position (`torch.Tensor`):
1219
+ Indices depicting the position of the input sequence tokens in the sequence.
1220
+ batch_size (`torch.Tensor`):
1221
+ Batch size.
1222
+ """
1223
+ if attention_mask is not None and attention_mask.dim() == 4:
1224
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1225
+ causal_mask = attention_mask
1226
+ else:
1227
+ min_dtype = torch.finfo(dtype).min
1228
+ causal_mask = torch.full(
1229
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1230
+ )
1231
+ if sequence_length != 1:
1232
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1233
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1234
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1235
+ if attention_mask is not None:
1236
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1237
+ mask_length = attention_mask.shape[-1]
1238
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
1239
+ causal_mask.device
1240
+ )
1241
+ padding_mask = padding_mask == 0
1242
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1243
+ padding_mask, min_dtype
1244
+ )
1245
+
1246
+ return causal_mask
1247
+
1248
+
1249
+ class GraniteMoeForCausalLM(GraniteMoePreTrainedModel, GenerationMixin):
1250
+ _tied_weights_keys = ["lm_head.weight"]
1251
+
1252
+ def __init__(self, config: GraniteMoeConfig):
1253
+ super().__init__(config)
1254
+ self.model = GraniteMoeModel(config)
1255
+ self.vocab_size = config.vocab_size
1256
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1257
+
1258
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1259
+ self.num_experts = config.num_local_experts
1260
+ self.num_experts_per_tok = config.num_experts_per_tok
1261
+
1262
+ # Initialize weights and apply final processing
1263
+ self.post_init()
1264
+
1265
+ def get_input_embeddings(self):
1266
+ return self.model.embed_tokens
1267
+
1268
+ def set_input_embeddings(self, value):
1269
+ self.model.embed_tokens = value
1270
+
1271
+ def get_output_embeddings(self):
1272
+ return self.lm_head
1273
+
1274
+ def set_output_embeddings(self, new_embeddings):
1275
+ self.lm_head = new_embeddings
1276
+
1277
+ def set_decoder(self, decoder):
1278
+ self.model = decoder
1279
+
1280
+ def get_decoder(self):
1281
+ return self.model
1282
+
1283
+ @add_start_docstrings_to_model_forward(GRANITEMOE_INPUTS_DOCSTRING)
1284
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1285
+ def forward(
1286
+ self,
1287
+ input_ids: torch.LongTensor = None,
1288
+ attention_mask: Optional[torch.Tensor] = None,
1289
+ position_ids: Optional[torch.LongTensor] = None,
1290
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1291
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1292
+ labels: Optional[torch.LongTensor] = None,
1293
+ use_cache: Optional[bool] = None,
1294
+ output_attentions: Optional[bool] = None,
1295
+ output_hidden_states: Optional[bool] = None,
1296
+ output_router_logits: Optional[bool] = None,
1297
+ return_dict: Optional[bool] = None,
1298
+ cache_position: Optional[torch.LongTensor] = None,
1299
+ **kwargs,
1300
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1301
+ r"""
1302
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1303
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1304
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1305
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1306
+
1307
+ Returns:
1308
+
1309
+ Example:
1310
+
1311
+ ```python
1312
+ >>> from transformers import AutoTokenizer, GraniteMoeForCausalLM
1313
+
1314
+ >>> model = GraniteMoeForCausalLM.from_pretrained("ibm/PowerMoE-3b")
1315
+ >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")
1316
+
1317
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1318
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1319
+
1320
+ >>> # Generate
1321
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1322
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1323
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1324
+ ```"""
1325
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1326
+ output_router_logits = (
1327
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1328
+ )
1329
+ output_hidden_states = (
1330
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1331
+ )
1332
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1333
+
1334
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1335
+ outputs = self.model(
1336
+ input_ids=input_ids,
1337
+ attention_mask=attention_mask,
1338
+ position_ids=position_ids,
1339
+ past_key_values=past_key_values,
1340
+ inputs_embeds=inputs_embeds,
1341
+ use_cache=use_cache,
1342
+ output_attentions=output_attentions,
1343
+ output_hidden_states=output_hidden_states,
1344
+ output_router_logits=output_router_logits,
1345
+ return_dict=return_dict,
1346
+ cache_position=cache_position,
1347
+ )
1348
+
1349
+ hidden_states = outputs[0]
1350
+ logits = self.lm_head(hidden_states)
1351
+ logits = logits / self.config.logits_scaling
1352
+
1353
+ loss = None
1354
+ if labels is not None:
1355
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1356
+ logits = logits.float()
1357
+ # Flatten the tokens
1358
+ loss = self.loss_function(
1359
+ logits,
1360
+ labels,
1361
+ vocab_size=self.config.vocab_size,
1362
+ **kwargs,
1363
+ )
1364
+
1365
+ aux_loss = None
1366
+ if output_router_logits:
1367
+ aux_loss = load_balancing_loss_func(
1368
+ outputs.router_logits if return_dict else outputs[-1],
1369
+ self.num_experts,
1370
+ self.num_experts_per_tok,
1371
+ attention_mask,
1372
+ )
1373
+ if labels is not None:
1374
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1375
+
1376
+ if not return_dict:
1377
+ output = (logits,) + outputs[1:]
1378
+ if output_router_logits:
1379
+ output = (aux_loss,) + output
1380
+ return (loss,) + output if loss is not None else output
1381
+
1382
+ return MoeCausalLMOutputWithPast(
1383
+ loss=loss,
1384
+ aux_loss=aux_loss,
1385
+ logits=logits,
1386
+ past_key_values=outputs.past_key_values,
1387
+ hidden_states=outputs.hidden_states,
1388
+ attentions=outputs.attentions,
1389
+ router_logits=outputs.router_logits,
1390
+ )
1391
+
1392
+ @staticmethod
1393
+ def _reorder_cache(past_key_values, beam_idx):
1394
+ reordered_past = ()
1395
+ for layer_past in past_key_values:
1396
+ reordered_past += (
1397
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1398
+ )
1399
+ return reordered_past
1400
+
1401
+
1402
+ __all__ = ["GraniteMoeForCausalLM", "GraniteMoeModel", "GraniteMoePreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/ibert/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_ibert import *
22
+ from .modeling_ibert import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (533 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/configuration_ibert.cpython-310.pyc ADDED
Binary file (6.23 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/modeling_ibert.cpython-310.pyc ADDED
Binary file (35.3 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/ibert/__pycache__/quant_modules.cpython-310.pyc ADDED
Binary file (23 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/ibert/configuration_ibert.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
3
+ # Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
4
+ # Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """I-BERT configuration"""
18
+
19
+ from collections import OrderedDict
20
+ from typing import Mapping
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...onnx import OnnxConfig
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ class IBertConfig(PretrainedConfig):
31
+ """
32
+ This is the configuration class to store the configuration of a [`IBertModel`]. It is used to instantiate a I-BERT
33
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
34
+ defaults will yield a similar configuration to that of the IBERT
35
+ [kssteven/ibert-roberta-base](https://huggingface.co/kssteven/ibert-roberta-base) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 30522):
42
+ Vocabulary size of the I-BERT model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`IBertModel`]
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" (often named feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
55
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
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.1):
58
+ The dropout ratio for the attention probabilities.
59
+ max_position_embeddings (`int`, *optional*, defaults to 512):
60
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
61
+ just in case (e.g., 512 or 1024 or 2048).
62
+ type_vocab_size (`int`, *optional*, defaults to 2):
63
+ The vocabulary size of the `token_type_ids` passed when calling [`IBertModel`]
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
67
+ The epsilon used by the layer normalization layers.
68
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
69
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
70
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
71
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
72
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
73
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
74
+ quant_mode (`bool`, *optional*, defaults to `False`):
75
+ Whether to quantize the model or not.
76
+ force_dequant (`str`, *optional*, defaults to `"none"`):
77
+ Force dequantize specific nonlinear layer. Dequatized layers are then executed with full precision.
78
+ `"none"`, `"gelu"`, `"softmax"`, `"layernorm"` and `"nonlinear"` are supported. As deafult, it is set as
79
+ `"none"`, which does not dequantize any layers. Please specify `"gelu"`, `"softmax"`, or `"layernorm"` to
80
+ dequantize GELU, Softmax, or LayerNorm, respectively. `"nonlinear"` will dequantize all nonlinear layers,
81
+ i.e., GELU, Softmax, and LayerNorm.
82
+ """
83
+
84
+ model_type = "ibert"
85
+
86
+ def __init__(
87
+ self,
88
+ vocab_size=30522,
89
+ hidden_size=768,
90
+ num_hidden_layers=12,
91
+ num_attention_heads=12,
92
+ intermediate_size=3072,
93
+ hidden_act="gelu",
94
+ hidden_dropout_prob=0.1,
95
+ attention_probs_dropout_prob=0.1,
96
+ max_position_embeddings=512,
97
+ type_vocab_size=2,
98
+ initializer_range=0.02,
99
+ layer_norm_eps=1e-12,
100
+ pad_token_id=1,
101
+ bos_token_id=0,
102
+ eos_token_id=2,
103
+ position_embedding_type="absolute",
104
+ quant_mode=False,
105
+ force_dequant="none",
106
+ **kwargs,
107
+ ):
108
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
109
+
110
+ self.vocab_size = vocab_size
111
+ self.hidden_size = hidden_size
112
+ self.num_hidden_layers = num_hidden_layers
113
+ self.num_attention_heads = num_attention_heads
114
+ self.hidden_act = hidden_act
115
+ self.intermediate_size = intermediate_size
116
+ self.hidden_dropout_prob = hidden_dropout_prob
117
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.type_vocab_size = type_vocab_size
120
+ self.initializer_range = initializer_range
121
+ self.layer_norm_eps = layer_norm_eps
122
+ self.position_embedding_type = position_embedding_type
123
+ self.quant_mode = quant_mode
124
+ self.force_dequant = force_dequant
125
+
126
+
127
+ class IBertOnnxConfig(OnnxConfig):
128
+ @property
129
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
130
+ if self.task == "multiple-choice":
131
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
132
+ else:
133
+ dynamic_axis = {0: "batch", 1: "sequence"}
134
+ return OrderedDict(
135
+ [
136
+ ("input_ids", dynamic_axis),
137
+ ("attention_mask", dynamic_axis),
138
+ ]
139
+ )
140
+
141
+
142
+ __all__ = ["IBertConfig", "IBertOnnxConfig"]
vllm/lib/python3.10/site-packages/transformers/models/ibert/modeling_ibert.py ADDED
@@ -0,0 +1,1366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
3
+ # Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
4
+ # Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """PyTorch I-BERT model."""
19
+
20
+ import math
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from ...activations import gelu
29
+ from ...modeling_outputs import (
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ BaseModelOutputWithPoolingAndCrossAttentions,
32
+ MaskedLMOutput,
33
+ MultipleChoiceModelOutput,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutput,
36
+ TokenClassifierOutput,
37
+ )
38
+ from ...modeling_utils import PreTrainedModel
39
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
40
+ from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
41
+ from .configuration_ibert import IBertConfig
42
+ from .quant_modules import IntGELU, IntLayerNorm, IntSoftmax, QuantAct, QuantEmbedding, QuantLinear
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CHECKPOINT_FOR_DOC = "kssteven/ibert-roberta-base"
48
+ _CONFIG_FOR_DOC = "IBertConfig"
49
+
50
+
51
+ class IBertEmbeddings(nn.Module):
52
+ """
53
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
54
+ """
55
+
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.quant_mode = config.quant_mode
59
+ self.embedding_bit = 8
60
+ self.embedding_act_bit = 16
61
+ self.act_bit = 8
62
+ self.ln_input_bit = 22
63
+ self.ln_output_bit = 32
64
+
65
+ self.word_embeddings = QuantEmbedding(
66
+ config.vocab_size,
67
+ config.hidden_size,
68
+ padding_idx=config.pad_token_id,
69
+ weight_bit=self.embedding_bit,
70
+ quant_mode=self.quant_mode,
71
+ )
72
+ self.token_type_embeddings = QuantEmbedding(
73
+ config.type_vocab_size, config.hidden_size, weight_bit=self.embedding_bit, quant_mode=self.quant_mode
74
+ )
75
+
76
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
77
+ self.register_buffer(
78
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
79
+ )
80
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
81
+
82
+ # End copy
83
+ self.padding_idx = config.pad_token_id
84
+ self.position_embeddings = QuantEmbedding(
85
+ config.max_position_embeddings,
86
+ config.hidden_size,
87
+ padding_idx=self.padding_idx,
88
+ weight_bit=self.embedding_bit,
89
+ quant_mode=self.quant_mode,
90
+ )
91
+
92
+ # Integer-only addition between embeddings
93
+ self.embeddings_act1 = QuantAct(self.embedding_act_bit, quant_mode=self.quant_mode)
94
+ self.embeddings_act2 = QuantAct(self.embedding_act_bit, quant_mode=self.quant_mode)
95
+
96
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
97
+ # any TensorFlow checkpoint file
98
+ self.LayerNorm = IntLayerNorm(
99
+ config.hidden_size,
100
+ eps=config.layer_norm_eps,
101
+ output_bit=self.ln_output_bit,
102
+ quant_mode=self.quant_mode,
103
+ force_dequant=config.force_dequant,
104
+ )
105
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
106
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
107
+
108
+ def forward(
109
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
110
+ ):
111
+ if position_ids is None:
112
+ if input_ids is not None:
113
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
114
+ position_ids = create_position_ids_from_input_ids(
115
+ input_ids, self.padding_idx, past_key_values_length
116
+ ).to(input_ids.device)
117
+ else:
118
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
119
+
120
+ if input_ids is not None:
121
+ input_shape = input_ids.size()
122
+ else:
123
+ input_shape = inputs_embeds.size()[:-1]
124
+
125
+ if token_type_ids is None:
126
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
127
+
128
+ if inputs_embeds is None:
129
+ inputs_embeds, inputs_embeds_scaling_factor = self.word_embeddings(input_ids)
130
+ else:
131
+ inputs_embeds_scaling_factor = None
132
+ token_type_embeddings, token_type_embeddings_scaling_factor = self.token_type_embeddings(token_type_ids)
133
+
134
+ embeddings, embeddings_scaling_factor = self.embeddings_act1(
135
+ inputs_embeds,
136
+ inputs_embeds_scaling_factor,
137
+ identity=token_type_embeddings,
138
+ identity_scaling_factor=token_type_embeddings_scaling_factor,
139
+ )
140
+
141
+ if self.position_embedding_type == "absolute":
142
+ position_embeddings, position_embeddings_scaling_factor = self.position_embeddings(position_ids)
143
+ embeddings, embeddings_scaling_factor = self.embeddings_act1(
144
+ embeddings,
145
+ embeddings_scaling_factor,
146
+ identity=position_embeddings,
147
+ identity_scaling_factor=position_embeddings_scaling_factor,
148
+ )
149
+
150
+ embeddings, embeddings_scaling_factor = self.LayerNorm(embeddings, embeddings_scaling_factor)
151
+ embeddings = self.dropout(embeddings)
152
+ embeddings, embeddings_scaling_factor = self.output_activation(embeddings, embeddings_scaling_factor)
153
+ return embeddings, embeddings_scaling_factor
154
+
155
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
156
+ """
157
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
158
+
159
+ Args:
160
+ inputs_embeds: torch.Tensor
161
+
162
+ Returns: torch.Tensor
163
+ """
164
+ input_shape = inputs_embeds.size()[:-1]
165
+ sequence_length = input_shape[1]
166
+
167
+ position_ids = torch.arange(
168
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
169
+ )
170
+ return position_ids.unsqueeze(0).expand(input_shape)
171
+
172
+
173
+ class IBertSelfAttention(nn.Module):
174
+ def __init__(self, config):
175
+ super().__init__()
176
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
177
+ raise ValueError(
178
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
179
+ f"heads ({config.num_attention_heads})"
180
+ )
181
+ self.quant_mode = config.quant_mode
182
+ self.weight_bit = 8
183
+ self.bias_bit = 32
184
+ self.act_bit = 8
185
+
186
+ self.num_attention_heads = config.num_attention_heads
187
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
188
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
189
+
190
+ # Q, K, V Linear layers
191
+ self.query = QuantLinear(
192
+ config.hidden_size,
193
+ self.all_head_size,
194
+ bias=True,
195
+ weight_bit=self.weight_bit,
196
+ bias_bit=self.bias_bit,
197
+ quant_mode=self.quant_mode,
198
+ per_channel=True,
199
+ )
200
+ self.key = QuantLinear(
201
+ config.hidden_size,
202
+ self.all_head_size,
203
+ bias=True,
204
+ weight_bit=self.weight_bit,
205
+ bias_bit=self.bias_bit,
206
+ quant_mode=self.quant_mode,
207
+ per_channel=True,
208
+ )
209
+ self.value = QuantLinear(
210
+ config.hidden_size,
211
+ self.all_head_size,
212
+ bias=True,
213
+ weight_bit=self.weight_bit,
214
+ bias_bit=self.bias_bit,
215
+ quant_mode=self.quant_mode,
216
+ per_channel=True,
217
+ )
218
+
219
+ # Requantization (32bit -> 8bit) for Q, K, V activations
220
+ self.query_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
221
+ self.key_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
222
+ self.value_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
223
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
224
+
225
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
226
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
227
+ if self.position_embedding_type != "absolute":
228
+ raise ValueError("I-BERT only supports 'absolute' for `config.position_embedding_type`")
229
+
230
+ self.softmax = IntSoftmax(self.act_bit, quant_mode=self.quant_mode, force_dequant=config.force_dequant)
231
+
232
+ def transpose_for_scores(self, x):
233
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
234
+ x = x.view(*new_x_shape)
235
+ return x.permute(0, 2, 1, 3)
236
+
237
+ def forward(
238
+ self,
239
+ hidden_states,
240
+ hidden_states_scaling_factor,
241
+ attention_mask=None,
242
+ head_mask=None,
243
+ output_attentions=False,
244
+ ):
245
+ # Projection
246
+ mixed_query_layer, mixed_query_layer_scaling_factor = self.query(hidden_states, hidden_states_scaling_factor)
247
+ mixed_key_layer, mixed_key_layer_scaling_factor = self.key(hidden_states, hidden_states_scaling_factor)
248
+ mixed_value_layer, mixed_value_layer_scaling_factor = self.value(hidden_states, hidden_states_scaling_factor)
249
+
250
+ # Requantization
251
+ query_layer, query_layer_scaling_factor = self.query_activation(
252
+ mixed_query_layer, mixed_query_layer_scaling_factor
253
+ )
254
+ key_layer, key_layer_scaling_factor = self.key_activation(mixed_key_layer, mixed_key_layer_scaling_factor)
255
+ value_layer, value_layer_scaling_factor = self.value_activation(
256
+ mixed_value_layer, mixed_value_layer_scaling_factor
257
+ )
258
+
259
+ # Transpose
260
+ query_layer = self.transpose_for_scores(query_layer)
261
+ key_layer = self.transpose_for_scores(key_layer)
262
+ value_layer = self.transpose_for_scores(value_layer)
263
+
264
+ # Take the dot product between "query" and "key" to get the raw attention scores.
265
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
266
+ scale = math.sqrt(self.attention_head_size)
267
+ attention_scores = attention_scores / scale
268
+ if self.quant_mode:
269
+ attention_scores_scaling_factor = query_layer_scaling_factor * key_layer_scaling_factor / scale
270
+ else:
271
+ attention_scores_scaling_factor = None
272
+
273
+ if attention_mask is not None:
274
+ # Apply the attention mask is (precomputed for all layers in IBertModel forward() function)
275
+ attention_scores = attention_scores + attention_mask
276
+
277
+ # Normalize the attention scores to probabilities.
278
+ attention_probs, attention_probs_scaling_factor = self.softmax(
279
+ attention_scores, attention_scores_scaling_factor
280
+ )
281
+
282
+ # This is actually dropping out entire tokens to attend to, which might
283
+ # seem a bit unusual, but is taken from the original Transformer paper.
284
+ attention_probs = self.dropout(attention_probs)
285
+
286
+ # Mask heads if we want to
287
+ if head_mask is not None:
288
+ attention_probs = attention_probs * head_mask
289
+
290
+ context_layer = torch.matmul(attention_probs, value_layer)
291
+ if attention_probs_scaling_factor is not None:
292
+ context_layer_scaling_factor = attention_probs_scaling_factor * value_layer_scaling_factor
293
+ else:
294
+ context_layer_scaling_factor = None
295
+
296
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
297
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
298
+ context_layer = context_layer.view(*new_context_layer_shape)
299
+
300
+ # requantization: 32-bit -> 8-bit
301
+ context_layer, context_layer_scaling_factor = self.output_activation(
302
+ context_layer, context_layer_scaling_factor
303
+ )
304
+
305
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
306
+ output_scaling_factor = (
307
+ (context_layer_scaling_factor, attention_probs_scaling_factor)
308
+ if output_attentions
309
+ else (context_layer_scaling_factor,)
310
+ )
311
+
312
+ return outputs, output_scaling_factor
313
+
314
+
315
+ class IBertSelfOutput(nn.Module):
316
+ def __init__(self, config):
317
+ super().__init__()
318
+ self.quant_mode = config.quant_mode
319
+ self.act_bit = 8
320
+ self.weight_bit = 8
321
+ self.bias_bit = 32
322
+ self.ln_input_bit = 22
323
+ self.ln_output_bit = 32
324
+
325
+ self.dense = QuantLinear(
326
+ config.hidden_size,
327
+ config.hidden_size,
328
+ bias=True,
329
+ weight_bit=self.weight_bit,
330
+ bias_bit=self.bias_bit,
331
+ quant_mode=self.quant_mode,
332
+ per_channel=True,
333
+ )
334
+ self.ln_input_act = QuantAct(self.ln_input_bit, quant_mode=self.quant_mode)
335
+ self.LayerNorm = IntLayerNorm(
336
+ config.hidden_size,
337
+ eps=config.layer_norm_eps,
338
+ output_bit=self.ln_output_bit,
339
+ quant_mode=self.quant_mode,
340
+ force_dequant=config.force_dequant,
341
+ )
342
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
343
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
344
+
345
+ def forward(self, hidden_states, hidden_states_scaling_factor, input_tensor, input_tensor_scaling_factor):
346
+ hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor)
347
+ hidden_states = self.dropout(hidden_states)
348
+ hidden_states, hidden_states_scaling_factor = self.ln_input_act(
349
+ hidden_states,
350
+ hidden_states_scaling_factor,
351
+ identity=input_tensor,
352
+ identity_scaling_factor=input_tensor_scaling_factor,
353
+ )
354
+ hidden_states, hidden_states_scaling_factor = self.LayerNorm(hidden_states, hidden_states_scaling_factor)
355
+
356
+ hidden_states, hidden_states_scaling_factor = self.output_activation(
357
+ hidden_states, hidden_states_scaling_factor
358
+ )
359
+ return hidden_states, hidden_states_scaling_factor
360
+
361
+
362
+ class IBertAttention(nn.Module):
363
+ def __init__(self, config):
364
+ super().__init__()
365
+ self.quant_mode = config.quant_mode
366
+ self.self = IBertSelfAttention(config)
367
+ self.output = IBertSelfOutput(config)
368
+ self.pruned_heads = set()
369
+
370
+ def prune_heads(self, heads):
371
+ if len(heads) == 0:
372
+ return
373
+ heads, index = find_pruneable_heads_and_indices(
374
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
375
+ )
376
+
377
+ # Prune linear layers
378
+ self.self.query = prune_linear_layer(self.self.query, index)
379
+ self.self.key = prune_linear_layer(self.self.key, index)
380
+ self.self.value = prune_linear_layer(self.self.value, index)
381
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
382
+
383
+ # Update hyper params and store pruned heads
384
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
385
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
386
+ self.pruned_heads = self.pruned_heads.union(heads)
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states,
391
+ hidden_states_scaling_factor,
392
+ attention_mask=None,
393
+ head_mask=None,
394
+ output_attentions=False,
395
+ ):
396
+ self_outputs, self_outputs_scaling_factor = self.self(
397
+ hidden_states,
398
+ hidden_states_scaling_factor,
399
+ attention_mask,
400
+ head_mask,
401
+ output_attentions,
402
+ )
403
+ attention_output, attention_output_scaling_factor = self.output(
404
+ self_outputs[0], self_outputs_scaling_factor[0], hidden_states, hidden_states_scaling_factor
405
+ )
406
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
407
+ outputs_scaling_factor = (attention_output_scaling_factor,) + self_outputs_scaling_factor[1:]
408
+ return outputs, outputs_scaling_factor
409
+
410
+
411
+ class IBertIntermediate(nn.Module):
412
+ def __init__(self, config):
413
+ super().__init__()
414
+ self.quant_mode = config.quant_mode
415
+ self.act_bit = 8
416
+ self.weight_bit = 8
417
+ self.bias_bit = 32
418
+ self.dense = QuantLinear(
419
+ config.hidden_size,
420
+ config.intermediate_size,
421
+ bias=True,
422
+ weight_bit=self.weight_bit,
423
+ bias_bit=self.bias_bit,
424
+ quant_mode=self.quant_mode,
425
+ per_channel=True,
426
+ )
427
+ if config.hidden_act != "gelu":
428
+ raise ValueError("I-BERT only supports 'gelu' for `config.hidden_act`")
429
+ self.intermediate_act_fn = IntGELU(quant_mode=self.quant_mode, force_dequant=config.force_dequant)
430
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
431
+
432
+ def forward(self, hidden_states, hidden_states_scaling_factor):
433
+ hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor)
434
+ hidden_states, hidden_states_scaling_factor = self.intermediate_act_fn(
435
+ hidden_states, hidden_states_scaling_factor
436
+ )
437
+
438
+ # Requantization: 32bit -> 8-bit
439
+ hidden_states, hidden_states_scaling_factor = self.output_activation(
440
+ hidden_states, hidden_states_scaling_factor
441
+ )
442
+ return hidden_states, hidden_states_scaling_factor
443
+
444
+
445
+ class IBertOutput(nn.Module):
446
+ def __init__(self, config):
447
+ super().__init__()
448
+ self.quant_mode = config.quant_mode
449
+ self.act_bit = 8
450
+ self.weight_bit = 8
451
+ self.bias_bit = 32
452
+ self.ln_input_bit = 22
453
+ self.ln_output_bit = 32
454
+
455
+ self.dense = QuantLinear(
456
+ config.intermediate_size,
457
+ config.hidden_size,
458
+ bias=True,
459
+ weight_bit=self.weight_bit,
460
+ bias_bit=self.bias_bit,
461
+ quant_mode=self.quant_mode,
462
+ per_channel=True,
463
+ )
464
+ self.ln_input_act = QuantAct(self.ln_input_bit, quant_mode=self.quant_mode)
465
+ self.LayerNorm = IntLayerNorm(
466
+ config.hidden_size,
467
+ eps=config.layer_norm_eps,
468
+ output_bit=self.ln_output_bit,
469
+ quant_mode=self.quant_mode,
470
+ force_dequant=config.force_dequant,
471
+ )
472
+ self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode)
473
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
474
+
475
+ def forward(self, hidden_states, hidden_states_scaling_factor, input_tensor, input_tensor_scaling_factor):
476
+ hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor)
477
+ hidden_states = self.dropout(hidden_states)
478
+ hidden_states, hidden_states_scaling_factor = self.ln_input_act(
479
+ hidden_states,
480
+ hidden_states_scaling_factor,
481
+ identity=input_tensor,
482
+ identity_scaling_factor=input_tensor_scaling_factor,
483
+ )
484
+ hidden_states, hidden_states_scaling_factor = self.LayerNorm(hidden_states, hidden_states_scaling_factor)
485
+
486
+ hidden_states, hidden_states_scaling_factor = self.output_activation(
487
+ hidden_states, hidden_states_scaling_factor
488
+ )
489
+ return hidden_states, hidden_states_scaling_factor
490
+
491
+
492
+ class IBertLayer(nn.Module):
493
+ def __init__(self, config):
494
+ super().__init__()
495
+ self.quant_mode = config.quant_mode
496
+ self.act_bit = 8
497
+
498
+ self.seq_len_dim = 1
499
+ self.attention = IBertAttention(config)
500
+ self.intermediate = IBertIntermediate(config)
501
+ self.output = IBertOutput(config)
502
+
503
+ self.pre_intermediate_act = QuantAct(self.act_bit, quant_mode=self.quant_mode)
504
+ self.pre_output_act = QuantAct(self.act_bit, quant_mode=self.quant_mode)
505
+
506
+ def forward(
507
+ self,
508
+ hidden_states,
509
+ hidden_states_scaling_factor,
510
+ attention_mask=None,
511
+ head_mask=None,
512
+ output_attentions=False,
513
+ ):
514
+ self_attention_outputs, self_attention_outputs_scaling_factor = self.attention(
515
+ hidden_states,
516
+ hidden_states_scaling_factor,
517
+ attention_mask,
518
+ head_mask,
519
+ output_attentions=output_attentions,
520
+ )
521
+ attention_output = self_attention_outputs[0]
522
+ attention_output_scaling_factor = self_attention_outputs_scaling_factor[0]
523
+
524
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
525
+
526
+ layer_output, layer_output_scaling_factor = self.feed_forward_chunk(
527
+ attention_output, attention_output_scaling_factor
528
+ )
529
+ outputs = (layer_output,) + outputs
530
+
531
+ return outputs
532
+
533
+ def feed_forward_chunk(self, attention_output, attention_output_scaling_factor):
534
+ attention_output, attention_output_scaling_factor = self.pre_intermediate_act(
535
+ attention_output, attention_output_scaling_factor
536
+ )
537
+ intermediate_output, intermediate_output_scaling_factor = self.intermediate(
538
+ attention_output, attention_output_scaling_factor
539
+ )
540
+
541
+ intermediate_output, intermediate_output_scaling_factor = self.pre_output_act(
542
+ intermediate_output, intermediate_output_scaling_factor
543
+ )
544
+ layer_output, layer_output_scaling_factor = self.output(
545
+ intermediate_output, intermediate_output_scaling_factor, attention_output, attention_output_scaling_factor
546
+ )
547
+ return layer_output, layer_output_scaling_factor
548
+
549
+
550
+ class IBertEncoder(nn.Module):
551
+ def __init__(self, config):
552
+ super().__init__()
553
+ self.config = config
554
+ self.quant_mode = config.quant_mode
555
+ self.layer = nn.ModuleList([IBertLayer(config) for _ in range(config.num_hidden_layers)])
556
+
557
+ def forward(
558
+ self,
559
+ hidden_states,
560
+ hidden_states_scaling_factor,
561
+ attention_mask=None,
562
+ head_mask=None,
563
+ output_attentions=False,
564
+ output_hidden_states=False,
565
+ return_dict=True,
566
+ ):
567
+ all_hidden_states = () if output_hidden_states else None
568
+ all_self_attentions = () if output_attentions else None
569
+ all_cross_attentions = None # `config.add_cross_attention` is not supported
570
+ next_decoder_cache = None # `config.use_cache` is not supported
571
+
572
+ for i, layer_module in enumerate(self.layer):
573
+ if output_hidden_states:
574
+ all_hidden_states = all_hidden_states + (hidden_states,)
575
+
576
+ layer_head_mask = head_mask[i] if head_mask is not None else None
577
+
578
+ layer_outputs = layer_module(
579
+ hidden_states,
580
+ hidden_states_scaling_factor,
581
+ attention_mask,
582
+ layer_head_mask,
583
+ output_attentions,
584
+ )
585
+
586
+ hidden_states = layer_outputs[0]
587
+ if output_attentions:
588
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
589
+
590
+ if output_hidden_states:
591
+ all_hidden_states = all_hidden_states + (hidden_states,)
592
+
593
+ if not return_dict:
594
+ return tuple(
595
+ v
596
+ for v in [
597
+ hidden_states,
598
+ next_decoder_cache,
599
+ all_hidden_states,
600
+ all_self_attentions,
601
+ all_cross_attentions,
602
+ ]
603
+ if v is not None
604
+ )
605
+ return BaseModelOutputWithPastAndCrossAttentions(
606
+ last_hidden_state=hidden_states,
607
+ past_key_values=next_decoder_cache,
608
+ hidden_states=all_hidden_states,
609
+ attentions=all_self_attentions,
610
+ cross_attentions=all_cross_attentions,
611
+ )
612
+
613
+
614
+ class IBertPooler(nn.Module):
615
+ def __init__(self, config):
616
+ super().__init__()
617
+ self.quant_mode = config.quant_mode
618
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
619
+ self.activation = nn.Tanh()
620
+
621
+ def forward(self, hidden_states):
622
+ # We "pool" the model by simply taking the hidden state corresponding
623
+ # to the first token.
624
+ first_token_tensor = hidden_states[:, 0]
625
+ pooled_output = self.dense(first_token_tensor)
626
+ pooled_output = self.activation(pooled_output)
627
+ return pooled_output
628
+
629
+
630
+ class IBertPreTrainedModel(PreTrainedModel):
631
+ """
632
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
633
+ models.
634
+ """
635
+
636
+ config_class = IBertConfig
637
+ base_model_prefix = "ibert"
638
+
639
+ def _init_weights(self, module):
640
+ """Initialize the weights"""
641
+ if isinstance(module, (QuantLinear, nn.Linear)):
642
+ # Slightly different from the TF version which uses truncated_normal for initialization
643
+ # cf https://github.com/pytorch/pytorch/pull/5617
644
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
645
+ if module.bias is not None:
646
+ module.bias.data.zero_()
647
+ elif isinstance(module, (QuantEmbedding, nn.Embedding)):
648
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
649
+ if module.padding_idx is not None:
650
+ module.weight.data[module.padding_idx].zero_()
651
+ elif isinstance(module, (IntLayerNorm, nn.LayerNorm)):
652
+ module.bias.data.zero_()
653
+ module.weight.data.fill_(1.0)
654
+
655
+ def resize_token_embeddings(self, new_num_tokens=None):
656
+ raise NotImplementedError("`resize_token_embeddings` is not supported for I-BERT.")
657
+
658
+
659
+ IBERT_START_DOCSTRING = r"""
660
+
661
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
662
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
663
+ etc.)
664
+
665
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
666
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
667
+ and behavior.
668
+
669
+ Parameters:
670
+ config ([`IBertConfig`]): Model configuration class with all the parameters of the
671
+ model. Initializing with a config file does not load the weights associated with the model, only the
672
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
673
+ """
674
+
675
+ IBERT_INPUTS_DOCSTRING = r"""
676
+ Args:
677
+ input_ids (`torch.LongTensor` of shape `({0})`):
678
+ Indices of input sequence tokens in the vocabulary.
679
+
680
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
681
+ [`PreTrainedTokenizer.__call__`] for details.
682
+
683
+ [What are input IDs?](../glossary#input-ids)
684
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
685
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
686
+
687
+ - 1 for tokens that are **not masked**,
688
+ - 0 for tokens that are **masked**.
689
+
690
+ [What are attention masks?](../glossary#attention-mask)
691
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
692
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
693
+ 1]`:
694
+
695
+ - 0 corresponds to a *sentence A* token,
696
+ - 1 corresponds to a *sentence B* token.
697
+
698
+ [What are token type IDs?](../glossary#token-type-ids)
699
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
700
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
701
+ config.max_position_embeddings - 1]`.
702
+
703
+ [What are position IDs?](../glossary#position-ids)
704
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
705
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
706
+
707
+ - 1 indicates the head is **not masked**,
708
+ - 0 indicates the head is **masked**.
709
+
710
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
711
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
712
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
713
+ model's internal embedding lookup matrix.
714
+ output_attentions (`bool`, *optional*):
715
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
716
+ tensors for more detail.
717
+ output_hidden_states (`bool`, *optional*):
718
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
719
+ more detail.
720
+ return_dict (`bool`, *optional*):
721
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
722
+ """
723
+
724
+
725
+ @add_start_docstrings(
726
+ "The bare I-BERT Model transformer outputting raw hidden-states without any specific head on top.",
727
+ IBERT_START_DOCSTRING,
728
+ )
729
+ class IBertModel(IBertPreTrainedModel):
730
+ """
731
+
732
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
733
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
734
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
735
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
736
+
737
+ """
738
+
739
+ def __init__(self, config, add_pooling_layer=True):
740
+ super().__init__(config)
741
+ self.config = config
742
+ self.quant_mode = config.quant_mode
743
+
744
+ self.embeddings = IBertEmbeddings(config)
745
+ self.encoder = IBertEncoder(config)
746
+
747
+ self.pooler = IBertPooler(config) if add_pooling_layer else None
748
+
749
+ # Initialize weights and apply final processing
750
+ self.post_init()
751
+
752
+ def get_input_embeddings(self):
753
+ return self.embeddings.word_embeddings
754
+
755
+ def set_input_embeddings(self, value):
756
+ self.embeddings.word_embeddings = value
757
+
758
+ def _prune_heads(self, heads_to_prune):
759
+ """
760
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
761
+ class PreTrainedModel
762
+ """
763
+ for layer, heads in heads_to_prune.items():
764
+ self.encoder.layer[layer].attention.prune_heads(heads)
765
+
766
+ @add_start_docstrings_to_model_forward(IBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
767
+ @add_code_sample_docstrings(
768
+ checkpoint=_CHECKPOINT_FOR_DOC,
769
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
770
+ config_class=_CONFIG_FOR_DOC,
771
+ )
772
+ def forward(
773
+ self,
774
+ input_ids: Optional[torch.LongTensor] = None,
775
+ attention_mask: Optional[torch.FloatTensor] = None,
776
+ token_type_ids: Optional[torch.LongTensor] = None,
777
+ position_ids: Optional[torch.LongTensor] = None,
778
+ head_mask: Optional[torch.FloatTensor] = None,
779
+ inputs_embeds: Optional[torch.FloatTensor] = None,
780
+ output_attentions: Optional[bool] = None,
781
+ output_hidden_states: Optional[bool] = None,
782
+ return_dict: Optional[bool] = None,
783
+ ) -> Union[BaseModelOutputWithPoolingAndCrossAttentions, Tuple[torch.FloatTensor]]:
784
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
785
+ output_hidden_states = (
786
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
787
+ )
788
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
789
+
790
+ if input_ids is not None and inputs_embeds is not None:
791
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
792
+ elif input_ids is not None:
793
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
794
+ input_shape = input_ids.size()
795
+ elif inputs_embeds is not None:
796
+ input_shape = inputs_embeds.size()[:-1]
797
+ else:
798
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
799
+
800
+ batch_size, seq_length = input_shape
801
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
802
+
803
+ if attention_mask is None:
804
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
805
+ if token_type_ids is None:
806
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
807
+
808
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
809
+ # ourselves in which case we just need to make it broadcastable to all heads.
810
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
811
+
812
+ # Prepare head mask if needed
813
+ # 1.0 in head_mask indicate we keep the head
814
+ # attention_probs has shape bsz x n_heads x N x N
815
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
816
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
817
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
818
+
819
+ embedding_output, embedding_output_scaling_factor = self.embeddings(
820
+ input_ids=input_ids,
821
+ position_ids=position_ids,
822
+ token_type_ids=token_type_ids,
823
+ inputs_embeds=inputs_embeds,
824
+ )
825
+ encoder_outputs = self.encoder(
826
+ embedding_output,
827
+ embedding_output_scaling_factor,
828
+ attention_mask=extended_attention_mask,
829
+ head_mask=head_mask,
830
+ output_attentions=output_attentions,
831
+ output_hidden_states=output_hidden_states,
832
+ return_dict=return_dict,
833
+ )
834
+ sequence_output = encoder_outputs[0]
835
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
836
+
837
+ if not return_dict:
838
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
839
+
840
+ return BaseModelOutputWithPoolingAndCrossAttentions(
841
+ last_hidden_state=sequence_output,
842
+ pooler_output=pooled_output,
843
+ past_key_values=encoder_outputs.past_key_values,
844
+ hidden_states=encoder_outputs.hidden_states,
845
+ attentions=encoder_outputs.attentions,
846
+ cross_attentions=encoder_outputs.cross_attentions,
847
+ )
848
+
849
+
850
+ @add_start_docstrings("""I-BERT Model with a `language modeling` head on top.""", IBERT_START_DOCSTRING)
851
+ class IBertForMaskedLM(IBertPreTrainedModel):
852
+ _tied_weights_keys = ["lm_head.decoder.bias", "lm_head.decoder.weight"]
853
+
854
+ def __init__(self, config):
855
+ super().__init__(config)
856
+
857
+ self.ibert = IBertModel(config, add_pooling_layer=False)
858
+ self.lm_head = IBertLMHead(config)
859
+
860
+ # Initialize weights and apply final processing
861
+ self.post_init()
862
+
863
+ def get_output_embeddings(self):
864
+ return self.lm_head.decoder
865
+
866
+ def set_output_embeddings(self, new_embeddings):
867
+ self.lm_head.decoder = new_embeddings
868
+ self.lm_head.bias = new_embeddings.bias
869
+
870
+ @add_start_docstrings_to_model_forward(IBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
871
+ @add_code_sample_docstrings(
872
+ checkpoint=_CHECKPOINT_FOR_DOC,
873
+ output_type=MaskedLMOutput,
874
+ config_class=_CONFIG_FOR_DOC,
875
+ mask="<mask>",
876
+ )
877
+ def forward(
878
+ self,
879
+ input_ids: Optional[torch.LongTensor] = None,
880
+ attention_mask: Optional[torch.FloatTensor] = None,
881
+ token_type_ids: Optional[torch.LongTensor] = None,
882
+ position_ids: Optional[torch.LongTensor] = None,
883
+ head_mask: Optional[torch.FloatTensor] = None,
884
+ inputs_embeds: Optional[torch.FloatTensor] = None,
885
+ labels: Optional[torch.LongTensor] = None,
886
+ output_attentions: Optional[bool] = None,
887
+ output_hidden_states: Optional[bool] = None,
888
+ return_dict: Optional[bool] = None,
889
+ ) -> Union[MaskedLMOutput, Tuple[torch.FloatTensor]]:
890
+ r"""
891
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
892
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
893
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
894
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
895
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
896
+ Used to hide legacy arguments that have been deprecated.
897
+ """
898
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
899
+
900
+ outputs = self.ibert(
901
+ input_ids,
902
+ attention_mask=attention_mask,
903
+ token_type_ids=token_type_ids,
904
+ position_ids=position_ids,
905
+ head_mask=head_mask,
906
+ inputs_embeds=inputs_embeds,
907
+ output_attentions=output_attentions,
908
+ output_hidden_states=output_hidden_states,
909
+ return_dict=return_dict,
910
+ )
911
+ sequence_output = outputs[0]
912
+ prediction_scores = self.lm_head(sequence_output)
913
+
914
+ masked_lm_loss = None
915
+ if labels is not None:
916
+ loss_fct = CrossEntropyLoss()
917
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
918
+
919
+ if not return_dict:
920
+ output = (prediction_scores,) + outputs[2:]
921
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
922
+
923
+ return MaskedLMOutput(
924
+ loss=masked_lm_loss,
925
+ logits=prediction_scores,
926
+ hidden_states=outputs.hidden_states,
927
+ attentions=outputs.attentions,
928
+ )
929
+
930
+
931
+ class IBertLMHead(nn.Module):
932
+ """I-BERT Head for masked language modeling."""
933
+
934
+ def __init__(self, config):
935
+ super().__init__()
936
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
937
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
938
+
939
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
940
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
941
+ self.decoder.bias = self.bias
942
+
943
+ def forward(self, features, **kwargs):
944
+ x = self.dense(features)
945
+ x = gelu(x)
946
+ x = self.layer_norm(x)
947
+
948
+ # project back to size of vocabulary with bias
949
+ x = self.decoder(x)
950
+
951
+ return x
952
+
953
+ def _tie_weights(self) -> None:
954
+ # For accelerate compatibility and to not break backward compatibility
955
+ if self.decoder.bias.device.type == "meta":
956
+ self.decoder.bias = self.bias
957
+ else:
958
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
959
+ self.bias = self.decoder.bias
960
+
961
+
962
+ @add_start_docstrings(
963
+ """
964
+ I-BERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
965
+ output) e.g. for GLUE tasks.
966
+ """,
967
+ IBERT_START_DOCSTRING,
968
+ )
969
+ class IBertForSequenceClassification(IBertPreTrainedModel):
970
+ def __init__(self, config):
971
+ super().__init__(config)
972
+ self.num_labels = config.num_labels
973
+
974
+ self.ibert = IBertModel(config, add_pooling_layer=False)
975
+ self.classifier = IBertClassificationHead(config)
976
+
977
+ # Initialize weights and apply final processing
978
+ self.post_init()
979
+
980
+ @add_start_docstrings_to_model_forward(IBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
981
+ @add_code_sample_docstrings(
982
+ checkpoint=_CHECKPOINT_FOR_DOC,
983
+ output_type=SequenceClassifierOutput,
984
+ config_class=_CONFIG_FOR_DOC,
985
+ )
986
+ def forward(
987
+ self,
988
+ input_ids: Optional[torch.LongTensor] = None,
989
+ attention_mask: Optional[torch.FloatTensor] = None,
990
+ token_type_ids: Optional[torch.LongTensor] = None,
991
+ position_ids: Optional[torch.LongTensor] = None,
992
+ head_mask: Optional[torch.FloatTensor] = None,
993
+ inputs_embeds: Optional[torch.FloatTensor] = None,
994
+ labels: Optional[torch.LongTensor] = None,
995
+ output_attentions: Optional[bool] = None,
996
+ output_hidden_states: Optional[bool] = None,
997
+ return_dict: Optional[bool] = None,
998
+ ) -> Union[SequenceClassifierOutput, Tuple[torch.FloatTensor]]:
999
+ r"""
1000
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1001
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1002
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1003
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1004
+ """
1005
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1006
+
1007
+ outputs = self.ibert(
1008
+ input_ids,
1009
+ attention_mask=attention_mask,
1010
+ token_type_ids=token_type_ids,
1011
+ position_ids=position_ids,
1012
+ head_mask=head_mask,
1013
+ inputs_embeds=inputs_embeds,
1014
+ output_attentions=output_attentions,
1015
+ output_hidden_states=output_hidden_states,
1016
+ return_dict=return_dict,
1017
+ )
1018
+ sequence_output = outputs[0]
1019
+ logits = self.classifier(sequence_output)
1020
+
1021
+ loss = None
1022
+ if labels is not None:
1023
+ if self.config.problem_type is None:
1024
+ if self.num_labels == 1:
1025
+ self.config.problem_type = "regression"
1026
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1027
+ self.config.problem_type = "single_label_classification"
1028
+ else:
1029
+ self.config.problem_type = "multi_label_classification"
1030
+
1031
+ if self.config.problem_type == "regression":
1032
+ loss_fct = MSELoss()
1033
+ if self.num_labels == 1:
1034
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1035
+ else:
1036
+ loss = loss_fct(logits, labels)
1037
+ elif self.config.problem_type == "single_label_classification":
1038
+ loss_fct = CrossEntropyLoss()
1039
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1040
+ elif self.config.problem_type == "multi_label_classification":
1041
+ loss_fct = BCEWithLogitsLoss()
1042
+ loss = loss_fct(logits, labels)
1043
+ if not return_dict:
1044
+ output = (logits,) + outputs[2:]
1045
+ return ((loss,) + output) if loss is not None else output
1046
+
1047
+ return SequenceClassifierOutput(
1048
+ loss=loss,
1049
+ logits=logits,
1050
+ hidden_states=outputs.hidden_states,
1051
+ attentions=outputs.attentions,
1052
+ )
1053
+
1054
+
1055
+ @add_start_docstrings(
1056
+ """
1057
+ I-BERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1058
+ softmax) e.g. for RocStories/SWAG tasks.
1059
+ """,
1060
+ IBERT_START_DOCSTRING,
1061
+ )
1062
+ class IBertForMultipleChoice(IBertPreTrainedModel):
1063
+ def __init__(self, config):
1064
+ super().__init__(config)
1065
+
1066
+ self.ibert = IBertModel(config)
1067
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1068
+ self.classifier = nn.Linear(config.hidden_size, 1)
1069
+
1070
+ # Initialize weights and apply final processing
1071
+ self.post_init()
1072
+
1073
+ @add_start_docstrings_to_model_forward(IBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1074
+ @add_code_sample_docstrings(
1075
+ checkpoint=_CHECKPOINT_FOR_DOC,
1076
+ output_type=MultipleChoiceModelOutput,
1077
+ config_class=_CONFIG_FOR_DOC,
1078
+ )
1079
+ def forward(
1080
+ self,
1081
+ input_ids: Optional[torch.LongTensor] = None,
1082
+ token_type_ids: Optional[torch.LongTensor] = None,
1083
+ attention_mask: Optional[torch.FloatTensor] = None,
1084
+ labels: Optional[torch.LongTensor] = None,
1085
+ position_ids: Optional[torch.LongTensor] = None,
1086
+ head_mask: Optional[torch.FloatTensor] = None,
1087
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1088
+ output_attentions: Optional[bool] = None,
1089
+ output_hidden_states: Optional[bool] = None,
1090
+ return_dict: Optional[bool] = None,
1091
+ ) -> Union[MultipleChoiceModelOutput, Tuple[torch.FloatTensor]]:
1092
+ r"""
1093
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1094
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1095
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1096
+ `input_ids` above)
1097
+ """
1098
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1099
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1100
+
1101
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1102
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1103
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1104
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1105
+ flat_inputs_embeds = (
1106
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1107
+ if inputs_embeds is not None
1108
+ else None
1109
+ )
1110
+
1111
+ outputs = self.ibert(
1112
+ flat_input_ids,
1113
+ position_ids=flat_position_ids,
1114
+ token_type_ids=flat_token_type_ids,
1115
+ attention_mask=flat_attention_mask,
1116
+ head_mask=head_mask,
1117
+ inputs_embeds=flat_inputs_embeds,
1118
+ output_attentions=output_attentions,
1119
+ output_hidden_states=output_hidden_states,
1120
+ return_dict=return_dict,
1121
+ )
1122
+ pooled_output = outputs[1]
1123
+
1124
+ pooled_output = self.dropout(pooled_output)
1125
+ logits = self.classifier(pooled_output)
1126
+ reshaped_logits = logits.view(-1, num_choices)
1127
+
1128
+ loss = None
1129
+ if labels is not None:
1130
+ loss_fct = CrossEntropyLoss()
1131
+ loss = loss_fct(reshaped_logits, labels)
1132
+
1133
+ if not return_dict:
1134
+ output = (reshaped_logits,) + outputs[2:]
1135
+ return ((loss,) + output) if loss is not None else output
1136
+
1137
+ return MultipleChoiceModelOutput(
1138
+ loss=loss,
1139
+ logits=reshaped_logits,
1140
+ hidden_states=outputs.hidden_states,
1141
+ attentions=outputs.attentions,
1142
+ )
1143
+
1144
+
1145
+ @add_start_docstrings(
1146
+ """
1147
+ I-BERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1148
+ Named-Entity-Recognition (NER) tasks.
1149
+ """,
1150
+ IBERT_START_DOCSTRING,
1151
+ )
1152
+ class IBertForTokenClassification(IBertPreTrainedModel):
1153
+ def __init__(self, config):
1154
+ super().__init__(config)
1155
+ self.num_labels = config.num_labels
1156
+
1157
+ self.ibert = IBertModel(config, add_pooling_layer=False)
1158
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1159
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1160
+
1161
+ # Initialize weights and apply final processing
1162
+ self.post_init()
1163
+
1164
+ @add_start_docstrings_to_model_forward(IBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1165
+ @add_code_sample_docstrings(
1166
+ checkpoint=_CHECKPOINT_FOR_DOC,
1167
+ output_type=TokenClassifierOutput,
1168
+ config_class=_CONFIG_FOR_DOC,
1169
+ )
1170
+ def forward(
1171
+ self,
1172
+ input_ids: Optional[torch.LongTensor] = None,
1173
+ attention_mask: Optional[torch.FloatTensor] = None,
1174
+ token_type_ids: Optional[torch.LongTensor] = None,
1175
+ position_ids: Optional[torch.LongTensor] = None,
1176
+ head_mask: Optional[torch.FloatTensor] = None,
1177
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1178
+ labels: Optional[torch.LongTensor] = None,
1179
+ output_attentions: Optional[bool] = None,
1180
+ output_hidden_states: Optional[bool] = None,
1181
+ return_dict: Optional[bool] = None,
1182
+ ) -> Union[TokenClassifierOutput, Tuple[torch.FloatTensor]]:
1183
+ r"""
1184
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1185
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1186
+ """
1187
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1188
+
1189
+ outputs = self.ibert(
1190
+ input_ids,
1191
+ attention_mask=attention_mask,
1192
+ token_type_ids=token_type_ids,
1193
+ position_ids=position_ids,
1194
+ head_mask=head_mask,
1195
+ inputs_embeds=inputs_embeds,
1196
+ output_attentions=output_attentions,
1197
+ output_hidden_states=output_hidden_states,
1198
+ return_dict=return_dict,
1199
+ )
1200
+
1201
+ sequence_output = outputs[0]
1202
+
1203
+ sequence_output = self.dropout(sequence_output)
1204
+ logits = self.classifier(sequence_output)
1205
+
1206
+ loss = None
1207
+ if labels is not None:
1208
+ loss_fct = CrossEntropyLoss()
1209
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1210
+
1211
+ if not return_dict:
1212
+ output = (logits,) + outputs[2:]
1213
+ return ((loss,) + output) if loss is not None else output
1214
+
1215
+ return TokenClassifierOutput(
1216
+ loss=loss,
1217
+ logits=logits,
1218
+ hidden_states=outputs.hidden_states,
1219
+ attentions=outputs.attentions,
1220
+ )
1221
+
1222
+
1223
+ class IBertClassificationHead(nn.Module):
1224
+ """Head for sentence-level classification tasks."""
1225
+
1226
+ def __init__(self, config):
1227
+ super().__init__()
1228
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1229
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1230
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
1231
+
1232
+ def forward(self, features, **kwargs):
1233
+ hidden_states = features[:, 0, :] # take <s> token (equiv. to [CLS])
1234
+ hidden_states = self.dropout(hidden_states)
1235
+ hidden_states = self.dense(hidden_states)
1236
+ hidden_states = torch.tanh(hidden_states)
1237
+ hidden_states = self.dropout(hidden_states)
1238
+ hidden_states = self.out_proj(hidden_states)
1239
+ return hidden_states
1240
+
1241
+
1242
+ @add_start_docstrings(
1243
+ """
1244
+ I-BERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1245
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1246
+ """,
1247
+ IBERT_START_DOCSTRING,
1248
+ )
1249
+ class IBertForQuestionAnswering(IBertPreTrainedModel):
1250
+ def __init__(self, config):
1251
+ super().__init__(config)
1252
+ self.num_labels = config.num_labels
1253
+
1254
+ self.ibert = IBertModel(config, add_pooling_layer=False)
1255
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1256
+
1257
+ # Initialize weights and apply final processing
1258
+ self.post_init()
1259
+
1260
+ @add_start_docstrings_to_model_forward(IBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1261
+ @add_code_sample_docstrings(
1262
+ checkpoint=_CHECKPOINT_FOR_DOC,
1263
+ output_type=QuestionAnsweringModelOutput,
1264
+ config_class=_CONFIG_FOR_DOC,
1265
+ )
1266
+ def forward(
1267
+ self,
1268
+ input_ids: Optional[torch.LongTensor] = None,
1269
+ attention_mask: Optional[torch.FloatTensor] = None,
1270
+ token_type_ids: Optional[torch.LongTensor] = None,
1271
+ position_ids: Optional[torch.LongTensor] = None,
1272
+ head_mask: Optional[torch.FloatTensor] = None,
1273
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1274
+ start_positions: Optional[torch.LongTensor] = None,
1275
+ end_positions: Optional[torch.LongTensor] = None,
1276
+ output_attentions: Optional[bool] = None,
1277
+ output_hidden_states: Optional[bool] = None,
1278
+ return_dict: Optional[bool] = None,
1279
+ ) -> Union[QuestionAnsweringModelOutput, Tuple[torch.FloatTensor]]:
1280
+ r"""
1281
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1282
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1283
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1284
+ are not taken into account for computing the loss.
1285
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1286
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1287
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1288
+ are not taken into account for computing the loss.
1289
+ """
1290
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1291
+
1292
+ outputs = self.ibert(
1293
+ input_ids,
1294
+ attention_mask=attention_mask,
1295
+ token_type_ids=token_type_ids,
1296
+ position_ids=position_ids,
1297
+ head_mask=head_mask,
1298
+ inputs_embeds=inputs_embeds,
1299
+ output_attentions=output_attentions,
1300
+ output_hidden_states=output_hidden_states,
1301
+ return_dict=return_dict,
1302
+ )
1303
+
1304
+ sequence_output = outputs[0]
1305
+
1306
+ logits = self.qa_outputs(sequence_output)
1307
+ start_logits, end_logits = logits.split(1, dim=-1)
1308
+ start_logits = start_logits.squeeze(-1).contiguous()
1309
+ end_logits = end_logits.squeeze(-1).contiguous()
1310
+
1311
+ total_loss = None
1312
+ if start_positions is not None and end_positions is not None:
1313
+ # If we are on multi-GPU, split add a dimension
1314
+ if len(start_positions.size()) > 1:
1315
+ start_positions = start_positions.squeeze(-1)
1316
+ if len(end_positions.size()) > 1:
1317
+ end_positions = end_positions.squeeze(-1)
1318
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1319
+ ignored_index = start_logits.size(1)
1320
+ start_positions = start_positions.clamp(0, ignored_index)
1321
+ end_positions = end_positions.clamp(0, ignored_index)
1322
+
1323
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1324
+ start_loss = loss_fct(start_logits, start_positions)
1325
+ end_loss = loss_fct(end_logits, end_positions)
1326
+ total_loss = (start_loss + end_loss) / 2
1327
+
1328
+ if not return_dict:
1329
+ output = (start_logits, end_logits) + outputs[2:]
1330
+ return ((total_loss,) + output) if total_loss is not None else output
1331
+
1332
+ return QuestionAnsweringModelOutput(
1333
+ loss=total_loss,
1334
+ start_logits=start_logits,
1335
+ end_logits=end_logits,
1336
+ hidden_states=outputs.hidden_states,
1337
+ attentions=outputs.attentions,
1338
+ )
1339
+
1340
+
1341
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
1342
+ """
1343
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
1344
+ are ignored. This is modified from fairseq's *utils.make_positions*.
1345
+
1346
+ Args:
1347
+ input_ids (`torch.LongTensor`):
1348
+ Indices of input sequence tokens in the vocabulary.
1349
+
1350
+ Returns: torch.Tensor
1351
+ """
1352
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
1353
+ mask = input_ids.ne(padding_idx).int()
1354
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
1355
+ return incremental_indices.long() + padding_idx
1356
+
1357
+
1358
+ __all__ = [
1359
+ "IBertForMaskedLM",
1360
+ "IBertForMultipleChoice",
1361
+ "IBertForQuestionAnswering",
1362
+ "IBertForSequenceClassification",
1363
+ "IBertForTokenClassification",
1364
+ "IBertModel",
1365
+ "IBertPreTrainedModel",
1366
+ ]
vllm/lib/python3.10/site-packages/transformers/models/ibert/quant_modules.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The I-BERT Authors (Sehoon Kim, Amir Gholami, Zhewei Yao,
3
+ # Michael Mahoney, Kurt Keutzer - UC Berkeley) and The HuggingFace Inc. team.
4
+ # Copyright (c) 20121, NVIDIA CORPORATION. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import decimal
19
+
20
+ import numpy as np
21
+ import torch
22
+ from torch import nn
23
+ from torch.autograd import Function
24
+
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class QuantEmbedding(nn.Module):
32
+ """
33
+ Quantized version of `torch.nn.Embedding`. Adds quantization-specific arguments on top of `torch.nn.Embedding`.
34
+
35
+ Args:
36
+ weight_bit (`int`, *optional*, defaults to `8`):
37
+ Bitwidth for the quantized weight.
38
+ momentum (`float`, *optional*, defaults to `0.95`):
39
+ Momentum for updating the activation quantization range.
40
+ quant_mode (`bool`, *optional*, defaults to `False`):
41
+ Whether or not the layer is quantized.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ num_embeddings,
47
+ embedding_dim,
48
+ padding_idx=None,
49
+ max_norm=None,
50
+ norm_type=2.0,
51
+ scale_grad_by_freq=False,
52
+ sparse=False,
53
+ _weight=None,
54
+ weight_bit=8,
55
+ momentum=0.95,
56
+ quant_mode=False,
57
+ ):
58
+ super().__init__()
59
+ self.num_ = num_embeddings
60
+ self.dim = embedding_dim
61
+ self.padding_idx = padding_idx
62
+ self.max_norm = max_norm
63
+ self.norm_type = norm_type
64
+ self.scale_grad_by_freq = scale_grad_by_freq
65
+ self.sparse = sparse
66
+
67
+ self.weight = nn.Parameter(torch.zeros([num_embeddings, embedding_dim]))
68
+ self.register_buffer("weight_scaling_factor", torch.zeros(1))
69
+ self.register_buffer("weight_integer", torch.zeros_like(self.weight))
70
+
71
+ self.weight_bit = weight_bit
72
+ self.momentum = momentum
73
+ self.quant_mode = quant_mode
74
+ self.percentile_mode = False
75
+ self.weight_function = SymmetricQuantFunction.apply
76
+
77
+ def forward(self, x, positions=None, incremental_state=None):
78
+ if not self.quant_mode:
79
+ return (
80
+ nn.functional.embedding(
81
+ x,
82
+ self.weight,
83
+ self.padding_idx,
84
+ self.max_norm,
85
+ self.norm_type,
86
+ self.scale_grad_by_freq,
87
+ self.sparse,
88
+ ),
89
+ None,
90
+ )
91
+
92
+ w = self.weight
93
+ w_transform = w.data.detach()
94
+ w_min = w_transform.min().expand(1)
95
+ w_max = w_transform.max().expand(1)
96
+
97
+ self.weight_scaling_factor = symmetric_linear_quantization_params(self.weight_bit, w_min, w_max, False)
98
+ self.weight_integer = self.weight_function(
99
+ self.weight, self.weight_bit, self.percentile_mode, self.weight_scaling_factor
100
+ )
101
+
102
+ emb_int = nn.functional.embedding(
103
+ x,
104
+ self.weight_integer,
105
+ self.padding_idx,
106
+ self.max_norm,
107
+ self.norm_type,
108
+ self.scale_grad_by_freq,
109
+ self.sparse,
110
+ )
111
+ return emb_int * self.weight_scaling_factor, self.weight_scaling_factor
112
+
113
+
114
+ class QuantAct(nn.Module):
115
+ """
116
+ Quantizes the given activation.
117
+
118
+ Args:
119
+ activation_bit (`int`):
120
+ Bitwidth for the quantized activation.
121
+ act_range_momentum (`float`, *optional*, defaults to `0.95`):
122
+ Momentum for updating the activation quantization range.
123
+ per_channel (`bool`, *optional*, defaults to `False`):
124
+ Whether to or not use channel-wise quantization.
125
+ channel_len (`int`, *optional*):
126
+ Specify the channel length when set the *per_channel* True.
127
+ quant_mode (`bool`, *optional*, defaults to `False`):
128
+ Whether or not the layer is quantized.
129
+ """
130
+
131
+ def __init__(self, activation_bit, act_range_momentum=0.95, per_channel=False, channel_len=None, quant_mode=False):
132
+ super().__init__()
133
+
134
+ self.activation_bit = activation_bit
135
+ self.act_range_momentum = act_range_momentum
136
+ self.quant_mode = quant_mode
137
+ self.per_channel = per_channel
138
+ self.percentile = False
139
+ self.act_function = SymmetricQuantFunction.apply
140
+
141
+ if not self.per_channel:
142
+ self.register_buffer("x_min", torch.zeros(1))
143
+ self.register_buffer("x_max", torch.zeros(1))
144
+ self.register_buffer("act_scaling_factor", torch.zeros(1))
145
+ self.x_min -= 1e-5
146
+ self.x_max += 1e-5
147
+ else:
148
+ raise NotImplementedError("per-channel mode is not currently supported for activation.")
149
+
150
+ def __repr__(self):
151
+ return (
152
+ f"{self.__class__.__name__}(activation_bit={self.activation_bit}, "
153
+ f"quant_mode: {self.quant_mode}, Act_min: {self.x_min.item():.2f}, "
154
+ f"Act_max: {self.x_max.item():.2f})"
155
+ )
156
+
157
+ def forward(
158
+ self,
159
+ x,
160
+ pre_act_scaling_factor=None,
161
+ identity=None,
162
+ identity_scaling_factor=None,
163
+ specified_min=None,
164
+ specified_max=None,
165
+ ):
166
+ x_act = x if identity is None else identity + x
167
+ # collect running stats if training
168
+ if self.training:
169
+ assert not self.percentile, "percentile mode is not currently supported for activation."
170
+ assert not self.per_channel, "per-channel mode is not currently supported for activation."
171
+ x_min = x_act.data.min()
172
+ x_max = x_act.data.max()
173
+
174
+ assert (
175
+ x_max.isnan().sum() == 0 and x_min.isnan().sum() == 0
176
+ ), "NaN detected when computing min/max of the activation"
177
+
178
+ # Initialization
179
+ if self.x_min.min() > -1.1e-5 and self.x_max.max() < 1.1e-5:
180
+ self.x_min = self.x_min + x_min
181
+ self.x_max = self.x_max + x_max
182
+
183
+ # exponential moving average (EMA)
184
+ # use momentum to prevent the quantized values change greatly every iteration
185
+ elif self.act_range_momentum == -1:
186
+ self.x_min = torch.min(self.x_min, x_min)
187
+ self.x_max = torch.max(self.x_max, x_max)
188
+ else:
189
+ self.x_min = self.x_min * self.act_range_momentum + x_min * (1 - self.act_range_momentum)
190
+ self.x_max = self.x_max * self.act_range_momentum + x_max * (1 - self.act_range_momentum)
191
+
192
+ if not self.quant_mode:
193
+ return x_act, None
194
+
195
+ x_min = self.x_min if specified_min is None else specified_min
196
+ x_max = self.x_max if specified_max is None else specified_max
197
+
198
+ self.act_scaling_factor = symmetric_linear_quantization_params(
199
+ self.activation_bit, x_min, x_max, per_channel=self.per_channel
200
+ )
201
+
202
+ if pre_act_scaling_factor is None:
203
+ # this is for the input quantization
204
+ quant_act_int = self.act_function(x, self.activation_bit, self.percentile, self.act_scaling_factor)
205
+ else:
206
+ quant_act_int = FixedPointMul.apply(
207
+ x,
208
+ pre_act_scaling_factor,
209
+ self.activation_bit,
210
+ self.act_scaling_factor,
211
+ identity,
212
+ identity_scaling_factor,
213
+ )
214
+
215
+ correct_output_scale = self.act_scaling_factor.view(-1)
216
+
217
+ return quant_act_int * correct_output_scale, self.act_scaling_factor
218
+
219
+
220
+ class QuantLinear(nn.Module):
221
+ """
222
+ Quantized version of `torch.nn.Linear`. Adds quantization-specific arguments on top of `torch.nn.Linear`.
223
+
224
+ Args:
225
+ weight_bit (`int`, *optional*, defaults to `8`):
226
+ Bitwidth for the quantized weight.
227
+ bias_bit (`int`, *optional*, defaults to `32`):
228
+ Bitwidth for the quantized bias.
229
+ per_channel (`bool`, *optional*, defaults to `False`):
230
+ Whether or not to use channel-wise quantization.
231
+ quant_mode (`bool`, *optional*, defaults to `False`):
232
+ Whether or not the layer is quantized.
233
+ """
234
+
235
+ def __init__(
236
+ self, in_features, out_features, bias=True, weight_bit=8, bias_bit=32, per_channel=False, quant_mode=False
237
+ ):
238
+ super().__init__()
239
+ self.in_features = in_features
240
+ self.out_features = out_features
241
+
242
+ self.weight = nn.Parameter(torch.zeros([out_features, in_features]))
243
+ self.register_buffer("weight_integer", torch.zeros_like(self.weight))
244
+ self.register_buffer("fc_scaling_factor", torch.zeros(self.out_features))
245
+ if bias:
246
+ self.bias = nn.Parameter(torch.zeros(out_features))
247
+ self.register_buffer("bias_integer", torch.zeros_like(self.bias))
248
+
249
+ self.weight_bit = weight_bit
250
+ self.quant_mode = quant_mode
251
+ self.per_channel = per_channel
252
+ self.bias_bit = bias_bit
253
+ self.quant_mode = quant_mode
254
+ self.percentile_mode = False
255
+ self.weight_function = SymmetricQuantFunction.apply
256
+
257
+ def __repr__(self):
258
+ s = super().__repr__()
259
+ s = f"({s} weight_bit={self.weight_bit}, quant_mode={self.quant_mode})"
260
+ return s
261
+
262
+ def forward(self, x, prev_act_scaling_factor=None):
263
+ if not self.quant_mode:
264
+ return nn.functional.linear(x, weight=self.weight, bias=self.bias), None
265
+
266
+ # assert that prev_act_scaling_factor is a scalar tensor
267
+ assert prev_act_scaling_factor is not None and prev_act_scaling_factor.shape == (1,), (
268
+ "Input activation to the QuantLinear layer should be globally (non-channel-wise) quantized. "
269
+ "Please add a QuantAct layer with `per_channel = True` before this QuantAct layer"
270
+ )
271
+
272
+ w = self.weight
273
+ w_transform = w.data.detach()
274
+ if self.per_channel:
275
+ w_min, _ = torch.min(w_transform, dim=1, out=None)
276
+ w_max, _ = torch.max(w_transform, dim=1, out=None)
277
+ else:
278
+ w_min = w_transform.min().expand(1)
279
+ w_max = w_transform.max().expand(1)
280
+
281
+ self.fc_scaling_factor = symmetric_linear_quantization_params(self.weight_bit, w_min, w_max, self.per_channel)
282
+ self.weight_integer = self.weight_function(
283
+ self.weight, self.weight_bit, self.percentile_mode, self.fc_scaling_factor
284
+ )
285
+
286
+ bias_scaling_factor = self.fc_scaling_factor * prev_act_scaling_factor
287
+
288
+ if self.bias is not None:
289
+ self.bias_integer = self.weight_function(self.bias, self.bias_bit, False, bias_scaling_factor)
290
+
291
+ prev_act_scaling_factor = prev_act_scaling_factor.view(1, -1)
292
+ x_int = x / prev_act_scaling_factor
293
+
294
+ return (
295
+ nn.functional.linear(x_int, weight=self.weight_integer, bias=self.bias_integer) * bias_scaling_factor,
296
+ bias_scaling_factor,
297
+ )
298
+
299
+
300
+ class IntGELU(nn.Module):
301
+ """
302
+ Quantized version of `torch.nn.GELU`. Adds quantization-specific arguments on top of `torch.nn.GELU`.
303
+
304
+ Args:
305
+ quant_mode (`bool`, *optional*, defaults to `False`):
306
+ Whether or not the layer is quantized.
307
+ force_dequant (`str`, *optional*, defaults to `"none"`):
308
+ Force dequantize the layer if either "gelu" or "nonlinear" is given.
309
+ """
310
+
311
+ def __init__(self, quant_mode=True, force_dequant="none"):
312
+ super().__init__()
313
+ self.quant_mode = quant_mode
314
+
315
+ if force_dequant in ["nonlinear", "gelu"]:
316
+ logger.info("Force dequantize gelu")
317
+ self.quant_mode = False
318
+
319
+ if not self.quant_mode:
320
+ self.activation_fn = nn.GELU()
321
+
322
+ self.k = 1.4142
323
+ self.const = 14 # dummy integer constant
324
+ self.coeff = [-0.2888, -1.769, 1] # a(x+b)**2 + c
325
+ self.coeff[2] /= self.coeff[0]
326
+
327
+ def int_erf(self, x_int, scaling_factor):
328
+ b_int = torch.floor(self.coeff[1] / scaling_factor)
329
+ c_int = torch.floor(self.coeff[2] / scaling_factor**2)
330
+ sign = torch.sign(x_int)
331
+
332
+ abs_int = torch.min(torch.abs(x_int), -b_int)
333
+ y_int = sign * ((abs_int + b_int) ** 2 + c_int)
334
+ scaling_factor = scaling_factor**2 * self.coeff[0]
335
+
336
+ # avoid overflow
337
+ y_int = floor_ste.apply(y_int / 2**self.const)
338
+ scaling_factor = scaling_factor * 2**self.const
339
+
340
+ return y_int, scaling_factor
341
+
342
+ def forward(self, x, scaling_factor=None):
343
+ if not self.quant_mode:
344
+ return self.activation_fn(x), None
345
+
346
+ x_int = x / scaling_factor
347
+ sigmoid_int, sigmoid_scaling_factor = self.int_erf(x_int, scaling_factor / self.k)
348
+
349
+ shift_int = 1.0 // sigmoid_scaling_factor
350
+
351
+ x_int = x_int * (sigmoid_int + shift_int)
352
+ scaling_factor = scaling_factor * sigmoid_scaling_factor / 2
353
+
354
+ return x_int * scaling_factor, scaling_factor
355
+
356
+
357
+ class IntSoftmax(nn.Module):
358
+ """
359
+ Quantized version of `torch.nn.Softmax`. Adds quantization-specific arguments on top of `torch.nn.Softmax`.
360
+
361
+ Args:
362
+ output_bit (`int`):
363
+ Bitwidth for the layer output activation.
364
+ quant_mode (`bool`, *optional*, defaults to `False`):
365
+ Whether or not the layer is quantized.
366
+ force_dequant (`str`, *optional*, defaults to `"none"`):
367
+ Force dequantize the layer if either "softmax" or "nonlinear" is given.
368
+ """
369
+
370
+ def __init__(self, output_bit, quant_mode=False, force_dequant="none"):
371
+ super().__init__()
372
+ self.output_bit = output_bit
373
+ self.max_bit = 32
374
+ self.quant_mode = quant_mode
375
+
376
+ if force_dequant in ["nonlinear", "softmax"]:
377
+ logger.info("Force dequantize softmax")
378
+ self.quant_mode = False
379
+
380
+ self.act = QuantAct(16, quant_mode=self.quant_mode)
381
+ self.x0 = -0.6931 # -ln2
382
+ self.const = 30 # dummy integer constant
383
+ self.coef = [0.35815147, 0.96963238, 1.0] # ax**2 + bx + c
384
+ self.coef[1] /= self.coef[0]
385
+ self.coef[2] /= self.coef[0]
386
+
387
+ def int_polynomial(self, x_int, scaling_factor):
388
+ with torch.no_grad():
389
+ b_int = torch.floor(self.coef[1] / scaling_factor)
390
+ c_int = torch.floor(self.coef[2] / scaling_factor**2)
391
+ z = (x_int + b_int) * x_int + c_int
392
+ scaling_factor = self.coef[0] * scaling_factor**2
393
+ return z, scaling_factor
394
+
395
+ def int_exp(self, x_int, scaling_factor):
396
+ with torch.no_grad():
397
+ x0_int = torch.floor(self.x0 / scaling_factor)
398
+ x_int = torch.max(x_int, self.const * x0_int)
399
+
400
+ q = floor_ste.apply(x_int / x0_int)
401
+ r = x_int - x0_int * q
402
+ exp_int, exp_scaling_factor = self.int_polynomial(r, scaling_factor)
403
+ exp_int = torch.clamp(floor_ste.apply(exp_int * 2 ** (self.const - q)), min=0)
404
+ scaling_factor = exp_scaling_factor / 2**self.const
405
+ return exp_int, scaling_factor
406
+
407
+ def forward(self, x, scaling_factor):
408
+ if not self.quant_mode:
409
+ return nn.functional.softmax(x, dim=-1), None
410
+
411
+ x_int = x / scaling_factor
412
+
413
+ x_int_max, _ = x_int.max(dim=-1, keepdim=True)
414
+ x_int = x_int - x_int_max
415
+ exp_int, exp_scaling_factor = self.int_exp(x_int, scaling_factor)
416
+
417
+ # Avoid overflow
418
+ exp, exp_scaling_factor = self.act(exp_int, exp_scaling_factor)
419
+ exp_int = exp / exp_scaling_factor
420
+
421
+ exp_int_sum = exp_int.sum(dim=-1, keepdim=True)
422
+ factor = floor_ste.apply(2**self.max_bit / exp_int_sum)
423
+ exp_int = floor_ste.apply(exp_int * factor / 2 ** (self.max_bit - self.output_bit))
424
+ scaling_factor = 1 / 2**self.output_bit
425
+ return exp_int * scaling_factor, scaling_factor
426
+
427
+
428
+ class IntLayerNorm(nn.Module):
429
+ """
430
+ Quantized version of `torch.nn.LayerNorm`. Adds quantization-specific arguments on top of `torch.nn.LayerNorm`.
431
+
432
+ Args:
433
+ output_bit (`int`, *optional*, defaults to `8`):
434
+ Bitwidth for the layer output activation.
435
+ quant_mode (`bool`, *optional*, defaults to `False`):
436
+ Whether or not the layer is quantized.
437
+ force_dequant (`str`, *optional*, defaults to `"none"`):
438
+ Force dequantize the layer if either "layernorm" or "nonlinear" is given.
439
+ """
440
+
441
+ def __init__(self, normalized_shape, eps, output_bit=8, quant_mode=False, force_dequant="none"):
442
+ super().__init__()
443
+ self.normalized_shape = normalized_shape
444
+ self.eps = eps
445
+
446
+ self.weight = nn.Parameter(torch.zeros(normalized_shape))
447
+ self.bias = nn.Parameter(torch.zeros(normalized_shape))
448
+
449
+ self.quant_mode = quant_mode
450
+ if force_dequant in ["nonlinear", "layernorm"]:
451
+ logger.info("Force dequantize layernorm")
452
+ self.quant_mode = False
453
+
454
+ self.register_buffer("shift", torch.zeros(1))
455
+ self.output_bit = output_bit
456
+ self.max_bit = 32
457
+ self.dim_sqrt = None
458
+ self.activation = QuantAct(self.output_bit, quant_mode=self.quant_mode)
459
+
460
+ def set_shift(self, y_int):
461
+ with torch.no_grad():
462
+ y_sq_int = y_int**2
463
+ var_int = torch.sum(y_sq_int, axis=2, keepdim=True)
464
+ shift = (torch.log2(torch.sqrt(var_int / 2**self.max_bit)).ceil()).max()
465
+ shift_old = self.shift
466
+ self.shift = torch.max(self.shift, shift)
467
+ logger.info(f"Dynamic shift adjustment: {int(shift_old)} -> {int(self.shift)}")
468
+
469
+ def overflow_fallback(self, y_int):
470
+ """
471
+ This fallback function is called when overflow is detected during training time, and adjusts the `self.shift`
472
+ to avoid overflow in the subsequent runs.
473
+ """
474
+ self.set_shift(y_int) # adjusts `self.shift`
475
+ y_int_shifted = floor_ste.apply(y_int / 2**self.shift)
476
+ y_sq_int = y_int_shifted**2
477
+ var_int = torch.sum(y_sq_int, axis=2, keepdim=True)
478
+ return var_int
479
+
480
+ def forward(self, x, scaling_factor=None):
481
+ if not self.quant_mode:
482
+ mean = x.mean(axis=2, keepdim=True)
483
+ y = x - mean
484
+ var = torch.mean(y**2, axis=2, keepdim=True)
485
+ x = y / torch.sqrt(self.eps + var)
486
+ x = x * self.weight + self.bias
487
+ return x, None
488
+
489
+ # compute sqrt of the feature dimension if it is the first run
490
+ if self.dim_sqrt is None:
491
+ n = torch.tensor(x.shape[2], dtype=torch.float)
492
+ self.dim_sqrt = torch.sqrt(n).to(x.device)
493
+
494
+ # Normalization: computes mean and variance(std)
495
+ x_int = x / scaling_factor
496
+ mean_int = round_ste.apply(x_int.mean(axis=2, keepdim=True))
497
+ y_int = x_int - mean_int
498
+ y_int_shifted = floor_ste.apply(y_int / 2**self.shift)
499
+ y_sq_int = y_int_shifted**2
500
+ var_int = torch.sum(y_sq_int, axis=2, keepdim=True)
501
+
502
+ # overflow handling in training time
503
+ if self.training:
504
+ # if overflow is detected
505
+ if var_int.max() >= 2**self.max_bit:
506
+ var_int = self.overflow_fallback(y_int)
507
+ assert var_int.max() < 2**self.max_bit + 0.1, (
508
+ "Error detected in overflow handling: "
509
+ "`var_int` exceeds `self.max_bit` (the maximum possible bit width)"
510
+ )
511
+
512
+ # To be replaced with integer-sqrt kernel that produces the same output
513
+ std_int = floor_ste.apply(torch.sqrt(var_int)) * 2**self.shift
514
+ factor = floor_ste.apply(2**31 / std_int)
515
+ y_int = floor_ste.apply(y_int * factor / 2)
516
+ scaling_factor = self.dim_sqrt / 2**30
517
+
518
+ # scaling and shifting
519
+ bias = self.bias.data.detach() / (self.weight.data.detach())
520
+ bias_int = floor_ste.apply(bias / scaling_factor)
521
+
522
+ y_int = y_int + bias_int
523
+ scaling_factor = scaling_factor * self.weight
524
+ x = y_int * scaling_factor
525
+
526
+ return x, scaling_factor
527
+
528
+
529
+ def get_percentile_min_max(input, lower_percentile, upper_percentile, output_tensor=False):
530
+ """
531
+ Calculate the percentile max and min values in a given tensor
532
+
533
+ Args:
534
+ input (`torch.Tensor`):
535
+ The target tensor to calculate percentile max and min.
536
+ lower_percentile (`float`):
537
+ If 0.1, means we return the value of the smallest 0.1% value in the tensor as percentile min.
538
+ upper_percentile (`float`):
539
+ If 99.9, means we return the value of the largest 0.1% value in the tensor as percentile max.
540
+ output_tensor (`bool`, *optional*, defaults to `False`):
541
+ If True, this function returns tensors, otherwise it returns values.
542
+
543
+ Returns:
544
+ `Tuple(torch.Tensor, torch.Tensor)`: Percentile min and max value of *input*
545
+ """
546
+ input_length = input.shape[0]
547
+
548
+ lower_index = round(input_length * (1 - lower_percentile * 0.01))
549
+ upper_index = round(input_length * upper_percentile * 0.01)
550
+
551
+ upper_bound = torch.kthvalue(input, k=upper_index).values
552
+
553
+ if lower_percentile == 0:
554
+ lower_bound = upper_bound * 0
555
+ # lower_index += 1
556
+ else:
557
+ lower_bound = -torch.kthvalue(-input, k=lower_index).values
558
+
559
+ if not output_tensor:
560
+ lower_bound = lower_bound.item()
561
+ upper_bound = upper_bound.item()
562
+ return lower_bound, upper_bound
563
+
564
+
565
+ def linear_quantize(input, scale, zero_point, inplace=False):
566
+ """
567
+ Quantize single-precision input tensor to integers with the given scaling factor and zeropoint.
568
+
569
+ Args:
570
+ input (`torch.Tensor`):
571
+ Single-precision input tensor to be quantized.
572
+ scale (`torch.Tensor`):
573
+ Scaling factor for quantization.
574
+ zero_pint (`torch.Tensor`):
575
+ Shift for quantization.
576
+ inplace (`bool`, *optional*, defaults to `False`):
577
+ Whether to compute inplace or not.
578
+
579
+ Returns:
580
+ `torch.Tensor`: Linearly quantized value of *input* according to *scale* and *zero_point*.
581
+ """
582
+ # reshape scale and zeropoint for convolutional weights and activation
583
+ if len(input.shape) == 4:
584
+ scale = scale.view(-1, 1, 1, 1)
585
+ zero_point = zero_point.view(-1, 1, 1, 1)
586
+ # reshape scale and zeropoint for linear weights
587
+ elif len(input.shape) == 2:
588
+ scale = scale.view(-1, 1)
589
+ zero_point = zero_point.view(-1, 1)
590
+ else:
591
+ scale = scale.view(-1)
592
+ zero_point = zero_point.view(-1)
593
+ # quantized = float / scale + zero_point
594
+ if inplace:
595
+ input.mul_(1.0 / scale).add_(zero_point).round_()
596
+ return input
597
+ return torch.round(1.0 / scale * input + zero_point)
598
+
599
+
600
+ def symmetric_linear_quantization_params(num_bits, saturation_min, saturation_max, per_channel=False):
601
+ """
602
+ Compute the scaling factor with the given quantization range for symmetric quantization.
603
+
604
+ Args:
605
+ saturation_min (`torch.Tensor`):
606
+ Lower bound for quantization range.
607
+ saturation_max (`torch.Tensor`):
608
+ Upper bound for quantization range.
609
+ per_channel (`bool`, *optional*, defaults to `False`):
610
+ Whether to or not use channel-wise quantization.
611
+
612
+ Returns:
613
+ `torch.Tensor`: Scaling factor that linearly quantizes the given range between *saturation_min* and
614
+ *saturation_max*.
615
+ """
616
+ # in this part, we do not need any gradient computation,
617
+ # in order to enforce this, we put torch.no_grad()
618
+ with torch.no_grad():
619
+ n = 2 ** (num_bits - 1) - 1
620
+
621
+ if per_channel:
622
+ scale, _ = torch.max(torch.stack([saturation_min.abs(), saturation_max.abs()], dim=1), dim=1)
623
+ scale = torch.clamp(scale, min=1e-8) / n
624
+
625
+ else:
626
+ scale = max(saturation_min.abs(), saturation_max.abs())
627
+ scale = torch.clamp(scale, min=1e-8) / n
628
+
629
+ return scale
630
+
631
+
632
+ class SymmetricQuantFunction(Function):
633
+ """
634
+ Class to quantize the given floating-point values using symmetric quantization with given range and bitwidth.
635
+ """
636
+
637
+ @staticmethod
638
+ def forward(ctx, x, k, percentile_mode, scale):
639
+ """
640
+ Args:
641
+ x (`torch.Tensor`):
642
+ Floating point tensor to be quantized.
643
+ k (`int`):
644
+ Quantization bitwidth.
645
+ percentile_mode (`bool`):
646
+ Whether or not to use percentile calibration.
647
+ scale (`torch.Tensor`):
648
+ Pre-calculated scaling factor for *x*. Note that the current implementation of SymmetricQuantFunction
649
+ requires pre-calculated scaling factor.
650
+
651
+ Returns:
652
+ `torch.Tensor`: Symmetric-quantized value of *input*.
653
+ """
654
+ zero_point = torch.tensor(0.0).to(scale.device)
655
+
656
+ n = 2 ** (k - 1) - 1
657
+ new_quant_x = linear_quantize(x, scale, zero_point, inplace=False)
658
+ new_quant_x = torch.clamp(new_quant_x, -n, n - 1)
659
+
660
+ ctx.scale = scale
661
+ return new_quant_x
662
+
663
+ @staticmethod
664
+ def backward(ctx, grad_output):
665
+ scale = ctx.scale
666
+ if len(grad_output.shape) == 4:
667
+ scale = scale.view(-1, 1, 1, 1)
668
+ # reshape scale and zeropoint for linear weights
669
+ elif len(grad_output.shape) == 2:
670
+ scale = scale.view(-1, 1)
671
+ else:
672
+ scale = scale.view(-1)
673
+
674
+ return grad_output.clone() / scale, None, None, None, None
675
+
676
+
677
+ class floor_ste(Function):
678
+ """
679
+ Straight-through Estimator(STE) for torch.floor()
680
+ """
681
+
682
+ @staticmethod
683
+ def forward(ctx, x):
684
+ return torch.floor(x)
685
+
686
+ @staticmethod
687
+ def backward(ctx, grad_output):
688
+ return grad_output.clone()
689
+
690
+
691
+ class round_ste(Function):
692
+ """
693
+ Straight-through Estimator(STE) for torch.round()
694
+ """
695
+
696
+ @staticmethod
697
+ def forward(ctx, x):
698
+ return torch.round(x)
699
+
700
+ @staticmethod
701
+ def backward(ctx, grad_output):
702
+ return grad_output.clone()
703
+
704
+
705
+ def batch_frexp(inputs, max_bit=31):
706
+ """
707
+ Decompose the scaling factor into mantissa and twos exponent.
708
+
709
+ Args:
710
+ scaling_factor (`torch.Tensor`):
711
+ Target scaling factor to decompose.
712
+
713
+ Returns:
714
+ ``Tuple(torch.Tensor, torch.Tensor)`: mantisa and exponent
715
+ """
716
+
717
+ shape_of_input = inputs.size()
718
+
719
+ # trans the input to be a 1-d tensor
720
+ inputs = inputs.view(-1)
721
+
722
+ output_m, output_e = np.frexp(inputs.cpu().numpy())
723
+ tmp_m = []
724
+ for m in output_m:
725
+ int_m_shifted = int(
726
+ decimal.Decimal(m * (2**max_bit)).quantize(decimal.Decimal("1"), rounding=decimal.ROUND_HALF_UP)
727
+ )
728
+ tmp_m.append(int_m_shifted)
729
+ output_m = np.array(tmp_m)
730
+
731
+ output_e = float(max_bit) - output_e
732
+
733
+ return (
734
+ torch.from_numpy(output_m).to(inputs.device).view(shape_of_input),
735
+ torch.from_numpy(output_e).to(inputs.device).view(shape_of_input),
736
+ )
737
+
738
+
739
+ class FixedPointMul(Function):
740
+ """
741
+ Function to perform fixed-point arithmetic that can match integer arithmetic on hardware.
742
+
743
+ Args:
744
+ pre_act (`torch.Tensor`):
745
+ Input tensor.
746
+ pre_act_scaling_factor (`torch.Tensor`):
747
+ Scaling factor of the input tensor *pre_act*.
748
+ bit_num (`int`):
749
+ Quantization bitwidth.
750
+ z_scaling_factor (`torch.Tensor`):
751
+ Scaling factor of the output tensor.
752
+ identity (`torch.Tensor`, *optional*):
753
+ Identity tensor, if exists.
754
+ identity_scaling_factor (`torch.Tensor`, *optional*):
755
+ Scaling factor of the identity tensor *identity*, if exists.
756
+
757
+ Returns:
758
+ `torch.Tensor`: Output tensor(*pre_act* if *identity* is not given, otherwise the addition of *pre_act* and
759
+ *identity*), whose scale is rescaled to *z_scaling_factor*.
760
+ """
761
+
762
+ @staticmethod
763
+ def forward(
764
+ ctx,
765
+ pre_act,
766
+ pre_act_scaling_factor,
767
+ bit_num,
768
+ z_scaling_factor,
769
+ identity=None,
770
+ identity_scaling_factor=None,
771
+ ):
772
+ if len(pre_act_scaling_factor.shape) == 3:
773
+ reshape = lambda x: x # noqa: E731
774
+ else:
775
+ reshape = lambda x: x.view(1, 1, -1) # noqa: E731
776
+ ctx.identity = identity
777
+
778
+ n = 2 ** (bit_num - 1) - 1
779
+
780
+ with torch.no_grad():
781
+ pre_act_scaling_factor = reshape(pre_act_scaling_factor)
782
+ if identity is not None:
783
+ identity_scaling_factor = reshape(identity_scaling_factor)
784
+
785
+ ctx.z_scaling_factor = z_scaling_factor
786
+
787
+ z_int = torch.round(pre_act / pre_act_scaling_factor)
788
+ _A = pre_act_scaling_factor.type(torch.double)
789
+ _B = (z_scaling_factor.type(torch.float)).type(torch.double)
790
+ new_scale = _A / _B
791
+ new_scale = reshape(new_scale)
792
+
793
+ m, e = batch_frexp(new_scale)
794
+
795
+ output = z_int.type(torch.double) * m.type(torch.double)
796
+ output = torch.round(output / (2.0**e))
797
+
798
+ if identity is not None:
799
+ # needs addition of identity activation
800
+ wx_int = torch.round(identity / identity_scaling_factor)
801
+
802
+ _A = identity_scaling_factor.type(torch.double)
803
+ _B = (z_scaling_factor.type(torch.float)).type(torch.double)
804
+ new_scale = _A / _B
805
+ new_scale = reshape(new_scale)
806
+
807
+ m1, e1 = batch_frexp(new_scale)
808
+ output1 = wx_int.type(torch.double) * m1.type(torch.double)
809
+ output1 = torch.round(output1 / (2.0**e1))
810
+
811
+ output = output1 + output
812
+
813
+ return torch.clamp(output.type(torch.float), -n - 1, n)
814
+
815
+ @staticmethod
816
+ def backward(ctx, grad_output):
817
+ identity_grad = None
818
+ if ctx.identity is not None:
819
+ identity_grad = grad_output.clone() / ctx.z_scaling_factor
820
+ return grad_output.clone() / ctx.z_scaling_factor, None, None, None, None, identity_grad, None
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (650 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/configuration_llava_next_video.cpython-310.pyc ADDED
Binary file (5.75 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/image_processing_llava_next_video.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/modeling_llava_next_video.cpython-310.pyc ADDED
Binary file (34.9 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/modular_llava_next_video.cpython-310.pyc ADDED
Binary file (21.6 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/__pycache__/processing_llava_next_video.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/configuration_llava_next_video.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/llava_next_video/modular_llava_next_video.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_llava_next_video.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+
23
+ from ...configuration_utils import PretrainedConfig
24
+ from ..auto import CONFIG_MAPPING, AutoConfig
25
+
26
+
27
+ class LlavaNextVideoConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`LlavaNextVideoForConditionalGeneration`]. It is used to instantiate an
30
+ Llava-NeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the [llava-hf/LLaVA-NeXT-Video-7B-hf](https://huggingface.co/llava-hf/LLaVA-NeXT-Video-7B-hf)
32
+ model.
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
38
+ The config object or dictionary of the vision backbone.
39
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
40
+ The config object or dictionary of the text backbone.
41
+ image_token_index (`int`, *optional*, defaults to 32001):
42
+ The image token index to encode the image prompt.
43
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
44
+ The activation function used by the multimodal projector.
45
+ multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
46
+ Whether to use bias in the multimodal projector.
47
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
48
+ The feature selection strategy used to select the vision feature from the vision backbone.
49
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
50
+ If `"full"`, the full vision features are used.
51
+ vision_feature_layer (`Union[int, List[int]]`, *optional*, defaults to -2):
52
+ The index of the layer to select the vision feature. If multiple indices are provided,
53
+ the vision feature of the corresponding indices will be concatenated to form the
54
+ vision features.
55
+ image_grid_pinpoints (`List`, *optional*, defaults to `[[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]`):
56
+ A list of possible resolutions to use for processing high resolution images. Each item in the list should be a tuple or list
57
+ of the form `(height, width)`.
58
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
59
+ Whether the model's input and output word embeddings should be tied.
60
+ video_token_index (`int`, *optional*, defaults to 32000):
61
+ The video token index to encode the image prompt.
62
+ spatial_pool_mode (`str`, *optional*, defaults to `"average"`):
63
+ Pooling mode to use for videos. Can be "average", "max" or "conv".
64
+ spatial_pool_stride (`int`, *optional*, defaults to 2):
65
+ Stride used in the pooling layer for videos.
66
+ image_seq_length (`int`, *optional*, defaults to 576):
67
+ Sequence length of one image embedding.
68
+ video_seq_length (`int`, *optional*, defaults to 288):
69
+ Sequence length of one video embedding.
70
+
71
+ Example:
72
+
73
+ ```python
74
+ >>> from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoConfig, CLIPVisionConfig, LlamaConfig
75
+
76
+ >>> # Initializing a CLIP-vision config
77
+ >>> vision_config = CLIPVisionConfig()
78
+
79
+ >>> # Initializing a Llama config
80
+ >>> text_config = LlamaConfig()
81
+
82
+ >>> configuration = LlavaNextVideoConfig(vision_config, text_config)
83
+
84
+ >>> model = LlavaNextVideoForConditionalGeneration(configuration)
85
+
86
+ >>> # Accessing the model configuration
87
+ >>> configuration = model.config
88
+ ```"""
89
+
90
+ model_type = "llava_next_video"
91
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
92
+
93
+ def __init__(
94
+ self,
95
+ vision_config=None,
96
+ text_config=None,
97
+ image_token_index=32001,
98
+ projector_hidden_act="gelu",
99
+ multimodal_projector_bias=True,
100
+ vision_feature_select_strategy="default",
101
+ vision_feature_layer=-2,
102
+ image_grid_pinpoints=None,
103
+ tie_word_embeddings=False,
104
+ video_token_index=32000,
105
+ spatial_pool_mode="average",
106
+ spatial_pool_stride=2,
107
+ image_seq_length=576,
108
+ video_seq_length=288,
109
+ **kwargs,
110
+ ):
111
+ self.video_token_index = video_token_index
112
+ self.spatial_pool_mode = spatial_pool_mode
113
+ self.spatial_pool_stride = spatial_pool_stride
114
+ self.image_seq_length = image_seq_length
115
+ self.video_seq_length = video_seq_length
116
+ self.image_token_index = image_token_index
117
+ self.projector_hidden_act = projector_hidden_act
118
+ self.multimodal_projector_bias = multimodal_projector_bias
119
+
120
+ if vision_feature_select_strategy not in ["default", "full"]:
121
+ raise ValueError(
122
+ "vision_feature_select_strategy should be one of 'default', 'full'."
123
+ f"Got: {vision_feature_select_strategy}"
124
+ )
125
+
126
+ self.vision_feature_select_strategy = vision_feature_select_strategy
127
+ self.vision_feature_layer = vision_feature_layer
128
+ image_grid_pinpoints = (
129
+ image_grid_pinpoints
130
+ if image_grid_pinpoints is not None
131
+ else [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
132
+ )
133
+ self.image_grid_pinpoints = image_grid_pinpoints
134
+
135
+ if isinstance(vision_config, dict):
136
+ vision_config["model_type"] = (
137
+ vision_config["model_type"] if "model_type" in vision_config else "clip_vision_model"
138
+ )
139
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
140
+ elif vision_config is None:
141
+ vision_config = CONFIG_MAPPING["clip_vision_model"](
142
+ intermediate_size=4096,
143
+ hidden_size=1024,
144
+ patch_size=14,
145
+ image_size=336,
146
+ num_hidden_layers=24,
147
+ num_attention_heads=16,
148
+ vocab_size=32000,
149
+ projection_dim=768,
150
+ )
151
+
152
+ self.vision_config = vision_config
153
+
154
+ if isinstance(text_config, dict):
155
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "llama"
156
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
157
+ elif text_config is None:
158
+ text_config = CONFIG_MAPPING["llama"]()
159
+
160
+ self.text_config = text_config
161
+
162
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
163
+
164
+
165
+ __all__ = ["LlavaNextVideoConfig"]
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/image_processing_llava_next_video.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ """Image processor class for LLaVa-NeXT-Video."""
16
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ convert_to_rgb,
24
+ get_resize_output_image_size,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from ...image_utils import (
29
+ OPENAI_CLIP_MEAN,
30
+ OPENAI_CLIP_STD,
31
+ ChannelDimension,
32
+ ImageInput,
33
+ PILImageResampling,
34
+ VideoInput,
35
+ infer_channel_dimension_format,
36
+ is_scaled_image,
37
+ make_batched_videos,
38
+ make_list_of_images,
39
+ to_numpy_array,
40
+ validate_preprocess_arguments,
41
+ )
42
+ from ...utils import TensorType, logging
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ class LlavaNextVideoImageProcessor(BaseImageProcessor):
49
+ r"""
50
+ Constructs a LLaVa-NeXT-Video video processor. Based on [`CLIPImageProcessor`] with incorporation of processing each video frame.
51
+
52
+ Args:
53
+ do_resize (`bool`, *optional*, defaults to `True`):
54
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
55
+ `do_resize` in the `preprocess` method.
56
+ size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
57
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
58
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
59
+ method.
60
+ image_grid_pinpoints (`List` *optional*, defaults to `[[672, 336], [336, 672], [672, 672], [336, 1008], [1008, 336]]`):
61
+ A list of possible resolutions to use for processing high resolution images. The best resolution is selected
62
+ based on the original size of the image. Can be overridden by `image_grid_pinpoints` in the `preprocess`
63
+ method. Not used for processinf videos.
64
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
65
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
66
+ do_center_crop (`bool`, *optional*, defaults to `True`):
67
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
68
+ `preprocess` method.
69
+ crop_size (`Dict[str, int]` *optional*, defaults to 224):
70
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
71
+ method.
72
+ do_rescale (`bool`, *optional*, defaults to `True`):
73
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
74
+ the `preprocess` method.
75
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
76
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
77
+ method.
78
+ do_normalize (`bool`, *optional*, defaults to `True`):
79
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
80
+ image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
81
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
82
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
83
+ image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
84
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
85
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
86
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
87
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
88
+ Whether to convert the image to RGB.
89
+ """
90
+
91
+ model_input_names = ["pixel_values_videos"]
92
+
93
+ def __init__(
94
+ self,
95
+ do_resize: bool = True,
96
+ size: Dict[str, int] = None,
97
+ image_grid_pinpoints: List = None,
98
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
99
+ do_center_crop: bool = True,
100
+ crop_size: Dict[str, int] = None,
101
+ do_rescale: bool = True,
102
+ rescale_factor: Union[int, float] = 1 / 255,
103
+ do_normalize: bool = True,
104
+ image_mean: Optional[Union[float, List[float]]] = None,
105
+ image_std: Optional[Union[float, List[float]]] = None,
106
+ do_convert_rgb: bool = True,
107
+ **kwargs,
108
+ ) -> None:
109
+ super().__init__(**kwargs)
110
+ size = size if size is not None else {"shortest_edge": 224}
111
+ size = get_size_dict(size, default_to_square=False)
112
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
113
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
114
+
115
+ self.do_resize = do_resize
116
+ self.size = size
117
+ self.image_grid_pinpoints = image_grid_pinpoints
118
+ self.resample = resample
119
+ self.do_center_crop = do_center_crop
120
+ self.crop_size = crop_size
121
+ self.do_rescale = do_rescale
122
+ self.rescale_factor = rescale_factor
123
+ self.do_normalize = do_normalize
124
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
125
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
126
+ self.do_convert_rgb = do_convert_rgb
127
+
128
+ # Copied from transformers.models.clip.image_processing_clip.CLIPImageProcessor.resize with CLIP->LLaVa
129
+ def resize(
130
+ self,
131
+ image: np.ndarray,
132
+ size: Dict[str, int],
133
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
134
+ data_format: Optional[Union[str, ChannelDimension]] = None,
135
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
136
+ **kwargs,
137
+ ) -> np.ndarray:
138
+ """
139
+ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
140
+ resized to keep the input aspect ratio.
141
+
142
+ Args:
143
+ image (`np.ndarray`):
144
+ Image to resize.
145
+ size (`Dict[str, int]`):
146
+ Size of the output image.
147
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
148
+ Resampling filter to use when resiizing the image.
149
+ data_format (`str` or `ChannelDimension`, *optional*):
150
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
151
+ input_data_format (`ChannelDimension` or `str`, *optional*):
152
+ The channel dimension format of the input image. If not provided, it will be inferred.
153
+ """
154
+ default_to_square = True
155
+ if "shortest_edge" in size:
156
+ size = size["shortest_edge"]
157
+ default_to_square = False
158
+ elif "height" in size and "width" in size:
159
+ size = (size["height"], size["width"])
160
+ else:
161
+ raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
162
+
163
+ output_size = get_resize_output_image_size(
164
+ image,
165
+ size=size,
166
+ default_to_square=default_to_square,
167
+ input_data_format=input_data_format,
168
+ )
169
+
170
+ return resize(
171
+ image,
172
+ size=output_size,
173
+ resample=resample,
174
+ data_format=data_format,
175
+ input_data_format=input_data_format,
176
+ **kwargs,
177
+ )
178
+
179
+ def _preprocess(
180
+ self,
181
+ images: ImageInput,
182
+ do_resize: bool = None,
183
+ size: Dict[str, int] = None,
184
+ resample: PILImageResampling = None,
185
+ do_center_crop: bool = None,
186
+ crop_size: int = None,
187
+ do_rescale: bool = None,
188
+ rescale_factor: float = None,
189
+ do_normalize: bool = None,
190
+ image_mean: Optional[Union[float, List[float]]] = None,
191
+ image_std: Optional[Union[float, List[float]]] = None,
192
+ do_convert_rgb: bool = None,
193
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
194
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
195
+ ) -> list[np.ndarray]:
196
+ """
197
+ Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
198
+
199
+ Args:
200
+ images (`ImageInput`):
201
+ Batch of frames (one video) to preprocess. Expects a batch of frames with pixel values ranging from 0 to 255. If
202
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
203
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
204
+ Whether to resize the image.
205
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
206
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
207
+ the longest edge resized to keep the input aspect ratio.
208
+ resample (`int`, *optional*, defaults to `self.resample`):
209
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
210
+ has an effect if `do_resize` is set to `True`.
211
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
212
+ Whether to center crop the image.
213
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
214
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
215
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
216
+ Whether to rescale the image.
217
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
218
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
219
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
220
+ Whether to normalize the image.
221
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
222
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
223
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
224
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
225
+ `True`.
226
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
227
+ The channel dimension format for the output image. Can be one of:
228
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
229
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
230
+ - Unset: Use the channel dimension format of the input image.
231
+ input_data_format (`ChannelDimension` or `str`, *optional*):
232
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
233
+ from the input image. Can be one of:
234
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
235
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
236
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
237
+ """
238
+ images = make_list_of_images(images)
239
+
240
+ if do_convert_rgb:
241
+ images = [convert_to_rgb(image) for image in images]
242
+
243
+ # All transformations expect numpy arrays.
244
+ images = [to_numpy_array(image) for image in images]
245
+
246
+ if do_rescale and is_scaled_image(images[0]):
247
+ logger.warning_once(
248
+ "It looks like you are trying to rescale already rescaled images. If the input"
249
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
250
+ )
251
+ if input_data_format is None:
252
+ # We assume that all images have the same channel dimension format.
253
+ input_data_format = infer_channel_dimension_format(images[0])
254
+
255
+ all_images = []
256
+ for image in images:
257
+ if do_resize:
258
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
259
+
260
+ if do_center_crop:
261
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
262
+
263
+ if do_rescale:
264
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
265
+
266
+ if do_normalize:
267
+ image = self.normalize(
268
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
269
+ )
270
+
271
+ all_images.append(image)
272
+ images = [
273
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
274
+ for image in all_images
275
+ ]
276
+
277
+ return images
278
+
279
+ def preprocess(
280
+ self,
281
+ images: VideoInput,
282
+ do_resize: bool = None,
283
+ size: Dict[str, int] = None,
284
+ resample: PILImageResampling = None,
285
+ do_center_crop: bool = None,
286
+ crop_size: int = None,
287
+ do_rescale: bool = None,
288
+ rescale_factor: float = None,
289
+ do_normalize: bool = None,
290
+ image_mean: Optional[Union[float, List[float]]] = None,
291
+ image_std: Optional[Union[float, List[float]]] = None,
292
+ do_convert_rgb: bool = None,
293
+ return_tensors: Optional[Union[str, TensorType]] = None,
294
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
295
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
296
+ ):
297
+ """
298
+ Args:
299
+ images (`VideoInput`):
300
+ Videos to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
301
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
302
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
303
+ Whether to resize the video.
304
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
305
+ Size of the video after resizing. Shortest edge of the video is resized to size["shortest_edge"], with
306
+ the longest edge resized to keep the input aspect ratio.
307
+ resample (`int`, *optional*, defaults to `self.resample`):
308
+ Resampling filter to use if resizing the video. This can be one of the enum `PILImageResampling`. Only
309
+ has an effect if `do_resize` is set to `True`.
310
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
311
+ Whether to center crop the video.
312
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
313
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
314
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
315
+ Whether to rescale the video.
316
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
317
+ Rescale factor to rescale the video by if `do_rescale` is set to `True`.
318
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
319
+ Whether to normalize the video.
320
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
321
+ Frame mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
322
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
323
+ Frame standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
324
+ `True`.
325
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
326
+ Whether to convert the video to RGB.
327
+ return_tensors (`str` or `TensorType`, *optional*):
328
+ The type of tensors to return. Can be one of:
329
+ - Unset: Return a list of `np.ndarray`.
330
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
331
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
332
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
333
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
334
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
335
+ The channel dimension format for the output image. Can be one of:
336
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
337
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
338
+ - Unset: Use the channel dimension format of the input image.
339
+ input_data_format (`ChannelDimension` or `str`, *optional*):
340
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
341
+ from the input image. Can be one of:
342
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
343
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
344
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
345
+ """
346
+ do_resize = do_resize if do_resize is not None else self.do_resize
347
+ size = size if size is not None else self.size
348
+ size = get_size_dict(size, param_name="size", default_to_square=False)
349
+ resample = resample if resample is not None else self.resample
350
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
351
+ crop_size = crop_size if crop_size is not None else self.crop_size
352
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
353
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
354
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
355
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
356
+ image_mean = image_mean if image_mean is not None else self.image_mean
357
+ image_std = image_std if image_std is not None else self.image_std
358
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
359
+
360
+ images = make_batched_videos(images)
361
+
362
+ validate_preprocess_arguments(
363
+ do_rescale=do_rescale,
364
+ rescale_factor=rescale_factor,
365
+ do_normalize=do_normalize,
366
+ image_mean=image_mean,
367
+ image_std=image_std,
368
+ do_center_crop=do_center_crop,
369
+ crop_size=crop_size,
370
+ do_resize=do_resize,
371
+ size=size,
372
+ resample=resample,
373
+ )
374
+
375
+ # preprocess each video frame by frame
376
+ pixel_values = [
377
+ self._preprocess(
378
+ frames,
379
+ do_resize=do_resize,
380
+ size=size,
381
+ resample=resample,
382
+ do_center_crop=do_center_crop,
383
+ crop_size=crop_size,
384
+ do_rescale=do_rescale,
385
+ rescale_factor=rescale_factor,
386
+ do_normalize=do_normalize,
387
+ image_mean=image_mean,
388
+ image_std=image_std,
389
+ data_format=data_format,
390
+ input_data_format=input_data_format,
391
+ )
392
+ for frames in images
393
+ ]
394
+
395
+ data = {"pixel_values_videos": pixel_values}
396
+ return BatchFeature(data=data, tensor_type=return_tensors)
397
+
398
+
399
+ __all__ = ["LlavaNextVideoImageProcessor"]
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/modeling_llava_next_video.py ADDED
@@ -0,0 +1,881 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/llava_next_video/modular_llava_next_video.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_llava_next_video.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import math
23
+ from dataclasses import dataclass
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import numpy as np
27
+ import torch
28
+ from torch import nn
29
+
30
+ from ...activations import ACT2FN
31
+ from ...generation import GenerationMixin
32
+ from ...image_processing_utils import select_best_resolution
33
+ from ...modeling_outputs import ModelOutput
34
+ from ...modeling_utils import PreTrainedModel
35
+ from ...utils import (
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ is_torchdynamo_compiling,
39
+ logging,
40
+ replace_return_docstrings,
41
+ )
42
+ from ...utils.deprecation import deprecate_kwarg
43
+ from ..auto import AutoModel, AutoModelForCausalLM
44
+ from .configuration_llava_next_video import LlavaNextVideoConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CONFIG_FOR_DOC = "LlavaNextVideoConfig"
50
+
51
+
52
+ @dataclass
53
+ class LlavaNextVideoCausalLMOutputWithPast(ModelOutput):
54
+ """
55
+ Base class for LlavaNextVideo causal language model (or autoregressive) outputs.
56
+
57
+ Args:
58
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
59
+ Language modeling loss (for next-token prediction).
60
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
61
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
62
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
63
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
64
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
65
+
66
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
67
+ `past_key_values` input) to speed up sequential decoding.
68
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
69
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
70
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
71
+
72
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
73
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
74
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
75
+ sequence_length)`.
76
+
77
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
78
+ heads.
79
+ image_hidden_states (`torch.FloatTensor`, *optional*):
80
+ A `torch.FloatTensor` of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`.
81
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
82
+
83
+ video_hidden_states (`torch.FloatTensor`, *optional*):
84
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
85
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
86
+ """
87
+
88
+ loss: Optional[torch.FloatTensor] = None
89
+ logits: torch.FloatTensor = None
90
+ past_key_values: Optional[List[torch.FloatTensor]] = None
91
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
92
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
93
+ image_hidden_states: Optional[torch.FloatTensor] = None
94
+
95
+ video_hidden_states: Optional[torch.FloatTensor] = None
96
+
97
+
98
+ class LlavaNextVideoPooler(nn.Module):
99
+ def __init__(self, config):
100
+ super().__init__()
101
+
102
+ mode = config.spatial_pool_mode
103
+ stride = config.spatial_pool_stride
104
+ out_channels = getattr(config, "spatial_pool_out_channels", config.vision_config.hidden_size)
105
+ self.image_size = (config.vision_config.image_size // config.vision_config.patch_size) ** 2
106
+
107
+ if mode == "average":
108
+ self.pool = nn.AvgPool2d(kernel_size=stride, stride=stride)
109
+ elif mode == "max":
110
+ self.pool = nn.MaxPool2d(kernel_size=stride, stride=stride)
111
+ elif mode == "conv":
112
+ self.pool = nn.Conv2d(
113
+ in_channels=config.vision_config.hidden_size,
114
+ out_channels=out_channels,
115
+ kernel_size=stride,
116
+ stride=stride,
117
+ )
118
+ else:
119
+ raise ValueError(f"Unknown pooling mode: {mode}. Has to be one of [`average`, `max`, `conv`]")
120
+
121
+ def forward(self, image_features):
122
+ ori_width = int(math.sqrt(image_features.shape[1] * self.image_size // self.image_size))
123
+ ori_height = int(ori_width * self.image_size // self.image_size)
124
+
125
+ batch_size, _, dim = image_features.shape
126
+ image_features_spatial = image_features.view(batch_size, ori_height, ori_height, dim).permute(0, 3, 1, 2)
127
+ image_features_spatial_pool = self.pool(image_features_spatial)
128
+
129
+ return image_features_spatial_pool.flatten(2).transpose(1, 2).contiguous()
130
+
131
+
132
+ LLAVA_NEXT_VIDEO_START_DOCSTRING = r"""
133
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
134
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
135
+ etc.)
136
+
137
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
138
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
139
+ and behavior.
140
+
141
+ Parameters:
142
+ config ([`LlavaNextVideoConfig`] or [`LlavaNextVideoVisionConfig`]):
143
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
144
+ load the weights associated with the model, only the configuration. Check out the
145
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
146
+ """
147
+
148
+
149
+ @add_start_docstrings(
150
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
151
+ LLAVA_NEXT_VIDEO_START_DOCSTRING,
152
+ )
153
+ class LlavaNextVideoPreTrainedModel(PreTrainedModel):
154
+ config_class = LlavaNextVideoConfig
155
+ base_model_prefix = "model"
156
+ supports_gradient_checkpointing = True
157
+ _no_split_modules = ["LlavaNextVideoVisionAttention"]
158
+ _skip_keys_device_placement = "past_key_values"
159
+ _supports_cache_class = True
160
+ _supports_flash_attn_2 = True
161
+ _supports_sdpa = True
162
+ _supports_quantized_cache = True
163
+ _supports_static_cache = True
164
+
165
+ def _init_weights(self, module):
166
+ # important: this ported version of LlavaNextVideo isn't meant for training from scratch - only
167
+ # inference and fine-tuning - so the proper init weights code has been removed - the original codebase
168
+ # https://github.com/haotian-liu/LLaVA/tree/main/llava_next_video should serve for that purpose
169
+ std = (
170
+ self.config.initializer_range
171
+ if hasattr(self.config, "initializer_range")
172
+ else self.config.text_config.initializer_range
173
+ )
174
+
175
+ if hasattr(module, "class_embedding"):
176
+ module.class_embedding.data.normal_(mean=0.0, std=std)
177
+
178
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
179
+ module.weight.data.normal_(mean=0.0, std=std)
180
+ if module.bias is not None:
181
+ module.bias.data.zero_()
182
+ elif isinstance(module, nn.Embedding):
183
+ module.weight.data.normal_(mean=0.0, std=std)
184
+ if module.padding_idx is not None:
185
+ module.weight.data[module.padding_idx].zero_()
186
+
187
+
188
+ class LlavaNextVideoMultiModalProjector(nn.Module):
189
+ def __init__(self, config: LlavaNextVideoConfig):
190
+ super().__init__()
191
+ # We have hidden_size * the number of vision feature layers
192
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
193
+ self.linear_1 = nn.Linear(
194
+ config.vision_config.hidden_size * num_feature_layers,
195
+ config.text_config.hidden_size,
196
+ bias=config.multimodal_projector_bias,
197
+ )
198
+ self.act = ACT2FN[config.projector_hidden_act]
199
+ self.linear_2 = nn.Linear(
200
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
201
+ )
202
+
203
+ def forward(self, image_features):
204
+ hidden_states = self.linear_1(image_features)
205
+ hidden_states = self.act(hidden_states)
206
+ hidden_states = self.linear_2(hidden_states)
207
+ return hidden_states
208
+
209
+
210
+ def get_anyres_image_grid_shape(image_size, grid_pinpoints, patch_size):
211
+ """
212
+ Calculate the shape of the image patch grid after the preprocessing for images of any resolution.
213
+
214
+ Args:
215
+ image_size (`tuple`):
216
+ The size of the input image in the format (width, height).
217
+ grid_pinpoints (`List`):
218
+ A list containing possible resolutions. Each item in the list should be a tuple or list
219
+ of the form `(height, width)`.
220
+ patch_size (`int`):
221
+ The size of each image patch.
222
+
223
+ Returns:
224
+ tuple: The shape of the image patch grid in the format (width, height).
225
+ """
226
+ if not isinstance(grid_pinpoints, list):
227
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
228
+
229
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
230
+ if not isinstance(image_size, (list, tuple)):
231
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
232
+ raise TypeError(
233
+ f"image_size invalid type: {type(image_size)} not valid, should be either list, tuple, np.ndarray or tensor"
234
+ )
235
+ image_size = image_size.tolist()
236
+
237
+ height, width = select_best_resolution(image_size, grid_pinpoints)
238
+ return height // patch_size, width // patch_size
239
+
240
+
241
+ def image_size_to_num_patches(image_size, grid_pinpoints, patch_size: int):
242
+ """
243
+ Calculate the number of patches after the preprocessing for images of any resolution.
244
+
245
+ Args:
246
+ image_size (`torch.LongTensor` or `np.ndarray` or `Tuple[int, int]`):
247
+ The size of the input image in the format (height, width). ?
248
+ grid_pinpoints (`List`):
249
+ A list containing possible resolutions. Each item in the list should be a tuple or list
250
+ of the form `(height, width)`.
251
+ patch_size (`int`):
252
+ The size of each image patch.
253
+
254
+ Returns:
255
+ int: the number of patches
256
+ """
257
+ if not isinstance(grid_pinpoints, list):
258
+ raise TypeError("grid_pinpoints should be a list of tuples or lists")
259
+
260
+ # ! VERY IMPORTANT if image_size is tensor, must convert to into tuple, otherwise it will cause wrong calculate
261
+ if not isinstance(image_size, (list, tuple)):
262
+ if not isinstance(image_size, (torch.Tensor, np.ndarray)):
263
+ raise TypeError(f"image_size invalid type {type(image_size)} with value {image_size}")
264
+ image_size = image_size.tolist()
265
+
266
+ best_resolution = select_best_resolution(image_size, grid_pinpoints)
267
+ height, width = best_resolution
268
+ num_patches = 0
269
+ # consider change to ceil(height/patch_size)*ceil(width/patch_size) + 1
270
+ for i in range(0, height, patch_size):
271
+ for j in range(0, width, patch_size):
272
+ num_patches += 1
273
+ # add the base patch
274
+ num_patches += 1
275
+ return num_patches
276
+
277
+
278
+ def unpad_image(tensor, original_size):
279
+ """
280
+ Unpads a PyTorch tensor of a padded and resized image.
281
+
282
+ Args:
283
+ tensor (`torch.Tensor`):
284
+ The image tensor, assumed to be of shape (num_channels, height, width).
285
+ original_size (`tuple`):
286
+ The original size of the image (height, width).
287
+
288
+ Returns:
289
+ `torch.Tensor`: The unpadded image tensor.
290
+ """
291
+ if not isinstance(original_size, (list, tuple)):
292
+ if not isinstance(original_size, (torch.Tensor, np.ndarray)):
293
+ raise TypeError(
294
+ f"image_size invalid type: {type(original_size)} not valid, should be either list, tuple, np.ndarray or tensor"
295
+ )
296
+ original_size = original_size.tolist()
297
+ original_height, original_width = original_size
298
+ current_height, current_width = tensor.shape[1:]
299
+
300
+ original_aspect_ratio = original_width / original_height
301
+ current_aspect_ratio = current_width / current_height
302
+
303
+ if original_aspect_ratio > current_aspect_ratio:
304
+ scale_factor = current_width / original_width
305
+ new_height = int(round(original_height * scale_factor, 7))
306
+ padding = (current_height - new_height) // 2
307
+ unpadded_tensor = tensor[:, padding : current_height - padding, :]
308
+ else:
309
+ scale_factor = current_height / original_height
310
+ new_width = int(round(original_width * scale_factor, 7))
311
+ padding = (current_width - new_width) // 2
312
+ unpadded_tensor = tensor[:, :, padding : current_width - padding]
313
+
314
+ return unpadded_tensor
315
+
316
+
317
+ LLAVA_NEXT_VIDEO_INPUTS_DOCSTRING = r"""
318
+ Args:
319
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
320
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
321
+ it.
322
+
323
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
324
+ [`PreTrainedTokenizer.__call__`] for details.
325
+
326
+ [What are input IDs?](../glossary#input-ids)
327
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
328
+ The tensors corresponding to the input images. Pixel values can be obtained using
329
+ [`AutoImageProcessor`]. See [`LlavaNextVideoImageProcessor.__call__`] for details. [`LlavaProcessor`] uses
330
+ [`LlavaNextVideoImageProcessor`] for processing images.
331
+ image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`, *optional*):
332
+ The sizes of the images in the batch, being (height, width) for each image.
333
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
334
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
335
+
336
+ - 1 for tokens that are **not masked**,
337
+ - 0 for tokens that are **masked**.
338
+
339
+ [What are attention masks?](../glossary#attention-mask)
340
+
341
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
342
+ [`PreTrainedTokenizer.__call__`] for details.
343
+
344
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
345
+ `past_key_values`).
346
+
347
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
348
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
349
+ information on the default strategy.
350
+
351
+ - 1 indicates the head is **not masked**,
352
+ - 0 indicates the head is **masked**.
353
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
354
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
355
+ config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
356
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
357
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
358
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
359
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
360
+
361
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
362
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
363
+
364
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
365
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
366
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
367
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
368
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
369
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
370
+ model's internal embedding lookup matrix.
371
+ vision_feature_layer (`Union[int, List[int]], *optional*, defaults to -2`):
372
+ The index of the layer to select the vision feature. If multiple indices are provided,
373
+ the vision feature of the corresponding indices will be concatenated to form the
374
+ vision features.
375
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
376
+ The feature selection strategy used to select the vision feature from the vision backbone.
377
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
378
+ If `"full"`, the full vision features are used.
379
+ use_cache (`bool`, *optional*):
380
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
381
+ `past_key_values`).
382
+ output_attentions (`bool`, *optional*):
383
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
384
+ tensors for more detail.
385
+ output_hidden_states (`bool`, *optional*):
386
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
387
+ more detail.
388
+ return_dict (`bool`, *optional*):
389
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
390
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
391
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
392
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
393
+ the complete sequence length.
394
+ """
395
+
396
+
397
+ @add_start_docstrings(
398
+ """The LLAVA-NeXT model which consists of a vision backbone and a language model.""",
399
+ LLAVA_NEXT_VIDEO_START_DOCSTRING,
400
+ )
401
+ class LlavaNextVideoForConditionalGeneration(LlavaNextVideoPreTrainedModel, GenerationMixin):
402
+ def __init__(
403
+ self,
404
+ config: LlavaNextVideoConfig,
405
+ ):
406
+ super().__init__(config)
407
+ self.vision_tower = AutoModel.from_config(config.vision_config)
408
+
409
+ self.multi_modal_projector = LlavaNextVideoMultiModalProjector(config)
410
+ embed_std = 1 / math.sqrt(config.text_config.hidden_size)
411
+ self.image_newline = nn.Parameter(torch.randn(config.text_config.hidden_size, dtype=self.dtype) * embed_std)
412
+
413
+ self.vocab_size = config.text_config.vocab_size
414
+ self.language_model = AutoModelForCausalLM.from_config(config.text_config)
415
+ if self.language_model._tied_weights_keys is not None:
416
+ self._tied_weights_keys = [f"language_model.{k}" for k in self.language_model._tied_weights_keys]
417
+
418
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
419
+ self._padding_side = "left" # set it to left by default, user can use setter to change padding_sides
420
+ self.vision_resampler = LlavaNextVideoPooler(config)
421
+ self.post_init()
422
+
423
+ @property
424
+ def padding_side(self):
425
+ return self._padding_side
426
+
427
+ @padding_side.setter
428
+ def padding_side(self, padding_side: str):
429
+ if padding_side not in ["left", "right"]:
430
+ raise ValueError(f"{padding_side} is not `left` or `right`.")
431
+ self._padding_side = padding_side
432
+
433
+ def get_input_embeddings(self):
434
+ return self.language_model.get_input_embeddings()
435
+
436
+ def set_input_embeddings(self, value):
437
+ self.language_model.set_input_embeddings(value)
438
+
439
+ def get_output_embeddings(self):
440
+ return self.language_model.get_output_embeddings()
441
+
442
+ def set_output_embeddings(self, new_embeddings):
443
+ self.language_model.set_output_embeddings(new_embeddings)
444
+
445
+ def set_decoder(self, decoder):
446
+ self.language_model.set_decoder(decoder)
447
+
448
+ def get_decoder(self):
449
+ return self.language_model.get_decoder()
450
+
451
+ def pack_image_features(self, image_features, image_sizes, vision_feature_select_strategy, image_newline=None):
452
+ """
453
+ Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
454
+
455
+ Args:
456
+ image_features (`List[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
457
+ List of image feature tensor, each contains all the visual feature of all patches.
458
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
459
+ Actual image size of each images (H, W).
460
+ vision_feature_select_strategy (`str`)
461
+ The feature selection strategy used to select the vision feature from the vision backbone.
462
+ image_newline (`torch.Tensor` of shape `(embed_dim)`)
463
+ New line embedding vector.
464
+ Returns:
465
+ image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
466
+ feature_lens (`List[int]`)
467
+ token length of each image in image_features
468
+ """
469
+ new_image_features = []
470
+ feature_lens = []
471
+ for image_idx, image_feature in enumerate(image_features):
472
+ if image_feature.shape[0] > 1:
473
+ base_image_feature = image_feature[0]
474
+ image_feature = image_feature[1:]
475
+ height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
476
+
477
+ num_patch_height, num_patch_width = get_anyres_image_grid_shape(
478
+ image_sizes[image_idx],
479
+ self.config.image_grid_pinpoints,
480
+ self.config.vision_config.image_size,
481
+ )
482
+
483
+ if (
484
+ np.prod(image_feature.shape) % (num_patch_height * num_patch_width * height * width) != 0
485
+ and vision_feature_select_strategy == "default"
486
+ ):
487
+ logger.warning_once(
488
+ "Image feature shape does not line up with the provided patch size. "
489
+ "You may be using the `default` vision_feature_select_strategy with a"
490
+ " visual encoder that does not have CLS."
491
+ )
492
+
493
+ image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
494
+ image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
495
+ image_feature = image_feature.flatten(1, 2).flatten(2, 3)
496
+ image_feature = unpad_image(image_feature, image_sizes[image_idx])
497
+ if image_newline is not None:
498
+ image_feature = torch.cat(
499
+ (
500
+ image_feature,
501
+ image_newline[:, None, None]
502
+ .expand(*image_feature.shape[:-1], 1)
503
+ .to(image_feature.device, image_feature.dtype),
504
+ ),
505
+ dim=-1,
506
+ )
507
+ image_feature = image_feature.flatten(1, 2).transpose(0, 1)
508
+ image_feature = torch.cat((base_image_feature, image_feature), dim=0)
509
+ else:
510
+ image_feature = image_feature[0]
511
+ if image_newline is not None:
512
+ image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
513
+ new_image_features.append(image_feature)
514
+ feature_lens.append(image_feature.size(0))
515
+ image_features = torch.cat(new_image_features, dim=0)
516
+ feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features.device)
517
+ return image_features, feature_lens
518
+
519
+ def get_image_features(
520
+ self,
521
+ pixel_values: torch.FloatTensor,
522
+ image_sizes: torch.Tensor,
523
+ vision_feature_layer: Union[int, List[int]],
524
+ vision_feature_select_strategy: str,
525
+ ):
526
+ """
527
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
528
+
529
+ Args:
530
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
531
+ The tensors corresponding to the input images.
532
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
533
+ Actual image size of each images (H, W).
534
+ vision_feature_layer (`Union[int, List[int]]`):
535
+ The index of the layer to select the vision feature. If multiple indices are provided,
536
+ the vision feature of the corresponding indices will be concatenated to form the
537
+ vision features.
538
+ vision_feature_select_strategy (`str`):
539
+ The feature selection strategy used to select the vision feature from the vision backbone.
540
+ Can be one of `"default"` or `"full"`
541
+ Returns:
542
+ image_features (List[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
543
+ and are of shape `(num_patches, image_length, embed_dim)`).
544
+ """
545
+ # ! infer image_num_patches from image_sizes
546
+ image_num_patches = [
547
+ image_size_to_num_patches(
548
+ image_size=imsize,
549
+ grid_pinpoints=self.config.image_grid_pinpoints,
550
+ patch_size=self.config.vision_config.image_size,
551
+ )
552
+ for imsize in image_sizes
553
+ ]
554
+ if pixel_values.dim() == 5:
555
+ # stacked if input is (batch_size, num_patches, num_channels, height, width)
556
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
557
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
558
+ elif pixel_values.dim() != 4:
559
+ # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
560
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
561
+
562
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True)
563
+ # If we have one vision feature layer, return the corresponding hidden states,
564
+ # otherwise, select the hidden states of each feature layer and concatenate them
565
+ if isinstance(vision_feature_layer, int):
566
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
567
+ else:
568
+ hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
569
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
570
+
571
+ if vision_feature_select_strategy == "default":
572
+ selected_image_feature = selected_image_feature[:, 1:]
573
+ elif vision_feature_select_strategy == "full":
574
+ selected_image_feature = selected_image_feature
575
+ image_features = self.multi_modal_projector(selected_image_feature)
576
+ image_features = torch.split(image_features, image_num_patches, dim=0)
577
+ return image_features
578
+
579
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
580
+ @add_start_docstrings_to_model_forward(LLAVA_NEXT_VIDEO_INPUTS_DOCSTRING)
581
+ @replace_return_docstrings(output_type=LlavaNextVideoCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
582
+ def forward(
583
+ self,
584
+ input_ids: torch.LongTensor = None,
585
+ pixel_values: torch.FloatTensor = None,
586
+ pixel_values_videos: torch.FloatTensor = None,
587
+ image_sizes: Optional[torch.LongTensor] = None,
588
+ attention_mask: Optional[torch.Tensor] = None,
589
+ position_ids: Optional[torch.LongTensor] = None,
590
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
591
+ inputs_embeds: Optional[torch.FloatTensor] = None,
592
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
593
+ vision_feature_select_strategy: Optional[str] = None,
594
+ labels: Optional[torch.LongTensor] = None,
595
+ use_cache: Optional[bool] = None,
596
+ output_attentions: Optional[bool] = None,
597
+ output_hidden_states: Optional[bool] = None,
598
+ return_dict: Optional[bool] = None,
599
+ cache_position: Optional[torch.LongTensor] = None,
600
+ logits_to_keep: Union[int, torch.Tensor] = 0,
601
+ **lm_kwargs,
602
+ ) -> Union[Tuple, LlavaNextVideoCausalLMOutputWithPast]:
603
+ r"""
604
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, image_size, image_size)):
605
+ The tensors corresponding to the input videos. Pixel values can be obtained using
606
+ [`AutoImageProcessor`]. See [`LlavaNextVideoVideoProcessor.__call__`] for details. [`LlavaProcessor`] uses
607
+ [`LlavaNextVideoVideoProcessor`] for processing videos.
608
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
609
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
610
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
611
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
612
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
613
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
614
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
615
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
616
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
617
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
618
+
619
+ Returns:
620
+
621
+ Example:
622
+
623
+ ```python
624
+ >>> from PIL import Image
625
+ >>> import requests
626
+ >>> import av
627
+ >>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration
628
+
629
+ >>> def read_video_pyav(container, indices):
630
+ ... '''
631
+ ... Decode the video with PyAV decoder.
632
+ ... Args:
633
+ ... container (`av.container.input.InputContainer`): PyAV container.
634
+ ... indices (`List[int]`): List of frame indices to decode.
635
+ ... Returns:
636
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
637
+ ... '''
638
+ ... frames = []
639
+ ... container.seek(0)
640
+ ... start_index = indices[0]
641
+ ... end_index = indices[-1]
642
+ ... for i, frame in enumerate(container.decode(video=0)):
643
+ ... if i > end_index:
644
+ ... break
645
+ ... if i >= start_index and i in indices:
646
+ ... frames.append(frame)
647
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
648
+
649
+ >>> model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", device_map="auto")
650
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")
651
+
652
+ >>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:"
653
+ >>> video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
654
+ >>> container = av.open(video_path)
655
+
656
+ >>> # sample uniformly 8 frames from the video (model was trained with 32 frames per video, but this video is short)
657
+ >>> total_frames = container.streams.video[0].frames
658
+ >>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)
659
+ >>> clip = read_video_pyav(container, indices)
660
+ >>> inputs_video = processor(text=prompt, videos=clip, return_tensors="pt").to(model.device)
661
+
662
+ >>> # load an image to generate from an image
663
+ >>> prompt = "USER:<image>\nWhat is shown in this image? ASSISTANT:"
664
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
665
+ >>> image = Image.open(requests.get(url, stream=True).raw)
666
+ >>> inputs_image = processor(text=prompt, images=image, return_tensors="pt").to(model.device)
667
+
668
+ >>> # Generate from video
669
+ >>> generate_ids = model.generate(**inputs_video, max_length=50)
670
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
671
+ "USER:\nWhy is this video funny? ASSISTANT: The humor in this video comes from the unexpected and endearing sight of a baby wearing glasses and (...)"
672
+
673
+ >>> # Generate from image
674
+ >>> generate_ids = model.generate(**inputs_image, max_length=30)
675
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
676
+ "USER: \nWhat's the content of the image? ASSISTANT: The image shows a red stop sign on a pole, with a traditional Chinese archway (...)"
677
+ ```"""
678
+
679
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
680
+ output_hidden_states = (
681
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
682
+ )
683
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
684
+ self.vision_feature_layer = (
685
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
686
+ )
687
+ self.vision_feature_select_strategy = (
688
+ vision_feature_select_strategy
689
+ if vision_feature_select_strategy is not None
690
+ else self.config.vision_feature_select_strategy
691
+ )
692
+
693
+ if (input_ids is None) ^ (inputs_embeds is not None):
694
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
695
+
696
+ if (pixel_values is not None or pixel_values_videos is not None) and inputs_embeds is not None:
697
+ raise ValueError(
698
+ "You cannot specify both `pixel_values`/`pixel_values_videos` and `inputs_embeds` at the same time, "
699
+ "and must specify either one"
700
+ )
701
+
702
+ if inputs_embeds is None:
703
+ inputs_embeds = self.get_input_embeddings()(input_ids)
704
+
705
+ if pixel_values is not None and pixel_values.size(0) > 0:
706
+ image_features = self.get_image_features(
707
+ pixel_values,
708
+ image_sizes,
709
+ vision_feature_layer=self.vision_feature_layer,
710
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
711
+ )
712
+ image_features, feature_lens = self.pack_image_features(
713
+ image_features,
714
+ image_sizes,
715
+ self.vision_feature_select_strategy,
716
+ image_newline=self.image_newline,
717
+ )
718
+
719
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
720
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
721
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
722
+ n_image_tokens = (input_ids == self.config.image_token_index).sum()
723
+ n_image_features = image_features.shape[0]
724
+ raise ValueError(
725
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
726
+ )
727
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
728
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
729
+
730
+ if pixel_values_videos is not None and pixel_values_videos.size(0) > 0:
731
+ video_features = self.get_video_features(
732
+ pixel_values_videos,
733
+ vision_feature_layer=self.vision_feature_layer,
734
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
735
+ )
736
+ video_features = [feature.flatten(0, 1) for feature in video_features]
737
+ video_feature_lens = [feature.size(0) for feature in video_features]
738
+ video_features = torch.cat(video_features, dim=0)
739
+ video_feature_lens = torch.tensor(video_feature_lens, dtype=torch.long, device=video_features.device)
740
+
741
+ special_image_mask = (input_ids == self.config.video_token_index).unsqueeze(-1)
742
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
743
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != video_features.numel():
744
+ n_video_tokens = (input_ids == self.config.video_token_index).sum().item()
745
+ n_video_features = video_features.shape[0]
746
+ raise ValueError(
747
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
748
+ )
749
+ video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)
750
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, video_features)
751
+
752
+ outputs = self.language_model(
753
+ attention_mask=attention_mask,
754
+ position_ids=position_ids,
755
+ past_key_values=past_key_values,
756
+ inputs_embeds=inputs_embeds,
757
+ use_cache=use_cache,
758
+ output_attentions=output_attentions,
759
+ output_hidden_states=output_hidden_states,
760
+ return_dict=return_dict,
761
+ cache_position=cache_position,
762
+ logits_to_keep=logits_to_keep,
763
+ **lm_kwargs,
764
+ )
765
+
766
+ logits = outputs[0]
767
+
768
+ loss = None
769
+ if labels is not None:
770
+ # Shift so that tokens < n predict n
771
+ if attention_mask is not None:
772
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
773
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
774
+ shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)
775
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
776
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
777
+ else:
778
+ shift_logits = logits[..., :-1, :].contiguous()
779
+ shift_labels = labels[..., 1:].contiguous()
780
+ # Flatten the tokens
781
+ loss_fct = nn.CrossEntropyLoss()
782
+ loss = loss_fct(
783
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
784
+ )
785
+
786
+ if not return_dict:
787
+ output = (logits,) + outputs[1:]
788
+ return (loss,) + output if loss is not None else output
789
+
790
+ return LlavaNextVideoCausalLMOutputWithPast(
791
+ loss=loss,
792
+ logits=logits,
793
+ past_key_values=outputs.past_key_values,
794
+ hidden_states=outputs.hidden_states,
795
+ attentions=outputs.attentions,
796
+ image_hidden_states=image_features if pixel_values is not None else None,
797
+ video_hidden_states=video_features if pixel_values_videos is not None else None,
798
+ )
799
+
800
+ def prepare_inputs_for_generation(
801
+ self,
802
+ input_ids,
803
+ past_key_values=None,
804
+ inputs_embeds=None,
805
+ pixel_values=None,
806
+ pixel_values_videos=None,
807
+ image_sizes=None,
808
+ attention_mask=None,
809
+ cache_position=None,
810
+ logits_to_keep=None,
811
+ **kwargs,
812
+ ):
813
+ # Overwritten -- extra custom processing
814
+
815
+ model_inputs = self.language_model.prepare_inputs_for_generation(
816
+ input_ids,
817
+ past_key_values=past_key_values,
818
+ inputs_embeds=inputs_embeds,
819
+ attention_mask=attention_mask,
820
+ cache_position=cache_position,
821
+ logits_to_keep=logits_to_keep,
822
+ **kwargs,
823
+ )
824
+
825
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
826
+ # Otherwise we need pixel values to be passed to model
827
+ if cache_position[0] == 0:
828
+ model_inputs["pixel_values"] = pixel_values
829
+ model_inputs["pixel_values_videos"] = pixel_values_videos
830
+ model_inputs["image_sizes"] = image_sizes
831
+
832
+ return model_inputs
833
+
834
+ def get_video_features(
835
+ self,
836
+ pixel_values: torch.FloatTensor,
837
+ vision_feature_layer: Union[int, List[int]],
838
+ vision_feature_select_strategy: str,
839
+ ):
840
+ """
841
+ Obtains video last hidden states from the vision tower and apply multimodal projection.
842
+
843
+ Args:
844
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
845
+ The tensors corresponding to the input video.
846
+ vision_feature_layer (`Union[int, List[int]]`):
847
+ The index of the layer to select the vision feature. If multiple indices are provided,
848
+ the vision feature of the corresponding indices will be concatenated to form the
849
+ vision features.
850
+ vision_feature_select_strategy (`str`):
851
+ The feature selection strategy used to select the vision feature from the vision backbone.
852
+ Can be one of `"default"` or `"full"`
853
+ Returns:
854
+ video_features (List[`torch.Tensor`]): List of video feature tensor, each contains all the visual feature of all patches
855
+ and are of shape `(num_videos, video_length, embed_dim)`).
856
+ """
857
+ batch_size, frames, channels, height, width = pixel_values.shape
858
+ pixel_values = pixel_values.reshape(batch_size * frames, channels, height, width)
859
+ video_features = self.vision_tower(pixel_values, output_hidden_states=True)
860
+
861
+ # If we have one vision feature layer, return the corresponding hidden states,
862
+ # otherwise, select the hidden states of each feature layer and concatenate them
863
+ if isinstance(vision_feature_layer, int):
864
+ selected_video_features = video_features.hidden_states[vision_feature_layer]
865
+ else:
866
+ hs_pool = [video_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
867
+ selected_video_features = torch.cat(hs_pool, dim=-1)
868
+
869
+ if vision_feature_select_strategy == "default":
870
+ selected_video_features = selected_video_features[:, 1:]
871
+ elif vision_feature_select_strategy == "full":
872
+ selected_video_features = selected_video_features
873
+
874
+ # Same as image features except that video has pooling layer
875
+ video_features = self.vision_resampler(selected_video_features)
876
+ video_features = self.multi_modal_projector(video_features)
877
+ video_features = torch.split(video_features, frames, dim=0)
878
+ return video_features
879
+
880
+
881
+ __all__ = ["LlavaNextVideoForConditionalGeneration", "LlavaNextVideoPreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/modular_llava_next_video.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ import math
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from transformers.models.llava_next.modeling_llava_next import (
25
+ LlavaNextCausalLMOutputWithPast,
26
+ LlavaNextForConditionalGeneration,
27
+ LlavaNextPreTrainedModel,
28
+ image_size_to_num_patches,
29
+ )
30
+
31
+ from ...configuration_utils import PretrainedConfig
32
+ from ...utils import (
33
+ is_torchdynamo_compiling,
34
+ logging,
35
+ )
36
+ from ..auto import CONFIG_MAPPING, AutoConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ class LlavaNextVideoConfig(PretrainedConfig):
43
+ r"""
44
+ This is the configuration class to store the configuration of a [`LlavaNextVideoForConditionalGeneration`]. It is used to instantiate an
45
+ Llava-NeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
46
+ with the defaults will yield a similar configuration to that of the [llava-hf/LLaVA-NeXT-Video-7B-hf](https://huggingface.co/llava-hf/LLaVA-NeXT-Video-7B-hf)
47
+ model.
48
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
49
+ documentation from [`PretrainedConfig`] for more information.
50
+
51
+ Args:
52
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `CLIPVisionConfig`):
53
+ The config object or dictionary of the vision backbone.
54
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`):
55
+ The config object or dictionary of the text backbone.
56
+ image_token_index (`int`, *optional*, defaults to 32001):
57
+ The image token index to encode the image prompt.
58
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
59
+ The activation function used by the multimodal projector.
60
+ multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
61
+ Whether to use bias in the multimodal projector.
62
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
63
+ The feature selection strategy used to select the vision feature from the vision backbone.
64
+ Can be one of `"default"` or `"full"`. If `"default"`, the CLS token is removed from the vision features.
65
+ If `"full"`, the full vision features are used.
66
+ vision_feature_layer (`Union[int, List[int]]`, *optional*, defaults to -2):
67
+ The index of the layer to select the vision feature. If multiple indices are provided,
68
+ the vision feature of the corresponding indices will be concatenated to form the
69
+ vision features.
70
+ image_grid_pinpoints (`List`, *optional*, defaults to `[[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]`):
71
+ A list of possible resolutions to use for processing high resolution images. Each item in the list should be a tuple or list
72
+ of the form `(height, width)`.
73
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
74
+ Whether the model's input and output word embeddings should be tied.
75
+ video_token_index (`int`, *optional*, defaults to 32000):
76
+ The video token index to encode the image prompt.
77
+ spatial_pool_mode (`str`, *optional*, defaults to `"average"`):
78
+ Pooling mode to use for videos. Can be "average", "max" or "conv".
79
+ spatial_pool_stride (`int`, *optional*, defaults to 2):
80
+ Stride used in the pooling layer for videos.
81
+ image_seq_length (`int`, *optional*, defaults to 576):
82
+ Sequence length of one image embedding.
83
+ video_seq_length (`int`, *optional*, defaults to 288):
84
+ Sequence length of one video embedding.
85
+
86
+ Example:
87
+
88
+ ```python
89
+ >>> from transformers import LlavaNextVideoForConditionalGeneration, LlavaNextVideoConfig, CLIPVisionConfig, LlamaConfig
90
+
91
+ >>> # Initializing a CLIP-vision config
92
+ >>> vision_config = CLIPVisionConfig()
93
+
94
+ >>> # Initializing a Llama config
95
+ >>> text_config = LlamaConfig()
96
+
97
+ >>> configuration = LlavaNextVideoConfig(vision_config, text_config)
98
+
99
+ >>> model = LlavaNextVideoForConditionalGeneration(configuration)
100
+
101
+ >>> # Accessing the model configuration
102
+ >>> configuration = model.config
103
+ ```"""
104
+
105
+ model_type = "llava_next_video"
106
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
107
+
108
+ def __init__(
109
+ self,
110
+ vision_config=None,
111
+ text_config=None,
112
+ image_token_index=32001,
113
+ projector_hidden_act="gelu",
114
+ multimodal_projector_bias=True,
115
+ vision_feature_select_strategy="default",
116
+ vision_feature_layer=-2,
117
+ image_grid_pinpoints=None,
118
+ tie_word_embeddings=False,
119
+ video_token_index=32000,
120
+ spatial_pool_mode="average",
121
+ spatial_pool_stride=2,
122
+ image_seq_length=576,
123
+ video_seq_length=288,
124
+ **kwargs,
125
+ ):
126
+ self.video_token_index = video_token_index
127
+ self.spatial_pool_mode = spatial_pool_mode
128
+ self.spatial_pool_stride = spatial_pool_stride
129
+ self.image_seq_length = image_seq_length
130
+ self.video_seq_length = video_seq_length
131
+ self.image_token_index = image_token_index
132
+ self.projector_hidden_act = projector_hidden_act
133
+ self.multimodal_projector_bias = multimodal_projector_bias
134
+
135
+ if vision_feature_select_strategy not in ["default", "full"]:
136
+ raise ValueError(
137
+ "vision_feature_select_strategy should be one of 'default', 'full'."
138
+ f"Got: {vision_feature_select_strategy}"
139
+ )
140
+
141
+ self.vision_feature_select_strategy = vision_feature_select_strategy
142
+ self.vision_feature_layer = vision_feature_layer
143
+ image_grid_pinpoints = (
144
+ image_grid_pinpoints
145
+ if image_grid_pinpoints is not None
146
+ else [[336, 672], [672, 336], [672, 672], [1008, 336], [336, 1008]]
147
+ )
148
+ self.image_grid_pinpoints = image_grid_pinpoints
149
+
150
+ if isinstance(vision_config, dict):
151
+ vision_config["model_type"] = (
152
+ vision_config["model_type"] if "model_type" in vision_config else "clip_vision_model"
153
+ )
154
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
155
+ elif vision_config is None:
156
+ vision_config = CONFIG_MAPPING["clip_vision_model"](
157
+ intermediate_size=4096,
158
+ hidden_size=1024,
159
+ patch_size=14,
160
+ image_size=336,
161
+ num_hidden_layers=24,
162
+ num_attention_heads=16,
163
+ vocab_size=32000,
164
+ projection_dim=768,
165
+ )
166
+
167
+ self.vision_config = vision_config
168
+
169
+ if isinstance(text_config, dict):
170
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "llama"
171
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
172
+ elif text_config is None:
173
+ text_config = CONFIG_MAPPING["llama"]()
174
+
175
+ self.text_config = text_config
176
+
177
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
178
+
179
+
180
+ @dataclass
181
+ class LlavaNextVideoCausalLMOutputWithPast(LlavaNextCausalLMOutputWithPast):
182
+ """
183
+ video_hidden_states (`torch.FloatTensor`, *optional*):
184
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
185
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
186
+ """
187
+
188
+ video_hidden_states: Optional[torch.FloatTensor] = None
189
+
190
+
191
+ class LlavaNextVideoPooler(nn.Module):
192
+ def __init__(self, config):
193
+ super().__init__()
194
+
195
+ mode = config.spatial_pool_mode
196
+ stride = config.spatial_pool_stride
197
+ out_channels = getattr(config, "spatial_pool_out_channels", config.vision_config.hidden_size)
198
+ self.image_size = (config.vision_config.image_size // config.vision_config.patch_size) ** 2
199
+
200
+ if mode == "average":
201
+ self.pool = nn.AvgPool2d(kernel_size=stride, stride=stride)
202
+ elif mode == "max":
203
+ self.pool = nn.MaxPool2d(kernel_size=stride, stride=stride)
204
+ elif mode == "conv":
205
+ self.pool = nn.Conv2d(
206
+ in_channels=config.vision_config.hidden_size,
207
+ out_channels=out_channels,
208
+ kernel_size=stride,
209
+ stride=stride,
210
+ )
211
+ else:
212
+ raise ValueError(f"Unknown pooling mode: {mode}. Has to be one of [`average`, `max`, `conv`]")
213
+
214
+ def forward(self, image_features):
215
+ ori_width = int(math.sqrt(image_features.shape[1] * self.image_size // self.image_size))
216
+ ori_height = int(ori_width * self.image_size // self.image_size)
217
+
218
+ batch_size, _, dim = image_features.shape
219
+ image_features_spatial = image_features.view(batch_size, ori_height, ori_height, dim).permute(0, 3, 1, 2)
220
+ image_features_spatial_pool = self.pool(image_features_spatial)
221
+
222
+ return image_features_spatial_pool.flatten(2).transpose(1, 2).contiguous()
223
+
224
+
225
+ class LlavaNextVideoPreTrainedModel(LlavaNextPreTrainedModel):
226
+ pass
227
+
228
+
229
+ class LlavaNextVideoForConditionalGeneration(LlavaNextForConditionalGeneration):
230
+ def __init__(self, config: LlavaNextVideoConfig, **super_kwargs):
231
+ super().__init__(config, **super_kwargs)
232
+ self.vision_resampler = LlavaNextVideoPooler(config)
233
+ self.post_init()
234
+
235
+ def get_image_features(
236
+ self,
237
+ pixel_values: torch.FloatTensor,
238
+ image_sizes: torch.Tensor,
239
+ vision_feature_layer: Union[int, List[int]],
240
+ vision_feature_select_strategy: str,
241
+ ):
242
+ """
243
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
244
+
245
+ Args:
246
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
247
+ The tensors corresponding to the input images.
248
+ image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
249
+ Actual image size of each images (H, W).
250
+ vision_feature_layer (`Union[int, List[int]]`):
251
+ The index of the layer to select the vision feature. If multiple indices are provided,
252
+ the vision feature of the corresponding indices will be concatenated to form the
253
+ vision features.
254
+ vision_feature_select_strategy (`str`):
255
+ The feature selection strategy used to select the vision feature from the vision backbone.
256
+ Can be one of `"default"` or `"full"`
257
+ Returns:
258
+ image_features (List[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
259
+ and are of shape `(num_patches, image_length, embed_dim)`).
260
+ """
261
+ # ! infer image_num_patches from image_sizes
262
+ image_num_patches = [
263
+ image_size_to_num_patches(
264
+ image_size=imsize,
265
+ grid_pinpoints=self.config.image_grid_pinpoints,
266
+ patch_size=self.config.vision_config.image_size,
267
+ )
268
+ for imsize in image_sizes
269
+ ]
270
+ if pixel_values.dim() == 5:
271
+ # stacked if input is (batch_size, num_patches, num_channels, height, width)
272
+ _pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
273
+ pixel_values = torch.cat(_pixel_values_list, dim=0)
274
+ elif pixel_values.dim() != 4:
275
+ # otherwise has to be stacked from list of (num_patches, num_channels, height, width)
276
+ raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
277
+
278
+ image_features = self.vision_tower(pixel_values, output_hidden_states=True)
279
+ # If we have one vision feature layer, return the corresponding hidden states,
280
+ # otherwise, select the hidden states of each feature layer and concatenate them
281
+ if isinstance(vision_feature_layer, int):
282
+ selected_image_feature = image_features.hidden_states[vision_feature_layer]
283
+ else:
284
+ hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
285
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
286
+
287
+ if vision_feature_select_strategy == "default":
288
+ selected_image_feature = selected_image_feature[:, 1:]
289
+ elif vision_feature_select_strategy == "full":
290
+ selected_image_feature = selected_image_feature
291
+ image_features = self.multi_modal_projector(selected_image_feature)
292
+ image_features = torch.split(image_features, image_num_patches, dim=0)
293
+ return image_features
294
+
295
+ def get_video_features(
296
+ self,
297
+ pixel_values: torch.FloatTensor,
298
+ vision_feature_layer: Union[int, List[int]],
299
+ vision_feature_select_strategy: str,
300
+ ):
301
+ """
302
+ Obtains video last hidden states from the vision tower and apply multimodal projection.
303
+
304
+ Args:
305
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
306
+ The tensors corresponding to the input video.
307
+ vision_feature_layer (`Union[int, List[int]]`):
308
+ The index of the layer to select the vision feature. If multiple indices are provided,
309
+ the vision feature of the corresponding indices will be concatenated to form the
310
+ vision features.
311
+ vision_feature_select_strategy (`str`):
312
+ The feature selection strategy used to select the vision feature from the vision backbone.
313
+ Can be one of `"default"` or `"full"`
314
+ Returns:
315
+ video_features (List[`torch.Tensor`]): List of video feature tensor, each contains all the visual feature of all patches
316
+ and are of shape `(num_videos, video_length, embed_dim)`).
317
+ """
318
+ batch_size, frames, channels, height, width = pixel_values.shape
319
+ pixel_values = pixel_values.reshape(batch_size * frames, channels, height, width)
320
+ video_features = self.vision_tower(pixel_values, output_hidden_states=True)
321
+
322
+ # If we have one vision feature layer, return the corresponding hidden states,
323
+ # otherwise, select the hidden states of each feature layer and concatenate them
324
+ if isinstance(vision_feature_layer, int):
325
+ selected_video_features = video_features.hidden_states[vision_feature_layer]
326
+ else:
327
+ hs_pool = [video_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
328
+ selected_video_features = torch.cat(hs_pool, dim=-1)
329
+
330
+ if vision_feature_select_strategy == "default":
331
+ selected_video_features = selected_video_features[:, 1:]
332
+ elif vision_feature_select_strategy == "full":
333
+ selected_video_features = selected_video_features
334
+
335
+ # Same as image features except that video has pooling layer
336
+ video_features = self.vision_resampler(selected_video_features)
337
+ video_features = self.multi_modal_projector(video_features)
338
+ video_features = torch.split(video_features, frames, dim=0)
339
+ return video_features
340
+
341
+ def forward(
342
+ self,
343
+ input_ids: torch.LongTensor = None,
344
+ pixel_values: torch.FloatTensor = None,
345
+ pixel_values_videos: torch.FloatTensor = None,
346
+ image_sizes: Optional[torch.LongTensor] = None,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
350
+ inputs_embeds: Optional[torch.FloatTensor] = None,
351
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
352
+ vision_feature_select_strategy: Optional[str] = None,
353
+ labels: Optional[torch.LongTensor] = None,
354
+ use_cache: Optional[bool] = None,
355
+ output_attentions: Optional[bool] = None,
356
+ output_hidden_states: Optional[bool] = None,
357
+ return_dict: Optional[bool] = None,
358
+ cache_position: Optional[torch.LongTensor] = None,
359
+ logits_to_keep: Union[int, torch.Tensor] = 0,
360
+ **lm_kwargs,
361
+ ) -> Union[Tuple, LlavaNextVideoCausalLMOutputWithPast]:
362
+ r"""
363
+ pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, image_size, image_size)):
364
+ The tensors corresponding to the input videos. Pixel values can be obtained using
365
+ [`AutoImageProcessor`]. See [`LlavaNextVideoVideoProcessor.__call__`] for details. [`LlavaProcessor`] uses
366
+ [`LlavaNextVideoVideoProcessor`] for processing videos.
367
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
368
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
369
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
370
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
371
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
372
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
373
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
374
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
375
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
376
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
377
+
378
+ Returns:
379
+
380
+ Example:
381
+
382
+ ```python
383
+ >>> from PIL import Image
384
+ >>> import requests
385
+ >>> import av
386
+ >>> from transformers import AutoProcessor, LlavaNextVideoForConditionalGeneration
387
+
388
+ >>> def read_video_pyav(container, indices):
389
+ ... '''
390
+ ... Decode the video with PyAV decoder.
391
+ ... Args:
392
+ ... container (`av.container.input.InputContainer`): PyAV container.
393
+ ... indices (`List[int]`): List of frame indices to decode.
394
+ ... Returns:
395
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
396
+ ... '''
397
+ ... frames = []
398
+ ... container.seek(0)
399
+ ... start_index = indices[0]
400
+ ... end_index = indices[-1]
401
+ ... for i, frame in enumerate(container.decode(video=0)):
402
+ ... if i > end_index:
403
+ ... break
404
+ ... if i >= start_index and i in indices:
405
+ ... frames.append(frame)
406
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
407
+
408
+ >>> model = LlavaNextVideoForConditionalGeneration.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf", device_map="auto")
409
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/LLaVA-NeXT-Video-7B-hf")
410
+
411
+ >>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:"
412
+ >>> video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
413
+ >>> container = av.open(video_path)
414
+
415
+ >>> # sample uniformly 8 frames from the video (model was trained with 32 frames per video, but this video is short)
416
+ >>> total_frames = container.streams.video[0].frames
417
+ >>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)
418
+ >>> clip = read_video_pyav(container, indices)
419
+ >>> inputs_video = processor(text=prompt, videos=clip, return_tensors="pt").to(model.device)
420
+
421
+ >>> # load an image to generate from an image
422
+ >>> prompt = "USER:<image>\nWhat is shown in this image? ASSISTANT:"
423
+ >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
424
+ >>> image = Image.open(requests.get(url, stream=True).raw)
425
+ >>> inputs_image = processor(text=prompt, images=image, return_tensors="pt").to(model.device)
426
+
427
+ >>> # Generate from video
428
+ >>> generate_ids = model.generate(**inputs_video, max_length=50)
429
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
430
+ "USER:\nWhy is this video funny? ASSISTANT: The humor in this video comes from the unexpected and endearing sight of a baby wearing glasses and (...)"
431
+
432
+ >>> # Generate from image
433
+ >>> generate_ids = model.generate(**inputs_image, max_length=30)
434
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
435
+ "USER: \nWhat's the content of the image? ASSISTANT: The image shows a red stop sign on a pole, with a traditional Chinese archway (...)"
436
+ ```"""
437
+
438
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
439
+ output_hidden_states = (
440
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
441
+ )
442
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
443
+ self.vision_feature_layer = (
444
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
445
+ )
446
+ self.vision_feature_select_strategy = (
447
+ vision_feature_select_strategy
448
+ if vision_feature_select_strategy is not None
449
+ else self.config.vision_feature_select_strategy
450
+ )
451
+
452
+ if (input_ids is None) ^ (inputs_embeds is not None):
453
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
454
+
455
+ if (pixel_values is not None or pixel_values_videos is not None) and inputs_embeds is not None:
456
+ raise ValueError(
457
+ "You cannot specify both `pixel_values`/`pixel_values_videos` and `inputs_embeds` at the same time, "
458
+ "and must specify either one"
459
+ )
460
+
461
+ if inputs_embeds is None:
462
+ inputs_embeds = self.get_input_embeddings()(input_ids)
463
+
464
+ if pixel_values is not None and pixel_values.size(0) > 0:
465
+ image_features = self.get_image_features(
466
+ pixel_values,
467
+ image_sizes,
468
+ vision_feature_layer=self.vision_feature_layer,
469
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
470
+ )
471
+ image_features, feature_lens = self.pack_image_features(
472
+ image_features,
473
+ image_sizes,
474
+ self.vision_feature_select_strategy,
475
+ image_newline=self.image_newline,
476
+ )
477
+
478
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
479
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
480
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
481
+ n_image_tokens = (input_ids == self.config.image_token_index).sum()
482
+ n_image_features = image_features.shape[0]
483
+ raise ValueError(
484
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
485
+ )
486
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
487
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
488
+
489
+ if pixel_values_videos is not None and pixel_values_videos.size(0) > 0:
490
+ video_features = self.get_video_features(
491
+ pixel_values_videos,
492
+ vision_feature_layer=self.vision_feature_layer,
493
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
494
+ )
495
+ video_features = [feature.flatten(0, 1) for feature in video_features]
496
+ video_feature_lens = [feature.size(0) for feature in video_features]
497
+ video_features = torch.cat(video_features, dim=0)
498
+ video_feature_lens = torch.tensor(video_feature_lens, dtype=torch.long, device=video_features.device)
499
+
500
+ special_image_mask = (input_ids == self.config.video_token_index).unsqueeze(-1)
501
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
502
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != video_features.numel():
503
+ n_video_tokens = (input_ids == self.config.video_token_index).sum().item()
504
+ n_video_features = video_features.shape[0]
505
+ raise ValueError(
506
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
507
+ )
508
+ video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)
509
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, video_features)
510
+
511
+ outputs = self.language_model(
512
+ attention_mask=attention_mask,
513
+ position_ids=position_ids,
514
+ past_key_values=past_key_values,
515
+ inputs_embeds=inputs_embeds,
516
+ use_cache=use_cache,
517
+ output_attentions=output_attentions,
518
+ output_hidden_states=output_hidden_states,
519
+ return_dict=return_dict,
520
+ cache_position=cache_position,
521
+ logits_to_keep=logits_to_keep,
522
+ **lm_kwargs,
523
+ )
524
+
525
+ logits = outputs[0]
526
+
527
+ loss = None
528
+ if labels is not None:
529
+ # Shift so that tokens < n predict n
530
+ if attention_mask is not None:
531
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
532
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
533
+ shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)
534
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
535
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
536
+ else:
537
+ shift_logits = logits[..., :-1, :].contiguous()
538
+ shift_labels = labels[..., 1:].contiguous()
539
+ # Flatten the tokens
540
+ loss_fct = nn.CrossEntropyLoss()
541
+ loss = loss_fct(
542
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
543
+ )
544
+
545
+ if not return_dict:
546
+ output = (logits,) + outputs[1:]
547
+ return (loss,) + output if loss is not None else output
548
+
549
+ return LlavaNextVideoCausalLMOutputWithPast(
550
+ loss=loss,
551
+ logits=logits,
552
+ past_key_values=outputs.past_key_values,
553
+ hidden_states=outputs.hidden_states,
554
+ attentions=outputs.attentions,
555
+ image_hidden_states=image_features if pixel_values is not None else None,
556
+ video_hidden_states=video_features if pixel_values_videos is not None else None,
557
+ )
558
+
559
+ def prepare_inputs_for_generation(
560
+ self,
561
+ input_ids,
562
+ past_key_values=None,
563
+ inputs_embeds=None,
564
+ pixel_values=None,
565
+ pixel_values_videos=None,
566
+ image_sizes=None,
567
+ attention_mask=None,
568
+ cache_position=None,
569
+ logits_to_keep=None,
570
+ **kwargs,
571
+ ):
572
+ # Overwritten -- extra custom processing
573
+
574
+ model_inputs = self.language_model.prepare_inputs_for_generation(
575
+ input_ids,
576
+ past_key_values=past_key_values,
577
+ inputs_embeds=inputs_embeds,
578
+ attention_mask=attention_mask,
579
+ cache_position=cache_position,
580
+ logits_to_keep=logits_to_keep,
581
+ **kwargs,
582
+ )
583
+
584
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
585
+ # Otherwise we need pixel values to be passed to model
586
+ if cache_position[0] == 0:
587
+ model_inputs["pixel_values"] = pixel_values
588
+ model_inputs["pixel_values_videos"] = pixel_values_videos
589
+ model_inputs["image_sizes"] = image_sizes
590
+
591
+ return model_inputs
592
+
593
+
594
+ __all__ = ["LlavaNextVideoConfig", "LlavaNextVideoForConditionalGeneration", "LlavaNextVideoPreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/llava_next_video/processing_llava_next_video.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
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
+ Processor class for LLaVa-NeXT-Video.
17
+ """
18
+
19
+ from typing import List, Union
20
+
21
+ import numpy as np
22
+
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...image_processing_utils import select_best_resolution
25
+ from ...image_utils import ImageInput, VideoInput, get_image_size, to_numpy_array
26
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, _validate_images_text_input_order
27
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
28
+ from ...utils import logging
29
+
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ class LlavaNextVideoProcessorKwargs(ProcessingKwargs, total=False):
35
+ # see processing_utils.ProcessingKwargs documentation for usage.
36
+ _defaults = {
37
+ "text_kwargs": {
38
+ "padding": False,
39
+ },
40
+ "common_kwargs": {
41
+ "return_tensors": "pt",
42
+ },
43
+ }
44
+
45
+
46
+ class LlavaNextVideoProcessor(ProcessorMixin):
47
+ r"""
48
+ Constructs a LLaVa-NeXT-Video processor which wraps a LLaVa-NeXT image processor, LLaVa-NeXT-Video video processor and
49
+ a LLaMa tokenizer into a single processor.
50
+
51
+ [`LlavaNextVideoProcessor`] offers all the functionalities of [`LlavaNextImageProcessor`], [`LlavaNextVideoImageProcessor`] and
52
+ [`LlamaTokenizerFast`]. See the [`~LlavaNextVideoProcessor.__call__`] and [`~LlavaNextVideoProcessor.decode`] for more information.
53
+
54
+ Args:
55
+ video_processor ([`LlavaNextVideoImageProcessor`], *optional*):
56
+ The video processor is a required input.
57
+ image_processor ([`LlavaNextImageProcessor`], *optional*):
58
+ The image processor is a required input.
59
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
60
+ The tokenizer is a required input.
61
+ chat_template (`str`, *optional*):
62
+ Jinja chat template that will be used in tokenizer's `apply_chat_template`
63
+ patch_size (`int`, *optional*):
64
+ Patch size from the vision tower.
65
+ vision_feature_select_strategy (`str`, *optional*):
66
+ The feature selection strategy used to select the vision feature from the vision backbone.
67
+ Shoudl be same as in model's config
68
+ video_token (`str`, *optional*, defaults to `"<video>"`):
69
+ Special token used to denote video location.
70
+ image_token (`str`, *optional*, defaults to `"<image>"`):
71
+ Special token used to denote image location.
72
+ num_additional_image_tokens (`int`, *optional*, defaults to 0):
73
+ Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other
74
+ extra tokens appended, no need to set this arg.
75
+ """
76
+
77
+ # video and image processor share same args, but have different processing logic
78
+ # only image processor config is saved in the hub
79
+ attributes = ["video_processor", "image_processor", "tokenizer"]
80
+ valid_kwargs = [
81
+ "chat_template",
82
+ "patch_size",
83
+ "vision_feature_select_strategy",
84
+ "image_token",
85
+ "video_token",
86
+ "num_additional_image_tokens",
87
+ ]
88
+ image_processor_class = ("LlavaNextImageProcessor", "LlavaNextImageProcessorFast")
89
+ video_processor_class = "LlavaNextVideoImageProcessor"
90
+ tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
91
+
92
+ def __init__(
93
+ self,
94
+ video_processor=None,
95
+ image_processor=None,
96
+ tokenizer=None,
97
+ chat_template=None,
98
+ patch_size=None,
99
+ vision_feature_select_strategy=None,
100
+ video_token="<video>",
101
+ image_token="<image>",
102
+ num_additional_image_tokens=0,
103
+ **kwargs,
104
+ ):
105
+ self.patch_size = patch_size
106
+ self.num_additional_image_tokens = num_additional_image_tokens
107
+ self.vision_feature_select_strategy = vision_feature_select_strategy
108
+ self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
109
+ self.video_token = tokenizer.video_token if hasattr(tokenizer, "video_token") else video_token
110
+ super().__init__(video_processor, image_processor, tokenizer, chat_template=chat_template)
111
+
112
+ def __call__(
113
+ self,
114
+ images: ImageInput = None,
115
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
116
+ audio=None,
117
+ videos: VideoInput = None,
118
+ **kwargs: Unpack[LlavaNextVideoProcessorKwargs],
119
+ ) -> BatchFeature:
120
+ """
121
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
122
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
123
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
124
+ LlavaNextImageProcessor's [`~LlavaNextImageProcessor.__call__`] if `images` is not `None`. To prepare the video(s),
125
+ this method forwards the `videos` and `kwrags` arguments to LlavaNextVideoImageProcessor's
126
+ [`~LlavaNextVideoImageProcessor.__call__`] if `videos` is not `None`. Please refer to the doctsring
127
+ of the above two methods for more information.
128
+
129
+ Args:
130
+ text (`str`, `List[str]`, `List[List[str]]`):
131
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
132
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
133
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
134
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
135
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
136
+ tensor. Both channels-first and channels-last formats are supported.
137
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
138
+ The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
139
+ tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
140
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
141
+ If set, will return tensors of a particular framework. Acceptable values are:
142
+
143
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
144
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
145
+ - `'np'`: Return NumPy `np.ndarray` objects.
146
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
147
+
148
+ Returns:
149
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
150
+
151
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
152
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
153
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
154
+ `None`).
155
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
156
+ """
157
+ # check if images and text inputs are reversed for BC
158
+ images, text = _validate_images_text_input_order(images, text)
159
+
160
+ output_kwargs = self._merge_kwargs(
161
+ LlavaNextVideoProcessorKwargs,
162
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
163
+ **kwargs,
164
+ )
165
+ if images is not None:
166
+ image_inputs = self.image_processor(images, **output_kwargs["images_kwargs"])
167
+ else:
168
+ image_inputs = {}
169
+
170
+ if videos is not None:
171
+ videos_inputs = self.video_processor(videos, **output_kwargs["videos_kwargs"])
172
+ else:
173
+ videos_inputs = {}
174
+
175
+ if isinstance(text, str):
176
+ text = [text]
177
+ elif not isinstance(text, list) and not isinstance(text[0], str):
178
+ raise ValueError("Invalid input text. Please provide a string, or a list of strings")
179
+
180
+ if image_inputs:
181
+ image_sizes = iter(image_inputs["image_sizes"])
182
+ height, width = get_image_size(to_numpy_array(image_inputs["pixel_values"][0][0]))
183
+ prompt_strings = []
184
+ for sample in text:
185
+ while self.image_token in sample:
186
+ image_size = next(image_sizes)
187
+ if not isinstance(image_size, (list, tuple)):
188
+ # cast to list to avoid numerical precision errors when calculating unpadding
189
+ image_size = image_size.tolist()
190
+ orig_height, orig_width = image_size
191
+ num_image_tokens = self._get_number_of_features(orig_height, orig_width, height, width)
192
+ if self.vision_feature_select_strategy == "default":
193
+ num_image_tokens -= 1
194
+ sample = sample.replace(self.image_token, "<placeholder>" * num_image_tokens, 1)
195
+ prompt_strings.append(sample)
196
+ text = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings]
197
+
198
+ # videos are easier, simply get frames and multiply
199
+ if videos_inputs:
200
+ one_video = videos_inputs.get("pixel_values_videos")[0]
201
+ if isinstance(one_video, (list, tuple)):
202
+ one_video = np.array(one_video)
203
+ else:
204
+ one_video = to_numpy_array(one_video)
205
+ height, width = get_image_size(one_video[0])
206
+ num_frames = one_video.shape[0] # frame dim is always after batch dim
207
+
208
+ # no `self.num_additional_image_tokens` added because video always has a default feature selection strategy
209
+ num_image_tokens = (height // self.patch_size) * (width // self.patch_size)
210
+ num_video_tokens = num_image_tokens // 4 * num_frames # divide by 4 needed for avg pooling layer
211
+ prompt_strings = []
212
+ for sample in text:
213
+ sample = sample.replace(self.video_token, self.video_token * num_video_tokens)
214
+ prompt_strings.append(sample)
215
+ text = prompt_strings
216
+
217
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
218
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})
219
+
220
+ # Copied from transformers.models.llava_next.processing_llava_next.LlavaNextProcessor._get_number_of_features
221
+ def _get_number_of_features(self, orig_height: int, orig_width: int, height: int, width: int) -> int:
222
+ image_grid_pinpoints = self.image_processor.image_grid_pinpoints
223
+
224
+ height_best_resolution, width_best_resolution = select_best_resolution(
225
+ [orig_height, orig_width], image_grid_pinpoints
226
+ )
227
+ scale_height, scale_width = height_best_resolution // height, width_best_resolution // width
228
+
229
+ patches_height = height // self.patch_size
230
+ patches_width = width // self.patch_size
231
+ unpadded_features, newline_features = self._get_unpadded_features(
232
+ orig_height, orig_width, patches_height, patches_width, scale_height, scale_width
233
+ )
234
+ # The base patch covers the entire image (+1 for the CLS)
235
+ base_features = patches_height * patches_width + self.num_additional_image_tokens
236
+ num_image_tokens = unpadded_features + newline_features + base_features
237
+ return num_image_tokens
238
+
239
+ # Copied from transformers.models.llava_next.processing_llava_next.LlavaNextProcessor._get_unpadded_features
240
+ def _get_unpadded_features(self, height, width, patches_height, patches_width, scale_height, scale_width):
241
+ """
242
+ Get number of features for a given image with height/width. LLaVA-NeXT is different from LLaVA
243
+ because it divided each image into patches depending on its resolution. Therefore we need to calculate how many
244
+ patches an image is divided into and get the number of features from that.
245
+ """
246
+ current_height = patches_height * scale_height
247
+ current_width = patches_width * scale_width
248
+
249
+ original_aspect_ratio = width / height
250
+ current_aspect_ratio = current_width / current_height
251
+ if original_aspect_ratio > current_aspect_ratio:
252
+ new_height = int(round(height * (current_width / width), 7))
253
+ padding = (current_height - new_height) // 2
254
+ current_height -= padding * 2
255
+ else:
256
+ new_width = int(round(width * (current_height / height), 7))
257
+ padding = (current_width - new_width) // 2
258
+ current_width -= padding * 2
259
+
260
+ unpadded_features = current_height * current_width
261
+ newline_features = current_height
262
+ return (unpadded_features, newline_features)
263
+
264
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
265
+ def batch_decode(self, *args, **kwargs):
266
+ """
267
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
268
+ refer to the docstring of this method for more information.
269
+ """
270
+ return self.tokenizer.batch_decode(*args, **kwargs)
271
+
272
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
273
+ def decode(self, *args, **kwargs):
274
+ """
275
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
276
+ the docstring of this method for more information.
277
+ """
278
+ return self.tokenizer.decode(*args, **kwargs)
279
+
280
+ @property
281
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
282
+ def model_input_names(self):
283
+ tokenizer_input_names = self.tokenizer.model_input_names
284
+ image_processor_input_names = self.image_processor.model_input_names
285
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
286
+
287
+
288
+ __all__ = ["LlavaNextVideoProcessor"]
vllm/lib/python3.10/site-packages/transformers/models/mamba/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mamba import *
22
+ from .modeling_mamba import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/mamba/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (533 Bytes). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mamba/__pycache__/configuration_mamba.cpython-310.pyc ADDED
Binary file (6.42 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mamba/__pycache__/modeling_mamba.cpython-310.pyc ADDED
Binary file (24.7 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mamba/configuration_mamba.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team.
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
+ """MAMBA configuration"""
16
+
17
+ import math
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class MambaConfig(PretrainedConfig):
27
+ """
28
+ This is the configuration class to store the configuration of a [`MambaModel`]. It is used to instantiate a MAMBA
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the MAMBA
31
+ [state-spaces/mamba-2.8b](https://huggingface.co/state-spaces/mamba-2.8b) architecture.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 50280):
39
+ Vocabulary size of the MAMBA model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`MambaModel`].
41
+ hidden_size (`int`, *optional*, defaults to 768):
42
+ Dimensionality of the embeddings and hidden states.
43
+ state_size (`int`, *optional*, defaults to 16): shape of the state space latents.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the model.
46
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
47
+ The epsilon to use in the layer normalization layers.
48
+ pad_token_id (`int`, *optional*, defaults to 0):
49
+ Padding token id.
50
+ bos_token_id (`int`, *optional*, defaults to 0):
51
+ The id of the beginning of sentence token in the vocabulary.
52
+ eos_token_id (`int`, *optional*, defaults to 0):
53
+ The id of the end of sentence token in the vocabulary.
54
+ expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size.
55
+ conv_kernel (`int`, *optional*, defaults to 4): Size of the convolution kernel.
56
+ use_bias (`bool`, *optional*, defaults to `False`):
57
+ Whether or not to use bias in ["in_proj", "out_proj"] of the mixer block
58
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
59
+ Whether or not to use bias in the convolution layer of the mixer block.
60
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ initializer_range (`float`, *optional*, defaults to 0.1):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ residual_in_fp32 (`bool`, *optional*, defaults to `True`):
65
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model
66
+ time_step_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
67
+ Rank of the discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
68
+ time_step_scale (`float`, *optional*, defaults to 1.0):
69
+ Scale used used to scale `dt_proj.bias`.
70
+ time_step_min (`float`, *optional*, defaults to 0.001):
71
+ Minimum `time_step` used to bound `dt_proj.bias`.
72
+ time_step_max (`float`, *optional*, defaults to 0.1):
73
+ Maximum `time_step` used to bound `dt_proj.bias`.
74
+ time_step_init_scheme (`float`, *optional*, defaults to `"random"`):
75
+ Init scheme used for `dt_proj.weight`. Should be one of `["random","uniform"]`
76
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
77
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
78
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `False`):
79
+ Whether or not to rescale `out_proj` weights when initializing.
80
+ use_cache (`bool`, *optional*, defaults to `True`):
81
+ Whether or not the cache should be used.
82
+ use_mambapy (`bool`, *optional*, defaults to `False`):
83
+ Determines the fallback strategy during training if the CUDA-based official implementation of Mamba is not avaiable. If `True`, the mamba.py implementation is used. If `False`, the naive and slower implementation is used. Consider switching to the naive version if memory is limited.
84
+
85
+
86
+ Example:
87
+
88
+ ```python
89
+ >>> from transformers import MambaConfig, MambaModel
90
+
91
+ >>> # Initializing a Mamba configuration
92
+ >>> configuration = MambaConfig()
93
+
94
+ >>> # Initializing a model (with random weights) from the configuration
95
+ >>> model = MambaModel(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```"""
100
+
101
+ model_type = "mamba"
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_size=50280,
106
+ hidden_size=768,
107
+ state_size=16,
108
+ num_hidden_layers=32,
109
+ layer_norm_epsilon=1e-5,
110
+ pad_token_id=0,
111
+ bos_token_id=0,
112
+ eos_token_id=0,
113
+ expand=2,
114
+ conv_kernel=4,
115
+ use_bias=False,
116
+ use_conv_bias=True,
117
+ hidden_act="silu",
118
+ initializer_range=0.1,
119
+ residual_in_fp32=True,
120
+ time_step_rank="auto",
121
+ time_step_scale=1.0,
122
+ time_step_min=0.001,
123
+ time_step_max=0.1,
124
+ time_step_init_scheme="random",
125
+ time_step_floor=1e-4,
126
+ rescale_prenorm_residual=False,
127
+ use_cache=True,
128
+ use_mambapy=False,
129
+ **kwargs,
130
+ ):
131
+ self.vocab_size = vocab_size
132
+ self.hidden_size = hidden_size
133
+ self.state_size = state_size
134
+ self.num_hidden_layers = num_hidden_layers
135
+ self.layer_norm_epsilon = layer_norm_epsilon
136
+ self.conv_kernel = conv_kernel
137
+ self.expand = expand
138
+ self.intermediate_size = int(expand * self.hidden_size)
139
+ self.bos_token_id = bos_token_id
140
+ self.eos_token_id = eos_token_id
141
+ self.pad_token_id = pad_token_id
142
+ self.use_bias = use_bias
143
+ self.use_conv_bias = use_conv_bias
144
+ self.hidden_act = hidden_act
145
+ self.initializer_range = initializer_range
146
+ self.time_step_rank = math.ceil(self.hidden_size / 16) if time_step_rank == "auto" else time_step_rank
147
+ self.time_step_scale = time_step_scale
148
+ self.time_step_min = time_step_min
149
+ self.time_step_max = time_step_max
150
+ self.time_step_init_scheme = time_step_init_scheme
151
+ self.time_step_floor = time_step_floor
152
+ self.rescale_prenorm_residual = rescale_prenorm_residual
153
+ self.residual_in_fp32 = residual_in_fp32
154
+ self.use_cache = use_cache
155
+ self.use_mambapy = use_mambapy
156
+
157
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs)
158
+
159
+
160
+ __all__ = ["MambaConfig"]
vllm/lib/python3.10/site-packages/transformers/models/mamba/modeling_mamba.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 state-spaces/mamba org and HuggingFace Inc. team.
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
+ """PyTorch MAMBA model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Any, Dict, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...cache_utils import MambaCache
28
+ from ...generation import GenerationMixin
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_code_sample_docstrings,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ )
37
+ from ...utils.import_utils import is_causal_conv1d_available, is_mamba_ssm_available, is_mambapy_available
38
+ from .configuration_mamba import MambaConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ if is_mambapy_available():
44
+ from mambapy.pscan import pscan
45
+ else:
46
+ pscan = None
47
+
48
+ if is_mamba_ssm_available():
49
+ from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, selective_scan_fn
50
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
51
+ else:
52
+ selective_state_update, selective_scan_fn, mamba_inner_fn = None, None, None
53
+
54
+ if is_causal_conv1d_available():
55
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
56
+ else:
57
+ causal_conv1d_update, causal_conv1d_fn = None, None
58
+
59
+ is_fast_path_available = all(
60
+ (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)
61
+ )
62
+
63
+ _CHECKPOINT_FOR_DOC = "state-spaces/mamba-130m-hf"
64
+ _CONFIG_FOR_DOC = "MambaConfig"
65
+
66
+
67
+ class MambaMixer(nn.Module):
68
+ """
69
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
70
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
71
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
72
+ and is why Mamba is called **selective** state spaces)
73
+ """
74
+
75
+ def __init__(self, config: MambaConfig, layer_idx: int):
76
+ super().__init__()
77
+ self.config = config
78
+ self.hidden_size = config.hidden_size
79
+ self.ssm_state_size = config.state_size
80
+ self.conv_kernel_size = config.conv_kernel
81
+ self.intermediate_size = config.intermediate_size
82
+ self.time_step_rank = int(config.time_step_rank)
83
+ self.layer_idx = layer_idx
84
+ self.use_conv_bias = config.use_conv_bias
85
+ self.conv1d = nn.Conv1d(
86
+ in_channels=self.intermediate_size,
87
+ out_channels=self.intermediate_size,
88
+ bias=config.use_conv_bias,
89
+ kernel_size=config.conv_kernel,
90
+ groups=self.intermediate_size,
91
+ padding=config.conv_kernel - 1,
92
+ )
93
+
94
+ self.activation = config.hidden_act
95
+ self.act = ACT2FN[config.hidden_act]
96
+
97
+ self.use_mambapy = config.use_mambapy
98
+
99
+ # projection of the input hidden states
100
+ self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=config.use_bias)
101
+ # selective projection used to make dt, B and C input dependant
102
+ self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False)
103
+ # time step projection (discretization)
104
+ self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True)
105
+
106
+ # S4D real initialization. These are not discretized!
107
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
108
+ A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :]
109
+ A = A.expand(self.intermediate_size, -1).contiguous()
110
+
111
+ self.A_log = nn.Parameter(torch.log(A))
112
+ self.D = nn.Parameter(torch.ones(self.intermediate_size))
113
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
114
+ self.use_bias = config.use_bias
115
+
116
+ if not is_fast_path_available:
117
+ if self.use_mambapy:
118
+ if is_mambapy_available():
119
+ logger.warning_once(
120
+ "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
121
+ " is None. Falling back to the mamba.py backend. To install follow https://github.com/state-spaces/mamba/#installation and"
122
+ " https://github.com/Dao-AILab/causal-conv1d"
123
+ )
124
+ else:
125
+ raise ImportError(
126
+ "use_mambapy is set to True but the mambapy package is not installed. To install it follow https://github.com/alxndrTL/mamba.py."
127
+ )
128
+ else:
129
+ logger.warning_once(
130
+ "The fast path is not available because one of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
131
+ " is None. Falling back to the sequential implementation of Mamba, as use_mambapy is set to False. To install follow https://github.com/state-spaces/mamba/#installation and"
132
+ " https://github.com/Dao-AILab/causal-conv1d. For the mamba.py backend, follow https://github.com/alxndrTL/mamba.py."
133
+ )
134
+
135
+ def cuda_kernels_forward(
136
+ self,
137
+ hidden_states: torch.Tensor,
138
+ cache_params: Optional[MambaCache] = None,
139
+ cache_position: Optional[torch.LongTensor] = None,
140
+ attention_mask: Optional[torch.LongTensor] = None,
141
+ ):
142
+ # 1. Gated MLP's linear projection
143
+ projected_states = self.in_proj(hidden_states).transpose(1, 2)
144
+
145
+ if self.training and cache_params is None: # Doesn't support outputting the states -> used for training
146
+ contextualized_states = mamba_inner_fn(
147
+ projected_states,
148
+ self.conv1d.weight,
149
+ self.conv1d.bias if self.use_conv_bias else None,
150
+ self.x_proj.weight,
151
+ self.dt_proj.weight,
152
+ self.out_proj.weight,
153
+ self.out_proj.bias.float() if self.use_bias else None,
154
+ -torch.exp(self.A_log.float()),
155
+ None, # input-dependent B
156
+ None, # input-dependent C
157
+ self.D.float(),
158
+ delta_bias=self.dt_proj.bias.float(),
159
+ delta_softplus=True,
160
+ )
161
+
162
+ else:
163
+ hidden_states, gate = projected_states.chunk(2, dim=1)
164
+
165
+ if attention_mask is not None:
166
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
167
+
168
+ # 2. Convolution sequence transformation
169
+ conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
170
+ if cache_params is not None and cache_position[0] > 0:
171
+ hidden_states = causal_conv1d_update(
172
+ hidden_states.squeeze(-1),
173
+ cache_params.conv_states[self.layer_idx],
174
+ conv_weights,
175
+ self.conv1d.bias,
176
+ self.activation,
177
+ )
178
+ hidden_states = hidden_states.unsqueeze(-1)
179
+ else:
180
+ if cache_params is not None:
181
+ conv_states = nn.functional.pad(
182
+ hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0)
183
+ )
184
+ cache_params.update_conv_state(self.layer_idx, conv_states, cache_position)
185
+ hidden_states = causal_conv1d_fn(
186
+ hidden_states, conv_weights, self.conv1d.bias, activation=self.activation
187
+ )
188
+
189
+ if attention_mask is not None:
190
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
191
+
192
+ # 3. State Space Model sequence transformation
193
+ # 3.a. input varying initialization of time_step, B and C
194
+ ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
195
+ time_step, B, C = torch.split(
196
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
197
+ )
198
+ discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2)
199
+
200
+ A = -torch.exp(self.A_log.float())
201
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
202
+ time_proj_bias = self.dt_proj.bias.float() if hasattr(self.dt_proj, "bias") else None
203
+ if cache_params is not None and cache_position[0] > 0:
204
+ scan_outputs = selective_state_update(
205
+ cache_params.ssm_states[self.layer_idx],
206
+ hidden_states[..., 0],
207
+ discrete_time_step[..., 0],
208
+ A,
209
+ B[:, 0],
210
+ C[:, 0],
211
+ self.D,
212
+ gate[..., 0],
213
+ time_proj_bias,
214
+ dt_softplus=True,
215
+ ).unsqueeze(-1)
216
+ else:
217
+ scan_outputs, ssm_state = selective_scan_fn(
218
+ hidden_states,
219
+ discrete_time_step,
220
+ A,
221
+ B.transpose(1, 2),
222
+ C.transpose(1, 2),
223
+ self.D.float(),
224
+ gate,
225
+ time_proj_bias,
226
+ delta_softplus=True,
227
+ return_last_state=True,
228
+ )
229
+ if ssm_state is not None and cache_params is not None:
230
+ cache_params.update_ssm_state(self.layer_idx, ssm_state)
231
+
232
+ # 4. Final linear projection
233
+ contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
234
+ return contextualized_states
235
+
236
+ # fmt: off
237
+ def slow_forward(self, input_states, cache_params: Optional[MambaCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.LongTensor] = None):
238
+ batch_size, seq_len, _ = input_states.shape
239
+ dtype = input_states.dtype
240
+ # 1. Gated MLP's linear projection
241
+ projected_states = self.in_proj(input_states).transpose(1, 2) # [batch, 2 * intermediate_size, seq_len]
242
+ hidden_states, gate = projected_states.chunk(2, dim=1)
243
+
244
+ if attention_mask is not None:
245
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
246
+
247
+ # 2. Convolution sequence transformation
248
+ if cache_params is not None:
249
+ ssm_state = cache_params.ssm_states[self.layer_idx].clone()
250
+ ssm_state = ssm_state.to(hidden_states.device)
251
+ # use `cache_position.shape[0]` to check whether we are in prefill
252
+ # stage, it's equivalent to check `cache_position[0] == 0`, which
253
+ # breaks dynamo fullgraph constraints
254
+ if cache_position.shape[0] == self.conv_kernel_size:
255
+ conv_state = nn.functional.pad(
256
+ hidden_states,
257
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
258
+ )
259
+
260
+ cache_params.update_conv_state(self.layer_idx, conv_state, cache_position)
261
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) # [batch, intermediate_size, seq_len]
262
+ else:
263
+ conv_state = cache_params.update_conv_state(self.layer_idx, hidden_states, cache_position)
264
+ conv_state = conv_state.to(self.conv1d.weight.device)
265
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
266
+ if self.use_conv_bias:
267
+ hidden_states += self.conv1d.bias
268
+ hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1) # [batch, intermediate_size, 1] : decoding
269
+ else:
270
+ ssm_state = torch.zeros(
271
+ (batch_size, self.intermediate_size, self.ssm_state_size),
272
+ device=hidden_states.device, dtype=dtype
273
+ )
274
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len]) # [batch, intermediate_size, seq_len]
275
+
276
+ if attention_mask is not None:
277
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
278
+
279
+ # 3. State Space Model sequence transformation
280
+ # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
281
+ ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
282
+ time_step, B, C = torch.split(
283
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
284
+ )
285
+ discrete_time_step = self.dt_proj(time_step) # [batch, seq_len, intermediate_size]
286
+ discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2) # [batch, intermediate_size, seq_len]
287
+
288
+ # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
289
+ A = -torch.exp(self.A_log.float()) # [intermediate_size, ssm_state_size]
290
+ discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None]) # [batch, intermediate_size, seq_len, ssm_state_size]
291
+ discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float() # [batch, intermediate_size, seq_len, ssm_state_size]
292
+ deltaB_u = discrete_B * hidden_states[:, :, :, None].float()
293
+
294
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
295
+ if self.use_mambapy and self.training and cache_params is None:
296
+ hs = pscan(discrete_A.transpose(1, 2), deltaB_u.transpose(1, 2)) # [batch, seq_len, intermediate_size, ssm_state_size]
297
+
298
+ scan_output = (hs @ C.unsqueeze(-1)).squeeze(3).transpose(1, 2) # [batch, intermediate_size, seq_len]
299
+ scan_output = scan_output + hidden_states * self.D[None, :, None]
300
+ scan_output = scan_output * self.act(gate)
301
+ else:
302
+ scan_outputs = []
303
+ for i in range(seq_len):
304
+ ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :] # [batch, intermediade_size, ssm_state]
305
+ scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1)) # [batch, intermediade_size, 1]
306
+ scan_outputs.append(scan_output[:, :, 0])
307
+ scan_output = torch.stack(scan_outputs, dim=-1) # [batch, seq_len, intermediade_size]
308
+ scan_output = scan_output + (hidden_states * self.D[None, :, None])
309
+ scan_output = (scan_output * self.act(gate))
310
+
311
+ if cache_params is not None:
312
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
313
+
314
+ # 4. Final linear projection
315
+ contextualized_states = self.out_proj(scan_output.transpose(1, 2)) # [batch, seq_len, hidden_size]
316
+ return contextualized_states
317
+ # fmt: on
318
+
319
+ def forward(
320
+ self,
321
+ hidden_states,
322
+ cache_params: Optional[MambaCache] = None,
323
+ cache_position: Optional[torch.LongTensor] = None,
324
+ attention_mask: Optional[torch.LongTensor] = None,
325
+ ):
326
+ if is_fast_path_available and "cuda" in self.x_proj.weight.device.type and not torch._dynamo.is_compiling():
327
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
328
+ return self.slow_forward(hidden_states, cache_params, cache_position, attention_mask)
329
+
330
+
331
+ class MambaRMSNorm(nn.Module):
332
+ def __init__(self, hidden_size, eps=1e-6):
333
+ """
334
+ MambaRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
335
+ """
336
+ super().__init__()
337
+ self.weight = nn.Parameter(torch.ones(hidden_size))
338
+ self.variance_epsilon = eps
339
+
340
+ def forward(self, hidden_states):
341
+ input_dtype = hidden_states.dtype
342
+ hidden_states = hidden_states.to(torch.float32)
343
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
344
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
345
+ return self.weight * hidden_states.to(input_dtype)
346
+
347
+ def extra_repr(self):
348
+ return f"{self.weight.shape[0]}, eps={self.variance_epsilon}"
349
+
350
+
351
+ class MambaBlock(nn.Module):
352
+ def __init__(self, config, layer_idx):
353
+ super().__init__()
354
+ self.config = config
355
+ self.layer_idx = layer_idx
356
+ self.residual_in_fp32 = config.residual_in_fp32
357
+ self.norm = MambaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
358
+ self.mixer = MambaMixer(config, layer_idx=layer_idx)
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states,
363
+ cache_params: Optional[MambaCache] = None,
364
+ cache_position: Optional[torch.LongTensor] = None,
365
+ attention_mask: Optional[torch.LongTensor] = None,
366
+ ):
367
+ residual = hidden_states
368
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
369
+ if self.residual_in_fp32:
370
+ residual = residual.to(torch.float32)
371
+
372
+ hidden_states = self.mixer(
373
+ hidden_states, cache_params=cache_params, cache_position=cache_position, attention_mask=attention_mask
374
+ )
375
+ hidden_states = residual + hidden_states
376
+ return hidden_states
377
+
378
+
379
+ class MambaPreTrainedModel(PreTrainedModel):
380
+ """
381
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
382
+ models.
383
+ """
384
+
385
+ config_class = MambaConfig
386
+ base_model_prefix = "backbone"
387
+ _no_split_modules = ["MambaBlock", "MambaMixer"]
388
+ supports_gradient_checkpointing = True
389
+ _is_stateful = True
390
+
391
+ def _init_weights(self, module):
392
+ """Initialize the weights."""
393
+ if isinstance(module, MambaMixer):
394
+ module.A_log._no_weight_decay = True
395
+ module.D._no_weight_decay = True
396
+
397
+ dt_init_std = self.config.time_step_rank**-0.5 * self.config.time_step_scale
398
+ if self.config.time_step_init_scheme == "constant":
399
+ nn.init.constant_(module.dt_proj.weight, dt_init_std)
400
+ elif self.config.time_step_init_scheme == "random":
401
+ nn.init.uniform_(module.dt_proj.weight, -dt_init_std, dt_init_std)
402
+
403
+ dt = torch.exp(
404
+ torch.rand(self.config.intermediate_size)
405
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
406
+ + math.log(self.config.time_step_min)
407
+ ).clamp(min=self.config.time_step_floor)
408
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
409
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
410
+ with torch.no_grad():
411
+ module.dt_proj.bias.copy_(inv_dt)
412
+ module.dt_proj.bias._no_reinit = True
413
+
414
+ if isinstance(module, nn.Linear):
415
+ if module.bias is not None:
416
+ if not getattr(module.bias, "_no_reinit", False):
417
+ nn.init.zeros_(module.bias)
418
+ elif isinstance(module, nn.Embedding):
419
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
420
+
421
+ if self.config.rescale_prenorm_residual:
422
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
423
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
424
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
425
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
426
+ #
427
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
428
+ for name, p in module.named_parameters():
429
+ if name in ["out_proj.weight"]:
430
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
431
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
432
+ # We need to reinit p since this code could be called multiple times
433
+ # Having just p *= scale would repeatedly scale it down
434
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
435
+ with torch.no_grad():
436
+ p /= math.sqrt(self.config.num_hidden_layers)
437
+
438
+
439
+ @dataclass
440
+ class MambaOutput(ModelOutput):
441
+ """
442
+ Class for the MAMBA model outputs.
443
+
444
+ Args:
445
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
446
+ Sequence of hidden-states at the output of the last layer of the model.
447
+ cache_params (`MambaCache`):
448
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
449
+ avoid providing the old `input_ids`.
450
+
451
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
452
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
453
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
454
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
455
+
456
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
457
+ """
458
+
459
+ last_hidden_state: Optional[torch.FloatTensor] = None
460
+ cache_params: Optional[MambaCache] = None
461
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
462
+
463
+
464
+ @dataclass
465
+ class MambaCausalLMOutput(ModelOutput):
466
+ """
467
+ Base class for causal language model (or autoregressive) outputs.
468
+
469
+ Args:
470
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
471
+ Language modeling loss (for next-token prediction).
472
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
473
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
474
+ cache_params (`MambaCache`):
475
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
476
+ avoid providing the old `input_ids`.
477
+
478
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
479
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
480
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
481
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
482
+
483
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
484
+ """
485
+
486
+ loss: Optional[torch.FloatTensor] = None
487
+ logits: Optional[torch.FloatTensor] = None
488
+ cache_params: Optional[MambaCache] = None
489
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
490
+
491
+
492
+ MAMBA_START_DOCSTRING = r"""
493
+
494
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
495
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
496
+ etc.)
497
+
498
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
499
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
500
+ and behavior.
501
+
502
+ Parameters:
503
+ config ([`MambaConfig`]): Model configuration class with all the parameters of the model.
504
+ Initializing with a config file does not load the weights associated with the model, only the
505
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
506
+ """
507
+
508
+ MAMBA_INPUTS_DOCSTRING = r"""
509
+ Args:
510
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
511
+ Indices of input sequence tokens in the vocabulary.
512
+
513
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
514
+ `input_ids`.
515
+
516
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
517
+ [`PreTrainedTokenizer.__call__`] for details.
518
+
519
+ [What are input IDs?](../glossary#input-ids)
520
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
521
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
522
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
523
+ model's internal embedding lookup matrix.
524
+ cache_params (`MambaCache`, *optional*):
525
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
526
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
527
+ use_cache (`bool`, *optional*):
528
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
529
+ output_hidden_states (`bool`, *optional*):
530
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
531
+ more detail.
532
+ return_dict (`bool`, *optional*):
533
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
534
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
535
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
536
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
537
+ the complete sequence length.
538
+ """
539
+
540
+
541
+ @add_start_docstrings(
542
+ "The bare MAMBA Model transformer outputting raw hidden-states without any specific head on top.",
543
+ MAMBA_START_DOCSTRING,
544
+ )
545
+ class MambaModel(MambaPreTrainedModel):
546
+ def __init__(self, config):
547
+ super().__init__(config)
548
+
549
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
550
+ self.layers = nn.ModuleList([MambaBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
551
+
552
+ self.gradient_checkpointing = False
553
+ self.norm_f = MambaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
554
+ # Initialize weights and apply final processing
555
+ self._register_load_state_dict_pre_hook(self.load_hook)
556
+ self.post_init()
557
+
558
+ def load_hook(self, state_dict, prefix, *args):
559
+ for k in state_dict:
560
+ if "embedding." in k:
561
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
562
+ break
563
+
564
+ def get_input_embeddings(self):
565
+ return self.embeddings
566
+
567
+ def set_input_embeddings(self, new_embeddings):
568
+ self.embeddings = new_embeddings
569
+
570
+ @add_start_docstrings_to_model_forward(MAMBA_INPUTS_DOCSTRING)
571
+ @add_code_sample_docstrings(
572
+ checkpoint=_CHECKPOINT_FOR_DOC,
573
+ output_type=MambaOutput,
574
+ config_class=_CONFIG_FOR_DOC,
575
+ )
576
+ def forward(
577
+ self,
578
+ input_ids: Optional[torch.LongTensor] = None,
579
+ inputs_embeds: Optional[torch.LongTensor] = None,
580
+ cache_params: Optional[MambaCache] = None,
581
+ use_cache: Optional[bool] = None,
582
+ output_hidden_states: Optional[bool] = None,
583
+ return_dict: Optional[bool] = None,
584
+ cache_position: Optional[torch.LongTensor] = None,
585
+ attention_mask: Optional[torch.LongTensor] = None,
586
+ ) -> Union[Tuple, MambaOutput]:
587
+ output_hidden_states = (
588
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
589
+ )
590
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
591
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
592
+
593
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
594
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
595
+
596
+ if inputs_embeds is None:
597
+ inputs_embeds = self.embeddings(input_ids)
598
+
599
+ if self.gradient_checkpointing and self.training and use_cache:
600
+ use_cache = False
601
+
602
+ if use_cache:
603
+ if cache_params is None:
604
+ cache_params = MambaCache(
605
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
606
+ )
607
+ cache_position = torch.arange(0, self.config.conv_kernel, device=inputs_embeds.device)
608
+ elif cache_position is None:
609
+ # cases when we do manual forward instead of using `model.generate` which will initiate
610
+ # `cache_position` and makes sure it is not None, throw error here instead of doing some
611
+ # hack to conjecture the current cache position
612
+ raise ValueError(
613
+ "You have to specify the `cache_position` manually when `use_cache=True` and `cache_params` is passed, "
614
+ "you don't have to pass a `cache_params` if you are in prefilling stage because in that case it will "
615
+ "be initialized for you automatically"
616
+ )
617
+ else:
618
+ cache_params = None
619
+
620
+ hidden_states = inputs_embeds
621
+ all_hidden_states = () if output_hidden_states else None
622
+ for mixer_block in self.layers:
623
+ if self.gradient_checkpointing and self.training:
624
+ hidden_states = self._gradient_checkpointing_func(
625
+ mixer_block.__call__, hidden_states, cache_params, cache_position, attention_mask
626
+ )
627
+ else:
628
+ hidden_states = mixer_block(
629
+ hidden_states,
630
+ cache_params=cache_params,
631
+ cache_position=cache_position,
632
+ attention_mask=attention_mask,
633
+ )
634
+
635
+ if output_hidden_states:
636
+ all_hidden_states = all_hidden_states + (hidden_states,)
637
+
638
+ hidden_states = self.norm_f(hidden_states)
639
+
640
+ if output_hidden_states:
641
+ all_hidden_states = all_hidden_states + (hidden_states,)
642
+
643
+ if not return_dict:
644
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
645
+
646
+ return MambaOutput(
647
+ last_hidden_state=hidden_states,
648
+ cache_params=cache_params if use_cache else None,
649
+ hidden_states=all_hidden_states,
650
+ )
651
+
652
+
653
+ @add_start_docstrings(
654
+ """
655
+ The MAMBA Model transformer with a language modeling head on top (linear layer with weights tied to the input
656
+ embeddings).
657
+ """,
658
+ MAMBA_START_DOCSTRING,
659
+ )
660
+ class MambaForCausalLM(MambaPreTrainedModel, GenerationMixin):
661
+ _tied_weights_keys = ["lm_head.weight"]
662
+
663
+ def __init__(self, config):
664
+ super().__init__(config)
665
+ self.backbone = MambaModel(config)
666
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
667
+ # Initialize weights and apply final processing
668
+ self.post_init()
669
+
670
+ def get_output_embeddings(self):
671
+ return self.lm_head
672
+
673
+ def set_output_embeddings(self, new_embeddings):
674
+ self.lm_head = new_embeddings
675
+
676
+ def get_input_embeddings(self):
677
+ return self.backbone.get_input_embeddings()
678
+
679
+ def set_input_embeddings(self, new_embeddings):
680
+ return self.backbone.set_input_embeddings(new_embeddings)
681
+
682
+ def _update_model_kwargs_for_generation(
683
+ self, outputs: ModelOutput, model_kwargs: Dict[str, Any], num_new_tokens: int = 1, **kwargs
684
+ ) -> Dict[str, Any]:
685
+ model_kwargs["cache_params"] = outputs.get("cache_params", None)
686
+ if (
687
+ model_kwargs.get("use_cache", True)
688
+ and "cache_position" in model_kwargs
689
+ and model_kwargs["cache_position"] is not None
690
+ ):
691
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
692
+
693
+ if "attention_mask" in model_kwargs:
694
+ attention_mask = model_kwargs["attention_mask"]
695
+ model_kwargs["attention_mask"] = torch.cat(
696
+ [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
697
+ )
698
+
699
+ return model_kwargs
700
+
701
+ def prepare_inputs_for_generation(
702
+ self,
703
+ input_ids,
704
+ inputs_embeds=None,
705
+ use_cache=None,
706
+ cache_params: Optional[MambaCache] = None,
707
+ cache_position: Optional[torch.LongTensor] = None,
708
+ attention_mask: Optional[torch.LongTensor] = None,
709
+ **kwargs,
710
+ ):
711
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
712
+
713
+ if use_cache:
714
+ # `cache_position` should have been initialized in `generate`
715
+ if cache_position is None:
716
+ raise ValueError(
717
+ "`cache_position` should not be None as it should have been initialized in "
718
+ "`model.generate`, you are responsible for passing in a valid `cache_position` if "
719
+ "you are calling `prepare_inputs_for_generation` directly with `use_cache=True`"
720
+ )
721
+ if cache_position[0] > 0:
722
+ input_ids = input_ids[:, -1].unsqueeze(-1)
723
+
724
+ if attention_mask is not None:
725
+ attention_mask = None
726
+
727
+ else:
728
+ # we initialize the `cache_position` to full size of `conv_states` at prefill stage
729
+ # considering padding will be applied when input length is shorter, and truncation
730
+ # will be applied when it is longer, so it will be equivalent to always have it match
731
+ # the length of `cache_params.conv_states`, which is `config.conv_kernel`
732
+ cache_position = torch.arange(0, self.config.conv_kernel, device=input_ids.device)
733
+
734
+ if inputs_embeds is not None and cache_params is None:
735
+ model_inputs = {"inputs_embeds": inputs_embeds}
736
+ else:
737
+ model_inputs = {"input_ids": input_ids.contiguous()}
738
+
739
+ model_inputs.update(
740
+ {
741
+ "cache_params": cache_params,
742
+ "use_cache": use_cache,
743
+ "cache_position": cache_position,
744
+ "attention_mask": attention_mask,
745
+ }
746
+ )
747
+ return model_inputs
748
+
749
+ @add_start_docstrings_to_model_forward(MAMBA_INPUTS_DOCSTRING)
750
+ @add_code_sample_docstrings(
751
+ checkpoint=_CHECKPOINT_FOR_DOC,
752
+ output_type=MambaCausalLMOutput,
753
+ config_class=_CONFIG_FOR_DOC,
754
+ )
755
+ def forward(
756
+ self,
757
+ input_ids: Optional[torch.LongTensor] = None,
758
+ attention_mask: Optional[torch.LongTensor] = None,
759
+ inputs_embeds: Optional[torch.FloatTensor] = None,
760
+ cache_params: Optional[MambaCache] = None,
761
+ labels: Optional[torch.LongTensor] = None,
762
+ output_hidden_states: Optional[bool] = None,
763
+ return_dict: Optional[bool] = None,
764
+ use_cache: Optional[bool] = None,
765
+ cache_position: Optional[torch.Tensor] = None,
766
+ **kwargs, # for now we need this for generation
767
+ ) -> Union[Tuple, MambaCausalLMOutput]:
768
+ r"""
769
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
770
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
771
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
772
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
773
+ """
774
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
775
+
776
+ mamba_outputs = self.backbone(
777
+ input_ids,
778
+ cache_params=cache_params,
779
+ inputs_embeds=inputs_embeds,
780
+ output_hidden_states=output_hidden_states,
781
+ return_dict=return_dict,
782
+ use_cache=use_cache,
783
+ cache_position=cache_position,
784
+ attention_mask=attention_mask,
785
+ )
786
+ hidden_states = mamba_outputs[0]
787
+
788
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
789
+
790
+ loss = None
791
+ if labels is not None:
792
+ # move labels to correct device to enable model parallelism
793
+ labels = labels.to(logits.device)
794
+ # Shift so that tokens < n predict n
795
+ shift_logits = logits[..., :-1, :].contiguous()
796
+ shift_labels = labels[..., 1:].contiguous()
797
+ # Flatten the tokens
798
+ loss_fct = CrossEntropyLoss()
799
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
800
+
801
+ if not return_dict:
802
+ output = (logits,) + mamba_outputs[1:]
803
+ return ((loss,) + output) if loss is not None else output
804
+
805
+ return MambaCausalLMOutput(
806
+ loss=loss,
807
+ logits=logits,
808
+ cache_params=mamba_outputs.cache_params,
809
+ hidden_states=mamba_outputs.hidden_states,
810
+ )
811
+
812
+
813
+ __all__ = ["MambaForCausalLM", "MambaModel", "MambaPreTrainedModel"]
vllm/lib/python3.10/site-packages/transformers/models/mistral3/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_mistral3 import *
22
+ from .modeling_mistral3 import *
23
+ from .processing_mistral3 import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/mistral3/__pycache__/modular_mistral3.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
vllm/lib/python3.10/site-packages/transformers/models/mistral3/configuration_mistral3.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ..auto import CONFIG_MAPPING, AutoConfig
19
+
20
+
21
+ class Mistral3Config(PretrainedConfig):
22
+ r"""
23
+ This is the configuration class to store the configuration of a [`Mistral3ForConditionalGeneration`]. It is used to instantiate an
24
+ Mistral3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
25
+ with the defaults will yield a similar configuration to that of
26
+ [mistralai/Mistral-Small-3.1-24B-Instruct-2503](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)
27
+
28
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
29
+ documentation from [`PretrainedConfig`] for more information.
30
+
31
+ Args:
32
+ vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `PixtralVisionConfig`):
33
+ The config object or dictionary of the vision backbone.
34
+ text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MistralConfig`):
35
+ The config object or dictionary of the text backbone.
36
+ image_token_index (`int`, *optional*, defaults to 10):
37
+ The image token index to encode the image prompt.
38
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
39
+ The activation function used by the multimodal projector.
40
+ vision_feature_layer (`Union[int, List[int]]`, *optional*, defaults to -1):
41
+ The index of the layer to select the vision feature. If multiple indices are provided,
42
+ the vision feature of the corresponding indices will be concatenated to form the
43
+ vision features.
44
+ multimodal_projector_bias (`bool`, *optional*, defaults to `False`):
45
+ Whether to use bias in the multimodal projector.
46
+ spatial_merge_size (`int`, *optional*, defaults to 2):
47
+ The downsampling factor for the spatial merge operation.
48
+
49
+ Example:
50
+
51
+ ```python
52
+ >>> from transformers import Mistral3ForConditionalGeneration, Mistral3Config, PixtralVisionConfig, MistralConfig
53
+
54
+ >>> # Initializing a Pixtral-vision config
55
+ >>> vision_config = PixtralVisionConfig()
56
+
57
+ >>> # Initializing a Mistral config
58
+ >>> text_config = MistralConfig()
59
+
60
+ >>> # Initializing a Mistral3 configuration
61
+ >>> configuration = Mistral3Config(vision_config, text_config)
62
+
63
+ >>> # Initializing a model from the mistral3.1 configuration
64
+ >>> model = Mistral3ForConditionalGeneration(configuration)
65
+
66
+ >>> # Accessing the model configuration
67
+ >>> configuration = model.config
68
+ ```"""
69
+
70
+ model_type = "mistral3"
71
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
72
+ is_composition = True
73
+
74
+ def __init__(
75
+ self,
76
+ vision_config=None,
77
+ text_config=None,
78
+ image_token_index=10,
79
+ projector_hidden_act="gelu",
80
+ vision_feature_layer=-1,
81
+ multimodal_projector_bias=False,
82
+ spatial_merge_size=2,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+ self.image_token_index = image_token_index
87
+ self.projector_hidden_act = projector_hidden_act
88
+
89
+ self.vision_feature_layer = vision_feature_layer
90
+
91
+ if isinstance(vision_config, dict):
92
+ vision_config["model_type"] = vision_config["model_type"] if "model_type" in vision_config else "pixtral"
93
+ vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
94
+ elif vision_config is None:
95
+ vision_config = CONFIG_MAPPING["pixtral"](
96
+ intermediate_size=4096,
97
+ hidden_size=1024,
98
+ patch_size=14,
99
+ image_size=1540,
100
+ num_hidden_layers=24,
101
+ num_attention_heads=16,
102
+ vocab_size=32000,
103
+ head_dim=64,
104
+ hidden_act="gelu",
105
+ )
106
+
107
+ self.vision_config = vision_config
108
+
109
+ if isinstance(text_config, dict):
110
+ text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "mistral"
111
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
112
+ elif text_config is None:
113
+ text_config = CONFIG_MAPPING["mistral"](
114
+ attention_dropout=0.0,
115
+ head_dim=128,
116
+ hidden_act="silu",
117
+ hidden_size=5120,
118
+ initializer_range=0.02,
119
+ intermediate_size=32768,
120
+ max_position_embeddings=131072,
121
+ model_type="mistral",
122
+ num_attention_heads=32,
123
+ num_hidden_layers=40,
124
+ num_key_value_heads=8,
125
+ rms_norm_eps=1e-05,
126
+ rope_theta=1000000000.0,
127
+ sliding_window=None,
128
+ use_cache=True,
129
+ vocab_size=131072,
130
+ )
131
+
132
+ self.text_config = text_config
133
+ self.multimodal_projector_bias = multimodal_projector_bias
134
+ self.spatial_merge_size = spatial_merge_size
135
+
136
+
137
+ __all__ = ["Mistral3Config"]
vllm/lib/python3.10/site-packages/transformers/models/mistral3/modular_mistral3.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...activations import ACT2FN
22
+ from ...utils import is_torchdynamo_compiling, logging
23
+ from ..llava.modeling_llava import LlavaCausalLMOutputWithPast, LlavaForConditionalGeneration
24
+ from ..mistral.modeling_mistral import MistralRMSNorm
25
+ from .configuration_mistral3 import Mistral3Config
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class Mistral3RMSNorm(MistralRMSNorm):
32
+ pass
33
+
34
+
35
+ class Mistral3PatchMerger(nn.Module):
36
+ """
37
+ Learned merging of spatial_merge_size ** 2 patches
38
+ """
39
+
40
+ def __init__(self, config: Mistral3Config):
41
+ super().__init__()
42
+ self.config = config
43
+
44
+ hidden_size = config.vision_config.hidden_size
45
+ self.spatial_merge_size = config.spatial_merge_size
46
+ self.patch_size = self.config.vision_config.patch_size
47
+ self.merging_layer = nn.Linear(hidden_size * self.spatial_merge_size**2, hidden_size, bias=False)
48
+
49
+ def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor) -> torch.Tensor:
50
+ image_sizes = [
51
+ (image_size[0] // self.patch_size, image_size[1] // self.patch_size) for image_size in image_sizes
52
+ ]
53
+
54
+ tokens_per_image = [h * w for h, w in image_sizes]
55
+ d = image_features.shape[-1]
56
+
57
+ permuted_tensor = []
58
+ for image_index, image_tokens in enumerate(image_features.split(tokens_per_image)):
59
+ # Reshape image_tokens into a 2D grid
60
+ h, w = image_sizes[image_index]
61
+ image_grid = image_tokens.view(h, w, d).permute(2, 0, 1).unsqueeze(0)
62
+ grid = torch.nn.functional.unfold(
63
+ image_grid, kernel_size=self.spatial_merge_size, stride=self.spatial_merge_size
64
+ )
65
+ grid = grid.view(d * self.spatial_merge_size**2, -1).t()
66
+ permuted_tensor.append(grid)
67
+
68
+ image_features = torch.cat(permuted_tensor, dim=0)
69
+ image_features = self.merging_layer(image_features)
70
+ return image_features
71
+
72
+
73
+ class Mistral3MultiModalProjector(nn.Module):
74
+ def __init__(self, config: Mistral3Config):
75
+ super().__init__()
76
+ self.norm = Mistral3RMSNorm(config.vision_config.hidden_size)
77
+ self.patch_merger = Mistral3PatchMerger(config)
78
+ # We have hidden_size * the number of vision feature layers
79
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
80
+ self.linear_1 = nn.Linear(
81
+ config.vision_config.hidden_size * num_feature_layers,
82
+ config.text_config.hidden_size,
83
+ bias=config.multimodal_projector_bias,
84
+ )
85
+ self.act = ACT2FN[config.projector_hidden_act]
86
+ self.linear_2 = nn.Linear(
87
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
88
+ )
89
+
90
+ def forward(self, image_features: torch.Tensor, image_sizes: torch.Tensor):
91
+ image_features = self.norm(image_features)
92
+ image_features = self.patch_merger(image_features, image_sizes)
93
+ hidden_states = self.linear_1(image_features)
94
+ hidden_states = self.act(hidden_states)
95
+ hidden_states = self.linear_2(hidden_states)
96
+ return hidden_states
97
+
98
+
99
+ class Mistral3CausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
100
+ pass
101
+
102
+
103
+ class Mistral3ForConditionalGeneration(LlavaForConditionalGeneration):
104
+ def get_image_features(
105
+ self,
106
+ pixel_values: torch.FloatTensor,
107
+ vision_feature_layer: Union[int, List[int]],
108
+ image_sizes: torch.Tensor,
109
+ **kwargs,
110
+ ):
111
+ """
112
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
113
+
114
+ Args:
115
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
116
+ The tensors corresponding to the input images.
117
+ vision_feature_layer (`Union[int, List[int]]`):
118
+ The index of the layer to select the vision feature. If multiple indices are provided,
119
+ the vision feature of the corresponding indices will be concatenated to form the
120
+ vision features.
121
+ image_sizes (`torch.Tensor`):
122
+ Tensor containing the image sizes as returned by the processor.
123
+ Returns:
124
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
125
+ """
126
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
127
+ # this is not memory efficient at all (output_hidden_states=True) will save all the hidden states.
128
+ image_outputs = self.vision_tower(pixel_values, image_sizes=image_sizes, output_hidden_states=True, **kwargs)
129
+ # If we have one vision feature layer, return the corresponding hidden states,
130
+ # otherwise, select the hidden states of each feature layer and concatenate them
131
+ if isinstance(vision_feature_layer, int):
132
+ selected_image_feature = image_outputs.hidden_states[vision_feature_layer]
133
+ else:
134
+ hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
135
+ selected_image_feature = torch.cat(hs_pool, dim=-1)
136
+
137
+ image_features = self.multi_modal_projector(selected_image_feature.squeeze(0), image_sizes)
138
+ return image_features
139
+
140
+ def forward(
141
+ self,
142
+ input_ids: torch.LongTensor = None,
143
+ pixel_values: torch.FloatTensor = None,
144
+ attention_mask: Optional[torch.Tensor] = None,
145
+ position_ids: Optional[torch.LongTensor] = None,
146
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
147
+ inputs_embeds: Optional[torch.FloatTensor] = None,
148
+ vision_feature_layer: Optional[Union[int, List[int]]] = None,
149
+ labels: Optional[torch.LongTensor] = None,
150
+ use_cache: Optional[bool] = None,
151
+ output_attentions: Optional[bool] = None,
152
+ output_hidden_states: Optional[bool] = None,
153
+ return_dict: Optional[bool] = None,
154
+ cache_position: Optional[torch.LongTensor] = None,
155
+ logits_to_keep: Union[int, torch.Tensor] = 0,
156
+ image_sizes: torch.Tensor = None,
157
+ **lm_kwargs,
158
+ ) -> Union[Tuple, Mistral3CausalLMOutputWithPast]:
159
+ r"""
160
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
161
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
162
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
163
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
164
+
165
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
166
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
167
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
168
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
169
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
170
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
171
+
172
+
173
+ Returns:
174
+
175
+ Example:
176
+
177
+ ```python
178
+ >>> from PIL import Image
179
+ >>> import requests
180
+ >>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration
181
+
182
+ >>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
183
+ >>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
184
+
185
+ >>> prompt = "<s>[INST][IMG]What is the image?[/INST]"
186
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
187
+ >>> image = Image.open(requests.get(url, stream=True).raw)
188
+
189
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
190
+
191
+ >>> # Generate
192
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
193
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
194
+ "What is the image?The image depicts two cats lying on a pink blanket."
195
+ ```"""
196
+
197
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
198
+ output_hidden_states = (
199
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
200
+ )
201
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
202
+ vision_feature_layer = (
203
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
204
+ )
205
+
206
+ if (input_ids is None) ^ (inputs_embeds is not None):
207
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
208
+
209
+ if pixel_values is not None and inputs_embeds is not None:
210
+ raise ValueError(
211
+ "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one"
212
+ )
213
+
214
+ if inputs_embeds is None:
215
+ inputs_embeds = self.get_input_embeddings()(input_ids)
216
+
217
+ if pixel_values is not None:
218
+ image_features = self.get_image_features(
219
+ pixel_values=pixel_values,
220
+ vision_feature_layer=vision_feature_layer,
221
+ image_sizes=image_sizes,
222
+ )
223
+
224
+ special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1)
225
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
226
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
227
+ n_image_tokens = (input_ids == self.config.image_token_index).sum()
228
+ n_image_features = image_features.shape[0] * image_features.shape[1]
229
+ raise ValueError(
230
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
231
+ )
232
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
233
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
234
+
235
+ outputs = self.language_model(
236
+ attention_mask=attention_mask,
237
+ position_ids=position_ids,
238
+ past_key_values=past_key_values,
239
+ inputs_embeds=inputs_embeds,
240
+ use_cache=use_cache,
241
+ output_attentions=output_attentions,
242
+ output_hidden_states=output_hidden_states,
243
+ return_dict=return_dict,
244
+ cache_position=cache_position,
245
+ logits_to_keep=logits_to_keep,
246
+ **lm_kwargs,
247
+ )
248
+
249
+ logits = outputs[0]
250
+
251
+ loss = None
252
+ if labels is not None:
253
+ # Shift so that tokens < n predict n
254
+ if attention_mask is not None:
255
+ # we use the input attention mask to shift the logits and labels, because it is 2D.
256
+ # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
257
+ shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device)
258
+ shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous()
259
+ shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous()
260
+ else:
261
+ shift_logits = logits[..., :-1, :].contiguous()
262
+ shift_labels = labels[..., 1:].contiguous()
263
+ # Flatten the tokens
264
+ loss_fct = nn.CrossEntropyLoss()
265
+ loss = loss_fct(
266
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
267
+ )
268
+
269
+ if not return_dict:
270
+ output = (logits,) + outputs[1:]
271
+ return (loss,) + output if loss is not None else output
272
+
273
+ return Mistral3CausalLMOutputWithPast(
274
+ loss=loss,
275
+ logits=logits,
276
+ past_key_values=outputs.past_key_values,
277
+ hidden_states=outputs.hidden_states,
278
+ attentions=outputs.attentions,
279
+ image_hidden_states=image_features if pixel_values is not None else None,
280
+ )
281
+
282
+
283
+ __all__ = [
284
+ "Mistral3PreTrainedModel", # noqa
285
+ "Mistral3ForConditionalGeneration",
286
+ ]
vllm/lib/python3.10/site-packages/transformers/models/oneformer/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_oneformer import *
22
+ from .image_processing_oneformer import *
23
+ from .modeling_oneformer import *
24
+ from .processing_oneformer import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
vllm/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (615 Bytes). View file