-
Notifications
You must be signed in to change notification settings - Fork 1k
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
Feature/top p sampling #1360
Feature/top p sampling #1360
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks great, thanks a lot! Only a few minor points from my side below:
Thanks for all the updates and fixes. It looks all great to me now. |
Thank you @rasbt: i had missed your comment |
No worries at all, I also thought it was probably quicker to just add instead of explain 😅 |
def test_generate_different_results_with_different_top_p(): | ||
config = Config(block_size=128, vocab_size=16, n_layer=1, n_head=4, n_embd=8) | ||
model = GPT(config) | ||
model.max_seq_length = 50 | ||
model.set_kv_cache(batch_size=1) | ||
|
||
torch.manual_seed(123) | ||
input_idx = torch.randint(10, size=(1,)) | ||
|
||
output1 = generate.generate(model, input_idx, 20, top_p=1.0) | ||
output2 = generate.generate(model, input_idx, 20, top_p=0.1) | ||
|
||
assert not torch.equal(output1, output2) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This test is not useful because it will also pass if you set the same top_p. That's because multinomial
advances the rng state.
For it to achieve the intended result, you need to seed before each call
torch.manual_seed(123)
input_idx = torch.randint(10, size=(1,))
torch.manual_seed(123)
output1 = generate.generate(model, input_idx, 20, top_p=1.0)
torch.manual_seed(123)
output2 = generate.generate(model, input_idx, 20, top_p=0.1)
cc @rasbt
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
arg, thanks!
This PR adds the nucleus-sampling (aka top-p sampling) as specified from https://arxiv.org/abs/1904.09751.
In top-p sampling the next token is chosen from the smallest set of tokens with a cumulative probability greater than
top-p
, i.e. by selecting the highest probability tokens whose cumulative probability exceeds thetop-p
threshold.