Harsh1729 commited on
Commit
459985d
·
verified ·
1 Parent(s): 865195c

Add final checkpoint (iter 238419)

Browse files
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "OpensciForCausalLM"
4
+ ],
5
+ "attention_bias": true,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_opensci.OpensciConfig",
9
+ "AutoModel": "modeling_opensci.OpensciPreTrainedModel",
10
+ "AutoModelForCausalLM": "modeling_opensci.OpensciForCausalLM"
11
+ },
12
+ "bos_token_id": 0,
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 0,
15
+ "head_dim": 64,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 8192,
20
+ "layer_norm_eps": 1e-05,
21
+ "max_position_embeddings": 4096,
22
+ "mlp_bias": true,
23
+ "model_type": "opensci",
24
+ "num_attention_heads": 32,
25
+ "num_hidden_layers": 24,
26
+ "num_key_value_heads": 32,
27
+ "pad_token_id": null,
28
+ "pretraining_tp": 1,
29
+ "qk_layernorm": true,
30
+ "rms_norm_eps": 1e-05,
31
+ "rope_parameters": null,
32
+ "rope_theta": 100000,
33
+ "tie_word_embeddings": true,
34
+ "transformers_version": "5.3.0",
35
+ "use_cache": true,
36
+ "vocab_size": 50304
37
+ }
configuration_opensci.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """OpenSci model configuration."""
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ # from transformers.modeling_rope_utils import rope_config_validation
23
+
24
+
25
+ class OpensciConfig(PretrainedConfig):
26
+ r"""This is the configuration class to store the configuration of a
27
+ [`OpensciModel`]. It is used to instantiate an Opensci model according to
28
+ the specified arguments, defining the model architecture. Instantiating a
29
+ configuration with the defaults will yield a similar configuration to that
30
+ of the Opensci-7B.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 32000):
38
+ Vocabulary size of the Opensci model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`OpensciModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 11008):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
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
55
+ `num_attention_heads`.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
+ The non-linear activation function (function or string) in the decoder.
58
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
62
+ The epsilon used by the rms normalization layers.
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
65
+ relevant if `config.is_decoder=True`.
66
+ pad_token_id (`int`, *optional*):
67
+ Padding token id.
68
+ bos_token_id (`int`, *optional*, defaults to 1):
69
+ Beginning of stream token id.
70
+ eos_token_id (`int`, *optional*, defaults to 2):
71
+ End of stream token id.
72
+ pretraining_tp (`int`, *optional*, defaults to 1):
73
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
74
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
75
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
76
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
77
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
78
+ Whether to tie weight embeddings
79
+ rope_theta (`float`, *optional*, defaults to 10000.0):
80
+ The base period of the RoPE embeddings.
81
+ rope_scaling (`Dict`, *optional*):
82
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
83
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
84
+ accordingly.
85
+ Expected contents:
86
+ `rope_type` (`str`):
87
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
88
+ 'Llama3'], with 'default' being the original RoPE implementation.
89
+ `factor` (`float`, *optional*):
90
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
91
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
92
+ original maximum pre-trained length.
93
+ `original_max_position_embeddings` (`int`, *optional*):
94
+ Used with 'dynamic', 'longrope' and 'Llama3'. The original max position embeddings used during
95
+ pretraining.
96
+ `attention_factor` (`float`, *optional*):
97
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
98
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
99
+ `factor` field to infer the suggested value.
100
+ `beta_fast` (`float`, *optional*):
101
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
102
+ ramp function. If unspecified, it defaults to 32.
103
+ `beta_slow` (`float`, *optional*):
104
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
105
+ ramp function. If unspecified, it defaults to 1.
106
+ `short_factor` (`List[float]`, *optional*):
107
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
108
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
109
+ size divided by the number of attention heads divided by 2
110
+ `long_factor` (`List[float]`, *optional*):
111
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
112
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
113
+ size divided by the number of attention heads divided by 2
114
+ `low_freq_factor` (`float`, *optional*):
115
+ Only used with 'Llama3'. Scaling factor applied to low frequency components of the RoPE
116
+ `high_freq_factor` (`float`, *optional*):
117
+ Only used with 'Llama3'. Scaling factor applied to high frequency components of the RoPE
118
+ attention_bias (`bool`, *optional*, defaults to `False`):
119
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
120
+ attention_dropout (`float`, *optional*, defaults to 0.0):
121
+ The dropout ratio for the attention probabilities.
122
+ mlp_bias (`bool`, *optional*, defaults to `False`):
123
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
124
+ head_dim (`int`, *optional*):
125
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
126
+
127
+ ```python
128
+ >>> from transformers import OpensciModel, OpensciConfig
129
+
130
+ >>> # Initializing a Opensci Opensci-7b style configuration
131
+ >>> configuration = OpensciConfig()
132
+
133
+ >>> # Initializing a model from the Opensci-7b style configuration
134
+ >>> model = OpensciModel(configuration)
135
+
136
+ >>> # Accessing the model configuration
137
+ >>> configuration = model.config
138
+ ```
139
+ """
140
+
141
+ model_type = "opensci"
142
+ keys_to_ignore_at_inference = ["past_key_values"]
143
+
144
+ def __init__(
145
+ self,
146
+ vocab_size=32000,
147
+ hidden_size=4096,
148
+ intermediate_size=11008,
149
+ num_hidden_layers=32,
150
+ num_attention_heads=32,
151
+ num_key_value_heads=None,
152
+ hidden_act="silu",
153
+ max_position_embeddings=2048,
154
+ initializer_range=0.02,
155
+ rms_norm_eps=1e-6,
156
+ use_cache=True,
157
+ pad_token_id=None,
158
+ bos_token_id=1,
159
+ eos_token_id=2,
160
+ pretraining_tp=1,
161
+ tie_word_embeddings=False,
162
+ rope_theta=10000.0,
163
+ rope_scaling=None,
164
+ attention_bias=False,
165
+ attention_dropout=0.0,
166
+ mlp_bias=False,
167
+ head_dim=None,
168
+ **kwargs,
169
+ ):
170
+ self.vocab_size = vocab_size
171
+ self.max_position_embeddings = max_position_embeddings
172
+ self.hidden_size = hidden_size
173
+ self.intermediate_size = intermediate_size
174
+ self.num_hidden_layers = num_hidden_layers
175
+ self.num_attention_heads = num_attention_heads
176
+
177
+ # for backward compatibility
178
+ if num_key_value_heads is None:
179
+ num_key_value_heads = num_attention_heads
180
+
181
+ self.num_key_value_heads = num_key_value_heads
182
+ self.hidden_act = hidden_act
183
+ self.initializer_range = initializer_range
184
+ self.rms_norm_eps = rms_norm_eps
185
+ self.pretraining_tp = pretraining_tp
186
+ self.use_cache = use_cache
187
+ self.rope_theta = rope_theta
188
+ self.rope_scaling = rope_scaling
189
+ self.attention_bias = attention_bias
190
+ self.attention_dropout = attention_dropout
191
+ self.mlp_bias = mlp_bias
192
+ self.head_dim = (
193
+ head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
194
+ )
195
+ # Validate the correctness of rotary position embeddings parameters
196
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
197
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
198
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
199
+ # rope_config_validation(self)
200
+
201
+ super().__init__(
202
+ pad_token_id=pad_token_id,
203
+ bos_token_id=bos_token_id,
204
+ eos_token_id=eos_token_id,
205
+ tie_word_embeddings=tie_word_embeddings,
206
+ **kwargs,
207
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2778de7ca6936818eacc154ec3ed7a0f541cc76e8a070158855fe926e6e39557
3
+ size 3428804400
modeling_opensci.py ADDED
@@ -0,0 +1,1049 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ from collections.abc import Callable
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
27
+ from transformers.generation import GenerationMixin
28
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
29
+
30
+ # from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ )
36
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
37
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from transformers.processing_utils import Unpack
39
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+
47
+ try:
48
+ from transformers.utils import TransformersKwargs
49
+ except ImportError:
50
+ from typing import TypedDict
51
+
52
+ class TransformersKwargs(TypedDict, total=False):
53
+ pass
54
+
55
+
56
+ from transformers.utils.deprecation import deprecate_kwarg
57
+ from .configuration_opensci import OpensciConfig
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CONFIG_FOR_DOC = "OpensciConfig"
63
+
64
+
65
+ class OpensciRMSNorm(nn.Module):
66
+ def __init__(self, hidden_size, eps=1e-6):
67
+ """OpensciRMSNorm is equivalent to T5LayerNorm."""
68
+ super().__init__()
69
+ self.weight = nn.Parameter(torch.ones(hidden_size))
70
+ self.variance_epsilon = eps
71
+
72
+ def forward(self, hidden_states):
73
+ input_dtype = hidden_states.dtype
74
+ hidden_states = hidden_states.to(torch.float32)
75
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
76
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
77
+ return self.weight * hidden_states.to(input_dtype)
78
+
79
+ def extra_repr(self):
80
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
81
+
82
+
83
+ ALL_LAYERNORM_LAYERS.append(OpensciRMSNorm)
84
+
85
+
86
+ class OpensciRotaryEmbedding(nn.Module):
87
+ def __init__(self, config: OpensciConfig, device=None):
88
+ super().__init__()
89
+ # BC: "rope_type" was originally "type"
90
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
91
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
92
+ else:
93
+ self.rope_type = "default"
94
+ self.max_seq_len_cached = config.max_position_embeddings
95
+ self.original_max_seq_len = config.max_position_embeddings
96
+
97
+ self.config = config
98
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
99
+
100
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+ self.original_inv_freq = self.inv_freq
103
+
104
+ def _dynamic_frequency_update(self, position_ids, device):
105
+ """Dynamic RoPE layers should recompute `inv_freq` in the following
106
+ situations:
107
+
108
+ 1 - growing beyond the cached sequence length (allow scaling)
109
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
110
+ """
111
+ seq_len = torch.max(position_ids) + 1
112
+ if seq_len > self.max_seq_len_cached: # growth
113
+ inv_freq, self.attention_scaling = self.rope_init_fn(
114
+ self.config, device, seq_len=seq_len
115
+ )
116
+ self.register_buffer(
117
+ "inv_freq", inv_freq, persistent=False
118
+ ) # TODO joao: may break with compilation
119
+ self.max_seq_len_cached = seq_len
120
+
121
+ if (
122
+ seq_len < self.original_max_seq_len
123
+ and self.max_seq_len_cached > self.original_max_seq_len
124
+ ): # reset
125
+ # This .to() is needed if the model has been moved to a device after being initialized (because
126
+ # the buffer is automatically moved, but not the original copy)
127
+ self.original_inv_freq = self.original_inv_freq.to(device)
128
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
129
+ self.max_seq_len_cached = self.original_max_seq_len
130
+
131
+ @torch.no_grad()
132
+ def forward(self, x, position_ids):
133
+ if "dynamic" in self.rope_type:
134
+ self._dynamic_frequency_update(position_ids, device=x.device)
135
+
136
+ # Core RoPE block
137
+ inv_freq_expanded = (
138
+ self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
139
+ )
140
+ position_ids_expanded = position_ids[:, None, :].float()
141
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
142
+ device_type = x.device.type
143
+ device_type = (
144
+ device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
145
+ )
146
+ with torch.autocast(device_type=device_type, enabled=False):
147
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ cos = emb.cos()
150
+ sin = emb.sin()
151
+
152
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
153
+ cos = cos * self.attention_scaling
154
+ sin = sin * self.attention_scaling
155
+
156
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
157
+
158
+
159
+ def rotate_half(x):
160
+ """Rotates half the hidden dims of the input."""
161
+ x1 = x[..., : x.shape[-1] // 2]
162
+ x2 = x[..., x.shape[-1] // 2 :]
163
+ return torch.cat((-x2, x1), dim=-1)
164
+
165
+
166
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
167
+ """Applies Rotary Position Embedding to the query and key tensors.
168
+
169
+ Args:
170
+ q (`torch.Tensor`): The query tensor.
171
+ k (`torch.Tensor`): The key tensor.
172
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
173
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
174
+ position_ids (`torch.Tensor`, *optional*):
175
+ Deprecated and unused.
176
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
177
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
178
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
179
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
180
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
181
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
182
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
183
+ Returns:
184
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
185
+ """
186
+ cos = cos.unsqueeze(unsqueeze_dim)
187
+ sin = sin.unsqueeze(unsqueeze_dim)
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ return q_embed, k_embed
191
+
192
+
193
+ class OpensciMLP(nn.Module):
194
+ def __init__(self, config):
195
+ super().__init__()
196
+ self.config = config
197
+ self.hidden_size = config.hidden_size
198
+ self.intermediate_size = config.intermediate_size
199
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
200
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
201
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
202
+ self.act_fn = ACT2FN[config.hidden_act]
203
+
204
+ def forward(self, x):
205
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
206
+ return down_proj
207
+
208
+
209
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
210
+ """This is the equivalent of torch.repeat_interleave(x, dim=1,
211
+ repeats=n_rep).
212
+
213
+ The hidden states go from (batch, num_key_value_heads, seqlen,
214
+ head_dim) to (batch, num_attention_heads, seqlen, head_dim)
215
+ """
216
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
217
+ if n_rep == 1:
218
+ return hidden_states
219
+ hidden_states = hidden_states[:, :, None, :, :].expand(
220
+ batch, num_key_value_heads, n_rep, slen, head_dim
221
+ )
222
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
223
+
224
+
225
+ def eager_attention_forward(
226
+ module: nn.Module,
227
+ query: torch.Tensor,
228
+ key: torch.Tensor,
229
+ value: torch.Tensor,
230
+ attention_mask: torch.Tensor | None,
231
+ scaling: float,
232
+ dropout: float = 0.0,
233
+ **kwargs,
234
+ ):
235
+ key_states = repeat_kv(key, module.num_key_value_groups)
236
+ value_states = repeat_kv(value, module.num_key_value_groups)
237
+
238
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
239
+ if attention_mask is not None:
240
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
241
+ attn_weights = attn_weights + causal_mask
242
+
243
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
244
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
245
+ attn_output = torch.matmul(attn_weights, value_states)
246
+ attn_output = attn_output.transpose(1, 2).contiguous()
247
+
248
+ return attn_output, attn_weights
249
+
250
+
251
+ class OpensciAttention(nn.Module):
252
+ """Multi-headed attention from 'Attention Is All You Need' paper."""
253
+
254
+ def __init__(self, config: OpensciConfig, layer_idx: int):
255
+ super().__init__()
256
+ self.config = config
257
+ self.layer_idx = layer_idx
258
+ self.head_dim = getattr(
259
+ config, "head_dim", config.hidden_size // config.num_attention_heads
260
+ )
261
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
262
+ self.scaling = self.head_dim**-0.5
263
+ self.attention_dropout = config.attention_dropout
264
+ self.is_causal = True
265
+
266
+ self.q_proj = nn.Linear(
267
+ config.hidden_size,
268
+ config.num_attention_heads * self.head_dim,
269
+ bias=config.attention_bias,
270
+ )
271
+ self.k_proj = nn.Linear(
272
+ config.hidden_size,
273
+ config.num_key_value_heads * self.head_dim,
274
+ bias=config.attention_bias,
275
+ )
276
+ self.v_proj = nn.Linear(
277
+ config.hidden_size,
278
+ config.num_key_value_heads * self.head_dim,
279
+ bias=config.attention_bias,
280
+ )
281
+ self.o_proj = nn.Linear(
282
+ config.num_attention_heads * self.head_dim,
283
+ config.hidden_size,
284
+ bias=config.attention_bias,
285
+ )
286
+ self.qk_layernorm = config.qk_layernorm
287
+ if self.qk_layernorm:
288
+ self.q_layernorm = OpensciRMSNorm(config.head_dim, eps=config.rms_norm_eps)
289
+ self.k_layernorm = OpensciRMSNorm(config.head_dim, eps=config.rms_norm_eps)
290
+
291
+ def forward(
292
+ self,
293
+ hidden_states: torch.Tensor,
294
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
295
+ attention_mask: torch.Tensor | None,
296
+ past_key_value: Cache | None = None,
297
+ cache_position: torch.LongTensor | None = None,
298
+ # **kwargs: Unpack[FlashAttentionKwargs],
299
+ ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
300
+ input_shape = hidden_states.shape[:-1]
301
+ hidden_shape = (*input_shape, -1, self.head_dim)
302
+
303
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
304
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
305
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
306
+
307
+ if self.qk_layernorm:
308
+ query_states = self.q_layernorm(query_states)
309
+ key_states = self.k_layernorm(key_states)
310
+ cos, sin = position_embeddings
311
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
312
+
313
+ if past_key_value is not None:
314
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
315
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
316
+ key_states, value_states = past_key_value.update(
317
+ key_states, value_states, self.layer_idx, cache_kwargs
318
+ )
319
+
320
+ attention_interface: Callable = eager_attention_forward
321
+ # if self.config._attn_implementation != "eager":
322
+ # if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
323
+ # logger.warning_once(
324
+ # "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
325
+ # 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
326
+ # )
327
+ # else:
328
+ # attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
329
+ if self.config._attn_implementation != "eager":
330
+ if self.config._attn_implementation in ALL_ATTENTION_FUNCTIONS:
331
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
332
+
333
+ attn_output, attn_weights = attention_interface(
334
+ self,
335
+ query_states,
336
+ key_states,
337
+ value_states,
338
+ attention_mask,
339
+ dropout=0.0 if not self.training else self.attention_dropout,
340
+ scaling=self.scaling,
341
+ # **kwargs,
342
+ )
343
+
344
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
345
+ attn_output = self.o_proj(attn_output)
346
+ return attn_output, attn_weights
347
+
348
+
349
+ class OpensciDecoderLayer(nn.Module):
350
+ def __init__(self, config: OpensciConfig, layer_idx: int):
351
+ super().__init__()
352
+ self.hidden_size = config.hidden_size
353
+
354
+ self.self_attn = OpensciAttention(config=config, layer_idx=layer_idx)
355
+
356
+ self.mlp = OpensciMLP(config)
357
+ self.input_layernorm = OpensciRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
358
+ self.post_attention_layernorm = OpensciRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states: torch.Tensor,
363
+ attention_mask: torch.Tensor | None = None,
364
+ position_ids: torch.LongTensor | None = None,
365
+ past_key_value: Cache | None = None,
366
+ output_attentions: bool | None = False,
367
+ use_cache: bool | None = False,
368
+ cache_position: torch.LongTensor | None = None,
369
+ position_embeddings: tuple[torch.Tensor, torch.Tensor]
370
+ | None = None, # necessary, but kept here for BC
371
+ # **kwargs: Unpack[FlashAttentionKwargs],
372
+ ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]:
373
+ residual = hidden_states
374
+
375
+ hidden_states = self.input_layernorm(hidden_states)
376
+
377
+ # Self Attention
378
+ hidden_states, self_attn_weights = self.self_attn(
379
+ hidden_states=hidden_states,
380
+ attention_mask=attention_mask,
381
+ # position_ids=position_ids,
382
+ past_key_value=past_key_value,
383
+ # output_attentions=output_attentions,
384
+ # use_cache=use_cache,
385
+ cache_position=cache_position,
386
+ position_embeddings=position_embeddings,
387
+ # **kwargs,
388
+ )
389
+ hidden_states = residual + hidden_states
390
+
391
+ # Fully Connected
392
+ residual = hidden_states
393
+ hidden_states = self.post_attention_layernorm(hidden_states)
394
+ hidden_states = self.mlp(hidden_states)
395
+ hidden_states = residual + hidden_states
396
+
397
+ outputs = (hidden_states,)
398
+ if output_attentions:
399
+ outputs += (self_attn_weights,)
400
+
401
+ return outputs
402
+
403
+
404
+ Opensci_START_DOCSTRING = r"""
405
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
406
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
407
+ etc.)
408
+
409
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
410
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
411
+ and behavior.
412
+
413
+ Parameters:
414
+ config ([`OpensciConfig`]):
415
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
416
+ load the weights associated with the model, only the configuration. Check out the
417
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
418
+ """
419
+
420
+
421
+ @add_start_docstrings(
422
+ "The bare Opensci Model outputting raw hidden-states without any specific head on top.",
423
+ Opensci_START_DOCSTRING,
424
+ )
425
+ class OpensciPreTrainedModel(PreTrainedModel):
426
+ config_class = OpensciConfig
427
+ base_model_prefix = "model"
428
+ supports_gradient_checkpointing = True
429
+ _no_split_modules = ["OpensciDecoderLayer"]
430
+ _skip_keys_device_placement = ["past_key_values"]
431
+ _supports_flash_attn_2 = True
432
+ _supports_sdpa = True
433
+ _supports_flex_attn = True
434
+ _supports_cache_class = True
435
+ _supports_quantized_cache = True
436
+ _supports_static_cache = True
437
+ _supports_attention_backend = True
438
+
439
+ def _init_weights(self, module):
440
+ std = self.config.initializer_range
441
+ if isinstance(module, nn.Linear):
442
+ module.weight.data.normal_(mean=0.0, std=std)
443
+ if module.bias is not None:
444
+ module.bias.data.zero_()
445
+ elif isinstance(module, nn.Embedding):
446
+ module.weight.data.normal_(mean=0.0, std=std)
447
+ if module.padding_idx is not None:
448
+ module.weight.data[module.padding_idx].zero_()
449
+
450
+
451
+ Opensci_INPUTS_DOCSTRING = r"""
452
+ Args:
453
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
454
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
455
+ it.
456
+
457
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
458
+ [`PreTrainedTokenizer.__call__`] for details.
459
+
460
+ [What are input IDs?](../glossary#input-ids)
461
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
462
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
463
+
464
+ - 1 for tokens that are **not masked**,
465
+ - 0 for tokens that are **masked**.
466
+
467
+ [What are attention masks?](../glossary#attention-mask)
468
+
469
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
470
+ [`PreTrainedTokenizer.__call__`] for details.
471
+
472
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
473
+ `past_key_values`).
474
+
475
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
476
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
477
+ information on the default strategy.
478
+
479
+ - 1 indicates the head is **not masked**,
480
+ - 0 indicates the head is **masked**.
481
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
482
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
483
+ config.n_positions - 1]`.
484
+
485
+ [What are position IDs?](../glossary#position-ids)
486
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
487
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
488
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
489
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
490
+
491
+ Two formats are allowed:
492
+ - a [`~cache_utils.Cache`] instance, see our
493
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
494
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
495
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
496
+ cache format.
497
+
498
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
499
+ legacy cache format will be returned.
500
+
501
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
502
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
503
+ of shape `(batch_size, sequence_length)`.
504
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
505
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
506
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
507
+ model's internal embedding lookup matrix.
508
+ use_cache (`bool`, *optional*):
509
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
510
+ `past_key_values`).
511
+ output_attentions (`bool`, *optional*):
512
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
513
+ tensors for more detail.
514
+ output_hidden_states (`bool`, *optional*):
515
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
516
+ more detail.
517
+ return_dict (`bool`, *optional*):
518
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
519
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
520
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
521
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
522
+ the complete sequence length.
523
+ """
524
+
525
+
526
+ @add_start_docstrings(
527
+ "The bare Opensci Model outputting raw hidden-states without any specific head on top.",
528
+ Opensci_START_DOCSTRING,
529
+ )
530
+ class OpensciModel(OpensciPreTrainedModel):
531
+ """Transformer decoder consisting of *config.num_hidden_layers* layers.
532
+ Each layer is a [`OpensciDecoderLayer`]
533
+
534
+ Args:
535
+ config: OpensciConfig
536
+ """
537
+
538
+ def __init__(self, config: OpensciConfig):
539
+ super().__init__(config)
540
+ self.padding_idx = config.pad_token_id
541
+ self.vocab_size = config.vocab_size
542
+
543
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
544
+ self.layers = nn.ModuleList(
545
+ [
546
+ OpensciDecoderLayer(config, layer_idx)
547
+ for layer_idx in range(config.num_hidden_layers)
548
+ ]
549
+ )
550
+ self.norm = OpensciRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
551
+ self.rotary_emb = OpensciRotaryEmbedding(config=config)
552
+ self.gradient_checkpointing = False
553
+
554
+ # Initialize weights and apply final processing
555
+ self.post_init()
556
+
557
+ def get_input_embeddings(self):
558
+ return self.embed_tokens
559
+
560
+ def set_input_embeddings(self, value):
561
+ self.embed_tokens = value
562
+
563
+ @add_start_docstrings_to_model_forward(Opensci_INPUTS_DOCSTRING)
564
+ def forward(
565
+ self,
566
+ input_ids: torch.LongTensor = None,
567
+ attention_mask: torch.Tensor | None = None,
568
+ position_ids: torch.LongTensor | None = None,
569
+ past_key_values: Cache | None = None,
570
+ inputs_embeds: torch.FloatTensor | None = None,
571
+ use_cache: bool | None = None,
572
+ output_attentions: bool | None = None,
573
+ output_hidden_states: bool | None = None,
574
+ return_dict: bool | None = None,
575
+ cache_position: torch.LongTensor | None = None,
576
+ # **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
577
+ ) -> tuple | BaseModelOutputWithPast:
578
+ output_attentions = (
579
+ output_attentions if output_attentions is not None else self.config.output_attentions
580
+ )
581
+ output_hidden_states = (
582
+ output_hidden_states
583
+ if output_hidden_states is not None
584
+ else self.config.output_hidden_states
585
+ )
586
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
587
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
588
+
589
+ if (input_ids is None) ^ (inputs_embeds is not None):
590
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
591
+
592
+ if self.gradient_checkpointing and self.training and use_cache:
593
+ logger.warning_once(
594
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
595
+ )
596
+ use_cache = False
597
+
598
+ if inputs_embeds is None:
599
+ inputs_embeds = self.embed_tokens(input_ids)
600
+
601
+ if use_cache and past_key_values is None:
602
+ past_key_values = DynamicCache()
603
+
604
+ if cache_position is None:
605
+ past_seen_tokens = (
606
+ past_key_values.get_seq_length() if past_key_values is not None else 0
607
+ )
608
+ cache_position = torch.arange(
609
+ past_seen_tokens,
610
+ past_seen_tokens + inputs_embeds.shape[1],
611
+ device=inputs_embeds.device,
612
+ )
613
+
614
+ if position_ids is None:
615
+ position_ids = cache_position.unsqueeze(0)
616
+
617
+ causal_mask = self._update_causal_mask(
618
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
619
+ )
620
+
621
+ hidden_states = inputs_embeds
622
+
623
+ # create position embeddings to be shared across the decoder layers
624
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
625
+
626
+ # decoder layers
627
+ all_hidden_states = () if output_hidden_states else None
628
+ all_self_attns = () if output_attentions else None
629
+
630
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
631
+ if output_hidden_states:
632
+ all_hidden_states += (hidden_states,)
633
+
634
+ if self.gradient_checkpointing and self.training:
635
+ layer_outputs = self._gradient_checkpointing_func(
636
+ decoder_layer.__call__,
637
+ hidden_states,
638
+ causal_mask,
639
+ position_ids,
640
+ past_key_values,
641
+ output_attentions,
642
+ use_cache,
643
+ cache_position,
644
+ position_embeddings,
645
+ )
646
+ else:
647
+ layer_outputs = decoder_layer(
648
+ hidden_states,
649
+ attention_mask=causal_mask,
650
+ position_ids=position_ids,
651
+ past_key_value=past_key_values,
652
+ output_attentions=output_attentions,
653
+ use_cache=use_cache,
654
+ cache_position=cache_position,
655
+ position_embeddings=position_embeddings,
656
+ # **flash_attn_kwargs,
657
+ )
658
+
659
+ hidden_states = layer_outputs[0]
660
+
661
+ if output_attentions:
662
+ all_self_attns += (layer_outputs[1],)
663
+
664
+ hidden_states = self.norm(hidden_states)
665
+
666
+ # add hidden states from the last decoder layer
667
+ if output_hidden_states:
668
+ all_hidden_states += (hidden_states,)
669
+
670
+ output = BaseModelOutputWithPast(
671
+ last_hidden_state=hidden_states,
672
+ past_key_values=past_key_values if use_cache else None,
673
+ hidden_states=all_hidden_states,
674
+ attentions=all_self_attns,
675
+ )
676
+ return output if return_dict else output.to_tuple()
677
+
678
+ def _update_causal_mask(
679
+ self,
680
+ attention_mask: torch.Tensor,
681
+ input_tensor: torch.Tensor,
682
+ cache_position: torch.Tensor,
683
+ past_key_values: Cache,
684
+ output_attentions: bool,
685
+ ):
686
+ if self.config._attn_implementation == "flash_attention_2":
687
+ if attention_mask is not None and (attention_mask == 0.0).any():
688
+ return attention_mask
689
+ return None
690
+
691
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
692
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
693
+ # to infer the attention mask.
694
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
695
+ using_static_cache = isinstance(past_key_values, StaticCache)
696
+
697
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
698
+ if (
699
+ self.config._attn_implementation == "sdpa"
700
+ and not using_static_cache
701
+ and not output_attentions
702
+ ):
703
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
704
+ attention_mask,
705
+ inputs_embeds=input_tensor,
706
+ past_key_values_length=past_seen_tokens,
707
+ is_training=self.training,
708
+ ):
709
+ return None
710
+
711
+ dtype, device = input_tensor.dtype, input_tensor.device
712
+ sequence_length = input_tensor.shape[1]
713
+ if using_static_cache:
714
+ target_length = past_key_values.get_max_cache_shape()
715
+ else:
716
+ target_length = (
717
+ attention_mask.shape[-1]
718
+ if isinstance(attention_mask, torch.Tensor)
719
+ else past_seen_tokens + sequence_length + 1
720
+ )
721
+
722
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
723
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
724
+ attention_mask,
725
+ sequence_length=sequence_length,
726
+ target_length=target_length,
727
+ dtype=dtype,
728
+ device=device,
729
+ cache_position=cache_position,
730
+ batch_size=input_tensor.shape[0],
731
+ )
732
+
733
+ if (
734
+ self.config._attn_implementation == "sdpa"
735
+ and attention_mask is not None
736
+ and attention_mask.device.type in ["cuda", "xpu"]
737
+ and not output_attentions
738
+ ):
739
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
740
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
741
+ # Details: https://github.com/pytorch/pytorch/issues/110213
742
+ min_dtype = torch.finfo(dtype).min
743
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
744
+
745
+ return causal_mask
746
+
747
+ @staticmethod
748
+ def _prepare_4d_causal_attention_mask_with_cache_position(
749
+ attention_mask: torch.Tensor,
750
+ sequence_length: int,
751
+ target_length: int,
752
+ dtype: torch.dtype,
753
+ device: torch.device,
754
+ cache_position: torch.Tensor,
755
+ batch_size: int,
756
+ **kwargs,
757
+ ):
758
+ """Creates a causal 4D mask of shape `(batch_size, 1, query_length,
759
+ key_value_length)` from a 2D mask of shape `(batch_size,
760
+ key_value_length)`, or if the input `attention_mask` is already 4D, do
761
+ nothing.
762
+
763
+ Args:
764
+ attention_mask (`torch.Tensor`):
765
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
766
+ `(batch_size, 1, query_length, key_value_length)`.
767
+ sequence_length (`int`):
768
+ The sequence length being processed.
769
+ target_length (`int`):
770
+ The target length: when generating with static cache, the mask should be as long as the static cache,
771
+ to account for the 0 padding, the part of the cache that is not filled yet.
772
+ dtype (`torch.dtype`):
773
+ The dtype to use for the 4D attention mask.
774
+ device (`torch.device`):
775
+ The device to plcae the 4D attention mask on.
776
+ cache_position (`torch.Tensor`):
777
+ Indices depicting the position of the input sequence tokens in the sequence.
778
+ batch_size (`torch.Tensor`):
779
+ Batch size.
780
+ """
781
+ if attention_mask is not None and attention_mask.dim() == 4:
782
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
783
+ causal_mask = attention_mask
784
+ else:
785
+ min_dtype = torch.finfo(dtype).min
786
+ causal_mask = torch.full(
787
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
788
+ )
789
+ if sequence_length != 1:
790
+ causal_mask = torch.triu(causal_mask, diagonal=1)
791
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(
792
+ -1, 1
793
+ )
794
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
795
+ if attention_mask is not None:
796
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
797
+ mask_length = attention_mask.shape[-1]
798
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
799
+ padding_mask = padding_mask == 0
800
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
801
+ padding_mask, min_dtype
802
+ )
803
+
804
+ return causal_mask
805
+
806
+
807
+ class KwargsForCausalLM(TransformersKwargs): ...
808
+
809
+
810
+ class OpensciForCausalLM(OpensciPreTrainedModel, GenerationMixin):
811
+ _tied_weights_keys = ["lm_head.weight"]
812
+ _tp_plan = {"lm_head": "colwise_rep"}
813
+
814
+ def __init__(self, config):
815
+ super().__init__(config)
816
+ self.model = OpensciModel(config)
817
+ self.vocab_size = config.vocab_size
818
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
819
+
820
+ # Initialize weights and apply final processing
821
+ self.post_init()
822
+
823
+ def get_input_embeddings(self):
824
+ return self.model.embed_tokens
825
+
826
+ def set_input_embeddings(self, value):
827
+ self.model.embed_tokens = value
828
+
829
+ def get_output_embeddings(self):
830
+ return self.lm_head
831
+
832
+ def set_output_embeddings(self, new_embeddings):
833
+ self.lm_head = new_embeddings
834
+
835
+ def set_decoder(self, decoder):
836
+ self.model = decoder
837
+
838
+ def get_decoder(self):
839
+ return self.model
840
+
841
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
842
+ @add_start_docstrings_to_model_forward(Opensci_INPUTS_DOCSTRING)
843
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
844
+ def forward(
845
+ self,
846
+ input_ids: torch.LongTensor = None,
847
+ attention_mask: torch.Tensor | None = None,
848
+ position_ids: torch.LongTensor | None = None,
849
+ past_key_values: Cache | list[torch.FloatTensor] | None = None,
850
+ inputs_embeds: torch.FloatTensor | None = None,
851
+ labels: torch.LongTensor | None = None,
852
+ use_cache: bool | None = None,
853
+ output_attentions: bool | None = None,
854
+ output_hidden_states: bool | None = None,
855
+ return_dict: bool | None = None,
856
+ cache_position: torch.LongTensor | None = None,
857
+ logits_to_keep: int | torch.Tensor = 0,
858
+ **kwargs: Unpack[KwargsForCausalLM],
859
+ ) -> tuple | CausalLMOutputWithPast:
860
+ r"""
861
+ Args:
862
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
863
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
864
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
865
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
866
+
867
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
868
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
869
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
870
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
871
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
872
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
873
+
874
+ Returns:
875
+
876
+ Example:
877
+
878
+ ```python
879
+ >>> from transformers import AutoTokenizer, OpensciForCausalLM
880
+
881
+ >>> model = OpensciForCausalLM.from_pretrained("meta-Opensci/Opensci-2-7b-hf")
882
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-Opensci/Opensci-2-7b-hf")
883
+
884
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
885
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
886
+
887
+ >>> # Generate
888
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
889
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
890
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
891
+ ```"""
892
+ output_attentions = (
893
+ output_attentions if output_attentions is not None else self.config.output_attentions
894
+ )
895
+ output_hidden_states = (
896
+ output_hidden_states
897
+ if output_hidden_states is not None
898
+ else self.config.output_hidden_states
899
+ )
900
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
901
+
902
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
903
+ outputs = self.model(
904
+ input_ids=input_ids,
905
+ attention_mask=attention_mask,
906
+ position_ids=position_ids,
907
+ past_key_values=past_key_values,
908
+ inputs_embeds=inputs_embeds,
909
+ use_cache=use_cache,
910
+ output_attentions=output_attentions,
911
+ output_hidden_states=output_hidden_states,
912
+ return_dict=return_dict,
913
+ cache_position=cache_position,
914
+ **kwargs,
915
+ )
916
+
917
+ hidden_states = outputs[0]
918
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
919
+ slice_indices = (
920
+ slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
921
+ )
922
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
923
+
924
+ loss = None
925
+ if labels is not None:
926
+ loss = self.loss_function(
927
+ logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs
928
+ )
929
+
930
+ if not return_dict:
931
+ output = (logits,) + outputs[1:]
932
+ return (loss,) + output if loss is not None else output
933
+
934
+ return CausalLMOutputWithPast(
935
+ loss=loss,
936
+ logits=logits,
937
+ past_key_values=outputs.past_key_values,
938
+ hidden_states=outputs.hidden_states,
939
+ attentions=outputs.attentions,
940
+ )
941
+
942
+
943
+ @add_start_docstrings(
944
+ """
945
+ The Opensci Model transformer with a sequence classification head on top (linear layer).
946
+
947
+ [`OpensciForSequenceClassification`] uses the last token in order to do the classification, as other causal models
948
+ (e.g. GPT-2) do.
949
+
950
+ Since it does classification on the last token, it requires to know the position of the last token. If a
951
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
952
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
953
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
954
+ each row of the batch).
955
+ """,
956
+ Opensci_START_DOCSTRING,
957
+ )
958
+ class OpensciForSequenceClassification(OpensciPreTrainedModel):
959
+ def __init__(self, config):
960
+ super().__init__(config)
961
+ self.num_labels = config.num_labels
962
+ self.model = OpensciModel(config)
963
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ def get_input_embeddings(self):
969
+ return self.model.embed_tokens
970
+
971
+ def set_input_embeddings(self, value):
972
+ self.model.embed_tokens = value
973
+
974
+ @add_start_docstrings_to_model_forward(Opensci_INPUTS_DOCSTRING)
975
+ def forward(
976
+ self,
977
+ input_ids: torch.LongTensor | None = None,
978
+ attention_mask: torch.Tensor | None = None,
979
+ position_ids: torch.LongTensor | None = None,
980
+ past_key_values: Cache | list[torch.FloatTensor] | None = None,
981
+ inputs_embeds: torch.FloatTensor | None = None,
982
+ labels: torch.LongTensor | None = None,
983
+ use_cache: bool | None = None,
984
+ output_attentions: bool | None = None,
985
+ output_hidden_states: bool | None = None,
986
+ return_dict: bool | None = None,
987
+ ) -> tuple | SequenceClassifierOutputWithPast:
988
+ r"""Labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
989
+
990
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
991
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
992
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
993
+ """
994
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
995
+
996
+ transformer_outputs = self.model(
997
+ input_ids,
998
+ attention_mask=attention_mask,
999
+ position_ids=position_ids,
1000
+ past_key_values=past_key_values,
1001
+ inputs_embeds=inputs_embeds,
1002
+ use_cache=use_cache,
1003
+ output_attentions=output_attentions,
1004
+ output_hidden_states=output_hidden_states,
1005
+ return_dict=return_dict,
1006
+ )
1007
+ hidden_states = transformer_outputs[0]
1008
+ logits = self.score(hidden_states)
1009
+
1010
+ if input_ids is not None:
1011
+ batch_size = input_ids.shape[0]
1012
+ else:
1013
+ batch_size = inputs_embeds.shape[0]
1014
+
1015
+ if self.config.pad_token_id is None and batch_size != 1:
1016
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1017
+ if self.config.pad_token_id is None:
1018
+ last_non_pad_token = -1
1019
+ elif input_ids is not None:
1020
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
1021
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
1022
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device)
1023
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
1024
+ else:
1025
+ last_non_pad_token = -1
1026
+ logger.warning_once(
1027
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1028
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1029
+ )
1030
+
1031
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
1032
+
1033
+ loss = None
1034
+ if labels is not None:
1035
+ loss = self.loss_function(
1036
+ logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config
1037
+ )
1038
+
1039
+ if not return_dict:
1040
+ output = (pooled_logits,) + transformer_outputs[1:]
1041
+ return ((loss,) + output) if loss is not None else output
1042
+
1043
+ return SequenceClassifierOutputWithPast(
1044
+ loss=loss,
1045
+ logits=pooled_logits,
1046
+ past_key_values=transformer_outputs.past_key_values,
1047
+ hidden_states=transformer_outputs.hidden_states,
1048
+ attentions=transformer_outputs.attentions,
1049
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "unk_token": "<|endoftext|>"
5
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "unk_token": "<|endoftext|>",
3
+ "bos_token": "<|endoftext|>",
4
+ "eos_token": "<|endoftext|>",
5
+ "add_prefix_space": false,
6
+ "tokenizer_class": "GPTNeoXTokenizer"
7
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff