-
Notifications
You must be signed in to change notification settings - Fork 301
Random Sampling Util for Text Generation #228
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
Merged
mattdangerw
merged 9 commits into
keras-team:master
from
jessechancy:jesse-random-sampling
Jun 21, 2022
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8be0f83
reformatted greedy search with helper functions and added random samp…
jessechancy b08d6c6
reformat files
jessechancy 9bcf5a8
split testing into two classes + minor changes
jessechancy d31020f
formatted code
jessechancy b05a01c
naming changes
jessechancy 7678560
naming changes
jessechancy bfb032d
format changes
jessechancy 0f6757d
naming changes to random_search
jessechancy 1f8cec1
removed docstring for helper and added random_search to init
jessechancy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,6 +17,35 @@ | |
import tensorflow as tf | ||
|
||
|
||
def validate_prompt(prompt): | ||
""" | ||
Helper function to validate input to text_generation utils. | ||
""" | ||
if isinstance(prompt, tf.RaggedTensor): | ||
raise ValueError( | ||
"RaggedTensor `prompt` is not supported, please " | ||
"provide `prompt` as a list or Tensor." | ||
) | ||
if not isinstance(prompt, tf.Tensor): | ||
prompt = tf.convert_to_tensor(prompt) | ||
return prompt | ||
|
||
|
||
def mask_tokens_after_end_token(prompt, max_length, end_token_id, pad_token_id): | ||
""" | ||
Helper function to mask the tokens after the end token. | ||
""" | ||
# Mask out tokens after `end_token_id` is encountered. | ||
# Find index of first end_token_id. | ||
end_indices = tf.math.argmax(prompt == end_token_id, -1) | ||
# Use max_length if no `end_token_id` is found. | ||
end_indices = tf.where(end_indices == 0, max_length, end_indices) | ||
# Build a mask including end_token and replace tokens after end_token | ||
# with `pad_token_id`. | ||
valid_indices = tf.sequence_mask(end_indices + 1, maxlen=max_length) | ||
return tf.where(valid_indices, prompt, pad_token_id) | ||
|
||
|
||
def greedy_search( | ||
token_probability_fn, | ||
prompt, | ||
|
@@ -88,13 +117,9 @@ def token_probability_fn(inputs): | |
"tf.function or run `tf.config.run_functions_eagerly(True)` to run " | ||
"tf.function in eager mode." | ||
) | ||
if isinstance(prompt, tf.RaggedTensor): | ||
raise ValueError( | ||
"RaggedTensor `prompt` is not supported, please " | ||
"provide `prompt` as a list or Tensor." | ||
) | ||
if not isinstance(prompt, tf.Tensor): | ||
prompt = tf.convert_to_tensor(prompt) | ||
|
||
prompt = validate_prompt(prompt) | ||
|
||
input_is_1d = prompt.shape.rank == 1 | ||
if input_is_1d: | ||
prompt = prompt[tf.newaxis, :] | ||
|
@@ -109,16 +134,111 @@ def token_probability_fn(inputs): | |
i += 1 | ||
|
||
if end_token_id is not None: | ||
# Mask out tokens after `end_token_id` is encountered. | ||
# Find index of first end_token_id. | ||
end_indices = tf.math.argmax(prompt == end_token_id, -1) | ||
# Use max_length if no `end_token_id` is found. | ||
end_indices = tf.where(end_indices == 0, max_length, end_indices) | ||
# Build a mask including end_token and replace tokens after end_token | ||
# with `pad_token_id`. | ||
valid_indices = tf.sequence_mask(end_indices + 1, maxlen=max_length) | ||
prompt = tf.where(valid_indices, prompt, pad_token_id) | ||
prompt = mask_tokens_after_end_token( | ||
prompt, max_length, end_token_id, pad_token_id | ||
) | ||
|
||
if input_is_1d: | ||
return tf.squeeze(prompt) | ||
return prompt | ||
|
||
|
||
def random_search( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We need to add this to the |
||
token_probability_fn, | ||
prompt, | ||
max_length, | ||
seed=None, | ||
end_token_id=None, | ||
pad_token_id=0, | ||
): | ||
""" | ||
Text generation utility based on randomly sampling the entire probability | ||
distribution. | ||
|
||
Random sampling samples the next token from the probability distribution | ||
provided by `token_probability_fn` and appends it to the existing sequence. | ||
|
||
Args: | ||
token_probability_fn: a callable, which takes in input_sequence | ||
and output the probability distribution of the next token. | ||
prompt: a list or a Tensor, can be 1D or 2D, the initial tokens to | ||
append generated tokens. | ||
max_length: int. The max length of generated text. | ||
seed: int, defaults to None. The random seed used for sampling. | ||
end_token_id: int, defaults to None. The token marking the end of the | ||
sequence, once encountered the generation is finished for the exact | ||
sequence. If None, every sequence is generated up to `max_length`. | ||
If set, all tokens after encountering `end_token_id` will be | ||
replaced with `pad_token_id`. | ||
pad_token_id: int, defaults to 0. The pad token after `end_token_id` | ||
is received. | ||
|
||
Returns: | ||
A 1D int Tensor, or 2D int Tensor representing the generated | ||
sequences. | ||
|
||
Examples: | ||
```python | ||
VOCAB_SIZE = 10 | ||
FEATURE_SIZE = 16 | ||
|
||
# Create a dummy model to predict the next token. | ||
model = tf.keras.Sequential( | ||
[ | ||
tf.keras.Input(shape=[None]), | ||
tf.keras.layers.Embedding( | ||
input_dim=VOCAB_SIZE, | ||
output_dim=FEATURE_SIZE, | ||
), | ||
tf.keras.layers.Dense(VOCAB_SIZE, activation="softmax"), | ||
] | ||
) | ||
|
||
# Define a function that outputs the next token's probability given the | ||
# input sequence. | ||
def token_probability_fn(inputs): | ||
return model(inputs)[:, -1, :] | ||
|
||
prompt = tf.random.uniform(shape=[5, 5], maxval=VOCAB_SIZE, dtype=tf.int64) | ||
|
||
# Print the generated sequence (token ids). | ||
keras_nlp.utils.random_sampling( | ||
token_probability_fn, | ||
prompt, | ||
max_length=10, | ||
end_token_id=0,) | ||
``` | ||
|
||
""" | ||
if not tf.executing_eagerly(): | ||
raise RuntimeError( | ||
"`keras_nlp.utils.random_sampling` currently requires an eager " | ||
"execution context. Please call `random_sampling` outside " | ||
"tf.function or run `tf.config.run_functions_eagerly(True)` to run " | ||
"tf.function in eager mode." | ||
) | ||
|
||
prompt = validate_prompt(prompt) | ||
input_is_1d = prompt.shape.rank == 1 | ||
if input_is_1d: | ||
prompt = prompt[tf.newaxis, :] | ||
|
||
i = prompt.shape[1] | ||
while i < max_length: | ||
# If the prompt has reached our desired length, exit while loop. | ||
pred = token_probability_fn(prompt) | ||
next_token = tf.cast( | ||
tf.random.categorical(tf.math.log(pred), 1, seed=seed), | ||
chenmoneygithub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dtype=prompt.dtype, | ||
) | ||
# Append the next token to current sequence. | ||
prompt = tf.concat([prompt, next_token], axis=-1) | ||
i += 1 | ||
|
||
if end_token_id is not None: | ||
prompt = mask_tokens_after_end_token( | ||
prompt, max_length, end_token_id, pad_token_id | ||
) | ||
if input_is_1d: | ||
return tf.squeeze(prompt) | ||
return prompt |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Hmm, with the whole docstring for a helper it's hard to tell it's just a helper function. In general I don't think you would need the whole args/return structure for something small like this.
Just
Helper function to validate input to text_generation utils.