modeling_mra.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. # coding=utf-8
  2. # Copyright 2023 University of Wisconsin-Madison and The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch MRA model."""
  16. import math
  17. from pathlib import Path
  18. from typing import Optional, Union
  19. import torch
  20. from torch import nn
  21. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  22. from torch.utils.cpp_extension import load
  23. from ...activations import ACT2FN
  24. from ...modeling_layers import GradientCheckpointingLayer
  25. from ...modeling_outputs import (
  26. BaseModelOutputWithCrossAttentions,
  27. MaskedLMOutput,
  28. MultipleChoiceModelOutput,
  29. QuestionAnsweringModelOutput,
  30. SequenceClassifierOutput,
  31. TokenClassifierOutput,
  32. )
  33. from ...modeling_utils import PreTrainedModel
  34. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  35. from ...utils import auto_docstring, is_cuda_platform, is_ninja_available, is_torch_cuda_available, logging
  36. from .configuration_mra import MraConfig
  37. logger = logging.get_logger(__name__)
  38. mra_cuda_kernel = None
  39. def load_cuda_kernels():
  40. global mra_cuda_kernel
  41. src_folder = Path(__file__).resolve().parent.parent.parent / "kernels" / "mra"
  42. def append_root(files):
  43. return [src_folder / file for file in files]
  44. src_files = append_root(["cuda_kernel.cu", "cuda_launch.cu", "torch_extension.cpp"])
  45. mra_cuda_kernel = load("cuda_kernel", src_files, verbose=True)
  46. def sparse_max(sparse_qk_prod, indices, query_num_block, key_num_block):
  47. """
  48. Computes maximum values for softmax stability.
  49. """
  50. if len(sparse_qk_prod.size()) != 4:
  51. raise ValueError("sparse_qk_prod must be a 4-dimensional tensor.")
  52. if len(indices.size()) != 2:
  53. raise ValueError("indices must be a 2-dimensional tensor.")
  54. if sparse_qk_prod.size(2) != 32:
  55. raise ValueError("The size of the second dimension of sparse_qk_prod must be 32.")
  56. if sparse_qk_prod.size(3) != 32:
  57. raise ValueError("The size of the third dimension of sparse_qk_prod must be 32.")
  58. index_vals = sparse_qk_prod.max(dim=-2).values.transpose(-1, -2)
  59. index_vals = index_vals.contiguous()
  60. indices = indices.int()
  61. indices = indices.contiguous()
  62. max_vals, max_vals_scatter = mra_cuda_kernel.index_max(index_vals, indices, query_num_block, key_num_block)
  63. max_vals_scatter = max_vals_scatter.transpose(-1, -2)[:, :, None, :]
  64. return max_vals, max_vals_scatter
  65. def sparse_mask(mask, indices, block_size=32):
  66. """
  67. Converts attention mask to a sparse mask for high resolution logits.
  68. """
  69. if len(mask.size()) != 2:
  70. raise ValueError("mask must be a 2-dimensional tensor.")
  71. if len(indices.size()) != 2:
  72. raise ValueError("indices must be a 2-dimensional tensor.")
  73. if mask.shape[0] != indices.shape[0]:
  74. raise ValueError("mask and indices must have the same size in the zero-th dimension.")
  75. batch_size, seq_len = mask.shape
  76. num_block = seq_len // block_size
  77. batch_idx = torch.arange(indices.size(0), dtype=torch.long, device=indices.device)
  78. mask = mask.reshape(batch_size, num_block, block_size)
  79. mask = mask[batch_idx[:, None], (indices % num_block).long(), :]
  80. return mask
  81. def mm_to_sparse(dense_query, dense_key, indices, block_size=32):
  82. """
  83. Performs Sampled Dense Matrix Multiplication.
  84. """
  85. batch_size, query_size, dim = dense_query.size()
  86. _, key_size, dim = dense_key.size()
  87. if query_size % block_size != 0:
  88. raise ValueError("query_size (size of first dimension of dense_query) must be divisible by block_size.")
  89. if key_size % block_size != 0:
  90. raise ValueError("key_size (size of first dimension of dense_key) must be divisible by block_size.")
  91. dense_query = dense_query.reshape(batch_size, query_size // block_size, block_size, dim).transpose(-1, -2)
  92. dense_key = dense_key.reshape(batch_size, key_size // block_size, block_size, dim).transpose(-1, -2)
  93. if len(dense_query.size()) != 4:
  94. raise ValueError("dense_query must be a 4-dimensional tensor.")
  95. if len(dense_key.size()) != 4:
  96. raise ValueError("dense_key must be a 4-dimensional tensor.")
  97. if len(indices.size()) != 2:
  98. raise ValueError("indices must be a 2-dimensional tensor.")
  99. if dense_query.size(3) != 32:
  100. raise ValueError("The third dimension of dense_query must be 32.")
  101. if dense_key.size(3) != 32:
  102. raise ValueError("The third dimension of dense_key must be 32.")
  103. dense_query = dense_query.contiguous()
  104. dense_key = dense_key.contiguous()
  105. indices = indices.int()
  106. indices = indices.contiguous()
  107. return mra_cuda_kernel.mm_to_sparse(dense_query, dense_key, indices.int())
  108. def sparse_dense_mm(sparse_query, indices, dense_key, query_num_block, block_size=32):
  109. """
  110. Performs matrix multiplication of a sparse matrix with a dense matrix.
  111. """
  112. batch_size, key_size, dim = dense_key.size()
  113. if key_size % block_size != 0:
  114. raise ValueError("key_size (size of first dimension of dense_key) must be divisible by block_size.")
  115. if sparse_query.size(2) != block_size:
  116. raise ValueError("The size of the second dimension of sparse_query must be equal to the block_size.")
  117. if sparse_query.size(3) != block_size:
  118. raise ValueError("The size of the third dimension of sparse_query must be equal to the block_size.")
  119. dense_key = dense_key.reshape(batch_size, key_size // block_size, block_size, dim).transpose(-1, -2)
  120. if len(sparse_query.size()) != 4:
  121. raise ValueError("sparse_query must be a 4-dimensional tensor.")
  122. if len(dense_key.size()) != 4:
  123. raise ValueError("dense_key must be a 4-dimensional tensor.")
  124. if len(indices.size()) != 2:
  125. raise ValueError("indices must be a 2-dimensional tensor.")
  126. if dense_key.size(3) != 32:
  127. raise ValueError("The size of the third dimension of dense_key must be 32.")
  128. sparse_query = sparse_query.contiguous()
  129. indices = indices.int()
  130. indices = indices.contiguous()
  131. dense_key = dense_key.contiguous()
  132. dense_qk_prod = mra_cuda_kernel.sparse_dense_mm(sparse_query, indices, dense_key, query_num_block)
  133. dense_qk_prod = dense_qk_prod.transpose(-1, -2).reshape(batch_size, query_num_block * block_size, dim)
  134. return dense_qk_prod
  135. def transpose_indices(indices, dim_1_block, dim_2_block):
  136. return ((indices % dim_2_block) * dim_1_block + torch.div(indices, dim_2_block, rounding_mode="floor")).long()
  137. class MraSampledDenseMatMul(torch.autograd.Function):
  138. @staticmethod
  139. def forward(ctx, dense_query, dense_key, indices, block_size):
  140. sparse_qk_prod = mm_to_sparse(dense_query, dense_key, indices, block_size)
  141. ctx.save_for_backward(dense_query, dense_key, indices)
  142. ctx.block_size = block_size
  143. return sparse_qk_prod
  144. @staticmethod
  145. def backward(ctx, grad):
  146. dense_query, dense_key, indices = ctx.saved_tensors
  147. block_size = ctx.block_size
  148. query_num_block = dense_query.size(1) // block_size
  149. key_num_block = dense_key.size(1) // block_size
  150. indices_T = transpose_indices(indices, query_num_block, key_num_block)
  151. grad_key = sparse_dense_mm(grad.transpose(-1, -2), indices_T, dense_query, key_num_block)
  152. grad_query = sparse_dense_mm(grad, indices, dense_key, query_num_block)
  153. return grad_query, grad_key, None, None
  154. @staticmethod
  155. def operator_call(dense_query, dense_key, indices, block_size=32):
  156. return MraSampledDenseMatMul.apply(dense_query, dense_key, indices, block_size)
  157. class MraSparseDenseMatMul(torch.autograd.Function):
  158. @staticmethod
  159. def forward(ctx, sparse_query, indices, dense_key, query_num_block):
  160. sparse_qk_prod = sparse_dense_mm(sparse_query, indices, dense_key, query_num_block)
  161. ctx.save_for_backward(sparse_query, indices, dense_key)
  162. ctx.query_num_block = query_num_block
  163. return sparse_qk_prod
  164. @staticmethod
  165. def backward(ctx, grad):
  166. sparse_query, indices, dense_key = ctx.saved_tensors
  167. query_num_block = ctx.query_num_block
  168. key_num_block = dense_key.size(1) // sparse_query.size(-1)
  169. indices_T = transpose_indices(indices, query_num_block, key_num_block)
  170. grad_key = sparse_dense_mm(sparse_query.transpose(-1, -2), indices_T, grad, key_num_block)
  171. grad_query = mm_to_sparse(grad, dense_key, indices)
  172. return grad_query, None, grad_key, None
  173. @staticmethod
  174. def operator_call(sparse_query, indices, dense_key, query_num_block):
  175. return MraSparseDenseMatMul.apply(sparse_query, indices, dense_key, query_num_block)
  176. class MraReduceSum:
  177. @staticmethod
  178. def operator_call(sparse_query, indices, query_num_block, key_num_block):
  179. batch_size, num_block, block_size, _ = sparse_query.size()
  180. if len(sparse_query.size()) != 4:
  181. raise ValueError("sparse_query must be a 4-dimensional tensor.")
  182. if len(indices.size()) != 2:
  183. raise ValueError("indices must be a 2-dimensional tensor.")
  184. _, _, block_size, _ = sparse_query.size()
  185. batch_size, num_block = indices.size()
  186. sparse_query = sparse_query.sum(dim=2).reshape(batch_size * num_block, block_size)
  187. batch_idx = torch.arange(indices.size(0), dtype=torch.long, device=indices.device)
  188. global_idxes = (
  189. torch.div(indices, key_num_block, rounding_mode="floor").long() + batch_idx[:, None] * query_num_block
  190. ).reshape(batch_size * num_block)
  191. temp = torch.zeros(
  192. (batch_size * query_num_block, block_size), dtype=sparse_query.dtype, device=sparse_query.device
  193. )
  194. output = temp.index_add(0, global_idxes, sparse_query).reshape(batch_size, query_num_block, block_size)
  195. output = output.reshape(batch_size, query_num_block * block_size)
  196. return output
  197. def get_low_resolution_logit(query, key, block_size, mask=None, value=None):
  198. """
  199. Compute low resolution approximation.
  200. """
  201. batch_size, seq_len, head_dim = query.size()
  202. num_block_per_row = seq_len // block_size
  203. value_hat = None
  204. if mask is not None:
  205. token_count = mask.reshape(batch_size, num_block_per_row, block_size).sum(dim=-1)
  206. query_hat = query.reshape(batch_size, num_block_per_row, block_size, head_dim).sum(dim=-2) / (
  207. token_count[:, :, None] + 1e-6
  208. )
  209. key_hat = key.reshape(batch_size, num_block_per_row, block_size, head_dim).sum(dim=-2) / (
  210. token_count[:, :, None] + 1e-6
  211. )
  212. if value is not None:
  213. value_hat = value.reshape(batch_size, num_block_per_row, block_size, head_dim).sum(dim=-2) / (
  214. token_count[:, :, None] + 1e-6
  215. )
  216. else:
  217. token_count = block_size * torch.ones(batch_size, num_block_per_row, dtype=torch.float, device=query.device)
  218. query_hat = query.reshape(batch_size, num_block_per_row, block_size, head_dim).mean(dim=-2)
  219. key_hat = key.reshape(batch_size, num_block_per_row, block_size, head_dim).mean(dim=-2)
  220. if value is not None:
  221. value_hat = value.reshape(batch_size, num_block_per_row, block_size, head_dim).mean(dim=-2)
  222. low_resolution_logit = torch.matmul(query_hat, key_hat.transpose(-1, -2)) / math.sqrt(head_dim)
  223. low_resolution_logit_row_max = low_resolution_logit.max(dim=-1, keepdims=True).values
  224. if mask is not None:
  225. low_resolution_logit = (
  226. low_resolution_logit - 1e4 * ((token_count[:, None, :] * token_count[:, :, None]) < 0.5).float()
  227. )
  228. return low_resolution_logit, token_count, low_resolution_logit_row_max, value_hat
  229. def get_block_idxes(
  230. low_resolution_logit, num_blocks, approx_mode, initial_prior_first_n_blocks, initial_prior_diagonal_n_blocks
  231. ):
  232. """
  233. Compute the indices of the subset of components to be used in the approximation.
  234. """
  235. batch_size, total_blocks_per_row, _ = low_resolution_logit.shape
  236. if initial_prior_diagonal_n_blocks > 0:
  237. offset = initial_prior_diagonal_n_blocks // 2
  238. temp_mask = torch.ones(total_blocks_per_row, total_blocks_per_row, device=low_resolution_logit.device)
  239. diagonal_mask = torch.tril(torch.triu(temp_mask, diagonal=-offset), diagonal=offset)
  240. low_resolution_logit = low_resolution_logit + diagonal_mask[None, :, :] * 5e3
  241. if initial_prior_first_n_blocks > 0:
  242. low_resolution_logit[:, :initial_prior_first_n_blocks, :] = (
  243. low_resolution_logit[:, :initial_prior_first_n_blocks, :] + 5e3
  244. )
  245. low_resolution_logit[:, :, :initial_prior_first_n_blocks] = (
  246. low_resolution_logit[:, :, :initial_prior_first_n_blocks] + 5e3
  247. )
  248. top_k_vals = torch.topk(
  249. low_resolution_logit.reshape(batch_size, -1), num_blocks, dim=-1, largest=True, sorted=False
  250. )
  251. indices = top_k_vals.indices
  252. if approx_mode == "full":
  253. threshold = top_k_vals.values.min(dim=-1).values
  254. high_resolution_mask = (low_resolution_logit >= threshold[:, None, None]).float()
  255. elif approx_mode == "sparse":
  256. high_resolution_mask = None
  257. else:
  258. raise ValueError(f"{approx_mode} is not a valid approx_model value.")
  259. return indices, high_resolution_mask
  260. def mra2_attention(
  261. query,
  262. key,
  263. value,
  264. mask,
  265. num_blocks,
  266. approx_mode,
  267. block_size=32,
  268. initial_prior_first_n_blocks=0,
  269. initial_prior_diagonal_n_blocks=0,
  270. ):
  271. """
  272. Use Mra to approximate self-attention.
  273. """
  274. if mra_cuda_kernel is None:
  275. return torch.zeros_like(query).requires_grad_()
  276. batch_size, num_head, seq_len, head_dim = query.size()
  277. meta_batch = batch_size * num_head
  278. if seq_len % block_size != 0:
  279. raise ValueError("sequence length must be divisible by the block_size.")
  280. num_block_per_row = seq_len // block_size
  281. query = query.reshape(meta_batch, seq_len, head_dim)
  282. key = key.reshape(meta_batch, seq_len, head_dim)
  283. value = value.reshape(meta_batch, seq_len, head_dim)
  284. if mask is not None:
  285. query = query * mask[:, :, None]
  286. key = key * mask[:, :, None]
  287. value = value * mask[:, :, None]
  288. if approx_mode == "full":
  289. low_resolution_logit, token_count, low_resolution_logit_row_max, value_hat = get_low_resolution_logit(
  290. query, key, block_size, mask, value
  291. )
  292. elif approx_mode == "sparse":
  293. with torch.no_grad():
  294. low_resolution_logit, token_count, low_resolution_logit_row_max, _ = get_low_resolution_logit(
  295. query, key, block_size, mask
  296. )
  297. else:
  298. raise Exception('approx_mode must be "full" or "sparse"')
  299. with torch.no_grad():
  300. low_resolution_logit_normalized = low_resolution_logit - low_resolution_logit_row_max
  301. indices, high_resolution_mask = get_block_idxes(
  302. low_resolution_logit_normalized,
  303. num_blocks,
  304. approx_mode,
  305. initial_prior_first_n_blocks,
  306. initial_prior_diagonal_n_blocks,
  307. )
  308. high_resolution_logit = MraSampledDenseMatMul.operator_call(
  309. query, key, indices, block_size=block_size
  310. ) / math.sqrt(head_dim)
  311. max_vals, max_vals_scatter = sparse_max(high_resolution_logit, indices, num_block_per_row, num_block_per_row)
  312. high_resolution_logit = high_resolution_logit - max_vals_scatter
  313. if mask is not None:
  314. high_resolution_logit = high_resolution_logit - 1e4 * (1 - sparse_mask(mask, indices)[:, :, :, None])
  315. high_resolution_attn = torch.exp(high_resolution_logit)
  316. high_resolution_attn_out = MraSparseDenseMatMul.operator_call(
  317. high_resolution_attn, indices, value, num_block_per_row
  318. )
  319. high_resolution_normalizer = MraReduceSum.operator_call(
  320. high_resolution_attn, indices, num_block_per_row, num_block_per_row
  321. )
  322. if approx_mode == "full":
  323. low_resolution_attn = (
  324. torch.exp(low_resolution_logit - low_resolution_logit_row_max - 1e4 * high_resolution_mask)
  325. * token_count[:, None, :]
  326. )
  327. low_resolution_attn_out = (
  328. torch.matmul(low_resolution_attn, value_hat)[:, :, None, :]
  329. .repeat(1, 1, block_size, 1)
  330. .reshape(meta_batch, seq_len, head_dim)
  331. )
  332. low_resolution_normalizer = (
  333. low_resolution_attn.sum(dim=-1)[:, :, None].repeat(1, 1, block_size).reshape(meta_batch, seq_len)
  334. )
  335. log_correction = low_resolution_logit_row_max.repeat(1, 1, block_size).reshape(meta_batch, seq_len) - max_vals
  336. if mask is not None:
  337. log_correction = log_correction * mask
  338. low_resolution_corr = torch.exp(log_correction * (log_correction <= 0).float())
  339. low_resolution_attn_out = low_resolution_attn_out * low_resolution_corr[:, :, None]
  340. low_resolution_normalizer = low_resolution_normalizer * low_resolution_corr
  341. high_resolution_corr = torch.exp(-log_correction * (log_correction > 0).float())
  342. high_resolution_attn_out = high_resolution_attn_out * high_resolution_corr[:, :, None]
  343. high_resolution_normalizer = high_resolution_normalizer * high_resolution_corr
  344. context_layer = (high_resolution_attn_out + low_resolution_attn_out) / (
  345. high_resolution_normalizer[:, :, None] + low_resolution_normalizer[:, :, None] + 1e-6
  346. )
  347. elif approx_mode == "sparse":
  348. context_layer = high_resolution_attn_out / (high_resolution_normalizer[:, :, None] + 1e-6)
  349. else:
  350. raise Exception('config.approx_mode must be "full" or "sparse"')
  351. if mask is not None:
  352. context_layer = context_layer * mask[:, :, None]
  353. context_layer = context_layer.reshape(batch_size, num_head, seq_len, head_dim)
  354. return context_layer
  355. class MraEmbeddings(nn.Module):
  356. """Construct the embeddings from word, position and token_type embeddings."""
  357. def __init__(self, config):
  358. super().__init__()
  359. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  360. self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
  361. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  362. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  363. # any TensorFlow checkpoint file
  364. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  365. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  366. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  367. self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2)
  368. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  369. self.register_buffer(
  370. "token_type_ids",
  371. torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
  372. persistent=False,
  373. )
  374. def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
  375. if input_ids is not None:
  376. input_shape = input_ids.size()
  377. else:
  378. input_shape = inputs_embeds.size()[:-1]
  379. seq_length = input_shape[1]
  380. if position_ids is None:
  381. position_ids = self.position_ids[:, :seq_length]
  382. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  383. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  384. # issue #5664
  385. if token_type_ids is None:
  386. if hasattr(self, "token_type_ids"):
  387. buffered_token_type_ids = self.token_type_ids[:, :seq_length]
  388. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
  389. token_type_ids = buffered_token_type_ids_expanded
  390. else:
  391. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  392. if inputs_embeds is None:
  393. inputs_embeds = self.word_embeddings(input_ids)
  394. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  395. embeddings = inputs_embeds + token_type_embeddings
  396. if self.position_embedding_type == "absolute":
  397. position_embeddings = self.position_embeddings(position_ids)
  398. embeddings += position_embeddings
  399. embeddings = self.LayerNorm(embeddings)
  400. embeddings = self.dropout(embeddings)
  401. return embeddings
  402. class MraSelfAttention(nn.Module):
  403. def __init__(self, config, position_embedding_type=None):
  404. super().__init__()
  405. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  406. raise ValueError(
  407. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  408. f"heads ({config.num_attention_heads})"
  409. )
  410. kernel_loaded = mra_cuda_kernel is not None
  411. if is_torch_cuda_available() and is_cuda_platform() and is_ninja_available() and not kernel_loaded:
  412. try:
  413. load_cuda_kernels()
  414. except Exception as e:
  415. logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}")
  416. self.num_attention_heads = config.num_attention_heads
  417. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  418. self.all_head_size = self.num_attention_heads * self.attention_head_size
  419. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  420. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  421. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  422. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  423. self.position_embedding_type = (
  424. position_embedding_type if position_embedding_type is not None else config.position_embedding_type
  425. )
  426. self.num_block = (config.max_position_embeddings // 32) * config.block_per_row
  427. self.num_block = min(self.num_block, int((config.max_position_embeddings // 32) ** 2))
  428. self.approx_mode = config.approx_mode
  429. self.initial_prior_first_n_blocks = config.initial_prior_first_n_blocks
  430. self.initial_prior_diagonal_n_blocks = config.initial_prior_diagonal_n_blocks
  431. def forward(self, hidden_states, attention_mask=None):
  432. batch_size, seq_len, _ = hidden_states.shape
  433. query_layer = (
  434. self.query(hidden_states)
  435. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  436. .transpose(1, 2)
  437. )
  438. key_layer = (
  439. self.key(hidden_states)
  440. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  441. .transpose(1, 2)
  442. )
  443. value_layer = (
  444. self.value(hidden_states)
  445. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  446. .transpose(1, 2)
  447. )
  448. # revert changes made by get_extended_attention_mask
  449. attention_mask = 1.0 + attention_mask / 10000.0
  450. attention_mask = (
  451. attention_mask.squeeze()
  452. .repeat(1, self.num_attention_heads, 1)
  453. .reshape(batch_size * self.num_attention_heads, seq_len)
  454. .int()
  455. )
  456. # The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs
  457. # smaller than this are padded with zeros.
  458. gpu_warp_size = 32
  459. if self.attention_head_size < gpu_warp_size:
  460. pad_size = batch_size, self.num_attention_heads, seq_len, gpu_warp_size - self.attention_head_size
  461. query_layer = torch.cat([query_layer, torch.zeros(pad_size, device=query_layer.device)], dim=-1)
  462. key_layer = torch.cat([key_layer, torch.zeros(pad_size, device=key_layer.device)], dim=-1)
  463. value_layer = torch.cat([value_layer, torch.zeros(pad_size, device=value_layer.device)], dim=-1)
  464. context_layer = mra2_attention(
  465. query_layer.float(),
  466. key_layer.float(),
  467. value_layer.float(),
  468. attention_mask.float(),
  469. self.num_block,
  470. approx_mode=self.approx_mode,
  471. initial_prior_first_n_blocks=self.initial_prior_first_n_blocks,
  472. initial_prior_diagonal_n_blocks=self.initial_prior_diagonal_n_blocks,
  473. )
  474. if self.attention_head_size < gpu_warp_size:
  475. context_layer = context_layer[:, :, :, : self.attention_head_size]
  476. context_layer = context_layer.reshape(batch_size, self.num_attention_heads, seq_len, self.attention_head_size)
  477. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  478. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  479. context_layer = context_layer.view(*new_context_layer_shape)
  480. outputs = (context_layer,)
  481. return outputs
  482. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
  483. class MraSelfOutput(nn.Module):
  484. def __init__(self, config):
  485. super().__init__()
  486. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  487. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  488. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  489. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  490. hidden_states = self.dense(hidden_states)
  491. hidden_states = self.dropout(hidden_states)
  492. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  493. return hidden_states
  494. class MraAttention(nn.Module):
  495. def __init__(self, config, position_embedding_type=None):
  496. super().__init__()
  497. self.self = MraSelfAttention(config, position_embedding_type=position_embedding_type)
  498. self.output = MraSelfOutput(config)
  499. self.pruned_heads = set()
  500. def prune_heads(self, heads):
  501. if len(heads) == 0:
  502. return
  503. heads, index = find_pruneable_heads_and_indices(
  504. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  505. )
  506. # Prune linear layers
  507. self.self.query = prune_linear_layer(self.self.query, index)
  508. self.self.key = prune_linear_layer(self.self.key, index)
  509. self.self.value = prune_linear_layer(self.self.value, index)
  510. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  511. # Update hyper params and store pruned heads
  512. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  513. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  514. self.pruned_heads = self.pruned_heads.union(heads)
  515. def forward(self, hidden_states, attention_mask=None):
  516. self_outputs = self.self(hidden_states, attention_mask)
  517. attention_output = self.output(self_outputs[0], hidden_states)
  518. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  519. return outputs
  520. # Copied from transformers.models.bert.modeling_bert.BertIntermediate
  521. class MraIntermediate(nn.Module):
  522. def __init__(self, config):
  523. super().__init__()
  524. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  525. if isinstance(config.hidden_act, str):
  526. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  527. else:
  528. self.intermediate_act_fn = config.hidden_act
  529. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  530. hidden_states = self.dense(hidden_states)
  531. hidden_states = self.intermediate_act_fn(hidden_states)
  532. return hidden_states
  533. # Copied from transformers.models.bert.modeling_bert.BertOutput
  534. class MraOutput(nn.Module):
  535. def __init__(self, config):
  536. super().__init__()
  537. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  538. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  539. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  540. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  541. hidden_states = self.dense(hidden_states)
  542. hidden_states = self.dropout(hidden_states)
  543. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  544. return hidden_states
  545. class MraLayer(GradientCheckpointingLayer):
  546. def __init__(self, config):
  547. super().__init__()
  548. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  549. self.seq_len_dim = 1
  550. self.attention = MraAttention(config)
  551. self.add_cross_attention = config.add_cross_attention
  552. self.intermediate = MraIntermediate(config)
  553. self.output = MraOutput(config)
  554. def forward(self, hidden_states, attention_mask=None):
  555. self_attention_outputs = self.attention(hidden_states, attention_mask)
  556. attention_output = self_attention_outputs[0]
  557. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  558. layer_output = apply_chunking_to_forward(
  559. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  560. )
  561. outputs = (layer_output,) + outputs
  562. return outputs
  563. def feed_forward_chunk(self, attention_output):
  564. intermediate_output = self.intermediate(attention_output)
  565. layer_output = self.output(intermediate_output, attention_output)
  566. return layer_output
  567. class MraEncoder(nn.Module):
  568. def __init__(self, config):
  569. super().__init__()
  570. self.config = config
  571. self.layer = nn.ModuleList([MraLayer(config) for _ in range(config.num_hidden_layers)])
  572. self.gradient_checkpointing = False
  573. def forward(
  574. self,
  575. hidden_states,
  576. attention_mask=None,
  577. head_mask=None,
  578. output_hidden_states=False,
  579. return_dict=True,
  580. ):
  581. all_hidden_states = () if output_hidden_states else None
  582. for i, layer_module in enumerate(self.layer):
  583. if output_hidden_states:
  584. all_hidden_states = all_hidden_states + (hidden_states,)
  585. layer_outputs = layer_module(hidden_states, attention_mask)
  586. hidden_states = layer_outputs[0]
  587. if output_hidden_states:
  588. all_hidden_states = all_hidden_states + (hidden_states,)
  589. if not return_dict:
  590. return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
  591. return BaseModelOutputWithCrossAttentions(
  592. last_hidden_state=hidden_states,
  593. hidden_states=all_hidden_states,
  594. )
  595. # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform
  596. class MraPredictionHeadTransform(nn.Module):
  597. def __init__(self, config):
  598. super().__init__()
  599. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  600. if isinstance(config.hidden_act, str):
  601. self.transform_act_fn = ACT2FN[config.hidden_act]
  602. else:
  603. self.transform_act_fn = config.hidden_act
  604. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  605. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  606. hidden_states = self.dense(hidden_states)
  607. hidden_states = self.transform_act_fn(hidden_states)
  608. hidden_states = self.LayerNorm(hidden_states)
  609. return hidden_states
  610. # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Mra
  611. class MraLMPredictionHead(nn.Module):
  612. def __init__(self, config):
  613. super().__init__()
  614. self.transform = MraPredictionHeadTransform(config)
  615. # The output weights are the same as the input embeddings, but there is
  616. # an output-only bias for each token.
  617. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  618. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  619. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  620. self.decoder.bias = self.bias
  621. def _tie_weights(self):
  622. self.decoder.bias = self.bias
  623. def forward(self, hidden_states):
  624. hidden_states = self.transform(hidden_states)
  625. hidden_states = self.decoder(hidden_states)
  626. return hidden_states
  627. # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Mra
  628. class MraOnlyMLMHead(nn.Module):
  629. def __init__(self, config):
  630. super().__init__()
  631. self.predictions = MraLMPredictionHead(config)
  632. def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
  633. prediction_scores = self.predictions(sequence_output)
  634. return prediction_scores
  635. @auto_docstring
  636. # Copied from transformers.models.yoso.modeling_yoso.YosoPreTrainedModel with Yoso->Mra,yoso->mra
  637. class MraPreTrainedModel(PreTrainedModel):
  638. config: MraConfig
  639. base_model_prefix = "mra"
  640. supports_gradient_checkpointing = True
  641. def _init_weights(self, module: nn.Module):
  642. """Initialize the weights"""
  643. std = self.config.initializer_range
  644. if isinstance(module, nn.Linear):
  645. # Slightly different from the TF version which uses truncated_normal for initialization
  646. # cf https://github.com/pytorch/pytorch/pull/5617
  647. module.weight.data.normal_(mean=0.0, std=std)
  648. if module.bias is not None:
  649. module.bias.data.zero_()
  650. elif isinstance(module, nn.Embedding):
  651. module.weight.data.normal_(mean=0.0, std=std)
  652. if module.padding_idx is not None:
  653. module.weight.data[module.padding_idx].zero_()
  654. elif isinstance(module, nn.LayerNorm):
  655. module.bias.data.zero_()
  656. module.weight.data.fill_(1.0)
  657. elif isinstance(module, MraLMPredictionHead):
  658. module.bias.data.zero_()
  659. @auto_docstring
  660. class MraModel(MraPreTrainedModel):
  661. def __init__(self, config):
  662. super().__init__(config)
  663. self.config = config
  664. self.embeddings = MraEmbeddings(config)
  665. self.encoder = MraEncoder(config)
  666. # Initialize weights and apply final processing
  667. self.post_init()
  668. def get_input_embeddings(self):
  669. return self.embeddings.word_embeddings
  670. def set_input_embeddings(self, value):
  671. self.embeddings.word_embeddings = value
  672. def _prune_heads(self, heads_to_prune):
  673. """
  674. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  675. class PreTrainedModel
  676. """
  677. for layer, heads in heads_to_prune.items():
  678. self.encoder.layer[layer].attention.prune_heads(heads)
  679. @auto_docstring
  680. def forward(
  681. self,
  682. input_ids: Optional[torch.Tensor] = None,
  683. attention_mask: Optional[torch.Tensor] = None,
  684. token_type_ids: Optional[torch.Tensor] = None,
  685. position_ids: Optional[torch.Tensor] = None,
  686. head_mask: Optional[torch.Tensor] = None,
  687. inputs_embeds: Optional[torch.Tensor] = None,
  688. output_hidden_states: Optional[bool] = None,
  689. return_dict: Optional[bool] = None,
  690. ) -> Union[tuple, BaseModelOutputWithCrossAttentions]:
  691. output_hidden_states = (
  692. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  693. )
  694. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  695. if input_ids is not None and inputs_embeds is not None:
  696. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  697. elif input_ids is not None:
  698. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  699. input_shape = input_ids.size()
  700. elif inputs_embeds is not None:
  701. input_shape = inputs_embeds.size()[:-1]
  702. else:
  703. raise ValueError("You have to specify either input_ids or inputs_embeds")
  704. batch_size, seq_length = input_shape
  705. device = input_ids.device if input_ids is not None else inputs_embeds.device
  706. if attention_mask is None:
  707. attention_mask = torch.ones(((batch_size, seq_length)), device=device)
  708. if token_type_ids is None:
  709. if hasattr(self.embeddings, "token_type_ids"):
  710. buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
  711. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
  712. token_type_ids = buffered_token_type_ids_expanded
  713. else:
  714. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  715. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  716. # ourselves in which case we just need to make it broadcastable to all heads.
  717. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  718. # Prepare head mask if needed
  719. # 1.0 in head_mask indicate we keep the head
  720. # attention_probs has shape bsz x n_heads x N x N
  721. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  722. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  723. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  724. embedding_output = self.embeddings(
  725. input_ids=input_ids,
  726. position_ids=position_ids,
  727. token_type_ids=token_type_ids,
  728. inputs_embeds=inputs_embeds,
  729. )
  730. encoder_outputs = self.encoder(
  731. embedding_output,
  732. attention_mask=extended_attention_mask,
  733. head_mask=head_mask,
  734. output_hidden_states=output_hidden_states,
  735. return_dict=return_dict,
  736. )
  737. sequence_output = encoder_outputs[0]
  738. if not return_dict:
  739. return (sequence_output,) + encoder_outputs[1:]
  740. return BaseModelOutputWithCrossAttentions(
  741. last_hidden_state=sequence_output,
  742. hidden_states=encoder_outputs.hidden_states,
  743. attentions=encoder_outputs.attentions,
  744. cross_attentions=encoder_outputs.cross_attentions,
  745. )
  746. @auto_docstring
  747. class MraForMaskedLM(MraPreTrainedModel):
  748. _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
  749. def __init__(self, config):
  750. super().__init__(config)
  751. self.mra = MraModel(config)
  752. self.cls = MraOnlyMLMHead(config)
  753. # Initialize weights and apply final processing
  754. self.post_init()
  755. def get_output_embeddings(self):
  756. return self.cls.predictions.decoder
  757. def set_output_embeddings(self, new_embeddings):
  758. self.cls.predictions.decoder = new_embeddings
  759. self.cls.predictions.bias = new_embeddings.bias
  760. @auto_docstring
  761. def forward(
  762. self,
  763. input_ids: Optional[torch.Tensor] = None,
  764. attention_mask: Optional[torch.Tensor] = None,
  765. token_type_ids: Optional[torch.Tensor] = None,
  766. position_ids: Optional[torch.Tensor] = None,
  767. head_mask: Optional[torch.Tensor] = None,
  768. inputs_embeds: Optional[torch.Tensor] = None,
  769. labels: Optional[torch.Tensor] = None,
  770. output_hidden_states: Optional[bool] = None,
  771. return_dict: Optional[bool] = None,
  772. ) -> Union[tuple, MaskedLMOutput]:
  773. r"""
  774. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  775. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  776. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  777. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  778. """
  779. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  780. outputs = self.mra(
  781. input_ids,
  782. attention_mask=attention_mask,
  783. token_type_ids=token_type_ids,
  784. position_ids=position_ids,
  785. head_mask=head_mask,
  786. inputs_embeds=inputs_embeds,
  787. output_hidden_states=output_hidden_states,
  788. return_dict=return_dict,
  789. )
  790. sequence_output = outputs[0]
  791. prediction_scores = self.cls(sequence_output)
  792. masked_lm_loss = None
  793. if labels is not None:
  794. loss_fct = CrossEntropyLoss() # -100 index = padding token
  795. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  796. if not return_dict:
  797. output = (prediction_scores,) + outputs[1:]
  798. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  799. return MaskedLMOutput(
  800. loss=masked_lm_loss,
  801. logits=prediction_scores,
  802. hidden_states=outputs.hidden_states,
  803. attentions=outputs.attentions,
  804. )
  805. # Copied from transformers.models.yoso.modeling_yoso.YosoClassificationHead with Yoso->Mra
  806. class MraClassificationHead(nn.Module):
  807. """Head for sentence-level classification tasks."""
  808. def __init__(self, config):
  809. super().__init__()
  810. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  811. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  812. self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
  813. self.config = config
  814. def forward(self, features, **kwargs):
  815. x = features[:, 0, :] # take <s> token (equiv. to [CLS])
  816. x = self.dropout(x)
  817. x = self.dense(x)
  818. x = ACT2FN[self.config.hidden_act](x)
  819. x = self.dropout(x)
  820. x = self.out_proj(x)
  821. return x
  822. @auto_docstring(
  823. custom_intro="""
  824. MRA Model transformer with a sequence classification/regression head on top (a linear layer on top of
  825. the pooled output) e.g. for GLUE tasks.
  826. """
  827. )
  828. class MraForSequenceClassification(MraPreTrainedModel):
  829. def __init__(self, config):
  830. super().__init__(config)
  831. self.num_labels = config.num_labels
  832. self.mra = MraModel(config)
  833. self.classifier = MraClassificationHead(config)
  834. # Initialize weights and apply final processing
  835. self.post_init()
  836. @auto_docstring
  837. def forward(
  838. self,
  839. input_ids: Optional[torch.Tensor] = None,
  840. attention_mask: Optional[torch.Tensor] = None,
  841. token_type_ids: Optional[torch.Tensor] = None,
  842. position_ids: Optional[torch.Tensor] = None,
  843. head_mask: Optional[torch.Tensor] = None,
  844. inputs_embeds: Optional[torch.Tensor] = None,
  845. labels: Optional[torch.Tensor] = None,
  846. output_hidden_states: Optional[bool] = None,
  847. return_dict: Optional[bool] = None,
  848. ) -> Union[tuple, SequenceClassifierOutput]:
  849. r"""
  850. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  851. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  852. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  853. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  854. """
  855. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  856. outputs = self.mra(
  857. input_ids,
  858. attention_mask=attention_mask,
  859. token_type_ids=token_type_ids,
  860. position_ids=position_ids,
  861. head_mask=head_mask,
  862. inputs_embeds=inputs_embeds,
  863. output_hidden_states=output_hidden_states,
  864. return_dict=return_dict,
  865. )
  866. sequence_output = outputs[0]
  867. logits = self.classifier(sequence_output)
  868. loss = None
  869. if labels is not None:
  870. if self.config.problem_type is None:
  871. if self.num_labels == 1:
  872. self.config.problem_type = "regression"
  873. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  874. self.config.problem_type = "single_label_classification"
  875. else:
  876. self.config.problem_type = "multi_label_classification"
  877. if self.config.problem_type == "regression":
  878. loss_fct = MSELoss()
  879. if self.num_labels == 1:
  880. loss = loss_fct(logits.squeeze(), labels.squeeze())
  881. else:
  882. loss = loss_fct(logits, labels)
  883. elif self.config.problem_type == "single_label_classification":
  884. loss_fct = CrossEntropyLoss()
  885. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  886. elif self.config.problem_type == "multi_label_classification":
  887. loss_fct = BCEWithLogitsLoss()
  888. loss = loss_fct(logits, labels)
  889. if not return_dict:
  890. output = (logits,) + outputs[1:]
  891. return ((loss,) + output) if loss is not None else output
  892. return SequenceClassifierOutput(
  893. loss=loss,
  894. logits=logits,
  895. hidden_states=outputs.hidden_states,
  896. attentions=outputs.attentions,
  897. )
  898. @auto_docstring
  899. class MraForMultipleChoice(MraPreTrainedModel):
  900. def __init__(self, config):
  901. super().__init__(config)
  902. self.mra = MraModel(config)
  903. self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
  904. self.classifier = nn.Linear(config.hidden_size, 1)
  905. # Initialize weights and apply final processing
  906. self.post_init()
  907. @auto_docstring
  908. def forward(
  909. self,
  910. input_ids: Optional[torch.Tensor] = None,
  911. attention_mask: Optional[torch.Tensor] = None,
  912. token_type_ids: Optional[torch.Tensor] = None,
  913. position_ids: Optional[torch.Tensor] = None,
  914. head_mask: Optional[torch.Tensor] = None,
  915. inputs_embeds: Optional[torch.Tensor] = None,
  916. labels: Optional[torch.Tensor] = None,
  917. output_hidden_states: Optional[bool] = None,
  918. return_dict: Optional[bool] = None,
  919. ) -> Union[tuple, MultipleChoiceModelOutput]:
  920. r"""
  921. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  922. Indices of input sequence tokens in the vocabulary.
  923. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  924. [`PreTrainedTokenizer.__call__`] for details.
  925. [What are input IDs?](../glossary#input-ids)
  926. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  927. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  928. 1]`:
  929. - 0 corresponds to a *sentence A* token,
  930. - 1 corresponds to a *sentence B* token.
  931. [What are token type IDs?](../glossary#token-type-ids)
  932. position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  933. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  934. config.max_position_embeddings - 1]`.
  935. [What are position IDs?](../glossary#position-ids)
  936. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  937. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  938. is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
  939. model's internal embedding lookup matrix.
  940. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  941. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  942. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  943. `input_ids` above)
  944. """
  945. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  946. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  947. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  948. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  949. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  950. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  951. inputs_embeds = (
  952. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  953. if inputs_embeds is not None
  954. else None
  955. )
  956. outputs = self.mra(
  957. input_ids,
  958. attention_mask=attention_mask,
  959. token_type_ids=token_type_ids,
  960. position_ids=position_ids,
  961. head_mask=head_mask,
  962. inputs_embeds=inputs_embeds,
  963. output_hidden_states=output_hidden_states,
  964. return_dict=return_dict,
  965. )
  966. hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
  967. pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
  968. pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
  969. pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
  970. logits = self.classifier(pooled_output)
  971. reshaped_logits = logits.view(-1, num_choices)
  972. loss = None
  973. if labels is not None:
  974. loss_fct = CrossEntropyLoss()
  975. loss = loss_fct(reshaped_logits, labels)
  976. if not return_dict:
  977. output = (reshaped_logits,) + outputs[1:]
  978. return ((loss,) + output) if loss is not None else output
  979. return MultipleChoiceModelOutput(
  980. loss=loss,
  981. logits=reshaped_logits,
  982. hidden_states=outputs.hidden_states,
  983. attentions=outputs.attentions,
  984. )
  985. @auto_docstring
  986. class MraForTokenClassification(MraPreTrainedModel):
  987. def __init__(self, config):
  988. super().__init__(config)
  989. self.num_labels = config.num_labels
  990. self.mra = MraModel(config)
  991. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  992. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  993. # Initialize weights and apply final processing
  994. self.post_init()
  995. @auto_docstring
  996. def forward(
  997. self,
  998. input_ids: Optional[torch.Tensor] = None,
  999. attention_mask: Optional[torch.Tensor] = None,
  1000. token_type_ids: Optional[torch.Tensor] = None,
  1001. position_ids: Optional[torch.Tensor] = None,
  1002. head_mask: Optional[torch.Tensor] = None,
  1003. inputs_embeds: Optional[torch.Tensor] = None,
  1004. labels: Optional[torch.Tensor] = None,
  1005. output_hidden_states: Optional[bool] = None,
  1006. return_dict: Optional[bool] = None,
  1007. ) -> Union[tuple, TokenClassifierOutput]:
  1008. r"""
  1009. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1010. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1011. """
  1012. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1013. outputs = self.mra(
  1014. input_ids,
  1015. attention_mask=attention_mask,
  1016. token_type_ids=token_type_ids,
  1017. position_ids=position_ids,
  1018. head_mask=head_mask,
  1019. inputs_embeds=inputs_embeds,
  1020. output_hidden_states=output_hidden_states,
  1021. return_dict=return_dict,
  1022. )
  1023. sequence_output = outputs[0]
  1024. sequence_output = self.dropout(sequence_output)
  1025. logits = self.classifier(sequence_output)
  1026. loss = None
  1027. if labels is not None:
  1028. loss_fct = CrossEntropyLoss()
  1029. # Only keep active parts of the loss
  1030. if attention_mask is not None:
  1031. active_loss = attention_mask.view(-1) == 1
  1032. active_logits = logits.view(-1, self.num_labels)
  1033. active_labels = torch.where(
  1034. active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
  1035. )
  1036. loss = loss_fct(active_logits, active_labels)
  1037. else:
  1038. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1039. if not return_dict:
  1040. output = (logits,) + outputs[1:]
  1041. return ((loss,) + output) if loss is not None else output
  1042. return TokenClassifierOutput(
  1043. loss=loss,
  1044. logits=logits,
  1045. hidden_states=outputs.hidden_states,
  1046. attentions=outputs.attentions,
  1047. )
  1048. @auto_docstring
  1049. class MraForQuestionAnswering(MraPreTrainedModel):
  1050. def __init__(self, config):
  1051. super().__init__(config)
  1052. config.num_labels = 2
  1053. self.num_labels = config.num_labels
  1054. self.mra = MraModel(config)
  1055. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1056. # Initialize weights and apply final processing
  1057. self.post_init()
  1058. @auto_docstring
  1059. def forward(
  1060. self,
  1061. input_ids: Optional[torch.Tensor] = None,
  1062. attention_mask: Optional[torch.Tensor] = None,
  1063. token_type_ids: Optional[torch.Tensor] = None,
  1064. position_ids: Optional[torch.Tensor] = None,
  1065. head_mask: Optional[torch.Tensor] = None,
  1066. inputs_embeds: Optional[torch.Tensor] = None,
  1067. start_positions: Optional[torch.Tensor] = None,
  1068. end_positions: Optional[torch.Tensor] = None,
  1069. output_hidden_states: Optional[bool] = None,
  1070. return_dict: Optional[bool] = None,
  1071. ) -> Union[tuple, QuestionAnsweringModelOutput]:
  1072. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1073. outputs = self.mra(
  1074. input_ids,
  1075. attention_mask=attention_mask,
  1076. token_type_ids=token_type_ids,
  1077. position_ids=position_ids,
  1078. head_mask=head_mask,
  1079. inputs_embeds=inputs_embeds,
  1080. output_hidden_states=output_hidden_states,
  1081. return_dict=return_dict,
  1082. )
  1083. sequence_output = outputs[0]
  1084. logits = self.qa_outputs(sequence_output)
  1085. start_logits, end_logits = logits.split(1, dim=-1)
  1086. start_logits = start_logits.squeeze(-1)
  1087. end_logits = end_logits.squeeze(-1)
  1088. total_loss = None
  1089. if start_positions is not None and end_positions is not None:
  1090. # If we are on multi-GPU, split add a dimension
  1091. if len(start_positions.size()) > 1:
  1092. start_positions = start_positions.squeeze(-1)
  1093. if len(end_positions.size()) > 1:
  1094. end_positions = end_positions.squeeze(-1)
  1095. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1096. ignored_index = start_logits.size(1)
  1097. start_positions = start_positions.clamp(0, ignored_index)
  1098. end_positions = end_positions.clamp(0, ignored_index)
  1099. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1100. start_loss = loss_fct(start_logits, start_positions)
  1101. end_loss = loss_fct(end_logits, end_positions)
  1102. total_loss = (start_loss + end_loss) / 2
  1103. if not return_dict:
  1104. output = (start_logits, end_logits) + outputs[1:]
  1105. return ((total_loss,) + output) if total_loss is not None else output
  1106. return QuestionAnsweringModelOutput(
  1107. loss=total_loss,
  1108. start_logits=start_logits,
  1109. end_logits=end_logits,
  1110. hidden_states=outputs.hidden_states,
  1111. attentions=outputs.attentions,
  1112. )
  1113. __all__ = [
  1114. "MraForMaskedLM",
  1115. "MraForMultipleChoice",
  1116. "MraForQuestionAnswering",
  1117. "MraForSequenceClassification",
  1118. "MraForTokenClassification",
  1119. "MraLayer",
  1120. "MraModel",
  1121. "MraPreTrainedModel",
  1122. ]