Harsh1729 commited on
Commit
a2f0b17
·
verified ·
1 Parent(s): 9dac0e7

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/p/project1/laionize/harsh/megatron_lm_reference/converted_checkpoints/open-sci-ref_model-1.7b_data-ontocord-MixtureVitae-v1-decontaminated-with_fix_samples-300B_global_bs-1024_context-4096_rotary-100000_schedule-WSD_lr-4e-3_warmup-25000_machine-JUWELS/hf/iter_0071526",
3
+ "architectures": [
4
+ "OpenSciForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
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": 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
+ "pretraining_tp": 1,
28
+ "qk_layernorm": true,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": null,
31
+ "rope_theta": 100000,
32
+ "tie_word_embeddings": true,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.44.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:bc5e2c5ec43d3ff6de489f3867ebb5fb798eb77cd390968d86714831908a6c86
3
+ size 3428804400
modeling_opensci.py ADDED
@@ -0,0 +1,989 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ TransformersKwargs,
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
+ if self.config._attn_implementation != "eager":
298
+ if self.config._attn_implementation in ALL_ATTENTION_FUNCTIONS:
299
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
300
+
301
+
302
+ attn_output, attn_weights = attention_interface(
303
+ self,
304
+ query_states,
305
+ key_states,
306
+ value_states,
307
+ attention_mask,
308
+ dropout=0.0 if not self.training else self.attention_dropout,
309
+ scaling=self.scaling,
310
+ # **kwargs,
311
+ )
312
+
313
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
314
+ attn_output = self.o_proj(attn_output)
315
+ return attn_output, attn_weights
316
+
317
+
318
+ class OpensciDecoderLayer(nn.Module):
319
+ def __init__(self, config: OpensciConfig, layer_idx: int):
320
+ super().__init__()
321
+ self.hidden_size = config.hidden_size
322
+
323
+ self.self_attn = OpensciAttention(config=config, layer_idx=layer_idx)
324
+
325
+ self.mlp = OpensciMLP(config)
326
+ self.input_layernorm = OpensciRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
327
+ self.post_attention_layernorm = OpensciRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
328
+
329
+ def forward(
330
+ self,
331
+ hidden_states: torch.Tensor,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ position_ids: Optional[torch.LongTensor] = None,
334
+ past_key_value: Optional[Cache] = None,
335
+ output_attentions: Optional[bool] = False,
336
+ use_cache: Optional[bool] = False,
337
+ cache_position: Optional[torch.LongTensor] = None,
338
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
339
+ # **kwargs: Unpack[FlashAttentionKwargs],
340
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
341
+ residual = hidden_states
342
+
343
+ hidden_states = self.input_layernorm(hidden_states)
344
+
345
+ # Self Attention
346
+ hidden_states, self_attn_weights = self.self_attn(
347
+ hidden_states=hidden_states,
348
+ attention_mask=attention_mask,
349
+ # position_ids=position_ids,
350
+ past_key_value=past_key_value,
351
+ # output_attentions=output_attentions,
352
+ # use_cache=use_cache,
353
+ cache_position=cache_position,
354
+ position_embeddings=position_embeddings,
355
+ # **kwargs,
356
+ )
357
+ hidden_states = residual + hidden_states
358
+
359
+ # Fully Connected
360
+ residual = hidden_states
361
+ hidden_states = self.post_attention_layernorm(hidden_states)
362
+ hidden_states = self.mlp(hidden_states)
363
+ hidden_states = residual + hidden_states
364
+
365
+ outputs = (hidden_states,)
366
+ if output_attentions:
367
+ outputs += (self_attn_weights,)
368
+
369
+ return outputs
370
+
371
+
372
+ Opensci_START_DOCSTRING = r"""
373
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
374
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
375
+ etc.)
376
+
377
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
378
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
379
+ and behavior.
380
+
381
+ Parameters:
382
+ config ([`OpensciConfig`]):
383
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
384
+ load the weights associated with the model, only the configuration. Check out the
385
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
386
+ """
387
+
388
+
389
+ @add_start_docstrings(
390
+ "The bare Opensci Model outputting raw hidden-states without any specific head on top.",
391
+ Opensci_START_DOCSTRING,
392
+ )
393
+ class OpensciPreTrainedModel(PreTrainedModel):
394
+ config_class = OpensciConfig
395
+ base_model_prefix = "model"
396
+ supports_gradient_checkpointing = True
397
+ _no_split_modules = ["OpensciDecoderLayer"]
398
+ _skip_keys_device_placement = ["past_key_values"]
399
+ _supports_flash_attn_2 = True
400
+ _supports_sdpa = True
401
+ _supports_flex_attn = True
402
+ _supports_cache_class = True
403
+ _supports_quantized_cache = True
404
+ _supports_static_cache = True
405
+ _supports_attention_backend = True
406
+
407
+ def _init_weights(self, module):
408
+ std = self.config.initializer_range
409
+ if isinstance(module, nn.Linear):
410
+ module.weight.data.normal_(mean=0.0, std=std)
411
+ if module.bias is not None:
412
+ module.bias.data.zero_()
413
+ elif isinstance(module, nn.Embedding):
414
+ module.weight.data.normal_(mean=0.0, std=std)
415
+ if module.padding_idx is not None:
416
+ module.weight.data[module.padding_idx].zero_()
417
+
418
+
419
+ Opensci_INPUTS_DOCSTRING = r"""
420
+ Args:
421
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
422
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
423
+ it.
424
+
425
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
426
+ [`PreTrainedTokenizer.__call__`] for details.
427
+
428
+ [What are input IDs?](../glossary#input-ids)
429
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
430
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
431
+
432
+ - 1 for tokens that are **not masked**,
433
+ - 0 for tokens that are **masked**.
434
+
435
+ [What are attention masks?](../glossary#attention-mask)
436
+
437
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
438
+ [`PreTrainedTokenizer.__call__`] for details.
439
+
440
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
441
+ `past_key_values`).
442
+
443
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
444
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
445
+ information on the default strategy.
446
+
447
+ - 1 indicates the head is **not masked**,
448
+ - 0 indicates the head is **masked**.
449
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
450
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
451
+ config.n_positions - 1]`.
452
+
453
+ [What are position IDs?](../glossary#position-ids)
454
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
455
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
456
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
457
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
458
+
459
+ Two formats are allowed:
460
+ - a [`~cache_utils.Cache`] instance, see our
461
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
462
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
463
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
464
+ cache format.
465
+
466
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
467
+ legacy cache format will be returned.
468
+
469
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
470
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
471
+ of shape `(batch_size, sequence_length)`.
472
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
473
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
474
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
475
+ model's internal embedding lookup matrix.
476
+ use_cache (`bool`, *optional*):
477
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
478
+ `past_key_values`).
479
+ output_attentions (`bool`, *optional*):
480
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
481
+ tensors for more detail.
482
+ output_hidden_states (`bool`, *optional*):
483
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
484
+ more detail.
485
+ return_dict (`bool`, *optional*):
486
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
487
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
488
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
489
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
490
+ the complete sequence length.
491
+ """
492
+
493
+
494
+ @add_start_docstrings(
495
+ "The bare Opensci Model outputting raw hidden-states without any specific head on top.",
496
+ Opensci_START_DOCSTRING,
497
+ )
498
+ class OpensciModel(OpensciPreTrainedModel):
499
+ """
500
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OpensciDecoderLayer`]
501
+
502
+ Args:
503
+ config: OpensciConfig
504
+ """
505
+
506
+ def __init__(self, config: OpensciConfig):
507
+ super().__init__(config)
508
+ self.padding_idx = config.pad_token_id
509
+ self.vocab_size = config.vocab_size
510
+
511
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
512
+ self.layers = nn.ModuleList(
513
+ [OpensciDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
514
+ )
515
+ self.norm = OpensciRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
516
+ self.rotary_emb = OpensciRotaryEmbedding(config=config)
517
+ self.gradient_checkpointing = False
518
+
519
+ # Initialize weights and apply final processing
520
+ self.post_init()
521
+
522
+ def get_input_embeddings(self):
523
+ return self.embed_tokens
524
+
525
+ def set_input_embeddings(self, value):
526
+ self.embed_tokens = value
527
+
528
+ @add_start_docstrings_to_model_forward(Opensci_INPUTS_DOCSTRING)
529
+ def forward(
530
+ self,
531
+ input_ids: torch.LongTensor = None,
532
+ attention_mask: Optional[torch.Tensor] = None,
533
+ position_ids: Optional[torch.LongTensor] = None,
534
+ past_key_values: Optional[Cache] = None,
535
+ inputs_embeds: Optional[torch.FloatTensor] = None,
536
+ use_cache: Optional[bool] = None,
537
+ output_attentions: Optional[bool] = None,
538
+ output_hidden_states: Optional[bool] = None,
539
+ return_dict: Optional[bool] = None,
540
+ cache_position: Optional[torch.LongTensor] = None,
541
+ # **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
542
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
543
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
544
+ output_hidden_states = (
545
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
546
+ )
547
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
548
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
549
+
550
+ if (input_ids is None) ^ (inputs_embeds is not None):
551
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
552
+
553
+ if self.gradient_checkpointing and self.training and use_cache:
554
+ logger.warning_once(
555
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
556
+ )
557
+ use_cache = False
558
+
559
+ if inputs_embeds is None:
560
+ inputs_embeds = self.embed_tokens(input_ids)
561
+
562
+ if use_cache and past_key_values is None:
563
+ past_key_values = DynamicCache()
564
+
565
+ if cache_position is None:
566
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
567
+ cache_position = torch.arange(
568
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
569
+ )
570
+
571
+ if position_ids is None:
572
+ position_ids = cache_position.unsqueeze(0)
573
+
574
+ causal_mask = self._update_causal_mask(
575
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
576
+ )
577
+
578
+ hidden_states = inputs_embeds
579
+
580
+ # create position embeddings to be shared across the decoder layers
581
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
582
+
583
+ # decoder layers
584
+ all_hidden_states = () if output_hidden_states else None
585
+ all_self_attns = () if output_attentions else None
586
+
587
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
588
+ if output_hidden_states:
589
+ all_hidden_states += (hidden_states,)
590
+
591
+ if self.gradient_checkpointing and self.training:
592
+ layer_outputs = self._gradient_checkpointing_func(
593
+ decoder_layer.__call__,
594
+ hidden_states,
595
+ causal_mask,
596
+ position_ids,
597
+ past_key_values,
598
+ output_attentions,
599
+ use_cache,
600
+ cache_position,
601
+ position_embeddings,
602
+ )
603
+ else:
604
+ layer_outputs = decoder_layer(
605
+ hidden_states,
606
+ attention_mask=causal_mask,
607
+ position_ids=position_ids,
608
+ past_key_value=past_key_values,
609
+ output_attentions=output_attentions,
610
+ use_cache=use_cache,
611
+ cache_position=cache_position,
612
+ position_embeddings=position_embeddings,
613
+ # **flash_attn_kwargs,
614
+ )
615
+
616
+ hidden_states = layer_outputs[0]
617
+
618
+ if output_attentions:
619
+ all_self_attns += (layer_outputs[1],)
620
+
621
+ hidden_states = self.norm(hidden_states)
622
+
623
+ # add hidden states from the last decoder layer
624
+ if output_hidden_states:
625
+ all_hidden_states += (hidden_states,)
626
+
627
+ output = BaseModelOutputWithPast(
628
+ last_hidden_state=hidden_states,
629
+ past_key_values=past_key_values if use_cache else None,
630
+ hidden_states=all_hidden_states,
631
+ attentions=all_self_attns,
632
+ )
633
+ return output if return_dict else output.to_tuple()
634
+
635
+ def _update_causal_mask(
636
+ self,
637
+ attention_mask: torch.Tensor,
638
+ input_tensor: torch.Tensor,
639
+ cache_position: torch.Tensor,
640
+ past_key_values: Cache,
641
+ output_attentions: bool,
642
+ ):
643
+ if self.config._attn_implementation == "flash_attention_2":
644
+ if attention_mask is not None and (attention_mask == 0.0).any():
645
+ return attention_mask
646
+ return None
647
+
648
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
649
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
650
+ # to infer the attention mask.
651
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
652
+ using_static_cache = isinstance(past_key_values, StaticCache)
653
+
654
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
655
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
656
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
657
+ attention_mask,
658
+ inputs_embeds=input_tensor,
659
+ past_key_values_length=past_seen_tokens,
660
+ is_training=self.training,
661
+ ):
662
+ return None
663
+
664
+ dtype, device = input_tensor.dtype, input_tensor.device
665
+ sequence_length = input_tensor.shape[1]
666
+ if using_static_cache:
667
+ target_length = past_key_values.get_max_cache_shape()
668
+ else:
669
+ target_length = (
670
+ attention_mask.shape[-1]
671
+ if isinstance(attention_mask, torch.Tensor)
672
+ else past_seen_tokens + sequence_length + 1
673
+ )
674
+
675
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
676
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
677
+ attention_mask,
678
+ sequence_length=sequence_length,
679
+ target_length=target_length,
680
+ dtype=dtype,
681
+ device=device,
682
+ cache_position=cache_position,
683
+ batch_size=input_tensor.shape[0],
684
+ )
685
+
686
+ if (
687
+ self.config._attn_implementation == "sdpa"
688
+ and attention_mask is not None
689
+ and attention_mask.device.type in ["cuda", "xpu"]
690
+ and not output_attentions
691
+ ):
692
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
693
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
694
+ # Details: https://github.com/pytorch/pytorch/issues/110213
695
+ min_dtype = torch.finfo(dtype).min
696
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
697
+
698
+ return causal_mask
699
+
700
+ @staticmethod
701
+ def _prepare_4d_causal_attention_mask_with_cache_position(
702
+ attention_mask: torch.Tensor,
703
+ sequence_length: int,
704
+ target_length: int,
705
+ dtype: torch.dtype,
706
+ device: torch.device,
707
+ cache_position: torch.Tensor,
708
+ batch_size: int,
709
+ **kwargs,
710
+ ):
711
+ """
712
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
713
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
714
+
715
+ Args:
716
+ attention_mask (`torch.Tensor`):
717
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
718
+ `(batch_size, 1, query_length, key_value_length)`.
719
+ sequence_length (`int`):
720
+ The sequence length being processed.
721
+ target_length (`int`):
722
+ The target length: when generating with static cache, the mask should be as long as the static cache,
723
+ to account for the 0 padding, the part of the cache that is not filled yet.
724
+ dtype (`torch.dtype`):
725
+ The dtype to use for the 4D attention mask.
726
+ device (`torch.device`):
727
+ The device to plcae the 4D attention mask on.
728
+ cache_position (`torch.Tensor`):
729
+ Indices depicting the position of the input sequence tokens in the sequence.
730
+ batch_size (`torch.Tensor`):
731
+ Batch size.
732
+ """
733
+ if attention_mask is not None and attention_mask.dim() == 4:
734
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
735
+ causal_mask = attention_mask
736
+ else:
737
+ min_dtype = torch.finfo(dtype).min
738
+ causal_mask = torch.full(
739
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
740
+ )
741
+ if sequence_length != 1:
742
+ causal_mask = torch.triu(causal_mask, diagonal=1)
743
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
744
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
745
+ if attention_mask is not None:
746
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
747
+ mask_length = attention_mask.shape[-1]
748
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
749
+ padding_mask = padding_mask == 0
750
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
751
+ padding_mask, min_dtype
752
+ )
753
+
754
+ return causal_mask
755
+
756
+
757
+ class KwargsForCausalLM(TransformersKwargs): ...
758
+
759
+
760
+ class OpensciForCausalLM(OpensciPreTrainedModel, GenerationMixin):
761
+ _tied_weights_keys = ["lm_head.weight"]
762
+ _tp_plan = {"lm_head": "colwise_rep"}
763
+
764
+ def __init__(self, config):
765
+ super().__init__(config)
766
+ self.model = OpensciModel(config)
767
+ self.vocab_size = config.vocab_size
768
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
769
+
770
+ # Initialize weights and apply final processing
771
+ self.post_init()
772
+
773
+ def get_input_embeddings(self):
774
+ return self.model.embed_tokens
775
+
776
+ def set_input_embeddings(self, value):
777
+ self.model.embed_tokens = value
778
+
779
+ def get_output_embeddings(self):
780
+ return self.lm_head
781
+
782
+ def set_output_embeddings(self, new_embeddings):
783
+ self.lm_head = new_embeddings
784
+
785
+ def set_decoder(self, decoder):
786
+ self.model = decoder
787
+
788
+ def get_decoder(self):
789
+ return self.model
790
+
791
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
792
+ @add_start_docstrings_to_model_forward(Opensci_INPUTS_DOCSTRING)
793
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
794
+ def forward(
795
+ self,
796
+ input_ids: torch.LongTensor = None,
797
+ attention_mask: Optional[torch.Tensor] = None,
798
+ position_ids: Optional[torch.LongTensor] = None,
799
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
800
+ inputs_embeds: Optional[torch.FloatTensor] = None,
801
+ labels: Optional[torch.LongTensor] = None,
802
+ use_cache: Optional[bool] = None,
803
+ output_attentions: Optional[bool] = None,
804
+ output_hidden_states: Optional[bool] = None,
805
+ return_dict: Optional[bool] = None,
806
+ cache_position: Optional[torch.LongTensor] = None,
807
+ logits_to_keep: Union[int, torch.Tensor] = 0,
808
+ **kwargs: Unpack[KwargsForCausalLM],
809
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
810
+ r"""
811
+ Args:
812
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
813
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
814
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
815
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
816
+
817
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
818
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
819
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
820
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
821
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
822
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
823
+
824
+ Returns:
825
+
826
+ Example:
827
+
828
+ ```python
829
+ >>> from transformers import AutoTokenizer, OpensciForCausalLM
830
+
831
+ >>> model = OpensciForCausalLM.from_pretrained("meta-Opensci/Opensci-2-7b-hf")
832
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-Opensci/Opensci-2-7b-hf")
833
+
834
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
835
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
836
+
837
+ >>> # Generate
838
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
839
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
840
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
841
+ ```"""
842
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
843
+ output_hidden_states = (
844
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
845
+ )
846
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
847
+
848
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
849
+ outputs = self.model(
850
+ input_ids=input_ids,
851
+ attention_mask=attention_mask,
852
+ position_ids=position_ids,
853
+ past_key_values=past_key_values,
854
+ inputs_embeds=inputs_embeds,
855
+ use_cache=use_cache,
856
+ output_attentions=output_attentions,
857
+ output_hidden_states=output_hidden_states,
858
+ return_dict=return_dict,
859
+ cache_position=cache_position,
860
+ **kwargs,
861
+ )
862
+
863
+ hidden_states = outputs[0]
864
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
865
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
866
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
867
+
868
+ loss = None
869
+ if labels is not None:
870
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
871
+
872
+ if not return_dict:
873
+ output = (logits,) + outputs[1:]
874
+ return (loss,) + output if loss is not None else output
875
+
876
+ return CausalLMOutputWithPast(
877
+ loss=loss,
878
+ logits=logits,
879
+ past_key_values=outputs.past_key_values,
880
+ hidden_states=outputs.hidden_states,
881
+ attentions=outputs.attentions,
882
+ )
883
+
884
+
885
+ @add_start_docstrings(
886
+ """
887
+ The Opensci Model transformer with a sequence classification head on top (linear layer).
888
+
889
+ [`OpensciForSequenceClassification`] uses the last token in order to do the classification, as other causal models
890
+ (e.g. GPT-2) do.
891
+
892
+ Since it does classification on the last token, it requires to know the position of the last token. If a
893
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
894
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
895
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
896
+ each row of the batch).
897
+ """,
898
+ Opensci_START_DOCSTRING,
899
+ )
900
+ class OpensciForSequenceClassification(OpensciPreTrainedModel):
901
+ def __init__(self, config):
902
+ super().__init__(config)
903
+ self.num_labels = config.num_labels
904
+ self.model = OpensciModel(config)
905
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
906
+
907
+ # Initialize weights and apply final processing
908
+ self.post_init()
909
+
910
+ def get_input_embeddings(self):
911
+ return self.model.embed_tokens
912
+
913
+ def set_input_embeddings(self, value):
914
+ self.model.embed_tokens = value
915
+
916
+ @add_start_docstrings_to_model_forward(Opensci_INPUTS_DOCSTRING)
917
+ def forward(
918
+ self,
919
+ input_ids: Optional[torch.LongTensor] = None,
920
+ attention_mask: Optional[torch.Tensor] = None,
921
+ position_ids: Optional[torch.LongTensor] = None,
922
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
923
+ inputs_embeds: Optional[torch.FloatTensor] = None,
924
+ labels: Optional[torch.LongTensor] = None,
925
+ use_cache: Optional[bool] = None,
926
+ output_attentions: Optional[bool] = None,
927
+ output_hidden_states: Optional[bool] = None,
928
+ return_dict: Optional[bool] = None,
929
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
930
+ r"""
931
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
932
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
933
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
934
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
935
+ """
936
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
937
+
938
+ transformer_outputs = self.model(
939
+ input_ids,
940
+ attention_mask=attention_mask,
941
+ position_ids=position_ids,
942
+ past_key_values=past_key_values,
943
+ inputs_embeds=inputs_embeds,
944
+ use_cache=use_cache,
945
+ output_attentions=output_attentions,
946
+ output_hidden_states=output_hidden_states,
947
+ return_dict=return_dict,
948
+ )
949
+ hidden_states = transformer_outputs[0]
950
+ logits = self.score(hidden_states)
951
+
952
+ if input_ids is not None:
953
+ batch_size = input_ids.shape[0]
954
+ else:
955
+ batch_size = inputs_embeds.shape[0]
956
+
957
+ if self.config.pad_token_id is None and batch_size != 1:
958
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
959
+ if self.config.pad_token_id is None:
960
+ last_non_pad_token = -1
961
+ elif input_ids is not None:
962
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
963
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
964
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device)
965
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
966
+ else:
967
+ last_non_pad_token = -1
968
+ logger.warning_once(
969
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
970
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
971
+ )
972
+
973
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
974
+
975
+ loss = None
976
+ if labels is not None:
977
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
978
+
979
+ if not return_dict:
980
+ output = (pooled_logits,) + transformer_outputs[1:]
981
+ return ((loss,) + output) if loss is not None else output
982
+
983
+ return SequenceClassifierOutputWithPast(
984
+ loss=loss,
985
+ logits=pooled_logits,
986
+ past_key_values=transformer_outputs.past_key_values,
987
+ hidden_states=transformer_outputs.hidden_states,
988
+ attentions=transformer_outputs.attentions,
989
+ )
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