keras-hub-nightly 0.15.0.dev20240823171555__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- keras_hub/__init__.py +52 -0
- keras_hub/api/__init__.py +27 -0
- keras_hub/api/layers/__init__.py +47 -0
- keras_hub/api/metrics/__init__.py +24 -0
- keras_hub/api/models/__init__.py +249 -0
- keras_hub/api/samplers/__init__.py +29 -0
- keras_hub/api/tokenizers/__init__.py +35 -0
- keras_hub/src/__init__.py +13 -0
- keras_hub/src/api_export.py +53 -0
- keras_hub/src/layers/__init__.py +13 -0
- keras_hub/src/layers/modeling/__init__.py +13 -0
- keras_hub/src/layers/modeling/alibi_bias.py +143 -0
- keras_hub/src/layers/modeling/cached_multi_head_attention.py +137 -0
- keras_hub/src/layers/modeling/f_net_encoder.py +200 -0
- keras_hub/src/layers/modeling/masked_lm_head.py +239 -0
- keras_hub/src/layers/modeling/position_embedding.py +123 -0
- keras_hub/src/layers/modeling/reversible_embedding.py +311 -0
- keras_hub/src/layers/modeling/rotary_embedding.py +169 -0
- keras_hub/src/layers/modeling/sine_position_encoding.py +108 -0
- keras_hub/src/layers/modeling/token_and_position_embedding.py +150 -0
- keras_hub/src/layers/modeling/transformer_decoder.py +496 -0
- keras_hub/src/layers/modeling/transformer_encoder.py +262 -0
- keras_hub/src/layers/modeling/transformer_layer_utils.py +106 -0
- keras_hub/src/layers/preprocessing/__init__.py +13 -0
- keras_hub/src/layers/preprocessing/masked_lm_mask_generator.py +220 -0
- keras_hub/src/layers/preprocessing/multi_segment_packer.py +319 -0
- keras_hub/src/layers/preprocessing/preprocessing_layer.py +62 -0
- keras_hub/src/layers/preprocessing/random_deletion.py +271 -0
- keras_hub/src/layers/preprocessing/random_swap.py +267 -0
- keras_hub/src/layers/preprocessing/start_end_packer.py +219 -0
- keras_hub/src/metrics/__init__.py +13 -0
- keras_hub/src/metrics/bleu.py +394 -0
- keras_hub/src/metrics/edit_distance.py +197 -0
- keras_hub/src/metrics/perplexity.py +181 -0
- keras_hub/src/metrics/rouge_base.py +204 -0
- keras_hub/src/metrics/rouge_l.py +97 -0
- keras_hub/src/metrics/rouge_n.py +125 -0
- keras_hub/src/models/__init__.py +13 -0
- keras_hub/src/models/albert/__init__.py +20 -0
- keras_hub/src/models/albert/albert_backbone.py +267 -0
- keras_hub/src/models/albert/albert_classifier.py +202 -0
- keras_hub/src/models/albert/albert_masked_lm.py +129 -0
- keras_hub/src/models/albert/albert_masked_lm_preprocessor.py +194 -0
- keras_hub/src/models/albert/albert_preprocessor.py +206 -0
- keras_hub/src/models/albert/albert_presets.py +70 -0
- keras_hub/src/models/albert/albert_tokenizer.py +119 -0
- keras_hub/src/models/backbone.py +311 -0
- keras_hub/src/models/bart/__init__.py +20 -0
- keras_hub/src/models/bart/bart_backbone.py +261 -0
- keras_hub/src/models/bart/bart_preprocessor.py +276 -0
- keras_hub/src/models/bart/bart_presets.py +74 -0
- keras_hub/src/models/bart/bart_seq_2_seq_lm.py +490 -0
- keras_hub/src/models/bart/bart_seq_2_seq_lm_preprocessor.py +262 -0
- keras_hub/src/models/bart/bart_tokenizer.py +124 -0
- keras_hub/src/models/bert/__init__.py +23 -0
- keras_hub/src/models/bert/bert_backbone.py +227 -0
- keras_hub/src/models/bert/bert_classifier.py +183 -0
- keras_hub/src/models/bert/bert_masked_lm.py +131 -0
- keras_hub/src/models/bert/bert_masked_lm_preprocessor.py +198 -0
- keras_hub/src/models/bert/bert_preprocessor.py +184 -0
- keras_hub/src/models/bert/bert_presets.py +147 -0
- keras_hub/src/models/bert/bert_tokenizer.py +112 -0
- keras_hub/src/models/bloom/__init__.py +20 -0
- keras_hub/src/models/bloom/bloom_attention.py +186 -0
- keras_hub/src/models/bloom/bloom_backbone.py +173 -0
- keras_hub/src/models/bloom/bloom_causal_lm.py +298 -0
- keras_hub/src/models/bloom/bloom_causal_lm_preprocessor.py +176 -0
- keras_hub/src/models/bloom/bloom_decoder.py +206 -0
- keras_hub/src/models/bloom/bloom_preprocessor.py +185 -0
- keras_hub/src/models/bloom/bloom_presets.py +121 -0
- keras_hub/src/models/bloom/bloom_tokenizer.py +116 -0
- keras_hub/src/models/causal_lm.py +383 -0
- keras_hub/src/models/classifier.py +109 -0
- keras_hub/src/models/csp_darknet/__init__.py +13 -0
- keras_hub/src/models/csp_darknet/csp_darknet_backbone.py +410 -0
- keras_hub/src/models/csp_darknet/csp_darknet_image_classifier.py +133 -0
- keras_hub/src/models/deberta_v3/__init__.py +24 -0
- keras_hub/src/models/deberta_v3/deberta_v3_backbone.py +210 -0
- keras_hub/src/models/deberta_v3/deberta_v3_classifier.py +228 -0
- keras_hub/src/models/deberta_v3/deberta_v3_masked_lm.py +135 -0
- keras_hub/src/models/deberta_v3/deberta_v3_masked_lm_preprocessor.py +191 -0
- keras_hub/src/models/deberta_v3/deberta_v3_preprocessor.py +206 -0
- keras_hub/src/models/deberta_v3/deberta_v3_presets.py +82 -0
- keras_hub/src/models/deberta_v3/deberta_v3_tokenizer.py +155 -0
- keras_hub/src/models/deberta_v3/disentangled_attention_encoder.py +227 -0
- keras_hub/src/models/deberta_v3/disentangled_self_attention.py +412 -0
- keras_hub/src/models/deberta_v3/relative_embedding.py +94 -0
- keras_hub/src/models/densenet/__init__.py +13 -0
- keras_hub/src/models/densenet/densenet_backbone.py +210 -0
- keras_hub/src/models/densenet/densenet_image_classifier.py +131 -0
- keras_hub/src/models/distil_bert/__init__.py +26 -0
- keras_hub/src/models/distil_bert/distil_bert_backbone.py +187 -0
- keras_hub/src/models/distil_bert/distil_bert_classifier.py +208 -0
- keras_hub/src/models/distil_bert/distil_bert_masked_lm.py +137 -0
- keras_hub/src/models/distil_bert/distil_bert_masked_lm_preprocessor.py +194 -0
- keras_hub/src/models/distil_bert/distil_bert_preprocessor.py +175 -0
- keras_hub/src/models/distil_bert/distil_bert_presets.py +57 -0
- keras_hub/src/models/distil_bert/distil_bert_tokenizer.py +114 -0
- keras_hub/src/models/electra/__init__.py +20 -0
- keras_hub/src/models/electra/electra_backbone.py +247 -0
- keras_hub/src/models/electra/electra_preprocessor.py +154 -0
- keras_hub/src/models/electra/electra_presets.py +95 -0
- keras_hub/src/models/electra/electra_tokenizer.py +104 -0
- keras_hub/src/models/f_net/__init__.py +20 -0
- keras_hub/src/models/f_net/f_net_backbone.py +236 -0
- keras_hub/src/models/f_net/f_net_classifier.py +154 -0
- keras_hub/src/models/f_net/f_net_masked_lm.py +132 -0
- keras_hub/src/models/f_net/f_net_masked_lm_preprocessor.py +196 -0
- keras_hub/src/models/f_net/f_net_preprocessor.py +177 -0
- keras_hub/src/models/f_net/f_net_presets.py +43 -0
- keras_hub/src/models/f_net/f_net_tokenizer.py +95 -0
- keras_hub/src/models/falcon/__init__.py +20 -0
- keras_hub/src/models/falcon/falcon_attention.py +156 -0
- keras_hub/src/models/falcon/falcon_backbone.py +164 -0
- keras_hub/src/models/falcon/falcon_causal_lm.py +291 -0
- keras_hub/src/models/falcon/falcon_causal_lm_preprocessor.py +173 -0
- keras_hub/src/models/falcon/falcon_preprocessor.py +187 -0
- keras_hub/src/models/falcon/falcon_presets.py +30 -0
- keras_hub/src/models/falcon/falcon_tokenizer.py +110 -0
- keras_hub/src/models/falcon/falcon_transformer_decoder.py +255 -0
- keras_hub/src/models/feature_pyramid_backbone.py +73 -0
- keras_hub/src/models/gemma/__init__.py +20 -0
- keras_hub/src/models/gemma/gemma_attention.py +250 -0
- keras_hub/src/models/gemma/gemma_backbone.py +316 -0
- keras_hub/src/models/gemma/gemma_causal_lm.py +448 -0
- keras_hub/src/models/gemma/gemma_causal_lm_preprocessor.py +167 -0
- keras_hub/src/models/gemma/gemma_decoder_block.py +241 -0
- keras_hub/src/models/gemma/gemma_preprocessor.py +191 -0
- keras_hub/src/models/gemma/gemma_presets.py +248 -0
- keras_hub/src/models/gemma/gemma_tokenizer.py +103 -0
- keras_hub/src/models/gemma/rms_normalization.py +40 -0
- keras_hub/src/models/gpt2/__init__.py +20 -0
- keras_hub/src/models/gpt2/gpt2_backbone.py +199 -0
- keras_hub/src/models/gpt2/gpt2_causal_lm.py +437 -0
- keras_hub/src/models/gpt2/gpt2_causal_lm_preprocessor.py +173 -0
- keras_hub/src/models/gpt2/gpt2_preprocessor.py +187 -0
- keras_hub/src/models/gpt2/gpt2_presets.py +82 -0
- keras_hub/src/models/gpt2/gpt2_tokenizer.py +110 -0
- keras_hub/src/models/gpt_neo_x/__init__.py +13 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_attention.py +251 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_backbone.py +175 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_causal_lm.py +201 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_causal_lm_preprocessor.py +141 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_decoder.py +258 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_preprocessor.py +145 -0
- keras_hub/src/models/gpt_neo_x/gpt_neo_x_tokenizer.py +88 -0
- keras_hub/src/models/image_classifier.py +90 -0
- keras_hub/src/models/llama/__init__.py +20 -0
- keras_hub/src/models/llama/llama_attention.py +225 -0
- keras_hub/src/models/llama/llama_backbone.py +188 -0
- keras_hub/src/models/llama/llama_causal_lm.py +327 -0
- keras_hub/src/models/llama/llama_causal_lm_preprocessor.py +170 -0
- keras_hub/src/models/llama/llama_decoder.py +246 -0
- keras_hub/src/models/llama/llama_layernorm.py +48 -0
- keras_hub/src/models/llama/llama_preprocessor.py +189 -0
- keras_hub/src/models/llama/llama_presets.py +80 -0
- keras_hub/src/models/llama/llama_tokenizer.py +84 -0
- keras_hub/src/models/llama3/__init__.py +20 -0
- keras_hub/src/models/llama3/llama3_backbone.py +84 -0
- keras_hub/src/models/llama3/llama3_causal_lm.py +46 -0
- keras_hub/src/models/llama3/llama3_causal_lm_preprocessor.py +173 -0
- keras_hub/src/models/llama3/llama3_preprocessor.py +21 -0
- keras_hub/src/models/llama3/llama3_presets.py +69 -0
- keras_hub/src/models/llama3/llama3_tokenizer.py +63 -0
- keras_hub/src/models/masked_lm.py +101 -0
- keras_hub/src/models/mistral/__init__.py +20 -0
- keras_hub/src/models/mistral/mistral_attention.py +238 -0
- keras_hub/src/models/mistral/mistral_backbone.py +203 -0
- keras_hub/src/models/mistral/mistral_causal_lm.py +328 -0
- keras_hub/src/models/mistral/mistral_causal_lm_preprocessor.py +175 -0
- keras_hub/src/models/mistral/mistral_layer_norm.py +48 -0
- keras_hub/src/models/mistral/mistral_preprocessor.py +190 -0
- keras_hub/src/models/mistral/mistral_presets.py +48 -0
- keras_hub/src/models/mistral/mistral_tokenizer.py +82 -0
- keras_hub/src/models/mistral/mistral_transformer_decoder.py +265 -0
- keras_hub/src/models/mix_transformer/__init__.py +13 -0
- keras_hub/src/models/mix_transformer/mix_transformer_backbone.py +181 -0
- keras_hub/src/models/mix_transformer/mix_transformer_classifier.py +133 -0
- keras_hub/src/models/mix_transformer/mix_transformer_layers.py +300 -0
- keras_hub/src/models/opt/__init__.py +20 -0
- keras_hub/src/models/opt/opt_backbone.py +173 -0
- keras_hub/src/models/opt/opt_causal_lm.py +301 -0
- keras_hub/src/models/opt/opt_causal_lm_preprocessor.py +177 -0
- keras_hub/src/models/opt/opt_preprocessor.py +188 -0
- keras_hub/src/models/opt/opt_presets.py +72 -0
- keras_hub/src/models/opt/opt_tokenizer.py +116 -0
- keras_hub/src/models/pali_gemma/__init__.py +23 -0
- keras_hub/src/models/pali_gemma/pali_gemma_backbone.py +277 -0
- keras_hub/src/models/pali_gemma/pali_gemma_causal_lm.py +313 -0
- keras_hub/src/models/pali_gemma/pali_gemma_causal_lm_preprocessor.py +147 -0
- keras_hub/src/models/pali_gemma/pali_gemma_decoder_block.py +160 -0
- keras_hub/src/models/pali_gemma/pali_gemma_presets.py +78 -0
- keras_hub/src/models/pali_gemma/pali_gemma_tokenizer.py +79 -0
- keras_hub/src/models/pali_gemma/pali_gemma_vit.py +566 -0
- keras_hub/src/models/phi3/__init__.py +20 -0
- keras_hub/src/models/phi3/phi3_attention.py +260 -0
- keras_hub/src/models/phi3/phi3_backbone.py +224 -0
- keras_hub/src/models/phi3/phi3_causal_lm.py +218 -0
- keras_hub/src/models/phi3/phi3_causal_lm_preprocessor.py +173 -0
- keras_hub/src/models/phi3/phi3_decoder.py +260 -0
- keras_hub/src/models/phi3/phi3_layernorm.py +48 -0
- keras_hub/src/models/phi3/phi3_preprocessor.py +190 -0
- keras_hub/src/models/phi3/phi3_presets.py +50 -0
- keras_hub/src/models/phi3/phi3_rotary_embedding.py +137 -0
- keras_hub/src/models/phi3/phi3_tokenizer.py +94 -0
- keras_hub/src/models/preprocessor.py +207 -0
- keras_hub/src/models/resnet/__init__.py +13 -0
- keras_hub/src/models/resnet/resnet_backbone.py +612 -0
- keras_hub/src/models/resnet/resnet_image_classifier.py +136 -0
- keras_hub/src/models/roberta/__init__.py +20 -0
- keras_hub/src/models/roberta/roberta_backbone.py +184 -0
- keras_hub/src/models/roberta/roberta_classifier.py +209 -0
- keras_hub/src/models/roberta/roberta_masked_lm.py +136 -0
- keras_hub/src/models/roberta/roberta_masked_lm_preprocessor.py +198 -0
- keras_hub/src/models/roberta/roberta_preprocessor.py +192 -0
- keras_hub/src/models/roberta/roberta_presets.py +43 -0
- keras_hub/src/models/roberta/roberta_tokenizer.py +132 -0
- keras_hub/src/models/seq_2_seq_lm.py +54 -0
- keras_hub/src/models/t5/__init__.py +20 -0
- keras_hub/src/models/t5/t5_backbone.py +261 -0
- keras_hub/src/models/t5/t5_layer_norm.py +35 -0
- keras_hub/src/models/t5/t5_multi_head_attention.py +324 -0
- keras_hub/src/models/t5/t5_presets.py +95 -0
- keras_hub/src/models/t5/t5_tokenizer.py +100 -0
- keras_hub/src/models/t5/t5_transformer_layer.py +178 -0
- keras_hub/src/models/task.py +419 -0
- keras_hub/src/models/vgg/__init__.py +13 -0
- keras_hub/src/models/vgg/vgg_backbone.py +158 -0
- keras_hub/src/models/vgg/vgg_image_classifier.py +124 -0
- keras_hub/src/models/vit_det/__init__.py +13 -0
- keras_hub/src/models/vit_det/vit_det_backbone.py +204 -0
- keras_hub/src/models/vit_det/vit_layers.py +565 -0
- keras_hub/src/models/whisper/__init__.py +20 -0
- keras_hub/src/models/whisper/whisper_audio_feature_extractor.py +260 -0
- keras_hub/src/models/whisper/whisper_backbone.py +305 -0
- keras_hub/src/models/whisper/whisper_cached_multi_head_attention.py +153 -0
- keras_hub/src/models/whisper/whisper_decoder.py +141 -0
- keras_hub/src/models/whisper/whisper_encoder.py +106 -0
- keras_hub/src/models/whisper/whisper_preprocessor.py +326 -0
- keras_hub/src/models/whisper/whisper_presets.py +148 -0
- keras_hub/src/models/whisper/whisper_tokenizer.py +163 -0
- keras_hub/src/models/xlm_roberta/__init__.py +26 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_backbone.py +81 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_classifier.py +225 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_masked_lm.py +141 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_masked_lm_preprocessor.py +195 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_preprocessor.py +205 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_presets.py +43 -0
- keras_hub/src/models/xlm_roberta/xlm_roberta_tokenizer.py +191 -0
- keras_hub/src/models/xlnet/__init__.py +13 -0
- keras_hub/src/models/xlnet/relative_attention.py +459 -0
- keras_hub/src/models/xlnet/xlnet_backbone.py +222 -0
- keras_hub/src/models/xlnet/xlnet_content_and_query_embedding.py +133 -0
- keras_hub/src/models/xlnet/xlnet_encoder.py +378 -0
- keras_hub/src/samplers/__init__.py +13 -0
- keras_hub/src/samplers/beam_sampler.py +207 -0
- keras_hub/src/samplers/contrastive_sampler.py +231 -0
- keras_hub/src/samplers/greedy_sampler.py +50 -0
- keras_hub/src/samplers/random_sampler.py +77 -0
- keras_hub/src/samplers/sampler.py +237 -0
- keras_hub/src/samplers/serialization.py +97 -0
- keras_hub/src/samplers/top_k_sampler.py +92 -0
- keras_hub/src/samplers/top_p_sampler.py +113 -0
- keras_hub/src/tests/__init__.py +13 -0
- keras_hub/src/tests/test_case.py +608 -0
- keras_hub/src/tokenizers/__init__.py +13 -0
- keras_hub/src/tokenizers/byte_pair_tokenizer.py +638 -0
- keras_hub/src/tokenizers/byte_tokenizer.py +299 -0
- keras_hub/src/tokenizers/sentence_piece_tokenizer.py +267 -0
- keras_hub/src/tokenizers/sentence_piece_tokenizer_trainer.py +150 -0
- keras_hub/src/tokenizers/tokenizer.py +235 -0
- keras_hub/src/tokenizers/unicode_codepoint_tokenizer.py +355 -0
- keras_hub/src/tokenizers/word_piece_tokenizer.py +544 -0
- keras_hub/src/tokenizers/word_piece_tokenizer_trainer.py +176 -0
- keras_hub/src/utils/__init__.py +13 -0
- keras_hub/src/utils/keras_utils.py +130 -0
- keras_hub/src/utils/pipeline_model.py +293 -0
- keras_hub/src/utils/preset_utils.py +621 -0
- keras_hub/src/utils/python_utils.py +21 -0
- keras_hub/src/utils/tensor_utils.py +206 -0
- keras_hub/src/utils/timm/__init__.py +13 -0
- keras_hub/src/utils/timm/convert.py +37 -0
- keras_hub/src/utils/timm/convert_resnet.py +171 -0
- keras_hub/src/utils/transformers/__init__.py +13 -0
- keras_hub/src/utils/transformers/convert.py +101 -0
- keras_hub/src/utils/transformers/convert_bert.py +173 -0
- keras_hub/src/utils/transformers/convert_distilbert.py +184 -0
- keras_hub/src/utils/transformers/convert_gemma.py +187 -0
- keras_hub/src/utils/transformers/convert_gpt2.py +186 -0
- keras_hub/src/utils/transformers/convert_llama3.py +136 -0
- keras_hub/src/utils/transformers/convert_pali_gemma.py +303 -0
- keras_hub/src/utils/transformers/safetensor_utils.py +97 -0
- keras_hub/src/version_utils.py +23 -0
- keras_hub_nightly-0.15.0.dev20240823171555.dist-info/METADATA +34 -0
- keras_hub_nightly-0.15.0.dev20240823171555.dist-info/RECORD +297 -0
- keras_hub_nightly-0.15.0.dev20240823171555.dist-info/WHEEL +5 -0
- keras_hub_nightly-0.15.0.dev20240823171555.dist-info/top_level.txt +1 -0
@@ -0,0 +1,207 @@
|
|
1
|
+
# Copyright 2024 The KerasHub 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
|
+
|
15
|
+
import keras
|
16
|
+
from keras import ops
|
17
|
+
from keras import tree
|
18
|
+
|
19
|
+
from keras_hub.src.api_export import keras_hub_export
|
20
|
+
from keras_hub.src.samplers.sampler import Sampler
|
21
|
+
from keras_hub.src.utils.tensor_utils import any_equal
|
22
|
+
|
23
|
+
|
24
|
+
@keras_hub_export("keras_hub.samplers.BeamSampler")
|
25
|
+
class BeamSampler(Sampler):
|
26
|
+
"""Beam Sampler class.
|
27
|
+
|
28
|
+
This sampler implements beam search algorithm. At each time-step, beam
|
29
|
+
search keeps the beams (sequences) of the top `num_beams` highest
|
30
|
+
accumulated probabilities, and uses each one of the beams to predict
|
31
|
+
candidate next tokens.
|
32
|
+
|
33
|
+
Args:
|
34
|
+
num_beams: int. The number of beams that should be kept at each
|
35
|
+
time-step. `num_beams` should be strictly positive.
|
36
|
+
return_all_beams: bool. When set to `True`, the sampler will return all
|
37
|
+
beams and their respective probabilities score.
|
38
|
+
|
39
|
+
Call arguments:
|
40
|
+
{{call_args}}
|
41
|
+
|
42
|
+
Examples:
|
43
|
+
```python
|
44
|
+
causal_lm = keras_hub.models.GPT2CausalLM.from_preset("gpt2_base_en")
|
45
|
+
|
46
|
+
# Pass by name to compile.
|
47
|
+
causal_lm.compile(sampler="beam")
|
48
|
+
causal_lm.generate(["Keras is a"])
|
49
|
+
|
50
|
+
# Pass by object to compile.
|
51
|
+
sampler = keras_hub.samplers.BeamSampler(num_beams=5)
|
52
|
+
causal_lm.compile(sampler=sampler)
|
53
|
+
causal_lm.generate(["Keras is a"])
|
54
|
+
```
|
55
|
+
"""
|
56
|
+
|
57
|
+
def __init__(
|
58
|
+
self,
|
59
|
+
num_beams=5,
|
60
|
+
return_all_beams=False,
|
61
|
+
**kwargs,
|
62
|
+
):
|
63
|
+
super().__init__(**kwargs)
|
64
|
+
self.num_beams = num_beams
|
65
|
+
self.return_all_beams = return_all_beams
|
66
|
+
|
67
|
+
def __call__(
|
68
|
+
self,
|
69
|
+
next,
|
70
|
+
prompt,
|
71
|
+
cache=None,
|
72
|
+
index=0,
|
73
|
+
mask=None,
|
74
|
+
stop_token_ids=None,
|
75
|
+
hidden_states=None,
|
76
|
+
model=None,
|
77
|
+
):
|
78
|
+
batch_size, max_length = ops.shape(prompt)[0], ops.shape(prompt)[1]
|
79
|
+
index = ops.cast(index, "int32")
|
80
|
+
|
81
|
+
def create_beams(x):
|
82
|
+
"""Add initial beam state."""
|
83
|
+
return ops.repeat(x, self.num_beams, axis=0)
|
84
|
+
|
85
|
+
def flatten_beams(x):
|
86
|
+
"""Combine the beam dim and batch dim."""
|
87
|
+
flat_shape = (batch_size * self.num_beams,) + ops.shape(x)[2:]
|
88
|
+
return ops.reshape(x, flat_shape)
|
89
|
+
|
90
|
+
def unflatten_beams(x):
|
91
|
+
"""Separate the beam dim and batch dim."""
|
92
|
+
unflat_shape = (batch_size, self.num_beams) + ops.shape(x)[1:]
|
93
|
+
return ops.reshape(x, unflat_shape)
|
94
|
+
|
95
|
+
if mask is None:
|
96
|
+
mask = ops.zeros_like(prompt, dtype="bool")
|
97
|
+
else:
|
98
|
+
mask = ops.cast(mask, dtype="bool")
|
99
|
+
# `ops.while_loop` will not accept `None` as a value for `loop_vars`.
|
100
|
+
has_cache = cache is not None
|
101
|
+
cache = cache if has_cache else ()
|
102
|
+
# Add extra sequences for each beam.
|
103
|
+
prompt, mask = create_beams(prompt), create_beams(mask)
|
104
|
+
cache = tree.map_structure(create_beams, cache)
|
105
|
+
# Setup the initial beam log-likelihoods.
|
106
|
+
# On the first loop, make sure only the original beam is considered.
|
107
|
+
log_probs = ops.array(
|
108
|
+
[[0.0] + [-1e9] * (self.num_beams - 1)], dtype="float32"
|
109
|
+
)
|
110
|
+
log_probs = flatten_beams(ops.repeat(log_probs, batch_size, axis=0))
|
111
|
+
|
112
|
+
def cond(prompt, cache, index, log_probs):
|
113
|
+
if stop_token_ids is None:
|
114
|
+
return True
|
115
|
+
# Stop if all sequences have produced a *new* stop token.
|
116
|
+
end_tokens = any_equal(prompt, stop_token_ids, ~mask)
|
117
|
+
prompt_done = ops.any(end_tokens, axis=-1)
|
118
|
+
return ops.logical_not(ops.all(prompt_done))
|
119
|
+
|
120
|
+
def body(prompt, cache, index, log_probs):
|
121
|
+
# Compute the softmax distribution for the next token.
|
122
|
+
logits, _, cache = next(prompt, cache, index)
|
123
|
+
vocab_size = ops.shape(logits)[-1]
|
124
|
+
probs = self.compute_probabilities(logits)
|
125
|
+
|
126
|
+
# Compute the running log-likelihood of each new candidate.
|
127
|
+
next_log_probs = ops.log(probs) + log_probs[..., None]
|
128
|
+
# Reshape `preds` to shape `(batch_size, num_beams * vocab_size)`.
|
129
|
+
next_log_probs = ops.reshape(next_log_probs, [batch_size, -1])
|
130
|
+
|
131
|
+
# Compute the top beam indices and next tokens.
|
132
|
+
next_log_probs, indices = ops.top_k(
|
133
|
+
next_log_probs, k=self.num_beams, sorted=False
|
134
|
+
)
|
135
|
+
beam_indices = indices // vocab_size
|
136
|
+
next_token = flatten_beams(indices % vocab_size)
|
137
|
+
# We need `ensure_shape` as `top_k` will change the static shape.
|
138
|
+
next_log_probs = flatten_beams(next_log_probs)
|
139
|
+
if keras.config.backend() == "tensorflow":
|
140
|
+
# Work around for bug in top_k output shape on tf backend.
|
141
|
+
import tensorflow as tf
|
142
|
+
|
143
|
+
log_probs = tf.ensure_shape(next_log_probs, log_probs.shape)
|
144
|
+
else:
|
145
|
+
log_probs = next_log_probs
|
146
|
+
|
147
|
+
def gather_beams(x):
|
148
|
+
x = unflatten_beams(x)
|
149
|
+
indices = beam_indices
|
150
|
+
for axis in range(2, len(x.shape)):
|
151
|
+
indices = ops.expand_dims(indices, axis=axis)
|
152
|
+
x = ops.take_along_axis(x, indices, axis=1)
|
153
|
+
return flatten_beams(x)
|
154
|
+
|
155
|
+
prompt = gather_beams(prompt)
|
156
|
+
if has_cache:
|
157
|
+
cache = tree.map_structure(gather_beams, cache)
|
158
|
+
|
159
|
+
# Update each beam with the next token.
|
160
|
+
next_token = ops.cast(next_token, prompt.dtype)
|
161
|
+
# Don't overwrite anywhere mask is True.
|
162
|
+
next_token = ops.where(mask[:, index], prompt[:, index], next_token)
|
163
|
+
# Update the prompt with the next token.
|
164
|
+
next_token = next_token[:, None]
|
165
|
+
prompt = ops.slice_update(prompt, [0, index], next_token)
|
166
|
+
# Return the iteration of the loop state.
|
167
|
+
return (prompt, cache, index + 1, log_probs)
|
168
|
+
|
169
|
+
prompt, _, _, log_probs = self.run_loop(
|
170
|
+
cond=cond,
|
171
|
+
body=body,
|
172
|
+
loop_vars=(prompt, cache, index, log_probs),
|
173
|
+
maximum_iterations=(max_length - index),
|
174
|
+
model=model,
|
175
|
+
)
|
176
|
+
|
177
|
+
all_prompts = unflatten_beams(prompt)
|
178
|
+
all_log_probs = unflatten_beams(log_probs)
|
179
|
+
|
180
|
+
if self.return_all_beams:
|
181
|
+
sorted_indices = ops.argsort(-all_log_probs, axis=-1)
|
182
|
+
sorted_log_probs = ops.take_along_axis(
|
183
|
+
all_log_probs,
|
184
|
+
sorted_indices,
|
185
|
+
axis=1,
|
186
|
+
)
|
187
|
+
sorted_prompts = ops.take_along_axis(
|
188
|
+
all_prompts,
|
189
|
+
ops.expand_dims(sorted_indices, -1),
|
190
|
+
axis=1,
|
191
|
+
)
|
192
|
+
return sorted_prompts, sorted_log_probs
|
193
|
+
else:
|
194
|
+
# Gather the top beam at each batch index.
|
195
|
+
top_beams = ops.argmax(all_log_probs, axis=-1)[:, None, None]
|
196
|
+
prompt = ops.take_along_axis(all_prompts, top_beams, axis=1)
|
197
|
+
return ops.squeeze(prompt, axis=1)
|
198
|
+
|
199
|
+
def get_config(self):
|
200
|
+
config = super().get_config()
|
201
|
+
config.update(
|
202
|
+
{
|
203
|
+
"num_beams": self.num_beams,
|
204
|
+
"return_all_beams": self.return_all_beams,
|
205
|
+
}
|
206
|
+
)
|
207
|
+
return config
|
@@ -0,0 +1,231 @@
|
|
1
|
+
# Copyright 2024 The KerasHub 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
|
+
|
15
|
+
from keras import ops
|
16
|
+
from keras import tree
|
17
|
+
|
18
|
+
from keras_hub.src.api_export import keras_hub_export
|
19
|
+
from keras_hub.src.samplers.sampler import Sampler
|
20
|
+
from keras_hub.src.utils.tensor_utils import any_equal
|
21
|
+
|
22
|
+
|
23
|
+
@keras_hub_export("keras_hub.samplers.ContrastiveSampler")
|
24
|
+
class ContrastiveSampler(Sampler):
|
25
|
+
"""Contrastive Sampler class.
|
26
|
+
|
27
|
+
This sampler implements contrastive search algorithm. In short, the sampler
|
28
|
+
chooses the token having the max "score" as the next token. The "score" is
|
29
|
+
a weighted sum between token's probability and max similarity against
|
30
|
+
previous tokens. By using this joint score, contrastive sampler reduces the
|
31
|
+
behavior of duplicating seen tokens.
|
32
|
+
|
33
|
+
Args:
|
34
|
+
k: int, the `k` value of top-k. Next token will be chosen from k tokens.
|
35
|
+
alpha: float, the weight of minus max similarity in joint score
|
36
|
+
computation. The larger the value of `alpha`, the score relies more
|
37
|
+
on the similarity than the token probability.
|
38
|
+
|
39
|
+
Call arguments:
|
40
|
+
{{call_args}}
|
41
|
+
|
42
|
+
Examples:
|
43
|
+
```python
|
44
|
+
causal_lm = keras_hub.models.GPT2CausalLM.from_preset("gpt2_base_en")
|
45
|
+
|
46
|
+
# Pass by name to compile.
|
47
|
+
causal_lm.compile(sampler="contrastive")
|
48
|
+
causal_lm.generate(["Keras is a"])
|
49
|
+
|
50
|
+
# Pass by object to compile.
|
51
|
+
sampler = keras_hub.samplers.ContrastiveSampler(k=5)
|
52
|
+
causal_lm.compile(sampler=sampler)
|
53
|
+
causal_lm.generate(["Keras is a"])
|
54
|
+
```
|
55
|
+
"""
|
56
|
+
|
57
|
+
def __init__(
|
58
|
+
self,
|
59
|
+
k=5,
|
60
|
+
alpha=0.6,
|
61
|
+
**kwargs,
|
62
|
+
):
|
63
|
+
super().__init__(**kwargs)
|
64
|
+
self.k = k
|
65
|
+
self.alpha = alpha
|
66
|
+
|
67
|
+
def __call__(
|
68
|
+
self,
|
69
|
+
next,
|
70
|
+
prompt,
|
71
|
+
cache=None,
|
72
|
+
index=0,
|
73
|
+
mask=None,
|
74
|
+
stop_token_ids=None,
|
75
|
+
hidden_states=None,
|
76
|
+
model=None,
|
77
|
+
):
|
78
|
+
if hidden_states is None:
|
79
|
+
raise ValueError(
|
80
|
+
"`ContrastiveSampler` requires passing a `hidden_states`, but"
|
81
|
+
"received `None`."
|
82
|
+
)
|
83
|
+
batch_size, max_length = ops.shape(prompt)[0], ops.shape(prompt)[1]
|
84
|
+
index = ops.cast(index, "int32")
|
85
|
+
|
86
|
+
def create_beams(x):
|
87
|
+
"""Add initial beam state."""
|
88
|
+
x = ops.repeat(x, self.k, axis=0)
|
89
|
+
flat_shape = (batch_size * self.k,) + ops.shape(x)[1:]
|
90
|
+
return ops.reshape(x, flat_shape)
|
91
|
+
|
92
|
+
def flatten_beams(x):
|
93
|
+
"""Combine the beam dim and batch dim."""
|
94
|
+
flat_shape = (batch_size * self.k,) + ops.shape(x)[2:]
|
95
|
+
return ops.reshape(x, flat_shape)
|
96
|
+
|
97
|
+
def unflatten_beams(x):
|
98
|
+
"""Separate the beam dim and batch dim."""
|
99
|
+
unflat_shape = (batch_size, self.k) + ops.shape(x)[1:]
|
100
|
+
return ops.reshape(x, unflat_shape)
|
101
|
+
|
102
|
+
mask = ops.zeros_like(prompt, dtype="bool") if mask is None else mask
|
103
|
+
# Compute initial logits.
|
104
|
+
logits, _, cache = next(prompt, cache, index)
|
105
|
+
# `ops.while_loop` will not accept `None` as a value for `loop_vars`.
|
106
|
+
has_cache = cache is not None
|
107
|
+
cache = cache if has_cache else ()
|
108
|
+
|
109
|
+
def cond(prompt, cache, index, logits, hidden_states):
|
110
|
+
if stop_token_ids is None:
|
111
|
+
return True
|
112
|
+
# Stop if all sequences have produced a *new* stop token.
|
113
|
+
end_tokens = any_equal(prompt, stop_token_ids, ~mask)
|
114
|
+
prompt_done = ops.any(end_tokens, axis=-1)
|
115
|
+
return ops.logical_not(ops.all(prompt_done))
|
116
|
+
|
117
|
+
def body(prompt, cache, index, logits, hidden_states):
|
118
|
+
# Compute the softmax distribution for the next token.
|
119
|
+
probabilities = self.compute_probabilities(logits)
|
120
|
+
|
121
|
+
# Replicate for `self.k` times to find the best token in top-k
|
122
|
+
# candidates.
|
123
|
+
prompt_beams = create_beams(prompt)
|
124
|
+
mask_beams = create_beams(mask)
|
125
|
+
hidden_states_beams = create_beams(hidden_states)
|
126
|
+
cache_beams = None
|
127
|
+
if has_cache:
|
128
|
+
cache_beams = tree.map_structure(create_beams, cache)
|
129
|
+
|
130
|
+
# Get top-k candidate tokens and their probabilities.
|
131
|
+
top_k_probabilities, top_k_indices = ops.top_k(
|
132
|
+
probabilities, k=self.k, sorted=False
|
133
|
+
)
|
134
|
+
next_token_probabilities = flatten_beams(top_k_probabilities)
|
135
|
+
next_token = flatten_beams(top_k_indices)
|
136
|
+
next_token = ops.cast(next_token, prompt.dtype)
|
137
|
+
next_token = ops.where(
|
138
|
+
mask_beams[:, index], prompt_beams[:, index], next_token
|
139
|
+
)
|
140
|
+
|
141
|
+
# Update the prompt with the next token.
|
142
|
+
next_token = ops.expand_dims(next_token, -1)
|
143
|
+
prompt_beams = ops.slice_update(
|
144
|
+
prompt_beams, [0, index], next_token
|
145
|
+
)
|
146
|
+
|
147
|
+
# Compute the logits and hidden states for top-k candidate tokens.
|
148
|
+
next_logits, next_hidden_states_beams, cache_beams = next(
|
149
|
+
prompt_beams, cache_beams, index + 1
|
150
|
+
)
|
151
|
+
|
152
|
+
# Compute the max similarity score for top-k candidate tokens
|
153
|
+
# against previous tokens.
|
154
|
+
similarity_scores = self.similarity(
|
155
|
+
hidden_states_beams, next_hidden_states_beams
|
156
|
+
)
|
157
|
+
# Replace all future indices with -1, the lowest similarity score.
|
158
|
+
score_mask = ops.expand_dims(ops.arange(max_length) < index, 0)
|
159
|
+
similarity_scores = ops.where(score_mask, similarity_scores, -1)
|
160
|
+
max_similarity_scores = ops.cast(
|
161
|
+
ops.max(similarity_scores, axis=1),
|
162
|
+
dtype=next_token_probabilities.dtype,
|
163
|
+
)
|
164
|
+
# The final score of each candidate token is weighted sum of
|
165
|
+
# probability and similarity against previous tokens.
|
166
|
+
accumulated_scores = (
|
167
|
+
(1 - self.alpha) * next_token_probabilities
|
168
|
+
- self.alpha * max_similarity_scores
|
169
|
+
)
|
170
|
+
# Unflatten variables to shape [batch_size, self.k, ...] for
|
171
|
+
# gather purpose.
|
172
|
+
unflat_score = unflatten_beams(accumulated_scores)
|
173
|
+
unflat_prompt = unflatten_beams(prompt_beams)
|
174
|
+
unflat_next_logits = unflatten_beams(next_logits)
|
175
|
+
unflat_next_hidden_states = unflatten_beams(
|
176
|
+
next_hidden_states_beams
|
177
|
+
)
|
178
|
+
best_token_indices = ops.argmax(unflat_score, axis=1)
|
179
|
+
|
180
|
+
def gather_best_token(beams):
|
181
|
+
indices = best_token_indices
|
182
|
+
for axis in range(1, len(beams.shape)):
|
183
|
+
indices = ops.expand_dims(indices, axis=axis)
|
184
|
+
best = ops.take_along_axis(
|
185
|
+
beams,
|
186
|
+
indices,
|
187
|
+
axis=1,
|
188
|
+
)
|
189
|
+
return ops.squeeze(best, axis=1)
|
190
|
+
|
191
|
+
prompt = gather_best_token(unflat_prompt)
|
192
|
+
# We avoid recomputing forward pass for each token by updating the
|
193
|
+
# cache/hidden_states using the output, and pass the logits to
|
194
|
+
# next iteration step.
|
195
|
+
logits = gather_best_token(unflat_next_logits)
|
196
|
+
next_hidden_states = gather_best_token(unflat_next_hidden_states)
|
197
|
+
if has_cache:
|
198
|
+
cache = tree.map_structure(unflatten_beams, cache_beams)
|
199
|
+
cache = tree.map_structure(gather_best_token, cache)
|
200
|
+
|
201
|
+
hidden_states = ops.slice_update(
|
202
|
+
hidden_states,
|
203
|
+
[0, index, 0],
|
204
|
+
next_hidden_states[:, None, :],
|
205
|
+
)
|
206
|
+
return (prompt, cache, index + 1, logits, hidden_states)
|
207
|
+
|
208
|
+
prompt, _, _, _, _ = self.run_loop(
|
209
|
+
cond=cond,
|
210
|
+
body=body,
|
211
|
+
loop_vars=(prompt, cache, index, logits, hidden_states),
|
212
|
+
maximum_iterations=(max_length - index),
|
213
|
+
model=model,
|
214
|
+
)
|
215
|
+
return prompt
|
216
|
+
|
217
|
+
def similarity(self, h1, h2):
|
218
|
+
h2 = ops.expand_dims(h2, -1)
|
219
|
+
h1_norm = ops.sqrt(ops.sum(h1 * h1, axis=-1))
|
220
|
+
h2_norm = ops.sqrt(ops.sum(h2 * h2, axis=-2))
|
221
|
+
return ops.squeeze(ops.matmul(h1, h2), axis=-1) / (h1_norm * h2_norm)
|
222
|
+
|
223
|
+
def get_config(self):
|
224
|
+
config = super().get_config()
|
225
|
+
config.update(
|
226
|
+
{
|
227
|
+
"k": self.k,
|
228
|
+
"alpha": self.alpha,
|
229
|
+
}
|
230
|
+
)
|
231
|
+
return config
|
@@ -0,0 +1,50 @@
|
|
1
|
+
# Copyright 2024 The KerasHub 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
|
+
|
15
|
+
from keras import ops
|
16
|
+
|
17
|
+
from keras_hub.src.api_export import keras_hub_export
|
18
|
+
from keras_hub.src.samplers.sampler import Sampler
|
19
|
+
|
20
|
+
|
21
|
+
@keras_hub_export("keras_hub.samplers.GreedySampler")
|
22
|
+
class GreedySampler(Sampler):
|
23
|
+
"""Greedy sampler class.
|
24
|
+
|
25
|
+
This sampler is implemented on greedy search, i.e., always picking up the
|
26
|
+
token of the largest probability as the next token.
|
27
|
+
|
28
|
+
Examples:
|
29
|
+
```python
|
30
|
+
causal_lm = keras_hub.models.GPT2CausalLM.from_preset("gpt2_base_en")
|
31
|
+
|
32
|
+
# Pass by name to compile.
|
33
|
+
causal_lm.compile(sampler="greedy")
|
34
|
+
causal_lm.generate(["Keras is a"])
|
35
|
+
|
36
|
+
# Pass by object to compile.
|
37
|
+
sampler = keras_hub.samplers.GreedySampler()
|
38
|
+
causal_lm.compile(sampler=sampler)
|
39
|
+
causal_lm.generate(["Keras is a"])
|
40
|
+
```
|
41
|
+
"""
|
42
|
+
|
43
|
+
def __init__(
|
44
|
+
self,
|
45
|
+
**kwargs,
|
46
|
+
):
|
47
|
+
super().__init__(**kwargs)
|
48
|
+
|
49
|
+
def get_next_token(self, probabilities):
|
50
|
+
return ops.argmax(probabilities, axis=-1)
|
@@ -0,0 +1,77 @@
|
|
1
|
+
# Copyright 2024 The KerasHub 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
|
+
|
15
|
+
from keras import ops
|
16
|
+
from keras import random
|
17
|
+
|
18
|
+
from keras_hub.src.api_export import keras_hub_export
|
19
|
+
from keras_hub.src.samplers.sampler import Sampler
|
20
|
+
|
21
|
+
|
22
|
+
@keras_hub_export("keras_hub.samplers.RandomSampler")
|
23
|
+
class RandomSampler(Sampler):
|
24
|
+
"""Random Sampler class.
|
25
|
+
|
26
|
+
This sampler implements random sampling. Briefly, random sampler randomly
|
27
|
+
selects a token from the entire distribution of the tokens, with selection
|
28
|
+
chance determined by the probability of each token.
|
29
|
+
|
30
|
+
Args:
|
31
|
+
seed: int. The random seed. Defaults to `None`.
|
32
|
+
|
33
|
+
Call arguments:
|
34
|
+
{{call_args}}
|
35
|
+
|
36
|
+
Examples:
|
37
|
+
```python
|
38
|
+
causal_lm = keras_hub.models.GPT2CausalLM.from_preset("gpt2_base_en")
|
39
|
+
|
40
|
+
# Pass by name to compile.
|
41
|
+
causal_lm.compile(sampler="random")
|
42
|
+
causal_lm.generate(["Keras is a"])
|
43
|
+
|
44
|
+
# Pass by object to compile.
|
45
|
+
sampler = keras_hub.samplers.RandomSampler(temperature=0.7)
|
46
|
+
causal_lm.compile(sampler=sampler)
|
47
|
+
causal_lm.generate(["Keras is a"])
|
48
|
+
```
|
49
|
+
"""
|
50
|
+
|
51
|
+
def __init__(
|
52
|
+
self,
|
53
|
+
seed=None,
|
54
|
+
**kwargs,
|
55
|
+
):
|
56
|
+
super().__init__(**kwargs)
|
57
|
+
self.seed = seed
|
58
|
+
self.seed_generator = random.SeedGenerator(seed)
|
59
|
+
|
60
|
+
def get_next_token(self, probabilities):
|
61
|
+
# Sample the next token from the probability distribution.
|
62
|
+
next_token_id = random.categorical(
|
63
|
+
ops.log(probabilities),
|
64
|
+
1,
|
65
|
+
seed=self.seed_generator,
|
66
|
+
dtype="int32",
|
67
|
+
)
|
68
|
+
return ops.squeeze(next_token_id, axis=-1)
|
69
|
+
|
70
|
+
def get_config(self):
|
71
|
+
config = super().get_config()
|
72
|
+
config.update(
|
73
|
+
{
|
74
|
+
"seed": self.seed,
|
75
|
+
}
|
76
|
+
)
|
77
|
+
return config
|