Compute the log probabilities of the given labels under the given logits. Args: logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) labels: Labels for which to compute the log probabilities. Label tokens with a value of -100 are ignored.
(logits: torch.FloatTensor, labels: torch.LongTensor, average_log_prob: bool = False)
| 88 | |
| 89 | |
| 90 | def _get_batch_logps(logits: torch.FloatTensor, labels: torch.LongTensor, average_log_prob: bool = False) -> torch.FloatTensor: |
| 91 | """Compute the log probabilities of the given labels under the given logits. |
| 92 | |
| 93 | Args: |
| 94 | logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) |
| 95 | labels: Labels for which to compute the log probabilities. Label tokens with a value of -100 are ignored. Shape: (batch_size, sequence_length) |
| 96 | average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. |
| 97 | |
| 98 | Returns: |
| 99 | A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. |
| 100 | """ |
| 101 | assert logits.shape[:-1] == labels.shape |
| 102 | |
| 103 | labels = labels[:, 1:].clone() |
| 104 | logits = logits[:, :-1, :] |
| 105 | loss_mask = (labels != -100) |
| 106 | |
| 107 | # dummy token; we'll ignore the losses on these tokens later |
| 108 | labels[labels == -100] = 0 |
| 109 | |
| 110 | per_token_logps = torch.gather(logits.log_softmax(-1), dim=2, index=labels.unsqueeze(2)).squeeze(2) |
| 111 | |
| 112 | if average_log_prob: |
| 113 | return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) |
| 114 | else: |
| 115 | return (per_token_logps * loss_mask).sum(-1) |
| 116 | |
| 117 | |
| 118 | def concatenated_inputs(batch: Dict[str, Union[List, torch.LongTensor]]) -> Dict[str, torch.LongTensor]: |
no outgoing calls
no test coverage detected