Advertisement
Guest User

Untitled

a guest
Mar 13th, 2023
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 48.95 KB | Source Code | 0 0
  1. # coding=utf-8
  2. # Copyright 2021 The EleutherAI and HuggingFace Teams. 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 GPT-J model."""
  16.  
  17. import warnings
  18. from typing import Optional, Tuple, Union
  19.  
  20. import torch
  21. import torch.utils.checkpoint
  22. from torch import nn
  23. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  24.  
  25. from ...activations import ACT2FN
  26. from ...modeling_outputs import (
  27. BaseModelOutputWithPast,
  28. CausalLMOutputWithPast,
  29. QuestionAnsweringModelOutput,
  30. SequenceClassifierOutputWithPast,
  31. )
  32. from ...modeling_utils import PreTrainedModel
  33. from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
  34. from ...utils.model_parallel_utils import assert_device_map, get_device_map
  35. from .configuration_gptj import GPTJConfig
  36.  
  37.  
  38. logger = logging.get_logger(__name__)
  39.  
  40. _CHECKPOINT_FOR_DOC = "hf-internal-testing/tiny-random-gptj"
  41. _REAL_CHECKPOINT_FOR_DOC = "EleutherAI/gpt-j-6B"
  42. _CONFIG_FOR_DOC = "GPTJConfig"
  43.  
  44.  
  45. GPTJ_PRETRAINED_MODEL_ARCHIVE_LIST = [
  46. "EleutherAI/gpt-j-6B",
  47. # See all GPT-J models at https://huggingface.co/models?filter=gptj
  48. ]
  49.  
  50.  
  51. def create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
  52. inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
  53. sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=torch.float), inv_freq).float()
  54. return torch.concat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
  55.  
  56.  
  57. def rotate_every_two(x: torch.Tensor) -> torch.Tensor:
  58. x1 = x[:, :, :, ::2]
  59. x2 = x[:, :, :, 1::2]
  60. x = torch.stack((-x2, x1), dim=-1)
  61. return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
  62.  
  63.  
  64. def apply_rotary_pos_emb(tensor: torch.Tensor, sincos: torch.Tensor) -> torch.Tensor:
  65. sin = sincos[0].repeat_interleave(2, dim=-1)[:, :, None, :]
  66. cos = sincos[1].repeat_interleave(2, dim=-1)[:, :, None, :]
  67. return (tensor * cos) + (rotate_every_two(tensor) * sin)
  68.  
  69.  
  70. class GPTJAttention(nn.Module):
  71. def __init__(self, config):
  72. super().__init__()
  73.  
  74. max_positions = config.max_position_embeddings
  75. self.register_buffer(
  76. "bias",
  77. torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
  78. 1, 1, max_positions, max_positions
  79. ),
  80. )
  81. self.register_buffer("masked_bias", torch.tensor(-1e9))
  82.  
  83. self.attn_dropout = nn.Dropout(config.attn_pdrop)
  84. self.resid_dropout = nn.Dropout(config.resid_pdrop)
  85.  
  86. self.embed_dim = config.hidden_size
  87. self.num_attention_heads = config.num_attention_heads
  88. self.head_dim = self.embed_dim // self.num_attention_heads
  89. if self.head_dim * self.num_attention_heads != self.embed_dim:
  90. raise ValueError(
  91. f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and"
  92. f" `num_attention_heads`: {self.num_attention_heads})."
  93. )
  94. self.scale_attn = torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype())
  95.  
  96. self.k_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
  97. self.v_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
  98. self.q_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
  99. self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
  100. self.rotary_dim = config.rotary_dim
  101. pos_embd_dim = self.rotary_dim or self.embed_dim
  102. self.embed_positions = create_sinusoidal_positions(max_positions, pos_embd_dim)
  103.  
  104. def _split_heads(self, tensor, num_attention_heads, attn_head_size, rotary):
  105. """
  106. Splits hidden dim into attn_head_size and num_attention_heads
  107. """
  108. new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
  109. tensor = tensor.view(new_shape)
  110. if rotary:
  111. return tensor
  112.  
  113. # if tensor.dim() == 5, flattens the first two dims, permutes, then inflates back the first two dims
  114. original_shape = tensor.size()
  115. tensor = tensor.view((-1,) + original_shape[-3:])
  116. tensor = tensor.permute(0, 2, 1, 3)
  117. tensor = tensor.view(original_shape[:-3] + tensor.size()[-3:])
  118. return tensor
  119.  
  120. def _merge_heads(self, tensor, num_attention_heads, attn_head_size):
  121. """
  122. Merges attn_head_size dim and num_attn_heads dim into hidden dim
  123. """
  124. # if tensor.dim() == 5, flattens the first two dims, permutes, then inflates back the first two dims
  125. original_shape = tensor.size()
  126. tensor = tensor.view((-1,) + original_shape[-3:])
  127. tensor = tensor.permute(0, 2, 1, 3)
  128. tensor = tensor.view(original_shape[:-3] + tensor.size()[-3:])
  129.  
  130. new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
  131. return tensor.reshape(new_shape)
  132.  
  133. def _attn(
  134. self,
  135. query,
  136. key,
  137. value,
  138. attention_mask=None,
  139. head_mask=None,
  140. ):
  141. # compute causal mask from causal mask buffer
  142. query_length, key_length = query.size(-2), key.size(-2)
  143. causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
  144.  
  145. # Keep the attention weights computation in fp32 to avoid overflow issues
  146. query = query.to(torch.float32)
  147. key = key.to(torch.float32)
  148.  
  149. attn_weights = torch.matmul(query, key.transpose(-1, -2))
  150.  
  151. mask_value = torch.finfo(attn_weights.dtype).min
  152. # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
  153. # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
  154. mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
  155. attn_weights = torch.where(causal_mask, attn_weights, mask_value)
  156.  
  157. attn_weights = attn_weights / self.scale_attn
  158.  
  159. if attention_mask is not None:
  160. # Apply the attention mask
  161. attn_weights = attn_weights + attention_mask
  162.  
  163. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  164. attn_weights = attn_weights.to(value.dtype)
  165. attn_weights = self.attn_dropout(attn_weights)
  166.  
  167. # Mask heads if we want to
  168. if head_mask is not None:
  169. attn_weights = attn_weights * head_mask
  170.  
  171. attn_output = torch.matmul(attn_weights, value)
  172.  
  173. return attn_output, attn_weights
  174.  
  175. def forward(
  176. self,
  177. hidden_states: Optional[torch.FloatTensor],
  178. layer_past: Optional[Tuple[torch.Tensor]] = None,
  179. attention_mask: Optional[torch.FloatTensor] = None,
  180. position_ids: Optional[torch.LongTensor] = None,
  181. head_mask: Optional[torch.FloatTensor] = None,
  182. use_cache: Optional[bool] = False,
  183. output_attentions: Optional[bool] = False,
  184. ) -> Union[
  185. Tuple[torch.Tensor, Tuple[torch.Tensor]],
  186. Optional[Tuple[torch.Tensor, Tuple[torch.Tensor], Tuple[torch.Tensor, ...]]],
  187. ]:
  188. query = self.q_proj(hidden_states)
  189. key = self.k_proj(hidden_states)
  190. value = self.v_proj(hidden_states)
  191.  
  192. query = self._split_heads(query, self.num_attention_heads, self.head_dim, True)
  193. key = self._split_heads(key, self.num_attention_heads, self.head_dim, True)
  194. value = self._split_heads(value, self.num_attention_heads, self.head_dim, False)
  195.  
  196. embed_positions = self.embed_positions
  197. if embed_positions.device != position_ids.device:
  198. embed_positions = embed_positions.to(position_ids.device)
  199. self.embed_positions = embed_positions
  200.  
  201. sincos = embed_positions[position_ids]
  202. sincos = sincos.chunk(2, dim=-1)
  203. sincos = [sincos[0].contiguous(), sincos[1].contiguous()]
  204.  
  205. if self.rotary_dim is not None:
  206. k_rot = key[:, :, :, : self.rotary_dim]
  207. k_pass = key[:, :, :, self.rotary_dim :]
  208.  
  209. q_rot = query[:, :, :, : self.rotary_dim]
  210. q_pass = query[:, :, :, self.rotary_dim :]
  211.  
  212. k_rot = apply_rotary_pos_emb(k_rot, sincos)
  213. q_rot = apply_rotary_pos_emb(q_rot, sincos)
  214.  
  215. key = torch.cat([k_rot, k_pass], dim=-1)
  216. query = torch.cat([q_rot, q_pass], dim=-1)
  217. else:
  218. key = apply_rotary_pos_emb(key, sincos)
  219. query = apply_rotary_pos_emb(query, sincos)
  220.  
  221. key = key.permute(0, 2, 1, 3)
  222. query = query.permute(0, 2, 1, 3)
  223.  
  224. if layer_past is not None:
  225. past_key = layer_past[0]
  226. past_value = layer_past[1]
  227. key = torch.cat((past_key, key), dim=-2)
  228. value = torch.cat((past_value, value), dim=-2)
  229.  
  230. if use_cache is True:
  231. present = (key, value)
  232. else:
  233. present = None
  234.  
  235. # compute self-attention: V x Softmax(QK^T)
  236. attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
  237.  
  238. attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_dim)
  239. attn_output = self.out_proj(attn_output)
  240. attn_output = self.resid_dropout(attn_output)
  241.  
  242. outputs = (attn_output, present)
  243. if output_attentions:
  244. outputs += (attn_weights,)
  245.  
  246. return outputs # a, present, (attentions)
  247.  
  248.  
  249. class GPTJMLP(nn.Module):
  250. def __init__(self, intermediate_size, config): # in MLP: intermediate_size= 4 * embed_dim
  251. super().__init__()
  252. embed_dim = config.n_embd
  253.  
  254. self.fc_in = nn.Linear(embed_dim, intermediate_size)
  255. self.fc_out = nn.Linear(intermediate_size, embed_dim)
  256.  
  257. self.act = ACT2FN[config.activation_function]
  258. self.dropout = nn.Dropout(config.resid_pdrop)
  259.  
  260. def forward(self, hidden_states: Optional[torch.FloatTensor]) -> torch.FloatTensor:
  261. hidden_states = self.fc_in(hidden_states)
  262. hidden_states = self.act(hidden_states)
  263. hidden_states = self.fc_out(hidden_states)
  264. hidden_states = self.dropout(hidden_states)
  265. return hidden_states
  266.  
  267.  
  268. class GPTJBlock(nn.Module):
  269. def __init__(self, config):
  270. super().__init__()
  271. inner_dim = config.n_inner if config.n_inner is not None else 4 * config.n_embd
  272. self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
  273. self.attn = GPTJAttention(config)
  274. self.mlp = GPTJMLP(inner_dim, config)
  275.  
  276. def forward(
  277. self,
  278. hidden_states: Optional[torch.FloatTensor],
  279. layer_past: Optional[Tuple[torch.Tensor]] = None,
  280. attention_mask: Optional[torch.FloatTensor] = None,
  281. position_ids: Optional[torch.FloatTensor] = None,
  282. head_mask: Optional[torch.FloatTensor] = None,
  283. use_cache: Optional[bool] = False,
  284. output_attentions: Optional[bool] = False,
  285. ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
  286. residual = hidden_states
  287. hidden_states = self.ln_1(hidden_states)
  288. attn_outputs = self.attn(
  289. hidden_states=hidden_states,
  290. layer_past=layer_past,
  291. attention_mask=attention_mask,
  292. position_ids=position_ids,
  293. head_mask=head_mask,
  294. use_cache=use_cache,
  295. output_attentions=output_attentions,
  296. )
  297. attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
  298. outputs = attn_outputs[1:]
  299.  
  300. feed_forward_hidden_states = self.mlp(hidden_states)
  301. hidden_states = attn_output + feed_forward_hidden_states + residual
  302.  
  303. if use_cache:
  304. outputs = (hidden_states,) + outputs
  305. else:
  306. outputs = (hidden_states,) + outputs[1:]
  307.  
  308. return outputs # hidden_states, present, (attentions)
  309.  
  310.  
  311. class GPTJPreTrainedModel(PreTrainedModel):
  312. """
  313. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  314. models.
  315. """
  316.  
  317. config_class = GPTJConfig
  318. base_model_prefix = "transformer"
  319. is_parallelizable = True
  320. supports_gradient_checkpointing = True
  321. _no_split_modules = ["GPTJBlock"]
  322.  
  323. def __init__(self, *inputs, **kwargs):
  324. super().__init__(*inputs, **kwargs)
  325.  
  326. def _init_weights(self, module):
  327. """Initialize the weights."""
  328. if isinstance(module, (nn.Linear,)):
  329. # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
  330. # cf https://github.com/pytorch/pytorch/pull/5617
  331. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  332. if module.bias is not None:
  333. module.bias.data.zero_()
  334. elif isinstance(module, nn.Embedding):
  335. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  336. if module.padding_idx is not None:
  337. module.weight.data[module.padding_idx].zero_()
  338. elif isinstance(module, nn.LayerNorm):
  339. module.bias.data.zero_()
  340. module.weight.data.fill_(1.0)
  341.  
  342. def _set_gradient_checkpointing(self, module, value=False):
  343. if isinstance(module, GPTJModel):
  344. module.gradient_checkpointing = value
  345.  
  346.  
  347. GPTJ_START_DOCSTRING = r"""
  348. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
  349. it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
  350. behavior.
  351.  
  352. Parameters:
  353. config ([`GPTJConfig`]): Model configuration class with all the parameters of the model.
  354. Initializing with a config file does not load the weights associated with the model, only the
  355. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  356. """
  357.  
  358. GPTJ_INPUTS_DOCSTRING = r"""
  359. Args:
  360. input_ids (`torch.LongTensor` of shape `({0})`):
  361. Indices of input sequence tokens in the vocabulary.
  362.  
  363. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  364. [`PreTrainedTokenizer.__call__`] for details.
  365.  
  366. [What are input IDs?](../glossary#input-ids)
  367. attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
  368. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  369.  
  370. - 1 for tokens that are **not masked**,
  371. - 0 for tokens that are **masked**.
  372.  
  373. [What are attention masks?](../glossary#attention-mask)
  374. token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  375. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  376. 1]`:
  377.  
  378. - 0 corresponds to a *sentence A* token,
  379. - 1 corresponds to a *sentence B* token.
  380.  
  381. [What are token type IDs?](../glossary#token-type-ids)
  382. position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  383. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  384. config.n_positions - 1]`.
  385.  
  386. [What are position IDs?](../glossary#position-ids)
  387. head_mask (`torch.FloatTensor` of shape `(num_attention_heads,)` or `(n_layer, num_attention_heads)`, *optional*):
  388. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  389.  
  390. - 1 indicates the head is **not masked**,
  391. - 0 indicates the head is **masked**.
  392.  
  393. inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_dim)`, *optional*):
  394. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  395. is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
  396. model's internal embedding lookup matrix.
  397. output_attentions (`bool`, *optional*):
  398. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  399. tensors for more detail.
  400. output_hidden_states (`bool`, *optional*):
  401. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  402. more detail.
  403. return_dict (`bool`, *optional*):
  404. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  405. """
  406.  
  407. PARALLELIZE_DOCSTRING = r"""
  408. This is an experimental feature and is a subject to change at a moment's notice. Uses a device map to distribute
  409. attention modules of the model across several devices. If no device map is given, it will evenly distribute blocks
  410. across all devices.
  411.  
  412. Args:
  413. device_map (`Dict[int, list]`, optional, defaults to None):
  414. A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
  415. automatically mapped to the first device (for esoteric reasons). That means that the first device should
  416. have fewer attention modules mapped to it than other devices. For reference, the GPT-J models have the
  417. following number of attention modules:
  418.  
  419. - gpt-j-6B: 28
  420.  
  421. Example:
  422.  
  423. ```python
  424. # Here is an example of a device map on a machine with 4 GPUs using gpt-j-6B, which has a total of 28 attention modules:
  425. model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B")
  426. device_map = {
  427. 0: [0, 1, 2, 3, 4, 5, 6],
  428. 1: [7, 8, 9, 10, 11, 12, 13],
  429. 2: [14, 15, 16, 17, 18, 19, 20],
  430. 3: [21, 22, 23, 24, 25, 26, 27],
  431. }
  432. model.parallelize(device_map)
  433. ```
  434. """
  435.  
  436. DEPARALLELIZE_DOCSTRING = r"""
  437. Moves the model to CPU from a model parallel state.
  438.  
  439. Example:
  440.  
  441. ```python
  442. # On a 4 GPU machine with gpt-j-6B:
  443. model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B")
  444. device_map = {
  445. 0: [0, 1, 2, 3, 4, 5, 6],
  446. 1: [7, 8, 9, 10, 11, 12, 13],
  447. 2: [14, 15, 16, 17, 18, 19, 20],
  448. 3: [21, 22, 23, 24, 25, 26, 27],
  449. }
  450. model.parallelize(device_map) # Splits the model across several devices
  451. model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
  452. ```
  453. """
  454.  
  455.  
  456. @add_start_docstrings(
  457. "The bare GPT-J Model transformer outputting raw hidden-states without any specific head on top.",
  458. GPTJ_START_DOCSTRING,
  459. )
  460. class GPTJModel(GPTJPreTrainedModel):
  461. def __init__(self, config):
  462. super().__init__(config)
  463.  
  464. self.embed_dim = config.n_embd
  465. self.vocab_size = config.vocab_size
  466. self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
  467. self.drop = nn.Dropout(config.embd_pdrop)
  468. self.h = nn.ModuleList([GPTJBlock(config) for _ in range(config.n_layer)])
  469. self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
  470.  
  471. # Model parallel
  472. self.model_parallel = False
  473. self.device_map = None
  474. self.gradient_checkpointing = False
  475.  
  476. # Initialize weights and apply final processing
  477. self.post_init()
  478.  
  479. @add_start_docstrings(PARALLELIZE_DOCSTRING)
  480. def parallelize(self, device_map=None):
  481. warnings.warn(
  482. "`GPTJModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
  483. " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
  484. " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
  485. " ...}",
  486. FutureWarning,
  487. )
  488. # Check validity of device_map
  489. self.device_map = (
  490. get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
  491. )
  492. assert_device_map(self.device_map, len(self.h))
  493. self.model_parallel = True
  494. self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
  495. self.last_device = "cuda:" + str(max(self.device_map.keys()))
  496. self.wte = self.wte.to(self.first_device)
  497. # Load onto devices
  498. for k, v in self.device_map.items():
  499. for block in v:
  500. cuda_device = "cuda:" + str(k)
  501. self.h[block] = self.h[block].to(cuda_device)
  502. # ln_f to last
  503. self.ln_f = self.ln_f.to(self.last_device)
  504.  
  505. @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
  506. def deparallelize(self):
  507. warnings.warn(
  508. "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
  509. FutureWarning,
  510. )
  511. self.model_parallel = False
  512. self.device_map = None
  513. self.first_device = "cpu"
  514. self.last_device = "cpu"
  515. self.wte = self.wte.to("cpu")
  516. for index in range(len(self.h)):
  517. self.h[index] = self.h[index].to("cpu")
  518. self.ln_f = self.ln_f.to("cpu")
  519. torch.cuda.empty_cache()
  520.  
  521. def get_input_embeddings(self):
  522. return self.wte
  523.  
  524. def set_input_embeddings(self, new_embeddings):
  525. self.wte = new_embeddings
  526.  
  527. @add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  528. @add_code_sample_docstrings(
  529. checkpoint=_CHECKPOINT_FOR_DOC,
  530. output_type=BaseModelOutputWithPast,
  531. config_class=_CONFIG_FOR_DOC,
  532. real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
  533. )
  534. def forward(
  535. self,
  536. input_ids: Optional[torch.LongTensor] = None,
  537. past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
  538. attention_mask: Optional[torch.FloatTensor] = None,
  539. token_type_ids: Optional[torch.LongTensor] = None,
  540. position_ids: Optional[torch.LongTensor] = None,
  541. head_mask: Optional[torch.FloatTensor] = None,
  542. inputs_embeds: Optional[torch.FloatTensor] = None,
  543. use_cache: Optional[bool] = None,
  544. output_attentions: Optional[bool] = None,
  545. output_hidden_states: Optional[bool] = None,
  546. return_dict: Optional[bool] = None,
  547. ) -> Union[Tuple, BaseModelOutputWithPast]:
  548. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  549. output_hidden_states = (
  550. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  551. )
  552. use_cache = use_cache if use_cache is not None else self.config.use_cache
  553. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  554.  
  555. if input_ids is not None and inputs_embeds is not None:
  556. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  557. elif input_ids is not None:
  558. input_shape = input_ids.size()
  559. input_ids = input_ids.view(-1, input_shape[-1])
  560. batch_size = input_ids.shape[0]
  561. elif inputs_embeds is not None:
  562. input_shape = inputs_embeds.size()[:-1]
  563. batch_size = inputs_embeds.shape[0]
  564. else:
  565. raise ValueError("You have to specify either input_ids or inputs_embeds")
  566.  
  567. device = input_ids.device if input_ids is not None else inputs_embeds.device
  568.  
  569. if token_type_ids is not None:
  570. token_type_ids = token_type_ids.view(-1, input_shape[-1])
  571.  
  572. if position_ids is not None:
  573. position_ids = position_ids.view(-1, input_shape[-1]).long()
  574.  
  575. if past_key_values is None:
  576. past_length = 0
  577. past_key_values = tuple([None] * len(self.h))
  578. else:
  579. past_length = past_key_values[0][0].size(-2)
  580.  
  581. if position_ids is None:
  582. position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
  583. position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
  584.  
  585. # Attention mask.
  586. if attention_mask is not None:
  587. if batch_size <= 0:
  588. raise ValueError("batch_size has to be defined and > 0")
  589. attention_mask = attention_mask.view(batch_size, -1)
  590. # We create a 3D attention mask from a 2D tensor mask.
  591. # Sizes are [batch_size, 1, 1, to_seq_length]
  592. # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
  593. # this attention mask is more simple than the triangular masking of causal attention
  594. # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
  595. attention_mask = attention_mask[:, None, None, :]
  596.  
  597. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  598. # masked positions, this operation will create a tensor which is 0.0 for
  599. # positions we want to attend and the dtype's smallest value for masked positions.
  600. # Since we are adding it to the raw scores before the softmax, this is
  601. # effectively the same as removing these entirely.
  602. attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
  603. attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
  604.  
  605. # Prepare head mask if needed
  606. # 1.0 in head_mask indicate we keep the head
  607. # attention_probs has shape bsz x num_attention_heads x N x N
  608. # head_mask has shape n_layer x batch x num_attention_heads x N x N
  609. head_mask = self.get_head_mask(head_mask, self.config.n_layer)
  610.  
  611. if inputs_embeds is None:
  612. inputs_embeds = self.wte(input_ids)
  613.  
  614. hidden_states = inputs_embeds
  615.  
  616. if token_type_ids is not None:
  617. token_type_embeds = self.wte(token_type_ids)
  618. hidden_states = hidden_states + token_type_embeds
  619.  
  620. hidden_states = self.drop(hidden_states)
  621.  
  622. output_shape = input_shape + (hidden_states.size(-1),)
  623.  
  624. if self.gradient_checkpointing and self.training:
  625. if use_cache:
  626. logger.warning_once(
  627. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  628. )
  629. use_cache = False
  630.  
  631. presents = () if use_cache else None
  632. all_self_attentions = () if output_attentions else None
  633. all_hidden_states = () if output_hidden_states else None
  634. for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
  635. # Model parallel
  636. if self.model_parallel:
  637. torch.cuda.set_device(hidden_states.device)
  638. # Ensure layer_past is on same device as hidden_states (might not be correct)
  639. if layer_past is not None:
  640. layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
  641. # Ensure that attention_mask is always on the same device as hidden_states
  642. if attention_mask is not None:
  643. attention_mask = attention_mask.to(hidden_states.device)
  644. if isinstance(head_mask, torch.Tensor):
  645. head_mask = head_mask.to(hidden_states.device)
  646. if output_hidden_states:
  647. all_hidden_states = all_hidden_states + (hidden_states,)
  648.  
  649. if self.gradient_checkpointing and self.training:
  650.  
  651. def create_custom_forward(module):
  652. def custom_forward(*inputs):
  653. # None for past_key_value
  654. return module(*inputs, use_cache, output_attentions)
  655.  
  656. return custom_forward
  657.  
  658. outputs = torch.utils.checkpoint.checkpoint(
  659. create_custom_forward(block),
  660. hidden_states,
  661. None,
  662. attention_mask,
  663. position_ids,
  664. head_mask[i],
  665. )
  666. else:
  667. outputs = block(
  668. hidden_states=hidden_states,
  669. layer_past=layer_past,
  670. attention_mask=attention_mask,
  671. position_ids=position_ids,
  672. head_mask=head_mask[i],
  673. use_cache=use_cache,
  674. output_attentions=output_attentions,
  675. )
  676.  
  677. hidden_states = outputs[0]
  678. if use_cache is True:
  679. presents = presents + (outputs[1],)
  680.  
  681. if output_attentions:
  682. all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
  683.  
  684. # Model Parallel: If it's the last layer for that device, put things on the next device
  685. if self.model_parallel:
  686. for k, v in self.device_map.items():
  687. if i == v[-1] and "cuda:" + str(k) != self.last_device:
  688. hidden_states = hidden_states.to("cuda:" + str(k + 1))
  689.  
  690. hidden_states = self.ln_f(hidden_states)
  691.  
  692. hidden_states = hidden_states.view(output_shape)
  693. # Add last hidden state
  694. if output_hidden_states:
  695. all_hidden_states = all_hidden_states + (hidden_states,)
  696.  
  697. if not return_dict:
  698. return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
  699.  
  700. return BaseModelOutputWithPast(
  701. last_hidden_state=hidden_states,
  702. past_key_values=presents,
  703. hidden_states=all_hidden_states,
  704. attentions=all_self_attentions,
  705. )
  706.  
  707.  
  708. @add_start_docstrings(
  709. """
  710. The GPT-J Model transformer with a language modeling head on top.
  711. """,
  712. GPTJ_START_DOCSTRING,
  713. )
  714. class GPTJForCausalLM(GPTJPreTrainedModel):
  715. _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
  716.  
  717. def __init__(self, config):
  718. super().__init__(config)
  719. self.transformer = GPTJModel(config)
  720. self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
  721.  
  722. # Model parallel
  723. self.model_parallel = False
  724. self.device_map = None
  725.  
  726. # Initialize weights and apply final processing
  727. self.post_init()
  728.  
  729. @add_start_docstrings(PARALLELIZE_DOCSTRING)
  730. def parallelize(self, device_map=None):
  731. warnings.warn(
  732. "`GPTJForCausalLM.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
  733. " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
  734. " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
  735. " 0, 'transformer.h.1': 1, ...}",
  736. FutureWarning,
  737. )
  738. self.device_map = (
  739. get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
  740. if device_map is None
  741. else device_map
  742. )
  743. assert_device_map(self.device_map, len(self.transformer.h))
  744. self.transformer.parallelize(self.device_map)
  745. self.lm_head = self.lm_head.to(self.transformer.first_device)
  746. self.model_parallel = True
  747.  
  748. @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
  749. def deparallelize(self):
  750. warnings.warn(
  751. "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
  752. FutureWarning,
  753. )
  754. self.transformer.deparallelize()
  755. self.transformer = self.transformer.to("cpu")
  756. self.lm_head = self.lm_head.to("cpu")
  757. self.model_parallel = False
  758. torch.cuda.empty_cache()
  759.  
  760. def get_output_embeddings(self):
  761. return self.lm_head
  762.  
  763. def set_output_embeddings(self, new_embeddings):
  764. self.lm_head = new_embeddings
  765.  
  766. def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
  767. token_type_ids = kwargs.get("token_type_ids", None)
  768. # only last token for inputs_ids if past is defined in kwargs
  769. if past_key_values:
  770. input_ids = input_ids[:, -1].unsqueeze(-1)
  771. if token_type_ids is not None:
  772. token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
  773.  
  774. attention_mask = kwargs.get("attention_mask", None)
  775. position_ids = kwargs.get("position_ids", None)
  776.  
  777. if attention_mask is not None and position_ids is None:
  778. # create position_ids on the fly for batch generation
  779. position_ids = attention_mask.long().cumsum(-1) - 1
  780. position_ids.masked_fill_(attention_mask == 0, 1)
  781. if past_key_values:
  782. position_ids = position_ids[:, -1].unsqueeze(-1)
  783.  
  784. # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
  785. if inputs_embeds is not None and past_key_values is None:
  786. model_inputs = {"inputs_embeds": inputs_embeds}
  787. else:
  788. model_inputs = {"input_ids": input_ids}
  789.  
  790. model_inputs.update(
  791. {
  792. "past_key_values": past_key_values,
  793. "use_cache": kwargs.get("use_cache"),
  794. "position_ids": position_ids,
  795. "attention_mask": attention_mask,
  796. "token_type_ids": token_type_ids,
  797. }
  798. )
  799.  
  800. return model_inputs
  801.  
  802. @add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  803. @add_code_sample_docstrings(
  804. checkpoint=_CHECKPOINT_FOR_DOC,
  805. output_type=CausalLMOutputWithPast,
  806. config_class=_CONFIG_FOR_DOC,
  807. real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
  808. )
  809. def forward(
  810. self,
  811. input_ids: Optional[torch.LongTensor] = None,
  812. past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
  813. attention_mask: Optional[torch.FloatTensor] = None,
  814. token_type_ids: Optional[torch.LongTensor] = None,
  815. position_ids: Optional[torch.LongTensor] = None,
  816. head_mask: Optional[torch.FloatTensor] = None,
  817. inputs_embeds: Optional[torch.FloatTensor] = None,
  818. labels: Optional[torch.LongTensor] = None,
  819. use_cache: Optional[bool] = None,
  820. output_attentions: Optional[bool] = None,
  821. output_hidden_states: Optional[bool] = None,
  822. return_dict: Optional[bool] = None,
  823. ) -> Union[Tuple, CausalLMOutputWithPast]:
  824. r"""
  825. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  826. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  827. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  828. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  829. """
  830. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  831.  
  832. transformer_outputs = self.transformer(
  833. input_ids,
  834. past_key_values=past_key_values,
  835. attention_mask=attention_mask,
  836. token_type_ids=token_type_ids,
  837. position_ids=position_ids,
  838. head_mask=head_mask,
  839. inputs_embeds=inputs_embeds,
  840. use_cache=use_cache,
  841. output_attentions=output_attentions,
  842. output_hidden_states=output_hidden_states,
  843. return_dict=return_dict,
  844. )
  845. hidden_states = transformer_outputs[0]
  846.  
  847. # Set device for model parallelism
  848. if self.model_parallel:
  849. torch.cuda.set_device(self.transformer.first_device)
  850. hidden_states = hidden_states.to(self.lm_head.weight.device)
  851.  
  852. # make sure sampling in fp16 works correctly and
  853. # compute loss in fp32 to match with mesh-tf version
  854. # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
  855. lm_logits = self.lm_head(hidden_states).to(torch.float32)
  856.  
  857. loss = None
  858. if labels is not None:
  859. # Shift so that tokens < n predict n
  860. shift_logits = lm_logits[..., :-1, :].contiguous()
  861. shift_labels = labels[..., 1:].contiguous()
  862. # Flatten the tokens
  863. loss_fct = CrossEntropyLoss()
  864. loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
  865.  
  866. loss = loss.to(hidden_states.dtype)
  867.  
  868. if not return_dict:
  869. output = (lm_logits,) + transformer_outputs[1:]
  870. return ((loss,) + output) if loss is not None else output
  871.  
  872. return CausalLMOutputWithPast(
  873. loss=loss,
  874. logits=lm_logits,
  875. past_key_values=transformer_outputs.past_key_values,
  876. hidden_states=transformer_outputs.hidden_states,
  877. attentions=transformer_outputs.attentions,
  878. )
  879.  
  880. @staticmethod
  881. def _reorder_cache(
  882. past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
  883. ) -> Tuple[Tuple[torch.Tensor]]:
  884. """
  885. This function is used to re-order the `past_key_values` cache if [`~PretrainedModel.beam_search`] or
  886. [`~PretrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
  887. beam_idx at every generation step.
  888. """
  889. return tuple(
  890. tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
  891. for layer_past in past_key_values
  892. )
  893.  
  894.  
  895. @add_start_docstrings(
  896. """
  897. The GPT-J Model transformer with a sequence classification head on top (linear layer).
  898.  
  899. [`GPTJForSequenceClassification`] uses the last token in order to do the classification, as other causal models
  900. (e.g. GPT, GPT-2, GPT-Neo) do.
  901.  
  902. Since it does classification on the last token, it requires to know the position of the last token. If a
  903. `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
  904. no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
  905. padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
  906. each row of the batch).
  907. """,
  908. GPTJ_START_DOCSTRING,
  909. )
  910. class GPTJForSequenceClassification(GPTJPreTrainedModel):
  911. _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
  912.  
  913. def __init__(self, config):
  914. super().__init__(config)
  915. self.num_labels = config.num_labels
  916. self.transformer = GPTJModel(config)
  917. self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
  918.  
  919. # Model parallel
  920. self.model_parallel = False
  921. self.device_map = None
  922.  
  923. # Initialize weights and apply final processing
  924. self.post_init()
  925.  
  926. @add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  927. @add_code_sample_docstrings(
  928. checkpoint="ydshieh/tiny-random-gptj-for-sequence-classification",
  929. output_type=SequenceClassifierOutputWithPast,
  930. config_class=_CONFIG_FOR_DOC,
  931. real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
  932. )
  933. def forward(
  934. self,
  935. input_ids: Optional[torch.LongTensor] = None,
  936. past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
  937. attention_mask: Optional[torch.FloatTensor] = None,
  938. token_type_ids: Optional[torch.LongTensor] = None,
  939. position_ids: Optional[torch.LongTensor] = None,
  940. head_mask: Optional[torch.FloatTensor] = None,
  941. inputs_embeds: Optional[torch.FloatTensor] = None,
  942. labels: Optional[torch.LongTensor] = None,
  943. use_cache: Optional[bool] = None,
  944. output_attentions: Optional[bool] = None,
  945. output_hidden_states: Optional[bool] = None,
  946. return_dict: Optional[bool] = None,
  947. ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
  948. r"""
  949. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  950. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  951. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  952. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  953. """
  954. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  955.  
  956. transformer_outputs = self.transformer(
  957. input_ids,
  958. past_key_values=past_key_values,
  959. attention_mask=attention_mask,
  960. token_type_ids=token_type_ids,
  961. position_ids=position_ids,
  962. head_mask=head_mask,
  963. inputs_embeds=inputs_embeds,
  964. use_cache=use_cache,
  965. output_attentions=output_attentions,
  966. output_hidden_states=output_hidden_states,
  967. return_dict=return_dict,
  968. )
  969. hidden_states = transformer_outputs[0]
  970. logits = self.score(hidden_states)
  971.  
  972. if input_ids is not None:
  973. batch_size = input_ids.shape[0]
  974. else:
  975. batch_size = inputs_embeds.shape[0]
  976.  
  977. if self.config.pad_token_id is None and batch_size != 1:
  978. raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
  979. if self.config.pad_token_id is None:
  980. sequence_lengths = -1
  981. else:
  982. if input_ids is not None:
  983. sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
  984. else:
  985. sequence_lengths = -1
  986. logger.warning(
  987. f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
  988. "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
  989. )
  990.  
  991. pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
  992.  
  993. loss = None
  994. if labels is not None:
  995. if self.config.problem_type is None:
  996. if self.num_labels == 1:
  997. self.config.problem_type = "regression"
  998. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  999. self.config.problem_type = "single_label_classification"
  1000. else:
  1001. self.config.problem_type = "multi_label_classification"
  1002.  
  1003. if self.config.problem_type == "regression":
  1004. loss_fct = MSELoss()
  1005. if self.num_labels == 1:
  1006. loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
  1007. else:
  1008. loss = loss_fct(pooled_logits, labels)
  1009. elif self.config.problem_type == "single_label_classification":
  1010. loss_fct = CrossEntropyLoss()
  1011. loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
  1012. elif self.config.problem_type == "multi_label_classification":
  1013. loss_fct = BCEWithLogitsLoss()
  1014. loss = loss_fct(pooled_logits, labels)
  1015. if not return_dict:
  1016. output = (pooled_logits,) + transformer_outputs[1:]
  1017. return ((loss,) + output) if loss is not None else output
  1018.  
  1019. return SequenceClassifierOutputWithPast(
  1020. loss=loss,
  1021. logits=pooled_logits,
  1022. past_key_values=transformer_outputs.past_key_values,
  1023. hidden_states=transformer_outputs.hidden_states,
  1024. attentions=transformer_outputs.attentions,
  1025. )
  1026.  
  1027.  
  1028. @add_start_docstrings(
  1029. """
  1030. The GPT-J Model transformer with a span classification head on top for extractive question-answering tasks like
  1031. SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
  1032. """,
  1033. GPTJ_START_DOCSTRING,
  1034. )
  1035. class GPTJForQuestionAnswering(GPTJPreTrainedModel):
  1036. _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
  1037.  
  1038. def __init__(self, config):
  1039. super().__init__(config)
  1040. self.num_labels = config.num_labels
  1041. self.transformer = GPTJModel(config)
  1042. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1043.  
  1044. # Model parallel
  1045. self.model_parallel = False
  1046. self.device_map = None
  1047.  
  1048. # Initialize weights and apply final processing
  1049. self.post_init()
  1050.  
  1051. @add_start_docstrings_to_model_forward(GPTJ_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1052. @add_code_sample_docstrings(
  1053. checkpoint=_CHECKPOINT_FOR_DOC,
  1054. output_type=QuestionAnsweringModelOutput,
  1055. config_class=_CONFIG_FOR_DOC,
  1056. real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
  1057. )
  1058. def forward(
  1059. self,
  1060. input_ids: Optional[torch.LongTensor] = None,
  1061. attention_mask: Optional[torch.FloatTensor] = None,
  1062. token_type_ids: Optional[torch.LongTensor] = None,
  1063. position_ids: Optional[torch.LongTensor] = None,
  1064. head_mask: Optional[torch.FloatTensor] = None,
  1065. inputs_embeds: Optional[torch.FloatTensor] = None,
  1066. start_positions: Optional[torch.LongTensor] = None,
  1067. end_positions: Optional[torch.LongTensor] = None,
  1068. output_attentions: Optional[bool] = None,
  1069. output_hidden_states: Optional[bool] = None,
  1070. return_dict: Optional[bool] = None,
  1071. ) -> Union[Tuple, QuestionAnsweringModelOutput]:
  1072. r"""
  1073. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1074. Labels for position (index) of the start of the labelled span for computing the token classification loss.
  1075. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  1076. are not taken into account for computing the loss.
  1077. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1078. Labels for position (index) of the end of the labelled span for computing the token classification loss.
  1079. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  1080. are not taken into account for computing the loss.
  1081. """
  1082. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1083.  
  1084. outputs = self.transformer(
  1085. input_ids,
  1086. attention_mask=attention_mask,
  1087. token_type_ids=token_type_ids,
  1088. position_ids=position_ids,
  1089. head_mask=head_mask,
  1090. inputs_embeds=inputs_embeds,
  1091. output_attentions=output_attentions,
  1092. output_hidden_states=output_hidden_states,
  1093. return_dict=return_dict,
  1094. )
  1095.  
  1096. sequence_output = outputs[0]
  1097.  
  1098. logits = self.qa_outputs(sequence_output)
  1099. start_logits, end_logits = logits.split(1, dim=-1)
  1100. start_logits = start_logits.squeeze(-1).contiguous()
  1101. end_logits = end_logits.squeeze(-1).contiguous()
  1102.  
  1103. total_loss = None
  1104. if start_positions is not None and end_positions is not None:
  1105. # If we are on multi-GPU, split add a dimension
  1106. if len(start_positions.size()) > 1:
  1107. start_positions = start_positions.squeeze(-1)
  1108. if len(end_positions.size()) > 1:
  1109. end_positions = end_positions.squeeze(-1)
  1110. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1111. ignored_index = start_logits.size(1)
  1112. start_positions = start_positions.clamp(0, ignored_index)
  1113. end_positions = end_positions.clamp(0, ignored_index)
  1114.  
  1115. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1116. start_loss = loss_fct(start_logits, start_positions)
  1117. end_loss = loss_fct(end_logits, end_positions)
  1118. total_loss = (start_loss + end_loss) / 2
  1119.  
  1120. if not return_dict:
  1121. output = (start_logits, end_logits) + outputs[2:]
  1122. return ((total_loss,) + output) if total_loss is not None else output
  1123.  
  1124. return QuestionAnsweringModelOutput(
  1125. loss=total_loss,
  1126. start_logits=start_logits,
  1127. end_logits=end_logits,
  1128. hidden_states=outputs.hidden_states,
  1129. attentions=outputs.attentions,
  1130. )
  1131.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement