modeling_canine.py 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. # coding=utf-8
  2. # Copyright 2021 Google AI 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 CANINE model."""
  16. import copy
  17. import math
  18. import os
  19. from dataclasses import dataclass
  20. from typing import Optional, Union
  21. import torch
  22. from torch import nn
  23. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  24. from ...activations import ACT2FN
  25. from ...modeling_layers import GradientCheckpointingLayer
  26. from ...modeling_outputs import (
  27. BaseModelOutput,
  28. ModelOutput,
  29. MultipleChoiceModelOutput,
  30. QuestionAnsweringModelOutput,
  31. SequenceClassifierOutput,
  32. TokenClassifierOutput,
  33. )
  34. from ...modeling_utils import PreTrainedModel
  35. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  36. from ...utils import auto_docstring, logging
  37. from .configuration_canine import CanineConfig
  38. logger = logging.get_logger(__name__)
  39. # Support up to 16 hash functions.
  40. _PRIMES = [31, 43, 59, 61, 73, 97, 103, 113, 137, 149, 157, 173, 181, 193, 211, 223]
  41. @dataclass
  42. @auto_docstring(
  43. custom_intro="""
  44. Output type of [`CanineModel`]. Based on [`~modeling_outputs.BaseModelOutputWithPooling`], but with slightly
  45. different `hidden_states` and `attentions`, as these also include the hidden states and attentions of the shallow
  46. Transformer encoders.
  47. """
  48. )
  49. class CanineModelOutputWithPooling(ModelOutput):
  50. r"""
  51. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  52. Sequence of hidden-states at the output of the last layer of the model (i.e. the output of the final
  53. shallow Transformer encoder).
  54. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
  55. Hidden-state of the first token of the sequence (classification token) at the last layer of the deep
  56. Transformer encoder, further processed by a Linear layer and a Tanh activation function. The Linear layer
  57. weights are trained from the next sentence prediction (classification) objective during pretraining.
  58. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  59. Tuple of `torch.FloatTensor` (one for the input to each encoder + one for the output of each layer of each
  60. encoder) of shape `(batch_size, sequence_length, hidden_size)` and `(batch_size, sequence_length //
  61. config.downsampling_rate, hidden_size)`. Hidden-states of the model at the output of each layer plus the
  62. initial input to each Transformer encoder. The hidden states of the shallow encoders have length
  63. `sequence_length`, but the hidden states of the deep encoder have length `sequence_length` //
  64. `config.downsampling_rate`.
  65. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  66. Tuple of `torch.FloatTensor` (one for each layer) of the 3 Transformer encoders of shape `(batch_size,
  67. num_heads, sequence_length, sequence_length)` and `(batch_size, num_heads, sequence_length //
  68. config.downsampling_rate, sequence_length // config.downsampling_rate)`. Attentions weights after the
  69. attention softmax, used to compute the weighted average in the self-attention heads.
  70. """
  71. last_hidden_state: Optional[torch.FloatTensor] = None
  72. pooler_output: Optional[torch.FloatTensor] = None
  73. hidden_states: Optional[tuple[torch.FloatTensor]] = None
  74. attentions: Optional[tuple[torch.FloatTensor]] = None
  75. def load_tf_weights_in_canine(model, config, tf_checkpoint_path):
  76. """Load tf checkpoints in a pytorch model."""
  77. try:
  78. import re
  79. import numpy as np
  80. import tensorflow as tf
  81. except ImportError:
  82. logger.error(
  83. "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
  84. "https://www.tensorflow.org/install/ for installation instructions."
  85. )
  86. raise
  87. tf_path = os.path.abspath(tf_checkpoint_path)
  88. logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
  89. # Load weights from TF model
  90. init_vars = tf.train.list_variables(tf_path)
  91. names = []
  92. arrays = []
  93. for name, shape in init_vars:
  94. logger.info(f"Loading TF weight {name} with shape {shape}")
  95. array = tf.train.load_variable(tf_path, name)
  96. names.append(name)
  97. arrays.append(array)
  98. for name, array in zip(names, arrays):
  99. name = name.split("/")
  100. # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
  101. # which are not required for using pretrained model
  102. # also discard the cls weights (which were used for the next sentence prediction pre-training task)
  103. if any(
  104. n
  105. in [
  106. "adam_v",
  107. "adam_m",
  108. "AdamWeightDecayOptimizer",
  109. "AdamWeightDecayOptimizer_1",
  110. "global_step",
  111. "cls",
  112. "autoregressive_decoder",
  113. "char_output_weights",
  114. ]
  115. for n in name
  116. ):
  117. logger.info(f"Skipping {'/'.join(name)}")
  118. continue
  119. # if first scope name starts with "bert", change it to "encoder"
  120. if name[0] == "bert":
  121. name[0] = "encoder"
  122. # remove "embeddings" middle name of HashBucketCodepointEmbedders
  123. elif name[1] == "embeddings":
  124. name.remove(name[1])
  125. # rename segment_embeddings to token_type_embeddings
  126. elif name[1] == "segment_embeddings":
  127. name[1] = "token_type_embeddings"
  128. # rename initial convolutional projection layer
  129. elif name[1] == "initial_char_encoder":
  130. name = ["chars_to_molecules"] + name[-2:]
  131. # rename final convolutional projection layer
  132. elif name[0] == "final_char_encoder" and name[1] in ["LayerNorm", "conv"]:
  133. name = ["projection"] + name[1:]
  134. pointer = model
  135. for m_name in name:
  136. if (re.fullmatch(r"[A-Za-z]+_\d+", m_name)) and "Embedder" not in m_name:
  137. scope_names = re.split(r"_(\d+)", m_name)
  138. else:
  139. scope_names = [m_name]
  140. if scope_names[0] == "kernel" or scope_names[0] == "gamma":
  141. pointer = getattr(pointer, "weight")
  142. elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
  143. pointer = getattr(pointer, "bias")
  144. elif scope_names[0] == "output_weights":
  145. pointer = getattr(pointer, "weight")
  146. else:
  147. try:
  148. pointer = getattr(pointer, scope_names[0])
  149. except AttributeError:
  150. logger.info(f"Skipping {'/'.join(name)}")
  151. continue
  152. if len(scope_names) >= 2:
  153. num = int(scope_names[1])
  154. pointer = pointer[num]
  155. if m_name[-11:] == "_embeddings":
  156. pointer = getattr(pointer, "weight")
  157. elif m_name[-10:] in [f"Embedder_{i}" for i in range(8)]:
  158. pointer = getattr(pointer, "weight")
  159. elif m_name == "kernel":
  160. array = np.transpose(array)
  161. if pointer.shape != array.shape:
  162. raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
  163. logger.info(f"Initialize PyTorch weight {name}")
  164. pointer.data = torch.from_numpy(array)
  165. return model
  166. class CanineEmbeddings(nn.Module):
  167. """Construct the character, position and token_type embeddings."""
  168. def __init__(self, config):
  169. super().__init__()
  170. self.config = config
  171. # character embeddings
  172. shard_embedding_size = config.hidden_size // config.num_hash_functions
  173. for i in range(config.num_hash_functions):
  174. name = f"HashBucketCodepointEmbedder_{i}"
  175. setattr(self, name, nn.Embedding(config.num_hash_buckets, shard_embedding_size))
  176. self.char_position_embeddings = nn.Embedding(config.num_hash_buckets, config.hidden_size)
  177. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  178. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  179. # any TensorFlow checkpoint file
  180. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  181. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  182. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  183. self.register_buffer(
  184. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  185. )
  186. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  187. def _hash_bucket_tensors(self, input_ids, num_hashes: int, num_buckets: int):
  188. """
  189. Converts ids to hash bucket ids via multiple hashing.
  190. Args:
  191. input_ids: The codepoints or other IDs to be hashed.
  192. num_hashes: The number of hash functions to use.
  193. num_buckets: The number of hash buckets (i.e. embeddings in each table).
  194. Returns:
  195. A list of tensors, each of which is the hash bucket IDs from one hash function.
  196. """
  197. if num_hashes > len(_PRIMES):
  198. raise ValueError(f"`num_hashes` must be <= {len(_PRIMES)}")
  199. primes = _PRIMES[:num_hashes]
  200. result_tensors = []
  201. for prime in primes:
  202. hashed = ((input_ids + 1) * prime) % num_buckets
  203. result_tensors.append(hashed)
  204. return result_tensors
  205. def _embed_hash_buckets(self, input_ids, embedding_size: int, num_hashes: int, num_buckets: int):
  206. """Converts IDs (e.g. codepoints) into embeddings via multiple hashing."""
  207. if embedding_size % num_hashes != 0:
  208. raise ValueError(f"Expected `embedding_size` ({embedding_size}) % `num_hashes` ({num_hashes}) == 0")
  209. hash_bucket_tensors = self._hash_bucket_tensors(input_ids, num_hashes=num_hashes, num_buckets=num_buckets)
  210. embedding_shards = []
  211. for i, hash_bucket_ids in enumerate(hash_bucket_tensors):
  212. name = f"HashBucketCodepointEmbedder_{i}"
  213. shard_embeddings = getattr(self, name)(hash_bucket_ids)
  214. embedding_shards.append(shard_embeddings)
  215. return torch.cat(embedding_shards, dim=-1)
  216. def forward(
  217. self,
  218. input_ids: Optional[torch.LongTensor] = None,
  219. token_type_ids: Optional[torch.LongTensor] = None,
  220. position_ids: Optional[torch.LongTensor] = None,
  221. inputs_embeds: Optional[torch.FloatTensor] = None,
  222. ) -> torch.FloatTensor:
  223. if input_ids is not None:
  224. input_shape = input_ids.size()
  225. else:
  226. input_shape = inputs_embeds.size()[:-1]
  227. seq_length = input_shape[1]
  228. if position_ids is None:
  229. position_ids = self.position_ids[:, :seq_length]
  230. if token_type_ids is None:
  231. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  232. if inputs_embeds is None:
  233. inputs_embeds = self._embed_hash_buckets(
  234. input_ids, self.config.hidden_size, self.config.num_hash_functions, self.config.num_hash_buckets
  235. )
  236. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  237. embeddings = inputs_embeds + token_type_embeddings
  238. if self.position_embedding_type == "absolute":
  239. position_embeddings = self.char_position_embeddings(position_ids)
  240. embeddings += position_embeddings
  241. embeddings = self.LayerNorm(embeddings)
  242. embeddings = self.dropout(embeddings)
  243. return embeddings
  244. class CharactersToMolecules(nn.Module):
  245. """Convert character sequence to initial molecule sequence (i.e. downsample) using strided convolutions."""
  246. def __init__(self, config):
  247. super().__init__()
  248. self.conv = nn.Conv1d(
  249. in_channels=config.hidden_size,
  250. out_channels=config.hidden_size,
  251. kernel_size=config.downsampling_rate,
  252. stride=config.downsampling_rate,
  253. )
  254. self.activation = ACT2FN[config.hidden_act]
  255. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  256. # any TensorFlow checkpoint file
  257. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  258. def forward(self, char_encoding: torch.Tensor) -> torch.Tensor:
  259. # `cls_encoding`: [batch, 1, hidden_size]
  260. cls_encoding = char_encoding[:, 0:1, :]
  261. # char_encoding has shape [batch, char_seq, hidden_size]
  262. # We transpose it to be [batch, hidden_size, char_seq]
  263. char_encoding = torch.transpose(char_encoding, 1, 2)
  264. downsampled = self.conv(char_encoding)
  265. downsampled = torch.transpose(downsampled, 1, 2)
  266. downsampled = self.activation(downsampled)
  267. # Truncate the last molecule in order to reserve a position for [CLS].
  268. # Often, the last position is never used (unless we completely fill the
  269. # text buffer). This is important in order to maintain alignment on TPUs
  270. # (i.e. a multiple of 128).
  271. downsampled_truncated = downsampled[:, 0:-1, :]
  272. # We also keep [CLS] as a separate sequence position since we always
  273. # want to reserve a position (and the model capacity that goes along
  274. # with that) in the deep BERT stack.
  275. # `result`: [batch, molecule_seq, molecule_dim]
  276. result = torch.cat([cls_encoding, downsampled_truncated], dim=1)
  277. result = self.LayerNorm(result)
  278. return result
  279. class ConvProjection(nn.Module):
  280. """
  281. Project representations from hidden_size*2 back to hidden_size across a window of w = config.upsampling_kernel_size
  282. characters.
  283. """
  284. def __init__(self, config):
  285. super().__init__()
  286. self.config = config
  287. self.conv = nn.Conv1d(
  288. in_channels=config.hidden_size * 2,
  289. out_channels=config.hidden_size,
  290. kernel_size=config.upsampling_kernel_size,
  291. stride=1,
  292. )
  293. self.activation = ACT2FN[config.hidden_act]
  294. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  295. # any TensorFlow checkpoint file
  296. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  297. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  298. def forward(
  299. self,
  300. inputs: torch.Tensor,
  301. final_seq_char_positions: Optional[torch.Tensor] = None,
  302. ) -> torch.Tensor:
  303. # inputs has shape [batch, mol_seq, molecule_hidden_size+char_hidden_final]
  304. # we transpose it to be [batch, molecule_hidden_size+char_hidden_final, mol_seq]
  305. inputs = torch.transpose(inputs, 1, 2)
  306. # PyTorch < 1.9 does not support padding="same" (which is used in the original implementation),
  307. # so we pad the tensor manually before passing it to the conv layer
  308. # based on https://github.com/google-research/big_transfer/blob/49afe42338b62af9fbe18f0258197a33ee578a6b/bit_tf2/models.py#L36-L38
  309. pad_total = self.config.upsampling_kernel_size - 1
  310. pad_beg = pad_total // 2
  311. pad_end = pad_total - pad_beg
  312. pad = nn.ConstantPad1d((pad_beg, pad_end), 0)
  313. # `result`: shape (batch_size, char_seq_len, hidden_size)
  314. result = self.conv(pad(inputs))
  315. result = torch.transpose(result, 1, 2)
  316. result = self.activation(result)
  317. result = self.LayerNorm(result)
  318. result = self.dropout(result)
  319. final_char_seq = result
  320. if final_seq_char_positions is not None:
  321. # Limit transformer query seq and attention mask to these character
  322. # positions to greatly reduce the compute cost. Typically, this is just
  323. # done for the MLM training task.
  324. # TODO add support for MLM
  325. raise NotImplementedError("CanineForMaskedLM is currently not supported")
  326. else:
  327. query_seq = final_char_seq
  328. return query_seq
  329. class CanineSelfAttention(nn.Module):
  330. def __init__(self, config):
  331. super().__init__()
  332. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  333. raise ValueError(
  334. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  335. f"heads ({config.num_attention_heads})"
  336. )
  337. self.num_attention_heads = config.num_attention_heads
  338. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  339. self.all_head_size = self.num_attention_heads * self.attention_head_size
  340. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  341. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  342. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  343. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  344. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  345. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  346. self.max_position_embeddings = config.max_position_embeddings
  347. self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
  348. def forward(
  349. self,
  350. from_tensor: torch.Tensor,
  351. to_tensor: torch.Tensor,
  352. attention_mask: Optional[torch.FloatTensor] = None,
  353. head_mask: Optional[torch.FloatTensor] = None,
  354. output_attentions: Optional[bool] = False,
  355. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  356. batch_size, seq_length, _ = from_tensor.shape
  357. # If this is instantiated as a cross-attention module, the keys
  358. # and values come from an encoder; the attention mask needs to be
  359. # such that the encoder's padding tokens are not attended to.
  360. key_layer = (
  361. self.key(to_tensor)
  362. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  363. .transpose(1, 2)
  364. )
  365. value_layer = (
  366. self.value(to_tensor)
  367. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  368. .transpose(1, 2)
  369. )
  370. query_layer = (
  371. self.query(from_tensor)
  372. .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
  373. .transpose(1, 2)
  374. )
  375. # Take the dot product between "query" and "key" to get the raw attention scores.
  376. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  377. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  378. seq_length = from_tensor.size()[1]
  379. position_ids_l = torch.arange(seq_length, dtype=torch.long, device=from_tensor.device).view(-1, 1)
  380. position_ids_r = torch.arange(seq_length, dtype=torch.long, device=from_tensor.device).view(1, -1)
  381. distance = position_ids_l - position_ids_r
  382. positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
  383. positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
  384. if self.position_embedding_type == "relative_key":
  385. relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  386. attention_scores = attention_scores + relative_position_scores
  387. elif self.position_embedding_type == "relative_key_query":
  388. relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  389. relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
  390. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  391. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  392. if attention_mask is not None:
  393. if attention_mask.ndim == 3:
  394. # if attention_mask is 3D, do the following:
  395. attention_mask = torch.unsqueeze(attention_mask, dim=1)
  396. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  397. # masked positions, this operation will create a tensor which is 0.0 for
  398. # positions we want to attend and the dtype's smallest value for masked positions.
  399. attention_mask = (1.0 - attention_mask.float()) * torch.finfo(attention_scores.dtype).min
  400. # Apply the attention mask (precomputed for all layers in CanineModel forward() function)
  401. attention_scores = attention_scores + attention_mask
  402. # Normalize the attention scores to probabilities.
  403. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  404. # This is actually dropping out entire tokens to attend to, which might
  405. # seem a bit unusual, but is taken from the original Transformer paper.
  406. attention_probs = self.dropout(attention_probs)
  407. # Mask heads if we want to
  408. if head_mask is not None:
  409. attention_probs = attention_probs * head_mask
  410. context_layer = torch.matmul(attention_probs, value_layer)
  411. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  412. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  413. context_layer = context_layer.view(*new_context_layer_shape)
  414. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  415. return outputs
  416. class CanineSelfOutput(nn.Module):
  417. def __init__(self, config):
  418. super().__init__()
  419. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  420. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  421. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  422. def forward(
  423. self, hidden_states: tuple[torch.FloatTensor], input_tensor: torch.FloatTensor
  424. ) -> tuple[torch.FloatTensor, torch.FloatTensor]:
  425. hidden_states = self.dense(hidden_states)
  426. hidden_states = self.dropout(hidden_states)
  427. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  428. return hidden_states
  429. class CanineAttention(nn.Module):
  430. """
  431. Additional arguments related to local attention:
  432. - **local** (`bool`, *optional*, defaults to `False`) -- Whether to apply local attention.
  433. - **always_attend_to_first_position** (`bool`, *optional*, defaults to `False`) -- Should all blocks be able to
  434. attend
  435. to the `to_tensor`'s first position (e.g. a [CLS] position)? - **first_position_attends_to_all** (`bool`,
  436. *optional*, defaults to `False`) -- Should the *from_tensor*'s first position be able to attend to all
  437. positions within the *from_tensor*? - **attend_from_chunk_width** (`int`, *optional*, defaults to 128) -- The
  438. width of each block-wise chunk in `from_tensor`. - **attend_from_chunk_stride** (`int`, *optional*, defaults to
  439. 128) -- The number of elements to skip when moving to the next block in `from_tensor`. -
  440. **attend_to_chunk_width** (`int`, *optional*, defaults to 128) -- The width of each block-wise chunk in
  441. *to_tensor*. - **attend_to_chunk_stride** (`int`, *optional*, defaults to 128) -- The number of elements to
  442. skip when moving to the next block in `to_tensor`.
  443. """
  444. def __init__(
  445. self,
  446. config,
  447. local=False,
  448. always_attend_to_first_position: bool = False,
  449. first_position_attends_to_all: bool = False,
  450. attend_from_chunk_width: int = 128,
  451. attend_from_chunk_stride: int = 128,
  452. attend_to_chunk_width: int = 128,
  453. attend_to_chunk_stride: int = 128,
  454. ):
  455. super().__init__()
  456. self.self = CanineSelfAttention(config)
  457. self.output = CanineSelfOutput(config)
  458. self.pruned_heads = set()
  459. # additional arguments related to local attention
  460. self.local = local
  461. if attend_from_chunk_width < attend_from_chunk_stride:
  462. raise ValueError(
  463. "`attend_from_chunk_width` < `attend_from_chunk_stride` would cause sequence positions to get skipped."
  464. )
  465. if attend_to_chunk_width < attend_to_chunk_stride:
  466. raise ValueError(
  467. "`attend_to_chunk_width` < `attend_to_chunk_stride`would cause sequence positions to get skipped."
  468. )
  469. self.always_attend_to_first_position = always_attend_to_first_position
  470. self.first_position_attends_to_all = first_position_attends_to_all
  471. self.attend_from_chunk_width = attend_from_chunk_width
  472. self.attend_from_chunk_stride = attend_from_chunk_stride
  473. self.attend_to_chunk_width = attend_to_chunk_width
  474. self.attend_to_chunk_stride = attend_to_chunk_stride
  475. def prune_heads(self, heads):
  476. if len(heads) == 0:
  477. return
  478. heads, index = find_pruneable_heads_and_indices(
  479. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  480. )
  481. # Prune linear layers
  482. self.self.query = prune_linear_layer(self.self.query, index)
  483. self.self.key = prune_linear_layer(self.self.key, index)
  484. self.self.value = prune_linear_layer(self.self.value, index)
  485. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  486. # Update hyper params and store pruned heads
  487. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  488. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  489. self.pruned_heads = self.pruned_heads.union(heads)
  490. def forward(
  491. self,
  492. hidden_states: tuple[torch.FloatTensor],
  493. attention_mask: Optional[torch.FloatTensor] = None,
  494. head_mask: Optional[torch.FloatTensor] = None,
  495. output_attentions: Optional[bool] = False,
  496. ) -> tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
  497. if not self.local:
  498. self_outputs = self.self(hidden_states, hidden_states, attention_mask, head_mask, output_attentions)
  499. attention_output = self_outputs[0]
  500. else:
  501. from_seq_length = to_seq_length = hidden_states.shape[1]
  502. from_tensor = to_tensor = hidden_states
  503. # Create chunks (windows) that we will attend *from* and then concatenate them.
  504. from_chunks = []
  505. if self.first_position_attends_to_all:
  506. from_chunks.append((0, 1))
  507. # We must skip this first position so that our output sequence is the
  508. # correct length (this matters in the *from* sequence only).
  509. from_start = 1
  510. else:
  511. from_start = 0
  512. for chunk_start in range(from_start, from_seq_length, self.attend_from_chunk_stride):
  513. chunk_end = min(from_seq_length, chunk_start + self.attend_from_chunk_width)
  514. from_chunks.append((chunk_start, chunk_end))
  515. # Determine the chunks (windows) that will attend *to*.
  516. to_chunks = []
  517. if self.first_position_attends_to_all:
  518. to_chunks.append((0, to_seq_length))
  519. for chunk_start in range(0, to_seq_length, self.attend_to_chunk_stride):
  520. chunk_end = min(to_seq_length, chunk_start + self.attend_to_chunk_width)
  521. to_chunks.append((chunk_start, chunk_end))
  522. if len(from_chunks) != len(to_chunks):
  523. raise ValueError(
  524. f"Expected to have same number of `from_chunks` ({from_chunks}) and "
  525. f"`to_chunks` ({from_chunks}). Check strides."
  526. )
  527. # next, compute attention scores for each pair of windows and concatenate
  528. attention_output_chunks = []
  529. attention_probs_chunks = []
  530. for (from_start, from_end), (to_start, to_end) in zip(from_chunks, to_chunks):
  531. from_tensor_chunk = from_tensor[:, from_start:from_end, :]
  532. to_tensor_chunk = to_tensor[:, to_start:to_end, :]
  533. # `attention_mask`: <float>[batch_size, from_seq, to_seq]
  534. # `attention_mask_chunk`: <float>[batch_size, from_seq_chunk, to_seq_chunk]
  535. attention_mask_chunk = attention_mask[:, from_start:from_end, to_start:to_end]
  536. if self.always_attend_to_first_position:
  537. cls_attention_mask = attention_mask[:, from_start:from_end, 0:1]
  538. attention_mask_chunk = torch.cat([cls_attention_mask, attention_mask_chunk], dim=2)
  539. cls_position = to_tensor[:, 0:1, :]
  540. to_tensor_chunk = torch.cat([cls_position, to_tensor_chunk], dim=1)
  541. attention_outputs_chunk = self.self(
  542. from_tensor_chunk, to_tensor_chunk, attention_mask_chunk, head_mask, output_attentions
  543. )
  544. attention_output_chunks.append(attention_outputs_chunk[0])
  545. if output_attentions:
  546. attention_probs_chunks.append(attention_outputs_chunk[1])
  547. attention_output = torch.cat(attention_output_chunks, dim=1)
  548. attention_output = self.output(attention_output, hidden_states)
  549. outputs = (attention_output,)
  550. if not self.local:
  551. outputs = outputs + self_outputs[1:] # add attentions if we output them
  552. else:
  553. outputs = outputs + tuple(attention_probs_chunks) # add attentions if we output them
  554. return outputs
  555. class CanineIntermediate(nn.Module):
  556. def __init__(self, config):
  557. super().__init__()
  558. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  559. if isinstance(config.hidden_act, str):
  560. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  561. else:
  562. self.intermediate_act_fn = config.hidden_act
  563. def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  564. hidden_states = self.dense(hidden_states)
  565. hidden_states = self.intermediate_act_fn(hidden_states)
  566. return hidden_states
  567. class CanineOutput(nn.Module):
  568. def __init__(self, config):
  569. super().__init__()
  570. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  571. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  572. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  573. def forward(self, hidden_states: tuple[torch.FloatTensor], input_tensor: torch.FloatTensor) -> torch.FloatTensor:
  574. hidden_states = self.dense(hidden_states)
  575. hidden_states = self.dropout(hidden_states)
  576. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  577. return hidden_states
  578. class CanineLayer(GradientCheckpointingLayer):
  579. def __init__(
  580. self,
  581. config,
  582. local,
  583. always_attend_to_first_position,
  584. first_position_attends_to_all,
  585. attend_from_chunk_width,
  586. attend_from_chunk_stride,
  587. attend_to_chunk_width,
  588. attend_to_chunk_stride,
  589. ):
  590. super().__init__()
  591. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  592. self.seq_len_dim = 1
  593. self.attention = CanineAttention(
  594. config,
  595. local,
  596. always_attend_to_first_position,
  597. first_position_attends_to_all,
  598. attend_from_chunk_width,
  599. attend_from_chunk_stride,
  600. attend_to_chunk_width,
  601. attend_to_chunk_stride,
  602. )
  603. self.intermediate = CanineIntermediate(config)
  604. self.output = CanineOutput(config)
  605. def forward(
  606. self,
  607. hidden_states: tuple[torch.FloatTensor],
  608. attention_mask: Optional[torch.FloatTensor] = None,
  609. head_mask: Optional[torch.FloatTensor] = None,
  610. output_attentions: Optional[bool] = False,
  611. ) -> tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
  612. self_attention_outputs = self.attention(
  613. hidden_states,
  614. attention_mask,
  615. head_mask,
  616. output_attentions=output_attentions,
  617. )
  618. attention_output = self_attention_outputs[0]
  619. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  620. layer_output = apply_chunking_to_forward(
  621. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  622. )
  623. outputs = (layer_output,) + outputs
  624. return outputs
  625. def feed_forward_chunk(self, attention_output):
  626. intermediate_output = self.intermediate(attention_output)
  627. layer_output = self.output(intermediate_output, attention_output)
  628. return layer_output
  629. class CanineEncoder(nn.Module):
  630. def __init__(
  631. self,
  632. config,
  633. local=False,
  634. always_attend_to_first_position=False,
  635. first_position_attends_to_all=False,
  636. attend_from_chunk_width=128,
  637. attend_from_chunk_stride=128,
  638. attend_to_chunk_width=128,
  639. attend_to_chunk_stride=128,
  640. ):
  641. super().__init__()
  642. self.config = config
  643. self.layer = nn.ModuleList(
  644. [
  645. CanineLayer(
  646. config,
  647. local,
  648. always_attend_to_first_position,
  649. first_position_attends_to_all,
  650. attend_from_chunk_width,
  651. attend_from_chunk_stride,
  652. attend_to_chunk_width,
  653. attend_to_chunk_stride,
  654. )
  655. for _ in range(config.num_hidden_layers)
  656. ]
  657. )
  658. self.gradient_checkpointing = False
  659. def forward(
  660. self,
  661. hidden_states: tuple[torch.FloatTensor],
  662. attention_mask: Optional[torch.FloatTensor] = None,
  663. head_mask: Optional[torch.FloatTensor] = None,
  664. output_attentions: Optional[bool] = False,
  665. output_hidden_states: Optional[bool] = False,
  666. return_dict: Optional[bool] = True,
  667. ) -> Union[tuple, BaseModelOutput]:
  668. all_hidden_states = () if output_hidden_states else None
  669. all_self_attentions = () if output_attentions else None
  670. for i, layer_module in enumerate(self.layer):
  671. if output_hidden_states:
  672. all_hidden_states = all_hidden_states + (hidden_states,)
  673. layer_head_mask = head_mask[i] if head_mask is not None else None
  674. layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
  675. hidden_states = layer_outputs[0]
  676. if output_attentions:
  677. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  678. if output_hidden_states:
  679. all_hidden_states = all_hidden_states + (hidden_states,)
  680. if not return_dict:
  681. return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
  682. return BaseModelOutput(
  683. last_hidden_state=hidden_states,
  684. hidden_states=all_hidden_states,
  685. attentions=all_self_attentions,
  686. )
  687. class CaninePooler(nn.Module):
  688. def __init__(self, config):
  689. super().__init__()
  690. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  691. self.activation = nn.Tanh()
  692. def forward(self, hidden_states: tuple[torch.FloatTensor]) -> torch.FloatTensor:
  693. # We "pool" the model by simply taking the hidden state corresponding
  694. # to the first token.
  695. first_token_tensor = hidden_states[:, 0]
  696. pooled_output = self.dense(first_token_tensor)
  697. pooled_output = self.activation(pooled_output)
  698. return pooled_output
  699. class CaninePredictionHeadTransform(nn.Module):
  700. def __init__(self, config):
  701. super().__init__()
  702. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  703. if isinstance(config.hidden_act, str):
  704. self.transform_act_fn = ACT2FN[config.hidden_act]
  705. else:
  706. self.transform_act_fn = config.hidden_act
  707. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  708. def forward(self, hidden_states: tuple[torch.FloatTensor]) -> torch.FloatTensor:
  709. hidden_states = self.dense(hidden_states)
  710. hidden_states = self.transform_act_fn(hidden_states)
  711. hidden_states = self.LayerNorm(hidden_states)
  712. return hidden_states
  713. class CanineLMPredictionHead(nn.Module):
  714. def __init__(self, config):
  715. super().__init__()
  716. self.transform = CaninePredictionHeadTransform(config)
  717. # The output weights are the same as the input embeddings, but there is
  718. # an output-only bias for each token.
  719. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  720. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  721. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  722. self.decoder.bias = self.bias
  723. def forward(self, hidden_states: tuple[torch.FloatTensor]) -> torch.FloatTensor:
  724. hidden_states = self.transform(hidden_states)
  725. hidden_states = self.decoder(hidden_states)
  726. return hidden_states
  727. class CanineOnlyMLMHead(nn.Module):
  728. def __init__(self, config):
  729. super().__init__()
  730. self.predictions = CanineLMPredictionHead(config)
  731. def forward(
  732. self,
  733. sequence_output: tuple[torch.Tensor],
  734. ) -> tuple[torch.Tensor]:
  735. prediction_scores = self.predictions(sequence_output)
  736. return prediction_scores
  737. @auto_docstring
  738. class CaninePreTrainedModel(PreTrainedModel):
  739. config: CanineConfig
  740. load_tf_weights = load_tf_weights_in_canine
  741. base_model_prefix = "canine"
  742. supports_gradient_checkpointing = True
  743. def _init_weights(self, module):
  744. """Initialize the weights"""
  745. if isinstance(module, (nn.Linear, nn.Conv1d)):
  746. # Slightly different from the TF version which uses truncated_normal for initialization
  747. # cf https://github.com/pytorch/pytorch/pull/5617
  748. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  749. if module.bias is not None:
  750. module.bias.data.zero_()
  751. elif isinstance(module, nn.Embedding):
  752. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  753. if module.padding_idx is not None:
  754. module.weight.data[module.padding_idx].zero_()
  755. elif isinstance(module, nn.LayerNorm):
  756. module.bias.data.zero_()
  757. module.weight.data.fill_(1.0)
  758. @auto_docstring
  759. class CanineModel(CaninePreTrainedModel):
  760. def __init__(self, config, add_pooling_layer=True):
  761. r"""
  762. add_pooling_layer (bool, *optional*, defaults to `True`):
  763. Whether to add a pooling layer
  764. """
  765. super().__init__(config)
  766. self.config = config
  767. shallow_config = copy.deepcopy(config)
  768. shallow_config.num_hidden_layers = 1
  769. self.char_embeddings = CanineEmbeddings(config)
  770. # shallow/low-dim transformer encoder to get a initial character encoding
  771. self.initial_char_encoder = CanineEncoder(
  772. shallow_config,
  773. local=True,
  774. always_attend_to_first_position=False,
  775. first_position_attends_to_all=False,
  776. attend_from_chunk_width=config.local_transformer_stride,
  777. attend_from_chunk_stride=config.local_transformer_stride,
  778. attend_to_chunk_width=config.local_transformer_stride,
  779. attend_to_chunk_stride=config.local_transformer_stride,
  780. )
  781. self.chars_to_molecules = CharactersToMolecules(config)
  782. # deep transformer encoder
  783. self.encoder = CanineEncoder(config)
  784. self.projection = ConvProjection(config)
  785. # shallow/low-dim transformer encoder to get a final character encoding
  786. self.final_char_encoder = CanineEncoder(shallow_config)
  787. self.pooler = CaninePooler(config) if add_pooling_layer else None
  788. # Initialize weights and apply final processing
  789. self.post_init()
  790. def _prune_heads(self, heads_to_prune):
  791. """
  792. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  793. class PreTrainedModel
  794. """
  795. for layer, heads in heads_to_prune.items():
  796. self.encoder.layer[layer].attention.prune_heads(heads)
  797. def _create_3d_attention_mask_from_input_mask(self, from_tensor, to_mask):
  798. """
  799. Create 3D attention mask from a 2D tensor mask.
  800. Args:
  801. from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
  802. to_mask: int32 Tensor of shape [batch_size, to_seq_length].
  803. Returns:
  804. float Tensor of shape [batch_size, from_seq_length, to_seq_length].
  805. """
  806. batch_size, from_seq_length = from_tensor.shape[0], from_tensor.shape[1]
  807. to_seq_length = to_mask.shape[1]
  808. to_mask = torch.reshape(to_mask, (batch_size, 1, to_seq_length)).float()
  809. # We don't assume that `from_tensor` is a mask (although it could be). We
  810. # don't actually care if we attend *from* padding tokens (only *to* padding)
  811. # tokens so we create a tensor of all ones.
  812. broadcast_ones = torch.ones(size=(batch_size, from_seq_length, 1), dtype=torch.float32, device=to_mask.device)
  813. # Here we broadcast along two dimensions to create the mask.
  814. mask = broadcast_ones * to_mask
  815. return mask
  816. def _downsample_attention_mask(self, char_attention_mask: torch.Tensor, downsampling_rate: int):
  817. """Downsample 2D character attention mask to 2D molecule attention mask using MaxPool1d layer."""
  818. # first, make char_attention_mask 3D by adding a channel dim
  819. batch_size, char_seq_len = char_attention_mask.shape
  820. poolable_char_mask = torch.reshape(char_attention_mask, (batch_size, 1, char_seq_len))
  821. # next, apply MaxPool1d to get pooled_molecule_mask of shape (batch_size, 1, mol_seq_len)
  822. pooled_molecule_mask = torch.nn.MaxPool1d(kernel_size=downsampling_rate, stride=downsampling_rate)(
  823. poolable_char_mask.float()
  824. )
  825. # finally, squeeze to get tensor of shape (batch_size, mol_seq_len)
  826. molecule_attention_mask = torch.squeeze(pooled_molecule_mask, dim=-1)
  827. return molecule_attention_mask
  828. def _repeat_molecules(self, molecules: torch.Tensor, char_seq_length: int) -> torch.Tensor:
  829. """Repeats molecules to make them the same length as the char sequence."""
  830. rate = self.config.downsampling_rate
  831. molecules_without_extra_cls = molecules[:, 1:, :]
  832. # `repeated`: [batch_size, almost_char_seq_len, molecule_hidden_size]
  833. repeated = torch.repeat_interleave(molecules_without_extra_cls, repeats=rate, dim=-2)
  834. # So far, we've repeated the elements sufficient for any `char_seq_length`
  835. # that's a multiple of `downsampling_rate`. Now we account for the last
  836. # n elements (n < `downsampling_rate`), i.e. the remainder of floor
  837. # division. We do this by repeating the last molecule a few extra times.
  838. last_molecule = molecules[:, -1:, :]
  839. remainder_length = char_seq_length % rate
  840. remainder_repeated = torch.repeat_interleave(
  841. last_molecule,
  842. # +1 molecule to compensate for truncation.
  843. repeats=remainder_length + rate,
  844. dim=-2,
  845. )
  846. # `repeated`: [batch_size, char_seq_len, molecule_hidden_size]
  847. return torch.cat([repeated, remainder_repeated], dim=-2)
  848. @auto_docstring
  849. def forward(
  850. self,
  851. input_ids: Optional[torch.LongTensor] = None,
  852. attention_mask: Optional[torch.FloatTensor] = None,
  853. token_type_ids: Optional[torch.LongTensor] = None,
  854. position_ids: Optional[torch.LongTensor] = None,
  855. head_mask: Optional[torch.FloatTensor] = None,
  856. inputs_embeds: Optional[torch.FloatTensor] = None,
  857. output_attentions: Optional[bool] = None,
  858. output_hidden_states: Optional[bool] = None,
  859. return_dict: Optional[bool] = None,
  860. ) -> Union[tuple, CanineModelOutputWithPooling]:
  861. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  862. output_hidden_states = (
  863. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  864. )
  865. all_hidden_states = () if output_hidden_states else None
  866. all_self_attentions = () if output_attentions else None
  867. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  868. if input_ids is not None and inputs_embeds is not None:
  869. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  870. elif input_ids is not None:
  871. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  872. input_shape = input_ids.size()
  873. elif inputs_embeds is not None:
  874. input_shape = inputs_embeds.size()[:-1]
  875. else:
  876. raise ValueError("You have to specify either input_ids or inputs_embeds")
  877. batch_size, seq_length = input_shape
  878. device = input_ids.device if input_ids is not None else inputs_embeds.device
  879. if attention_mask is None:
  880. attention_mask = torch.ones(((batch_size, seq_length)), device=device)
  881. if token_type_ids is None:
  882. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  883. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  884. # ourselves in which case we just need to make it broadcastable to all heads.
  885. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  886. molecule_attention_mask = self._downsample_attention_mask(
  887. attention_mask, downsampling_rate=self.config.downsampling_rate
  888. )
  889. extended_molecule_attention_mask: torch.Tensor = self.get_extended_attention_mask(
  890. molecule_attention_mask, (batch_size, molecule_attention_mask.shape[-1])
  891. )
  892. # Prepare head mask if needed
  893. # 1.0 in head_mask indicate we keep the head
  894. # attention_probs has shape bsz x n_heads x N x N
  895. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  896. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  897. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  898. # `input_char_embeddings`: shape (batch_size, char_seq, char_dim)
  899. input_char_embeddings = self.char_embeddings(
  900. input_ids=input_ids,
  901. position_ids=position_ids,
  902. token_type_ids=token_type_ids,
  903. inputs_embeds=inputs_embeds,
  904. )
  905. # Contextualize character embeddings using shallow Transformer.
  906. # We use a 3D attention mask for the local attention.
  907. # `input_char_encoding`: shape (batch_size, char_seq_len, char_dim)
  908. char_attention_mask = self._create_3d_attention_mask_from_input_mask(
  909. input_ids if input_ids is not None else inputs_embeds, attention_mask
  910. )
  911. init_chars_encoder_outputs = self.initial_char_encoder(
  912. input_char_embeddings,
  913. attention_mask=char_attention_mask,
  914. output_attentions=output_attentions,
  915. output_hidden_states=output_hidden_states,
  916. )
  917. input_char_encoding = init_chars_encoder_outputs.last_hidden_state
  918. # Downsample chars to molecules.
  919. # The following lines have dimensions: [batch, molecule_seq, molecule_dim].
  920. # In this transformation, we change the dimensionality from `char_dim` to
  921. # `molecule_dim`, but do *NOT* add a resnet connection. Instead, we rely on
  922. # the resnet connections (a) from the final char transformer stack back into
  923. # the original char transformer stack and (b) the resnet connections from
  924. # the final char transformer stack back into the deep BERT stack of
  925. # molecules.
  926. #
  927. # Empirically, it is critical to use a powerful enough transformation here:
  928. # mean pooling causes training to diverge with huge gradient norms in this
  929. # region of the model; using a convolution here resolves this issue. From
  930. # this, it seems that molecules and characters require a very different
  931. # feature space; intuitively, this makes sense.
  932. init_molecule_encoding = self.chars_to_molecules(input_char_encoding)
  933. # Deep BERT encoder
  934. # `molecule_sequence_output`: shape (batch_size, mol_seq_len, mol_dim)
  935. encoder_outputs = self.encoder(
  936. init_molecule_encoding,
  937. attention_mask=extended_molecule_attention_mask,
  938. head_mask=head_mask,
  939. output_attentions=output_attentions,
  940. output_hidden_states=output_hidden_states,
  941. return_dict=return_dict,
  942. )
  943. molecule_sequence_output = encoder_outputs[0]
  944. pooled_output = self.pooler(molecule_sequence_output) if self.pooler is not None else None
  945. # Upsample molecules back to characters.
  946. # `repeated_molecules`: shape (batch_size, char_seq_len, mol_hidden_size)
  947. repeated_molecules = self._repeat_molecules(molecule_sequence_output, char_seq_length=input_shape[-1])
  948. # Concatenate representations (contextualized char embeddings and repeated molecules):
  949. # `concat`: shape [batch_size, char_seq_len, molecule_hidden_size+char_hidden_final]
  950. concat = torch.cat([input_char_encoding, repeated_molecules], dim=-1)
  951. # Project representation dimension back to hidden_size
  952. # `sequence_output`: shape (batch_size, char_seq_len, hidden_size])
  953. sequence_output = self.projection(concat)
  954. # Apply final shallow Transformer
  955. # `sequence_output`: shape (batch_size, char_seq_len, hidden_size])
  956. final_chars_encoder_outputs = self.final_char_encoder(
  957. sequence_output,
  958. attention_mask=extended_attention_mask,
  959. output_attentions=output_attentions,
  960. output_hidden_states=output_hidden_states,
  961. )
  962. sequence_output = final_chars_encoder_outputs.last_hidden_state
  963. if output_hidden_states:
  964. deep_encoder_hidden_states = encoder_outputs.hidden_states if return_dict else encoder_outputs[1]
  965. all_hidden_states = (
  966. all_hidden_states
  967. + init_chars_encoder_outputs.hidden_states
  968. + deep_encoder_hidden_states
  969. + final_chars_encoder_outputs.hidden_states
  970. )
  971. if output_attentions:
  972. deep_encoder_self_attentions = encoder_outputs.attentions if return_dict else encoder_outputs[-1]
  973. all_self_attentions = (
  974. all_self_attentions
  975. + init_chars_encoder_outputs.attentions
  976. + deep_encoder_self_attentions
  977. + final_chars_encoder_outputs.attentions
  978. )
  979. if not return_dict:
  980. output = (sequence_output, pooled_output)
  981. output += tuple(v for v in [all_hidden_states, all_self_attentions] if v is not None)
  982. return output
  983. return CanineModelOutputWithPooling(
  984. last_hidden_state=sequence_output,
  985. pooler_output=pooled_output,
  986. hidden_states=all_hidden_states,
  987. attentions=all_self_attentions,
  988. )
  989. @auto_docstring(
  990. custom_intro="""
  991. CANINE Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
  992. output) e.g. for GLUE tasks.
  993. """
  994. )
  995. class CanineForSequenceClassification(CaninePreTrainedModel):
  996. def __init__(self, config):
  997. super().__init__(config)
  998. self.num_labels = config.num_labels
  999. self.canine = CanineModel(config)
  1000. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1001. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1002. # Initialize weights and apply final processing
  1003. self.post_init()
  1004. @auto_docstring
  1005. def forward(
  1006. self,
  1007. input_ids: Optional[torch.LongTensor] = None,
  1008. attention_mask: Optional[torch.FloatTensor] = None,
  1009. token_type_ids: Optional[torch.LongTensor] = None,
  1010. position_ids: Optional[torch.LongTensor] = None,
  1011. head_mask: Optional[torch.FloatTensor] = None,
  1012. inputs_embeds: Optional[torch.FloatTensor] = None,
  1013. labels: Optional[torch.LongTensor] = None,
  1014. output_attentions: Optional[bool] = None,
  1015. output_hidden_states: Optional[bool] = None,
  1016. return_dict: Optional[bool] = None,
  1017. ) -> Union[tuple, SequenceClassifierOutput]:
  1018. r"""
  1019. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1020. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1021. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1022. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1023. """
  1024. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1025. outputs = self.canine(
  1026. input_ids,
  1027. attention_mask=attention_mask,
  1028. token_type_ids=token_type_ids,
  1029. position_ids=position_ids,
  1030. head_mask=head_mask,
  1031. inputs_embeds=inputs_embeds,
  1032. output_attentions=output_attentions,
  1033. output_hidden_states=output_hidden_states,
  1034. return_dict=return_dict,
  1035. )
  1036. pooled_output = outputs[1]
  1037. pooled_output = self.dropout(pooled_output)
  1038. logits = self.classifier(pooled_output)
  1039. loss = None
  1040. if labels is not None:
  1041. if self.config.problem_type is None:
  1042. if self.num_labels == 1:
  1043. self.config.problem_type = "regression"
  1044. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  1045. self.config.problem_type = "single_label_classification"
  1046. else:
  1047. self.config.problem_type = "multi_label_classification"
  1048. if self.config.problem_type == "regression":
  1049. loss_fct = MSELoss()
  1050. if self.num_labels == 1:
  1051. loss = loss_fct(logits.squeeze(), labels.squeeze())
  1052. else:
  1053. loss = loss_fct(logits, labels)
  1054. elif self.config.problem_type == "single_label_classification":
  1055. loss_fct = CrossEntropyLoss()
  1056. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1057. elif self.config.problem_type == "multi_label_classification":
  1058. loss_fct = BCEWithLogitsLoss()
  1059. loss = loss_fct(logits, labels)
  1060. if not return_dict:
  1061. output = (logits,) + outputs[2:]
  1062. return ((loss,) + output) if loss is not None else output
  1063. return SequenceClassifierOutput(
  1064. loss=loss,
  1065. logits=logits,
  1066. hidden_states=outputs.hidden_states,
  1067. attentions=outputs.attentions,
  1068. )
  1069. @auto_docstring
  1070. class CanineForMultipleChoice(CaninePreTrainedModel):
  1071. def __init__(self, config):
  1072. super().__init__(config)
  1073. self.canine = CanineModel(config)
  1074. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1075. self.classifier = nn.Linear(config.hidden_size, 1)
  1076. # Initialize weights and apply final processing
  1077. self.post_init()
  1078. @auto_docstring
  1079. def forward(
  1080. self,
  1081. input_ids: Optional[torch.LongTensor] = None,
  1082. attention_mask: Optional[torch.FloatTensor] = None,
  1083. token_type_ids: Optional[torch.LongTensor] = None,
  1084. position_ids: Optional[torch.LongTensor] = None,
  1085. head_mask: Optional[torch.FloatTensor] = None,
  1086. inputs_embeds: Optional[torch.FloatTensor] = None,
  1087. labels: Optional[torch.LongTensor] = None,
  1088. output_attentions: Optional[bool] = None,
  1089. output_hidden_states: Optional[bool] = None,
  1090. return_dict: Optional[bool] = None,
  1091. ) -> Union[tuple, MultipleChoiceModelOutput]:
  1092. r"""
  1093. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  1094. Indices of input sequence tokens in the vocabulary.
  1095. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1096. [`PreTrainedTokenizer.__call__`] for details.
  1097. [What are input IDs?](../glossary#input-ids)
  1098. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1099. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1100. 1]`:
  1101. - 0 corresponds to a *sentence A* token,
  1102. - 1 corresponds to a *sentence B* token.
  1103. [What are token type IDs?](../glossary#token-type-ids)
  1104. position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1105. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  1106. config.max_position_embeddings - 1]`.
  1107. [What are position IDs?](../glossary#position-ids)
  1108. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  1109. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  1110. is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
  1111. model's internal embedding lookup matrix.
  1112. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1113. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1114. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  1115. `input_ids` above)
  1116. """
  1117. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1118. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1119. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1120. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1121. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  1122. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  1123. inputs_embeds = (
  1124. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1125. if inputs_embeds is not None
  1126. else None
  1127. )
  1128. outputs = self.canine(
  1129. input_ids,
  1130. attention_mask=attention_mask,
  1131. token_type_ids=token_type_ids,
  1132. position_ids=position_ids,
  1133. head_mask=head_mask,
  1134. inputs_embeds=inputs_embeds,
  1135. output_attentions=output_attentions,
  1136. output_hidden_states=output_hidden_states,
  1137. return_dict=return_dict,
  1138. )
  1139. pooled_output = outputs[1]
  1140. pooled_output = self.dropout(pooled_output)
  1141. logits = self.classifier(pooled_output)
  1142. reshaped_logits = logits.view(-1, num_choices)
  1143. loss = None
  1144. if labels is not None:
  1145. loss_fct = CrossEntropyLoss()
  1146. loss = loss_fct(reshaped_logits, labels)
  1147. if not return_dict:
  1148. output = (reshaped_logits,) + outputs[2:]
  1149. return ((loss,) + output) if loss is not None else output
  1150. return MultipleChoiceModelOutput(
  1151. loss=loss,
  1152. logits=reshaped_logits,
  1153. hidden_states=outputs.hidden_states,
  1154. attentions=outputs.attentions,
  1155. )
  1156. @auto_docstring
  1157. class CanineForTokenClassification(CaninePreTrainedModel):
  1158. def __init__(self, config):
  1159. super().__init__(config)
  1160. self.num_labels = config.num_labels
  1161. self.canine = CanineModel(config)
  1162. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1163. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1164. # Initialize weights and apply final processing
  1165. self.post_init()
  1166. @auto_docstring
  1167. def forward(
  1168. self,
  1169. input_ids: Optional[torch.LongTensor] = None,
  1170. attention_mask: Optional[torch.FloatTensor] = None,
  1171. token_type_ids: Optional[torch.LongTensor] = None,
  1172. position_ids: Optional[torch.LongTensor] = None,
  1173. head_mask: Optional[torch.FloatTensor] = None,
  1174. inputs_embeds: Optional[torch.FloatTensor] = None,
  1175. labels: Optional[torch.LongTensor] = None,
  1176. output_attentions: Optional[bool] = None,
  1177. output_hidden_states: Optional[bool] = None,
  1178. return_dict: Optional[bool] = None,
  1179. ) -> Union[tuple, TokenClassifierOutput]:
  1180. r"""
  1181. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1182. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1183. Example:
  1184. ```python
  1185. >>> from transformers import AutoTokenizer, CanineForTokenClassification
  1186. >>> import torch
  1187. >>> tokenizer = AutoTokenizer.from_pretrained("google/canine-s")
  1188. >>> model = CanineForTokenClassification.from_pretrained("google/canine-s")
  1189. >>> inputs = tokenizer(
  1190. ... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
  1191. ... )
  1192. >>> with torch.no_grad():
  1193. ... logits = model(**inputs).logits
  1194. >>> predicted_token_class_ids = logits.argmax(-1)
  1195. >>> # Note that tokens are classified rather then input words which means that
  1196. >>> # there might be more predicted token classes than words.
  1197. >>> # Multiple token classes might account for the same word
  1198. >>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
  1199. >>> predicted_tokens_classes # doctest: +SKIP
  1200. ```
  1201. ```python
  1202. >>> labels = predicted_token_class_ids
  1203. >>> loss = model(**inputs, labels=labels).loss
  1204. >>> round(loss.item(), 2) # doctest: +SKIP
  1205. ```"""
  1206. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1207. outputs = self.canine(
  1208. input_ids,
  1209. attention_mask=attention_mask,
  1210. token_type_ids=token_type_ids,
  1211. position_ids=position_ids,
  1212. head_mask=head_mask,
  1213. inputs_embeds=inputs_embeds,
  1214. output_attentions=output_attentions,
  1215. output_hidden_states=output_hidden_states,
  1216. return_dict=return_dict,
  1217. )
  1218. sequence_output = outputs[0]
  1219. sequence_output = self.dropout(sequence_output)
  1220. logits = self.classifier(sequence_output)
  1221. loss = None
  1222. if labels is not None:
  1223. loss_fct = CrossEntropyLoss()
  1224. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1225. if not return_dict:
  1226. output = (logits,) + outputs[2:]
  1227. return ((loss,) + output) if loss is not None else output
  1228. return TokenClassifierOutput(
  1229. loss=loss,
  1230. logits=logits,
  1231. hidden_states=outputs.hidden_states,
  1232. attentions=outputs.attentions,
  1233. )
  1234. @auto_docstring
  1235. class CanineForQuestionAnswering(CaninePreTrainedModel):
  1236. def __init__(self, config):
  1237. super().__init__(config)
  1238. self.num_labels = config.num_labels
  1239. self.canine = CanineModel(config)
  1240. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1241. # Initialize weights and apply final processing
  1242. self.post_init()
  1243. @auto_docstring
  1244. def forward(
  1245. self,
  1246. input_ids: Optional[torch.LongTensor] = None,
  1247. attention_mask: Optional[torch.FloatTensor] = None,
  1248. token_type_ids: Optional[torch.LongTensor] = None,
  1249. position_ids: Optional[torch.LongTensor] = None,
  1250. head_mask: Optional[torch.FloatTensor] = None,
  1251. inputs_embeds: Optional[torch.FloatTensor] = None,
  1252. start_positions: Optional[torch.LongTensor] = None,
  1253. end_positions: Optional[torch.LongTensor] = None,
  1254. output_attentions: Optional[bool] = None,
  1255. output_hidden_states: Optional[bool] = None,
  1256. return_dict: Optional[bool] = None,
  1257. ) -> Union[tuple, QuestionAnsweringModelOutput]:
  1258. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1259. outputs = self.canine(
  1260. input_ids,
  1261. attention_mask=attention_mask,
  1262. token_type_ids=token_type_ids,
  1263. position_ids=position_ids,
  1264. head_mask=head_mask,
  1265. inputs_embeds=inputs_embeds,
  1266. output_attentions=output_attentions,
  1267. output_hidden_states=output_hidden_states,
  1268. return_dict=return_dict,
  1269. )
  1270. sequence_output = outputs[0]
  1271. logits = self.qa_outputs(sequence_output)
  1272. start_logits, end_logits = logits.split(1, dim=-1)
  1273. start_logits = start_logits.squeeze(-1)
  1274. end_logits = end_logits.squeeze(-1)
  1275. total_loss = None
  1276. if start_positions is not None and end_positions is not None:
  1277. # If we are on multi-GPU, split add a dimension
  1278. if len(start_positions.size()) > 1:
  1279. start_positions = start_positions.squeeze(-1)
  1280. if len(end_positions.size()) > 1:
  1281. end_positions = end_positions.squeeze(-1)
  1282. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1283. ignored_index = start_logits.size(1)
  1284. start_positions.clamp_(0, ignored_index)
  1285. end_positions.clamp_(0, ignored_index)
  1286. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1287. start_loss = loss_fct(start_logits, start_positions)
  1288. end_loss = loss_fct(end_logits, end_positions)
  1289. total_loss = (start_loss + end_loss) / 2
  1290. if not return_dict:
  1291. output = (start_logits, end_logits) + outputs[2:]
  1292. return ((total_loss,) + output) if total_loss is not None else output
  1293. return QuestionAnsweringModelOutput(
  1294. loss=total_loss,
  1295. start_logits=start_logits,
  1296. end_logits=end_logits,
  1297. hidden_states=outputs.hidden_states,
  1298. attentions=outputs.attentions,
  1299. )
  1300. __all__ = [
  1301. "CanineForMultipleChoice",
  1302. "CanineForQuestionAnswering",
  1303. "CanineForSequenceClassification",
  1304. "CanineForTokenClassification",
  1305. "CanineLayer",
  1306. "CanineModel",
  1307. "CaninePreTrainedModel",
  1308. "load_tf_weights_in_canine",
  1309. ]