@tduncan / Nvidia-Optimization-Stack-VLLM Mirror · read-only / commits / 9db713a1dc
Fork 0

A high-throughput and memory-efficient inference and serving engine for LLMs

Mirrored from https://github.com/tduncan-lum/Nvidia-Optimization-Stack---VLLM.git

Synced Nov 16, 05:45 UTC

[Model] Add OLMo November 2024 model (#10503)

Shane A committed Nov 25, 2024 at 14:26 UTC 9db713a1dca7e1bc9b6ecf5303c63c7352c52a13
8 files changed +611 -2
docs/source/models/supported_models.rst
+5
@@ -234,6 +234,11 @@ Text Generation
234 - :code:`allenai/OLMo-1B-hf`, :code:`allenai/OLMo-7B-hf`, etc.
235 -
236 - ✅︎
237 + * - :code:`OLMo2ForCausalLM`
238 + - OLMo2
239 + - :code:`allenai/OLMo2-7B-1124`, etc.
240 + -
241 + - ✅︎
242 * - :code:`OLMoEForCausalLM`
243 - OLMoE
244 - :code:`allenai/OLMoE-1B-7B-0924`, :code:`allenai/OLMoE-1B-7B-0924-Instruct`, etc.
tests/distributed/test_pipeline_parallel.py
+1
@@ -167,6 +167,7 @@ TEXT_GENERATION_MODELS = {
167 "mosaicml/mpt-7b": PPTestSettings.fast(),
168 "nvidia/Minitron-8B-Base": PPTestSettings.fast(),
169 "allenai/OLMo-1B-hf": PPTestSettings.fast(),
170 + "shanearora/OLMo-7B-1124-hf": PPTestSettings.fast(),
171 "allenai/OLMoE-1B-7B-0924-Instruct": PPTestSettings.fast(),
172 "facebook/opt-iml-max-1.3b": PPTestSettings.fast(),
173 "OrionStarAI/Orion-14B-Chat": PPTestSettings.fast(trust_remote_code=True),
tests/models/registry.py
+1
@@ -93,6 +93,7 @@ _TEXT_GENERATION_EXAMPLE_MODELS = {
93 "MPTForCausalLM": _HfExamplesInfo("mosaicml/mpt-7b"),
94 "NemotronForCausalLM": _HfExamplesInfo("nvidia/Minitron-8B-Base"),
95 "OlmoForCausalLM": _HfExamplesInfo("allenai/OLMo-1B-hf"),
96 + "Olmo2ForCausalLM": _HfExamplesInfo("shanearora/OLMo-7B-1124-hf"),
97 "OlmoeForCausalLM": _HfExamplesInfo("allenai/OLMoE-1B-7B-0924-Instruct"),
98 "OPTForCausalLM": _HfExamplesInfo("facebook/opt-iml-max-1.3b"),
99 "OrionForCausalLM": _HfExamplesInfo("OrionStarAI/Orion-14B-Chat",
vllm/model_executor/models/olmo2.py new
+432
@@ -0,0 +1,432 @@
1 +# Adapted from
2 +# https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/modeling_olmo2.py
3 +# Copyright 2024 The vLLM team.
4 +# Copyright 2024 EleutherAI and the HuggingFace Inc. team. All rights reserved.
5 +#
6 +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
7 +# and OPT implementations in this library. It has been modified from its
8 +# original forms to accommodate minor architectural differences compared
9 +# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
10 +#
11 +# Licensed under the Apache License, Version 2.0 (the "License");
12 +# you may not use this file except in compliance with the License.
13 +# You may obtain a copy of the License at
14 +#
15 +# http://www.apache.org/licenses/LICENSE-2.0
16 +#
17 +# Unless required by applicable law or agreed to in writing, software
18 +# distributed under the License is distributed on an "AS IS" BASIS,
19 +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 +# See the License for the specific language governing permissions and
21 +# limitations under the License.
22 +"""Inference-only OLMo2 model compatible with HuggingFace weights."""
23 +
24 +from functools import partial
25 +from typing import Iterable, List, Optional, Tuple, Union
26 +
27 +import torch
28 +from torch import nn
29 +
30 +from vllm.attention import Attention, AttentionMetadata
31 +from vllm.config import VllmConfig
32 +from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
33 +from vllm.distributed.communication_op import tensor_model_parallel_all_gather
34 +from vllm.distributed.parallel_state import get_tensor_model_parallel_rank
35 +from vllm.distributed.utils import split_tensor_along_last_dim
36 +from vllm.model_executor.layers.activation import SiluAndMul
37 +from vllm.model_executor.layers.layernorm import RMSNorm
38 +from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
39 + QKVParallelLinear,
40 + RowParallelLinear)
41 +from vllm.model_executor.layers.logits_processor import LogitsProcessor
42 +from vllm.model_executor.layers.rotary_embedding import get_rope
43 +from vllm.model_executor.layers.sampler import Sampler, SamplerOutput
44 +from vllm.model_executor.layers.vocab_parallel_embedding import (
45 + ParallelLMHead, VocabParallelEmbedding)
46 +from vllm.model_executor.model_loader.weight_utils import default_weight_loader
47 +from vllm.model_executor.models.interfaces import SupportsPP
48 +from vllm.model_executor.models.utils import (
49 + is_pp_missing_parameter, make_empty_intermediate_tensors_factory,
50 + make_layers, maybe_prefix)
51 +from vllm.model_executor.sampling_metadata import SamplingMetadata
52 +from vllm.sequence import IntermediateTensors
53 +from vllm.transformers_utils.configs.olmo2 import Olmo2Config
54 +
55 +
56 +class Olmo2Attention(nn.Module):
57 + """
58 + This is the attention block where the output is computed as
59 + ``Attention(LN(x))`` in ``MLP(LN(x + Attention(LN(x))))``
60 + (plus another skip connection).
61 + """
62 +
63 + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
64 + super().__init__()
65 + self.config = vllm_config.model_config.hf_config
66 + assert isinstance(self.config, Olmo2Config)
67 +
68 + hidden_size = self.config.hidden_size
69 + self.tp_size = get_tensor_model_parallel_world_size()
70 + self.total_num_heads = self.config.num_attention_heads
71 +
72 + assert hidden_size % self.total_num_heads == 0
73 + assert self.total_num_heads % self.tp_size == 0
74 +
75 + self.num_heads = self.total_num_heads // self.tp_size
76 + self.total_num_kv_heads = (self.config.num_key_value_heads
77 + or self.total_num_heads)
78 + if self.total_num_kv_heads >= self.tp_size:
79 + assert self.total_num_kv_heads % self.tp_size == 0
80 + else:
81 + assert self.tp_size % self.total_num_kv_heads == 0
82 +
83 + self.num_kv_heads = max(1, self.total_num_kv_heads // self.tp_size)
84 + self.head_dim = hidden_size // self.total_num_heads
85 + self.q_size = self.num_heads * self.head_dim
86 + self.kv_size = self.num_kv_heads * self.head_dim
87 + self.max_position_embeddings = self.config.max_position_embeddings
88 + self.rope_theta = self.config.rope_theta
89 +
90 + # Attention input projection. Projects x -> (q, k, v)
91 + self.qkv_proj = QKVParallelLinear(
92 + hidden_size,
93 + self.head_dim,
94 + self.total_num_heads,
95 + self.total_num_kv_heads,
96 + bias=False,
97 + quant_config=vllm_config.quant_config,
98 + prefix=f"{prefix}.qkv_proj",
99 + )
100 +
101 + self.tp_rank = get_tensor_model_parallel_rank()
102 + self.k_norm = RMSNorm(
103 + self.total_num_kv_heads * self.head_dim,
104 + eps=self.config.rms_norm_eps,
105 + )
106 + self.q_norm = RMSNorm(self.config.hidden_size,
107 + eps=self.config.rms_norm_eps)
108 +
109 + # Rotary embeddings.
110 + self.rotary_emb = get_rope(
111 + self.head_dim,
112 + rotary_dim=self.head_dim,
113 + max_position=self.max_position_embeddings,
114 + base=self.rope_theta, # type: ignore
115 + )
116 + self.scaling = self.head_dim**-0.5
117 + self.attn = Attention(
118 + self.num_heads,
119 + self.head_dim,
120 + self.scaling,
121 + num_kv_heads=self.num_kv_heads,
122 + cache_config=vllm_config.cache_config,
123 + quant_config=vllm_config.quant_config,
124 + prefix=prefix,
125 + )
126 +
127 + # Attention output projection.
128 + self.o_proj = RowParallelLinear(
129 + self.total_num_heads * self.head_dim,
130 + hidden_size,
131 + bias=False,
132 + quant_config=vllm_config.quant_config,
133 + prefix=f"{prefix}.o_proj",
134 + )
135 +
136 + def _apply_qk_norm(self, q: torch.Tensor,
137 + k: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
138 + if self.tp_size > 1:
139 + q = tensor_model_parallel_all_gather(q.contiguous())
140 + k = tensor_model_parallel_all_gather(k.contiguous())
141 + q = self.q_norm.forward_native(q)
142 + k = self.k_norm.forward_native(k)
143 + if self.tp_size > 1:
144 + splitter = partial(split_tensor_along_last_dim,
145 + num_partitions=self.tp_size)
146 + q = splitter(q)[self.tp_rank]
147 + k = splitter(k)[self.tp_rank]
148 + return q, k
149 +
150 + def forward(
151 + self,
152 + positions: torch.Tensor,
153 + hidden_states: torch.Tensor,
154 + kv_cache: torch.Tensor,
155 + attn_metadata: AttentionMetadata,
156 + ) -> torch.Tensor:
157 + qkv, _ = self.qkv_proj(hidden_states)
158 + q, k, v = qkv.chunk(chunks=3, dim=-1)
159 + q, k = self._apply_qk_norm(q, k)
160 + q, k = self.rotary_emb(positions, q, k)
161 + attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
162 + output, _ = self.o_proj(attn_output)
163 + return output
164 +
165 +
166 +class Olmo2MLP(nn.Module):
167 + """
168 + This is the MLP block where the output is computed as
169 + ``MLP(x)`` in ``LN(MLP(x + LN(Attention(x))))``
170 + (plus another skip connection).
171 + """
172 +
173 + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
174 + super().__init__()
175 + config = vllm_config.model_config.hf_config
176 + assert isinstance(config, Olmo2Config)
177 + hidden_size = config.hidden_size
178 + intermediate_size = config.intermediate_size
179 +
180 + # Feed-forward input projection.
181 + self.gate_up_proj = MergedColumnParallelLinear(
182 + hidden_size,
183 + [intermediate_size] * 2,
184 + bias=False,
185 + quant_config=vllm_config.quant_config,
186 + prefix=f"{prefix}.gate_up_proj",
187 + )
188 +
189 + # Activation function.
190 + self.act_fn = SiluAndMul()
191 +
192 + # Feed-forward output projection.
193 + self.down_proj = RowParallelLinear(
194 + intermediate_size,
195 + hidden_size,
196 + bias=False,
197 + quant_config=vllm_config.quant_config,
198 + prefix=f"{prefix}.down_proj",
199 + )
200 +
201 + def forward(
202 + self,
203 + x: torch.Tensor,
204 + ) -> torch.Tensor:
205 + gate_up, _ = self.gate_up_proj(x)
206 + x = self.act_fn(gate_up)
207 + x, _ = self.down_proj(x)
208 + return x
209 +
210 +
211 +class Olmo2DecoderLayer(nn.Module):
212 + """
213 + This is a typical transformer block where the output is
214 + computed as ``MLP(LN(x + Attention(LN(x))))``
215 + (plus another skip connection).
216 + """
217 +
218 + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
219 + super().__init__()
220 + config = vllm_config.model_config.hf_config
221 + assert isinstance(config, Olmo2Config)
222 + # Attention block.
223 + self.self_attn = Olmo2Attention(vllm_config=vllm_config,
224 + prefix=f"{prefix}.self_attn")
225 +
226 + # MLP block.
227 + self.mlp = Olmo2MLP(vllm_config=vllm_config, prefix=f"{prefix}.mlp")
228 +
229 + # LayerNorm
230 + self.post_attention_layernorm = RMSNorm(config.hidden_size,
231 + eps=config.rms_norm_eps)
232 +
233 + self.post_feedforward_layernorm = RMSNorm(config.hidden_size,
234 + eps=config.rms_norm_eps)
235 +
236 + def forward(
237 + self,
238 + positions: torch.Tensor,
239 + hidden_states: torch.Tensor,
240 + kv_cache: torch.Tensor,
241 + attn_metadata: AttentionMetadata,
242 + ) -> torch.Tensor:
243 + # Attention block.
244 + residual = hidden_states
245 + hidden_states = self.self_attn(positions, hidden_states, kv_cache,
246 + attn_metadata)
247 + hidden_states = self.post_attention_layernorm(hidden_states)
248 + hidden_states = hidden_states + residual
249 +
250 + # MLP block.
251 + residual = hidden_states
252 + hidden_states = self.mlp(hidden_states)
253 + hidden_states = self.post_feedforward_layernorm(hidden_states)
254 + hidden_states = residual + hidden_states
255 + return hidden_states
256 +
257 +
258 +class Olmo2Model(nn.Module):
259 +
260 + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
261 + super().__init__()
262 + self.config = vllm_config.model_config.hf_config
263 + assert isinstance(self.config, Olmo2Config)
264 +
265 + self.embed_tokens = VocabParallelEmbedding(
266 + self.config.vocab_size,
267 + self.config.hidden_size,
268 + prefix=f"{prefix}.embed_tokens",
269 + )
270 + self.start_layer, self.end_layer, self.layers = make_layers(
271 + self.config.num_hidden_layers,
272 + lambda prefix: Olmo2DecoderLayer(vllm_config=vllm_config,
273 + prefix=prefix),
274 + prefix=f"{prefix}.layers",
275 + )
276 + self.norm = RMSNorm(
277 + self.config.hidden_size,
278 + eps=self.config.rms_norm_eps,
279 + )
280 + self.make_empty_intermediate_tensors = (
281 + make_empty_intermediate_tensors_factory(["hidden_states"],
282 + self.config.hidden_size))
283 +
284 + def forward(
285 + self,
286 + input_ids: torch.Tensor,
287 + positions: torch.Tensor,
288 + kv_caches: List[torch.Tensor],
289 + attn_metadata: AttentionMetadata,
290 + intermediate_tensors: Optional[IntermediateTensors],
291 + ) -> Union[torch.Tensor, IntermediateTensors]:
292 + """
293 + :param input_ids: A tensor of shape `(batch_size, seq_len)`.
294 + """
295 + if get_pp_group().is_first_rank:
296 + # Get embeddings of input.
297 + # shape: (batch_size, seq_len, d_model)
298 + inputs_embeds = self.embed_tokens(input_ids)
299 +
300 + # embed positions
301 + hidden_states = inputs_embeds
302 + else:
303 + assert intermediate_tensors is not None
304 + hidden_states = intermediate_tensors["hidden_states"]
305 + assert isinstance(hidden_states, torch.Tensor)
306 +
307 + # Apply blocks one-by-one.
308 + for i in range(self.start_layer, self.end_layer):
309 + # shape: (batch_size, seq_len, d_model)
310 + hidden_states = self.layers[i](
311 + positions,
312 + hidden_states,
313 + kv_caches[i - self.start_layer],
314 + attn_metadata,
315 + )
316 +
317 + if not get_pp_group().is_last_rank:
318 + return IntermediateTensors({"hidden_states": hidden_states})
319 +
320 + # Apply final layer norm.
321 + # shape: (batch_size, seq_len or 1, d_model)
322 + hidden_states = self.norm(hidden_states)
323 + return hidden_states
324 +
325 +
326 +class Olmo2ForCausalLM(nn.Module, SupportsPP):
327 + """
328 + Extremely barebones HF model wrapper.
329 + """
330 +
331 + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
332 + super().__init__()
333 + config = vllm_config.model_config.hf_config
334 + assert isinstance(config, Olmo2Config)
335 + self.config = config
336 + self.model = Olmo2Model(vllm_config=vllm_config,
337 + prefix=maybe_prefix(prefix, "model"))
338 + if config.tie_word_embeddings:
339 + self.lm_head = self.model.embed_tokens
340 + else:
341 + self.unpadded_vocab_size = config.vocab_size
342 + self.lm_head = ParallelLMHead(
343 + config.vocab_size,
344 + config.hidden_size,
345 + org_num_embeddings=config.vocab_size,
346 + quant_config=vllm_config.quant_config,
347 + prefix=maybe_prefix(prefix, "lm_head"),
348 + )
349 + self.logits_processor = LogitsProcessor(config.vocab_size)
350 + self.sampler = Sampler()
351 + self.make_empty_intermediate_tensors = (
352 + self.model.make_empty_intermediate_tensors)
353 +
354 + def forward(
355 + self,
356 + input_ids: torch.Tensor,
357 + positions: torch.Tensor,
358 + kv_caches: List[torch.Tensor],
359 + attn_metadata: AttentionMetadata,
360 + intermediate_tensors: Optional[IntermediateTensors] = None,
361 + ) -> Union[torch.Tensor, IntermediateTensors]:
362 + hidden_states = self.model(
363 + input_ids=input_ids,
364 + positions=positions,
365 + kv_caches=kv_caches,
366 + attn_metadata=attn_metadata,
367 + intermediate_tensors=intermediate_tensors,
368 + )
369 + return hidden_states
370 +
371 + def compute_logits(
372 + self,
373 + hidden_states: torch.Tensor,
374 + sampling_metadata: SamplingMetadata,
375 + ) -> Optional[torch.Tensor]:
376 + logits = self.logits_processor(self.lm_head, hidden_states,
377 + sampling_metadata)
378 + return logits
379 +
380 + def sample(
381 + self,
382 + logits: torch.Tensor,
383 + sampling_metadata: SamplingMetadata,
384 + ) -> Optional[SamplerOutput]:
385 + next_tokens = self.sampler(logits, sampling_metadata)
386 + return next_tokens
387 +
388 + def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
389 + stacked_params_mapping = [
390 + # (param_name, shard_name, shard_id)
391 + ("qkv_proj", "q_proj", "q"),
392 + ("qkv_proj", "k_proj", "k"),
393 + ("qkv_proj", "v_proj", "v"),
394 + ("gate_up_proj", "gate_proj", 0),
395 + ("gate_up_proj", "up_proj", 1),
396 + ]
397 +
398 + params_dict = dict(self.named_parameters(remove_duplicate=False))
399 + for name, loaded_weight in weights:
400 + if "rotary_emb.inv_freq" in name:
401 + continue
402 + if ("rotary_emb.cos_cached" in name
403 + or "rotary_emb.sin_cached" in name):
404 + # Models trained using ColossalAI may include these tensors in
405 + # the checkpoint. Skip them.
406 + continue
407 + if is_pp_missing_parameter(name, self):
408 + continue
409 + # With tie_word_embeddings, we can skip lm_head.weight
410 + # The weight might appear unnecessarily in the files if the model is
411 + # processed with quantization, LoRA, fine-tuning, etc.
412 + if self.config.tie_word_embeddings and "lm_head.weight" in name:
413 + continue
414 + for param_name, weight_name, shard_id in stacked_params_mapping:
415 + if weight_name not in name:
416 + continue
417 + name = name.replace(weight_name, param_name)
418 + # Skip loading extra bias for GPTQ models.
419 + if name.endswith(".bias") and name not in params_dict:
420 + continue
421 + param = params_dict[name]
422 + weight_loader = param.weight_loader # type: ignore
423 + weight_loader(param, loaded_weight, shard_id)
424 + break
425 + else:
426 + # Skip loading extra bias for GPTQ models.
427 + if name.endswith(".bias") and name not in params_dict:
428 + continue
429 + param = params_dict[name]
430 + weight_loader = getattr(param, "weight_loader",
431 + default_weight_loader)
432 + weight_loader(param, loaded_weight)
vllm/model_executor/models/registry.py
+1
@@ -74,6 +74,7 @@ _TEXT_GENERATION_MODELS = {
74 "MPTForCausalLM": ("mpt", "MPTForCausalLM"),
75 "NemotronForCausalLM": ("nemotron", "NemotronForCausalLM"),
76 "OlmoForCausalLM": ("olmo", "OlmoForCausalLM"),
77 + "Olmo2ForCausalLM": ("olmo2", "Olmo2ForCausalLM"),
78 "OlmoeForCausalLM": ("olmoe", "OlmoeForCausalLM"),
79 "OPTForCausalLM": ("opt", "OPTForCausalLM"),
80 "OrionForCausalLM": ("orion", "OrionForCausalLM"),
vllm/transformers_utils/config.py
+3 -2
@@ -28,8 +28,8 @@ from vllm.transformers_utils.configs import (ChatGLMConfig, DbrxConfig,
28 MedusaConfig, MllamaConfig,
29 MLPSpeculatorConfig, MPTConfig,
30 NemotronConfig, NVLM_D_Config,
31 - RWConfig, SolarConfig,
32 - UltravoxConfig)
31 + Olmo2Config, RWConfig,
32 + SolarConfig, UltravoxConfig)
33 # yapf: enable
34 from vllm.transformers_utils.utils import check_gguf_file
35 from vllm.utils import resolve_obj_by_qualname
@@ -62,6 +62,7 @@ _CONFIG_REGISTRY: Dict[str, Type[PretrainedConfig]] = {
62 "internvl_chat": InternVLChatConfig,
63 "nemotron": NemotronConfig,
64 "NVLM_D": NVLM_D_Config,
65 + "olmo2": Olmo2Config,
66 "solar": SolarConfig,
67 "ultravox": UltravoxConfig,
68 **_CONFIG_REGISTRY_OVERRIDE_HF
vllm/transformers_utils/configs/__init__.py
+2
@@ -15,6 +15,7 @@ from vllm.transformers_utils.configs.mlp_speculator import MLPSpeculatorConfig
15 from vllm.transformers_utils.configs.mpt import MPTConfig
16 from vllm.transformers_utils.configs.nemotron import NemotronConfig
17 from vllm.transformers_utils.configs.nvlm_d import NVLM_D_Config
18 +from vllm.transformers_utils.configs.olmo2 import Olmo2Config
19 from vllm.transformers_utils.configs.solar import SolarConfig
20 from vllm.transformers_utils.configs.ultravox import UltravoxConfig
21
@@ -33,6 +34,7 @@ __all__ = [
34 "MLPSpeculatorConfig",
35 "NemotronConfig",
36 "NVLM_D_Config",
37 + "Olmo2Config",
38 "SolarConfig",
39 "UltravoxConfig",
40 ]
\ No newline at end of file
vllm/transformers_utils/configs/olmo2.py new
+166
@@ -0,0 +1,166 @@
1 +# yapf: disable
2 +# ruff: noqa: E501
3 +# coding=utf-8
4 +# Copied from
5 +# https://github.com/huggingface/transformers/blob/main/src/transformers/models/olmo2/configuration_olmo2.py
6 +"""OLMo 2 configuration."""
7 +
8 +from transformers.configuration_utils import PretrainedConfig
9 +from transformers.utils import logging
10 +
11 +logger = logging.get_logger(__name__)
12 +
13 +
14 +class Olmo2Config(PretrainedConfig):
15 + r"""
16 + This is the configuration class to store the configuration of a [`Olmo2Model`]. It is used to instantiate an OLMo2
17 + model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
18 + defaults will yield a similar configuration to that of the [allenai/Olmo2-7B-1124-hf](https://huggingface.co/allenai/Olmo2-7B-1124-hf).
19 +
20 + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21 + documentation from [`PretrainedConfig`] for more information.
22 +
23 +
24 + Args:
25 + vocab_size (`int`, *optional*, defaults to 50304):
26 + Vocabulary size of the Olmo2 model. Defines the number of different tokens that can be represented by the
27 + `inputs_ids` passed when calling [`Olmo2Model`]
28 + hidden_size (`int`, *optional*, defaults to 4096):
29 + Dimension of the hidden representations.
30 + intermediate_size (`int`, *optional*, defaults to 11008):
31 + Dimension of the MLP representations.
32 + num_hidden_layers (`int`, *optional*, defaults to 32):
33 + Number of hidden layers in the Transformer decoder.
34 + num_attention_heads (`int`, *optional*, defaults to 32):
35 + Number of attention heads for each attention layer in the Transformer decoder.
36 + num_key_value_heads (`int`, *optional*):
37 + This is the number of key_value heads that should be used to implement Grouped Query Attention. If
38 + `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
39 + `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
40 + converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
41 + by meanpooling all the original heads within that group. For more details checkout [this
42 + paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
43 + `num_attention_heads`.
44 + hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
45 + The non-linear activation function (function or string) in the decoder.
46 + max_position_embeddings (`int`, *optional*, defaults to 2048):
47 + The maximum sequence length that this model might ever be used with.
48 + initializer_range (`float`, *optional*, defaults to 0.02):
49 + The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
50 + use_cache (`bool`, *optional*, defaults to `True`):
51 + Whether or not the model should return the last key/values attentions (not used by all models). Only
52 + relevant if `config.is_decoder=True`.
53 + pad_token_id (`int`, *optional*, defaults to 1):
54 + Padding token id.
55 + bos_token_id (`int`, *optional*):
56 + Beginning of stream token id.
57 + eos_token_id (`int`, *optional*, defaults to 50279):
58 + End of stream token id.
59 + tie_word_embeddings (`bool`, *optional*, defaults to `False`):
60 + Whether to tie weight embeddings
61 + rope_theta (`float`, *optional*, defaults to 10000.0):
62 + The base period of the RoPE embeddings.
63 + rope_scaling (`Dict`, *optional*):
64 + Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
65 + strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
66 + `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
67 + `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
68 + these scaling strategies behave:
69 + https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
70 + experimental feature, subject to breaking API changes in future versions.
71 + attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
72 + Whether to use a bias in the query, key, value and output projection layers during self-attention.
73 + attention_dropout (`float`, *optional*, defaults to 0.0):
74 + The dropout ratio for the attention probabilities.
75 + rms_norm_eps (`float`, *optional*, defaults to 1e-05):
76 + The epsilon used by the rms normalization layers.
77 +
78 + ```python
79 + >>> from transformers import Olmo2Model, Olmo2Config
80 +
81 + >>> # Initializing a Olmo2 7B style configuration
82 + >>> configuration = Olmo2Config()
83 +
84 + >>> # Initializing a model from the Olmo2 7B style configuration
85 + >>> model = Olmo2Model(configuration)
86 +
87 + >>> # Accessing the model configuration
88 + >>> configuration = model.config
89 + ```
90 + """
91 +
92 + model_type = "olmo2"
93 + keys_to_ignore_at_inference = ["past_key_values"]
94 +
95 + def __init__(
96 + self,
97 + vocab_size=50304,
98 + hidden_size=4096,
99 + intermediate_size=11008,
100 + num_hidden_layers=32,
101 + num_attention_heads=32,
102 + num_key_value_heads=None,
103 + hidden_act="silu",
104 + max_position_embeddings=2048,
105 + initializer_range=0.02,
106 + use_cache=True,
107 + pad_token_id=1,
108 + bos_token_id=None,
109 + eos_token_id=50279,
110 + tie_word_embeddings=False,
111 + rope_theta=10000.0,
112 + rope_scaling=None,
113 + attention_bias=False,
114 + attention_dropout=0.0,
115 + rms_norm_eps=1e-5,
116 + **kwargs,
117 + ):
118 + super().__init__(
119 + pad_token_id=pad_token_id,
120 + bos_token_id=bos_token_id,
121 + eos_token_id=eos_token_id,
122 + tie_word_embeddings=tie_word_embeddings,
123 + **kwargs,
124 + )
125 + self.vocab_size = vocab_size
126 + self.max_position_embeddings = max_position_embeddings
127 + self.hidden_size = hidden_size
128 + self.intermediate_size = intermediate_size
129 + self.num_hidden_layers = num_hidden_layers
130 + self.num_attention_heads = num_attention_heads
131 +
132 + # for backward compatibility
133 + if num_key_value_heads is None:
134 + num_key_value_heads = num_attention_heads
135 +
136 + self.num_key_value_heads = num_key_value_heads
137 + self.hidden_act = hidden_act
138 + self.initializer_range = initializer_range
139 + self.use_cache = use_cache
140 + self.rope_theta = rope_theta
141 + self.rope_scaling = rope_scaling
142 + self._rope_scaling_validation()
143 + self.attention_bias = attention_bias
144 + self.attention_dropout = attention_dropout
145 +
146 + self.rms_norm_eps = rms_norm_eps
147 +
148 + def _rope_scaling_validation(self):
149 + """
150 + Validate the `rope_scaling` configuration.
151 + """
152 + if self.rope_scaling is None:
153 + return
154 +
155 + if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
156 + raise ValueError(
157 + "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
158 + )
159 + rope_scaling_type = self.rope_scaling.get("type", None)
160 + rope_scaling_factor = self.rope_scaling.get("factor", None)
161 + if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
162 + raise ValueError(
163 + f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
164 + )
165 + if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
166 + raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")