hywu commited on
Commit
7b3d4aa
1 Parent(s): 2589983

upload camelidae

Browse files
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_dim": 512,
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_camelidae.CamelidaeConfig",
8
+ "AutoModelForCausalLM": "modeling_camelidae.LlamaForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "eos_token_id": 2,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 7168,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 20480,
16
+ "max_position_embeddings": 4096,
17
+ "model_type": "llama",
18
+ "moe_dtype": "bfloat16",
19
+ "moe_scaling": 0.25,
20
+ "num_attention_heads": 56,
21
+ "num_experts": 8,
22
+ "num_hidden_layers": 60,
23
+ "num_key_value_heads": 8,
24
+ "output_router_logits": false,
25
+ "pad_token_id": 0,
26
+ "pretraining_tp": 1,
27
+ "rms_norm_eps": 1e-05,
28
+ "rope_scaling": null,
29
+ "rope_theta": 5000000.0,
30
+ "tie_word_embeddings": false,
31
+ "topk": 2,
32
+ "torch_dtype": "bfloat16",
33
+ "transformers_version": "4.34.0.dev0",
34
+ "use_cache": true,
35
+ "vocab_size": 64000
36
+ }
configuration_camelidae.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class CamelidaeConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer encoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ pretraining_tp (`int`, *optional*, defaults to `1`):
62
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
63
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
64
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
65
+ issue](https://github.com/pytorch/pytorch/issues/76232).
66
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
67
+ The non-linear activation function (function or string) in the decoder.
68
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
69
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
70
+ just in case (e.g., 512 or 1024 or 2048).
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
74
+ The epsilon used by the rms normalization layers.
75
+ use_cache (`bool`, *optional*, defaults to `True`):
76
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
77
+ relevant if `config.is_decoder=True`.
78
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_scaling (`Dict`, *optional*):
81
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
82
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
83
+ is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
84
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
85
+ these scaling strategies behave:
86
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
87
+ experimental feature, subject to breaking API changes in future versions.
88
+ moe_dtype (`str`, *optional*, default to `"bfloat16"`):
89
+ The `dtype` used for the moe layers. It is preferable to keep the `dtype` to `"bfloat16"`
90
+ moe_scaling (`float`, *optional*, defaults to 0.25):
91
+ The scaling factor of expert.
92
+ num_experts (`int`, *optional*, defaults to 8):
93
+ The number of MoE expert
94
+ topk (`int`, *optional*, defaults to 2):
95
+ The number of experts to root per-token, can be also interpreted as the `top-p` routing
96
+ parameter
97
+ output_router_logits (`bool`, *optional*, defaults to `False`):
98
+ Whether or not the router logits should be returned by the model. Enabeling this will also
99
+ allow the model to output the auxiliary loss.
100
+ adapter_dim (`int`, *optional*, defaults to 64):
101
+ Dimension of the adapter.
102
+ Example:
103
+
104
+ ```python
105
+ >>> from transformers import CamelidaeModel, CamelidaeConfig
106
+
107
+ >>> # Initializing a Camelidae camelidae-7b style configuration
108
+ >>> configuration = CamelidaeConfig()
109
+
110
+ >>> # Initializing a model from the camelidae-7b style configuration
111
+ >>> model = CamelidaeModel(configuration)
112
+
113
+ >>> # Accessing the model configuration
114
+ >>> configuration = model.config
115
+ ```"""
116
+ model_type = "llama"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=32000,
122
+ hidden_size=4096,
123
+ intermediate_size=11008,
124
+ num_hidden_layers=32,
125
+ num_attention_heads=32,
126
+ num_key_value_heads=None,
127
+ hidden_act="silu",
128
+ max_position_embeddings=2048,
129
+ initializer_range=0.02,
130
+ rms_norm_eps=1e-6,
131
+ use_cache=True,
132
+ pad_token_id=None,
133
+ bos_token_id=1,
134
+ eos_token_id=2,
135
+ pretraining_tp=1,
136
+ tie_word_embeddings=False,
137
+ rope_scaling=None,
138
+ moe_dtype="bfloat16",
139
+ moe_scaling=0.25,
140
+ num_experts=8,
141
+ topk=2,
142
+ output_router_logits=False,
143
+ adapter_dim=64,
144
+ **kwargs,
145
+ ):
146
+ self.vocab_size = vocab_size
147
+ self.max_position_embeddings = max_position_embeddings
148
+ self.hidden_size = hidden_size
149
+ self.intermediate_size = intermediate_size
150
+ self.num_hidden_layers = num_hidden_layers
151
+ self.num_attention_heads = num_attention_heads
152
+
153
+ # for backward compatibility
154
+ if num_key_value_heads is None:
155
+ num_key_value_heads = num_attention_heads
156
+
157
+ self.num_key_value_heads = num_key_value_heads
158
+ self.hidden_act = hidden_act
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.pretraining_tp = pretraining_tp
162
+ self.use_cache = use_cache
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_validation()
165
+
166
+ self.moe_dtype = moe_dtype
167
+ self.moe_scaling = moe_scaling
168
+ self.num_experts = num_experts
169
+ self.topk = topk
170
+ self.output_router_logits = output_router_logits
171
+
172
+ self.adapter_dim = adapter_dim
173
+
174
+ super().__init__(
175
+ pad_token_id=pad_token_id,
176
+ bos_token_id=bos_token_id,
177
+ eos_token_id=eos_token_id,
178
+ tie_word_embeddings=tie_word_embeddings,
179
+ **kwargs,
180
+ )
181
+
182
+ def _rope_scaling_validation(self):
183
+ """
184
+ Validate the `rope_scaling` configuration.
185
+ """
186
+ if self.rope_scaling is None:
187
+ return
188
+
189
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
190
+ raise ValueError(
191
+ "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
192
+ f"got {self.rope_scaling}"
193
+ )
194
+ rope_scaling_type = self.rope_scaling.get("type", None)
195
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
196
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
197
+ raise ValueError(
198
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
199
+ )
200
+ if (
201
+ rope_scaling_factor is None
202
+ or not isinstance(rope_scaling_factor, float)
203
+ or rope_scaling_factor <= 1.0
204
+ ):
205
+ raise ValueError(
206
+ f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}"
207
+ )
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": 0,
6
+ "transformers_version": "4.34.0.dev0"
7
+ }
modeling_camelidae.py ADDED
@@ -0,0 +1,1237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import copy
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+ from torch.distributions.normal import Normal
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ MoECausalLMOutputWithPast,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import (
42
+ ModelOutput,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+
49
+ from .configuration_camelidae import CamelidaeConfig
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CONFIG_FOR_DOC = "CamelidaeConfig"
54
+
55
+
56
+ class MoEModelOutputWithPast(ModelOutput):
57
+ last_hidden_state: torch.FloatTensor = None
58
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
59
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
60
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
61
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
62
+
63
+
64
+ class MoECausalLMOutputWithPast(ModelOutput):
65
+ loss: Optional[torch.FloatTensor] = None
66
+ aux_loss: Optional[torch.FloatTensor] = None
67
+ logits: torch.FloatTensor = None
68
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
69
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
70
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
71
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
72
+
73
+
74
+
75
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
76
+ def _make_causal_mask(
77
+ input_ids_shape: torch.Size,
78
+ dtype: torch.dtype,
79
+ device: torch.device,
80
+ past_key_values_length: int = 0,
81
+ ):
82
+ """
83
+ Make causal mask used for bi-directional self-attention.
84
+ """
85
+ bsz, tgt_len = input_ids_shape
86
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
87
+ mask_cond = torch.arange(mask.size(-1), device=device)
88
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
89
+ mask = mask.to(dtype)
90
+
91
+ if past_key_values_length > 0:
92
+ mask = torch.cat(
93
+ [
94
+ torch.zeros(
95
+ tgt_len, past_key_values_length, dtype=dtype, device=device
96
+ ),
97
+ mask,
98
+ ],
99
+ dim=-1,
100
+ )
101
+ return mask[None, None, :, :].expand(
102
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
103
+ )
104
+
105
+
106
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
107
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
108
+ """
109
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
110
+ """
111
+ bsz, src_len = mask.size()
112
+ tgt_len = tgt_len if tgt_len is not None else src_len
113
+
114
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
115
+
116
+ inverted_mask = 1.0 - expanded_mask
117
+
118
+ return inverted_mask.masked_fill(
119
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
120
+ )
121
+
122
+
123
+ class LlamaRMSNorm(nn.Module):
124
+ def __init__(self, hidden_size, eps=1e-6):
125
+ """
126
+ LlamaRMSNorm is equivalent to T5LayerNorm
127
+ """
128
+ super().__init__()
129
+ self.weight = nn.Parameter(torch.ones(hidden_size))
130
+ self.variance_epsilon = eps
131
+
132
+ def forward(self, hidden_states):
133
+ input_dtype = hidden_states.dtype
134
+ hidden_states = hidden_states.to(torch.float32)
135
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
136
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
137
+ return self.weight * hidden_states.to(input_dtype)
138
+
139
+
140
+ class LlamaRotaryEmbedding(torch.nn.Module):
141
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
142
+ super().__init__()
143
+
144
+ self.dim = dim
145
+ self.max_position_embeddings = max_position_embeddings
146
+ self.base = base
147
+ inv_freq = 1.0 / (
148
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
149
+ )
150
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
151
+
152
+ # Build here to make `torch.jit.trace` work.
153
+ self._set_cos_sin_cache(
154
+ seq_len=max_position_embeddings,
155
+ device=self.inv_freq.device,
156
+ dtype=torch.get_default_dtype(),
157
+ )
158
+
159
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
160
+ self.max_seq_len_cached = seq_len
161
+ t = torch.arange(
162
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
163
+ )
164
+
165
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
166
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
167
+ emb = torch.cat((freqs, freqs), dim=-1)
168
+ self.register_buffer(
169
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
170
+ )
171
+ self.register_buffer(
172
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
173
+ )
174
+
175
+ def forward(self, x, seq_len=None):
176
+ # x: [bs, num_attention_heads, seq_len, head_size]
177
+ if seq_len > self.max_seq_len_cached:
178
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
179
+
180
+ return (
181
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
182
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
183
+ )
184
+
185
+
186
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
187
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
188
+
189
+ def __init__(
190
+ self,
191
+ dim,
192
+ max_position_embeddings=2048,
193
+ base=10000,
194
+ device=None,
195
+ scaling_factor=1.0,
196
+ ):
197
+ self.scaling_factor = scaling_factor
198
+ super().__init__(dim, max_position_embeddings, base, device)
199
+
200
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
201
+ self.max_seq_len_cached = seq_len
202
+ t = torch.arange(
203
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
204
+ )
205
+ t = t / self.scaling_factor
206
+
207
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
208
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
209
+ emb = torch.cat((freqs, freqs), dim=-1)
210
+ self.register_buffer(
211
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
212
+ )
213
+ self.register_buffer(
214
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
215
+ )
216
+
217
+
218
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
219
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
220
+
221
+ def __init__(
222
+ self,
223
+ dim,
224
+ max_position_embeddings=2048,
225
+ base=10000,
226
+ device=None,
227
+ scaling_factor=1.0,
228
+ ):
229
+ self.scaling_factor = scaling_factor
230
+ super().__init__(dim, max_position_embeddings, base, device)
231
+
232
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
233
+ self.max_seq_len_cached = seq_len
234
+
235
+ if seq_len > self.max_position_embeddings:
236
+ base = self.base * (
237
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
238
+ - (self.scaling_factor - 1)
239
+ ) ** (self.dim / (self.dim - 2))
240
+ inv_freq = 1.0 / (
241
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
242
+ )
243
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
244
+
245
+ t = torch.arange(
246
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
247
+ )
248
+
249
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
250
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
251
+ emb = torch.cat((freqs, freqs), dim=-1)
252
+ self.register_buffer(
253
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
254
+ )
255
+ self.register_buffer(
256
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
257
+ )
258
+
259
+
260
+ def rotate_half(x):
261
+ """Rotates half the hidden dims of the input."""
262
+ x1 = x[..., : x.shape[-1] // 2]
263
+ x2 = x[..., x.shape[-1] // 2 :]
264
+ return torch.cat((-x2, x1), dim=-1)
265
+
266
+
267
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
268
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
269
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
270
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
271
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
272
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
273
+ q_embed = (q * cos) + (rotate_half(q) * sin)
274
+ k_embed = (k * cos) + (rotate_half(k) * sin)
275
+ return q_embed, k_embed
276
+
277
+
278
+ # Llama MoE
279
+ def load_balancing_loss_func(gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2) -> float:
280
+ r"""
281
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
282
+
283
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
284
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
285
+ experts is too unbalanced.
286
+
287
+ Args:
288
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
289
+ Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_experts].
290
+ num_experts (`int`, *optional*):
291
+ Number of experts
292
+
293
+ Returns:
294
+ The auxiliary loss.
295
+ """
296
+ if gate_logits is None:
297
+ return 0
298
+
299
+ if isinstance(gate_logits, tuple):
300
+ # cat along the layers?
301
+ compute_device = gate_logits[0].device
302
+ gate_logits = torch.cat([gate.to(compute_device) for gate in gate_logits], dim=0)
303
+
304
+ routing_weights, selected_experts = torch.topk(gate_logits, top_k, dim=-1)
305
+ routing_weights = routing_weights.softmax(dim=-1)
306
+
307
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
308
+ if selected_experts.dtype != torch.int64:
309
+ selected_experts = selected_experts.to(torch.int64)
310
+
311
+ if len(selected_experts.shape) == 2:
312
+ selected_experts = selected_experts.unsqueeze(2)
313
+
314
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
315
+
316
+ # For a given token, determine if it was routed to a given expert.
317
+ expert_mask = torch.max(expert_mask, axis=-2).values
318
+
319
+ # cast to float32 otherwise mean will fail
320
+ expert_mask = expert_mask.to(torch.float32)
321
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
322
+
323
+ router_prob_per_group_and_expert = torch.mean(routing_weights, axis=-1)
324
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert.unsqueeze(-1)) * (num_experts**2)
325
+
326
+ class ParallelAdapterMLP(nn.Module):
327
+ def __init__(self, config, adapter_dim, adapter_scaling):
328
+ super().__init__()
329
+ self.config = config
330
+ self.intermediate_size = config.intermediate_size
331
+ self.hidden_size = config.hidden_size
332
+ self.adapter_down = nn.Linear(self.hidden_size, adapter_dim, bias=False)
333
+ self.adapter_up = nn.Linear(adapter_dim, self.hidden_size, bias=False)
334
+ self.adapter_act = nn.GELU()
335
+
336
+ self.adapter_dropout = nn.Dropout(p=0.1)
337
+ self.adapter_scaling = adapter_scaling
338
+
339
+ def forward(self, x):
340
+ x = self.adapter_dropout(x)
341
+ x = self.adapter_scaling * self.adapter_up(self.adapter_act(self.adapter_down(x)))
342
+ return x
343
+
344
+
345
+ class CamelidaeGateAdapter(nn.Module):
346
+ def __init__(self, config: CamelidaeConfig):
347
+ super().__init__()
348
+
349
+ self.intermediate_size = config.intermediate_size
350
+ self.hidden_size = config.hidden_size
351
+
352
+ # Step 1: Router
353
+ self.num_experts = config.num_experts
354
+ self.topk = config.topk
355
+ self.router = nn.Linear(
356
+ config.hidden_size, self.num_experts, bias=False
357
+ )
358
+ self.dtype = getattr(torch, config.moe_dtype)
359
+
360
+ # Step 2: Get the experts
361
+ self.experts = nn.ModuleDict()
362
+ for idx in range(config.num_experts):
363
+ self.experts[f"expert_{idx}"] = ParallelAdapterMLP(config, config.adapter_dim, config.moe_scaling)
364
+
365
+ def forward(self, input_hidden_states, output_hidden_states, router_hidden_states):
366
+ orig_shape = output_hidden_states.shape
367
+ input_hidden_states = input_hidden_states.view(-1, input_hidden_states.shape[-1])
368
+ output_hidden_states = output_hidden_states.view(-1, output_hidden_states.shape[-1])
369
+ router_hidden_states = router_hidden_states.view(-1, router_hidden_states.shape[-1])
370
+
371
+ router_logits = self.router(router_hidden_states)
372
+
373
+ expert_weights, expert_indices = torch.topk(router_logits, self.topk, dim=-1)
374
+ expert_weights = expert_weights.softmax(dim=-1)
375
+ flat_expert_indices = expert_indices.view(-1)
376
+
377
+ input_hidden_states = input_hidden_states.repeat_interleave(self.topk, dim=0)
378
+ expert_hidden_states = output_hidden_states.repeat_interleave(self.topk, dim=0)
379
+ for idx, expert in enumerate(self.experts.values()):
380
+ expert_hidden_states[flat_expert_indices == idx] += expert(input_hidden_states[flat_expert_indices == idx])
381
+ hidden_states = (expert_hidden_states.view(*expert_weights.shape, -1) * expert_weights.unsqueeze(-1)).sum(dim=1)
382
+
383
+ return hidden_states.view(*orig_shape), router_logits
384
+
385
+
386
+ class LlamaMLP(nn.Module):
387
+ def __init__(self, config):
388
+ super().__init__()
389
+ self.config = config
390
+ self.hidden_size = config.hidden_size
391
+ self.intermediate_size = config.intermediate_size
392
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
393
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
394
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
395
+ self.act_fn = ACT2FN[config.hidden_act]
396
+
397
+ self.moe_adapter = CamelidaeGateAdapter(config)
398
+
399
+ def forward(self, x):
400
+ router_hidden_states = x
401
+ up_proj = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
402
+ down_proj = self.down_proj(up_proj)
403
+ down_proj, router_logits = self.moe_adapter(down_proj, down_proj, router_hidden_states)
404
+
405
+ return down_proj, router_logits
406
+
407
+
408
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
409
+ """
410
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
411
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
412
+ """
413
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
414
+ if n_rep == 1:
415
+ return hidden_states
416
+ hidden_states = hidden_states[:, :, None, :, :].expand(
417
+ batch, num_key_value_heads, n_rep, slen, head_dim
418
+ )
419
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
420
+
421
+
422
+ class LlamaAttention(nn.Module):
423
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
424
+
425
+ def __init__(self, config: CamelidaeConfig):
426
+ super().__init__()
427
+ self.config = config
428
+ self.hidden_size = config.hidden_size
429
+ self.num_heads = config.num_attention_heads
430
+ self.head_dim = self.hidden_size // self.num_heads
431
+ self.num_key_value_heads = config.num_key_value_heads
432
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
433
+ self.max_position_embeddings = config.max_position_embeddings
434
+
435
+ if (self.head_dim * self.num_heads) != self.hidden_size:
436
+ raise ValueError(
437
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
438
+ f" and `num_heads`: {self.num_heads})."
439
+ )
440
+ self.q_proj = nn.Linear(
441
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
442
+ )
443
+ self.k_proj = nn.Linear(
444
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
445
+ )
446
+ self.v_proj = nn.Linear(
447
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
448
+ )
449
+ self.o_proj = nn.Linear(
450
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
451
+ )
452
+ self._init_rope()
453
+
454
+ def _init_rope(self):
455
+ if self.config.rope_scaling is None:
456
+ self.rotary_emb = LlamaRotaryEmbedding(
457
+ self.head_dim, max_position_embeddings=self.max_position_embeddings
458
+ )
459
+ else:
460
+ scaling_type = self.config.rope_scaling["type"]
461
+ scaling_factor = self.config.rope_scaling["factor"]
462
+ if scaling_type == "linear":
463
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
464
+ self.head_dim,
465
+ max_position_embeddings=self.max_position_embeddings,
466
+ scaling_factor=scaling_factor,
467
+ )
468
+ elif scaling_type == "dynamic":
469
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
470
+ self.head_dim,
471
+ max_position_embeddings=self.max_position_embeddings,
472
+ scaling_factor=scaling_factor,
473
+ )
474
+ else:
475
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
476
+
477
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
478
+ return (
479
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
480
+ .transpose(1, 2)
481
+ .contiguous()
482
+ )
483
+
484
+ def forward(
485
+ self,
486
+ hidden_states: torch.Tensor,
487
+ attention_mask: Optional[torch.Tensor] = None,
488
+ position_ids: Optional[torch.LongTensor] = None,
489
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
490
+ output_attentions: bool = False,
491
+ use_cache: bool = False,
492
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
493
+ bsz, q_len, _ = hidden_states.size()
494
+
495
+ if self.config.pretraining_tp > 1:
496
+ key_value_slicing = (
497
+ self.num_key_value_heads * self.head_dim
498
+ ) // self.config.pretraining_tp
499
+ query_slices = self.q_proj.weight.split(
500
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
501
+ )
502
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
503
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
504
+
505
+ query_states = [
506
+ F.linear(hidden_states, query_slices[i])
507
+ for i in range(self.config.pretraining_tp)
508
+ ]
509
+ query_states = torch.cat(query_states, dim=-1)
510
+
511
+ key_states = [
512
+ F.linear(hidden_states, key_slices[i])
513
+ for i in range(self.config.pretraining_tp)
514
+ ]
515
+ key_states = torch.cat(key_states, dim=-1)
516
+
517
+ value_states = [
518
+ F.linear(hidden_states, value_slices[i])
519
+ for i in range(self.config.pretraining_tp)
520
+ ]
521
+ value_states = torch.cat(value_states, dim=-1)
522
+
523
+ else:
524
+ query_states = self.q_proj(hidden_states)
525
+ key_states = self.k_proj(hidden_states)
526
+ value_states = self.v_proj(hidden_states)
527
+
528
+ query_states = query_states.view(
529
+ bsz, q_len, self.num_heads, self.head_dim
530
+ ).transpose(1, 2)
531
+ key_states = key_states.view(
532
+ bsz, q_len, self.num_key_value_heads, self.head_dim
533
+ ).transpose(1, 2)
534
+ value_states = value_states.view(
535
+ bsz, q_len, self.num_key_value_heads, self.head_dim
536
+ ).transpose(1, 2)
537
+
538
+ kv_seq_len = key_states.shape[-2]
539
+ if past_key_value is not None:
540
+ kv_seq_len += past_key_value[0].shape[-2]
541
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
542
+ query_states, key_states = apply_rotary_pos_emb(
543
+ query_states, key_states, cos, sin, position_ids
544
+ )
545
+
546
+ if past_key_value is not None:
547
+ # reuse k, v, self_attention
548
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
549
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
550
+
551
+ past_key_value = (key_states, value_states) if use_cache else None
552
+
553
+ # repeat k/v heads if n_kv_heads < n_heads
554
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
555
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
556
+
557
+ attn_weights = torch.matmul(
558
+ query_states, key_states.transpose(2, 3)
559
+ ) / math.sqrt(self.head_dim)
560
+
561
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
562
+ raise ValueError(
563
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
564
+ f" {attn_weights.size()}"
565
+ )
566
+
567
+ if attention_mask is not None:
568
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
569
+ raise ValueError(
570
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
571
+ )
572
+ attn_weights = attn_weights + attention_mask
573
+
574
+ # upcast attention to fp32
575
+ attn_weights = nn.functional.softmax(
576
+ attn_weights, dim=-1, dtype=torch.float32
577
+ ).to(query_states.dtype)
578
+ attn_output = torch.matmul(attn_weights, value_states)
579
+
580
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
581
+ raise ValueError(
582
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
583
+ f" {attn_output.size()}"
584
+ )
585
+
586
+ attn_output = attn_output.transpose(1, 2).contiguous()
587
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
588
+
589
+ if self.config.pretraining_tp > 1:
590
+ attn_output = attn_output.split(
591
+ self.hidden_size // self.config.pretraining_tp, dim=2
592
+ )
593
+ o_proj_slices = self.o_proj.weight.split(
594
+ self.hidden_size // self.config.pretraining_tp, dim=1
595
+ )
596
+ attn_output = sum(
597
+ [
598
+ F.linear(attn_output[i], o_proj_slices[i])
599
+ for i in range(self.config.pretraining_tp)
600
+ ]
601
+ )
602
+ else:
603
+ attn_output = self.o_proj(attn_output)
604
+
605
+ if not output_attentions:
606
+ attn_weights = None
607
+
608
+ return attn_output, attn_weights, past_key_value
609
+
610
+
611
+ class LlamaDecoderLayer(nn.Module):
612
+ def __init__(self, config: CamelidaeConfig):
613
+ super().__init__()
614
+ self.config = config
615
+ self.hidden_size = config.hidden_size
616
+ self.self_attn = LlamaAttention(config=config)
617
+ self.mlp = LlamaMLP(config)
618
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
619
+ self.post_attention_layernorm = LlamaRMSNorm(
620
+ config.hidden_size, eps=config.rms_norm_eps
621
+ )
622
+
623
+ def forward(
624
+ self,
625
+ hidden_states: torch.Tensor,
626
+ attention_mask: Optional[torch.Tensor] = None,
627
+ position_ids: Optional[torch.LongTensor] = None,
628
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
629
+ output_attentions: Optional[bool] = False,
630
+ output_router_logits: Optional[bool] = False,
631
+ use_cache: Optional[bool] = False,
632
+ ) -> Tuple[
633
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
634
+ ]:
635
+ """
636
+ Args:
637
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
638
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
639
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
640
+ output_attentions (`bool`, *optional*):
641
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
642
+ returned tensors for more detail.
643
+ use_cache (`bool`, *optional*):
644
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
645
+ (see `past_key_values`).
646
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
647
+ """
648
+
649
+ residual = hidden_states
650
+
651
+ hidden_states = self.input_layernorm(hidden_states)
652
+ # router_hidden_states = hidden_states
653
+
654
+ # Self Attention
655
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
656
+ hidden_states=hidden_states,
657
+ attention_mask=attention_mask,
658
+ position_ids=position_ids,
659
+ past_key_value=past_key_value,
660
+ output_attentions=output_attentions,
661
+ use_cache=use_cache,
662
+ )
663
+ hidden_states = residual + hidden_states
664
+
665
+ # Fully Connected
666
+ residual = hidden_states
667
+ hidden_states = self.post_attention_layernorm(hidden_states)
668
+ hidden_states, router_logits = self.mlp(hidden_states)
669
+ hidden_states = residual + hidden_states
670
+
671
+ outputs = (hidden_states,)
672
+
673
+ if output_attentions:
674
+ outputs += (self_attn_weights,)
675
+
676
+ if use_cache:
677
+ outputs += (present_key_value,)
678
+
679
+ if output_router_logits:
680
+ outputs += (router_logits,)
681
+
682
+ return outputs
683
+
684
+
685
+ LLAMA_START_DOCSTRING = r"""
686
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
687
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
688
+ etc.)
689
+
690
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
691
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
692
+ and behavior.
693
+
694
+ Parameters:
695
+ config ([`CamelidaeConfig`]):
696
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
697
+ load the weights associated with the model, only the configuration. Check out the
698
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
699
+ """
700
+
701
+
702
+ @add_start_docstrings(
703
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
704
+ LLAMA_START_DOCSTRING,
705
+ )
706
+ class LlamaPreTrainedModel(PreTrainedModel):
707
+ config_class = CamelidaeConfig
708
+ base_model_prefix = "model"
709
+ supports_gradient_checkpointing = True
710
+ _no_split_modules = ["LlamaDecoderLayer"]
711
+ _skip_keys_device_placement = "past_key_values"
712
+
713
+ def _init_weights(self, module):
714
+ std = self.config.initializer_range
715
+ if isinstance(module, nn.Linear):
716
+ module.weight.data.normal_(mean=0.0, std=std)
717
+ if module.bias is not None:
718
+ module.bias.data.zero_()
719
+ elif isinstance(module, nn.Embedding):
720
+ module.weight.data.normal_(mean=0.0, std=std)
721
+ if module.padding_idx is not None:
722
+ module.weight.data[module.padding_idx].zero_()
723
+
724
+ def _set_gradient_checkpointing(self, module, value=False):
725
+ if isinstance(module, LlamaModel):
726
+ module.gradient_checkpointing = value
727
+
728
+
729
+ LLAMA_INPUTS_DOCSTRING = r"""
730
+ Args:
731
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
732
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
733
+ it.
734
+
735
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
736
+ [`PreTrainedTokenizer.__call__`] for details.
737
+
738
+ [What are input IDs?](../glossary#input-ids)
739
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
740
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
741
+
742
+ - 1 for tokens that are **not masked**,
743
+ - 0 for tokens that are **masked**.
744
+
745
+ [What are attention masks?](../glossary#attention-mask)
746
+
747
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
748
+ [`PreTrainedTokenizer.__call__`] for details.
749
+
750
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
751
+ `past_key_values`).
752
+
753
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
754
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
755
+ information on the default strategy.
756
+
757
+ - 1 indicates the head is **not masked**,
758
+ - 0 indicates the head is **masked**.
759
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
760
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
761
+ config.n_positions - 1]`.
762
+
763
+ [What are position IDs?](../glossary#position-ids)
764
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
765
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
766
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
767
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
768
+
769
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
770
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
771
+
772
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
773
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
774
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
775
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
776
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
777
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
778
+ model's internal embedding lookup matrix.
779
+ use_cache (`bool`, *optional*):
780
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
781
+ `past_key_values`).
782
+ output_attentions (`bool`, *optional*):
783
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
784
+ tensors for more detail.
785
+ output_hidden_states (`bool`, *optional*):
786
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
787
+ more detail.
788
+ output_router_logits (`bool`, *optional*):
789
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
790
+ should not be returned during inference.
791
+ return_dict (`bool`, *optional*):
792
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
793
+ """
794
+
795
+
796
+ @add_start_docstrings(
797
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
798
+ LLAMA_START_DOCSTRING,
799
+ )
800
+ class LlamaModel(LlamaPreTrainedModel):
801
+ """
802
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
803
+
804
+ Args:
805
+ config: CamelidaeConfig
806
+ """
807
+
808
+ def __init__(self, config: CamelidaeConfig):
809
+ super().__init__(config)
810
+ self.padding_idx = config.pad_token_id
811
+ self.vocab_size = config.vocab_size
812
+
813
+ self.embed_tokens = nn.Embedding(
814
+ config.vocab_size, config.hidden_size, self.padding_idx
815
+ )
816
+ self.layers = nn.ModuleList(
817
+ [LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]
818
+ )
819
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
820
+
821
+ self.gradient_checkpointing = False
822
+ # Initialize weights and apply final processing
823
+ self.post_init()
824
+
825
+ def get_input_embeddings(self):
826
+ return self.embed_tokens
827
+
828
+ def set_input_embeddings(self, value):
829
+ self.embed_tokens = value
830
+
831
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
832
+ def _prepare_decoder_attention_mask(
833
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
834
+ ):
835
+ # create causal mask
836
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
837
+ combined_attention_mask = None
838
+ if input_shape[-1] > 1:
839
+ combined_attention_mask = _make_causal_mask(
840
+ input_shape,
841
+ inputs_embeds.dtype,
842
+ device=inputs_embeds.device,
843
+ past_key_values_length=past_key_values_length,
844
+ )
845
+
846
+ if attention_mask is not None:
847
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
848
+ expanded_attn_mask = _expand_mask(
849
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
850
+ ).to(inputs_embeds.device)
851
+ combined_attention_mask = (
852
+ expanded_attn_mask
853
+ if combined_attention_mask is None
854
+ else expanded_attn_mask + combined_attention_mask
855
+ )
856
+
857
+ return combined_attention_mask
858
+
859
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
860
+ def forward(
861
+ self,
862
+ input_ids: torch.LongTensor = None,
863
+ attention_mask: Optional[torch.Tensor] = None,
864
+ position_ids: Optional[torch.LongTensor] = None,
865
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
866
+ inputs_embeds: Optional[torch.FloatTensor] = None,
867
+ use_cache: Optional[bool] = None,
868
+ output_attentions: Optional[bool] = None,
869
+ output_hidden_states: Optional[bool] = None,
870
+ output_router_logits: Optional[bool] = None,
871
+ return_dict: Optional[bool] = None,
872
+ ) -> Union[Tuple, MoEModelOutputWithPast]:
873
+ output_attentions = (
874
+ output_attentions
875
+ if output_attentions is not None
876
+ else self.config.output_attentions
877
+ )
878
+ output_hidden_states = (
879
+ output_hidden_states
880
+ if output_hidden_states is not None
881
+ else self.config.output_hidden_states
882
+ )
883
+ output_router_logits = (
884
+ output_router_logits
885
+ if output_router_logits is not None
886
+ else self.config.output_router_logits
887
+ )
888
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
889
+
890
+ return_dict = (
891
+ return_dict if return_dict is not None else self.config.use_return_dict
892
+ )
893
+
894
+ # retrieve input_ids and inputs_embeds
895
+ if input_ids is not None and inputs_embeds is not None:
896
+ raise ValueError(
897
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
898
+ )
899
+ elif input_ids is not None:
900
+ batch_size, seq_length = input_ids.shape
901
+ elif inputs_embeds is not None:
902
+ batch_size, seq_length, _ = inputs_embeds.shape
903
+ else:
904
+ raise ValueError(
905
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
906
+ )
907
+
908
+ seq_length_with_past = seq_length
909
+ past_key_values_length = 0
910
+
911
+ if past_key_values is not None:
912
+ past_key_values_length = past_key_values[0][0].shape[2]
913
+ seq_length_with_past = seq_length_with_past + past_key_values_length
914
+
915
+ if position_ids is None:
916
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
917
+ position_ids = torch.arange(
918
+ past_key_values_length,
919
+ seq_length + past_key_values_length,
920
+ dtype=torch.long,
921
+ device=device,
922
+ )
923
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
924
+ else:
925
+ position_ids = position_ids.view(-1, seq_length).long()
926
+
927
+ if inputs_embeds is None:
928
+ inputs_embeds = self.embed_tokens(input_ids)
929
+ # embed positions
930
+ if attention_mask is None:
931
+ attention_mask = torch.ones(
932
+ (batch_size, seq_length_with_past),
933
+ dtype=torch.bool,
934
+ device=inputs_embeds.device,
935
+ )
936
+ attention_mask = self._prepare_decoder_attention_mask(
937
+ attention_mask,
938
+ (batch_size, seq_length),
939
+ inputs_embeds,
940
+ past_key_values_length,
941
+ )
942
+
943
+ hidden_states = inputs_embeds
944
+
945
+ if self.gradient_checkpointing and self.training:
946
+ if use_cache:
947
+ logger.warning_once(
948
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
949
+ )
950
+ use_cache = False
951
+
952
+ # decoder layers
953
+ all_hidden_states = () if output_hidden_states else None
954
+ all_self_attns = () if output_attentions else None
955
+ all_router_logits = () if output_router_logits else None
956
+ next_decoder_cache = () if use_cache else None
957
+
958
+ for idx, decoder_layer in enumerate(self.layers):
959
+ if output_hidden_states:
960
+ all_hidden_states += (hidden_states,)
961
+
962
+ past_key_value = (
963
+ past_key_values[idx] if past_key_values is not None else None
964
+ )
965
+
966
+ if self.gradient_checkpointing and self.training:
967
+
968
+ def create_custom_forward(module):
969
+ def custom_forward(*inputs):
970
+ # None for past_key_value
971
+ return module(
972
+ *inputs, output_attentions, output_router_logits, None
973
+ )
974
+
975
+ return custom_forward
976
+
977
+ layer_outputs = torch.utils.checkpoint.checkpoint(
978
+ create_custom_forward(decoder_layer),
979
+ hidden_states,
980
+ attention_mask,
981
+ position_ids,
982
+ None,
983
+ )
984
+ else:
985
+ layer_outputs = decoder_layer(
986
+ hidden_states,
987
+ attention_mask=attention_mask,
988
+ position_ids=position_ids,
989
+ past_key_value=past_key_value,
990
+ output_attentions=output_attentions,
991
+ output_router_logits=output_router_logits,
992
+ use_cache=use_cache,
993
+ )
994
+
995
+ hidden_states = layer_outputs[0]
996
+
997
+ if use_cache:
998
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
999
+
1000
+ if output_attentions:
1001
+ all_self_attns += (layer_outputs[1],)
1002
+
1003
+ if output_router_logits:
1004
+ all_router_logits += (layer_outputs[-1],)
1005
+
1006
+ hidden_states = self.norm(hidden_states)
1007
+
1008
+ # add hidden states from the last decoder layer
1009
+ if output_hidden_states:
1010
+ all_hidden_states += (hidden_states,)
1011
+
1012
+ next_cache = next_decoder_cache if use_cache else None
1013
+ if not return_dict:
1014
+ return tuple(
1015
+ v
1016
+ for v in [
1017
+ hidden_states,
1018
+ next_cache,
1019
+ all_hidden_states,
1020
+ all_self_attns,
1021
+ all_router_logits
1022
+ ]
1023
+ if v is not None
1024
+ )
1025
+ return MoEModelOutputWithPast(
1026
+ last_hidden_state=hidden_states,
1027
+ past_key_values=next_cache,
1028
+ hidden_states=all_hidden_states,
1029
+ attentions=all_self_attns,
1030
+ router_logits=all_router_logits,
1031
+ )
1032
+
1033
+
1034
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1035
+ _tied_weights_keys = ["lm_head.weight"]
1036
+
1037
+ def __init__(self, config):
1038
+ super().__init__(config)
1039
+ self.config = config
1040
+ self.model = LlamaModel(config)
1041
+ self.vocab_size = config.vocab_size
1042
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1043
+
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ def get_input_embeddings(self):
1048
+ return self.model.embed_tokens
1049
+
1050
+ def set_input_embeddings(self, value):
1051
+ self.model.embed_tokens = value
1052
+
1053
+ def get_output_embeddings(self):
1054
+ return self.lm_head
1055
+
1056
+ def set_output_embeddings(self, new_embeddings):
1057
+ self.lm_head = new_embeddings
1058
+
1059
+ def set_decoder(self, decoder):
1060
+ self.model = decoder
1061
+
1062
+ def get_decoder(self):
1063
+ return self.model
1064
+
1065
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1066
+ @replace_return_docstrings(
1067
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1068
+ )
1069
+ def forward(
1070
+ self,
1071
+ input_ids: torch.LongTensor = None,
1072
+ attention_mask: Optional[torch.Tensor] = None,
1073
+ position_ids: Optional[torch.LongTensor] = None,
1074
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1075
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1076
+ labels: Optional[torch.LongTensor] = None,
1077
+ use_cache: Optional[bool] = None,
1078
+ output_attentions: Optional[bool] = None,
1079
+ output_hidden_states: Optional[bool] = None,
1080
+ output_router_logits: Optional[bool] = None,
1081
+ return_dict: Optional[bool] = None,
1082
+ ) -> Union[Tuple, MoECausalLMOutputWithPast]:
1083
+ r"""
1084
+ Args:
1085
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1086
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1087
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1088
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1089
+
1090
+ Returns:
1091
+
1092
+ Example:
1093
+
1094
+ ```python
1095
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1096
+
1097
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1098
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1099
+
1100
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1101
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1102
+
1103
+ >>> # Generate
1104
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1105
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1106
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1107
+ ```"""
1108
+
1109
+ output_attentions = (
1110
+ output_attentions
1111
+ if output_attentions is not None
1112
+ else self.config.output_attentions
1113
+ )
1114
+ output_hidden_states = (
1115
+ output_hidden_states
1116
+ if output_hidden_states is not None
1117
+ else self.config.output_hidden_states
1118
+ )
1119
+ output_router_logits = (
1120
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1121
+ )
1122
+ return_dict = (
1123
+ return_dict if return_dict is not None else self.config.use_return_dict
1124
+ )
1125
+
1126
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1127
+ outputs = self.model(
1128
+ input_ids=input_ids,
1129
+ attention_mask=attention_mask,
1130
+ position_ids=position_ids,
1131
+ past_key_values=past_key_values,
1132
+ inputs_embeds=inputs_embeds,
1133
+ use_cache=use_cache,
1134
+ output_attentions=output_attentions,
1135
+ output_hidden_states=output_hidden_states,
1136
+ output_router_logits=output_router_logits,
1137
+ return_dict=return_dict,
1138
+ )
1139
+
1140
+ hidden_states = outputs[0]
1141
+ if self.config.pretraining_tp > 1:
1142
+ lm_head_slices = self.lm_head.weight.split(
1143
+ self.vocab_size // self.config.pretraining_tp, dim=0
1144
+ )
1145
+ logits = [
1146
+ F.linear(hidden_states, lm_head_slices[i])
1147
+ for i in range(self.config.pretraining_tp)
1148
+ ]
1149
+ logits = torch.cat(logits, dim=-1)
1150
+ else:
1151
+ logits = self.lm_head(hidden_states)
1152
+ logits = logits.float()
1153
+
1154
+ loss = None
1155
+
1156
+ if labels is not None:
1157
+ # Shift so that tokens < n predict n
1158
+ shift_logits = logits[..., :-1, :].contiguous()
1159
+ shift_labels = labels[..., 1:].contiguous()
1160
+ # Flatten the tokens
1161
+ loss_fct = CrossEntropyLoss()
1162
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1163
+ shift_labels = shift_labels.view(-1)
1164
+ # Enable model parallelism
1165
+ shift_labels = shift_labels.to(shift_logits.device)
1166
+ loss = loss_fct(shift_logits, shift_labels)
1167
+
1168
+ aux_loss = None
1169
+ if output_router_logits:
1170
+ aux_loss = load_balancing_loss_func(
1171
+ outputs.router_logits if return_dict else outputs[-1], self.config.num_experts, self.config.topk
1172
+ )
1173
+ if labels is not None:
1174
+ loss += 0.01 * aux_loss
1175
+
1176
+ if not return_dict:
1177
+ output = (logits,) + outputs[1:]
1178
+ if output_router_logits:
1179
+ output = (aux_loss,) + output
1180
+ return (loss,) + output if loss is not None else output
1181
+
1182
+ return MoECausalLMOutputWithPast(
1183
+ loss=loss,
1184
+ aux_loss=aux_loss,
1185
+ logits=logits,
1186
+ past_key_values=outputs.past_key_values,
1187
+ hidden_states=outputs.hidden_states,
1188
+ attentions=outputs.attentions,
1189
+ router_logits=outputs.router_logits,
1190
+ )
1191
+
1192
+ def prepare_inputs_for_generation(
1193
+ self,
1194
+ input_ids,
1195
+ past_key_values=None,
1196
+ attention_mask=None,
1197
+ inputs_embeds=None,
1198
+ **kwargs,
1199
+ ):
1200
+ if past_key_values:
1201
+ input_ids = input_ids[:, -1:]
1202
+
1203
+ position_ids = kwargs.get("position_ids", None)
1204
+ if attention_mask is not None and position_ids is None:
1205
+ # create position_ids on the fly for batch generation
1206
+ position_ids = attention_mask.long().cumsum(-1) - 1
1207
+ position_ids.masked_fill_(attention_mask == 0, 1)
1208
+ if past_key_values:
1209
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1210
+
1211
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1212
+ if inputs_embeds is not None and past_key_values is None:
1213
+ model_inputs = {"inputs_embeds": inputs_embeds}
1214
+ else:
1215
+ model_inputs = {"input_ids": input_ids}
1216
+
1217
+ model_inputs.update(
1218
+ {
1219
+ "position_ids": position_ids,
1220
+ "past_key_values": past_key_values,
1221
+ "use_cache": kwargs.get("use_cache"),
1222
+ "attention_mask": attention_mask,
1223
+ }
1224
+ )
1225
+ return model_inputs
1226
+
1227
+ @staticmethod
1228
+ def _reorder_cache(past_key_values, beam_idx):
1229
+ reordered_past = ()
1230
+ for layer_past in past_key_values:
1231
+ reordered_past += (
1232
+ tuple(
1233
+ past_state.index_select(0, beam_idx.to(past_state.device))
1234
+ for past_state in layer_past
1235
+ ),
1236
+ )
1237
+ return reordered_past
pytorch_model-00001-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be87e17aaa3276fea9561a06b9a5353045985c6359834c02751d0ebabd65b4c2
3
+ size 9785334020
pytorch_model-00002-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f26357f97562974c5a7014e2e37c79cd5ca4c6ba54a90946ef5381ad358f5f9f
3
+ size 9866225647
pytorch_model-00003-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83f337e332ccd568a032fe6f2184d1fede3902f7f9dc836557166b8b0664c10c
3
+ size 9866225711
pytorch_model-00004-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:089c9a3e4a328a2e3233fa287381af5949b12e3ee38e5985a480865a3115023c
3
+ size 9866225711
pytorch_model-00005-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26aa62839b58f8b9cec89b6b8feb469af9a3cb51da902153478693d11b833046
3
+ size 9866225711
pytorch_model-00006-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:446f3732079f44742a9f5d9446d479ea1010860bb7c57f6db2a1ae6073e7de07
3
+ size 9866225711
pytorch_model-00007-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8222183fdaecafa2277c32521c6d23b6f9baebf3a0a1c12b75b6a480bbb6a0e
3
+ size 9866225711
pytorch_model-00008-of-00008.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f88e52addaee8aab3f202457e486d14b9d3dd4a8ee728149d87702e95b6fd20a
3
+ size 6849027339
pytorch_model.bin.index.json ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": true,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:386c49cf943d71aa110361135338c50e38beeff0a66593480421f37b319e1a39
3
+ size 1033105
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<|startoftext|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "<|endoftext|>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": true,
22
+ "model_max_length": 4096,
23
+ "pad_token": {
24
+ "__type": "AddedToken",
25
+ "content": "<unk>",
26
+ "lstrip": false,
27
+ "normalized": true,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "sp_model_kwargs": {},
32
+ "spaces_between_special_tokens": false,
33
+ "tokenizer_class": "LlamaTokenizer",
34
+ "unk_token": {
35
+ "__type": "AddedToken",
36
+ "content": "<unk>",
37
+ "lstrip": false,
38
+ "normalized": true,
39
+ "rstrip": false,
40
+ "single_word": false
41
+ },
42
+ "use_default_system_prompt": true
43
+ }