11104491 commited on
Commit
fb04a75
1 Parent(s): c690d2a

First model version

Browse files
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BlueLMForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_bluelm.BlueLMConfig",
7
+ "AutoModelForCausalLM": "modeling_bluelm.BlueLMForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 4096,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 11008,
15
+ "max_position_embeddings": 2048,
16
+ "model_type": "BlueLM",
17
+ "num_attention_heads": 32,
18
+ "num_hidden_layers": 32,
19
+ "num_key_value_heads": 32,
20
+ "pad_token_id": 3,
21
+ "pretraining_tp": 1,
22
+ "rms_norm_eps": 1e-06,
23
+ "rope_scaling": null,
24
+ "rope_theta": 10000.0,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.33.1",
28
+ "use_cache": true,
29
+ "use_stable_embedding": true,
30
+ "vocab_size": 100096
31
+ }
configuration_bluelm.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 vivo.
2
+ #
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ """ BlueLM model configuration"""
23
+
24
+ from transformers.configuration_utils import PretrainedConfig
25
+
26
+ BlueLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
27
+
28
+
29
+ class BlueLMConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`BlueLMModel`]. It is used to instantiate an BlueLM
32
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
33
+ defaults will yield a similar configuration to that of the BlueLM-7B.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32000):
41
+ Vocabulary size of the BlueLM model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`BlueLMModel`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 11008):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ num_key_value_heads (`int`, *optional*):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ pretraining_tp (`int`, *optional*, defaults to `1`):
60
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
61
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
62
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
63
+ issue](https://github.com/pytorch/pytorch/issues/76232).
64
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
65
+ The non-linear activation function (function or string) in the decoder.
66
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
67
+ The maximum sequence length that this model might ever be used with.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
71
+ The epsilon used by the rms normalization layers.
72
+ use_cache (`bool`, *optional*, defaults to `True`):
73
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
74
+ relevant if `config.is_decoder=True`.
75
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
76
+ Whether to tie weight embeddings
77
+ rope_theta (`float`, *optional*, defaults to 10000.0):
78
+ The base period of the RoPE embeddings.
79
+ rope_scaling (`Dict`, *optional*):
80
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
81
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
82
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
83
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
84
+ these scaling strategies behave:
85
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
86
+ experimental feature, subject to breaking API changes in future versions.
87
+
88
+ """
89
+
90
+ model_type = "BlueLM"
91
+ keys_to_ignore_at_inference = ["past_key_values"]
92
+
93
+ def __init__(
94
+ self,
95
+ vocab_size=100096,
96
+ hidden_size=4096,
97
+ intermediate_size=11008,
98
+ num_hidden_layers=32,
99
+ num_attention_heads=32,
100
+ num_key_value_heads=None,
101
+ hidden_act="silu",
102
+ max_position_embeddings=2048,
103
+ initializer_range=0.02,
104
+ rms_norm_eps=1e-6,
105
+ use_cache=True,
106
+ pad_token_id=None,
107
+ bos_token_id=1,
108
+ eos_token_id=2,
109
+ pretraining_tp=1,
110
+ tie_word_embeddings=False,
111
+ rope_theta=10000.0,
112
+ rope_scaling=None,
113
+ use_stable_embedding=True,
114
+ **kwargs,
115
+ ):
116
+ self.vocab_size = vocab_size
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.hidden_size = hidden_size
119
+ self.intermediate_size = intermediate_size
120
+ self.num_hidden_layers = num_hidden_layers
121
+ self.num_attention_heads = num_attention_heads
122
+ self.use_stable_embedding = use_stable_embedding
123
+ # for backward compatibility
124
+ if num_key_value_heads is None:
125
+ num_key_value_heads = num_attention_heads
126
+
127
+ self.num_key_value_heads = num_key_value_heads
128
+ self.hidden_act = hidden_act
129
+ self.initializer_range = initializer_range
130
+ self.rms_norm_eps = rms_norm_eps
131
+ self.pretraining_tp = pretraining_tp
132
+ self.use_cache = use_cache
133
+ self.rope_theta = rope_theta
134
+ self.rope_scaling = rope_scaling
135
+ self._rope_scaling_validation()
136
+
137
+ super().__init__(
138
+ pad_token_id=pad_token_id,
139
+ bos_token_id=bos_token_id,
140
+ eos_token_id=eos_token_id,
141
+ tie_word_embeddings=tie_word_embeddings,
142
+ **kwargs,
143
+ )
144
+
145
+ def _rope_scaling_validation(self):
146
+ """
147
+ Validate the `rope_scaling` configuration.
148
+ """
149
+ if self.rope_scaling is None:
150
+ return
151
+
152
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
153
+ raise ValueError(
154
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
155
+ f"got {self.rope_scaling}"
156
+ )
157
+ rope_scaling_type = self.rope_scaling.get("type", None)
158
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
159
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
160
+ raise ValueError(
161
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
162
+ )
163
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
164
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 3,
6
+ "transformers_version": "4.33.1"
7
+ }
modeling_bluelm.py ADDED
@@ -0,0 +1,997 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 vivo.
2
+ #
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """ PyTorch BlueLM model."""
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
32
+ from transformers.modeling_utils import PreTrainedModel
33
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
34
+ from .configuration_bluelm import BlueLMConfig
35
+
36
+
37
+ try:
38
+ from xformers import ops as xops
39
+ except ImportError:
40
+ xops = None
41
+ # print("xformers is not installed correctly.")
42
+
43
+ try:
44
+ from apex.normalization import MixedFusedRMSNorm
45
+ except ImportError:
46
+ MixedFusedRMSNorm = None
47
+ # print("Please install nvidia apex from source (https://github.com/NVIDIA/apex#linux) or use ngc container.")
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CONFIG_FOR_DOC = "BlueLMConfig"
53
+
54
+
55
+ def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0):
56
+ """
57
+ Make causal mask used for bi-directional self-attention.
58
+ """
59
+ bsz, tgt_len = input_ids_shape
60
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min))
61
+ mask_cond = torch.arange(mask.size(-1))
62
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
63
+ mask = mask.to(dtype)
64
+
65
+ if past_key_values_length > 0:
66
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
67
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
68
+
69
+
70
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
71
+ """
72
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
73
+ """
74
+ bsz, src_len = mask.size()
75
+ tgt_len = tgt_len if tgt_len is not None else src_len
76
+
77
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
78
+
79
+ inverted_mask = 1.0 - expanded_mask
80
+
81
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
82
+
83
+
84
+ class BlueLMRMSNorm(nn.Module):
85
+ def __init__(self, hidden_size, eps=1e-6):
86
+ """
87
+ BlueLMRMSNorm is equivalent to T5LayerNorm
88
+ """
89
+ super().__init__()
90
+ self.weight = nn.Parameter(torch.ones(hidden_size))
91
+ self.variance_epsilon = eps
92
+
93
+ def forward(self, hidden_states):
94
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
95
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
96
+
97
+ # convert into half-precision if necessary
98
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
99
+ hidden_states = hidden_states.to(self.weight.dtype)
100
+
101
+ return self.weight * hidden_states
102
+
103
+
104
+ class BlueLMRotaryEmbedding(torch.nn.Module):
105
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
106
+ super().__init__()
107
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
108
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
109
+
110
+ # Build here to make `torch.jit.trace` work.
111
+ self.max_seq_len_cached = max_position_embeddings
112
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
113
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
114
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
115
+ emb = torch.cat((freqs, freqs), dim=-1)
116
+ self.register_buffer("cos_cached", emb.cos()[None, :, None, :], persistent=False)
117
+ self.register_buffer("sin_cached", emb.sin()[None, :, None, :], persistent=False)
118
+
119
+ def forward(self, x, seq_len=None):
120
+ # x: [bs, num_attention_heads, seq_len, head_size]
121
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
122
+ if seq_len > self.max_seq_len_cached:
123
+ self.max_seq_len_cached = seq_len
124
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
125
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
126
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
127
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
128
+ self.register_buffer("cos_cached", emb.cos()[None, :, None, :], persistent=False)
129
+ self.register_buffer("sin_cached", emb.sin()[None, :, None, :], persistent=False)
130
+ return (
131
+ self.cos_cached[:, :seq_len, ...].to(dtype=x.dtype),
132
+ self.sin_cached[:, :seq_len, ...].to(dtype=x.dtype),
133
+ )
134
+
135
+
136
+ def rotate_half(x):
137
+ """Rotates half the hidden dims of the input."""
138
+ x1 = x[..., : x.shape[-1] // 2]
139
+ x2 = x[..., x.shape[-1] // 2 :]
140
+ return torch.cat((-x2, x1), dim=-1)
141
+
142
+
143
+ def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
144
+ cos = cos[:, offset : q.shape[1] + offset, ...]
145
+ sin = sin[:, offset : q.shape[1] + offset, ...]
146
+ q_embed = (q * cos) + (rotate_half(q) * sin)
147
+ k_embed = (k * cos) + (rotate_half(k) * sin)
148
+ return q_embed, k_embed
149
+
150
+
151
+ class BlueLMMLP(nn.Module):
152
+ def __init__(
153
+ self,
154
+ hidden_size: int,
155
+ intermediate_size: int,
156
+ hidden_act: str,
157
+ dropout_prob: float,
158
+ ):
159
+ super().__init__()
160
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
161
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
162
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
163
+ self.act_fn = ACT2FN[hidden_act]
164
+ self.dropout = nn.Dropout(dropout_prob)
165
+
166
+ def forward(self, x):
167
+ return self.dropout(self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)))
168
+
169
+
170
+ class BlueLMAttention(nn.Module):
171
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
172
+
173
+ def __init__(
174
+ self,
175
+ hidden_size: int,
176
+ num_heads: int,
177
+ dropout_prob: float,
178
+ ):
179
+ super().__init__()
180
+ self.hidden_size = hidden_size
181
+ self.num_heads = num_heads
182
+ self.head_dim = hidden_size // num_heads
183
+ self.dropout_prob = dropout_prob
184
+
185
+ if (self.head_dim * num_heads) != self.hidden_size:
186
+ raise ValueError(
187
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
188
+ f" and `num_heads`: {num_heads})."
189
+ )
190
+ self.q_proj = nn.Linear(
191
+ hidden_size,
192
+ num_heads * self.head_dim,
193
+ bias=False,
194
+ )
195
+ self.k_proj = nn.Linear(
196
+ hidden_size,
197
+ num_heads * self.head_dim,
198
+ bias=False,
199
+ )
200
+ self.v_proj = nn.Linear(
201
+ hidden_size,
202
+ num_heads * self.head_dim,
203
+ bias=False,
204
+ )
205
+ self.o_proj = nn.Linear(
206
+ num_heads * self.head_dim,
207
+ hidden_size,
208
+ bias=False,
209
+ )
210
+ self.rotary_emb = BlueLMRotaryEmbedding(self.head_dim)
211
+ if xops is not None:
212
+ self.causal_mask = xops.LowerTriangularMask()
213
+
214
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
215
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).contiguous()
216
+
217
+ def forward(
218
+ self,
219
+ hidden_states: torch.Tensor,
220
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
221
+ attention_mask: Optional[torch.Tensor] = None,
222
+ output_attentions: bool = False,
223
+ use_cache: bool = False,
224
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
225
+ """Input shape: Batch x Time x Channel"""
226
+
227
+ bsz, q_len, _ = hidden_states.size()
228
+
229
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
230
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
231
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
232
+
233
+ kv_seq_len = key_states.shape[1]
234
+ offset = 0
235
+ if past_key_value is not None:
236
+ offset = past_key_value[0].shape[1]
237
+ kv_seq_len += offset
238
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
239
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, offset=offset)
240
+ # [bsz, t, nh, hd]
241
+
242
+ if past_key_value is not None:
243
+ # reuse k, v, self_attention
244
+ key_states = torch.cat([past_key_value[0], key_states], dim=1)
245
+ value_states = torch.cat([past_key_value[1], value_states], dim=1)
246
+
247
+ past_key_value = (key_states, value_states) if use_cache else None
248
+
249
+ if xops is not None and self.training:
250
+ attn_weights = None
251
+ attn_output = xops.memory_efficient_attention(
252
+ query_states, key_states, value_states, attn_bias=self.causal_mask, p=self.dropout_prob,
253
+ op=xops.fmha.MemoryEfficientAttentionFlashAttentionOp
254
+ )
255
+ else:
256
+ # [bsz, t, nh, hd]
257
+ attn_weights = torch.einsum("bqnh,bknh->bnqk", query_states, key_states) / math.sqrt(self.head_dim)
258
+
259
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
260
+ raise ValueError(
261
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
262
+ f" {attn_weights.size()}"
263
+ )
264
+
265
+ if attention_mask is not None:
266
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
267
+ raise ValueError(
268
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
269
+ )
270
+ attn_weights = attn_weights + attention_mask
271
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
272
+
273
+ # upcast attention to fp32
274
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
275
+ attn_output = torch.einsum("bnqk,bknh->bqnh", attn_weights, value_states)
276
+
277
+ if attn_output.size() != (bsz, q_len, self.num_heads, self.head_dim):
278
+ raise ValueError(
279
+ f"`attn_output` should be of size {(bsz, q_len, self.num_heads, self.head_dim)}, but is"
280
+ f" {attn_output.size()}"
281
+ )
282
+
283
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
284
+
285
+ attn_output = self.o_proj(attn_output)
286
+
287
+ if not output_attentions:
288
+ attn_weights = None
289
+
290
+ return attn_output, attn_weights, past_key_value
291
+
292
+
293
+ class BlueLMDecoderLayer(nn.Module):
294
+ def __init__(self, config: BlueLMConfig):
295
+ super().__init__()
296
+ self.hidden_size = config.hidden_size
297
+ self.self_attn = BlueLMAttention(
298
+ hidden_size=self.hidden_size,
299
+ num_heads=config.num_attention_heads,
300
+ dropout_prob=0,
301
+ )
302
+ self.mlp = BlueLMMLP(
303
+ hidden_size=self.hidden_size,
304
+ intermediate_size=config.intermediate_size,
305
+ hidden_act=config.hidden_act,
306
+ dropout_prob=0,
307
+ )
308
+ if MixedFusedRMSNorm is None:
309
+ self.input_layernorm = BlueLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
310
+ self.post_attention_layernorm = BlueLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
311
+ else:
312
+ self.input_layernorm = MixedFusedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
313
+ self.post_attention_layernorm = MixedFusedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
314
+
315
+ def forward(
316
+ self,
317
+ hidden_states: torch.Tensor,
318
+ attention_mask: Optional[torch.Tensor] = None,
319
+ output_attentions: Optional[bool] = False,
320
+ use_cache: Optional[bool] = False,
321
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
322
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
323
+ """
324
+ Args:
325
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
326
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
327
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
328
+ output_attentions (`bool`, *optional*):
329
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
330
+ returned tensors for more detail.
331
+ use_cache (`bool`, *optional*):
332
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
333
+ (see `past_key_values`).
334
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
335
+ """
336
+
337
+ residual = hidden_states
338
+
339
+ hidden_states = self.input_layernorm(hidden_states)
340
+
341
+ # Self Attention
342
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
343
+ hidden_states=hidden_states,
344
+ past_key_value=past_key_value,
345
+ attention_mask=attention_mask,
346
+ output_attentions=output_attentions,
347
+ use_cache=use_cache,
348
+ )
349
+ hidden_states = residual + hidden_states
350
+
351
+ # Fully Connected
352
+ residual = hidden_states
353
+ hidden_states = self.post_attention_layernorm(hidden_states)
354
+ hidden_states = self.mlp(hidden_states)
355
+ hidden_states = residual + hidden_states
356
+
357
+ outputs = (hidden_states,)
358
+
359
+ if output_attentions:
360
+ outputs += (self_attn_weights,)
361
+
362
+ if use_cache:
363
+ outputs += (present_key_value,)
364
+
365
+ return outputs
366
+
367
+
368
+ BlueLM_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 ([`BlueLMConfig`]):
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 BlueLM Model outputting raw hidden-states without any specific head on top.",
387
+ BlueLM_START_DOCSTRING,
388
+ )
389
+ class BlueLMPreTrainedModel(PreTrainedModel):
390
+ config_class = BlueLMConfig
391
+ base_model_prefix = "model"
392
+ supports_gradient_checkpointing = True
393
+ _no_split_modules = ["BlueLMDecoderLayer"]
394
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
395
+
396
+ def _init_weights(self, module):
397
+ std = self.config.initializer_range
398
+ if isinstance(module, nn.Linear):
399
+ # module.weight.data.normal_(mean=0.0, std=std)
400
+ torch.nn.init.xavier_normal_(module.weight.data)
401
+ if module.bias is not None:
402
+ module.bias.data.zero_()
403
+ elif isinstance(module, nn.Embedding):
404
+ if self.config.use_stable_embedding:
405
+ torch.nn.init.xavier_normal_(module.weight.data)
406
+ else:
407
+ module.weight.data.normal_(mean=0.0, std=std)
408
+ if module.padding_idx is not None:
409
+ module.weight.data[module.padding_idx].zero_()
410
+
411
+ def _set_gradient_checkpointing(self, module, value=False):
412
+ if isinstance(module, BlueLMModel):
413
+ module.gradient_checkpointing = value
414
+
415
+
416
+ BlueLM_INPUTS_DOCSTRING = r"""
417
+ Args:
418
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
419
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
420
+ it.
421
+
422
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
423
+ [`PreTrainedTokenizer.__call__`] for details.
424
+
425
+ [What are input IDs?](../glossary#input-ids)
426
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
427
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
428
+
429
+ - 1 for tokens that are **not masked**,
430
+ - 0 for tokens that are **masked**.
431
+
432
+ [What are attention masks?](../glossary#attention-mask)
433
+
434
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
435
+ [`PreTrainedTokenizer.__call__`] for details.
436
+
437
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
438
+ `past_key_values`).
439
+
440
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
441
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
442
+ information on the default strategy.
443
+
444
+ - 1 indicates the head is **not masked**,
445
+ - 0 indicates the head is **masked**.
446
+
447
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
448
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
449
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
450
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
451
+
452
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
453
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
454
+
455
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
456
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
457
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
458
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
459
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
460
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
461
+ model's internal embedding lookup matrix.
462
+ use_cache (`bool`, *optional*):
463
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
464
+ `past_key_values`).
465
+ output_attentions (`bool`, *optional*):
466
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
467
+ tensors for more detail.
468
+ output_hidden_states (`bool`, *optional*):
469
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
470
+ more detail.
471
+ return_dict (`bool`, *optional*):
472
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
473
+ """
474
+
475
+
476
+ @add_start_docstrings(
477
+ "The bare BlueLM Model outputting raw hidden-states without any specific head on top.",
478
+ BlueLM_START_DOCSTRING,
479
+ )
480
+ class BlueLMModel(BlueLMPreTrainedModel):
481
+ """
482
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`BlueLMDecoderLayer`]
483
+
484
+ Args:
485
+ config: BlueLMConfig
486
+ """
487
+
488
+ def __init__(self, config: BlueLMConfig):
489
+ super().__init__(config)
490
+ self.padding_idx = config.pad_token_id
491
+ self.vocab_size = config.vocab_size
492
+
493
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
494
+ if config.use_stable_embedding:
495
+ self.embed_layer_norm = nn.LayerNorm(config.hidden_size,eps=config.rms_norm_eps)
496
+ else:
497
+ self.embed_layer_norm = None
498
+ self.layers = nn.ModuleList([BlueLMDecoderLayer(config) for _ in range(config.num_hidden_layers)])
499
+ if MixedFusedRMSNorm is None:
500
+ self.norm = BlueLMRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
501
+ else:
502
+ self.norm = MixedFusedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
503
+
504
+ self.gradient_checkpointing = False
505
+ # Initialize weights and apply final processing
506
+ self.post_init()
507
+
508
+ def get_input_embeddings(self):
509
+ return self.embed_tokens
510
+
511
+ def set_input_embeddings(self, value):
512
+ self.embed_tokens = value
513
+
514
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
515
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
516
+ # create causal mask
517
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
518
+ combined_attention_mask = None
519
+ if input_shape[-1] > 1:
520
+ combined_attention_mask = _make_causal_mask(
521
+ input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length
522
+ ).to(inputs_embeds.device)
523
+
524
+ if attention_mask is not None:
525
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
526
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
527
+ inputs_embeds.device
528
+ )
529
+ combined_attention_mask = (
530
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
531
+ )
532
+
533
+ return combined_attention_mask
534
+
535
+ def forward(
536
+ self,
537
+ input_ids: torch.LongTensor = None,
538
+ attention_mask: Optional[torch.Tensor] = None,
539
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
540
+ inputs_embeds: Optional[torch.FloatTensor] = None,
541
+ use_cache: Optional[bool] = None,
542
+ output_attentions: Optional[bool] = None,
543
+ output_hidden_states: Optional[bool] = None,
544
+ return_dict: Optional[bool] = None,
545
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
546
+ r"""
547
+ Args:
548
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
549
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
550
+ provide it.
551
+
552
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
553
+ [`PreTrainedTokenizer.__call__`] for details.
554
+
555
+ [What are input IDs?](../glossary#input-ids)
556
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
557
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
558
+
559
+ - 1 for tokens that are **not masked**,
560
+ - 0 for tokens that are **masked**.
561
+
562
+ [What are attention masks?](../glossary#attention-mask)
563
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
564
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
565
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
566
+
567
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
568
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
569
+
570
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
571
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
572
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
573
+ use_cache (`bool`, *optional*):
574
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
575
+ (see `past_key_values`).
576
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
577
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
578
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
579
+ than the model's internal embedding lookup matrix.
580
+ output_attentions (`bool`, *optional*):
581
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
582
+ returned tensors for more detail.
583
+ output_hidden_states (`bool`, *optional*):
584
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
585
+ for more detail.
586
+ return_dict (`bool`, *optional*):
587
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
588
+ """
589
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
590
+ output_hidden_states = (
591
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
592
+ )
593
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
594
+
595
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
596
+
597
+ # retrieve input_ids and inputs_embeds
598
+ if input_ids is not None and inputs_embeds is not None:
599
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
600
+ elif input_ids is not None:
601
+ batch_size, seq_length = input_ids.shape
602
+ elif inputs_embeds is not None:
603
+ batch_size, seq_length, _ = inputs_embeds.shape
604
+ else:
605
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
606
+ seq_length_with_past = seq_length
607
+ past_key_values_length = 0
608
+ if past_key_values is not None:
609
+ past_key_values_length = past_key_values[0][0].shape[1]
610
+ seq_length_with_past = seq_length_with_past + past_key_values_length
611
+ if inputs_embeds is None:
612
+ inputs_embeds = self.embed_tokens(input_ids)
613
+ if self.embed_layer_norm:
614
+ inputs_embeds = self.embed_layer_norm(inputs_embeds)
615
+ # embed positions
616
+ if xops is not None and self.training:
617
+ attention_mask = None
618
+ else:
619
+ if attention_mask is None:
620
+ attention_mask = torch.ones(
621
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
622
+ )
623
+ attention_mask = self._prepare_decoder_attention_mask(
624
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
625
+ )
626
+
627
+ hidden_states = inputs_embeds
628
+
629
+ if self.gradient_checkpointing and self.training:
630
+ if use_cache:
631
+ logger.warning_once(
632
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
633
+ )
634
+ use_cache = False
635
+
636
+ # decoder layers
637
+ all_hidden_states = () if output_hidden_states else None
638
+ all_self_attns = () if output_attentions else None
639
+ next_decoder_cache = () if use_cache else None
640
+
641
+ for idx, decoder_layer in enumerate(self.layers):
642
+ if output_hidden_states:
643
+ all_hidden_states += (hidden_states,)
644
+
645
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
646
+
647
+ if self.gradient_checkpointing and self.training:
648
+
649
+ def create_custom_forward(module):
650
+ def custom_forward(*inputs):
651
+ # None for past_key_value
652
+ return module(*inputs, output_attentions, None)
653
+
654
+ return custom_forward
655
+
656
+ layer_outputs = torch.utils.checkpoint.checkpoint(
657
+ create_custom_forward(decoder_layer),
658
+ hidden_states,
659
+ attention_mask,
660
+ None,
661
+ )
662
+ else:
663
+ layer_outputs = decoder_layer(
664
+ hidden_states,
665
+ attention_mask=attention_mask,
666
+ past_key_value=past_key_value,
667
+ output_attentions=output_attentions,
668
+ use_cache=use_cache,
669
+ )
670
+
671
+ hidden_states = layer_outputs[0]
672
+
673
+ if use_cache:
674
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
675
+
676
+ if output_attentions:
677
+ all_self_attns += (layer_outputs[1],)
678
+
679
+ hidden_states = self.norm(hidden_states)
680
+
681
+ # add hidden states from the last decoder layer
682
+ if output_hidden_states:
683
+ all_hidden_states += (hidden_states,)
684
+
685
+ next_cache = next_decoder_cache if use_cache else None
686
+ if not return_dict:
687
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
688
+ return BaseModelOutputWithPast(
689
+ last_hidden_state=hidden_states,
690
+ past_key_values=next_cache,
691
+ hidden_states=all_hidden_states,
692
+ attentions=all_self_attns,
693
+ )
694
+
695
+
696
+ class BlueLMForCausalLM(BlueLMPreTrainedModel):
697
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
698
+
699
+ def __init__(self, config):
700
+ super().__init__(config)
701
+ self.model = BlueLMModel(config)
702
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
703
+
704
+ # Initialize weights and apply final processing
705
+ self.post_init()
706
+
707
+ def get_input_embeddings(self):
708
+ return self.model.embed_tokens
709
+
710
+ def set_input_embeddings(self, value):
711
+ self.model.embed_tokens = value
712
+
713
+ def get_output_embeddings(self):
714
+ return self.lm_head
715
+
716
+ def set_output_embeddings(self, new_embeddings):
717
+ self.lm_head = new_embeddings
718
+
719
+ def set_decoder(self, decoder):
720
+ self.model = decoder
721
+
722
+ def get_decoder(self):
723
+ return self.model
724
+
725
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
726
+ def forward(
727
+ self,
728
+ input_ids: torch.LongTensor = None,
729
+ attention_mask: Optional[torch.Tensor] = None,
730
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
731
+ inputs_embeds: Optional[torch.FloatTensor] = None,
732
+ labels: Optional[torch.LongTensor] = None,
733
+ use_cache: Optional[bool] = None,
734
+ output_attentions: Optional[bool] = None,
735
+ output_hidden_states: Optional[bool] = None,
736
+ return_dict: Optional[bool] = None,
737
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
738
+ r"""
739
+ Args:
740
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
741
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
742
+ provide it.
743
+
744
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
745
+ [`PreTrainedTokenizer.__call__`] for details.
746
+
747
+ [What are input IDs?](../glossary#input-ids)
748
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
749
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
750
+
751
+ - 1 for tokens that are **not masked**,
752
+ - 0 for tokens that are **masked**.
753
+
754
+ [What are attention masks?](../glossary#attention-mask)
755
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
756
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
757
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
758
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
759
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
760
+
761
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
762
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
763
+
764
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
765
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
766
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
767
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
768
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
769
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
770
+ than the model's internal embedding lookup matrix.
771
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
772
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
773
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
774
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
775
+ use_cache (`bool`, *optional*):
776
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
777
+ (see `past_key_values`).
778
+ output_attentions (`bool`, *optional*):
779
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
780
+ returned tensors for more detail.
781
+ output_hidden_states (`bool`, *optional*):
782
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
783
+ for more detail.
784
+ return_dict (`bool`, *optional*):
785
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
786
+
787
+ Returns:
788
+
789
+ Example:
790
+
791
+ ```python
792
+ >>> from transformers import AutoTokenizer, BlueLMForCausalLM
793
+
794
+ >>> model = BlueLMForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
795
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
796
+
797
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
798
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
799
+
800
+ >>> # Generate
801
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
802
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
803
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
804
+ ```"""
805
+
806
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
807
+ output_hidden_states = (
808
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
809
+ )
810
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
811
+
812
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
813
+ outputs = self.model(
814
+ input_ids=input_ids,
815
+ attention_mask=attention_mask,
816
+ past_key_values=past_key_values,
817
+ inputs_embeds=inputs_embeds,
818
+ use_cache=use_cache,
819
+ output_attentions=output_attentions,
820
+ output_hidden_states=output_hidden_states,
821
+ return_dict=return_dict,
822
+ )
823
+
824
+ hidden_states = outputs[0]
825
+ logits = self.lm_head(hidden_states)
826
+
827
+ loss = None
828
+ if labels is not None:
829
+ # Shift so that tokens < n predict n
830
+ shift_logits = logits[..., :-1, :].contiguous()
831
+ shift_labels = labels[..., 1:].contiguous()
832
+ # Flatten the tokens
833
+ loss_fct = CrossEntropyLoss()
834
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
835
+ shift_labels = shift_labels.view(-1)
836
+ # Enable model/pipeline parallelism
837
+ shift_labels = shift_labels.to(shift_logits.device)
838
+ loss = loss_fct(shift_logits, shift_labels)
839
+
840
+ if not return_dict:
841
+ output = (logits,) + outputs[1:]
842
+ return (loss,) + output if loss is not None else output
843
+
844
+ return CausalLMOutputWithPast(
845
+ loss=loss,
846
+ logits=logits,
847
+ past_key_values=outputs.past_key_values,
848
+ hidden_states=outputs.hidden_states,
849
+ attentions=outputs.attentions,
850
+ )
851
+
852
+ def prepare_inputs_for_generation(
853
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
854
+ ):
855
+ if past_key_values:
856
+ input_ids = input_ids[:, -1:]
857
+
858
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
859
+ if inputs_embeds is not None and past_key_values is None:
860
+ model_inputs = {"inputs_embeds": inputs_embeds}
861
+ else:
862
+ model_inputs = {"input_ids": input_ids}
863
+
864
+ model_inputs.update(
865
+ {
866
+ "past_key_values": past_key_values,
867
+ "use_cache": kwargs.get("use_cache"),
868
+ "attention_mask": attention_mask,
869
+ }
870
+ )
871
+ return model_inputs
872
+
873
+ @staticmethod
874
+ def _reorder_cache(past_key_values, beam_idx):
875
+ reordered_past = ()
876
+ for layer_past in past_key_values:
877
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
878
+ return reordered_past
879
+
880
+
881
+ @add_start_docstrings(
882
+ """
883
+ The BlueLM Model transformer with a sequence classification head on top (linear layer).
884
+
885
+ [`BlueLMForSequenceClassification`] 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
+ BlueLM_START_DOCSTRING,
895
+ )
896
+ class BlueLMForSequenceClassification(BlueLMPreTrainedModel):
897
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
898
+
899
+ def __init__(self, config):
900
+ super().__init__(config)
901
+ self.num_labels = config.num_labels
902
+ self.model = BlueLMModel(config)
903
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
904
+
905
+ # Initialize weights and apply final processing
906
+ self.post_init()
907
+
908
+ def get_input_embeddings(self):
909
+ return self.model.embed_tokens
910
+
911
+ def set_input_embeddings(self, value):
912
+ self.model.embed_tokens = value
913
+
914
+ @add_start_docstrings_to_model_forward(BlueLM_INPUTS_DOCSTRING)
915
+ def forward(
916
+ self,
917
+ input_ids: torch.LongTensor = None,
918
+ attention_mask: Optional[torch.Tensor] = None,
919
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
920
+ inputs_embeds: Optional[torch.FloatTensor] = None,
921
+ labels: Optional[torch.LongTensor] = None,
922
+ use_cache: Optional[bool] = None,
923
+ output_attentions: Optional[bool] = None,
924
+ output_hidden_states: Optional[bool] = None,
925
+ return_dict: Optional[bool] = None,
926
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
927
+ r"""
928
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
929
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
930
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
931
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
932
+ """
933
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
934
+
935
+ transformer_outputs = self.model(
936
+ input_ids,
937
+ past_key_values=past_key_values,
938
+ attention_mask=attention_mask,
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
+ sequence_lengths = -1
957
+ else:
958
+ if input_ids is not None:
959
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
960
+ else:
961
+ sequence_lengths = -1
962
+
963
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
964
+
965
+ loss = None
966
+ if labels is not None:
967
+ if self.config.problem_type is None:
968
+ if self.num_labels == 1:
969
+ self.config.problem_type = "regression"
970
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
971
+ self.config.problem_type = "single_label_classification"
972
+ else:
973
+ self.config.problem_type = "multi_label_classification"
974
+
975
+ if self.config.problem_type == "regression":
976
+ loss_fct = MSELoss()
977
+ if self.num_labels == 1:
978
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
979
+ else:
980
+ loss = loss_fct(pooled_logits, labels)
981
+ elif self.config.problem_type == "single_label_classification":
982
+ loss_fct = CrossEntropyLoss()
983
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
984
+ elif self.config.problem_type == "multi_label_classification":
985
+ loss_fct = BCEWithLogitsLoss()
986
+ loss = loss_fct(pooled_logits, labels)
987
+ if not return_dict:
988
+ output = (pooled_logits,) + transformer_outputs[1:]
989
+ return ((loss,) + output) if loss is not None else output
990
+
991
+ return SequenceClassifierOutputWithPast(
992
+ loss=loss,
993
+ logits=pooled_logits,
994
+ past_key_values=transformer_outputs.past_key_values,
995
+ hidden_states=transformer_outputs.hidden_states,
996
+ attentions=transformer_outputs.attentions,
997
+ )
pytorch_model-00001-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7fbe80002a30b2434f3f1e1650b937a58206766572ad3edc829b49d852c15f32
3
+ size 1944118389
pytorch_model-00002-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb014a3ce998821056c4a39712548657ff38405b77d6c351dab9984c4d4855fb
3
+ size 1933671335
pytorch_model-00003-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9c6a10022c9756d0b7f3cd3ec81b491d18118944ba0a2fd642cbc1da9303e06
3
+ size 1933671399
pytorch_model-00004-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f7fa21a86b36ad7258cc275dbc1c3ae07c4d6474bdb75e5bad0bd3bcae4ee3d5
3
+ size 1990294503
pytorch_model-00005-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae851e1eb4d07a1b6a6208c2826406cfb4dcc7df8ee342c1c0bca98665273ef3
3
+ size 1990294503
pytorch_model-00006-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e6c62d65f92f9075f08c92325e9a6630bd6355135e5faf605bcd02fce9f6832
3
+ size 1990294503
pytorch_model-00007-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:492a134f87ba028313ac4bb6d9dd32341c8d759fc4f4e4da005f102ba22c7bc8
3
+ size 1990303033
pytorch_model-00008-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edb3ea673bcdef37a952220163997a0246521d5902d8af9257be8888ffe036d6
3
+ size 819987370
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 14592532480
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00008-of-00008.bin",
7
+ "model.embed_layer_norm.bias": "pytorch_model-00001-of-00008.bin",
8
+ "model.embed_layer_norm.weight": "pytorch_model-00001-of-00008.bin",
9
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00008.bin",
10
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
11
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00008.bin",
12
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00008.bin",
13
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00008.bin",
14
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
15
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00008.bin",
16
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00008.bin",
17
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00008.bin",
18
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00008.bin",
19
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00008.bin",
20
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00008.bin",
21
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00008.bin",
22
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00008.bin",
23
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00008.bin",
24
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00008.bin",
25
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00008.bin",
26
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00008.bin",
27
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00008.bin",
28
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
29
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
30
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
31
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
32
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
33
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
34
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
35
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
36
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
37
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
38
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
39
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
40
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
41
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
42
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
43
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
44
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
45
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
46
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
47
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
48
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
49
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
50
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
51
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
52
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
53
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
54
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
55
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
56
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
57
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
58
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
59
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
60
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
61
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
62
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
63
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
64
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
65
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
66
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
67
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
68
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
69
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
70
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
71
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
72
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
73
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
74
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
75
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
76
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
77
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
78
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
79
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
80
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
81
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
82
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00004-of-00008.bin",
83
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00004-of-00008.bin",
84
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00004-of-00008.bin",
85
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00004-of-00008.bin",
86
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00004-of-00008.bin",
87
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
88
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00004-of-00008.bin",
89
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
90
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
91
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
92
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
93
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
94
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
95
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
96
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00004-of-00008.bin",
97
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
98
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00004-of-00008.bin",
99
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00004-of-00008.bin",
100
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
101
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
102
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
103
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
104
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
105
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
106
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
107
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
108
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
109
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
110
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
111
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
112
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
113
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
114
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
115
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
116
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
117
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
118
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
119
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00008.bin",
120
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00008.bin",
121
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
122
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
123
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00008.bin",
124
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00008.bin",
125
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00008.bin",
126
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00008.bin",
127
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
128
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
129
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
130
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
131
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
132
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
133
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
134
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
135
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
136
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00005-of-00008.bin",
137
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00005-of-00008.bin",
138
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00005-of-00008.bin",
139
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00005-of-00008.bin",
140
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00005-of-00008.bin",
141
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
142
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00005-of-00008.bin",
143
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
144
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00005-of-00008.bin",
145
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
146
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
147
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
148
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
149
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
150
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00005-of-00008.bin",
151
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
152
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00005-of-00008.bin",
153
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
154
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
155
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
156
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
157
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
158
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
159
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
160
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
161
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
162
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
163
+ "model.layers.24.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
164
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
165
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
166
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
167
+ "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
168
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
169
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
170
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
171
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
172
+ "model.layers.25.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
173
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
174
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
175
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
176
+ "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
177
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
178
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
179
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
180
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
181
+ "model.layers.26.input_layernorm.weight": "pytorch_model-00006-of-00008.bin",
182
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00006-of-00008.bin",
183
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00006-of-00008.bin",
184
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00006-of-00008.bin",
185
+ "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00006-of-00008.bin",
186
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00006-of-00008.bin",
187
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00006-of-00008.bin",
188
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
189
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00006-of-00008.bin",
190
+ "model.layers.27.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
191
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
192
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
193
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
194
+ "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
195
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
196
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
197
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00006-of-00008.bin",
198
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
199
+ "model.layers.28.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
200
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
201
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
202
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
203
+ "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
204
+ "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
205
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
206
+ "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
207
+ "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
208
+ "model.layers.29.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
209
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
210
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
211
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
212
+ "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
213
+ "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
214
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
215
+ "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
216
+ "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
217
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
218
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
219
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
220
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
221
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
222
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
223
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
224
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
225
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
226
+ "model.layers.30.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
227
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
228
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
229
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
230
+ "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
231
+ "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
232
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
233
+ "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
234
+ "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
235
+ "model.layers.31.input_layernorm.weight": "pytorch_model-00007-of-00008.bin",
236
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00007-of-00008.bin",
237
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00007-of-00008.bin",
238
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00007-of-00008.bin",
239
+ "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00007-of-00008.bin",
240
+ "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00007-of-00008.bin",
241
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00007-of-00008.bin",
242
+ "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00007-of-00008.bin",
243
+ "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00007-of-00008.bin",
244
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
245
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
246
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
247
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
248
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
249
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
250
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
251
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
252
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
253
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
254
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
255
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
256
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
257
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
258
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
259
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
260
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
261
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
262
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00002-of-00008.bin",
263
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00002-of-00008.bin",
264
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
265
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00002-of-00008.bin",
266
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00002-of-00008.bin",
267
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
268
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
269
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
270
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
271
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
272
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
273
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00002-of-00008.bin",
274
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
275
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
276
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00002-of-00008.bin",
277
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00002-of-00008.bin",
278
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00002-of-00008.bin",
279
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00002-of-00008.bin",
280
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
281
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
282
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
283
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
284
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
285
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
286
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
287
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
288
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
289
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00003-of-00008.bin",
290
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00003-of-00008.bin",
291
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00003-of-00008.bin",
292
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00003-of-00008.bin",
293
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00003-of-00008.bin",
294
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00003-of-00008.bin",
295
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00003-of-00008.bin",
296
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00003-of-00008.bin",
297
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00003-of-00008.bin",
298
+ "model.norm.weight": "pytorch_model-00007-of-00008.bin"
299
+ }
300
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [],
3
+ "bos_token": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": true,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ "eos_token": {
11
+ "content": "</s>",
12
+ "lstrip": false,
13
+ "normalized": true,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ "unk_token": {
18
+ "content": "<unk>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<pad>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenization_bluelm.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 vivo.
2
+ #
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ """Tokenization classes for BlueLM."""
23
+ import os
24
+ from shutil import copyfile
25
+ from typing import Any, Dict, List, Optional, Tuple
26
+
27
+ import sentencepiece as spm
28
+
29
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
30
+ from transformers.utils import logging
31
+
32
+
33
+ logger = logging.get_logger(__name__)
34
+
35
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
36
+
37
+ PRETRAINED_VOCAB_FILES_MAP = {
38
+ "vocab_file": {},
39
+ "tokenizer_file": {},
40
+ }
41
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
42
+
43
+
44
+ class BlueLMTokenizer(PreTrainedTokenizer):
45
+ """
46
+ Construct a BlueLM tokenizer. Based on byte-level Byte-Pair-Encoding.
47
+
48
+ Args:
49
+ vocab_file (`str`):
50
+ Path to the vocabulary file.
51
+ """
52
+
53
+ vocab_files_names = VOCAB_FILES_NAMES
54
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
55
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
56
+ model_input_names = ["input_ids", "attention_mask"]
57
+
58
+ def __init__(
59
+ self,
60
+ vocab_file,
61
+ unk_token="<unk>",
62
+ bos_token="<s>",
63
+ eos_token="</s>",
64
+ pad_token=None,
65
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
66
+ add_bos_token=True,
67
+ add_eos_token=False,
68
+ clean_up_tokenization_spaces=False,
69
+ **kwargs,
70
+ ):
71
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
72
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
73
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
74
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
75
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
76
+ super().__init__(
77
+ bos_token=bos_token,
78
+ eos_token=eos_token,
79
+ unk_token=unk_token,
80
+ pad_token=pad_token,
81
+ add_bos_token=add_bos_token,
82
+ add_eos_token=add_eos_token,
83
+ sp_model_kwargs=self.sp_model_kwargs,
84
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
85
+ **kwargs,
86
+ )
87
+ self.vocab_file = vocab_file
88
+ self.add_bos_token = add_bos_token
89
+ self.add_eos_token = add_eos_token
90
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
91
+ self.sp_model.Load(vocab_file)
92
+
93
+ def __getstate__(self):
94
+ state = self.__dict__.copy()
95
+ state["sp_model"] = None
96
+ return state
97
+
98
+ def __setstate__(self, d):
99
+ self.__dict__ = d
100
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
101
+ self.sp_model.Load(self.vocab_file)
102
+
103
+ @property
104
+ def vocab_size(self):
105
+ """Returns vocab size"""
106
+ return self.sp_model.get_piece_size()
107
+
108
+ def get_vocab(self):
109
+ """Returns vocab as a dict"""
110
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
111
+ vocab.update(self.added_tokens_encoder)
112
+ return vocab
113
+
114
+ def _tokenize(self, text):
115
+ """Returns a tokenized string."""
116
+ return self.sp_model.encode(text, out_type=str)
117
+
118
+ def _convert_token_to_id(self, token):
119
+ """Converts a token (str) in an id using the vocab."""
120
+ return self.sp_model.piece_to_id(token)
121
+
122
+ def _convert_id_to_token(self, index):
123
+ """Converts an index (integer) in a token (str) using the vocab."""
124
+ token = self.sp_model.IdToPiece(index)
125
+ return token
126
+
127
+ def convert_tokens_to_string(self, tokens):
128
+ """Converts a sequence of tokens (string) in a single string."""
129
+ current_sub_tokens = []
130
+ out_string = ""
131
+ prev_is_special = False
132
+ for i, token in enumerate(tokens):
133
+ # make sure that special tokens are not decoded using sentencepiece model
134
+ if token in self.all_special_tokens:
135
+ if not prev_is_special and i != 0:
136
+ out_string += " "
137
+ out_string += self.sp_model.decode(current_sub_tokens) + token
138
+ prev_is_special = True
139
+ current_sub_tokens = []
140
+ else:
141
+ current_sub_tokens.append(token)
142
+ prev_is_special = False
143
+ out_string += self.sp_model.decode(current_sub_tokens)
144
+ return out_string
145
+
146
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+
150
+ Args:
151
+ save_directory (`str`):
152
+ The directory in which to save the vocabulary.
153
+
154
+ Returns:
155
+ `Tuple(str)`: Paths to the files saved.
156
+ """
157
+ if not os.path.isdir(save_directory):
158
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
159
+ return
160
+ out_vocab_file = os.path.join(
161
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
162
+ )
163
+
164
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
165
+ copyfile(self.vocab_file, out_vocab_file)
166
+ elif not os.path.isfile(self.vocab_file):
167
+ with open(out_vocab_file, "wb") as fi:
168
+ content_spiece_model = self.sp_model.serialized_model_proto()
169
+ fi.write(content_spiece_model)
170
+
171
+ return (out_vocab_file,)
172
+
173
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
174
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
175
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
176
+
177
+ output = bos_token_id + token_ids_0 + eos_token_id
178
+
179
+ if token_ids_1 is not None:
180
+ output = output + bos_token_id + token_ids_1 + eos_token_id
181
+
182
+ return output
183
+
184
+ def get_special_tokens_mask(
185
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
186
+ ) -> List[int]:
187
+ """
188
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
189
+ special tokens using the tokenizer `prepare_for_model` method.
190
+
191
+ Args:
192
+ token_ids_0 (`List[int]`):
193
+ List of IDs.
194
+ token_ids_1 (`List[int]`, *optional*):
195
+ Optional second list of IDs for sequence pairs.
196
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
197
+ Whether or not the token list is already formatted with special tokens for the model.
198
+
199
+ Returns:
200
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
201
+ """
202
+ if already_has_special_tokens:
203
+ return super().get_special_tokens_mask(
204
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
205
+ )
206
+
207
+ bos_token_id = [1] if self.add_bos_token else []
208
+ eos_token_id = [1] if self.add_eos_token else []
209
+
210
+ if token_ids_1 is None:
211
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
212
+ return (
213
+ bos_token_id
214
+ + ([0] * len(token_ids_0))
215
+ + eos_token_id
216
+ + bos_token_id
217
+ + ([0] * len(token_ids_1))
218
+ + eos_token_id
219
+ )
220
+
221
+ def create_token_type_ids_from_sequences(
222
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
223
+ ) -> List[int]:
224
+ """
225
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
226
+ sequence pair mask has the following format:
227
+
228
+ ```
229
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
230
+ | first sequence | second sequence |
231
+ ```
232
+
233
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
234
+
235
+ Args:
236
+ token_ids_0 (`List[int]`):
237
+ List of ids.
238
+ token_ids_1 (`List[int]`, *optional*):
239
+ Optional second list of IDs for sequence pairs.
240
+
241
+ Returns:
242
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
243
+ """
244
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
245
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
246
+
247
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
248
+
249
+ if token_ids_1 is not None:
250
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
251
+
252
+ return output
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5ed07a4a6a74d6a69f56478892da8a06fbaa29dc27ff4d957fda6237643150b
3
+ size 1609668
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": ["tokenization_bluelm.BlueLMTokenizer", null]
4
+ },
5
+ "add_bos_token": true,
6
+ "add_eos_token": false,
7
+ "bos_token": {
8
+ "__type": "AddedToken",
9
+ "content": "<s>",
10
+ "lstrip": false,
11
+ "normalized": true,
12
+ "rstrip": false,
13
+ "single_word": false
14
+ },
15
+ "clean_up_tokenization_spaces": false,
16
+ "eos_token": {
17
+ "__type": "AddedToken",
18
+ "content": "</s>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "model_max_length": 1000000000000000019884624838656,
25
+ "pad_token": {
26
+ "__type": "AddedToken",
27
+ "content": "<pad>",
28
+ "lstrip": false,
29
+ "normalized": true,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ },
33
+ "sp_model_kwargs": {},
34
+ "tokenizer_class": "BlueLMTokenizer",
35
+ "unk_token": {
36
+ "__type": "AddedToken",
37
+ "content": "<unk>",
38
+ "lstrip": false,
39
+ "normalized": true,
40
+ "rstrip": false,
41
+ "single_word": false
42
+ }
43
+ }