shanearora
commited on
Commit
•
c52ca52
1
Parent(s):
62dcbf0
add model and config files from transformers PR
Browse files- configuration_olmo_1124.py +166 -0
- modeling_olmo_1124.py +1095 -0
configuration_olmo_1124.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/olmo_1124/modular_olmo_1124.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_olmo_1124.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
|
8 |
+
from ...configuration_utils import PretrainedConfig
|
9 |
+
|
10 |
+
|
11 |
+
class Olmo1124Config(PretrainedConfig):
|
12 |
+
r"""
|
13 |
+
This is the configuration class to store the configuration of a [`Olmo1124Model`]. It is used to instantiate an OLMo November 2024
|
14 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
15 |
+
defaults will yield a similar configuration to that of the [allenai/Olmo1124-7B-hf](https://huggingface.co/allenai/Olmo1124-7B-hf).
|
16 |
+
|
17 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
18 |
+
documentation from [`PretrainedConfig`] for more information.
|
19 |
+
|
20 |
+
|
21 |
+
Args:
|
22 |
+
vocab_size (`int`, *optional*, defaults to 50304):
|
23 |
+
Vocabulary size of the Olmo1124 model. Defines the number of different tokens that can be represented by the
|
24 |
+
`inputs_ids` passed when calling [`Olmo1124Model`]
|
25 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
26 |
+
Dimension of the hidden representations.
|
27 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
28 |
+
Dimension of the MLP representations.
|
29 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
30 |
+
Number of hidden layers in the Transformer decoder.
|
31 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
32 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
33 |
+
num_key_value_heads (`int`, *optional*):
|
34 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
35 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
36 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
37 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
38 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
39 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
40 |
+
`num_attention_heads`.
|
41 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
42 |
+
The non-linear activation function (function or string) in the decoder.
|
43 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
44 |
+
The maximum sequence length that this model might ever be used with.
|
45 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
46 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
47 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
48 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
49 |
+
relevant if `config.is_decoder=True`.
|
50 |
+
pad_token_id (`int`, *optional*, defaults to 1):
|
51 |
+
Padding token id.
|
52 |
+
bos_token_id (`int`, *optional*):
|
53 |
+
Beginning of stream token id.
|
54 |
+
eos_token_id (`int`, *optional*, defaults to 50279):
|
55 |
+
End of stream token id.
|
56 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
57 |
+
Whether to tie weight embeddings
|
58 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
59 |
+
The base period of the RoPE embeddings.
|
60 |
+
rope_scaling (`Dict`, *optional*):
|
61 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
62 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
63 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
64 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
65 |
+
these scaling strategies behave:
|
66 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
67 |
+
experimental feature, subject to breaking API changes in future versions.
|
68 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
69 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
70 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
71 |
+
The dropout ratio for the attention probabilities.
|
72 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-05):
|
73 |
+
The epsilon used by the rms normalization layers.
|
74 |
+
|
75 |
+
```python
|
76 |
+
>>> from transformers import Olmo1124Model, Olmo1124Config
|
77 |
+
|
78 |
+
>>> # Initializing a Olmo November 2024 7B style configuration
|
79 |
+
>>> configuration = Olmo1124Config()
|
80 |
+
|
81 |
+
>>> # Initializing a model from the Olmo November 2024 7B style configuration
|
82 |
+
>>> model = Olmo1124Model(configuration)
|
83 |
+
|
84 |
+
>>> # Accessing the model configuration
|
85 |
+
>>> configuration = model.config
|
86 |
+
```
|
87 |
+
"""
|
88 |
+
|
89 |
+
model_type = "olmo_1124"
|
90 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
91 |
+
|
92 |
+
def __init__(
|
93 |
+
self,
|
94 |
+
vocab_size=50304,
|
95 |
+
hidden_size=4096,
|
96 |
+
intermediate_size=11008,
|
97 |
+
num_hidden_layers=32,
|
98 |
+
num_attention_heads=32,
|
99 |
+
num_key_value_heads=None,
|
100 |
+
hidden_act="silu",
|
101 |
+
max_position_embeddings=2048,
|
102 |
+
initializer_range=0.02,
|
103 |
+
use_cache=True,
|
104 |
+
pad_token_id=1,
|
105 |
+
bos_token_id=None,
|
106 |
+
eos_token_id=50279,
|
107 |
+
tie_word_embeddings=False,
|
108 |
+
rope_theta=10000.0,
|
109 |
+
rope_scaling=None,
|
110 |
+
attention_bias=False,
|
111 |
+
attention_dropout=0.0,
|
112 |
+
rms_norm_eps=1e-5,
|
113 |
+
**kwargs,
|
114 |
+
):
|
115 |
+
super().__init__(
|
116 |
+
pad_token_id=pad_token_id,
|
117 |
+
bos_token_id=bos_token_id,
|
118 |
+
eos_token_id=eos_token_id,
|
119 |
+
tie_word_embeddings=tie_word_embeddings,
|
120 |
+
**kwargs,
|
121 |
+
)
|
122 |
+
self.vocab_size = vocab_size
|
123 |
+
self.max_position_embeddings = max_position_embeddings
|
124 |
+
self.hidden_size = hidden_size
|
125 |
+
self.intermediate_size = intermediate_size
|
126 |
+
self.num_hidden_layers = num_hidden_layers
|
127 |
+
self.num_attention_heads = num_attention_heads
|
128 |
+
|
129 |
+
# for backward compatibility
|
130 |
+
if num_key_value_heads is None:
|
131 |
+
num_key_value_heads = num_attention_heads
|
132 |
+
|
133 |
+
self.num_key_value_heads = num_key_value_heads
|
134 |
+
self.hidden_act = hidden_act
|
135 |
+
self.initializer_range = initializer_range
|
136 |
+
self.use_cache = use_cache
|
137 |
+
self.rope_theta = rope_theta
|
138 |
+
self.rope_scaling = rope_scaling
|
139 |
+
self._rope_scaling_validation()
|
140 |
+
self.attention_bias = attention_bias
|
141 |
+
self.attention_dropout = attention_dropout
|
142 |
+
|
143 |
+
self.rms_norm_eps = rms_norm_eps
|
144 |
+
|
145 |
+
def _rope_scaling_validation(self):
|
146 |
+
"""
|
147 |
+
Validate the `rope_scaling` configuration.
|
148 |
+
"""
|
149 |
+
if self.rope_scaling is None:
|
150 |
+
return
|
151 |
+
|
152 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
153 |
+
raise ValueError(
|
154 |
+
"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
|
155 |
+
)
|
156 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
157 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
158 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
159 |
+
raise ValueError(
|
160 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
161 |
+
)
|
162 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float)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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
2 |
+
# This file was automatically generated from src/transformers/models/olmo_1124/modular_olmo_1124.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_olmo_1124.py file directly. One of our CI enforces this.
|
6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
7 |
+
import math
|
8 |
+
from typing import List, Optional, Tuple, Union
|
9 |
+
|
10 |
+
import torch
|
11 |
+
from torch import nn
|
12 |
+
|
13 |
+
from ...activations import ACT2FN
|
14 |
+
from ...cache_utils import Cache, DynamicCache, StaticCache
|
15 |
+
from ...generation import GenerationMixin
|
16 |
+
from ...modeling_attn_mask_utils import AttentionMaskConverter
|
17 |
+
from ...modeling_flash_attention_utils import _flash_attention_forward
|
18 |
+
from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
19 |
+
from ...modeling_utils import PreTrainedModel
|
20 |
+
from ...utils import (
|
21 |
+
add_start_docstrings,
|
22 |
+
add_start_docstrings_to_model_forward,
|
23 |
+
is_flash_attn_2_available,
|
24 |
+
is_flash_attn_greater_or_equal_2_10,
|
25 |
+
logging,
|
26 |
+
replace_return_docstrings,
|
27 |
+
)
|
28 |
+
from .configuration_olmo_1124 import Olmo1124Config
|
29 |
+
|
30 |
+
|
31 |
+
if is_flash_attn_2_available():
|
32 |
+
from ...modeling_flash_attention_utils import _flash_attention_forward
|
33 |
+
|
34 |
+
|
35 |
+
logger = logging.get_logger(__name__)
|
36 |
+
|
37 |
+
_CONFIG_FOR_DOC = "Olmo1124Config"
|
38 |
+
|
39 |
+
|
40 |
+
class Olmo1124RMSNorm(nn.Module):
|
41 |
+
def __init__(self, hidden_size, eps=1e-6):
|
42 |
+
"""
|
43 |
+
Olmo1124RMSNorm is equivalent to T5LayerNorm
|
44 |
+
"""
|
45 |
+
super().__init__()
|
46 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
47 |
+
self.variance_epsilon = eps
|
48 |
+
|
49 |
+
def forward(self, hidden_states):
|
50 |
+
input_dtype = hidden_states.dtype
|
51 |
+
hidden_states = hidden_states.to(torch.float32)
|
52 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
53 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
54 |
+
return self.weight * hidden_states.to(input_dtype)
|
55 |
+
|
56 |
+
def extra_repr(self):
|
57 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
58 |
+
|
59 |
+
|
60 |
+
# copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Olmo1124
|
61 |
+
# TODO(joao): add me back asap :)
|
62 |
+
class Olmo1124RotaryEmbedding(nn.Module):
|
63 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
64 |
+
super().__init__()
|
65 |
+
self.scaling_factor = scaling_factor
|
66 |
+
self.dim = dim
|
67 |
+
self.max_position_embeddings = max_position_embeddings
|
68 |
+
self.base = base
|
69 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
|
70 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
71 |
+
# For BC we register cos and sin cached
|
72 |
+
self.max_seq_len_cached = max_position_embeddings
|
73 |
+
|
74 |
+
@torch.no_grad()
|
75 |
+
def forward(self, x, position_ids):
|
76 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
77 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
78 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
79 |
+
# Force float32 since bfloat16 loses precision on long contexts
|
80 |
+
# See https://github.com/huggingface/transformers/pull/29285
|
81 |
+
device_type = x.device.type
|
82 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
83 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
84 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
85 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
86 |
+
cos = emb.cos()
|
87 |
+
sin = emb.sin()
|
88 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
89 |
+
|
90 |
+
|
91 |
+
# copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->Olmo1124
|
92 |
+
# TODO(joao): add me back asap :)
|
93 |
+
class Olmo1124LinearScalingRotaryEmbedding(Olmo1124RotaryEmbedding):
|
94 |
+
"""Olmo1124RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
95 |
+
|
96 |
+
def forward(self, x, position_ids):
|
97 |
+
# difference to the original RoPE: a scaling factor is aplied to the position ids
|
98 |
+
position_ids = position_ids.float() / self.scaling_factor
|
99 |
+
cos, sin = super().forward(x, position_ids)
|
100 |
+
return cos, sin
|
101 |
+
|
102 |
+
|
103 |
+
# copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->Olmo1124
|
104 |
+
# TODO(joao): add me back asap :)
|
105 |
+
class Olmo1124DynamicNTKScalingRotaryEmbedding(Olmo1124RotaryEmbedding):
|
106 |
+
"""Olmo1124RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
107 |
+
|
108 |
+
def forward(self, x, position_ids):
|
109 |
+
# difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
|
110 |
+
seq_len = torch.max(position_ids) + 1
|
111 |
+
if seq_len > self.max_position_embeddings:
|
112 |
+
base = self.base * (
|
113 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
114 |
+
) ** (self.dim / (self.dim - 2))
|
115 |
+
inv_freq = 1.0 / (
|
116 |
+
base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
|
117 |
+
)
|
118 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
|
119 |
+
|
120 |
+
cos, sin = super().forward(x, position_ids)
|
121 |
+
return cos, sin
|
122 |
+
|
123 |
+
|
124 |
+
def rotate_half(x):
|
125 |
+
"""Rotates half the hidden dims of the input."""
|
126 |
+
x1 = x[..., : x.shape[-1] // 2]
|
127 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
128 |
+
return torch.cat((-x2, x1), dim=-1)
|
129 |
+
|
130 |
+
|
131 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
132 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
133 |
+
|
134 |
+
Args:
|
135 |
+
q (`torch.Tensor`): The query tensor.
|
136 |
+
k (`torch.Tensor`): The key tensor.
|
137 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
138 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
139 |
+
position_ids (`torch.Tensor`, *optional*):
|
140 |
+
Deprecated and unused.
|
141 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
142 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
143 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
144 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
145 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
146 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
147 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
148 |
+
Returns:
|
149 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
150 |
+
"""
|
151 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
152 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
153 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
154 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
155 |
+
return q_embed, k_embed
|
156 |
+
|
157 |
+
|
158 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
159 |
+
"""
|
160 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
161 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
162 |
+
"""
|
163 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
164 |
+
if n_rep == 1:
|
165 |
+
return hidden_states
|
166 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
167 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
168 |
+
|
169 |
+
|
170 |
+
class Olmo1124Attention(nn.Module):
|
171 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
172 |
+
|
173 |
+
# copied from transformers.models.llama.modeling_llama.LlamaAttention.__init__ with Llama->Olmo1124
|
174 |
+
# TODO(joao): add me back asap :)
|
175 |
+
def __init__(self, config: Olmo1124Config, layer_idx: Optional[int] = None):
|
176 |
+
super().__init__()
|
177 |
+
self.config = config
|
178 |
+
self.layer_idx = layer_idx
|
179 |
+
if layer_idx is None:
|
180 |
+
logger.warning_once(
|
181 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
182 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
183 |
+
"when creating this class."
|
184 |
+
)
|
185 |
+
|
186 |
+
self.attention_dropout = config.attention_dropout
|
187 |
+
self.hidden_size = config.hidden_size
|
188 |
+
self.num_heads = config.num_attention_heads
|
189 |
+
self.head_dim = self.hidden_size // self.num_heads
|
190 |
+
self.num_key_value_heads = config.num_key_value_heads
|
191 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
192 |
+
self.max_position_embeddings = config.max_position_embeddings
|
193 |
+
self.rope_theta = config.rope_theta
|
194 |
+
self.is_causal = True
|
195 |
+
|
196 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
197 |
+
raise ValueError(
|
198 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
199 |
+
f" and `num_heads`: {self.num_heads})."
|
200 |
+
)
|
201 |
+
|
202 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
203 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
204 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
205 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
|
206 |
+
self._init_rope()
|
207 |
+
self.q_norm = Olmo1124RMSNorm(self.num_heads * self.head_dim, config.rms_norm_eps)
|
208 |
+
self.k_norm = Olmo1124RMSNorm(self.num_key_value_heads * self.head_dim, config.rms_norm_eps)
|
209 |
+
|
210 |
+
def _init_rope(self):
|
211 |
+
if self.config.rope_scaling is None:
|
212 |
+
self.rotary_emb = Olmo1124RotaryEmbedding(
|
213 |
+
self.head_dim,
|
214 |
+
max_position_embeddings=self.max_position_embeddings,
|
215 |
+
base=self.rope_theta,
|
216 |
+
)
|
217 |
+
else:
|
218 |
+
scaling_type = self.config.rope_scaling["type"]
|
219 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
220 |
+
if scaling_type == "linear":
|
221 |
+
self.rotary_emb = Olmo1124LinearScalingRotaryEmbedding(
|
222 |
+
self.head_dim,
|
223 |
+
max_position_embeddings=self.max_position_embeddings,
|
224 |
+
scaling_factor=scaling_factor,
|
225 |
+
base=self.rope_theta,
|
226 |
+
)
|
227 |
+
elif scaling_type == "dynamic":
|
228 |
+
self.rotary_emb = Olmo1124DynamicNTKScalingRotaryEmbedding(
|
229 |
+
self.head_dim,
|
230 |
+
max_position_embeddings=self.max_position_embeddings,
|
231 |
+
scaling_factor=scaling_factor,
|
232 |
+
base=self.rope_theta,
|
233 |
+
)
|
234 |
+
else:
|
235 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
236 |
+
|
237 |
+
def forward(
|
238 |
+
self,
|
239 |
+
hidden_states: torch.Tensor,
|
240 |
+
attention_mask: Optional[torch.Tensor] = None,
|
241 |
+
position_ids: Optional[torch.LongTensor] = None,
|
242 |
+
past_key_value: Optional[Cache] = None,
|
243 |
+
output_attentions: bool = False,
|
244 |
+
use_cache: bool = False,
|
245 |
+
cache_position: Optional[torch.LongTensor] = None,
|
246 |
+
**kwargs,
|
247 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
248 |
+
bsz, q_len, _ = hidden_states.size()
|
249 |
+
|
250 |
+
query_states = self.q_norm(self.q_proj(hidden_states))
|
251 |
+
key_states = self.k_norm(self.k_proj(hidden_states))
|
252 |
+
value_states = self.v_proj(hidden_states)
|
253 |
+
|
254 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
255 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
256 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
257 |
+
|
258 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
259 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
260 |
+
|
261 |
+
if past_key_value is not None:
|
262 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
263 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
264 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
265 |
+
|
266 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
267 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
268 |
+
|
269 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
270 |
+
|
271 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
272 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
273 |
+
attn_weights = attn_weights + causal_mask
|
274 |
+
|
275 |
+
# upcast attention to fp32
|
276 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
277 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
278 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
279 |
+
|
280 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
281 |
+
raise ValueError(
|
282 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
283 |
+
f" {attn_output.size()}"
|
284 |
+
)
|
285 |
+
|
286 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
287 |
+
|
288 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
289 |
+
|
290 |
+
attn_output = self.o_proj(attn_output)
|
291 |
+
|
292 |
+
if not output_attentions:
|
293 |
+
attn_weights = None
|
294 |
+
|
295 |
+
return attn_output, attn_weights, past_key_value
|
296 |
+
|
297 |
+
|
298 |
+
class Olmo1124FlashAttention2(Olmo1124Attention):
|
299 |
+
"""
|
300 |
+
Olmo1124 flash attention module. This module inherits from `Olmo1124Attention` as the weights of the module stays
|
301 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
302 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
303 |
+
|
304 |
+
OLMo November 2024 flash attention module. This module inherits from `Olmo1124Attention` as the weights of the module stays
|
305 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
306 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
307 |
+
"""
|
308 |
+
|
309 |
+
def __init__(self, *args, **kwargs):
|
310 |
+
super().__init__(*args, **kwargs)
|
311 |
+
|
312 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
313 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, 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.
|
314 |
+
# 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).
|
315 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
316 |
+
|
317 |
+
def forward(
|
318 |
+
self,
|
319 |
+
hidden_states: torch.Tensor,
|
320 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
321 |
+
position_ids: Optional[torch.LongTensor] = None,
|
322 |
+
past_key_value: Optional[Cache] = None,
|
323 |
+
output_attentions: bool = False,
|
324 |
+
use_cache: bool = False,
|
325 |
+
cache_position: Optional[torch.LongTensor] = None,
|
326 |
+
**kwargs,
|
327 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
328 |
+
output_attentions = False
|
329 |
+
|
330 |
+
bsz, q_len, _ = hidden_states.size()
|
331 |
+
|
332 |
+
query_states = self.q_norm(self.q_proj(hidden_states))
|
333 |
+
key_states = self.k_norm(self.k_proj(hidden_states))
|
334 |
+
value_states = self.v_proj(hidden_states)
|
335 |
+
|
336 |
+
# Flash attention requires the input to have the shape
|
337 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
338 |
+
# therefore we just need to keep the original shape
|
339 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
340 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
341 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
342 |
+
|
343 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
344 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
345 |
+
|
346 |
+
if past_key_value is not None:
|
347 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
348 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
349 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
350 |
+
|
351 |
+
# 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
|
352 |
+
# to be able to avoid many of these transpose/reshape/view.
|
353 |
+
query_states = query_states.transpose(1, 2)
|
354 |
+
key_states = key_states.transpose(1, 2)
|
355 |
+
value_states = value_states.transpose(1, 2)
|
356 |
+
|
357 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
358 |
+
|
359 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
360 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
361 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
362 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
363 |
+
# in fp32. (OlmoRMSNorm handles it correctly)
|
364 |
+
|
365 |
+
input_dtype = query_states.dtype
|
366 |
+
if input_dtype == torch.float32:
|
367 |
+
if torch.is_autocast_enabled():
|
368 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
369 |
+
# Handle the case where the model is quantized
|
370 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
371 |
+
target_dtype = self.config._pre_quantization_dtype
|
372 |
+
else:
|
373 |
+
target_dtype = self.q_proj.weight.dtype
|
374 |
+
|
375 |
+
logger.warning_once(
|
376 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
377 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
378 |
+
f" {target_dtype}."
|
379 |
+
)
|
380 |
+
|
381 |
+
query_states = query_states.to(target_dtype)
|
382 |
+
key_states = key_states.to(target_dtype)
|
383 |
+
value_states = value_states.to(target_dtype)
|
384 |
+
|
385 |
+
attn_output = _flash_attention_forward(
|
386 |
+
query_states,
|
387 |
+
key_states,
|
388 |
+
value_states,
|
389 |
+
attention_mask,
|
390 |
+
q_len,
|
391 |
+
position_ids=position_ids,
|
392 |
+
dropout=dropout_rate,
|
393 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
394 |
+
is_causal=self.is_causal,
|
395 |
+
)
|
396 |
+
|
397 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
398 |
+
attn_output = self.o_proj(attn_output)
|
399 |
+
|
400 |
+
if not output_attentions:
|
401 |
+
attn_weights = None
|
402 |
+
|
403 |
+
return attn_output, attn_weights, past_key_value
|
404 |
+
|
405 |
+
|
406 |
+
class Olmo1124SdpaAttention(Olmo1124Attention):
|
407 |
+
"""
|
408 |
+
Olmo1124 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
409 |
+
`Olmo1124Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
410 |
+
SDPA API.
|
411 |
+
"""
|
412 |
+
|
413 |
+
# Adapted from Olmo1124Attention.forward
|
414 |
+
def forward(
|
415 |
+
self,
|
416 |
+
hidden_states: torch.Tensor,
|
417 |
+
attention_mask: Optional[torch.Tensor] = None,
|
418 |
+
position_ids: Optional[torch.LongTensor] = None,
|
419 |
+
past_key_value: Optional[Cache] = None,
|
420 |
+
output_attentions: bool = False,
|
421 |
+
use_cache: bool = False,
|
422 |
+
cache_position: Optional[torch.LongTensor] = None,
|
423 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
424 |
+
if output_attentions:
|
425 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
426 |
+
logger.warning_once(
|
427 |
+
"Olmo1124Model is using Olmo1124SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
428 |
+
'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.'
|
429 |
+
)
|
430 |
+
return super().forward(
|
431 |
+
hidden_states=hidden_states,
|
432 |
+
attention_mask=attention_mask,
|
433 |
+
position_ids=position_ids,
|
434 |
+
past_key_value=past_key_value,
|
435 |
+
output_attentions=output_attentions,
|
436 |
+
use_cache=use_cache,
|
437 |
+
cache_position=cache_position,
|
438 |
+
)
|
439 |
+
bsz, q_len, _ = hidden_states.size()
|
440 |
+
query_states = self.q_norm(self.q_proj(hidden_states))
|
441 |
+
key_states = self.k_norm(self.k_proj(hidden_states))
|
442 |
+
value_states = self.v_proj(hidden_states)
|
443 |
+
|
444 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
445 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
446 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
447 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
448 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
449 |
+
if past_key_value is not None:
|
450 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
451 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
452 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
453 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
454 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
455 |
+
causal_mask = attention_mask
|
456 |
+
# if attention_mask is not None and cache_position is not None:
|
457 |
+
if attention_mask is not None:
|
458 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
459 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
460 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
461 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
462 |
+
query_states = query_states.contiguous()
|
463 |
+
key_states = key_states.contiguous()
|
464 |
+
value_states = value_states.contiguous()
|
465 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
466 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
467 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
468 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
469 |
+
query_states,
|
470 |
+
key_states,
|
471 |
+
value_states,
|
472 |
+
attn_mask=causal_mask,
|
473 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
474 |
+
is_causal=is_causal,
|
475 |
+
)
|
476 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
477 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
478 |
+
attn_output = self.o_proj(attn_output)
|
479 |
+
return attn_output, None, past_key_value
|
480 |
+
|
481 |
+
|
482 |
+
class Olmo1124MLP(nn.Module):
|
483 |
+
def __init__(self, config):
|
484 |
+
super().__init__()
|
485 |
+
self.config = config
|
486 |
+
self.hidden_size = config.hidden_size
|
487 |
+
self.intermediate_size = config.intermediate_size
|
488 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
489 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
490 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
491 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
492 |
+
|
493 |
+
def forward(self, x):
|
494 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
495 |
+
|
496 |
+
|
497 |
+
OLMO_1124_ATTENTION_CLASSES = {
|
498 |
+
"eager": Olmo1124Attention,
|
499 |
+
"flash_attention_2": Olmo1124FlashAttention2,
|
500 |
+
"sdpa": Olmo1124SdpaAttention,
|
501 |
+
}
|
502 |
+
|
503 |
+
|
504 |
+
class Olmo1124DecoderLayer(nn.Module):
|
505 |
+
def __init__(self, config: Olmo1124Config, layer_idx: int):
|
506 |
+
super().__init__()
|
507 |
+
self.hidden_size = config.hidden_size
|
508 |
+
|
509 |
+
self.self_attn = OLMO_1124_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
510 |
+
|
511 |
+
self.mlp = Olmo1124MLP(config)
|
512 |
+
self.post_attention_layernorm = Olmo1124RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
513 |
+
self.post_feedforward_layernorm = Olmo1124RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
514 |
+
|
515 |
+
# copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer.forward
|
516 |
+
# TODO(joao): add me back asap :)
|
517 |
+
def forward(
|
518 |
+
self,
|
519 |
+
hidden_states: torch.Tensor,
|
520 |
+
attention_mask: Optional[torch.Tensor] = None,
|
521 |
+
position_ids: Optional[torch.LongTensor] = None,
|
522 |
+
past_key_value: Optional[Cache] = None,
|
523 |
+
output_attentions: Optional[bool] = False,
|
524 |
+
use_cache: Optional[bool] = False,
|
525 |
+
cache_position: Optional[torch.LongTensor] = None,
|
526 |
+
**kwargs,
|
527 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
528 |
+
"""
|
529 |
+
Args:
|
530 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
531 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
532 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
533 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
534 |
+
output_attentions (`bool`, *optional*):
|
535 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
536 |
+
returned tensors for more detail.
|
537 |
+
use_cache (`bool`, *optional*):
|
538 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
539 |
+
(see `past_key_values`).
|
540 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
541 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
542 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
543 |
+
kwargs (`dict`, *optional*):
|
544 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
545 |
+
into the model
|
546 |
+
"""
|
547 |
+
residual = hidden_states
|
548 |
+
|
549 |
+
# Self Attention
|
550 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
551 |
+
hidden_states=hidden_states,
|
552 |
+
attention_mask=attention_mask,
|
553 |
+
position_ids=position_ids,
|
554 |
+
past_key_value=past_key_value,
|
555 |
+
output_attentions=output_attentions,
|
556 |
+
use_cache=use_cache,
|
557 |
+
cache_position=cache_position,
|
558 |
+
**kwargs,
|
559 |
+
)
|
560 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
561 |
+
hidden_states = residual + hidden_states
|
562 |
+
|
563 |
+
# Fully Connected
|
564 |
+
residual = hidden_states
|
565 |
+
hidden_states = self.mlp(hidden_states)
|
566 |
+
hidden_states = self.post_feedforward_layernorm(hidden_states)
|
567 |
+
hidden_states = residual + hidden_states
|
568 |
+
|
569 |
+
outputs = (hidden_states,)
|
570 |
+
if output_attentions:
|
571 |
+
outputs += (self_attn_weights,)
|
572 |
+
if use_cache:
|
573 |
+
outputs += (present_key_value,)
|
574 |
+
return outputs
|
575 |
+
|
576 |
+
|
577 |
+
OLMO_1124_START_DOCSTRING = r"""
|
578 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
579 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
580 |
+
etc.)
|
581 |
+
|
582 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
583 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
584 |
+
and behavior.
|
585 |
+
|
586 |
+
Parameters:
|
587 |
+
config ([`Olmo1124Config`]):
|
588 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
589 |
+
load the weights associated with the model, only the configuration. Check out the
|
590 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
591 |
+
"""
|
592 |
+
|
593 |
+
|
594 |
+
@add_start_docstrings(
|
595 |
+
"The bare Olmo1124 Model outputting raw hidden-states without any specific head on top.",
|
596 |
+
OLMO_1124_START_DOCSTRING,
|
597 |
+
)
|
598 |
+
class Olmo1124PreTrainedModel(PreTrainedModel):
|
599 |
+
config_class = Olmo1124Config
|
600 |
+
base_model_prefix = "model"
|
601 |
+
supports_gradient_checkpointing = True
|
602 |
+
_no_split_modules = ["Olmo1124DecoderLayer"]
|
603 |
+
_skip_keys_device_placement = ["past_key_values"]
|
604 |
+
_supports_flash_attn_2 = True
|
605 |
+
_supports_sdpa = True
|
606 |
+
_supports_cache_class = True
|
607 |
+
_supports_quantized_cache = True
|
608 |
+
_supports_static_cache = True
|
609 |
+
|
610 |
+
def _init_weights(self, module):
|
611 |
+
std = self.config.initializer_range
|
612 |
+
if isinstance(module, nn.Linear):
|
613 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
614 |
+
if module.bias is not None:
|
615 |
+
module.bias.data.zero_()
|
616 |
+
elif isinstance(module, nn.Embedding):
|
617 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
618 |
+
if module.padding_idx is not None:
|
619 |
+
module.weight.data[module.padding_idx].zero_()
|
620 |
+
|
621 |
+
|
622 |
+
OLMO_1124_INPUTS_DOCSTRING = r"""
|
623 |
+
Args:
|
624 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
625 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
626 |
+
it.
|
627 |
+
|
628 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
629 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
630 |
+
|
631 |
+
[What are input IDs?](../glossary#input-ids)
|
632 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
633 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
634 |
+
|
635 |
+
- 1 for tokens that are **not masked**,
|
636 |
+
- 0 for tokens that are **masked**.
|
637 |
+
|
638 |
+
[What are attention masks?](../glossary#attention-mask)
|
639 |
+
|
640 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
641 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
642 |
+
|
643 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
644 |
+
`past_key_values`).
|
645 |
+
|
646 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
647 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
648 |
+
information on the default strategy.
|
649 |
+
|
650 |
+
- 1 indicates the head is **not masked**,
|
651 |
+
- 0 indicates the head is **masked**.
|
652 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
653 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
654 |
+
config.n_positions - 1]`.
|
655 |
+
|
656 |
+
[What are position IDs?](../glossary#position-ids)
|
657 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
658 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
659 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
660 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
661 |
+
|
662 |
+
Two formats are allowed:
|
663 |
+
- a [`~cache_utils.Cache`] instance, see our
|
664 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
665 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
666 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
667 |
+
cache format.
|
668 |
+
|
669 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
670 |
+
legacy cache format will be returned.
|
671 |
+
|
672 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
673 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
674 |
+
of shape `(batch_size, sequence_length)`.
|
675 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
676 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
677 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
678 |
+
model's internal embedding lookup matrix.
|
679 |
+
use_cache (`bool`, *optional*):
|
680 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
681 |
+
`past_key_values`).
|
682 |
+
output_attentions (`bool`, *optional*):
|
683 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
684 |
+
tensors for more detail.
|
685 |
+
output_hidden_states (`bool`, *optional*):
|
686 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
687 |
+
more detail.
|
688 |
+
return_dict (`bool`, *optional*):
|
689 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
690 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
691 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
692 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
693 |
+
the complete sequence length.
|
694 |
+
"""
|
695 |
+
|
696 |
+
|
697 |
+
@add_start_docstrings(
|
698 |
+
"The bare Olmo1124 Model outputting raw hidden-states without any specific head on top.",
|
699 |
+
OLMO_1124_START_DOCSTRING,
|
700 |
+
)
|
701 |
+
class Olmo1124Model(Olmo1124PreTrainedModel):
|
702 |
+
"""
|
703 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Olmo1124DecoderLayer`]
|
704 |
+
|
705 |
+
Args:
|
706 |
+
config: Olmo1124Config
|
707 |
+
"""
|
708 |
+
|
709 |
+
def __init__(self, config: Olmo1124Config):
|
710 |
+
super().__init__(config)
|
711 |
+
self.padding_idx = config.pad_token_id
|
712 |
+
self.vocab_size = config.vocab_size
|
713 |
+
|
714 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
715 |
+
self.layers = nn.ModuleList(
|
716 |
+
[Olmo1124DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
717 |
+
)
|
718 |
+
self.norm = Olmo1124RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
719 |
+
self.gradient_checkpointing = False
|
720 |
+
|
721 |
+
# Initialize weights and apply final processing
|
722 |
+
self.post_init()
|
723 |
+
|
724 |
+
def get_input_embeddings(self):
|
725 |
+
return self.embed_tokens
|
726 |
+
|
727 |
+
def set_input_embeddings(self, value):
|
728 |
+
self.embed_tokens = value
|
729 |
+
|
730 |
+
@add_start_docstrings_to_model_forward(OLMO_1124_INPUTS_DOCSTRING)
|
731 |
+
# copied from transformers.models.llama.modeling_llama.LlamaModel.forward
|
732 |
+
# TODO(joao): add me back asap :)
|
733 |
+
def forward(
|
734 |
+
self,
|
735 |
+
input_ids: torch.LongTensor = None,
|
736 |
+
attention_mask: Optional[torch.Tensor] = None,
|
737 |
+
position_ids: Optional[torch.LongTensor] = None,
|
738 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
739 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
740 |
+
use_cache: Optional[bool] = None,
|
741 |
+
output_attentions: Optional[bool] = None,
|
742 |
+
output_hidden_states: Optional[bool] = None,
|
743 |
+
return_dict: Optional[bool] = None,
|
744 |
+
cache_position: Optional[torch.LongTensor] = None,
|
745 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
746 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
747 |
+
output_hidden_states = (
|
748 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
749 |
+
)
|
750 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
751 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
752 |
+
|
753 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
754 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
755 |
+
|
756 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
757 |
+
logger.warning_once(
|
758 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
759 |
+
)
|
760 |
+
use_cache = False
|
761 |
+
|
762 |
+
if inputs_embeds is None:
|
763 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
764 |
+
|
765 |
+
# kept for BC (non `Cache` `past_key_values` inputs)
|
766 |
+
return_legacy_cache = False
|
767 |
+
if use_cache and not isinstance(past_key_values, Cache):
|
768 |
+
return_legacy_cache = True
|
769 |
+
if past_key_values is None:
|
770 |
+
past_key_values = DynamicCache()
|
771 |
+
else:
|
772 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
773 |
+
logger.warning_once(
|
774 |
+
"We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
|
775 |
+
"will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
|
776 |
+
"(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
|
777 |
+
)
|
778 |
+
|
779 |
+
if cache_position is None:
|
780 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
781 |
+
cache_position = torch.arange(
|
782 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
783 |
+
)
|
784 |
+
if position_ids is None:
|
785 |
+
position_ids = cache_position.unsqueeze(0)
|
786 |
+
|
787 |
+
causal_mask = self._update_causal_mask(
|
788 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
789 |
+
)
|
790 |
+
|
791 |
+
# embed positions
|
792 |
+
hidden_states = inputs_embeds
|
793 |
+
|
794 |
+
# decoder layers
|
795 |
+
all_hidden_states = () if output_hidden_states else None
|
796 |
+
all_self_attns = () if output_attentions else None
|
797 |
+
next_decoder_cache = None
|
798 |
+
|
799 |
+
for decoder_layer in self.layers:
|
800 |
+
if output_hidden_states:
|
801 |
+
all_hidden_states += (hidden_states,)
|
802 |
+
|
803 |
+
if self.gradient_checkpointing and self.training:
|
804 |
+
layer_outputs = self._gradient_checkpointing_func(
|
805 |
+
decoder_layer.__call__,
|
806 |
+
hidden_states,
|
807 |
+
causal_mask,
|
808 |
+
position_ids,
|
809 |
+
past_key_values,
|
810 |
+
output_attentions,
|
811 |
+
use_cache,
|
812 |
+
cache_position,
|
813 |
+
)
|
814 |
+
else:
|
815 |
+
layer_outputs = decoder_layer(
|
816 |
+
hidden_states,
|
817 |
+
attention_mask=causal_mask,
|
818 |
+
position_ids=position_ids,
|
819 |
+
past_key_value=past_key_values,
|
820 |
+
output_attentions=output_attentions,
|
821 |
+
use_cache=use_cache,
|
822 |
+
cache_position=cache_position,
|
823 |
+
)
|
824 |
+
|
825 |
+
hidden_states = layer_outputs[0]
|
826 |
+
|
827 |
+
if use_cache:
|
828 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
829 |
+
|
830 |
+
if output_attentions:
|
831 |
+
all_self_attns += (layer_outputs[1],)
|
832 |
+
|
833 |
+
hidden_states = self.norm(hidden_states)
|
834 |
+
|
835 |
+
# add hidden states from the last decoder layer
|
836 |
+
if output_hidden_states:
|
837 |
+
all_hidden_states += (hidden_states,)
|
838 |
+
|
839 |
+
next_cache = next_decoder_cache if use_cache else None
|
840 |
+
if return_legacy_cache:
|
841 |
+
next_cache = next_cache.to_legacy_cache()
|
842 |
+
|
843 |
+
if not return_dict:
|
844 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
845 |
+
return BaseModelOutputWithPast(
|
846 |
+
last_hidden_state=hidden_states,
|
847 |
+
past_key_values=next_cache,
|
848 |
+
hidden_states=all_hidden_states,
|
849 |
+
attentions=all_self_attns,
|
850 |
+
)
|
851 |
+
|
852 |
+
def _update_causal_mask(
|
853 |
+
self,
|
854 |
+
attention_mask: torch.Tensor,
|
855 |
+
input_tensor: torch.Tensor,
|
856 |
+
cache_position: torch.Tensor,
|
857 |
+
past_key_values: Cache,
|
858 |
+
output_attentions: bool,
|
859 |
+
):
|
860 |
+
if self.config._attn_implementation == "flash_attention_2":
|
861 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
862 |
+
return attention_mask
|
863 |
+
return None
|
864 |
+
|
865 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
866 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
867 |
+
# to infer the attention mask.
|
868 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
869 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
870 |
+
|
871 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
872 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
873 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
874 |
+
attention_mask,
|
875 |
+
inputs_embeds=input_tensor,
|
876 |
+
past_key_values_length=past_seen_tokens,
|
877 |
+
is_training=self.training,
|
878 |
+
):
|
879 |
+
return None
|
880 |
+
|
881 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
882 |
+
sequence_length = input_tensor.shape[1]
|
883 |
+
if using_static_cache:
|
884 |
+
target_length = past_key_values.get_max_cache_shape()
|
885 |
+
else:
|
886 |
+
target_length = (
|
887 |
+
attention_mask.shape[-1]
|
888 |
+
if isinstance(attention_mask, torch.Tensor)
|
889 |
+
else past_seen_tokens + sequence_length + 1
|
890 |
+
)
|
891 |
+
|
892 |
+
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
|
893 |
+
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
|
894 |
+
attention_mask,
|
895 |
+
sequence_length=sequence_length,
|
896 |
+
target_length=target_length,
|
897 |
+
dtype=dtype,
|
898 |
+
device=device,
|
899 |
+
cache_position=cache_position,
|
900 |
+
batch_size=input_tensor.shape[0],
|
901 |
+
)
|
902 |
+
|
903 |
+
if (
|
904 |
+
self.config._attn_implementation == "sdpa"
|
905 |
+
and attention_mask is not None
|
906 |
+
and attention_mask.device.type == "cuda"
|
907 |
+
and not output_attentions
|
908 |
+
):
|
909 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
910 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
911 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
912 |
+
min_dtype = torch.finfo(dtype).min
|
913 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
914 |
+
|
915 |
+
return causal_mask
|
916 |
+
|
917 |
+
@staticmethod
|
918 |
+
def _prepare_4d_causal_attention_mask_with_cache_position(
|
919 |
+
attention_mask: torch.Tensor,
|
920 |
+
sequence_length: int,
|
921 |
+
target_length: int,
|
922 |
+
dtype: torch.dtype,
|
923 |
+
device: torch.device,
|
924 |
+
cache_position: torch.Tensor,
|
925 |
+
batch_size: int,
|
926 |
+
**kwargs,
|
927 |
+
):
|
928 |
+
"""
|
929 |
+
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
|
930 |
+
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
|
931 |
+
|
932 |
+
Args:
|
933 |
+
attention_mask (`torch.Tensor`):
|
934 |
+
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
|
935 |
+
`(batch_size, 1, query_length, key_value_length)`.
|
936 |
+
sequence_length (`int`):
|
937 |
+
The sequence length being processed.
|
938 |
+
target_length (`int`):
|
939 |
+
The target length: when generating with static cache, the mask should be as long as the static cache,
|
940 |
+
to account for the 0 padding, the part of the cache that is not filled yet.
|
941 |
+
dtype (`torch.dtype`):
|
942 |
+
The dtype to use for the 4D attention mask.
|
943 |
+
device (`torch.device`):
|
944 |
+
The device to plcae the 4D attention mask on.
|
945 |
+
cache_position (`torch.Tensor`):
|
946 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
947 |
+
batch_size (`torch.Tensor`):
|
948 |
+
Batch size.
|
949 |
+
"""
|
950 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
951 |
+
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
|
952 |
+
causal_mask = attention_mask
|
953 |
+
else:
|
954 |
+
min_dtype = torch.finfo(dtype).min
|
955 |
+
causal_mask = torch.full(
|
956 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
957 |
+
)
|
958 |
+
if sequence_length != 1:
|
959 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
960 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
961 |
+
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
|
962 |
+
if attention_mask is not None:
|
963 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
964 |
+
mask_length = attention_mask.shape[-1]
|
965 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
966 |
+
padding_mask = padding_mask == 0
|
967 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
968 |
+
padding_mask, min_dtype
|
969 |
+
)
|
970 |
+
|
971 |
+
return causal_mask
|
972 |
+
|
973 |
+
|
974 |
+
class Olmo1124ForCausalLM(Olmo1124PreTrainedModel, GenerationMixin):
|
975 |
+
_tied_weights_keys = ["lm_head.weight"]
|
976 |
+
|
977 |
+
def __init__(self, config: Olmo1124Config):
|
978 |
+
super().__init__(config)
|
979 |
+
self.model = Olmo1124Model(config)
|
980 |
+
self.vocab_size = config.vocab_size
|
981 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
982 |
+
|
983 |
+
# Initialize weights and apply final processing
|
984 |
+
self.post_init()
|
985 |
+
|
986 |
+
def get_input_embeddings(self):
|
987 |
+
return self.model.embed_tokens
|
988 |
+
|
989 |
+
def set_input_embeddings(self, value):
|
990 |
+
self.model.embed_tokens = value
|
991 |
+
|
992 |
+
def get_output_embeddings(self):
|
993 |
+
return self.lm_head
|
994 |
+
|
995 |
+
def set_output_embeddings(self, new_embeddings):
|
996 |
+
self.lm_head = new_embeddings
|
997 |
+
|
998 |
+
def set_decoder(self, decoder):
|
999 |
+
self.model = decoder
|
1000 |
+
|
1001 |
+
def get_decoder(self):
|
1002 |
+
return self.model
|
1003 |
+
|
1004 |
+
@add_start_docstrings_to_model_forward(OLMO_1124_INPUTS_DOCSTRING)
|
1005 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1006 |
+
# Ignore copy
|
1007 |
+
def forward(
|
1008 |
+
self,
|
1009 |
+
input_ids: torch.LongTensor = None,
|
1010 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1011 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1012 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1013 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1014 |
+
labels: Optional[torch.LongTensor] = None,
|
1015 |
+
use_cache: Optional[bool] = None,
|
1016 |
+
output_attentions: Optional[bool] = None,
|
1017 |
+
output_hidden_states: Optional[bool] = None,
|
1018 |
+
return_dict: Optional[bool] = None,
|
1019 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1020 |
+
num_logits_to_keep: int = 0,
|
1021 |
+
**loss_kwargs,
|
1022 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1023 |
+
r"""
|
1024 |
+
Args:
|
1025 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1026 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1027 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1028 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1029 |
+
|
1030 |
+
num_logits_to_keep (`int`, *optional*):
|
1031 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
1032 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
1033 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
1034 |
+
|
1035 |
+
Returns:
|
1036 |
+
|
1037 |
+
Example:
|
1038 |
+
|
1039 |
+
```python
|
1040 |
+
>>> from transformers import AutoTokenizer, Olmo1124ForCausalLM
|
1041 |
+
|
1042 |
+
>>> model = Olmo1124ForCausalLM.from_pretrained("allenai/Olmo1124-1B-hf")
|
1043 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/Olmo1124-1B-hf")
|
1044 |
+
|
1045 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1046 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1047 |
+
|
1048 |
+
>>> # Generate
|
1049 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1050 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1051 |
+
'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
|
1052 |
+
```
|
1053 |
+
"""
|
1054 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1055 |
+
output_hidden_states = (
|
1056 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1057 |
+
)
|
1058 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1059 |
+
|
1060 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1061 |
+
outputs = self.model(
|
1062 |
+
input_ids=input_ids,
|
1063 |
+
attention_mask=attention_mask,
|
1064 |
+
position_ids=position_ids,
|
1065 |
+
past_key_values=past_key_values,
|
1066 |
+
inputs_embeds=inputs_embeds,
|
1067 |
+
use_cache=use_cache,
|
1068 |
+
output_attentions=output_attentions,
|
1069 |
+
output_hidden_states=output_hidden_states,
|
1070 |
+
return_dict=return_dict,
|
1071 |
+
cache_position=cache_position,
|
1072 |
+
)
|
1073 |
+
|
1074 |
+
hidden_states = outputs[0]
|
1075 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
1076 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
1077 |
+
|
1078 |
+
loss = None
|
1079 |
+
if labels is not None:
|
1080 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
|
1081 |
+
|
1082 |
+
if not return_dict:
|
1083 |
+
output = (logits,) + outputs[1:]
|
1084 |
+
return (loss,) + output if loss is not None else output
|
1085 |
+
|
1086 |
+
return CausalLMOutputWithPast(
|
1087 |
+
loss=loss,
|
1088 |
+
logits=logits,
|
1089 |
+
past_key_values=outputs.past_key_values,
|
1090 |
+
hidden_states=outputs.hidden_states,
|
1091 |
+
attentions=outputs.attentions,
|
1092 |
+
)
|
1093 |
+
|
1094 |
+
|
1095 |
+
__all__ = ["Olmo1124ForCausalLM", "Olmo1124Model", "Olmo1124PreTrainedModel"]
|