modeling_rwkv.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. # coding=utf-8
  2. # Copyright 2023 Bo Peng 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. """PyTorch RWKV model."""
  17. import math
  18. from dataclasses import dataclass
  19. from pathlib import Path
  20. from typing import Optional, Union
  21. import torch
  22. from torch import nn
  23. from ...generation import GenerationMixin
  24. from ...modeling_layers import GradientCheckpointingLayer
  25. from ...modeling_utils import PreTrainedModel
  26. from ...utils import (
  27. ModelOutput,
  28. auto_docstring,
  29. is_bitsandbytes_available,
  30. is_ninja_available,
  31. is_torch_cuda_available,
  32. logging,
  33. )
  34. from .configuration_rwkv import RwkvConfig
  35. logger = logging.get_logger(__name__)
  36. rwkv_cuda_kernel = None
  37. def load_wkv_cuda_kernel(context_length):
  38. from torch.utils.cpp_extension import load as load_kernel
  39. global rwkv_cuda_kernel
  40. kernel_folder = Path(__file__).resolve().parent.parent.parent / "kernels" / "rwkv"
  41. cuda_kernel_files = [kernel_folder / f for f in ["wkv_op.cpp", "wkv_cuda.cu", "wkv_cuda_bf16.cu"]]
  42. # Only load the kernel if it's not been loaded yet or if we changed the context length
  43. if rwkv_cuda_kernel is not None and rwkv_cuda_kernel.max_seq_length == context_length:
  44. return
  45. logger.info(f"Loading CUDA kernel for RWKV at context length of {context_length}.")
  46. flags = [
  47. "-res-usage",
  48. "--maxrregcount 60",
  49. "--use_fast_math",
  50. "-O3",
  51. "-Xptxas -O3",
  52. "--extra-device-vectorization",
  53. f"-DTmax={context_length}",
  54. ]
  55. rwkv_cuda_kernel = load_kernel(
  56. name=f"wkv_{context_length}",
  57. sources=cuda_kernel_files,
  58. verbose=(logging.get_verbosity() == logging.DEBUG),
  59. extra_cuda_cflags=flags,
  60. )
  61. rwkv_cuda_kernel.max_seq_length = context_length
  62. class RwkvLinearAttention(torch.autograd.Function):
  63. @staticmethod
  64. def forward(ctx, time_decay, time_first, key, value, state=None, return_state=False):
  65. batch_size, seq_len, hidden_size = key.size()
  66. if seq_len > rwkv_cuda_kernel.max_seq_length:
  67. raise ValueError(
  68. f"Cannot process a batch with {seq_len} tokens at the same time, use a maximum of "
  69. f"{rwkv_cuda_kernel.max_seq_length} with this model."
  70. )
  71. if batch_size * hidden_size % min(hidden_size, 32) != 0:
  72. raise ValueError(
  73. f"The product of batch size ({batch_size}) and hidden size ({hidden_size}) needs to be a round "
  74. f"multiple of {min(hidden_size, 32)}."
  75. )
  76. ctx.input_dtype = key.dtype
  77. if (
  78. time_decay.device.type != "cuda"
  79. or time_first.device.type != "cuda"
  80. or key.device.type != "cuda"
  81. or value.device.type != "cuda"
  82. ):
  83. raise ValueError("Calling the CUDA kernel for wkv attention requires all tensors to be on CUDA devices.")
  84. time_decay = -torch.exp(time_decay.float().contiguous())
  85. if key.dtype == torch.float16:
  86. time_first = time_first.float()
  87. key = key.float()
  88. value = value.float()
  89. time_first = time_first.contiguous()
  90. key = key.contiguous()
  91. value = value.contiguous()
  92. # The CUDA kernel will fill this tensor.
  93. output = torch.empty_like(key, memory_format=torch.contiguous_format)
  94. if return_state or state is not None:
  95. if state is None:
  96. state = torch.zeros(
  97. batch_size,
  98. hidden_size,
  99. 3,
  100. dtype=torch.float32,
  101. device=key.device,
  102. memory_format=torch.contiguous_format,
  103. )
  104. state[:, :, 2] -= 1e38
  105. else:
  106. state = torch.cat([s.unsqueeze(2) for s in state], dim=2).contiguous()
  107. if key.dtype == torch.bfloat16:
  108. forward_func = rwkv_cuda_kernel.forward_with_state_bf16
  109. else:
  110. forward_func = rwkv_cuda_kernel.forward_with_state
  111. forward_func(time_decay, time_first, key, value, output, state)
  112. else:
  113. forward_func = rwkv_cuda_kernel.forward_bf16 if key.dtype == torch.bfloat16 else rwkv_cuda_kernel.forward
  114. forward_func(time_decay, time_first, key, value, output)
  115. ctx.save_for_backward(time_decay, time_first, key, value, output)
  116. if state is not None:
  117. state = [s.squeeze(2) for s in torch.chunk(state, 3, dim=2)]
  118. return output.to(ctx.input_dtype), state
  119. @staticmethod
  120. # g stands for grad
  121. def backward(ctx, g_output, g_state=None):
  122. input_dtype = ctx.input_dtype
  123. time_decay, time_first, key, value, output = ctx.saved_tensors
  124. # The CUDA kernel will fill those tensors.
  125. g_time_decay = torch.empty_like(
  126. time_decay,
  127. memory_format=torch.contiguous_format,
  128. dtype=torch.bfloat16 if input_dtype == torch.bfloat16 else torch.float32,
  129. )
  130. g_time_first = torch.empty_like(time_first, memory_format=torch.contiguous_format)
  131. g_key = torch.empty_like(key, memory_format=torch.contiguous_format)
  132. g_value = torch.empty_like(value, memory_format=torch.contiguous_format)
  133. if input_dtype == torch.float16:
  134. g_output = g_output.float()
  135. backward_func = rwkv_cuda_kernel.backward_bf16 if input_dtype == torch.bfloat16 else rwkv_cuda_kernel.backward
  136. backward_func(
  137. time_decay,
  138. time_first,
  139. key,
  140. value,
  141. output,
  142. g_output.contiguous(),
  143. g_time_decay,
  144. g_time_first,
  145. g_key,
  146. g_value,
  147. )
  148. return (
  149. g_time_decay.to(input_dtype),
  150. g_time_first.to(input_dtype),
  151. g_key.to(input_dtype),
  152. g_value.to(input_dtype),
  153. None,
  154. None,
  155. )
  156. def rwkv_linear_attention_cpu(time_decay, time_first, key, value, state=None, return_state=False):
  157. # For CPU fallback. Will be slower and probably take more memory than the custom CUDA kernel if not executed
  158. # within a torch.no_grad.
  159. _, seq_length, _ = key.size()
  160. output = torch.zeros_like(key)
  161. if state is None:
  162. num_state = torch.zeros_like(key[:, 0], dtype=torch.float32)
  163. den_state = torch.zeros_like(key[:, 0], dtype=torch.float32)
  164. max_state = torch.zeros_like(key[:, 0], dtype=torch.float32) - 1e38
  165. else:
  166. num_state, den_state, max_state = state
  167. # For numerical stability
  168. # real_numerator_state = num_state * torch.exp(max_state)
  169. # real_denominator_state = den_state * torch.exp(max_state)
  170. time_decay = -torch.exp(time_decay)
  171. for current_index in range(seq_length):
  172. current_key = key[:, current_index].float()
  173. current_value = value[:, current_index]
  174. # wkv computation at time t
  175. max_for_output = torch.maximum(max_state, current_key + time_first)
  176. e1 = torch.exp(max_state - max_for_output)
  177. e2 = torch.exp(current_key + time_first - max_for_output)
  178. numerator = e1 * num_state + e2 * current_value
  179. denominator = e1 * den_state + e2
  180. output[:, current_index] = (numerator / denominator).to(output.dtype)
  181. # Update state for next iteration
  182. max_for_state = torch.maximum(max_state + time_decay, current_key)
  183. e1 = torch.exp(max_state + time_decay - max_for_state)
  184. e2 = torch.exp(current_key - max_for_state)
  185. num_state = e1 * num_state + e2 * current_value
  186. den_state = e1 * den_state + e2
  187. max_state = max_for_state
  188. if return_state or state is not None:
  189. state = [num_state, den_state, max_state]
  190. return output, state
  191. def rwkv_linear_attention(time_decay, time_first, key, value, state=None, return_state=False):
  192. no_cuda = any(t.device.type != "cuda" for t in [time_decay, time_first, key, value])
  193. # Launching the CUDA kernel for just one token will actually be slower (there is no for loop in the CPU version
  194. # in this case).
  195. one_token = key.size(1) == 1
  196. if rwkv_cuda_kernel is None or no_cuda or one_token:
  197. return rwkv_linear_attention_cpu(time_decay, time_first, key, value, state=state, return_state=return_state)
  198. else:
  199. return RwkvLinearAttention.apply(time_decay, time_first, key, value, state, return_state)
  200. class RwkvSelfAttention(nn.Module):
  201. def __init__(self, config, layer_id=0):
  202. super().__init__()
  203. self.config = config
  204. kernel_loaded = rwkv_cuda_kernel is not None and rwkv_cuda_kernel.max_seq_length == config.context_length
  205. if is_ninja_available() and is_torch_cuda_available() and not kernel_loaded:
  206. try:
  207. load_wkv_cuda_kernel(config.context_length)
  208. except Exception:
  209. logger.info("Could not load the custom CUDA kernel for RWKV attention.")
  210. self.layer_id = layer_id
  211. hidden_size = config.hidden_size
  212. attention_hidden_size = (
  213. config.attention_hidden_size if config.attention_hidden_size is not None else hidden_size
  214. )
  215. self.attention_hidden_size = attention_hidden_size
  216. self.time_decay = nn.Parameter(torch.empty(attention_hidden_size))
  217. self.time_first = nn.Parameter(torch.empty(attention_hidden_size))
  218. self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
  219. self.time_mix_value = nn.Parameter(torch.empty(1, 1, hidden_size))
  220. self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
  221. self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
  222. self.key = nn.Linear(hidden_size, attention_hidden_size, bias=False)
  223. self.value = nn.Linear(hidden_size, attention_hidden_size, bias=False)
  224. self.receptance = nn.Linear(hidden_size, attention_hidden_size, bias=False)
  225. self.output = nn.Linear(attention_hidden_size, hidden_size, bias=False)
  226. # TODO: maybe jit, otherwise move inside forward
  227. def extract_key_value(self, hidden, state=None):
  228. # Mix hidden with the previous timestep to produce key, value, receptance
  229. if hidden.size(1) == 1 and state is not None:
  230. shifted = state[1][:, :, self.layer_id]
  231. else:
  232. shifted = self.time_shift(hidden)
  233. if state is not None:
  234. shifted[:, 0] = state[1][:, :, self.layer_id]
  235. key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
  236. value = hidden * self.time_mix_value + shifted * (1 - self.time_mix_value)
  237. receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
  238. key = self.key(key)
  239. value = self.value(value)
  240. receptance = torch.sigmoid(self.receptance(receptance))
  241. if state is not None:
  242. state[1][:, :, self.layer_id] = hidden[:, -1]
  243. return receptance, key, value, state
  244. def forward(self, hidden, state=None, use_cache=False):
  245. receptance, key, value, state = self.extract_key_value(hidden, state=state)
  246. layer_state = tuple(s[:, :, self.layer_id] for s in state[2:]) if state is not None else None
  247. rwkv, layer_state = rwkv_linear_attention(
  248. self.time_decay,
  249. self.time_first,
  250. key,
  251. value,
  252. state=layer_state,
  253. return_state=use_cache,
  254. )
  255. if layer_state is not None:
  256. state[2][:, :, self.layer_id] = layer_state[0]
  257. state[3][:, :, self.layer_id] = layer_state[1]
  258. state[4][:, :, self.layer_id] = layer_state[2]
  259. return self.output(receptance * rwkv), state
  260. class RwkvFeedForward(nn.Module):
  261. def __init__(self, config, layer_id=0):
  262. super().__init__()
  263. self.config = config
  264. self.layer_id = layer_id
  265. hidden_size = config.hidden_size
  266. intermediate_size = (
  267. config.intermediate_size if config.intermediate_size is not None else 4 * config.hidden_size
  268. )
  269. self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
  270. self.time_mix_key = nn.Parameter(torch.empty(1, 1, hidden_size))
  271. self.time_mix_receptance = nn.Parameter(torch.empty(1, 1, hidden_size))
  272. self.key = nn.Linear(hidden_size, intermediate_size, bias=False)
  273. self.receptance = nn.Linear(hidden_size, hidden_size, bias=False)
  274. self.value = nn.Linear(intermediate_size, hidden_size, bias=False)
  275. def forward(self, hidden, state=None):
  276. if hidden.size(1) == 1 and state is not None:
  277. shifted = state[0][:, :, self.layer_id]
  278. else:
  279. shifted = self.time_shift(hidden)
  280. if state is not None:
  281. shifted[:, 0] = state[0][:, :, self.layer_id]
  282. key = hidden * self.time_mix_key + shifted * (1 - self.time_mix_key)
  283. receptance = hidden * self.time_mix_receptance + shifted * (1 - self.time_mix_receptance)
  284. key = torch.square(torch.relu(self.key(key)))
  285. value = self.value(key)
  286. receptance = torch.sigmoid(self.receptance(receptance))
  287. if state is not None:
  288. state[0][:, :, self.layer_id] = hidden[:, -1]
  289. return receptance * value, state
  290. class RwkvBlock(GradientCheckpointingLayer):
  291. def __init__(self, config, layer_id):
  292. super().__init__()
  293. self.config = config
  294. self.layer_id = layer_id
  295. if layer_id == 0:
  296. self.pre_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
  297. self.ln1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
  298. self.ln2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_epsilon)
  299. self.attention = RwkvSelfAttention(config, layer_id)
  300. self.feed_forward = RwkvFeedForward(config, layer_id)
  301. def forward(self, hidden, state=None, use_cache=False, output_attentions=False):
  302. if self.layer_id == 0:
  303. hidden = self.pre_ln(hidden)
  304. attention, state = self.attention(self.ln1(hidden), state=state, use_cache=use_cache)
  305. hidden = hidden + attention
  306. feed_forward, state = self.feed_forward(self.ln2(hidden), state=state)
  307. hidden = hidden + feed_forward
  308. outputs = (hidden, state)
  309. if output_attentions:
  310. outputs += (attention,)
  311. else:
  312. outputs += (None,)
  313. return outputs
  314. @auto_docstring
  315. class RwkvPreTrainedModel(PreTrainedModel):
  316. config: RwkvConfig
  317. base_model_prefix = "rwkv"
  318. _no_split_modules = ["RwkvBlock"]
  319. _keep_in_fp32_modules = ["time_decay", "time_first"]
  320. supports_gradient_checkpointing = True
  321. _is_stateful = True
  322. def _init_weights(self, module: nn.Module):
  323. """Initialize the weights."""
  324. if isinstance(module, RwkvSelfAttention):
  325. layer_id = module.layer_id
  326. num_hidden_layers = module.config.num_hidden_layers
  327. hidden_size = module.config.hidden_size
  328. attention_hidden_size = module.attention_hidden_size
  329. ratio_0_to_1 = layer_id / (num_hidden_layers - 1) # 0 to 1
  330. ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
  331. time_weight = torch.tensor(
  332. [i / hidden_size for i in range(hidden_size)],
  333. dtype=module.time_mix_key.dtype,
  334. device=module.time_mix_key.device,
  335. )
  336. time_weight = time_weight[None, None, :]
  337. decay_speed = [
  338. -5 + 8 * (h / (attention_hidden_size - 1)) ** (0.7 + 1.3 * ratio_0_to_1)
  339. for h in range(attention_hidden_size)
  340. ]
  341. decay_speed = torch.tensor(decay_speed, dtype=module.time_decay.dtype, device=module.time_decay.device)
  342. zigzag = (
  343. torch.tensor(
  344. [(i + 1) % 3 - 1 for i in range(attention_hidden_size)],
  345. dtype=module.time_first.dtype,
  346. device=module.time_first.device,
  347. )
  348. * 0.5
  349. )
  350. module.time_decay.data = decay_speed
  351. module.time_first.data = torch.ones_like(module.time_first * math.log(0.3) + zigzag)
  352. module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
  353. module.time_mix_value.data = torch.pow(time_weight, ratio_1_to_almost0) + 0.3 * ratio_0_to_1
  354. module.time_mix_receptance.data = torch.pow(time_weight, 0.5 * ratio_1_to_almost0)
  355. elif isinstance(module, RwkvFeedForward):
  356. layer_id = module.layer_id
  357. num_hidden_layers = module.config.num_hidden_layers
  358. hidden_size = module.config.hidden_size
  359. ratio_1_to_almost0 = 1.0 - (layer_id / num_hidden_layers) # 1 to ~0
  360. time_weight = torch.tensor(
  361. [i / hidden_size for i in range(hidden_size)],
  362. dtype=module.time_mix_key.dtype,
  363. device=module.time_mix_key.device,
  364. )
  365. time_weight = time_weight[None, None, :]
  366. module.time_mix_key.data = torch.pow(time_weight, ratio_1_to_almost0)
  367. module.time_mix_receptance.data = torch.pow(time_weight, ratio_1_to_almost0)
  368. elif isinstance(module, nn.Linear):
  369. shape = module.weight.data.shape
  370. gain = 1.0
  371. scale = 1.0 # extra scale for gain
  372. if module.bias is not None:
  373. module.bias.data.zero_()
  374. if shape[0] > shape[1]:
  375. gain = math.sqrt(shape[0] / shape[1])
  376. if shape[0] == self.config.vocab_size and shape[1] == self.config.hidden_size: # final projection?
  377. scale = 0.5
  378. gain *= scale
  379. nn.init.orthogonal_(module.weight, gain=gain)
  380. elif isinstance(module, nn.Embedding):
  381. shape = module.weight.data.shape
  382. gain = 1e-4 * math.sqrt(max(shape[0], shape[1]))
  383. nn.init.orthogonal_(module.weight, gain=gain)
  384. elif isinstance(module, nn.LayerNorm):
  385. module.weight.data.fill_(1.0)
  386. module.bias.data.zero_()
  387. @dataclass
  388. @auto_docstring(
  389. custom_intro="""
  390. Class for the RWKV model outputs.
  391. """
  392. )
  393. class RwkvOutput(ModelOutput):
  394. r"""
  395. state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
  396. The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
  397. avoid providing the old `input_ids`.
  398. """
  399. last_hidden_state: Optional[torch.FloatTensor] = None
  400. state: Optional[list[torch.FloatTensor]] = None
  401. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  402. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  403. @dataclass
  404. @auto_docstring(
  405. custom_intro="""
  406. Base class for causal language model (or autoregressive) outputs.
  407. """
  408. )
  409. class RwkvCausalLMOutput(ModelOutput):
  410. r"""
  411. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  412. Language modeling loss (for next-token prediction).
  413. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  414. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  415. state (list of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`):
  416. The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
  417. avoid providing the old `input_ids`.
  418. """
  419. loss: Optional[torch.FloatTensor] = None
  420. logits: Optional[torch.FloatTensor] = None
  421. state: Optional[list[torch.FloatTensor]] = None
  422. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  423. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  424. @auto_docstring
  425. class RwkvModel(RwkvPreTrainedModel):
  426. def __init__(self, config):
  427. super().__init__(config)
  428. self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
  429. self.blocks = nn.ModuleList([RwkvBlock(config, layer_id=idx) for idx in range(config.num_hidden_layers)])
  430. self.ln_out = nn.LayerNorm(config.hidden_size)
  431. self.layers_are_rescaled = False
  432. self.gradient_checkpointing = False
  433. # Initialize weights and apply final processing
  434. self.post_init()
  435. def get_input_embeddings(self):
  436. return self.embeddings
  437. def set_input_embeddings(self, new_embeddings):
  438. self.embeddings = new_embeddings
  439. @auto_docstring
  440. def forward(
  441. self,
  442. input_ids: Optional[torch.LongTensor] = None,
  443. attention_mask: Optional[torch.LongTensor] = None,
  444. inputs_embeds: Optional[torch.FloatTensor] = None,
  445. state: Optional[list[torch.FloatTensor]] = None,
  446. use_cache: Optional[bool] = None,
  447. output_attentions: Optional[bool] = None,
  448. output_hidden_states: Optional[bool] = None,
  449. return_dict: Optional[bool] = None,
  450. ) -> Union[tuple, RwkvOutput]:
  451. r"""
  452. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  453. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  454. `past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input
  455. sequence tokens in the vocabulary.
  456. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  457. `input_ids`.
  458. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  459. [`PreTrainedTokenizer.__call__`] for details.
  460. [What are input IDs?](../glossary#input-ids)
  461. state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
  462. If passed along, the model uses the previous state in all the blocks (which will give the output for the
  463. `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
  464. use_cache (`bool`, *optional*):
  465. If set to `True`, the last state is returned and can be used to quickly generate the next logits.
  466. """
  467. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  468. output_hidden_states = (
  469. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  470. )
  471. use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
  472. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  473. if attention_mask is not None:
  474. logger.warning_once("`attention_mask` was passed, but it is unused in this model.")
  475. if self.training == self.layers_are_rescaled:
  476. self._rescale_layers()
  477. if input_ids is not None and inputs_embeds is not None:
  478. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  479. elif input_ids is None and inputs_embeds is None:
  480. raise ValueError("You have to specify either input_ids or inputs_embeds")
  481. if inputs_embeds is None:
  482. inputs_embeds = self.embeddings(input_ids)
  483. if use_cache and state is None:
  484. shape = (inputs_embeds.size(0), self.config.hidden_size, self.config.num_hidden_layers)
  485. state = [
  486. torch.zeros(
  487. *shape, dtype=inputs_embeds.dtype if i <= 1 else torch.float32, device=inputs_embeds.device
  488. )
  489. for i in range(5)
  490. ]
  491. state[4] -= 1e30
  492. if self.gradient_checkpointing and self.training:
  493. if use_cache:
  494. logger.warning_once(
  495. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  496. )
  497. use_cache = False
  498. hidden_states = inputs_embeds
  499. all_self_attentions = () if output_attentions else None
  500. all_hidden_states = () if output_hidden_states else None
  501. for idx, block in enumerate(self.blocks):
  502. hidden_states, state, attentions = block(
  503. hidden_states, state=state, use_cache=use_cache, output_attentions=output_attentions
  504. )
  505. if (
  506. self.layers_are_rescaled
  507. and self.config.rescale_every > 0
  508. and (idx + 1) % self.config.rescale_every == 0
  509. ):
  510. hidden_states = hidden_states / 2
  511. if output_hidden_states:
  512. all_hidden_states = all_hidden_states + (hidden_states,)
  513. if output_attentions:
  514. all_self_attentions = all_self_attentions + (attentions,)
  515. hidden_states = self.ln_out(hidden_states)
  516. if output_hidden_states:
  517. all_hidden_states = all_hidden_states + (hidden_states,)
  518. if not return_dict:
  519. return tuple(x for x in [hidden_states, state, all_hidden_states, all_self_attentions] if x is not None)
  520. return RwkvOutput(
  521. last_hidden_state=hidden_states,
  522. state=state,
  523. hidden_states=all_hidden_states,
  524. attentions=all_self_attentions,
  525. )
  526. def _rescale_layers(self):
  527. # Layers should be rescaled for inference only.
  528. if self.layers_are_rescaled == (not self.training):
  529. return
  530. if self.config.rescale_every > 0:
  531. with torch.no_grad():
  532. for block_id, block in enumerate(self.blocks):
  533. if self.training:
  534. block.attention.output.weight.mul_(2 ** int(block_id // self.config.rescale_every))
  535. block.feed_forward.value.weight.mul_(2 ** int(block_id // self.config.rescale_every))
  536. else:
  537. # Deal with quantization statistics
  538. if hasattr(block.attention.output.weight, "SCB"):
  539. block.attention.output.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
  540. block.feed_forward.value.weight.SCB.div_(2 ** int(block_id // self.config.rescale_every))
  541. elif hasattr(block.attention.output.weight, "quant_state"):
  542. self._bnb_4bit_dequantize_and_rescale(block.attention.output, block_id)
  543. self._bnb_4bit_dequantize_and_rescale(block.feed_forward.value, block_id)
  544. else:
  545. block.attention.output.weight.div_(2 ** int(block_id // self.config.rescale_every))
  546. block.feed_forward.value.weight.div_(2 ** int(block_id // self.config.rescale_every))
  547. self.layers_are_rescaled = not self.training
  548. def _bnb_4bit_dequantize_and_rescale(self, target_layer, block_id):
  549. r"""
  550. Perform the dequantization and rescaling of the weights of a given layer. After that operation the layer will
  551. be quantized again.
  552. """
  553. if not is_bitsandbytes_available():
  554. raise ImportError("Please install bitsandbytes to use this method.")
  555. import bitsandbytes as bnb
  556. dequant_weights = bnb.functional.dequantize_4bit(target_layer.weight.data, target_layer.weight.quant_state)
  557. dequant_weights.div_(2 ** int(block_id // self.config.rescale_every))
  558. # re-quantize the model:
  559. # we need to put it first on CPU then back to the device
  560. # this will create an overhead :/
  561. # We set requires_grad=False as we cannot compute gradients on top of 4bit parameters anyway and to avoid
  562. # bugs with bnb
  563. quant_weight = bnb.nn.Params4bit(dequant_weights.to("cpu"), requires_grad=False).to(dequant_weights.device)
  564. setattr(target_layer, "weight", quant_weight)
  565. @auto_docstring(
  566. custom_intro="""
  567. The RWKV Model transformer with a language modeling head on top (linear layer with weights tied to the input
  568. embeddings).
  569. """
  570. )
  571. class RwkvForCausalLM(RwkvPreTrainedModel, GenerationMixin):
  572. _tied_weights_keys = ["head.weight"]
  573. def __init__(self, config):
  574. super().__init__(config)
  575. self.rwkv = RwkvModel(config)
  576. self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  577. # Initialize weights and apply final processing
  578. self.post_init()
  579. def get_output_embeddings(self):
  580. return self.head
  581. def set_output_embeddings(self, new_embeddings):
  582. self.head = new_embeddings
  583. def prepare_inputs_for_generation(self, input_ids, state=None, inputs_embeds=None, use_cache=None, **kwargs):
  584. # Overwritten -- this model uses `state`, but doesn't have a cache (`past_key_values`)
  585. # only last token for inputs_ids if the state is passed along.
  586. if state is not None:
  587. input_ids = input_ids[:, -1].unsqueeze(-1)
  588. # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
  589. if inputs_embeds is not None and state is None:
  590. model_inputs = {"inputs_embeds": inputs_embeds}
  591. else:
  592. model_inputs = {"input_ids": input_ids}
  593. model_inputs["state"] = state
  594. model_inputs["use_cache"] = use_cache
  595. # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
  596. for key, value in kwargs.items():
  597. if key not in model_inputs:
  598. model_inputs[key] = value
  599. return model_inputs
  600. @auto_docstring
  601. def forward(
  602. self,
  603. input_ids: Optional[torch.LongTensor] = None,
  604. attention_mask: Optional[torch.LongTensor] = None,
  605. inputs_embeds: Optional[torch.FloatTensor] = None,
  606. state: Optional[list[torch.FloatTensor]] = None,
  607. labels: Optional[torch.LongTensor] = None,
  608. use_cache: Optional[bool] = None,
  609. output_attentions: Optional[bool] = None,
  610. output_hidden_states: Optional[bool] = None,
  611. return_dict: Optional[bool] = None,
  612. **kwargs,
  613. ) -> Union[tuple, RwkvCausalLMOutput]:
  614. r"""
  615. input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
  616. `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
  617. `past_key_values.get_seq_length()` (`sequence_length` of input past key value states). Indices of input
  618. sequence tokens in the vocabulary.
  619. If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
  620. `input_ids`.
  621. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  622. [`PreTrainedTokenizer.__call__`] for details.
  623. [What are input IDs?](../glossary#input-ids)
  624. state (tuple of five `torch.FloatTensor` of shape `(batch_size, hidden_size, num_hidden_layers)`, *optional*):
  625. If passed along, the model uses the previous state in all the blocks (which will give the output for the
  626. `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
  627. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  628. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  629. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  630. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  631. use_cache (`bool`, *optional*):
  632. If set to `True`, the last state is returned and can be used to quickly generate the next logits.
  633. """
  634. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  635. rwkv_outputs = self.rwkv(
  636. input_ids,
  637. inputs_embeds=inputs_embeds,
  638. state=state,
  639. use_cache=use_cache,
  640. output_attentions=output_attentions,
  641. output_hidden_states=output_hidden_states,
  642. return_dict=return_dict,
  643. )
  644. hidden_states = rwkv_outputs[0]
  645. logits = self.head(hidden_states)
  646. loss = None
  647. if labels is not None:
  648. loss = self.loss_function(
  649. logits,
  650. labels,
  651. vocab_size=self.config.vocab_size,
  652. **kwargs,
  653. )
  654. if not return_dict:
  655. output = (logits,) + rwkv_outputs[1:]
  656. return ((loss,) + output) if loss is not None else output
  657. return RwkvCausalLMOutput(
  658. loss=loss,
  659. logits=logits,
  660. state=rwkv_outputs.state,
  661. hidden_states=rwkv_outputs.hidden_states,
  662. attentions=rwkv_outputs.attentions,
  663. )
  664. __all__ = ["RwkvForCausalLM", "RwkvModel", "RwkvPreTrainedModel"]