SmerkyG commited on
Commit
770adc2
·
verified ·
1 Parent(s): 121df86

Delete .ipynb_checkpoints

Browse files
.ipynb_checkpoints/added_tokens-checkpoint.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "<s>": 0
3
- }
 
 
 
 
.ipynb_checkpoints/config-checkpoint.json DELETED
@@ -1,26 +0,0 @@
1
- {
2
- "architectures": [
3
- "Rwkv6MoeForCausalLM"
4
- ],
5
- "auto_map": {
6
- "AutoConfig": "configuration_rwkv6_moe.Rwkv6MoeConfig",
7
- "AutoModelForCausalLM": "modeling_rwkv6_moe.Rwkv6MoeForCausalLM"
8
- },
9
- "attention_hidden_size": 4096,
10
- "bos_token_id": 0,
11
- "eos_token_id": 0,
12
- "head_size": 64,
13
- "head_size_divisor": 8,
14
- "hidden_size": 4096,
15
- "intermediate_size": null,
16
- "layer_norm_epsilon": 1e-05,
17
- "model_type": "rwkv6_moe",
18
- "num_attention_heads": 64,
19
- "num_experts": 8,
20
- "num_hidden_layers": 32,
21
- "rescale_every": 6,
22
- "tie_word_embeddings": false,
23
- "transformers_version": "4.34.0",
24
- "use_cache": true,
25
- "vocab_size": 65536
26
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.ipynb_checkpoints/configuration_rwkv6_moe-checkpoint.py DELETED
@@ -1,126 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
3
- # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- """ RWKV configuration"""
17
-
18
- from transformers.configuration_utils import PretrainedConfig
19
- from transformers.utils import logging
20
-
21
-
22
- logger = logging.get_logger(__name__)
23
-
24
- RWKV6_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
-
26
-
27
- class Rwkv6MoeConfig(PretrainedConfig):
28
- """
29
- This is the configuration class to store the configuration of a [`Rwkv6MoeModel`]. It is used to instantiate a RWKV6Moe
30
- model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
31
- defaults will yield a similar configuration to that of the RWVK-4
32
- [RWKV/rwkv-5-world-1b5](https://huggingface.co/RWKV/rwkv-5-world-1b5) architecture.
33
-
34
- Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
- documentation from [`PretrainedConfig`] for more information.
36
-
37
-
38
- Args:
39
- vocab_size (`int`, *optional*, defaults to 65536):
40
- Vocabulary size of the RWKV6Moe model. Defines the number of different tokens that can be represented by the
41
- `inputs_ids` passed when calling [`Rwkv6MoeModel`].
42
- hidden_size (`int`, *optional*, defaults to 768):
43
- Dimensionality of the embeddings and hidden states.
44
- num_hidden_layers (`int`, *optional*, defaults to 24):
45
- Number of hidden layers in the model.
46
- attention_hidden_size (`int`, *optional*):
47
- Dimensionality of the attention hidden states. Will default to `hidden_size` if unset.
48
- num_attention_heads (`int`, *optional*, defaults to 64):
49
- The attention heads to use in rwkv6 self_attention module.
50
- head_size (`int`, *optional*, defaults to 64): head_size of rwkv6 self_attention module.
51
- intermediate_size (`int`, *optional*):
52
- Dimensionality of the inner feed-forward layers. Will default to 4 times `hidden_size` if unset.
53
- layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
54
- The epsilon to use in the layer normalization layers.
55
- shared_expert (`bool`, *optional*, defaults to True):
56
- Whether or not there is a shared expert
57
- num_experts (`int`, *optional*, defaults to 8):
58
- The number of feed forward network experts.
59
- bos_token_id (`int`, *optional*, defaults to 0):
60
- The id of the beginning of sentence token in the vocabulary. Defaults to 0.
61
- eos_token_id (`int`, *optional*, defaults to 0):
62
- The id of the end of sentence token in the vocabulary. Defaults to 0.
63
- rescale_every (`int`, *optional*, defaults to 6):
64
- At inference, the hidden states (and weights of the correponding output layers) are divided by 2 every
65
- `rescale_every` layer. If set to 0 or a negative number, no rescale is done.
66
- tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
- Whether or not to tie the word embeddings with the input token embeddings.
68
- use_cache (`bool`, *optional*, defaults to `True`):
69
- Whether or not the model should return the last state.
70
-
71
-
72
- Example:
73
-
74
- ```python
75
- >>> from transformers import Rwkv6MoeConfig, Rwkv6MoeModel
76
-
77
- >>> # Initializing a Rwkv6Moe configuration
78
- >>> configuration = Rwkv6MoeConfig()
79
-
80
- >>> # Initializing a model (with random weights) from the configuration
81
- >>> model = Rwkv6MoeModel(configuration)
82
-
83
- >>> # Accessing the model configuration
84
- >>> configuration = model.config
85
- ```"""
86
-
87
- model_type = "rwkv6_moe"
88
-
89
- def __init__(
90
- self,
91
- vocab_size=65536,
92
- hidden_size=768,
93
- num_hidden_layers=24,
94
- attention_hidden_size=None,
95
- head_size=64,
96
- head_size_divisor=8,
97
- intermediate_size=None,
98
- layer_norm_epsilon=1e-5,
99
- shared_expert=True,
100
- num_experts=8,
101
- bos_token_id=0,
102
- eos_token_id=0,
103
- rescale_every=6,
104
- tie_word_embeddings=False,
105
- use_cache=True,
106
- **kwargs,
107
- ):
108
- self.vocab_size = vocab_size
109
- self.hidden_size = hidden_size
110
- self.num_hidden_layers = num_hidden_layers
111
- self.attention_hidden_size = attention_hidden_size if attention_hidden_size is not None else hidden_size
112
- self.head_size = head_size
113
- self.head_size_divisor = head_size_divisor
114
- self.intermediate_size = None
115
- self.layer_norm_epsilon = layer_norm_epsilon
116
- self.shared_expert = shared_expert
117
- self.num_experts = num_experts
118
- self.rescale_every = rescale_every
119
- self.use_cache = use_cache
120
-
121
- self.bos_token_id = bos_token_id
122
- self.eos_token_id = eos_token_id
123
-
124
- super().__init__(
125
- tie_word_embeddings=tie_word_embeddings, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs
126
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.ipynb_checkpoints/generation_config-checkpoint.json DELETED
@@ -1,12 +0,0 @@
1
- {
2
- "chat_format": "chatml",
3
- "eos_token_id": 0,
4
- "pad_token_id": 0,
5
- "max_window_size": 4096,
6
- "max_new_tokens": 4096,
7
- "do_sample": true,
8
- "top_k": 0,
9
- "top_p": 0.1,
10
- "repetition_penalty": 1.0,
11
- "transformers_version": "4.31.1"
12
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
.ipynb_checkpoints/modeling_rwkv6_moe-checkpoint.py DELETED
@@ -1,801 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 The RWKV team and HuggingFace Inc. team.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- """PyTorch RWKV6Moe World model."""
16
-
17
- from dataclasses import dataclass
18
- from typing import List, Optional, Tuple, Union
19
-
20
- from pathlib import Path
21
-
22
- import torch
23
- import torch.nn.functional as F
24
- import torch.utils.checkpoint
25
- from torch import nn
26
- from torch.nn import CrossEntropyLoss
27
-
28
- from transformers.modeling_utils import PreTrainedModel
29
- from transformers.utils import (
30
- ModelOutput,
31
- add_code_sample_docstrings,
32
- add_start_docstrings,
33
- add_start_docstrings_to_model_forward,
34
- is_ninja_available,
35
- is_torch_cuda_available,
36
- logging,
37
- )
38
-
39
- from .configuration_rwkv6_moe import Rwkv6MoeConfig
40
- try:
41
- from fla.ops.rwkv6 import fused_recurrent_rwkv6
42
- except ImportError:
43
- print("Required module is not installed. Please install it using the following commands:")
44
- print("pip install -U git+https://github.com/sustcsonglin/flash-linear-attention")
45
- print("Additionally, ensure you have the correct version of Triton installed:")
46
- print("pip install triton==2.2.0")
47
-
48
-
49
- logger = logging.get_logger(__name__)
50
-
51
- _CHECKPOINT_FOR_DOC = "RWKV/rwkv-6-moe-11a41b"
52
- _CONFIG_FOR_DOC = "Rwkv6MoeConfig"
53
-
54
- def rwkv6_moe_linear_attention_cpu(receptance, key, value, time_decay, time_first, state):
55
- # For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel if not executed
56
- # within a torch.no_grad.
57
- batch, seq_length, _ = receptance.shape
58
- num_heads, head_size = time_first.shape
59
- key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2).transpose(-2, -1)
60
- value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
61
- receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2)
62
- time_decay = torch.exp(-torch.exp(time_decay.float())).view(batch, seq_length, num_heads, head_size).permute(0, 2, 3, 1)
63
- time_first = time_first.float().reshape(-1, 1, 1).reshape(num_heads, -1, 1)
64
- out = torch.zeros_like(key).reshape(batch, seq_length, num_heads, head_size)
65
-
66
- for current_index in range(seq_length):
67
- current_receptance = receptance[:, :, current_index:current_index+1, :]
68
- current_key = key[:, :, :, current_index:current_index+1]
69
- current_value = value[:, :, current_index:current_index+1, :]
70
- current_time_decay = time_decay[:, :, :, current_index:current_index+1]
71
- attention_output = current_key @ current_value
72
- out[:, current_index] = (current_receptance @ (time_first * attention_output + state)).squeeze(2)
73
- with torch.no_grad():
74
- state = attention_output + current_time_decay * state
75
-
76
- return out, state
77
-
78
- def rwkv6_moe_linear_attention(
79
- training,
80
- receptance,
81
- key,
82
- value,
83
- time_decay,
84
- time_first,
85
- state,
86
- ):
87
- no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, receptance, key, value])
88
- # Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
89
- # in this case).
90
- one_token = key.size(1) == 1
91
- if not training or no_cuda or one_token:
92
- return rwkv6_moe_linear_attention_cpu(
93
- receptance, key, value, time_decay, time_first, state
94
- )
95
- else:
96
- batch, seq_length, _ = receptance.shape
97
- num_heads, head_size = time_first.shape
98
- key = key.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, T, H, K -> B, H, T, K
99
- value = value.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, T, H, K - > B, H, T, V
100
- receptance = receptance.float().view(batch, seq_length, num_heads, head_size).transpose(1, 2) # B, H, T, K
101
- time_decay = -torch.exp(time_decay.float()).view(batch, seq_length, num_heads, head_size).permute(0, 2, 1, 3) # B, T, H, K -> B, H, T, K
102
- time_first = time_first.float().reshape(num_heads, head_size) # H, K
103
- out, state = fused_recurrent_rwkv6(receptance, key, value, time_decay, time_first, scale=1.0, initial_state=state, output_final_state=True)
104
- return out.transpose(1, 2), state
105
-
106
-
107
- class Rwkv6MoeSelfAttention(nn.Module):
108
- def __init__(self, config, layer_id=0):
109
- super().__init__()
110
- self.config = config
111
- self.layer_id = layer_id
112
- hidden_size = config.hidden_size
113
- attention_hidden_size = config.attention_hidden_size
114
- self.attention_hidden_size = attention_hidden_size
115
- head_size = config.head_size
116
- num_heads = attention_hidden_size // head_size
117
-
118
- self.time_maa_x = nn.Parameter(torch.empty(1, 1, hidden_size))
119
- self.time_maa_w = nn.Parameter(torch.empty(1, 1, hidden_size))
120
- self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
121
- self.time_maa_v = nn.Parameter(torch.empty(1, 1, hidden_size))
122
- self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
123
- self.time_maa_g = nn.Parameter(torch.empty(1, 1, hidden_size))
124
-
125
- TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
126
- if hidden_size == 4096: #7b
127
- TIME_MIX_EXTRA_DIM = 64
128
- self.time_maa_w1 = nn.Parameter(torch.empty(hidden_size, TIME_MIX_EXTRA_DIM*5))
129
- self.time_maa_w2 = nn.Parameter(torch.empty(5, TIME_MIX_EXTRA_DIM, hidden_size))
130
-
131
- self.time_decay = nn.Parameter(torch.empty(1, 1, attention_hidden_size))
132
-
133
- TIME_DECAY_EXTRA_DIM = 64
134
- if hidden_size == 4096: #7b
135
- TIME_DECAY_EXTRA_DIM = 128
136
- self.time_decay_w1 = nn.Parameter(torch.empty(hidden_size, TIME_DECAY_EXTRA_DIM))
137
- self.time_decay_w2 = nn.Parameter(torch.empty(TIME_DECAY_EXTRA_DIM, attention_hidden_size))
138
-
139
- self.time_faaaa = nn.Parameter(torch.empty(num_heads, config.head_size))
140
-
141
-
142
- self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
143
- self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
144
- self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
145
- self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
146
- self.gate = nn.Linear(hidden_size, attention_hidden_size, bias=False)
147
- self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
148
- self.ln_x = nn.GroupNorm(num_heads, hidden_size, eps=(1e-5)*(config.head_size_divisor**2))
149
-
150
- def extract_key_value(self, hidden, state=None):
151
- # Mix hidden with the previous timestep to produce key, value, receptance
152
- if hidden.size(1) == 1 and state is not None:
153
- shifted = state[0][:, :, self.layer_id]
154
- else:
155
- shifted = self.time_shift(hidden)
156
- if state is not None:
157
- shifted[:, 0] = state[0][:, :, self.layer_id]
158
- if len(shifted.size()) == 2:
159
- shifted = shifted.unsqueeze(1)
160
-
161
- x = hidden
162
-
163
- B, T, C = hidden.shape
164
-
165
- xx = shifted - x
166
-
167
- xxx = x + xx * self.time_maa_x
168
- xxx = torch.tanh(xxx @ self.time_maa_w1).view(B*T, 5, -1).transpose(0, 1)
169
- xxx = torch.bmm(xxx, self.time_maa_w2).view(5, B, T, -1)
170
- mw, mk, mv, mr, mg = xxx.unbind(dim=0)
171
-
172
- time_decay = x + xx * (self.time_maa_w + mw)
173
- key = x + xx * (self.time_maa_k + mk)
174
- value = x + xx * (self.time_maa_v + mv)
175
- receptance = x + xx * (self.time_maa_r + mr)
176
- gate = x + xx * (self.time_maa_g + mg)
177
-
178
- receptance = self.receptance(receptance)
179
- key = self.key(key)
180
- value = self.value(value)
181
- gate = F.silu(self.gate(gate))
182
-
183
- time_decay = torch.tanh(time_decay @ self.time_decay_w1) @ self.time_decay_w2
184
- time_decay = self.time_decay + time_decay
185
-
186
- if state is not None:
187
- state[0][:, :, self.layer_id] = hidden[:, -1]
188
-
189
- return receptance, key, value, gate, time_decay, state
190
-
191
- def forward(self, hidden, state=None, use_cache=False, seq_mode=True):
192
- receptance, key, value, gate, time_decay, state = self.extract_key_value(hidden, state=state)
193
-
194
- B,T,C = receptance.shape
195
- H, S = self.time_faaaa.shape
196
-
197
- layer_state = state[1][:, :, :, :, self.layer_id] if state is not None else None
198
- out, layer_state = rwkv6_moe_linear_attention(
199
- self.training, receptance, key, value, time_decay, self.time_faaaa, layer_state,
200
- )
201
-
202
- if layer_state is not None:
203
- state[1][:, :, :, :, self.layer_id] = layer_state
204
-
205
- out = out.reshape(B * T, H * S)
206
- out = F.group_norm(out, num_groups=H, weight=self.ln_x.weight.to(out.dtype), bias=self.ln_x.bias.to(out.dtype), eps=self.ln_x.eps).reshape(B, T, H * S)
207
- out = out.to(dtype=hidden.dtype) * gate
208
- out = self.output(out)
209
- return out, state
210
-
211
- class Rwkv6MoeFeedForwardExpert(nn.Module):
212
- def __init__(self, config, layer_id=0):
213
- super().__init__()
214
- hidden_size = config.hidden_size
215
- # https://github.com/BlinkDL/RWKV-LM/blob/3db37a72356b736966ddd377268f02b80963af3f/RWKV-v4neo/train.py#L168
216
- intermediate_size = (
217
- config.intermediate_size
218
- if config.intermediate_size is not None
219
- else int((config.hidden_size * 3.5) // 32 * 32)
220
- )
221
-
222
- self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
223
- self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
224
-
225
- def forward(self, hidden, state=None):
226
- return self.value( torch.relu( self.key(hidden) ).square() )
227
-
228
- class Rwkv6MoeFeedForward(nn.Module):
229
- def __init__(self, config, layer_id=0):
230
- super().__init__()
231
- self.config = config
232
- self.layer_id = layer_id
233
- hidden_size = config.hidden_size
234
-
235
- self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
236
- self.time_maa_k = nn.Parameter(torch.empty(1, 1, hidden_size))
237
- self.time_maa_r = nn.Parameter(torch.empty(1, 1, hidden_size))
238
-
239
- self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
240
- self.shared_expert = Rwkv6MoeFeedForwardExpert(config, layer_id) if config.shared_expert else None
241
- self.experts = nn.ModuleList([Rwkv6MoeFeedForwardExpert(config, layer_id) for _ in range(config.num_experts)])
242
-
243
- primes = [5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443]
244
- self.hash_prime = primes[layer_id]
245
-
246
- def forward(self, hidden, input_ids:torch.LongTensor, state=None):
247
- if hidden.size(1) == 1 and state is not None:
248
- shifted = state[2][:, :, self.layer_id]
249
- else:
250
- shifted = self.time_shift(hidden)
251
- if state is not None:
252
- shifted[:, 0] = state[2][:, :, self.layer_id]
253
- if len(shifted.size()) == 2:
254
- shifted = shifted.unsqueeze(1)
255
-
256
- delta_hidden_to_shifted = shifted - hidden
257
- hidden_with_tokenshift = hidden + delta_hidden_to_shifted * self.time_maa_k
258
- receptance = hidden + delta_hidden_to_shifted * self.time_maa_r
259
-
260
- receptance = torch.sigmoid(self.receptance(receptance))
261
-
262
- # flatten batch and sequence dimensions of input_ids and hidden_with_tokenshift
263
- flat_input_ids = input_ids.flatten()
264
- flat_hidden_with_tokenshift = hidden_with_tokenshift.reshape(-1, hidden_with_tokenshift.size(-1))
265
-
266
- if self.shared_expert is not None:
267
- flat_value = self.shared_expert(flat_hidden_with_tokenshift)
268
- else:
269
- flat_value = torch.zeros_like(flat_hidden_with_tokenshift)
270
-
271
- # add in contributions from experts
272
-
273
- # find the expert index for each flat index (flattened batchseq index)
274
- expert_by_flat_idx = (flat_input_ids * self.hash_prime) % self.config.num_experts
275
- # one hot mask of expert choices by flat batchseq index
276
- expert_mask = torch.nn.functional.one_hot(expert_by_flat_idx, num_classes=self.config.num_experts).mT # expert_idx, flat_idx
277
- # go through each expert and add in their contributions
278
- for expert_idx in range(self.config.num_experts):
279
- expert = self.experts[expert_idx]
280
- # get a list of flat batchseq indices for the current expert
281
- flat_indices_for_expert = expert_mask[expert_idx].nonzero().flatten()
282
- if flat_indices_for_expert.size(-1) > 0:
283
- # select out the inputs from this expert's flat batchseq locations into a compact tensor
284
- expert_hidden_with_tokenshift = flat_hidden_with_tokenshift[flat_indices_for_expert]
285
- # run the compact tensor through the expert
286
- compact_expert_output = expert(expert_hidden_with_tokenshift)
287
- # add the expert's results to the appropriate original locations
288
- flat_value.index_add_(dim=0, index=flat_indices_for_expert, source=compact_expert_output)
289
-
290
- value = flat_value.view(hidden.size(0), hidden.size(1), hidden.size(2))
291
-
292
- if state is not None:
293
- state[2][:, :, self.layer_id] = hidden[:, -1]
294
-
295
- return receptance * value, state
296
-
297
-
298
- class Rwkv6MoeBlock(nn.Module):
299
- def __init__(self, config, layer_id):
300
- super().__init__()
301
- self.config = config
302
- self.layer_id = layer_id
303
-
304
- if layer_id == 0:
305
- self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
306
-
307
- self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
308
- self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
309
-
310
- self.attention = Rwkv6MoeSelfAttention(config, layer_id)
311
- self.feed_forward = Rwkv6MoeFeedForward(config, layer_id)
312
-
313
- def forward(self, hidden, input_ids:torch.LongTensor, state=None, use_cache=False, output_attentions=False, seq_mode=True):
314
- if self.layer_id == 0:
315
- hidden = self.pre_ln(hidden)
316
- attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache, seq_mode=seq_mode)
317
- hidden = hidden + attention
318
-
319
- feed_forward, state = self.feed_forward(self.ln2(hidden), input_ids=input_ids, state=state)
320
- hidden = hidden + feed_forward
321
-
322
- outputs = (hidden, state)
323
- if output_attentions:
324
- outputs += (attention,)
325
- else:
326
- outputs += (None,)
327
-
328
- return outputs
329
-
330
-
331
- class Rwkv6MoePreTrainedModel(PreTrainedModel):
332
- """
333
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
334
- models.
335
- """
336
-
337
- config_class = Rwkv6MoeConfig
338
- base_model_prefix = "rwkv6moe"
339
- _no_split_modules = ["Rwkv6MoeBlock"]
340
- _keep_in_fp32_modules = ["time_decay", "time_first"]
341
- supports_gradient_checkpointing = True
342
-
343
- def _init_weights(self, module):
344
- """Initialize the weights."""
345
- if isinstance(module, Rwkv6MoeSelfAttention):
346
- layer_id = module.layer_id
347
- num_hidden_layers = module.config.num_hidden_layers
348
- hidden_size = module.config.hidden_size
349
- attention_hidden_size = module.attention_hidden_size
350
- head_size = module.config.head_size
351
- num_heads = attention_hidden_size // head_size
352
-
353
- ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
354
- ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
355
-
356
- time_weight = torch.tensor(
357
- [i / hidden_size for i in range(hidden_size)],
358
- dtype=module.time_maa_k.dtype,
359
- device=module.time_maa_k.device,
360
- )
361
- time_weight = time_weight[None, None, :]
362
-
363
- decay_speed = [
364
- -6.0 + 5.0 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
365
- for h in range(attention_hidden_size)
366
- ]
367
- decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
368
- tmp = torch.tensor(
369
- [
370
- (1.0 - (i / (attention_hidden_size - 1.0))) * ratio_0_to_1 + 0.1 * ((i + 1) % 3 - 1)
371
- for i in range(attention_hidden_size)
372
- ],
373
- dtype=module.time_faaaa.dtype,
374
- device=module.time_faaaa.device,
375
- )
376
-
377
- with torch.no_grad():
378
- module.time_maa_x.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
379
- module.time_maa_w.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
380
- module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
381
- module.time_maa_v.data = 1.0 - (torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1)
382
- module.time_maa_r.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
383
- module.time_maa_g.data = 1.0 - torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
384
-
385
- TIME_MIX_EXTRA_DIM = 32 # generate TIME_MIX for w,k,v,r,g
386
- module.time_maa_w1.data = torch.zeros(hidden_size, TIME_MIX_EXTRA_DIM*5, dtype=module.time_maa_w1.dtype, device=module.time_maa_w1.device).uniform_(-1e-4, 1e-4)
387
- module.time_maa_w2.data = torch.zeros(5, TIME_MIX_EXTRA_DIM, hidden_size, dtype=module.time_maa_w2.dtype, device=module.time_maa_w2.device).uniform_(-1e-4, 1e-4)
388
-
389
- TIME_DECAY_EXTRA_DIM = 64
390
- module.time_decay_w1.data = torch.zeros(hidden_size, TIME_DECAY_EXTRA_DIM, dtype=module.time_decay_w1.dtype, device=module.time_decay_w1.device).uniform_(-1e-4, 1e-4)
391
- module.time_decay_w2.data = torch.zeros(TIME_DECAY_EXTRA_DIM, attention_hidden_size, dtype=module.time_decay_w2.dtype, device=module.time_decay_w2.device).uniform_(-1e-4, 1e-4)
392
-
393
- module.time_decay.data = decay_speed.reshape(num_heads, head_size)
394
- module.time_faaaa.data = tmp.reshape(num_heads, head_size)
395
-
396
- elif isinstance(module, Rwkv6MoeFeedForward):
397
- layer_id = module.layer_id
398
- num_hidden_layers = module.config.num_hidden_layers
399
- hidden_size = module.config.hidden_size
400
-
401
- ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
402
-
403
- time_weight = torch.tensor(
404
- [i / hidden_size for i in range(hidden_size)],
405
- dtype=module.time_maa_k.dtype,
406
- device=module.time_maa_k.device,
407
- )
408
- time_weight = time_weight[None, None, :]
409
-
410
- with torch.no_grad():
411
- module.time_maa_k.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
412
- module.time_maa_r.data = 1.0 - torch.pow(time_weight, ratio_1_to_almost0)
413
-
414
-
415
- @dataclass
416
- class Rwkv6MoeOutput(ModelOutput):
417
- """
418
- Class for the RWKV model outputs.
419
-
420
- Args:
421
- last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
422
- Sequence of hidden-states at the output of the last layer of the model.
423
- state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
424
- The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
425
- avoid providing the old `input_ids`.
426
- hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
427
- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
428
- one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
429
- the model at the output of each layer plus the optional initial embedding outputs.
430
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
431
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
432
- sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
433
- the self-attention heads.
434
- """
435
-
436
- last_hidden_state: torch.FloatTensor = None
437
- state: Optional[List[torch.FloatTensor]] = None
438
- hidden_states: Optional[Tuple[torch.FloatTensor]] = None
439
- attentions: Optional[Tuple[torch.FloatTensor]] = None
440
-
441
-
442
- @dataclass
443
- class Rwkv6MoeCausalLMOutput(ModelOutput):
444
- """
445
- Base class for causal language model (or autoregressive) outputs.
446
-
447
- Args:
448
- loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
449
- Language modeling loss (for next-token prediction).
450
- logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
451
- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
452
- state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
453
- The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
454
- avoid providing the old `input_ids`.
455
- hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
456
- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
457
- one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of
458
- the model at the output of each layer plus the optional initial embedding outputs.
459
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
460
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
461
- sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
462
- the self-attention heads.
463
- """
464
-
465
- loss: Optional[torch.FloatTensor] = None
466
- logits: torch.FloatTensor = None
467
- state: Optional[List[torch.FloatTensor]] = None
468
- hidden_states: Optional[Tuple[torch.FloatTensor]] = None
469
- attentions: Optional[Tuple[torch.FloatTensor]] = None
470
-
471
-
472
- RWKV6MOE_START_DOCSTRING = r"""
473
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
474
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
475
- etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)
476
- subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
477
- general usage and behavior.
478
-
479
- Parameters:
480
- config ([`Rwkv6MoeConfig`]): Model configuration class with all the parameters of the model.
481
- Initializing with a config file does not load the weights associated with the model, only the
482
- configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
483
- """
484
-
485
- RWKV6MOE_INPUTS_DOCSTRING = r"""
486
- Args:
487
- input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
488
- `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
489
- `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
490
- sequence tokens in the vocabulary. If `past_key_values` is used, only `input_ids` that do not have their
491
- past calculated should be passed as `input_ids`. Indices can be obtained using [`AutoTokenizer`]. See
492
- [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
493
- IDs?](../glossary#input-ids)
494
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
495
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
496
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
497
- model's internal embedding lookup matrix.
498
- state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
499
- If passed along, the model uses the previous state in all the blocks (which will give the output for the
500
- `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
501
- use_cache (`bool`, *optional*):
502
- If set to `True`, the last state is returned and can be used to quickly generate the next logits.
503
- output_attentions (`bool`, *optional*):
504
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
505
- tensors for more detail.
506
- output_hidden_states (`bool`, *optional*):
507
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
508
- more detail.
509
- return_dict (`bool`, *optional*):
510
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
511
- """
512
-
513
-
514
- @add_start_docstrings(
515
- "The bare RWKV6Moe Model transformer outputting raw hidden-states without any specific head on top.",
516
- RWKV6MOE_START_DOCSTRING,
517
- )
518
- class Rwkv6MoeModel(Rwkv6MoePreTrainedModel):
519
- def __init__(self, config):
520
- super().__init__(config)
521
-
522
- self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
523
- self.blocks = nn.ModuleList([Rwkv6MoeBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
524
- self.ln_out = nn.LayerNorm(config.hidden_size)
525
-
526
- self.layers_are_rescaled = False
527
- self.gradient_checkpointing = False
528
-
529
- # Initialize weights and apply final processing
530
- self.post_init()
531
-
532
- def get_input_embeddings(self):
533
- return self.embeddings
534
-
535
- def set_input_embeddings(self, new_embeddings):
536
- self.embeddings = new_embeddings
537
-
538
- @add_start_docstrings_to_model_forward(RWKV6MOE_INPUTS_DOCSTRING)
539
- @add_code_sample_docstrings(
540
- checkpoint=_CHECKPOINT_FOR_DOC,
541
- output_type=Rwkv6MoeOutput,
542
- config_class=_CONFIG_FOR_DOC,
543
- )
544
- def forward(
545
- self,
546
- input_ids: Optional[torch.LongTensor] = None,
547
- attention_mask: Optional[torch.LongTensor] = None, # noqa
548
- inputs_embeds: Optional[torch.FloatTensor] = None,
549
- state: Optional[List[torch.FloatTensor]] = None,
550
- use_cache: Optional[bool] = None,
551
- output_attentions: Optional[bool] = None,
552
- output_hidden_states: Optional[bool] = None,
553
- return_dict: Optional[bool] = None,
554
- ) -> Union[Tuple, Rwkv6MoeOutput]:
555
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
556
- output_hidden_states = (
557
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
558
- )
559
- # FIXME - training is supportable with the CUDA code
560
- # rwkv6 only support inference in huggingface.
561
- use_cache = use_cache if use_cache is not None else self.config.use_cache
562
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
563
-
564
- if self.training == self.layers_are_rescaled and (
565
- self.embeddings.weight.dtype == torch.float16 or self.embeddings.weight.dtype == torch.bfloat16
566
- ):
567
- self._rescale_layers()
568
-
569
- if input_ids is None:
570
- raise ValueError("RWKV-MoE requires that you specify input_ids, as it uses these to select experts")
571
- if input_ids is not None and inputs_embeds is not None:
572
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
573
- elif input_ids is None and inputs_embeds is None:
574
- raise ValueError("You have to specify either input_ids or inputs_embeds")
575
-
576
- if inputs_embeds is None:
577
- inputs_embeds = self.embeddings(input_ids)
578
-
579
- if state is None:
580
- state = []
581
- head_size = self.config.head_size
582
- num_heads = self.config.attention_hidden_size // head_size
583
- state_attn_x = torch.zeros(
584
- (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
585
- dtype=inputs_embeds.dtype,
586
- requires_grad=False,
587
- device=inputs_embeds.device,
588
- ).contiguous()
589
- state_attn_kv = torch.zeros(
590
- (
591
- inputs_embeds.size(0),
592
- num_heads,
593
- head_size,
594
- head_size,
595
- self.config.num_hidden_layers,
596
- ),
597
- dtype=torch.float32,
598
- requires_grad=False,
599
- device=inputs_embeds.device,
600
- ).contiguous()
601
- state_ffn_x = torch.zeros(
602
- (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers),
603
- dtype=inputs_embeds.dtype,
604
- requires_grad=False,
605
- device=inputs_embeds.device,
606
- ).contiguous()
607
- state.append(state_attn_x)
608
- state.append(state_attn_kv)
609
- state.append(state_ffn_x)
610
-
611
- seq_mode = inputs_embeds.shape[1] > 1
612
- hidden_states = inputs_embeds
613
-
614
- all_self_attentions = () if output_attentions else None
615
- all_hidden_states = () if output_hidden_states else None
616
- for idx, block in enumerate(self.blocks):
617
- hidden_states, state, attentions = block(
618
- hidden_states, input_ids=input_ids, state=state, use_cache=use_cache, output_attentions=output_attentions, seq_mode=seq_mode
619
- )
620
- if (
621
- self.layers_are_rescaled
622
- and self.config.rescale_every > 0
623
- and (idx + 1) % self.config.rescale_every == 0
624
- ):
625
- hidden_states = hidden_states / 2
626
-
627
- if output_hidden_states:
628
- all_hidden_states = all_hidden_states + (hidden_states,)
629
-
630
- if output_attentions:
631
- all_self_attentions = all_self_attentions + (attentions,)
632
-
633
- hidden_states = self.ln_out(hidden_states)
634
-
635
- if output_hidden_states:
636
- all_hidden_states = all_hidden_states + (hidden_states,)
637
-
638
- if not return_dict:
639
- return (hidden_states, state, all_hidden_states, all_self_attentions)
640
-
641
- return Rwkv6MoeOutput(
642
- last_hidden_state=hidden_states,
643
- state=state,
644
- hidden_states=all_hidden_states, # None
645
- attentions=all_self_attentions, # None
646
- )
647
-
648
- def _rescale_layers(self):
649
- # Layers should be rescaled for inference only.
650
- if self.layers_are_rescaled == (not self.training):
651
- return
652
- if self.config.rescale_every > 0:
653
- with torch.no_grad():
654
- for block_id, block in enumerate(self.blocks):
655
- if self.training:
656
- block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
657
- block.feed_forward.shared_expert.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
658
- for expert in block.feed_forward.experts:
659
- expert.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
660
- else:
661
- # Deal with quantization statistics
662
- if hasattr(block.attention.output.weight, "SCB"):
663
- block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
664
- block.feed_forward.shared_expert.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
665
- for expert in block.feed_forward.experts:
666
- expert.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
667
- elif hasattr(block.attention.output.weight, "quant_state"):
668
- self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
669
- self._bnb_4bit_dequantize_and_rescale(block.feed_forward.shared_expert.value, block_id)
670
- for expert in block.feed_forward.experts:
671
- self._bnb_4bit_dequantize_and_rescale(expert.value, block_id)
672
- else:
673
- block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
674
- block.feed_forward.shared_expert.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
675
- for expert in block.feed_forward.experts:
676
- expert.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
677
-
678
- self.layers_are_rescaled = not self.training
679
-
680
- def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
681
- r"""
682
- Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
683
- be quantized again.
684
- """
685
- if not is_bitsandbytes_available():
686
- raise ImportError("Please install bitsandbytes to use this method.")
687
- import bitsandbytes as bnb
688
-
689
- dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
690
-
691
- dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
692
-
693
- # re-quantize the model:
694
- # we need to put it first on CPU then back to the device
695
- # this will create an overhead :/
696
- # We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
697
- # bugs with bnb
698
- quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
699
- setattr(target_layer, "weight", quant_weight)
700
-
701
-
702
- # copied from HuggingFace https://github.com/huggingface/transformers/blob/main/src/transformers/models/rwkv/modeling_rwkv.py
703
- @add_start_docstrings(
704
- """
705
- The RWKV6Moe Model transformer with a language modeling head on top (linear layer with weights tied to the input
706
- embeddings).
707
- """,
708
- RWKV6MOE_START_DOCSTRING,
709
- )
710
- class Rwkv6MoeForCausalLM(Rwkv6MoePreTrainedModel):
711
- _tied_weights_keys = ["head.weight"]
712
-
713
- def __init__(self, config):
714
- super().__init__(config)
715
- self.model = Rwkv6MoeModel(config)
716
- self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
717
-
718
- # Initialize weights and apply final processing
719
- self.post_init()
720
-
721
- def get_output_embeddings(self):
722
- return self.head
723
-
724
- def set_output_embeddings(self, new_embeddings):
725
- self.head = new_embeddings
726
-
727
- def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, **kwargs):
728
- # only last token for inputs_ids if the state is passed along.
729
- if state is not None:
730
- input_ids = input_ids[:, -1].unsqueeze(-1)
731
-
732
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
733
- if inputs_embeds is not None and state is None:
734
- model_inputs = {"inputs_embeds": inputs_embeds}
735
- else:
736
- model_inputs = {"input_ids": input_ids}
737
-
738
- model_inputs["state"] = state
739
- return model_inputs
740
-
741
- @add_start_docstrings_to_model_forward(RWKV6MOE_INPUTS_DOCSTRING)
742
- @add_code_sample_docstrings(
743
- checkpoint=_CHECKPOINT_FOR_DOC,
744
- output_type=Rwkv6MoeCausalLMOutput,
745
- config_class=_CONFIG_FOR_DOC,
746
- )
747
- def forward(
748
- self,
749
- input_ids: Optional[torch.LongTensor] = None,
750
- attention_mask: Optional[torch.LongTensor] = None,
751
- inputs_embeds: Optional[torch.FloatTensor] = None,
752
- state: Optional[List[torch.FloatTensor]] = None,
753
- labels: Optional[torch.LongTensor] = None,
754
- use_cache: Optional[bool] = None,
755
- output_attentions: Optional[bool] = None,
756
- output_hidden_states: Optional[bool] = None,
757
- return_dict: Optional[bool] = None,
758
- ) -> Union[Tuple, Rwkv6MoeCausalLMOutput]:
759
- r"""
760
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
761
- Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
762
- `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
763
- are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
764
- """
765
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
766
-
767
- outputs = self.model(
768
- input_ids,
769
- inputs_embeds=inputs_embeds,
770
- state=state,
771
- use_cache=use_cache,
772
- output_attentions=output_attentions,
773
- output_hidden_states=output_hidden_states,
774
- return_dict=return_dict,
775
- )
776
- hidden_states = outputs[0]
777
-
778
- logits = self.head(hidden_states)
779
-
780
- loss = None
781
- if labels is not None:
782
- # move labels to correct device to enable model parallelism
783
- labels = labels.to(logits.device)
784
- # Shift so that tokens < n predict n
785
- shift_logits = logits[..., :-1, :].contiguous()
786
- shift_labels = labels[..., 1:].contiguous()
787
- # Flatten the tokens
788
- loss_fct = CrossEntropyLoss()
789
- loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
790
-
791
- if not return_dict:
792
- output = (logits,) + outputs[1:]
793
- return ((loss,) + output) if loss is not None else output
794
-
795
- return Rwkv6MoeCausalLMOutput(
796
- loss=loss,
797
- logits=logits,
798
- state=outputs.state,
799
- hidden_states=outputs.hidden_states,
800
- attentions=outputs.attentions,
801
- )