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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2024 The Qwen team, Alibaba Group 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 RWKV6Qwen2 model."""
|
21 |
+
|
22 |
+
import math
|
23 |
+
import inspect
|
24 |
+
from typing import List, Optional, Tuple, Union, Dict, Any
|
25 |
+
|
26 |
+
import torch
|
27 |
+
import torch.utils.checkpoint
|
28 |
+
from torch import nn
|
29 |
+
import torch.nn.functional as F
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
|
32 |
+
from transformers.cache_utils import Cache, StaticCache, DynamicCache
|
33 |
+
from transformers.generation import GenerationMixin
|
34 |
+
from transformers.modeling_outputs import (
|
35 |
+
BaseModelOutputWithPast,
|
36 |
+
CausalLMOutputWithPast,
|
37 |
+
QuestionAnsweringModelOutput,
|
38 |
+
SequenceClassifierOutputWithPast,
|
39 |
+
TokenClassifierOutput,
|
40 |
+
)
|
41 |
+
from transformers.modeling_utils import PreTrainedModel
|
42 |
+
from transformers.utils import (
|
43 |
+
add_code_sample_docstrings,
|
44 |
+
add_start_docstrings,
|
45 |
+
add_start_docstrings_to_model_forward,
|
46 |
+
is_flash_attn_2_available,
|
47 |
+
is_flash_attn_greater_or_equal_2_10,
|
48 |
+
logging,
|
49 |
+
replace_return_docstrings,
|
50 |
+
)
|
51 |
+
from .configuration_rwkv6qwen2 import RWKV6Qwen2Config
|
52 |
+
|
53 |
+
from transformers.models.qwen2.modeling_qwen2 import Qwen2DecoderLayer, Qwen2MLP, Qwen2RMSNorm, repeat_kv
|
54 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
55 |
+
|
56 |
+
logger = logging.get_logger(__name__)
|
57 |
+
|
58 |
+
|
59 |
+
_CHECKPOINT_FOR_DOC = "RWKV/RWKV6Qwen2-7B"
|
60 |
+
_CONFIG_FOR_DOC = "RWKV6Qwen2Config"
|
61 |
+
|
62 |
+
class RWKV6State(Cache):
|
63 |
+
def __init__(self) -> None:
|
64 |
+
super().__init__()
|
65 |
+
self._seen_tokens = 0 # Used in `generate` to keep tally of how many tokens the cache has seen
|
66 |
+
self.layer_kv_states: List[torch.Tensor] = []
|
67 |
+
self.layer_shift_states: List[torch.Tensor] = []
|
68 |
+
|
69 |
+
def __getitem__(self, layer_idx: int) -> Tuple[torch.Tensor, torch.Tensor]:
|
70 |
+
"""
|
71 |
+
Support for backwards-compatible `past_key_value` indexing, e.g. `past_key_value[0][0].shape[2]` to get the
|
72 |
+
sequence length.
|
73 |
+
"""
|
74 |
+
if layer_idx < len(self):
|
75 |
+
return (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
|
76 |
+
else:
|
77 |
+
raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
|
78 |
+
|
79 |
+
def __iter__(self):
|
80 |
+
"""
|
81 |
+
Support for backwards-compatible `past_key_value` iteration, e.g. `for x in past_key_value:` to iterate over
|
82 |
+
keys and values
|
83 |
+
"""
|
84 |
+
for layer_idx in range(len(self)):
|
85 |
+
yield (self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx])
|
86 |
+
|
87 |
+
def __len__(self):
|
88 |
+
"""
|
89 |
+
Support for backwards-compatible `past_key_value` length, e.g. `len(past_key_value)`. This value corresponds
|
90 |
+
to the number of layers in the model.
|
91 |
+
"""
|
92 |
+
return len(self.layer_kv_states)
|
93 |
+
|
94 |
+
def get_usable_length(self, new_seq_length: int, layer_idx: Optional[int] = 0) -> int:
|
95 |
+
"""Given the sequence length of the new inputs, returns the usable length of the cache."""
|
96 |
+
# Linear Attention variants do not have a maximum length
|
97 |
+
return new_seq_length
|
98 |
+
|
99 |
+
def reorder_cache(self, beam_idx: torch.LongTensor):
|
100 |
+
"""Reorders the cache for beam search, given the selected beam indices."""
|
101 |
+
raise NotImplementedError('Cannot reorder Linear Attention state')
|
102 |
+
|
103 |
+
def get_seq_length(self, layer_idx: int = 0) -> int:
|
104 |
+
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
|
105 |
+
return self._seen_tokens
|
106 |
+
|
107 |
+
def get_max_cache_shape(self) -> Optional[int]:
|
108 |
+
"""Returns the maximum sequence length of the cache object. DynamicCache does not have a maximum length."""
|
109 |
+
return None
|
110 |
+
|
111 |
+
def get_max_length(self) -> Optional[int]:
|
112 |
+
"""
|
113 |
+
Returns the maximum sequence length of the cached states. DynamicCache does not have a maximum length.
|
114 |
+
"""
|
115 |
+
return None
|
116 |
+
|
117 |
+
# def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
|
118 |
+
# """Converts the `DynamicCache` instance into the its equivalent in the legacy cache format. Used for
|
119 |
+
# backward compatibility."""
|
120 |
+
# legacy_cache = ()
|
121 |
+
# for layer_idx in range(len(self)):
|
122 |
+
# legacy_cache += ((self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx]),)
|
123 |
+
# return legacy_cache
|
124 |
+
|
125 |
+
# @classmethod
|
126 |
+
# #@deprecate_kwarg("num_hidden_layers", version="4.47.0")
|
127 |
+
# def from_legacy_cache(
|
128 |
+
# cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor, torch.FloatTensor]]] = None, num_hidden_layers: int | None = None
|
129 |
+
# ) -> "RWKV6State":
|
130 |
+
# """Converts a cache in the legacy cache format into an equivalent `DynamicCache`. Used for
|
131 |
+
# backward compatibility."""
|
132 |
+
# cache = cls()
|
133 |
+
# if past_key_values is not None:
|
134 |
+
# for layer_idx in range(len(past_key_values)):
|
135 |
+
# layer_kv_state, layer_shift_state = past_key_values[layer_idx]
|
136 |
+
# cache.update(layer_kv_state, layer_shift_state, layer_idx)
|
137 |
+
# return cache
|
138 |
+
|
139 |
+
def crop(self, max_length: int):
|
140 |
+
# can't implement this for linear attention variants
|
141 |
+
return
|
142 |
+
|
143 |
+
@torch.no_grad
|
144 |
+
def update(
|
145 |
+
self,
|
146 |
+
kv_state: torch.Tensor,
|
147 |
+
shift_state: torch.Tensor,
|
148 |
+
token_count: int,
|
149 |
+
layer_idx: int,
|
150 |
+
cache_kwargs: Optional[Dict[str, Any]] = None,
|
151 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
152 |
+
# Update the number of seen tokens
|
153 |
+
if layer_idx == 0:
|
154 |
+
self._seen_tokens += token_count
|
155 |
+
|
156 |
+
# Update the cache
|
157 |
+
# There may be skipped layers, fill them with empty lists
|
158 |
+
for _ in range(len(self.layer_kv_states), layer_idx + 1):
|
159 |
+
self.layer_kv_states.append(torch.zeros_like(kv_state).requires_grad_(False))
|
160 |
+
self.layer_shift_states.append(torch.zeros_like(shift_state).requires_grad_(False))
|
161 |
+
self.layer_kv_states[layer_idx].copy_(kv_state)
|
162 |
+
self.layer_shift_states[layer_idx].copy_(shift_state)
|
163 |
+
|
164 |
+
return self.layer_kv_states[layer_idx], self.layer_shift_states[layer_idx]
|
165 |
+
|
166 |
+
# @deprecate_kwarg("num_hidden_layers", version="4.47.0")
|
167 |
+
# def batch_split(
|
168 |
+
# self, full_batch_size: int, split_size: int, num_hidden_layers: int = None
|
169 |
+
# ) -> List["DynamicCache"]:
|
170 |
+
# """Split the current instance into a list of `DynamicCache` by the batch size. This will be used by
|
171 |
+
# `_split_model_inputs()` in `generation.utils`"""
|
172 |
+
# out = []
|
173 |
+
# for i in range(0, full_batch_size, split_size):
|
174 |
+
# current_split = DynamicCache()
|
175 |
+
# current_split._seen_tokens = self._seen_tokens
|
176 |
+
# current_split.key_cache = [tensor[i : i + split_size] for tensor in self.key_cache]
|
177 |
+
# current_split.value_cache = [tensor[i : i + split_size] for tensor in self.value_cache]
|
178 |
+
# out.append(current_split)
|
179 |
+
# return out
|
180 |
+
|
181 |
+
# @classmethod
|
182 |
+
# @deprecate_kwarg("num_hidden_layers", version="4.47.0")
|
183 |
+
# def from_batch_splits(cls, splits: List["DynamicCache"], num_hidden_layers: int = None) -> "DynamicCache":
|
184 |
+
# """This is the opposite of the above `batch_split()` method. This will be used by `stack_model_outputs` in
|
185 |
+
# `generation.utils`"""
|
186 |
+
# cache = cls()
|
187 |
+
# for idx in range(len(splits[0])):
|
188 |
+
# key_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
|
189 |
+
# value_cache = [current.key_cache[idx] for current in splits if current.key_cache[idx] != []]
|
190 |
+
# if key_cache != []:
|
191 |
+
# layer_keys = torch.cat(key_cache, dim=0)
|
192 |
+
# layer_values = torch.cat(value_cache, dim=0)
|
193 |
+
# cache.update(layer_keys, layer_values, idx)
|
194 |
+
# return cache
|
195 |
+
|
196 |
+
# def batch_repeat_interleave(self, repeats: int):
|
197 |
+
# """Repeat the cache `repeats` times in the batch dimension. Used in contrastive search."""
|
198 |
+
# for layer_idx in range(len(self)):
|
199 |
+
# self.key_cache[layer_idx] = self.key_cache[layer_idx].repeat_interleave(repeats, dim=0)
|
200 |
+
# self.value_cache[layer_idx] = self.value_cache[layer_idx].repeat_interleave(repeats, dim=0)
|
201 |
+
|
202 |
+
# def batch_select_indices(self, indices: torch.Tensor):
|
203 |
+
# """Only keep the `indices` in the batch dimension of the cache. Used in contrastive search."""
|
204 |
+
# for layer_idx in range(len(self)):
|
205 |
+
# self.key_cache[layer_idx] = self.key_cache[layer_idx][indices, ...]
|
206 |
+
# self.value_cache[layer_idx] = self.value_cache[layer_idx][indices, ...]
|
207 |
+
|
208 |
+
try:
|
209 |
+
#from fla.ops.gla.chunk import chunk_gla
|
210 |
+
from fla.ops.gla.fused_recurrent import fused_recurrent_gla
|
211 |
+
except ImportError:
|
212 |
+
print("Required module is not installed. Please install it using the following commands:")
|
213 |
+
print("pip install -U git+https://github.com/fla-org/flash-linear-attention")
|
214 |
+
print("Additionally, ensure you have at least version 2.2.0 of Triton installed:")
|
215 |
+
print("pip install triton>=2.2.0")
|
216 |
+
|
217 |
+
class Qwen2RotaryEmbedding(nn.Module):
|
218 |
+
def __init__(self, config: RWKV6Qwen2Config, device=None):
|
219 |
+
super().__init__()
|
220 |
+
# BC: "rope_type" was originally "type"
|
221 |
+
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
222 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
223 |
+
else:
|
224 |
+
self.rope_type = "default"
|
225 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
226 |
+
self.original_max_seq_len = config.max_position_embeddings
|
227 |
+
|
228 |
+
self.config = config
|
229 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
230 |
+
|
231 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
232 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
233 |
+
self.original_inv_freq = self.inv_freq
|
234 |
+
|
235 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
236 |
+
"""
|
237 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
238 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
239 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
240 |
+
"""
|
241 |
+
seq_len = torch.max(position_ids) + 1
|
242 |
+
if seq_len > self.max_seq_len_cached: # growth
|
243 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
244 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
245 |
+
self.max_seq_len_cached = seq_len
|
246 |
+
|
247 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
248 |
+
# This .to() is needed if the model has been moved to a device after being initialized (because
|
249 |
+
# the buffer is automatically moved, but not the original copy)
|
250 |
+
self.original_inv_freq = self.original_inv_freq.to(device)
|
251 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
252 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
253 |
+
|
254 |
+
@torch.no_grad()
|
255 |
+
def forward(self, x, position_ids):
|
256 |
+
if "dynamic" in self.rope_type:
|
257 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
258 |
+
|
259 |
+
# Core RoPE block
|
260 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
261 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
262 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
263 |
+
device_type = x.device.type
|
264 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
265 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
266 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
267 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
268 |
+
cos = emb.cos()
|
269 |
+
sin = emb.sin()
|
270 |
+
|
271 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
272 |
+
cos = cos * self.attention_scaling
|
273 |
+
sin = sin * self.attention_scaling
|
274 |
+
|
275 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
276 |
+
|
277 |
+
def generate_rotary_embedding(max_seqlen:int, dim:int, theta:float = 10000.0, scale:float = 1):
|
278 |
+
#inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float).to(device) / dim))
|
279 |
+
|
280 |
+
angular_velocity = theta ** -(torch.arange(0, dim, 2, dtype=torch.float) / dim) / scale # frequencies from 1.0 ... 1/theta
|
281 |
+
angles = torch.outer(torch.arange(max_seqlen), angular_velocity)
|
282 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
283 |
+
emb = torch.cat((angles, angles), dim=-1)
|
284 |
+
return torch.stack([emb.cos(), emb.sin()], dim=0)
|
285 |
+
#return torch.polar(torch.ones_like(angles), angles)
|
286 |
+
|
287 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
288 |
+
def rotate_half(x):
|
289 |
+
"""Rotates half the hidden dims of the input."""
|
290 |
+
x1 = x[..., : x.shape[-1] // 2]
|
291 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
292 |
+
return torch.cat((-x2, x1), dim=-1)
|
293 |
+
|
294 |
+
# # Copied from transformers.models.mixtral.modeling_mixtral.apply_rotary_pos_emb
|
295 |
+
# def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim:int=1):
|
296 |
+
# B, L = q.size(0), q.size(-2)
|
297 |
+
# cos = cos[:L].unsqueeze(0).expand(B,L,-1).unsqueeze(unsqueeze_dim)
|
298 |
+
# sin = sin[:L].unsqueeze(0).expand(B,L,-1).unsqueeze(unsqueeze_dim)
|
299 |
+
# q_embed = (q * cos) + (rotate_half(q) * sin)
|
300 |
+
# k_embed = (k * cos) + (rotate_half(k) * sin)
|
301 |
+
# return q_embed, k_embed
|
302 |
+
|
303 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
304 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
305 |
+
|
306 |
+
Args:
|
307 |
+
q (`torch.Tensor`): The query tensor.
|
308 |
+
k (`torch.Tensor`): The key tensor.
|
309 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
310 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
311 |
+
position_ids (`torch.Tensor`, *optional*):
|
312 |
+
Deprecated and unused.
|
313 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
314 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
315 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
316 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
317 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
318 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
319 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
320 |
+
Returns:
|
321 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
322 |
+
"""
|
323 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
324 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
325 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
326 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
327 |
+
return q_embed, k_embed
|
328 |
+
|
329 |
+
def ortho_init(x, scale):
|
330 |
+
with torch.no_grad():
|
331 |
+
shape = x.shape
|
332 |
+
if len(shape) == 2:
|
333 |
+
gain = math.sqrt(shape[0] / shape[1]) if shape[0] > shape[1] else 1
|
334 |
+
#nn.init.orthogonal_(x, gain=gain * scale)
|
335 |
+
x.copy_(nn.init.orthogonal_(torch.empty_like(x, dtype=torch.float32), gain=gain * scale))
|
336 |
+
elif len(shape) == 3:
|
337 |
+
gain = math.sqrt(shape[1] / shape[2]) if shape[1] > shape[2] else 1
|
338 |
+
for i in range(shape[0]):
|
339 |
+
#nn.init.orthogonal_(x[i], gain=gain * scale)
|
340 |
+
x[i].copy_(nn.init.orthogonal_(torch.empty_like(x[i], dtype=torch.float32), gain=gain * scale))
|
341 |
+
else:
|
342 |
+
assert False
|
343 |
+
return x
|
344 |
+
|
345 |
+
class RWKV6Attention(nn.Module):
|
346 |
+
def __init__(self, config, layer_idx: Optional[int] = None):
|
347 |
+
super().__init__()
|
348 |
+
self.config = config
|
349 |
+
self.layer_idx = layer_idx
|
350 |
+
|
351 |
+
if layer_idx is None:
|
352 |
+
logger.warning_once(
|
353 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
354 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
355 |
+
"when creating this class."
|
356 |
+
)
|
357 |
+
|
358 |
+
self.hidden_size = config.hidden_size
|
359 |
+
self.num_heads = config.num_attention_heads
|
360 |
+
self.head_dim = getattr(config, 'head_dim', self.hidden_size // self.num_heads)
|
361 |
+
self.num_key_value_heads = config.num_key_value_heads
|
362 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
363 |
+
self.attention_dropout = config.attention_dropout
|
364 |
+
|
365 |
+
n_layer = self.config.num_hidden_layers
|
366 |
+
n_embd = self.hidden_size
|
367 |
+
dim_att = self.num_heads * self.head_dim
|
368 |
+
layer_id = self.layer_idx
|
369 |
+
|
370 |
+
if self.hidden_size % self.num_heads != 0:
|
371 |
+
raise ValueError(
|
372 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
373 |
+
f" and `num_heads`: {self.num_heads})."
|
374 |
+
)
|
375 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
376 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
377 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
378 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=getattr(config, 'attention_output_bias', config.attention_bias))
|
379 |
+
|
380 |
+
calc_lora_rank = lambda exponent, multiplier: max(1, round(self.hidden_size ** exponent * multiplier / 32)) * 32
|
381 |
+
|
382 |
+
if config.gate_rank_type == 1:
|
383 |
+
self.gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
384 |
+
elif config.gate_rank_type == 2:
|
385 |
+
lora_rank_gate = config.lora_rank_gate or calc_lora_rank(0.8, 0.6)
|
386 |
+
self.g1 = nn.Parameter(torch.empty(n_embd, lora_rank_gate))
|
387 |
+
self.g2 = nn.Parameter(torch.empty(lora_rank_gate, n_embd))
|
388 |
+
|
389 |
+
if config.groupnorm_att:
|
390 |
+
self.ln_x = nn.GroupNorm(self.num_heads, dim_att, eps=self.head_dim * 1e-5)
|
391 |
+
|
392 |
+
with torch.no_grad():
|
393 |
+
if config.gate_rank_type == 1:
|
394 |
+
self.gate.weight.zero_()
|
395 |
+
elif config.gate_rank_type == 2:
|
396 |
+
self.g1.zero_()
|
397 |
+
ortho_init(self.g2, 0.1)
|
398 |
+
|
399 |
+
ratio_0_to_1 = layer_id / (n_layer - 1) # 0 to 1
|
400 |
+
ratio_1_to_almost0 = 1.0 - (layer_id / n_layer) # 1 to ~0
|
401 |
+
|
402 |
+
if self.config.use_tokenshift:
|
403 |
+
ddd = torch.ones(1, 1, n_embd)
|
404 |
+
for i in range(n_embd):
|
405 |
+
ddd[0, 0, i] = i / n_embd
|
406 |
+
|
407 |
+
ddd = torch.zeros(1, 1, n_embd)
|
408 |
+
self.time_maa_x = nn.Parameter(1.0 - torch.pow(ddd, ratio_1_to_almost0))
|
409 |
+
self.time_maa_r = nn.Parameter(torch.zeros_like(ddd))
|
410 |
+
self.time_maa_k = nn.Parameter(torch.zeros_like(ddd))
|
411 |
+
self.time_maa_v = nn.Parameter(torch.zeros_like(ddd))
|
412 |
+
self.time_maa_w = nn.Parameter(torch.zeros_like(ddd))
|
413 |
+
self.time_maa_g = nn.Parameter(torch.zeros_like(ddd))
|
414 |
+
|
415 |
+
lora_rank_tokenshift = config.lora_rank_tokenshift or (32 if n_embd < 4096 else 64)
|
416 |
+
|
417 |
+
self.time_maa_w2 = nn.Parameter(torch.zeros(5, lora_rank_tokenshift, n_embd).uniform_(-0.01, 0.01))
|
418 |
+
self.time_maa_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_tokenshift*self.time_maa_w2.size(0)))
|
419 |
+
|
420 |
+
lora_rank_decay = config.lora_rank_decay or (64 if n_embd < 4096 else 128)
|
421 |
+
|
422 |
+
# RWKV-6
|
423 |
+
decay_speed = torch.ones(dim_att)
|
424 |
+
for n in range(dim_att):
|
425 |
+
decay_speed[n] = -6 + 5 * (n / (dim_att - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
|
426 |
+
self.time_decay = nn.Parameter(decay_speed.reshape(1,1,dim_att))
|
427 |
+
self.time_decay_w1 = nn.Parameter(torch.zeros(n_embd, lora_rank_decay))
|
428 |
+
self.time_decay_w2 = nn.Parameter(torch.zeros(lora_rank_decay, dim_att).uniform_(-0.01, 0.01))
|
429 |
+
|
430 |
+
def forward(
|
431 |
+
self,
|
432 |
+
hidden_states: torch.Tensor,
|
433 |
+
attention_mask: Optional[torch.Tensor] = None,
|
434 |
+
position_ids: Optional[torch.LongTensor] = None,
|
435 |
+
past_key_values: Optional[RWKV6State] = None,
|
436 |
+
output_attentions: bool = False,
|
437 |
+
use_cache: bool = False,
|
438 |
+
cache_position: Optional[torch.LongTensor] = None,
|
439 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
440 |
+
):
|
441 |
+
output_shift_state = hidden_states[:, -1:].detach().clone()
|
442 |
+
|
443 |
+
bsz, q_len, hidden_dim = hidden_states.size()
|
444 |
+
H = self.num_heads
|
445 |
+
|
446 |
+
x = hidden_states
|
447 |
+
|
448 |
+
if use_cache and past_key_values is not None and len(past_key_values) > self.layer_idx:
|
449 |
+
input_kv_state, input_shift_state = past_key_values[self.layer_idx]
|
450 |
+
xprev = torch.cat([input_shift_state, x[:, :-1]], dim=1)
|
451 |
+
else:
|
452 |
+
input_kv_state = None
|
453 |
+
xprev = F.pad(x, (0, 0, 1, -1))
|
454 |
+
|
455 |
+
if self.config.use_tokenshift:
|
456 |
+
dxprev = xprev - x
|
457 |
+
|
458 |
+
xxx = x + dxprev * self.time_maa_x
|
459 |
+
xxx = torch.tanh(xxx @ self.time_maa_w1).view(bsz*q_len, self.time_maa_w2.size(0), -1).transpose(0, 1)
|
460 |
+
xxx = torch.bmm(xxx, self.time_maa_w2).view(self.time_maa_w2.size(0), bsz, q_len, hidden_dim)
|
461 |
+
|
462 |
+
mr, mk, mv, mw, mg = xxx.unbind(dim=0)
|
463 |
+
xr = x + dxprev * (self.time_maa_r + mr)
|
464 |
+
xk = x + dxprev * (self.time_maa_k + mk)
|
465 |
+
xv = x + dxprev * (self.time_maa_v + mv)
|
466 |
+
xw = x + dxprev * (self.time_maa_w + mw)
|
467 |
+
xg = x + dxprev * (self.time_maa_g + mg)
|
468 |
+
else:
|
469 |
+
xr = xk = xv = xw = xg = x
|
470 |
+
|
471 |
+
query_states = self.q_proj(xr)
|
472 |
+
key_states = self.k_proj(xk)
|
473 |
+
value_states = self.v_proj(xv)
|
474 |
+
decay_states = (self.time_decay + torch.tanh(xw @ self.time_decay_w1) @ self.time_decay_w2).to(query_states.dtype)
|
475 |
+
if self.config.gate_rank_type == 1:
|
476 |
+
gate_states = torch.sigmoid(self.gate(xg))
|
477 |
+
elif self.config.gate_rank_type == 2:
|
478 |
+
gate_states = torch.sigmoid(xg @ self.g1) @ self.g2
|
479 |
+
|
480 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
481 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
482 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
483 |
+
decay_states = decay_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
484 |
+
|
485 |
+
if position_embeddings is not None:
|
486 |
+
cos, sin = position_embeddings
|
487 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, unsqueeze_dim=1)
|
488 |
+
|
489 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
490 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
491 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
492 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
493 |
+
|
494 |
+
decay_states_log = -decay_states.float().exp()
|
495 |
+
decay_states_log = decay_states_log.clamp(-5) # FIXME - is this necessary?
|
496 |
+
if self.config.balance_state:
|
497 |
+
key_states = (key_states * (1 - decay_states_log.exp())).to(key_states.dtype)
|
498 |
+
|
499 |
+
# dealing with left-padding
|
500 |
+
if attention_mask is not None:
|
501 |
+
value_states = value_states * attention_mask[:, None, -value_states.shape[-2]:, None]
|
502 |
+
|
503 |
+
query_states = query_states.to(value_states.dtype)
|
504 |
+
key_states = key_states.to(value_states.dtype)
|
505 |
+
|
506 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
507 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
508 |
+
# cast them back in float16 just to be sure everything works as expected.
|
509 |
+
input_dtype = query_states.dtype
|
510 |
+
if input_dtype == torch.float32:
|
511 |
+
if torch.is_autocast_enabled():
|
512 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
513 |
+
# Handle the case where the model is quantized
|
514 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
515 |
+
target_dtype = self.config._pre_quantization_dtype
|
516 |
+
else:
|
517 |
+
target_dtype = self.q_proj.weight.dtype
|
518 |
+
|
519 |
+
logger.warning_once(
|
520 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
521 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
522 |
+
f" {target_dtype}."
|
523 |
+
)
|
524 |
+
|
525 |
+
query_states = query_states.to(target_dtype)
|
526 |
+
key_states = key_states.to(target_dtype)
|
527 |
+
value_states = value_states.to(target_dtype)
|
528 |
+
|
529 |
+
attn_weights = torch.empty(0, device=x.device)
|
530 |
+
|
531 |
+
scale = query_states.shape[-1] ** -0.5
|
532 |
+
output_final_state = not self.training and use_cache and past_key_values is not None
|
533 |
+
#attn_output, output_kv_state = ChunkGLAFunction.apply(query_states, key_states, value_states, decay_states_log.float(), scale, input_kv_state, output_final_state)
|
534 |
+
#attn_output, output_kv_state = chunk_gla(query_states, key_states, value_states, decay_states_log, scale, input_kv_state, output_final_state)
|
535 |
+
attn_output, output_kv_state = fused_recurrent_gla(query_states, key_states, value_states, decay_states_log, None, scale, input_kv_state, output_final_state)
|
536 |
+
|
537 |
+
if output_final_state:
|
538 |
+
past_key_values.update(output_kv_state, output_shift_state, q_len, self.layer_idx)
|
539 |
+
|
540 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
541 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
542 |
+
if self.config.groupnorm_att:
|
543 |
+
attn_output = self.ln_x(attn_output.view(bsz * q_len, -1)).view(bsz, q_len, -1)
|
544 |
+
if self.config.gate_rank_type != 0:
|
545 |
+
attn_output = attn_output * gate_states
|
546 |
+
attn_output = self.o_proj(attn_output)
|
547 |
+
|
548 |
+
return attn_output, attn_weights
|
549 |
+
|
550 |
+
class RWKV6Qwen2DecoderLayer(Qwen2DecoderLayer):
|
551 |
+
def __init__(self, config: RWKV6Qwen2Config, layer_idx: int):
|
552 |
+
nn.Module.__init__(self)
|
553 |
+
self.hidden_size = config.hidden_size
|
554 |
+
|
555 |
+
self.self_attn = RWKV6Attention(config, layer_idx) #QWEN2_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
556 |
+
|
557 |
+
self.mlp = Qwen2MLP(config)
|
558 |
+
self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
559 |
+
self.post_attention_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
560 |
+
|
561 |
+
def forward(
|
562 |
+
self,
|
563 |
+
hidden_states: torch.Tensor,
|
564 |
+
attention_mask: Optional[torch.Tensor] = None,
|
565 |
+
position_ids: Optional[torch.LongTensor] = None,
|
566 |
+
past_key_values: Optional[Cache] = None,
|
567 |
+
output_attentions: Optional[bool] = False,
|
568 |
+
use_cache: Optional[bool] = False,
|
569 |
+
cache_position: Optional[torch.LongTensor] = None,
|
570 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
571 |
+
**kwargs,
|
572 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
573 |
+
residual = hidden_states
|
574 |
+
|
575 |
+
hidden_states = self.input_layernorm(hidden_states)
|
576 |
+
|
577 |
+
# Self Attention
|
578 |
+
hidden_states, self_attn_weights = self.self_attn(
|
579 |
+
hidden_states=hidden_states,
|
580 |
+
attention_mask=attention_mask,
|
581 |
+
position_ids=position_ids,
|
582 |
+
past_key_values=past_key_values,
|
583 |
+
output_attentions=output_attentions,
|
584 |
+
use_cache=use_cache,
|
585 |
+
cache_position=cache_position,
|
586 |
+
position_embeddings=position_embeddings,
|
587 |
+
**kwargs,
|
588 |
+
)
|
589 |
+
hidden_states = residual + hidden_states
|
590 |
+
|
591 |
+
# Fully Connected
|
592 |
+
residual = hidden_states
|
593 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
594 |
+
hidden_states = self.mlp(hidden_states)
|
595 |
+
hidden_states = residual + hidden_states
|
596 |
+
|
597 |
+
outputs = (hidden_states,)
|
598 |
+
if output_attentions:
|
599 |
+
outputs += (self_attn_weights,)
|
600 |
+
|
601 |
+
return outputs
|
602 |
+
|
603 |
+
RWKV6QWEN2_START_DOCSTRING = r"""
|
604 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
605 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
606 |
+
etc.)
|
607 |
+
|
608 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
609 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
610 |
+
and behavior.
|
611 |
+
|
612 |
+
Parameters:
|
613 |
+
config ([`RWKV6Qwen2Config`]):
|
614 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
615 |
+
load the weights associated with the model, only the configuration. Check out the
|
616 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
617 |
+
"""
|
618 |
+
|
619 |
+
|
620 |
+
@add_start_docstrings(
|
621 |
+
"The bare Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
622 |
+
RWKV6QWEN2_START_DOCSTRING,
|
623 |
+
)
|
624 |
+
class RWKV6Qwen2PreTrainedModel(PreTrainedModel):
|
625 |
+
config_class = RWKV6Qwen2Config
|
626 |
+
base_model_prefix = "model"
|
627 |
+
supports_gradient_checkpointing = True
|
628 |
+
_no_split_modules = ["RWKV6Qwen2DecoderLayer"]
|
629 |
+
_skip_keys_device_placement = "past_key_values"
|
630 |
+
_supports_flash_attn_2 = True
|
631 |
+
_supports_sdpa = True
|
632 |
+
_supports_cache_class = True
|
633 |
+
_supports_quantized_cache = True
|
634 |
+
_supports_static_cache = True
|
635 |
+
|
636 |
+
def _init_weights(self, module):
|
637 |
+
std = self.config.initializer_range
|
638 |
+
if isinstance(module, nn.Linear):
|
639 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
640 |
+
if module.bias is not None:
|
641 |
+
module.bias.data.zero_()
|
642 |
+
elif isinstance(module, nn.Embedding):
|
643 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
644 |
+
if module.padding_idx is not None:
|
645 |
+
module.weight.data[module.padding_idx].zero_()
|
646 |
+
|
647 |
+
|
648 |
+
RWKV6QWEN2_INPUTS_DOCSTRING = r"""
|
649 |
+
Args:
|
650 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
651 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
652 |
+
it.
|
653 |
+
|
654 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
655 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
656 |
+
|
657 |
+
[What are input IDs?](../glossary#input-ids)
|
658 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
659 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
660 |
+
|
661 |
+
- 1 for tokens that are **not masked**,
|
662 |
+
- 0 for tokens that are **masked**.
|
663 |
+
|
664 |
+
[What are attention masks?](../glossary#attention-mask)
|
665 |
+
|
666 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
667 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
668 |
+
|
669 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
670 |
+
`past_key_values`).
|
671 |
+
|
672 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
673 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
674 |
+
information on the default strategy.
|
675 |
+
|
676 |
+
- 1 indicates the head is **not masked**,
|
677 |
+
- 0 indicates the head is **masked**.
|
678 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
679 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
680 |
+
config.n_positions - 1]`.
|
681 |
+
|
682 |
+
[What are position IDs?](../glossary#position-ids)
|
683 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
684 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
685 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
686 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
687 |
+
|
688 |
+
Two formats are allowed:
|
689 |
+
- a [`~cache_utils.Cache`] instance, see our
|
690 |
+
[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
|
691 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
692 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
693 |
+
cache format.
|
694 |
+
|
695 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
696 |
+
legacy cache format will be returned.
|
697 |
+
|
698 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
699 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
700 |
+
of shape `(batch_size, sequence_length)`.
|
701 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
702 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
703 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
704 |
+
model's internal embedding lookup matrix.
|
705 |
+
use_cache (`bool`, *optional*):
|
706 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
707 |
+
`past_key_values`).
|
708 |
+
output_attentions (`bool`, *optional*):
|
709 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
710 |
+
tensors for more detail.
|
711 |
+
output_hidden_states (`bool`, *optional*):
|
712 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
713 |
+
more detail.
|
714 |
+
return_dict (`bool`, *optional*):
|
715 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
716 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
717 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
718 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
719 |
+
the complete sequence length.
|
720 |
+
"""
|
721 |
+
|
722 |
+
@add_start_docstrings(
|
723 |
+
"The bare RWKV6Qwen2 Model outputting raw hidden-states without any specific head on top.",
|
724 |
+
RWKV6QWEN2_START_DOCSTRING,
|
725 |
+
)
|
726 |
+
class RWKV6Qwen2Model(RWKV6Qwen2PreTrainedModel):
|
727 |
+
"""
|
728 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen2DecoderLayer`]
|
729 |
+
|
730 |
+
Args:
|
731 |
+
config: RWKV6Qwen2Config
|
732 |
+
"""
|
733 |
+
|
734 |
+
def __init__(self, config: RWKV6Qwen2Config):
|
735 |
+
super().__init__(config)
|
736 |
+
self.padding_idx = config.pad_token_id
|
737 |
+
self.vocab_size = config.vocab_size
|
738 |
+
|
739 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
740 |
+
self.layers = nn.ModuleList(
|
741 |
+
[RWKV6Qwen2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
742 |
+
)
|
743 |
+
self._attn_implementation = config._attn_implementation
|
744 |
+
self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
745 |
+
self.rotary_emb = Qwen2RotaryEmbedding(config=config)
|
746 |
+
|
747 |
+
self.gradient_checkpointing = False
|
748 |
+
# Initialize weights and apply final processing
|
749 |
+
self.post_init()
|
750 |
+
|
751 |
+
def get_input_embeddings(self):
|
752 |
+
return self.embed_tokens
|
753 |
+
|
754 |
+
def set_input_embeddings(self, value):
|
755 |
+
self.embed_tokens = value
|
756 |
+
|
757 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
758 |
+
def forward(
|
759 |
+
self,
|
760 |
+
input_ids: torch.LongTensor = None,
|
761 |
+
attention_mask: Optional[torch.Tensor] = None,
|
762 |
+
position_ids: Optional[torch.LongTensor] = None,
|
763 |
+
past_key_values: Optional[Cache] = None,
|
764 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
765 |
+
use_cache: Optional[bool] = None,
|
766 |
+
output_attentions: Optional[bool] = None,
|
767 |
+
output_hidden_states: Optional[bool] = None,
|
768 |
+
return_dict: Optional[bool] = None,
|
769 |
+
cache_position: Optional[torch.LongTensor] = None,
|
770 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
771 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
772 |
+
output_hidden_states = (
|
773 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
774 |
+
)
|
775 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
776 |
+
|
777 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
778 |
+
|
779 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
780 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
781 |
+
|
782 |
+
if self.gradient_checkpointing and self.training:
|
783 |
+
if use_cache:
|
784 |
+
logger.warning_once(
|
785 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
786 |
+
)
|
787 |
+
use_cache = False
|
788 |
+
|
789 |
+
# kept for BC (non `Cache` `past_key_values` inputs)
|
790 |
+
#return_legacy_cache = False
|
791 |
+
if use_cache and not isinstance(past_key_values, RWKV6State):
|
792 |
+
#return_legacy_cache = True
|
793 |
+
past_key_values = RWKV6State()
|
794 |
+
# if past_key_values is None:
|
795 |
+
# past_key_values = DynamicCache()
|
796 |
+
# else:
|
797 |
+
# past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
798 |
+
# logger.warning_once(
|
799 |
+
# "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
|
800 |
+
# "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
|
801 |
+
# "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
|
802 |
+
# )
|
803 |
+
|
804 |
+
if inputs_embeds is None:
|
805 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
806 |
+
|
807 |
+
if cache_position is None:
|
808 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
809 |
+
cache_position = torch.arange(
|
810 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
811 |
+
)
|
812 |
+
|
813 |
+
if position_ids is None:
|
814 |
+
position_ids = cache_position.unsqueeze(0)
|
815 |
+
|
816 |
+
# causal_mask = self._update_causal_mask(
|
817 |
+
# attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
818 |
+
# )
|
819 |
+
|
820 |
+
causal_mask = None
|
821 |
+
|
822 |
+
hidden_states = inputs_embeds
|
823 |
+
|
824 |
+
# create position embeddings to be shared across the decoder layers
|
825 |
+
position_embeddings = None
|
826 |
+
if self.config.use_rope:
|
827 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
828 |
+
|
829 |
+
# decoder layers
|
830 |
+
all_hidden_states = () if output_hidden_states else None
|
831 |
+
all_self_attns = () if output_attentions else None
|
832 |
+
next_decoder_cache = None
|
833 |
+
|
834 |
+
for decoder_layer in self.layers:
|
835 |
+
if output_hidden_states:
|
836 |
+
all_hidden_states += (hidden_states,)
|
837 |
+
|
838 |
+
if self.gradient_checkpointing and self.training:
|
839 |
+
layer_outputs = self._gradient_checkpointing_func(
|
840 |
+
decoder_layer.__call__,
|
841 |
+
hidden_states,
|
842 |
+
causal_mask,
|
843 |
+
position_ids,
|
844 |
+
past_key_values,
|
845 |
+
output_attentions,
|
846 |
+
use_cache,
|
847 |
+
cache_position,
|
848 |
+
position_embeddings,
|
849 |
+
)
|
850 |
+
else:
|
851 |
+
layer_outputs = decoder_layer(
|
852 |
+
hidden_states,
|
853 |
+
attention_mask=attention_mask,
|
854 |
+
position_ids=position_ids,
|
855 |
+
past_key_values=past_key_values,
|
856 |
+
output_attentions=output_attentions,
|
857 |
+
use_cache=use_cache,
|
858 |
+
cache_position=cache_position,
|
859 |
+
position_embeddings=position_embeddings,
|
860 |
+
)
|
861 |
+
|
862 |
+
hidden_states = layer_outputs[0]
|
863 |
+
|
864 |
+
if output_attentions:
|
865 |
+
all_self_attns += (layer_outputs[1],)
|
866 |
+
|
867 |
+
hidden_states = self.norm(hidden_states)
|
868 |
+
|
869 |
+
# add hidden states from the last decoder layer
|
870 |
+
if output_hidden_states:
|
871 |
+
all_hidden_states += (hidden_states,)
|
872 |
+
|
873 |
+
#if return_legacy_cache:
|
874 |
+
# next_cache = next_cache.to_legacy_cache()
|
875 |
+
|
876 |
+
if not return_dict:
|
877 |
+
return tuple(v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None)
|
878 |
+
return BaseModelOutputWithPast(
|
879 |
+
last_hidden_state=hidden_states,
|
880 |
+
past_key_values=past_key_values,
|
881 |
+
hidden_states=all_hidden_states,
|
882 |
+
attentions=all_self_attns,
|
883 |
+
)
|
884 |
+
|
885 |
+
class RWKV6Qwen2ForCausalLM(RWKV6Qwen2PreTrainedModel, GenerationMixin):
|
886 |
+
_tied_weights_keys = ["lm_head.weight"]
|
887 |
+
|
888 |
+
def __init__(self, config):
|
889 |
+
super().__init__(config)
|
890 |
+
self.model = RWKV6Qwen2Model(config)
|
891 |
+
self.vocab_size = config.vocab_size
|
892 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
893 |
+
|
894 |
+
# Initialize weights and apply final processing
|
895 |
+
self.post_init()
|
896 |
+
|
897 |
+
def get_input_embeddings(self):
|
898 |
+
return self.model.embed_tokens
|
899 |
+
|
900 |
+
def set_input_embeddings(self, value):
|
901 |
+
self.model.embed_tokens = value
|
902 |
+
|
903 |
+
def get_output_embeddings(self):
|
904 |
+
return self.lm_head
|
905 |
+
|
906 |
+
def set_output_embeddings(self, new_embeddings):
|
907 |
+
self.lm_head = new_embeddings
|
908 |
+
|
909 |
+
def set_decoder(self, decoder):
|
910 |
+
self.model = decoder
|
911 |
+
|
912 |
+
def get_decoder(self):
|
913 |
+
return self.model
|
914 |
+
|
915 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
916 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
917 |
+
def forward(
|
918 |
+
self,
|
919 |
+
input_ids: torch.LongTensor = None,
|
920 |
+
attention_mask: Optional[torch.Tensor] = None,
|
921 |
+
position_ids: Optional[torch.LongTensor] = None,
|
922 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
923 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
924 |
+
labels: Optional[torch.LongTensor] = None,
|
925 |
+
use_cache: Optional[bool] = None,
|
926 |
+
output_attentions: Optional[bool] = None,
|
927 |
+
output_hidden_states: Optional[bool] = None,
|
928 |
+
return_dict: Optional[bool] = None,
|
929 |
+
cache_position: Optional[torch.LongTensor] = None,
|
930 |
+
num_logits_to_keep: int = 0,
|
931 |
+
**loss_kwargs,
|
932 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
933 |
+
r"""
|
934 |
+
Args:
|
935 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
936 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
937 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
938 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
939 |
+
|
940 |
+
num_logits_to_keep (`int`, *optional*):
|
941 |
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
942 |
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
943 |
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
944 |
+
|
945 |
+
Returns:
|
946 |
+
|
947 |
+
Example:
|
948 |
+
|
949 |
+
```python
|
950 |
+
>>> from transformers import AutoTokenizer, RWKV6Qwen2ForCausalLM
|
951 |
+
|
952 |
+
>>> model = RWKV6Qwen2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
953 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
954 |
+
|
955 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
956 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
957 |
+
|
958 |
+
>>> # Generate
|
959 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
960 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
961 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
962 |
+
```"""
|
963 |
+
|
964 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
965 |
+
output_hidden_states = (
|
966 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
967 |
+
)
|
968 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
969 |
+
|
970 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
971 |
+
outputs = self.model(
|
972 |
+
input_ids=input_ids,
|
973 |
+
attention_mask=attention_mask,
|
974 |
+
position_ids=position_ids,
|
975 |
+
past_key_values=past_key_values,
|
976 |
+
inputs_embeds=inputs_embeds,
|
977 |
+
use_cache=use_cache,
|
978 |
+
output_attentions=output_attentions,
|
979 |
+
output_hidden_states=output_hidden_states,
|
980 |
+
return_dict=return_dict,
|
981 |
+
cache_position=cache_position,
|
982 |
+
)
|
983 |
+
|
984 |
+
hidden_states = outputs[0]
|
985 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
986 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
987 |
+
|
988 |
+
loss = None
|
989 |
+
if labels is not None:
|
990 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
|
991 |
+
|
992 |
+
if not return_dict:
|
993 |
+
output = (logits,) + outputs[1:]
|
994 |
+
return (loss,) + output if loss is not None else output
|
995 |
+
|
996 |
+
return CausalLMOutputWithPast(
|
997 |
+
loss=loss,
|
998 |
+
logits=logits,
|
999 |
+
past_key_values=outputs.past_key_values,
|
1000 |
+
hidden_states=outputs.hidden_states,
|
1001 |
+
attentions=outputs.attentions,
|
1002 |
+
)
|
1003 |
+
|
1004 |
+
def prepare_inputs_for_generation(
|
1005 |
+
self,
|
1006 |
+
input_ids: torch.LongTensor,
|
1007 |
+
past_key_values: Optional[Cache] = None,
|
1008 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
1009 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1010 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1011 |
+
**kwargs,
|
1012 |
+
):
|
1013 |
+
# only last token for `inputs_ids` if the `past_key_values` is not empty.
|
1014 |
+
if past_key_values is not None and len(past_key_values) > 0:
|
1015 |
+
input_ids = input_ids[:, -1:]
|
1016 |
+
|
1017 |
+
model_inputs = {
|
1018 |
+
'past_key_values': past_key_values,
|
1019 |
+
'attention_mask': attention_mask,
|
1020 |
+
'cache_position': cache_position,
|
1021 |
+
}
|
1022 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1023 |
+
if inputs_embeds is not None and past_key_values is None:
|
1024 |
+
model_inputs['inputs_embeds'] = inputs_embeds
|
1025 |
+
else:
|
1026 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1027 |
+
# recompiles graphs as the stride of the inputs is a guard.
|
1028 |
+
# Ref: https://github.com/huggingface/transformers/pull/29114
|
1029 |
+
# TODO: use `next_tokens` directly instead.
|
1030 |
+
model_inputs['input_ids'] = input_ids.contiguous()
|
1031 |
+
|
1032 |
+
model_inputs.update(**kwargs)
|
1033 |
+
|
1034 |
+
# 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)
|
1035 |
+
model_inputs.pop("labels", None)
|
1036 |
+
|
1037 |
+
return model_inputs
|
1038 |
+
|
1039 |
+
@add_start_docstrings(
|
1040 |
+
"""
|
1041 |
+
The RWKV6Qwen2 Model transformer with a sequence classification head on top (linear layer).
|
1042 |
+
|
1043 |
+
[`RWKV6Qwen2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1044 |
+
(e.g. GPT-2) do.
|
1045 |
+
|
1046 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1047 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1048 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1049 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1050 |
+
each row of the batch).
|
1051 |
+
""",
|
1052 |
+
RWKV6QWEN2_START_DOCSTRING,
|
1053 |
+
)
|
1054 |
+
class RWKV6Qwen2ForSequenceClassification(RWKV6Qwen2PreTrainedModel):
|
1055 |
+
def __init__(self, config):
|
1056 |
+
super().__init__(config)
|
1057 |
+
self.num_labels = config.num_labels
|
1058 |
+
self.model = RWKV6Qwen2Model(config)
|
1059 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1060 |
+
|
1061 |
+
# Initialize weights and apply final processing
|
1062 |
+
self.post_init()
|
1063 |
+
|
1064 |
+
def get_input_embeddings(self):
|
1065 |
+
return self.model.embed_tokens
|
1066 |
+
|
1067 |
+
def set_input_embeddings(self, value):
|
1068 |
+
self.model.embed_tokens = value
|
1069 |
+
|
1070 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
1071 |
+
def forward(
|
1072 |
+
self,
|
1073 |
+
input_ids: torch.LongTensor = None,
|
1074 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1075 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1076 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1077 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1078 |
+
labels: Optional[torch.LongTensor] = None,
|
1079 |
+
use_cache: Optional[bool] = None,
|
1080 |
+
output_attentions: Optional[bool] = None,
|
1081 |
+
output_hidden_states: Optional[bool] = None,
|
1082 |
+
return_dict: Optional[bool] = None,
|
1083 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1084 |
+
r"""
|
1085 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1086 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1087 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1088 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1089 |
+
"""
|
1090 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1091 |
+
|
1092 |
+
transformer_outputs = self.model(
|
1093 |
+
input_ids,
|
1094 |
+
attention_mask=attention_mask,
|
1095 |
+
position_ids=position_ids,
|
1096 |
+
past_key_values=past_key_values,
|
1097 |
+
inputs_embeds=inputs_embeds,
|
1098 |
+
use_cache=use_cache,
|
1099 |
+
output_attentions=output_attentions,
|
1100 |
+
output_hidden_states=output_hidden_states,
|
1101 |
+
return_dict=return_dict,
|
1102 |
+
)
|
1103 |
+
hidden_states = transformer_outputs[0]
|
1104 |
+
logits = self.score(hidden_states)
|
1105 |
+
|
1106 |
+
if input_ids is not None:
|
1107 |
+
batch_size = input_ids.shape[0]
|
1108 |
+
else:
|
1109 |
+
batch_size = inputs_embeds.shape[0]
|
1110 |
+
|
1111 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1112 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1113 |
+
if self.config.pad_token_id is None:
|
1114 |
+
sequence_lengths = -1
|
1115 |
+
else:
|
1116 |
+
if input_ids is not None:
|
1117 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1118 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1119 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1120 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1121 |
+
else:
|
1122 |
+
sequence_lengths = -1
|
1123 |
+
|
1124 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1125 |
+
|
1126 |
+
loss = None
|
1127 |
+
if labels is not None:
|
1128 |
+
labels = labels.to(logits.device)
|
1129 |
+
if self.config.problem_type is None:
|
1130 |
+
if self.num_labels == 1:
|
1131 |
+
self.config.problem_type = "regression"
|
1132 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1133 |
+
self.config.problem_type = "single_label_classification"
|
1134 |
+
else:
|
1135 |
+
self.config.problem_type = "multi_label_classification"
|
1136 |
+
|
1137 |
+
if self.config.problem_type == "regression":
|
1138 |
+
loss_fct = MSELoss()
|
1139 |
+
if self.num_labels == 1:
|
1140 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1141 |
+
else:
|
1142 |
+
loss = loss_fct(pooled_logits, labels)
|
1143 |
+
elif self.config.problem_type == "single_label_classification":
|
1144 |
+
loss_fct = CrossEntropyLoss()
|
1145 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1146 |
+
elif self.config.problem_type == "multi_label_classification":
|
1147 |
+
loss_fct = BCEWithLogitsLoss()
|
1148 |
+
loss = loss_fct(pooled_logits, labels)
|
1149 |
+
if not return_dict:
|
1150 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1151 |
+
return ((loss,) + output) if loss is not None else output
|
1152 |
+
|
1153 |
+
return SequenceClassifierOutputWithPast(
|
1154 |
+
loss=loss,
|
1155 |
+
logits=pooled_logits,
|
1156 |
+
past_key_values=transformer_outputs.past_key_values,
|
1157 |
+
hidden_states=transformer_outputs.hidden_states,
|
1158 |
+
attentions=transformer_outputs.attentions,
|
1159 |
+
)
|
1160 |
+
|
1161 |
+
|
1162 |
+
@add_start_docstrings(
|
1163 |
+
"""
|
1164 |
+
The RWKV6Qwen2 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
|
1165 |
+
output) e.g. for Named-Entity-Recognition (NER) tasks.
|
1166 |
+
""",
|
1167 |
+
RWKV6QWEN2_START_DOCSTRING,
|
1168 |
+
)
|
1169 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with Llama->RWKV6Qwen2, LLAMA->RWKV6QWEN2
|
1170 |
+
class RWKV6Qwen2ForTokenClassification(RWKV6Qwen2PreTrainedModel):
|
1171 |
+
def __init__(self, config):
|
1172 |
+
super().__init__(config)
|
1173 |
+
self.num_labels = config.num_labels
|
1174 |
+
self.model = RWKV6Qwen2Model(config)
|
1175 |
+
if getattr(config, "classifier_dropout", None) is not None:
|
1176 |
+
classifier_dropout = config.classifier_dropout
|
1177 |
+
elif getattr(config, "hidden_dropout", None) is not None:
|
1178 |
+
classifier_dropout = config.hidden_dropout
|
1179 |
+
else:
|
1180 |
+
classifier_dropout = 0.1
|
1181 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1182 |
+
self.score = nn.Linear(config.hidden_size, config.num_labels)
|
1183 |
+
|
1184 |
+
# Initialize weights and apply final processing
|
1185 |
+
self.post_init()
|
1186 |
+
|
1187 |
+
def get_input_embeddings(self):
|
1188 |
+
return self.model.embed_tokens
|
1189 |
+
|
1190 |
+
def set_input_embeddings(self, value):
|
1191 |
+
self.model.embed_tokens = value
|
1192 |
+
|
1193 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
1194 |
+
@add_code_sample_docstrings(
|
1195 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1196 |
+
output_type=TokenClassifierOutput,
|
1197 |
+
config_class=_CONFIG_FOR_DOC,
|
1198 |
+
)
|
1199 |
+
def forward(
|
1200 |
+
self,
|
1201 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1202 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1203 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1204 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1205 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1206 |
+
labels: Optional[torch.LongTensor] = None,
|
1207 |
+
use_cache: Optional[bool] = None,
|
1208 |
+
output_attentions: Optional[bool] = None,
|
1209 |
+
output_hidden_states: Optional[bool] = None,
|
1210 |
+
return_dict: Optional[bool] = None,
|
1211 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1212 |
+
r"""
|
1213 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1214 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1215 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1216 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1217 |
+
"""
|
1218 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1219 |
+
|
1220 |
+
outputs = self.model(
|
1221 |
+
input_ids,
|
1222 |
+
attention_mask=attention_mask,
|
1223 |
+
position_ids=position_ids,
|
1224 |
+
past_key_values=past_key_values,
|
1225 |
+
inputs_embeds=inputs_embeds,
|
1226 |
+
use_cache=use_cache,
|
1227 |
+
output_attentions=output_attentions,
|
1228 |
+
output_hidden_states=output_hidden_states,
|
1229 |
+
return_dict=return_dict,
|
1230 |
+
)
|
1231 |
+
sequence_output = outputs[0]
|
1232 |
+
sequence_output = self.dropout(sequence_output)
|
1233 |
+
logits = self.score(sequence_output)
|
1234 |
+
|
1235 |
+
loss = None
|
1236 |
+
if labels is not None:
|
1237 |
+
loss = self.loss_function(logits, labels, self.config)
|
1238 |
+
|
1239 |
+
if not return_dict:
|
1240 |
+
output = (logits,) + outputs[2:]
|
1241 |
+
return ((loss,) + output) if loss is not None else output
|
1242 |
+
|
1243 |
+
return TokenClassifierOutput(
|
1244 |
+
loss=loss,
|
1245 |
+
logits=logits,
|
1246 |
+
hidden_states=outputs.hidden_states,
|
1247 |
+
attentions=outputs.attentions,
|
1248 |
+
)
|
1249 |
+
|
1250 |
+
|
1251 |
+
@add_start_docstrings(
|
1252 |
+
"""
|
1253 |
+
The RWKV6Qwen2 Model transformer with a span classification head on top for extractive question-answering tasks like
|
1254 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1255 |
+
""",
|
1256 |
+
RWKV6QWEN2_START_DOCSTRING,
|
1257 |
+
)
|
1258 |
+
# Copied from transformers.models.mistral.modeling_mistral.MistralForQuestionAnswering with Mistral->RWKV6Qwen2, MISTRAL->RWKV6QWEN2
|
1259 |
+
class RWKV6Qwen2ForQuestionAnswering(RWKV6Qwen2PreTrainedModel):
|
1260 |
+
base_model_prefix = "model"
|
1261 |
+
|
1262 |
+
# Copied from models.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->RWKV6Qwen2
|
1263 |
+
def __init__(self, config):
|
1264 |
+
super().__init__(config)
|
1265 |
+
self.model = RWKV6Qwen2Model(config)
|
1266 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1267 |
+
|
1268 |
+
# Initialize weights and apply final processing
|
1269 |
+
self.post_init()
|
1270 |
+
|
1271 |
+
def get_input_embeddings(self):
|
1272 |
+
return self.model.embed_tokens
|
1273 |
+
|
1274 |
+
def set_input_embeddings(self, value):
|
1275 |
+
self.model.embed_tokens = value
|
1276 |
+
|
1277 |
+
@add_start_docstrings_to_model_forward(RWKV6QWEN2_INPUTS_DOCSTRING)
|
1278 |
+
def forward(
|
1279 |
+
self,
|
1280 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1281 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1282 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1283 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1284 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1285 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1286 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1287 |
+
output_attentions: Optional[bool] = None,
|
1288 |
+
output_hidden_states: Optional[bool] = None,
|
1289 |
+
return_dict: Optional[bool] = None,
|
1290 |
+
**kwargs,
|
1291 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1292 |
+
r"""
|
1293 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1294 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1295 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1296 |
+
are not taken into account for computing the loss.
|
1297 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1298 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1299 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1300 |
+
are not taken into account for computing the loss.
|
1301 |
+
"""
|
1302 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1303 |
+
|
1304 |
+
outputs = self.model(
|
1305 |
+
input_ids,
|
1306 |
+
attention_mask=attention_mask,
|
1307 |
+
position_ids=position_ids,
|
1308 |
+
past_key_values=past_key_values,
|
1309 |
+
inputs_embeds=inputs_embeds,
|
1310 |
+
output_attentions=output_attentions,
|
1311 |
+
output_hidden_states=output_hidden_states,
|
1312 |
+
return_dict=return_dict,
|
1313 |
+
)
|
1314 |
+
|
1315 |
+
sequence_output = outputs[0]
|
1316 |
+
|
1317 |
+
logits = self.qa_outputs(sequence_output)
|
1318 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1319 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1320 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1321 |
+
|
1322 |
+
loss = None
|
1323 |
+
if start_positions is not None and end_positions is not None:
|
1324 |
+
loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
|
1325 |
+
|
1326 |
+
if not return_dict:
|
1327 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1328 |
+
return ((loss,) + output) if loss is not None else output
|
1329 |
+
|
1330 |
+
return QuestionAnsweringModelOutput(
|
1331 |
+
loss=loss,
|
1332 |
+
start_logits=start_logits,
|
1333 |
+
end_logits=end_logits,
|
1334 |
+
hidden_states=outputs.hidden_states,
|
1335 |
+
attentions=outputs.attentions,
|
1336 |
+
)
|