wanzin commited on
Commit
c98e0b1
·
verified ·
1 Parent(s): 6007ac1

Update configuration_llama.py

Browse files
Files changed (1) hide show
  1. configuration_llama.py +57 -38
configuration_llama.py CHANGED
@@ -17,14 +17,12 @@
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
- """ LLaMA model configuration"""
21
 
22
  from transformers.configuration_utils import PretrainedConfig
23
- from transformers.utils import logging
24
 
25
 
26
- logger = logging.get_logger(__name__)
27
-
28
  class LlamaConfig(PretrainedConfig):
29
  r"""
30
  This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
@@ -50,7 +48,7 @@ class LlamaConfig(PretrainedConfig):
50
  num_key_value_heads (`int`, *optional*):
51
  This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
  `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
- `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
  converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
  by meanpooling all the original heads within that group. For more details checkout [this
56
  paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
@@ -75,25 +73,58 @@ class LlamaConfig(PretrainedConfig):
75
  End of stream token id.
76
  pretraining_tp (`int`, *optional*, defaults to 1):
77
  Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
78
- document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
79
- necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
80
- issue](https://github.com/pytorch/pytorch/issues/76232).
81
  tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
  Whether to tie weight embeddings
83
  rope_theta (`float`, *optional*, defaults to 10000.0):
84
  The base period of the RoPE embeddings.
85
  rope_scaling (`Dict`, *optional*):
86
- Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
87
- strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
88
- `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
89
- `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
90
- these scaling strategies behave:
91
- https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
92
- experimental feature, subject to breaking API changes in future versions.
93
- attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  Whether to use a bias in the query, key, value and output projection layers during self-attention.
95
  attention_dropout (`float`, *optional*, defaults to 0.0):
96
  The dropout ratio for the attention probabilities.
 
 
 
 
97
 
98
  ```python
99
  >>> from transformers import LlamaModel, LlamaConfig
@@ -133,6 +164,8 @@ class LlamaConfig(PretrainedConfig):
133
  rope_scaling=None,
134
  attention_bias=False,
135
  attention_dropout=0.0,
 
 
136
  **kwargs,
137
  ):
138
  self.vocab_size = vocab_size
@@ -154,9 +187,15 @@ class LlamaConfig(PretrainedConfig):
154
  self.use_cache = use_cache
155
  self.rope_theta = rope_theta
156
  self.rope_scaling = rope_scaling
157
- self._rope_scaling_validation()
158
  self.attention_bias = attention_bias
159
  self.attention_dropout = attention_dropout
 
 
 
 
 
 
 
160
 
161
  super().__init__(
162
  pad_token_id=pad_token_id,
@@ -164,24 +203,4 @@ class LlamaConfig(PretrainedConfig):
164
  eos_token_id=eos_token_id,
165
  tie_word_embeddings=tie_word_embeddings,
166
  **kwargs,
167
- )
168
-
169
- def _rope_scaling_validation(self):
170
- """
171
- Validate the `rope_scaling` configuration.
172
- """
173
- if self.rope_scaling is None:
174
- return
175
-
176
- if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
177
- raise ValueError(
178
- "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
179
- )
180
- rope_scaling_type = self.rope_scaling.get("type", None)
181
- rope_scaling_factor = self.rope_scaling.get("factor", None)
182
- if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
183
- raise ValueError(
184
- f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
185
- )
186
- if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
187
- raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
 
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
+ """LLaMA model configuration"""
21
 
22
  from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
 
25
 
 
 
26
  class LlamaConfig(PretrainedConfig):
27
  r"""
28
  This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
 
48
  num_key_value_heads (`int`, *optional*):
49
  This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
  `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
  converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
  by meanpooling all the original heads within that group. For more details checkout [this
54
  paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
 
73
  End of stream token id.
74
  pretraining_tp (`int`, *optional*, defaults to 1):
75
  Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
76
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
77
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
78
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
79
  tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
  Whether to tie weight embeddings
81
  rope_theta (`float`, *optional*, defaults to 10000.0):
82
  The base period of the RoPE embeddings.
83
  rope_scaling (`Dict`, *optional*):
84
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
85
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
86
+ accordingly.
87
+ Expected contents:
88
+ `rope_type` (`str`):
89
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
90
+ 'llama3'], with 'default' being the original RoPE implementation.
91
+ `factor` (`float`, *optional*):
92
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
93
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
94
+ original maximum pre-trained length.
95
+ `original_max_position_embeddings` (`int`, *optional*):
96
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
97
+ pretraining.
98
+ `attention_factor` (`float`, *optional*):
99
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
100
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
101
+ `factor` field to infer the suggested value.
102
+ `beta_fast` (`float`, *optional*):
103
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
104
+ ramp function. If unspecified, it defaults to 32.
105
+ `beta_slow` (`float`, *optional*):
106
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
107
+ ramp function. If unspecified, it defaults to 1.
108
+ `short_factor` (`List[float]`, *optional*):
109
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
110
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
111
+ size divided by the number of attention heads divided by 2
112
+ `long_factor` (`List[float]`, *optional*):
113
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
114
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
+ size divided by the number of attention heads divided by 2
116
+ `low_freq_factor` (`float`, *optional*):
117
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
118
+ `high_freq_factor` (`float`, *optional*):
119
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
120
+ attention_bias (`bool`, *optional*, defaults to `False`):
121
  Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
  attention_dropout (`float`, *optional*, defaults to 0.0):
123
  The dropout ratio for the attention probabilities.
124
+ mlp_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
+ head_dim (`int`, *optional*):
127
+ The attention head dimension. If None, it will default to hidden_size // num_heads
128
 
129
  ```python
130
  >>> from transformers import LlamaModel, LlamaConfig
 
164
  rope_scaling=None,
165
  attention_bias=False,
166
  attention_dropout=0.0,
167
+ mlp_bias=False,
168
+ head_dim=None,
169
  **kwargs,
170
  ):
171
  self.vocab_size = vocab_size
 
187
  self.use_cache = use_cache
188
  self.rope_theta = rope_theta
189
  self.rope_scaling = rope_scaling
 
190
  self.attention_bias = attention_bias
191
  self.attention_dropout = attention_dropout
192
+ self.mlp_bias = mlp_bias
193
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
194
+ # Validate the correctness of rotary position embeddings parameters
195
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
196
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
197
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
198
+ rope_config_validation(self)
199
 
200
  super().__init__(
201
  pad_token_id=pad_token_id,
 
203
  eos_token_id=eos_token_id,
204
  tie_word_embeddings=tie_word_embeddings,
205
  **kwargs,
206
+ )