|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | +from torch import Tensor |
| 5 | +from jaxtyping import Float, Int |
| 6 | + |
| 7 | + |
| 8 | +class RefLogProbMLM(nn.Module): |
| 9 | + """Reference Log Probability Masked Language Model wrapper. |
| 10 | +
|
| 11 | + This class wraps a pre-trained language model to compute reference log probabilities |
| 12 | + for masked language modeling tasks. It takes a sequence with a masked position |
| 13 | + and returns the log probability of the reference token at that position. |
| 14 | +
|
| 15 | + The model expects input tensors with specific shapes: |
| 16 | + - input_ids_BL: Batch of token ID sequences [batch_size, sequence_length] |
| 17 | + - pos_B: Positions to evaluate for each sequence in the batch |
| 18 | + - ref_B: Reference token IDs to compute log probabilities for |
| 19 | +
|
| 20 | + Attributes: |
| 21 | + model: The underlying language model that provides logits |
| 22 | + """ |
| 23 | + |
| 24 | + def __init__(self, model: nn.Module): |
| 25 | + super().__init__() |
| 26 | + self.model = model |
| 27 | + |
| 28 | + def forward( |
| 29 | + self, |
| 30 | + input_ids_BL: Int[Tensor, "B L"], |
| 31 | + pos_B: Int[Tensor, " B"], |
| 32 | + ref_B: Int[Tensor, " B"], |
| 33 | + ) -> Float[Tensor, " B"]: |
| 34 | + """Forward pass to compute reference log probabilities. |
| 35 | +
|
| 36 | + This method: |
| 37 | + 1. Runs the input through the language model to get logits |
| 38 | + 2. Extracts logits at the specified positions |
| 39 | + 3. Computes log probabilities using softmax |
| 40 | + 4. Returns the log probability of the reference tokens |
| 41 | +
|
| 42 | + Args: |
| 43 | + input_ids_BL: Batch of token ID sequences with shape [B, L] where |
| 44 | + B is batch size and L is sequence length |
| 45 | + pos_B: Positions to evaluate for each sequence in the batch with |
| 46 | + shape [B] where each element is the position index |
| 47 | + ref_B: Reference token IDs to compute log probabilities for with |
| 48 | + shape [B] where each element is the token ID |
| 49 | +
|
| 50 | + Returns: |
| 51 | + Log probabilities of the reference tokens at the specified positions |
| 52 | + with shape [B] where B is the batch size |
| 53 | + """ |
| 54 | + B, L = input_ids_BL.shape |
| 55 | + batch_indices_B = torch.arange(B) |
| 56 | + logits_BLV = self.model(input_ids_BL).logits |
| 57 | + logits_BV = logits_BLV[batch_indices_B, pos_B] |
| 58 | + logprobs_BV = F.log_softmax(logits_BV, dim=-1) |
| 59 | + res_B = logprobs_BV[batch_indices_B, ref_B] |
| 60 | + return res_B |
0 commit comments