|
| 1 | +# Copyright 2022 The KerasNLP Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Greedy Sampler.""" |
| 15 | + |
| 16 | +import tensorflow as tf |
| 17 | +from tensorflow import keras |
| 18 | + |
| 19 | +from keras_nlp.samplers.sampler import Sampler |
| 20 | +from keras_nlp.samplers.sampler import base_sampler_keyword_args |
| 21 | +from keras_nlp.samplers.sampler import call_keyword_docstring |
| 22 | +from keras_nlp.samplers.sampler import sample_keyword_docstring |
| 23 | + |
| 24 | + |
| 25 | +class BeamSampler(Sampler): |
| 26 | + """Beam Sampler class. |
| 27 | +
|
| 28 | + This sampler implements beam search algorithm. |
| 29 | +
|
| 30 | + Args: |
| 31 | + {{base_sampler_keyword_args}} |
| 32 | +
|
| 33 | + Call Args: |
| 34 | + {{call_keyword_args}} |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + num_beams, |
| 40 | + seed=None, |
| 41 | + from_logits=False, |
| 42 | + end_token_id=None, |
| 43 | + pad_token_id=0, |
| 44 | + jit_compile=True, |
| 45 | + ): |
| 46 | + self.num_beams = num_beams |
| 47 | + self.seed = seed |
| 48 | + self.from_logits = from_logits |
| 49 | + super().__init__(end_token_id, pad_token_id, jit_compile) |
| 50 | + |
| 51 | + def sample(self, token_probability_fn, prompt, mask, num_steps): |
| 52 | + """Sampler's logic implementation. |
| 53 | +
|
| 54 | + Args: |
| 55 | + {{call_keyword_docstring}} |
| 56 | + """ |
| 57 | + batch_size, max_length = tf.shape(prompt)[0], tf.shape(prompt)[1] |
| 58 | + max_length = tf.cast(max_length, num_steps.dtype) |
| 59 | + length = max_length - num_steps |
| 60 | + dummy_preds = self._validate_token_probability_fn( |
| 61 | + token_probability_fn, prompt, mask |
| 62 | + ) |
| 63 | + vocab_size = dummy_preds.shape[-1] |
| 64 | + pred_dtype = dummy_preds.dtype |
| 65 | + |
| 66 | + num_beams = self.num_beams |
| 67 | + |
| 68 | + # Initialize beam with shape `(batch_size, num_beams, length)`. |
| 69 | + beams = tf.repeat(tf.expand_dims(prompt, axis=1), num_beams, axis=1) |
| 70 | + # Initialize `beams_prob` with shape `(batch_size, num_beams)`. |
| 71 | + beams_prob = tf.zeros([batch_size, 1], dtype=pred_dtype) |
| 72 | + beams_prob = tf.concat( |
| 73 | + [beams_prob, tf.fill((batch_size, num_beams - 1), pred_dtype.min)], |
| 74 | + axis=-1, |
| 75 | + ) |
| 76 | + |
| 77 | + def one_step(beams, beams_prob, length): |
| 78 | + truncated_beams = beams[..., :length] |
| 79 | + |
| 80 | + flattened_beams = tf.reshape( |
| 81 | + truncated_beams, shape=[batch_size * num_beams, -1] |
| 82 | + ) |
| 83 | + preds = token_probability_fn(flattened_beams) |
| 84 | + if self.from_logits: |
| 85 | + preds = keras.activations.softmax(preds, axis=-1) |
| 86 | + # Reshape `preds` to shape `(batch_size, num_beams * vocab_size)`. |
| 87 | + preds = tf.reshape(preds, shape=[batch_size, -1]) |
| 88 | + |
| 89 | + probs = tf.math.log(preds) + tf.repeat( |
| 90 | + beams_prob, repeats=vocab_size, axis=1 |
| 91 | + ) |
| 92 | + |
| 93 | + candidate_prob, candidate_indexes = tf.math.top_k( |
| 94 | + probs, k=num_beams, sorted=False |
| 95 | + ) |
| 96 | + candidate_beam_indexes = candidate_indexes // vocab_size |
| 97 | + next_token = candidate_indexes % vocab_size |
| 98 | + |
| 99 | + beams = tf.gather( |
| 100 | + beams, candidate_beam_indexes, axis=1, batch_dims=1 |
| 101 | + ) |
| 102 | + |
| 103 | + # Build a new column of updates to scatter into the beam tensor. |
| 104 | + next_token = tf.where( |
| 105 | + condition=mask[..., length, tf.newaxis], |
| 106 | + x=beams[..., length], |
| 107 | + y=next_token, |
| 108 | + ) |
| 109 | + next_token = tf.reshape(next_token, shape=[-1]) |
| 110 | + |
| 111 | + # Generate `(batch_index, beam_index)` tuples for each beam. |
| 112 | + beam_indices = tf.where(tf.ones((batch_size, num_beams), tf.bool)) |
| 113 | + beam_indices = tf.cast(beam_indices, dtype=length.dtype) |
| 114 | + # Build a tensor of repeated `length` values. |
| 115 | + length_indices = tf.fill((batch_size * num_beams, 1), length) |
| 116 | + # Concatenate to a triplet of `(batch_index, beam_index, length)`. |
| 117 | + indices = tf.concat([beam_indices, length_indices], axis=-1) |
| 118 | + |
| 119 | + # Update `beams[:, :, length]` with `next_token`. |
| 120 | + beams = tf.tensor_scatter_nd_update( |
| 121 | + tensor=beams, |
| 122 | + indices=indices, |
| 123 | + updates=next_token, |
| 124 | + ) |
| 125 | + |
| 126 | + beams_prob = candidate_prob |
| 127 | + length = tf.add(length, 1) |
| 128 | + |
| 129 | + return beams, beams_prob, length |
| 130 | + |
| 131 | + # Run a while loop till text of length `max_length` has been generated. |
| 132 | + beams, beams_prob, length = tf.while_loop( |
| 133 | + cond=lambda beams, beams_prob, length: tf.less(length, max_length), |
| 134 | + body=one_step, |
| 135 | + loop_vars=(beams, beams_prob, length), |
| 136 | + ) |
| 137 | + |
| 138 | + # Get the beam with the maximum probability. |
| 139 | + max_indexes = tf.math.argmax(beams_prob, axis=-1) |
| 140 | + max_beams = tf.gather( |
| 141 | + beams, max_indexes[:, tf.newaxis], axis=1, batch_dims=1 |
| 142 | + ) |
| 143 | + prompt = tf.squeeze(max_beams) |
| 144 | + |
| 145 | + return prompt |
| 146 | + |
| 147 | + |
| 148 | +BeamSampler.__doc__ = BeamSampler.__doc__.replace( |
| 149 | + "{{base_sampler_keyword_args}}", base_sampler_keyword_args |
| 150 | +) |
| 151 | +BeamSampler.__doc__ = BeamSampler.__doc__.replace( |
| 152 | + "{{call_keyword_docstring}}", call_keyword_docstring |
| 153 | +) |
| 154 | +BeamSampler.sample.__doc__ = BeamSampler.sample.__doc__.replace( |
| 155 | + "{{sample_keyword_docstring}}", sample_keyword_docstring |
| 156 | +) |
0 commit comments