Выбираем наиболее вероятные токены
_, max_indices = torch.max(logits, dim=-1)
надо получить вот это
print(f"\nGreedy Search")
for i, tok in enumerate(...):
score = ...[0][i].cpu()
print(f"| {tok:5d} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}| {tokenizer.decode([tok]):8s} ")
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
It seems you are trying to use a pre-trained model (likely a language model) to generate text using greedy search. In greedy search, at each step, the most probable next token is chosen.
To complete your code snippet, you need to iterate through the max_indices you obtained from torch.max and retrieve the corresponding scores from the logits. Then you can convert these scores to probabilities, decode the tokens into text, and print the results.
Here's how you can do it:
python
import numpy as np
import torch
# Assuming 'logits' is the output from your model that contains raw score for each token in the vocabulary
# Also assuming you have a 'tokenizer' object that can decode token ids into text
with torch.no_grad():
with torch.autocast('cuda', dtype=torch.float32):
# Assuming 'input' is your input tensor
# outpute = modeltt(input, labels=input, use_cache = False) # This line is commented out
outpute = modeltt(input, use_cache = False)
# logits are typically the last hidden state in the output of a transformer-based language model
logits = outpute.logits
# Selecting the most probable tokens
_, max_indices = torch.max(logits, dim=-1)
print(f"\nGreedy Search")
for i, tok in enumerate(max_indices.squeeze()):
score = logits[0][i][tok].cpu() # Get the score for the specific token
print(f"| {tok.item():5d} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%} | {tokenizer.decode([tok]):8s} ")
Please note the following:
The logits variable should contain the output from your model. Make sure it is the right tensor that contains the scores for each token.
The max_indices are the tokens with the highest score for each position in the sequence.
We use logits[0][i][tok] to get the score for each token. This assumes that the logits tensor has the shape [batch_size, sequence_length, vocab_size]. Adjust the indexing if your output is shaped differently.
tok.item() is used to get the Python scalar from the Torch tensor.
score.numpy() is used to convert the score from a Torch tensor to a NumPy array before printing.
tokenizer.decode([tok]) is used to convert the token id tok into its string representation.
Make sure you replace modeltt, input, and tokenizer with the actual objects you are using in your code.
User
with torch.no_grad():
with torch.autocast('cuda', dtype=torch.float32):
# Assuming 'input' is your input tensor
outpute = modeltt(input, labels=input, use_cache = False) # This line is commented out
logits are typically the last hidden state in the output of a transformer-based language model
logits = outpute.logits
Selecting the most probable tokens
_, max_indices = torch.max(logits, dim=-1)
тут видимо не хватает нормализации max_indices
print(f"\nGreedy Search")
for i, tok in enumerate(max_indices.squeeze()):
score = logits[0][i][tok].cpu() # Get the score for the specific token
print(f"| {tok.item():5d} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%} | {tokenizer.decode([tok]):8s} ")
Please note the following:
Assistant
Your observation regarding the normalization of max_indices is not entirely clear. In the context of greedy search, normalization typically refers to converting the raw scores (logits) into probabilities, which isn't necessary for selecting the most probable token since we're only interested in the index with the highest value, not the actual probability.
However, if your goal is to display the probabilities associated with the most probable tokens, you would indeed need to apply a softmax function to the logits before extracting the scores. The softmax function will convert the logits into probabilities, which will sum to 1 across the vocabulary for each time step.
Here is how you might modify your code to include the softmax step and display the probabilities:
python
import numpy as np
import torch
from torch.nn.functional import softmax
# ... (other parts of your code) ...
# Assuming 'logits' is the output from your model
logits = outpute.logits
# Apply softmax to convert logits to probabilities
probs = softmax(logits, dim=-1)
# Selecting the most probable tokens
_, max_indices = torch.max(probs, dim=-1)
print(f"\nGreedy Search")
for i, tok in enumerate(max_indices.squeeze()):
# Get the probability of the most probable token
prob = probs[0][i][tok].cpu()
print(f"| {tok.item():5d} | {prob.numpy():.3f} | {prob.numpy():.2%} | {tokenizer.decode([tok]):8s} ")
In this code snippet:
softmax(logits, dim=-1) is applied to the logits to convert them into probabilities. The dim=-1 argument specifies that the softmax should be applied across the vocabulary dimension.
prob = probs[0][i][tok].cpu() retrieves the probability of the token with the highest score at each step.
The rest of the code remains the same, but we are now printing the probability (prob.numpy()) instead of the raw score.
Remember, when you apply the softmax function, you're converting raw scores to probabilities, which you can interpret as the model's confidence in its prediction for each token. The torch.max() function still gives you the index of the highest value, which is the most probable token, but now you're also displaying the associated probability instead of the raw score.