modeling_yoso.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. # Copyright 2022 University of Wisconsin-Madison and The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """PyTorch YOSO model."""
  15. import math
  16. import torch
  17. from torch import nn
  18. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  19. from ... import initialization as init
  20. from ...activations import ACT2FN
  21. from ...modeling_layers import GradientCheckpointingLayer
  22. from ...modeling_outputs import (
  23. BaseModelOutputWithCrossAttentions,
  24. MaskedLMOutput,
  25. MultipleChoiceModelOutput,
  26. QuestionAnsweringModelOutput,
  27. SequenceClassifierOutput,
  28. TokenClassifierOutput,
  29. )
  30. from ...modeling_utils import PreTrainedModel
  31. from ...pytorch_utils import apply_chunking_to_forward
  32. from ...utils import (
  33. auto_docstring,
  34. is_kernels_available,
  35. is_ninja_available,
  36. is_torch_cuda_available,
  37. logging,
  38. )
  39. from .configuration_yoso import YosoConfig
  40. logger = logging.get_logger(__name__)
  41. lsh_cumulation = None
  42. def load_cuda_kernels():
  43. global lsh_cumulation
  44. if not is_kernels_available():
  45. raise ImportError("kernels is not installed, please install it with `pip install kernels`")
  46. from ...integrations.hub_kernels import get_kernel
  47. yoso = get_kernel("kernels-community/yoso")
  48. lsh_cumulation = yoso.lsh_cumulation
  49. def to_contiguous(input_tensors):
  50. if isinstance(input_tensors, list):
  51. out = []
  52. for tensor in input_tensors:
  53. if not tensor.is_contiguous():
  54. tensor = tensor.contiguous()
  55. out.append(tensor)
  56. return out
  57. else:
  58. if not input_tensors.is_contiguous():
  59. input_tensors = input_tensors.contiguous()
  60. return input_tensors
  61. def normalize(input_tensors):
  62. if isinstance(input_tensors, list):
  63. out = []
  64. for tensor in input_tensors:
  65. out.append(nn.functional.normalize(tensor, p=2, dim=-1))
  66. return out
  67. else:
  68. return nn.functional.normalize(input_tensors, p=2, dim=-1)
  69. def hashing(query, key, num_hash, hash_len):
  70. if len(query.size()) != 3:
  71. raise ValueError("Query has incorrect size.")
  72. if len(key.size()) != 3:
  73. raise ValueError("Key has incorrect size.")
  74. rmat = torch.randn(query.size(0), query.size(2), num_hash * hash_len, device=query.device)
  75. raise_pow = 2 ** torch.arange(hash_len, device=query.device)
  76. query_projection = torch.matmul(query, rmat).reshape(query.size(0), query.size(1), num_hash, hash_len)
  77. key_projection = torch.matmul(key, rmat).reshape(key.size(0), key.size(1), num_hash, hash_len)
  78. query_binary = (query_projection > 0).int()
  79. key_binary = (key_projection > 0).int()
  80. query_hash = torch.sum(query_binary * raise_pow, dim=-1)
  81. query_hash = torch.sum(key_binary * raise_pow, dim=-1)
  82. return query_hash.int(), query_hash.int()
  83. class YosoCumulation(torch.autograd.Function):
  84. @staticmethod
  85. def forward(ctx, query_mask, key_mask, query, key, value, config):
  86. hash_code_len = config["hash_code_len"]
  87. expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
  88. expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
  89. cumulation_value = torch.matmul(expectation, value)
  90. ctx.save_for_backward(query_mask, key_mask, expectation, query, key, value)
  91. ctx.config = config
  92. return cumulation_value
  93. @staticmethod
  94. def backward(ctx, grad):
  95. grad = to_contiguous(grad)
  96. query_mask, key_mask, expectation, query, key, value = ctx.saved_tensors
  97. config = ctx.config
  98. hash_code_len = config["hash_code_len"]
  99. weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
  100. grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
  101. grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
  102. grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
  103. return None, None, grad_query, grad_key, grad_value, None
  104. class YosoLSHCumulation(torch.autograd.Function):
  105. @staticmethod
  106. def forward(ctx, query_mask, key_mask, query, key, value, config):
  107. if query_mask.size(0) != key_mask.size(0):
  108. raise ValueError("Query mask and Key mask differ in sizes in dimension 0")
  109. if query_mask.size(0) != query.size(0):
  110. raise ValueError("Query mask and Query differ in sizes in dimension 0")
  111. if query_mask.size(0) != key.size(0):
  112. raise ValueError("Query mask and Key differ in sizes in dimension 0")
  113. if query_mask.size(0) != value.size(0):
  114. raise ValueError("Query mask and Value mask differ in sizes in dimension 0")
  115. if key.size(1) != value.size(1):
  116. raise ValueError("Key and Value differ in sizes in dimension 1")
  117. if query.size(2) != key.size(2):
  118. raise ValueError("Query and Key differ in sizes in dimension 2")
  119. query_mask, key_mask, query, key, value = to_contiguous([query_mask, key_mask, query, key, value])
  120. use_cuda = query_mask.is_cuda
  121. num_hash = config["num_hash"]
  122. hash_code_len = config["hash_code_len"]
  123. hashtable_capacity = int(2**hash_code_len)
  124. if config["use_fast_hash"]:
  125. query_hash_code, key_hash_code = lsh_cumulation.fast_hash(
  126. query_mask, query, key_mask, key, num_hash, hash_code_len, use_cuda, 1
  127. )
  128. else:
  129. query_hash_code, key_hash_code = hashing(query, key, num_hash, hash_code_len)
  130. cumulation_value = lsh_cumulation.lsh_cumulation(
  131. query_mask, query_hash_code, key_mask, key_hash_code, value, hashtable_capacity, use_cuda, 1
  132. )
  133. ctx.save_for_backward(query_mask, key_mask, query_hash_code, key_hash_code, query, key, value)
  134. ctx.config = config
  135. return cumulation_value
  136. @staticmethod
  137. def backward(ctx, grad):
  138. grad = to_contiguous(grad)
  139. query_mask, key_mask, query_hash_code, key_hash_code, query, key, value = ctx.saved_tensors
  140. config = ctx.config
  141. use_cuda = grad.is_cuda
  142. hash_code_len = config["hash_code_len"]
  143. hashtable_capacity = int(2**hash_code_len)
  144. if config["lsh_backward"]:
  145. grad_value = lsh_cumulation.lsh_cumulation(
  146. key_mask, key_hash_code, query_mask, query_hash_code, grad, hashtable_capacity, use_cuda, 1
  147. )
  148. grad_query = lsh_cumulation.lsh_weighted_cumulation(
  149. query_mask,
  150. query_hash_code,
  151. grad,
  152. key_mask,
  153. key_hash_code,
  154. value,
  155. (hash_code_len / 2) * key,
  156. hashtable_capacity,
  157. use_cuda,
  158. 4,
  159. )
  160. grad_key = lsh_cumulation.lsh_weighted_cumulation(
  161. key_mask,
  162. key_hash_code,
  163. value,
  164. query_mask,
  165. query_hash_code,
  166. grad,
  167. (hash_code_len / 2) * query,
  168. hashtable_capacity,
  169. use_cuda,
  170. 4,
  171. )
  172. else:
  173. expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
  174. expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
  175. weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
  176. grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
  177. grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
  178. grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
  179. return None, None, grad_query, grad_key, grad_value, None
  180. # Copied from transformers.models.nystromformer.modeling_nystromformer.NystromformerEmbeddings
  181. class YosoEmbeddings(nn.Module):
  182. """Construct the embeddings from word, position and token_type embeddings."""
  183. def __init__(self, config):
  184. super().__init__()
  185. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  186. self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
  187. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  188. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  189. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  190. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  191. self.register_buffer(
  192. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2, persistent=False
  193. )
  194. self.register_buffer(
  195. "token_type_ids",
  196. torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
  197. persistent=False,
  198. )
  199. def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
  200. if input_ids is not None:
  201. input_shape = input_ids.size()
  202. else:
  203. input_shape = inputs_embeds.size()[:-1]
  204. seq_length = input_shape[1]
  205. if position_ids is None:
  206. position_ids = self.position_ids[:, :seq_length]
  207. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  208. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  209. # issue #5664
  210. if token_type_ids is None:
  211. if hasattr(self, "token_type_ids"):
  212. buffered_token_type_ids = self.token_type_ids[:, :seq_length]
  213. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
  214. token_type_ids = buffered_token_type_ids_expanded
  215. else:
  216. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  217. if inputs_embeds is None:
  218. inputs_embeds = self.word_embeddings(input_ids)
  219. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  220. embeddings = inputs_embeds + token_type_embeddings
  221. position_embeddings = self.position_embeddings(position_ids)
  222. embeddings += position_embeddings
  223. embeddings = self.LayerNorm(embeddings)
  224. embeddings = self.dropout(embeddings)
  225. return embeddings
  226. class YosoSelfAttention(nn.Module):
  227. def __init__(self, config):
  228. super().__init__()
  229. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  230. raise ValueError(
  231. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  232. f"heads ({config.num_attention_heads})"
  233. )
  234. kernel_loaded = lsh_cumulation is not None
  235. if is_torch_cuda_available() and is_ninja_available() and not kernel_loaded:
  236. try:
  237. load_cuda_kernels()
  238. except Exception as e:
  239. logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}")
  240. self.num_attention_heads = config.num_attention_heads
  241. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  242. self.all_head_size = self.num_attention_heads * self.attention_head_size
  243. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  244. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  245. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  246. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  247. self.use_expectation = config.use_expectation
  248. self.hash_code_len = config.hash_code_len
  249. self.use_conv = config.conv_window is not None
  250. self.use_fast_hash = config.use_fast_hash
  251. self.num_hash = config.num_hash
  252. self.lsh_backward = config.lsh_backward
  253. self.lsh_config = {
  254. "hash_code_len": self.hash_code_len,
  255. "use_fast_hash": self.use_fast_hash,
  256. "num_hash": self.num_hash,
  257. "lsh_backward": self.lsh_backward,
  258. }
  259. if config.conv_window is not None:
  260. self.conv = nn.Conv2d(
  261. in_channels=config.num_attention_heads,
  262. out_channels=config.num_attention_heads,
  263. kernel_size=(config.conv_window, 1),
  264. padding=(config.conv_window // 2, 0),
  265. bias=False,
  266. groups=config.num_attention_heads,
  267. )
  268. def forward(self, hidden_states, attention_mask=None, output_attentions=False):
  269. batch_size, seq_length, _ = hidden_states.shape
  270. query_layer = (
  271. self.query(hidden_states)
  272. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  273. .transpose(1, 2)
  274. )
  275. key_layer = (
  276. self.key(hidden_states)
  277. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  278. .transpose(1, 2)
  279. )
  280. value_layer = (
  281. self.value(hidden_states)
  282. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  283. .transpose(1, 2)
  284. )
  285. if self.use_conv:
  286. conv_value_layer = self.conv(value_layer * attention_mask[:, None, :, None])
  287. batch_size, num_heads, seq_len, head_dim = query_layer.size()
  288. query_layer = query_layer.reshape(batch_size * num_heads, seq_len, head_dim)
  289. key_layer = key_layer.reshape(batch_size * num_heads, seq_len, head_dim)
  290. value_layer = value_layer.reshape(batch_size * num_heads, seq_len, head_dim)
  291. attention_mask = 1.0 + attention_mask / 10000.0
  292. attention_mask = (
  293. attention_mask.unsqueeze(1)
  294. .repeat_interleave(num_heads, dim=1)
  295. .reshape(batch_size * num_heads, seq_len)
  296. .int()
  297. )
  298. # The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs
  299. # smaller than this are padded with zeros.
  300. gpu_warp_size = 32
  301. if (not self.use_expectation) and head_dim < gpu_warp_size:
  302. pad_size = batch_size * num_heads, seq_len, gpu_warp_size - head_dim
  303. query_layer = torch.cat(
  304. [
  305. query_layer,
  306. torch.zeros(pad_size, device=query_layer.device),
  307. ],
  308. dim=-1,
  309. )
  310. key_layer = torch.cat(
  311. [
  312. key_layer,
  313. torch.zeros(pad_size, device=key_layer.device),
  314. ],
  315. dim=-1,
  316. )
  317. value_layer = torch.cat(
  318. [
  319. value_layer,
  320. torch.zeros(pad_size, device=value_layer.device),
  321. ],
  322. dim=-1,
  323. )
  324. if self.use_expectation or self.training:
  325. query_layer, key_layer = normalize([query_layer, key_layer])
  326. if self.use_expectation:
  327. context_layer = YosoCumulation.apply(
  328. attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
  329. )
  330. else:
  331. context_layer = YosoLSHCumulation.apply(
  332. attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
  333. )
  334. if (not self.use_expectation) and head_dim < gpu_warp_size:
  335. context_layer = context_layer[:, :, :head_dim]
  336. context_layer = normalize(context_layer)
  337. context_layer = context_layer.reshape(batch_size, num_heads, seq_len, head_dim)
  338. if self.use_conv:
  339. context_layer += conv_value_layer
  340. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  341. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  342. context_layer = context_layer.view(*new_context_layer_shape)
  343. outputs = (context_layer, context_layer) if output_attentions else (context_layer,)
  344. return outputs
  345. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
  346. class YosoSelfOutput(nn.Module):
  347. def __init__(self, config):
  348. super().__init__()
  349. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  350. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  351. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  352. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  353. hidden_states = self.dense(hidden_states)
  354. hidden_states = self.dropout(hidden_states)
  355. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  356. return hidden_states
  357. class YosoAttention(nn.Module):
  358. def __init__(self, config):
  359. super().__init__()
  360. self.self = YosoSelfAttention(config)
  361. self.output = YosoSelfOutput(config)
  362. def forward(self, hidden_states, attention_mask=None, output_attentions=False):
  363. self_outputs = self.self(hidden_states, attention_mask, output_attentions)
  364. attention_output = self.output(self_outputs[0], hidden_states)
  365. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  366. return outputs
  367. # Copied from transformers.models.bert.modeling_bert.BertIntermediate
  368. class YosoIntermediate(nn.Module):
  369. def __init__(self, config):
  370. super().__init__()
  371. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  372. if isinstance(config.hidden_act, str):
  373. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  374. else:
  375. self.intermediate_act_fn = config.hidden_act
  376. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  377. hidden_states = self.dense(hidden_states)
  378. hidden_states = self.intermediate_act_fn(hidden_states)
  379. return hidden_states
  380. # Copied from transformers.models.bert.modeling_bert.BertOutput
  381. class YosoOutput(nn.Module):
  382. def __init__(self, config):
  383. super().__init__()
  384. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  385. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  386. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  387. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  388. hidden_states = self.dense(hidden_states)
  389. hidden_states = self.dropout(hidden_states)
  390. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  391. return hidden_states
  392. class YosoLayer(GradientCheckpointingLayer):
  393. def __init__(self, config):
  394. super().__init__()
  395. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  396. self.seq_len_dim = 1
  397. self.attention = YosoAttention(config)
  398. self.add_cross_attention = config.add_cross_attention
  399. self.intermediate = YosoIntermediate(config)
  400. self.output = YosoOutput(config)
  401. def forward(self, hidden_states, attention_mask=None, output_attentions=False):
  402. self_attention_outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
  403. attention_output = self_attention_outputs[0]
  404. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  405. layer_output = apply_chunking_to_forward(
  406. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  407. )
  408. outputs = (layer_output,) + outputs
  409. return outputs
  410. def feed_forward_chunk(self, attention_output):
  411. intermediate_output = self.intermediate(attention_output)
  412. layer_output = self.output(intermediate_output, attention_output)
  413. return layer_output
  414. class YosoEncoder(nn.Module):
  415. def __init__(self, config):
  416. super().__init__()
  417. self.config = config
  418. self.layer = nn.ModuleList([YosoLayer(config) for _ in range(config.num_hidden_layers)])
  419. self.gradient_checkpointing = False
  420. def forward(
  421. self,
  422. hidden_states,
  423. attention_mask=None,
  424. output_attentions=False,
  425. output_hidden_states=False,
  426. return_dict=True,
  427. ):
  428. all_hidden_states = () if output_hidden_states else None
  429. all_self_attentions = () if output_attentions else None
  430. for i, layer_module in enumerate(self.layer):
  431. if output_hidden_states:
  432. all_hidden_states = all_hidden_states + (hidden_states,)
  433. layer_outputs = layer_module(hidden_states, attention_mask, output_attentions)
  434. hidden_states = layer_outputs[0]
  435. if output_attentions:
  436. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  437. if output_hidden_states:
  438. all_hidden_states = all_hidden_states + (hidden_states,)
  439. if not return_dict:
  440. return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
  441. return BaseModelOutputWithCrossAttentions(
  442. last_hidden_state=hidden_states,
  443. hidden_states=all_hidden_states,
  444. attentions=all_self_attentions,
  445. )
  446. # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform
  447. class YosoPredictionHeadTransform(nn.Module):
  448. def __init__(self, config):
  449. super().__init__()
  450. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  451. if isinstance(config.hidden_act, str):
  452. self.transform_act_fn = ACT2FN[config.hidden_act]
  453. else:
  454. self.transform_act_fn = config.hidden_act
  455. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  456. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  457. hidden_states = self.dense(hidden_states)
  458. hidden_states = self.transform_act_fn(hidden_states)
  459. hidden_states = self.LayerNorm(hidden_states)
  460. return hidden_states
  461. # Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Yoso
  462. class YosoLMPredictionHead(nn.Module):
  463. def __init__(self, config):
  464. super().__init__()
  465. self.transform = YosoPredictionHeadTransform(config)
  466. # The output weights are the same as the input embeddings, but there is
  467. # an output-only bias for each token.
  468. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
  469. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  470. def forward(self, hidden_states):
  471. hidden_states = self.transform(hidden_states)
  472. hidden_states = self.decoder(hidden_states)
  473. return hidden_states
  474. # Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Yoso
  475. class YosoOnlyMLMHead(nn.Module):
  476. def __init__(self, config):
  477. super().__init__()
  478. self.predictions = YosoLMPredictionHead(config)
  479. def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
  480. prediction_scores = self.predictions(sequence_output)
  481. return prediction_scores
  482. @auto_docstring
  483. class YosoPreTrainedModel(PreTrainedModel):
  484. config: YosoConfig
  485. base_model_prefix = "yoso"
  486. supports_gradient_checkpointing = True
  487. @torch.no_grad()
  488. def _init_weights(self, module: nn.Module):
  489. """Initialize the weights"""
  490. super()._init_weights(module)
  491. if isinstance(module, YosoLMPredictionHead):
  492. init.zeros_(module.bias)
  493. elif isinstance(module, YosoEmbeddings):
  494. init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)) + 2)
  495. init.zeros_(module.token_type_ids)
  496. @auto_docstring
  497. class YosoModel(YosoPreTrainedModel):
  498. def __init__(self, config):
  499. super().__init__(config)
  500. self.config = config
  501. self.embeddings = YosoEmbeddings(config)
  502. self.encoder = YosoEncoder(config)
  503. # Initialize weights and apply final processing
  504. self.post_init()
  505. def get_input_embeddings(self):
  506. return self.embeddings.word_embeddings
  507. def set_input_embeddings(self, value):
  508. self.embeddings.word_embeddings = value
  509. @auto_docstring
  510. def forward(
  511. self,
  512. input_ids: torch.Tensor | None = None,
  513. attention_mask: torch.Tensor | None = None,
  514. token_type_ids: torch.Tensor | None = None,
  515. position_ids: torch.Tensor | None = None,
  516. inputs_embeds: torch.Tensor | None = None,
  517. output_attentions: bool | None = None,
  518. output_hidden_states: bool | None = None,
  519. return_dict: bool | None = None,
  520. **kwargs,
  521. ) -> tuple | BaseModelOutputWithCrossAttentions:
  522. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  523. output_hidden_states = (
  524. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  525. )
  526. return_dict = return_dict if return_dict is not None else self.config.return_dict
  527. if input_ids is not None and inputs_embeds is not None:
  528. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  529. elif input_ids is not None:
  530. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  531. input_shape = input_ids.size()
  532. elif inputs_embeds is not None:
  533. input_shape = inputs_embeds.size()[:-1]
  534. else:
  535. raise ValueError("You have to specify either input_ids or inputs_embeds")
  536. batch_size, seq_length = input_shape
  537. device = input_ids.device if input_ids is not None else inputs_embeds.device
  538. if attention_mask is None:
  539. attention_mask = torch.ones(((batch_size, seq_length)), device=device)
  540. if token_type_ids is None:
  541. if hasattr(self.embeddings, "token_type_ids"):
  542. buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
  543. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
  544. token_type_ids = buffered_token_type_ids_expanded
  545. else:
  546. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  547. embedding_output = self.embeddings(
  548. input_ids=input_ids,
  549. position_ids=position_ids,
  550. token_type_ids=token_type_ids,
  551. inputs_embeds=inputs_embeds,
  552. )
  553. encoder_outputs = self.encoder(
  554. embedding_output,
  555. attention_mask=attention_mask,
  556. output_attentions=output_attentions,
  557. output_hidden_states=output_hidden_states,
  558. return_dict=return_dict,
  559. )
  560. sequence_output = encoder_outputs[0]
  561. if not return_dict:
  562. return (sequence_output,) + encoder_outputs[1:]
  563. return BaseModelOutputWithCrossAttentions(
  564. last_hidden_state=sequence_output,
  565. hidden_states=encoder_outputs.hidden_states,
  566. attentions=encoder_outputs.attentions,
  567. cross_attentions=encoder_outputs.cross_attentions,
  568. )
  569. @auto_docstring
  570. class YosoForMaskedLM(YosoPreTrainedModel):
  571. _tied_weights_keys = {
  572. "cls.predictions.decoder.bias": "cls.predictions.bias",
  573. "cls.predictions.decoder.weight": "yoso.embeddings.word_embeddings.weight",
  574. }
  575. def __init__(self, config):
  576. super().__init__(config)
  577. self.yoso = YosoModel(config)
  578. self.cls = YosoOnlyMLMHead(config)
  579. # Initialize weights and apply final processing
  580. self.post_init()
  581. def get_output_embeddings(self):
  582. return self.cls.predictions.decoder
  583. def set_output_embeddings(self, new_embeddings):
  584. self.cls.predictions.decoder = new_embeddings
  585. self.cls.predictions.bias = new_embeddings.bias
  586. @auto_docstring
  587. def forward(
  588. self,
  589. input_ids: torch.Tensor | None = None,
  590. attention_mask: torch.Tensor | None = None,
  591. token_type_ids: torch.Tensor | None = None,
  592. position_ids: torch.Tensor | None = None,
  593. inputs_embeds: torch.Tensor | None = None,
  594. labels: torch.Tensor | None = None,
  595. output_attentions: bool | None = None,
  596. output_hidden_states: bool | None = None,
  597. return_dict: bool | None = None,
  598. **kwargs,
  599. ) -> tuple | MaskedLMOutput:
  600. r"""
  601. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  602. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  603. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  604. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  605. """
  606. return_dict = return_dict if return_dict is not None else self.config.return_dict
  607. outputs = self.yoso(
  608. input_ids,
  609. attention_mask=attention_mask,
  610. token_type_ids=token_type_ids,
  611. position_ids=position_ids,
  612. inputs_embeds=inputs_embeds,
  613. output_attentions=output_attentions,
  614. output_hidden_states=output_hidden_states,
  615. return_dict=return_dict,
  616. )
  617. sequence_output = outputs[0]
  618. prediction_scores = self.cls(sequence_output)
  619. masked_lm_loss = None
  620. if labels is not None:
  621. loss_fct = CrossEntropyLoss() # -100 index = padding token
  622. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  623. if not return_dict:
  624. output = (prediction_scores,) + outputs[1:]
  625. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  626. return MaskedLMOutput(
  627. loss=masked_lm_loss,
  628. logits=prediction_scores,
  629. hidden_states=outputs.hidden_states,
  630. attentions=outputs.attentions,
  631. )
  632. class YosoClassificationHead(nn.Module):
  633. """Head for sentence-level classification tasks."""
  634. def __init__(self, config):
  635. super().__init__()
  636. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  637. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  638. self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
  639. self.config = config
  640. def forward(self, features, **kwargs):
  641. x = features[:, 0, :] # take <s> token (equiv. to [CLS])
  642. x = self.dropout(x)
  643. x = self.dense(x)
  644. x = ACT2FN[self.config.hidden_act](x)
  645. x = self.dropout(x)
  646. x = self.out_proj(x)
  647. return x
  648. @auto_docstring(
  649. custom_intro="""
  650. YOSO Model transformer with a sequence classification/regression head on top (a linear layer on top of
  651. the pooled output) e.g. for GLUE tasks.
  652. """
  653. )
  654. class YosoForSequenceClassification(YosoPreTrainedModel):
  655. def __init__(self, config):
  656. super().__init__(config)
  657. self.num_labels = config.num_labels
  658. self.yoso = YosoModel(config)
  659. self.classifier = YosoClassificationHead(config)
  660. # Initialize weights and apply final processing
  661. self.post_init()
  662. @auto_docstring
  663. def forward(
  664. self,
  665. input_ids: torch.Tensor | None = None,
  666. attention_mask: torch.Tensor | None = None,
  667. token_type_ids: torch.Tensor | None = None,
  668. position_ids: torch.Tensor | None = None,
  669. inputs_embeds: torch.Tensor | None = None,
  670. labels: torch.Tensor | None = None,
  671. output_attentions: bool | None = None,
  672. output_hidden_states: bool | None = None,
  673. return_dict: bool | None = None,
  674. **kwargs,
  675. ) -> tuple | SequenceClassifierOutput:
  676. r"""
  677. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  678. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  679. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  680. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  681. """
  682. return_dict = return_dict if return_dict is not None else self.config.return_dict
  683. outputs = self.yoso(
  684. input_ids,
  685. attention_mask=attention_mask,
  686. token_type_ids=token_type_ids,
  687. position_ids=position_ids,
  688. inputs_embeds=inputs_embeds,
  689. output_attentions=output_attentions,
  690. output_hidden_states=output_hidden_states,
  691. return_dict=return_dict,
  692. )
  693. sequence_output = outputs[0]
  694. logits = self.classifier(sequence_output)
  695. loss = None
  696. if labels is not None:
  697. if self.config.problem_type is None:
  698. if self.num_labels == 1:
  699. self.config.problem_type = "regression"
  700. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  701. self.config.problem_type = "single_label_classification"
  702. else:
  703. self.config.problem_type = "multi_label_classification"
  704. if self.config.problem_type == "regression":
  705. loss_fct = MSELoss()
  706. if self.num_labels == 1:
  707. loss = loss_fct(logits.squeeze(), labels.squeeze())
  708. else:
  709. loss = loss_fct(logits, labels)
  710. elif self.config.problem_type == "single_label_classification":
  711. loss_fct = CrossEntropyLoss()
  712. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  713. elif self.config.problem_type == "multi_label_classification":
  714. loss_fct = BCEWithLogitsLoss()
  715. loss = loss_fct(logits, labels)
  716. if not return_dict:
  717. output = (logits,) + outputs[1:]
  718. return ((loss,) + output) if loss is not None else output
  719. return SequenceClassifierOutput(
  720. loss=loss,
  721. logits=logits,
  722. hidden_states=outputs.hidden_states,
  723. attentions=outputs.attentions,
  724. )
  725. @auto_docstring
  726. class YosoForMultipleChoice(YosoPreTrainedModel):
  727. def __init__(self, config):
  728. super().__init__(config)
  729. self.yoso = YosoModel(config)
  730. self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
  731. self.classifier = nn.Linear(config.hidden_size, 1)
  732. # Initialize weights and apply final processing
  733. self.post_init()
  734. @auto_docstring
  735. def forward(
  736. self,
  737. input_ids: torch.Tensor | None = None,
  738. attention_mask: torch.Tensor | None = None,
  739. token_type_ids: torch.Tensor | None = None,
  740. position_ids: torch.Tensor | None = None,
  741. inputs_embeds: torch.Tensor | None = None,
  742. labels: torch.Tensor | None = None,
  743. output_attentions: bool | None = None,
  744. output_hidden_states: bool | None = None,
  745. return_dict: bool | None = None,
  746. **kwargs,
  747. ) -> tuple | MultipleChoiceModelOutput:
  748. r"""
  749. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  750. Indices of input sequence tokens in the vocabulary.
  751. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  752. [`PreTrainedTokenizer.__call__`] for details.
  753. [What are input IDs?](../glossary#input-ids)
  754. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  755. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  756. 1]`:
  757. - 0 corresponds to a *sentence A* token,
  758. - 1 corresponds to a *sentence B* token.
  759. [What are token type IDs?](../glossary#token-type-ids)
  760. position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  761. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  762. config.max_position_embeddings - 1]`.
  763. [What are position IDs?](../glossary#position-ids)
  764. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  765. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  766. is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
  767. model's internal embedding lookup matrix.
  768. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  769. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  770. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  771. `input_ids` above)
  772. """
  773. return_dict = return_dict if return_dict is not None else self.config.return_dict
  774. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  775. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  776. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  777. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  778. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  779. inputs_embeds = (
  780. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  781. if inputs_embeds is not None
  782. else None
  783. )
  784. outputs = self.yoso(
  785. input_ids,
  786. attention_mask=attention_mask,
  787. token_type_ids=token_type_ids,
  788. position_ids=position_ids,
  789. inputs_embeds=inputs_embeds,
  790. output_attentions=output_attentions,
  791. output_hidden_states=output_hidden_states,
  792. return_dict=return_dict,
  793. )
  794. hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
  795. pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
  796. pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
  797. pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
  798. logits = self.classifier(pooled_output)
  799. reshaped_logits = logits.view(-1, num_choices)
  800. loss = None
  801. if labels is not None:
  802. loss_fct = CrossEntropyLoss()
  803. loss = loss_fct(reshaped_logits, labels)
  804. if not return_dict:
  805. output = (reshaped_logits,) + outputs[1:]
  806. return ((loss,) + output) if loss is not None else output
  807. return MultipleChoiceModelOutput(
  808. loss=loss,
  809. logits=reshaped_logits,
  810. hidden_states=outputs.hidden_states,
  811. attentions=outputs.attentions,
  812. )
  813. @auto_docstring
  814. class YosoForTokenClassification(YosoPreTrainedModel):
  815. def __init__(self, config):
  816. super().__init__(config)
  817. self.num_labels = config.num_labels
  818. self.yoso = YosoModel(config)
  819. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  820. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  821. # Initialize weights and apply final processing
  822. self.post_init()
  823. @auto_docstring
  824. def forward(
  825. self,
  826. input_ids: torch.Tensor | None = None,
  827. attention_mask: torch.Tensor | None = None,
  828. token_type_ids: torch.Tensor | None = None,
  829. position_ids: torch.Tensor | None = None,
  830. inputs_embeds: torch.Tensor | None = None,
  831. labels: torch.Tensor | None = None,
  832. output_attentions: bool | None = None,
  833. output_hidden_states: bool | None = None,
  834. return_dict: bool | None = None,
  835. **kwargs,
  836. ) -> tuple | TokenClassifierOutput:
  837. r"""
  838. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  839. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  840. """
  841. return_dict = return_dict if return_dict is not None else self.config.return_dict
  842. outputs = self.yoso(
  843. input_ids,
  844. attention_mask=attention_mask,
  845. token_type_ids=token_type_ids,
  846. position_ids=position_ids,
  847. inputs_embeds=inputs_embeds,
  848. output_attentions=output_attentions,
  849. output_hidden_states=output_hidden_states,
  850. return_dict=return_dict,
  851. )
  852. sequence_output = outputs[0]
  853. sequence_output = self.dropout(sequence_output)
  854. logits = self.classifier(sequence_output)
  855. loss = None
  856. if labels is not None:
  857. loss_fct = CrossEntropyLoss()
  858. # Only keep active parts of the loss
  859. if attention_mask is not None:
  860. active_loss = attention_mask.view(-1) == 1
  861. active_logits = logits.view(-1, self.num_labels)
  862. active_labels = torch.where(
  863. active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
  864. )
  865. loss = loss_fct(active_logits, active_labels)
  866. else:
  867. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  868. if not return_dict:
  869. output = (logits,) + outputs[1:]
  870. return ((loss,) + output) if loss is not None else output
  871. return TokenClassifierOutput(
  872. loss=loss,
  873. logits=logits,
  874. hidden_states=outputs.hidden_states,
  875. attentions=outputs.attentions,
  876. )
  877. @auto_docstring
  878. class YosoForQuestionAnswering(YosoPreTrainedModel):
  879. def __init__(self, config):
  880. super().__init__(config)
  881. config.num_labels = 2
  882. self.num_labels = config.num_labels
  883. self.yoso = YosoModel(config)
  884. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  885. # Initialize weights and apply final processing
  886. self.post_init()
  887. @auto_docstring
  888. def forward(
  889. self,
  890. input_ids: torch.Tensor | None = None,
  891. attention_mask: torch.Tensor | None = None,
  892. token_type_ids: torch.Tensor | None = None,
  893. position_ids: torch.Tensor | None = None,
  894. inputs_embeds: torch.Tensor | None = None,
  895. start_positions: torch.Tensor | None = None,
  896. end_positions: torch.Tensor | None = None,
  897. output_attentions: bool | None = None,
  898. output_hidden_states: bool | None = None,
  899. return_dict: bool | None = None,
  900. **kwargs,
  901. ) -> tuple | QuestionAnsweringModelOutput:
  902. return_dict = return_dict if return_dict is not None else self.config.return_dict
  903. outputs = self.yoso(
  904. input_ids,
  905. attention_mask=attention_mask,
  906. token_type_ids=token_type_ids,
  907. position_ids=position_ids,
  908. inputs_embeds=inputs_embeds,
  909. output_attentions=output_attentions,
  910. output_hidden_states=output_hidden_states,
  911. return_dict=return_dict,
  912. )
  913. sequence_output = outputs[0]
  914. logits = self.qa_outputs(sequence_output)
  915. start_logits, end_logits = logits.split(1, dim=-1)
  916. start_logits = start_logits.squeeze(-1)
  917. end_logits = end_logits.squeeze(-1)
  918. total_loss = None
  919. if start_positions is not None and end_positions is not None:
  920. # If we are on multi-GPU, split add a dimension
  921. if len(start_positions.size()) > 1:
  922. start_positions = start_positions.squeeze(-1)
  923. if len(end_positions.size()) > 1:
  924. end_positions = end_positions.squeeze(-1)
  925. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  926. ignored_index = start_logits.size(1)
  927. start_positions = start_positions.clamp(0, ignored_index)
  928. end_positions = end_positions.clamp(0, ignored_index)
  929. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  930. start_loss = loss_fct(start_logits, start_positions)
  931. end_loss = loss_fct(end_logits, end_positions)
  932. total_loss = (start_loss + end_loss) / 2
  933. if not return_dict:
  934. output = (start_logits, end_logits) + outputs[1:]
  935. return ((total_loss,) + output) if total_loss is not None else output
  936. return QuestionAnsweringModelOutput(
  937. loss=total_loss,
  938. start_logits=start_logits,
  939. end_logits=end_logits,
  940. hidden_states=outputs.hidden_states,
  941. attentions=outputs.attentions,
  942. )
  943. __all__ = [
  944. "YosoForMaskedLM",
  945. "YosoForMultipleChoice",
  946. "YosoForQuestionAnswering",
  947. "YosoForSequenceClassification",
  948. "YosoForTokenClassification",
  949. "YosoLayer",
  950. "YosoModel",
  951. "YosoPreTrainedModel",
  952. ]