Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid nan during sampling in generate() #17937

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/transformers/generation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1970,8 +1970,19 @@ def sample(
else (outputs.hidden_states,)
)

# To avoid all `-inf` along the vocab dimension (dim -1), which gives `nan` after `softmax` and error
# in `torch.multinomial`.
_next_token_scores = torch.max(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ydshieh, softmax should be able to handle -inf correctly actually.
You can try:

torch.nn.functional.softmax(torch.tensor([0, float("-inf")]))

which works as mathematically expected.

It's only when all values are -inf that it doesn't work in which case this fix won't help because the generation is broken.

Copy link
Collaborator Author

@ydshieh ydshieh Jun 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will fix the nan issue actually. The concern is that it doesn't really make sense, as it changes the probability to uniform distribution along vocab dim, while in the broken cases, it is nothing can't be sampled (all probability 0 , mathematically)

next_token_scores,
torch.tensor(
torch.finfo(next_token_scores.dtype).min,
dtype=next_token_scores.dtype,
device=next_token_scores.device,
),
)

# sample
probs = nn.functional.softmax(next_token_scores, dim=-1)
probs = nn.functional.softmax(_next_token_scores, dim=-1)
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)

# finished sentences should have their next token be a padding token
Expand Down