Villekom commited on
Commit
da43d9c
·
verified ·
1 Parent(s): d6cf8b8

Upload folder using huggingface_hub

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