The error you're encountering is because torch.multinomial expects its input tensor probs to be either 1-dimensional, representing a single probability distribution, or 2-dimensional, where each row represents a distinct probability distribution. However, your probs tensor is 3-dimensional (2x2x50257). This mismatch is what's causing the issue.
Given that probs is a 2x2x50257 tensor, it seems you have a batch of distributions you want to sample from. The usual approach with torch.multinomial would be to work with a 2D tensor where rows represent different distributions.
If your intent is to sample once from each distribution along the last dimension (which seems to be the case since num_samples=1), you'd want to reshape or view your tensor in a way that aligns with this expectation. The challenge here is how you want to treat your batches and the 2x2 structure leading up to the 50257 categories. Assuming you want to keep the batch structure and sample from each of the distributions independently, you might need to reshape your probs tensor accordingly.
Here's a way you could adjust your function to handle the probs tensor properly by reshaping it into a 2D tensor before sampling and then reshaping the result back if needed:
import torch
import torch.nn.functional as F
def sample(scores, do_sample=False, temperature=1.0, top_k=0, top_p=1.0):
if do_sample:
# Apply temperature
if temperature != 1.0:
scores = scores / temperature
# Assuming top_k_top_p_filtering works correctly with your dimensions
next_token_logscores = top_k_top_p_filtering(scores, top_k=top_k, top_p=top_p)
# Softmax along the last dimension
probs = F.softmax(next_token_logscores, dim=-1)
# Reshape probs to 2D (flatten the first two dimensions)
original_shape = probs.shape
probs_2d = probs.view(-1, original_shape[-1])
# Sample
next_token_flat = torch.multinomial(probs_2d, num_samples=1).squeeze(1)
# Optionally, reshape back to original batch structure if needed
# Here, reshaping back to (original_shape[0], original_shape[1], -1) assuming you're sampling 1 value per distribution
next_token = next_token_flat.view(original_shape[0], original_shape[1])
else:
# For the non-sampling case, you'd do something similar with argmax if needed
next_token = torch.argmax(scores, dim=-1)
return next_token
Note: Make sure the reshaping step (probs_2d = probs.view(-1, original_shape[-1])) doesn't interfere with the semantics of your data. This operation combines the first two dimensions, treating each 50257-length inner-most dimension as a separate distribution. After sampling (torch.multinomial(probs_2d, num_samples=1)), if you need to maintain the original batch and spatial dimensions (assuming the 2x2 was spatial or some other important dimension), you may reshape it back as shown.
Lastly, ensure your top_k_top_p_filtering function (not provided in your question) can handle the input tensor properly and returns a tensor that supports the desired operation.