easy-cs-rec-custommodel 0.8.6__py2.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.
Potentially problematic release.
This version of easy-cs-rec-custommodel might be problematic. Click here for more details.
- easy_cs_rec_custommodel-0.8.6.dist-info/LICENSE +203 -0
- easy_cs_rec_custommodel-0.8.6.dist-info/METADATA +48 -0
- easy_cs_rec_custommodel-0.8.6.dist-info/RECORD +336 -0
- easy_cs_rec_custommodel-0.8.6.dist-info/WHEEL +6 -0
- easy_cs_rec_custommodel-0.8.6.dist-info/top_level.txt +2 -0
- easy_rec/__init__.py +114 -0
- easy_rec/python/__init__.py +0 -0
- easy_rec/python/builders/__init__.py +0 -0
- easy_rec/python/builders/hyperparams_builder.py +78 -0
- easy_rec/python/builders/loss_builder.py +333 -0
- easy_rec/python/builders/optimizer_builder.py +211 -0
- easy_rec/python/builders/strategy_builder.py +44 -0
- easy_rec/python/compat/__init__.py +0 -0
- easy_rec/python/compat/adam_s.py +245 -0
- easy_rec/python/compat/array_ops.py +229 -0
- easy_rec/python/compat/dynamic_variable.py +542 -0
- easy_rec/python/compat/early_stopping.py +653 -0
- easy_rec/python/compat/embedding_ops.py +162 -0
- easy_rec/python/compat/embedding_parallel_saver.py +316 -0
- easy_rec/python/compat/estimator_train.py +116 -0
- easy_rec/python/compat/exporter.py +473 -0
- easy_rec/python/compat/feature_column/__init__.py +0 -0
- easy_rec/python/compat/feature_column/feature_column.py +3675 -0
- easy_rec/python/compat/feature_column/feature_column_v2.py +5233 -0
- easy_rec/python/compat/feature_column/sequence_feature_column.py +648 -0
- easy_rec/python/compat/feature_column/utils.py +154 -0
- easy_rec/python/compat/layers.py +329 -0
- easy_rec/python/compat/ops.py +14 -0
- easy_rec/python/compat/optimizers.py +619 -0
- easy_rec/python/compat/queues.py +311 -0
- easy_rec/python/compat/regularizers.py +208 -0
- easy_rec/python/compat/sok_optimizer.py +440 -0
- easy_rec/python/compat/sync_replicas_optimizer.py +528 -0
- easy_rec/python/compat/weight_decay_optimizers.py +475 -0
- easy_rec/python/core/__init__.py +0 -0
- easy_rec/python/core/easyrec_metrics/__init__.py +24 -0
- easy_rec/python/core/easyrec_metrics/distribute_metrics_impl_pai.py +3702 -0
- easy_rec/python/core/easyrec_metrics/distribute_metrics_impl_tf.py +3768 -0
- easy_rec/python/core/learning_schedules.py +228 -0
- easy_rec/python/core/metrics.py +402 -0
- easy_rec/python/core/sampler.py +844 -0
- easy_rec/python/eval.py +102 -0
- easy_rec/python/export.py +150 -0
- easy_rec/python/feature_column/__init__.py +0 -0
- easy_rec/python/feature_column/feature_column.py +664 -0
- easy_rec/python/feature_column/feature_group.py +89 -0
- easy_rec/python/hpo/__init__.py +0 -0
- easy_rec/python/hpo/emr_hpo.py +140 -0
- easy_rec/python/hpo/generate_hpo_sql.py +71 -0
- easy_rec/python/hpo/pai_hpo.py +297 -0
- easy_rec/python/inference/__init__.py +0 -0
- easy_rec/python/inference/csv_predictor.py +189 -0
- easy_rec/python/inference/hive_parquet_predictor.py +200 -0
- easy_rec/python/inference/hive_predictor.py +166 -0
- easy_rec/python/inference/odps_predictor.py +70 -0
- easy_rec/python/inference/parquet_predictor.py +147 -0
- easy_rec/python/inference/parquet_predictor_v2.py +147 -0
- easy_rec/python/inference/predictor.py +621 -0
- easy_rec/python/inference/processor/__init__.py +0 -0
- easy_rec/python/inference/processor/test.py +170 -0
- easy_rec/python/inference/vector_retrieve.py +124 -0
- easy_rec/python/input/__init__.py +0 -0
- easy_rec/python/input/batch_tfrecord_input.py +117 -0
- easy_rec/python/input/criteo_binary_reader.py +259 -0
- easy_rec/python/input/criteo_input.py +107 -0
- easy_rec/python/input/csv_input.py +175 -0
- easy_rec/python/input/csv_input_ex.py +72 -0
- easy_rec/python/input/csv_input_v2.py +68 -0
- easy_rec/python/input/datahub_input.py +320 -0
- easy_rec/python/input/dummy_input.py +58 -0
- easy_rec/python/input/hive_input.py +123 -0
- easy_rec/python/input/hive_parquet_input.py +140 -0
- easy_rec/python/input/hive_rtp_input.py +174 -0
- easy_rec/python/input/input.py +1064 -0
- easy_rec/python/input/kafka_dataset.py +144 -0
- easy_rec/python/input/kafka_input.py +235 -0
- easy_rec/python/input/load_parquet.py +317 -0
- easy_rec/python/input/odps_input.py +101 -0
- easy_rec/python/input/odps_input_v2.py +110 -0
- easy_rec/python/input/odps_input_v3.py +132 -0
- easy_rec/python/input/odps_rtp_input.py +187 -0
- easy_rec/python/input/odps_rtp_input_v2.py +104 -0
- easy_rec/python/input/parquet_input.py +397 -0
- easy_rec/python/input/parquet_input_v2.py +180 -0
- easy_rec/python/input/parquet_input_v3.py +203 -0
- easy_rec/python/input/rtp_input.py +225 -0
- easy_rec/python/input/rtp_input_v2.py +145 -0
- easy_rec/python/input/tfrecord_input.py +100 -0
- easy_rec/python/layers/__init__.py +0 -0
- easy_rec/python/layers/backbone.py +571 -0
- easy_rec/python/layers/capsule_layer.py +176 -0
- easy_rec/python/layers/cmbf.py +390 -0
- easy_rec/python/layers/common_layers.py +192 -0
- easy_rec/python/layers/dnn.py +87 -0
- easy_rec/python/layers/embed_input_layer.py +25 -0
- easy_rec/python/layers/fm.py +26 -0
- easy_rec/python/layers/input_layer.py +396 -0
- easy_rec/python/layers/keras/__init__.py +34 -0
- easy_rec/python/layers/keras/activation.py +114 -0
- easy_rec/python/layers/keras/attention.py +267 -0
- easy_rec/python/layers/keras/auxiliary_loss.py +47 -0
- easy_rec/python/layers/keras/blocks.py +262 -0
- easy_rec/python/layers/keras/bst.py +119 -0
- easy_rec/python/layers/keras/custom_ops.py +250 -0
- easy_rec/python/layers/keras/data_augment.py +133 -0
- easy_rec/python/layers/keras/din.py +67 -0
- easy_rec/python/layers/keras/einsum_dense.py +598 -0
- easy_rec/python/layers/keras/embedding.py +81 -0
- easy_rec/python/layers/keras/fibinet.py +251 -0
- easy_rec/python/layers/keras/interaction.py +416 -0
- easy_rec/python/layers/keras/layer_norm.py +364 -0
- easy_rec/python/layers/keras/mask_net.py +166 -0
- easy_rec/python/layers/keras/multi_head_attention.py +717 -0
- easy_rec/python/layers/keras/multi_task.py +125 -0
- easy_rec/python/layers/keras/numerical_embedding.py +376 -0
- easy_rec/python/layers/keras/ppnet.py +194 -0
- easy_rec/python/layers/keras/transformer.py +192 -0
- easy_rec/python/layers/layer_norm.py +51 -0
- easy_rec/python/layers/mmoe.py +83 -0
- easy_rec/python/layers/multihead_attention.py +162 -0
- easy_rec/python/layers/multihead_cross_attention.py +749 -0
- easy_rec/python/layers/senet.py +73 -0
- easy_rec/python/layers/seq_input_layer.py +134 -0
- easy_rec/python/layers/sequence_feature_layer.py +249 -0
- easy_rec/python/layers/uniter.py +301 -0
- easy_rec/python/layers/utils.py +248 -0
- easy_rec/python/layers/variational_dropout_layer.py +130 -0
- easy_rec/python/loss/__init__.py +0 -0
- easy_rec/python/loss/circle_loss.py +82 -0
- easy_rec/python/loss/contrastive_loss.py +79 -0
- easy_rec/python/loss/f1_reweight_loss.py +38 -0
- easy_rec/python/loss/focal_loss.py +93 -0
- easy_rec/python/loss/jrc_loss.py +128 -0
- easy_rec/python/loss/listwise_loss.py +161 -0
- easy_rec/python/loss/multi_similarity.py +68 -0
- easy_rec/python/loss/pairwise_loss.py +307 -0
- easy_rec/python/loss/softmax_loss_with_negative_mining.py +110 -0
- easy_rec/python/loss/zero_inflated_lognormal.py +76 -0
- easy_rec/python/main.py +878 -0
- easy_rec/python/model/__init__.py +0 -0
- easy_rec/python/model/autoint.py +73 -0
- easy_rec/python/model/cmbf.py +47 -0
- easy_rec/python/model/collaborative_metric_learning.py +182 -0
- easy_rec/python/model/custom_model.py +323 -0
- easy_rec/python/model/dat.py +138 -0
- easy_rec/python/model/dbmtl.py +116 -0
- easy_rec/python/model/dcn.py +70 -0
- easy_rec/python/model/deepfm.py +106 -0
- easy_rec/python/model/dlrm.py +73 -0
- easy_rec/python/model/dropoutnet.py +207 -0
- easy_rec/python/model/dssm.py +154 -0
- easy_rec/python/model/dssm_senet.py +143 -0
- easy_rec/python/model/dummy_model.py +48 -0
- easy_rec/python/model/easy_rec_estimator.py +739 -0
- easy_rec/python/model/easy_rec_model.py +467 -0
- easy_rec/python/model/esmm.py +242 -0
- easy_rec/python/model/fm.py +63 -0
- easy_rec/python/model/match_model.py +357 -0
- easy_rec/python/model/mind.py +445 -0
- easy_rec/python/model/mmoe.py +70 -0
- easy_rec/python/model/multi_task_model.py +303 -0
- easy_rec/python/model/multi_tower.py +62 -0
- easy_rec/python/model/multi_tower_bst.py +190 -0
- easy_rec/python/model/multi_tower_din.py +130 -0
- easy_rec/python/model/multi_tower_recall.py +68 -0
- easy_rec/python/model/pdn.py +203 -0
- easy_rec/python/model/ple.py +120 -0
- easy_rec/python/model/rank_model.py +485 -0
- easy_rec/python/model/rocket_launching.py +203 -0
- easy_rec/python/model/simple_multi_task.py +54 -0
- easy_rec/python/model/uniter.py +46 -0
- easy_rec/python/model/wide_and_deep.py +121 -0
- easy_rec/python/ops/1.12/incr_record.so +0 -0
- easy_rec/python/ops/1.12/kafka.so +0 -0
- easy_rec/python/ops/1.12/libcustom_ops.so +0 -0
- easy_rec/python/ops/1.12/libembed_op.so +0 -0
- easy_rec/python/ops/1.12/libhiredis.so.1.0.0 +0 -0
- easy_rec/python/ops/1.12/librdkafka++.so.1 +0 -0
- easy_rec/python/ops/1.12/librdkafka.so.1 +0 -0
- easy_rec/python/ops/1.12/libredis++.so +0 -0
- easy_rec/python/ops/1.12/libredis++.so.1 +0 -0
- easy_rec/python/ops/1.12/libredis++.so.1.2.3 +0 -0
- easy_rec/python/ops/1.12/libstr_avx_op.so +0 -0
- easy_rec/python/ops/1.12/libwrite_sparse_kv.so +0 -0
- easy_rec/python/ops/1.15/incr_record.so +0 -0
- easy_rec/python/ops/1.15/kafka.so +0 -0
- easy_rec/python/ops/1.15/libcustom_ops.so +0 -0
- easy_rec/python/ops/1.15/libembed_op.so +0 -0
- easy_rec/python/ops/1.15/libhiredis.so.1.0.0 +0 -0
- easy_rec/python/ops/1.15/librdkafka++.so +0 -0
- easy_rec/python/ops/1.15/librdkafka++.so.1 +0 -0
- easy_rec/python/ops/1.15/librdkafka.so +0 -0
- easy_rec/python/ops/1.15/librdkafka.so.1 +0 -0
- easy_rec/python/ops/1.15/libredis++.so.1 +0 -0
- easy_rec/python/ops/1.15/libstr_avx_op.so +0 -0
- easy_rec/python/ops/2.12/libcustom_ops.so +0 -0
- easy_rec/python/ops/2.12/libload_embed.so +0 -0
- easy_rec/python/ops/2.12/libstr_avx_op.so +0 -0
- easy_rec/python/ops/__init__.py +0 -0
- easy_rec/python/ops/gen_kafka_ops.py +193 -0
- easy_rec/python/ops/gen_str_avx_op.py +28 -0
- easy_rec/python/ops/incr_record.py +30 -0
- easy_rec/python/predict.py +170 -0
- easy_rec/python/protos/__init__.py +0 -0
- easy_rec/python/protos/autoint_pb2.py +122 -0
- easy_rec/python/protos/backbone_pb2.py +1416 -0
- easy_rec/python/protos/cmbf_pb2.py +435 -0
- easy_rec/python/protos/collaborative_metric_learning_pb2.py +252 -0
- easy_rec/python/protos/custom_model_pb2.py +57 -0
- easy_rec/python/protos/dat_pb2.py +262 -0
- easy_rec/python/protos/data_source_pb2.py +422 -0
- easy_rec/python/protos/dataset_pb2.py +1920 -0
- easy_rec/python/protos/dbmtl_pb2.py +191 -0
- easy_rec/python/protos/dcn_pb2.py +197 -0
- easy_rec/python/protos/deepfm_pb2.py +163 -0
- easy_rec/python/protos/dlrm_pb2.py +163 -0
- easy_rec/python/protos/dnn_pb2.py +329 -0
- easy_rec/python/protos/dropoutnet_pb2.py +239 -0
- easy_rec/python/protos/dssm_pb2.py +262 -0
- easy_rec/python/protos/dssm_senet_pb2.py +282 -0
- easy_rec/python/protos/easy_rec_model_pb2.py +1672 -0
- easy_rec/python/protos/esmm_pb2.py +133 -0
- easy_rec/python/protos/eval_pb2.py +930 -0
- easy_rec/python/protos/export_pb2.py +379 -0
- easy_rec/python/protos/feature_config_pb2.py +1359 -0
- easy_rec/python/protos/fm_pb2.py +90 -0
- easy_rec/python/protos/hive_config_pb2.py +138 -0
- easy_rec/python/protos/hyperparams_pb2.py +624 -0
- easy_rec/python/protos/keras_layer_pb2.py +692 -0
- easy_rec/python/protos/layer_pb2.py +1936 -0
- easy_rec/python/protos/loss_pb2.py +1713 -0
- easy_rec/python/protos/mind_pb2.py +497 -0
- easy_rec/python/protos/mmoe_pb2.py +215 -0
- easy_rec/python/protos/multi_tower_pb2.py +295 -0
- easy_rec/python/protos/multi_tower_recall_pb2.py +198 -0
- easy_rec/python/protos/optimizer_pb2.py +2017 -0
- easy_rec/python/protos/pdn_pb2.py +293 -0
- easy_rec/python/protos/pipeline_pb2.py +516 -0
- easy_rec/python/protos/ple_pb2.py +231 -0
- easy_rec/python/protos/predict_pb2.py +1140 -0
- easy_rec/python/protos/rocket_launching_pb2.py +169 -0
- easy_rec/python/protos/seq_encoder_pb2.py +1084 -0
- easy_rec/python/protos/simi_pb2.py +54 -0
- easy_rec/python/protos/simple_multi_task_pb2.py +97 -0
- easy_rec/python/protos/tf_predict_pb2.py +630 -0
- easy_rec/python/protos/tower_pb2.py +661 -0
- easy_rec/python/protos/train_pb2.py +1197 -0
- easy_rec/python/protos/uniter_pb2.py +307 -0
- easy_rec/python/protos/variational_dropout_pb2.py +91 -0
- easy_rec/python/protos/wide_and_deep_pb2.py +131 -0
- easy_rec/python/test/__init__.py +0 -0
- easy_rec/python/test/csv_input_test.py +340 -0
- easy_rec/python/test/custom_early_stop_func.py +19 -0
- easy_rec/python/test/dh_local_run.py +104 -0
- easy_rec/python/test/embed_test.py +155 -0
- easy_rec/python/test/emr_run.py +119 -0
- easy_rec/python/test/eval_metric_test.py +107 -0
- easy_rec/python/test/excel_convert_test.py +64 -0
- easy_rec/python/test/export_test.py +513 -0
- easy_rec/python/test/fg_test.py +70 -0
- easy_rec/python/test/hive_input_test.py +311 -0
- easy_rec/python/test/hpo_test.py +235 -0
- easy_rec/python/test/kafka_test.py +373 -0
- easy_rec/python/test/local_incr_test.py +122 -0
- easy_rec/python/test/loss_test.py +110 -0
- easy_rec/python/test/odps_command.py +61 -0
- easy_rec/python/test/odps_local_run.py +86 -0
- easy_rec/python/test/odps_run.py +254 -0
- easy_rec/python/test/odps_test_cls.py +39 -0
- easy_rec/python/test/odps_test_prepare.py +198 -0
- easy_rec/python/test/odps_test_util.py +237 -0
- easy_rec/python/test/pre_check_test.py +54 -0
- easy_rec/python/test/predictor_test.py +394 -0
- easy_rec/python/test/rtp_convert_test.py +133 -0
- easy_rec/python/test/run.py +138 -0
- easy_rec/python/test/train_eval_test.py +1299 -0
- easy_rec/python/test/util_test.py +85 -0
- easy_rec/python/test/zero_inflated_lognormal_test.py +53 -0
- easy_rec/python/tools/__init__.py +0 -0
- easy_rec/python/tools/add_boundaries_to_config.py +67 -0
- easy_rec/python/tools/add_feature_info_to_config.py +145 -0
- easy_rec/python/tools/convert_config_format.py +48 -0
- easy_rec/python/tools/convert_rtp_data.py +79 -0
- easy_rec/python/tools/convert_rtp_fg.py +106 -0
- easy_rec/python/tools/create_config_from_excel.py +427 -0
- easy_rec/python/tools/criteo/__init__.py +0 -0
- easy_rec/python/tools/criteo/convert_data.py +157 -0
- easy_rec/python/tools/edit_lookup_graph.py +134 -0
- easy_rec/python/tools/faiss_index_pai.py +116 -0
- easy_rec/python/tools/feature_selection.py +316 -0
- easy_rec/python/tools/hit_rate_ds.py +223 -0
- easy_rec/python/tools/hit_rate_pai.py +138 -0
- easy_rec/python/tools/pre_check.py +120 -0
- easy_rec/python/tools/predict_and_chk.py +111 -0
- easy_rec/python/tools/read_kafka.py +55 -0
- easy_rec/python/tools/split_model_pai.py +286 -0
- easy_rec/python/tools/split_pdn_model_pai.py +272 -0
- easy_rec/python/tools/test_saved_model.py +80 -0
- easy_rec/python/tools/view_saved_model.py +39 -0
- easy_rec/python/tools/write_kafka.py +65 -0
- easy_rec/python/train_eval.py +325 -0
- easy_rec/python/utils/__init__.py +15 -0
- easy_rec/python/utils/activation.py +120 -0
- easy_rec/python/utils/check_utils.py +87 -0
- easy_rec/python/utils/compat.py +14 -0
- easy_rec/python/utils/config_util.py +652 -0
- easy_rec/python/utils/constant.py +43 -0
- easy_rec/python/utils/convert_rtp_fg.py +616 -0
- easy_rec/python/utils/dag.py +192 -0
- easy_rec/python/utils/distribution_utils.py +268 -0
- easy_rec/python/utils/ds_util.py +65 -0
- easy_rec/python/utils/embedding_utils.py +73 -0
- easy_rec/python/utils/estimator_utils.py +1036 -0
- easy_rec/python/utils/export_big_model.py +630 -0
- easy_rec/python/utils/expr_util.py +118 -0
- easy_rec/python/utils/fg_util.py +53 -0
- easy_rec/python/utils/hit_rate_utils.py +220 -0
- easy_rec/python/utils/hive_utils.py +183 -0
- easy_rec/python/utils/hpo_util.py +137 -0
- easy_rec/python/utils/hvd_utils.py +56 -0
- easy_rec/python/utils/input_utils.py +108 -0
- easy_rec/python/utils/io_util.py +282 -0
- easy_rec/python/utils/load_class.py +249 -0
- easy_rec/python/utils/meta_graph_editor.py +941 -0
- easy_rec/python/utils/multi_optimizer.py +62 -0
- easy_rec/python/utils/numpy_utils.py +18 -0
- easy_rec/python/utils/odps_util.py +79 -0
- easy_rec/python/utils/pai_util.py +86 -0
- easy_rec/python/utils/proto_util.py +90 -0
- easy_rec/python/utils/restore_filter.py +89 -0
- easy_rec/python/utils/shape_utils.py +432 -0
- easy_rec/python/utils/static_shape.py +71 -0
- easy_rec/python/utils/test_utils.py +866 -0
- easy_rec/python/utils/tf_utils.py +56 -0
- easy_rec/version.py +4 -0
- test/__init__.py +0 -0
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
# -*- encoding:utf-8 -*-
|
|
2
|
+
# Copyright (c) Alibaba, Inc. and its affiliates.
|
|
3
|
+
import math
|
|
4
|
+
import string
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import tensorflow as tf
|
|
8
|
+
from tensorflow.python.keras import constraints
|
|
9
|
+
from tensorflow.python.keras import initializers
|
|
10
|
+
from tensorflow.python.keras import regularizers
|
|
11
|
+
from tensorflow.python.keras.layers import Dropout
|
|
12
|
+
from tensorflow.python.keras.layers import Layer
|
|
13
|
+
from tensorflow.python.keras.layers import Softmax
|
|
14
|
+
|
|
15
|
+
from easy_rec.python.layers.keras.activation import MaskedSoftmax
|
|
16
|
+
from easy_rec.python.layers.keras.einsum_dense import EinsumDense
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MultiHeadAttention(Layer):
|
|
20
|
+
"""MultiHeadAttention layer.
|
|
21
|
+
|
|
22
|
+
This is an implementation of multi-headed attention as described in the
|
|
23
|
+
paper "Attention is all you Need"
|
|
24
|
+
[Vaswani et al., 2017](https://arxiv.org/abs/1706.03762).
|
|
25
|
+
If `query`, `key,` `value` are the same, then
|
|
26
|
+
this is self-attention. Each time step in `query` attends to the
|
|
27
|
+
corresponding sequence in `key`, and returns a fixed-width vector.
|
|
28
|
+
|
|
29
|
+
This layer first projects `query`, `key` and `value`. These are
|
|
30
|
+
(effectively) a list of tensors of length `num_attention_heads`, where the
|
|
31
|
+
corresponding shapes are `(batch_size, <query dimensions>, key_dim)`,
|
|
32
|
+
`(batch_size, <key/value dimensions>, key_dim)`,
|
|
33
|
+
`(batch_size, <key/value dimensions>, value_dim)`.
|
|
34
|
+
|
|
35
|
+
Then, the query and key tensors are dot-producted and scaled. These are
|
|
36
|
+
softmaxed to obtain attention probabilities. The value tensors are then
|
|
37
|
+
interpolated by these probabilities, then concatenated back to a single
|
|
38
|
+
tensor.
|
|
39
|
+
|
|
40
|
+
Finally, the result tensor with the last dimension as `value_dim` can take
|
|
41
|
+
a linear projection and return.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
num_heads: Number of attention heads.
|
|
45
|
+
key_dim: Size of each attention head for query and key.
|
|
46
|
+
value_dim: Size of each attention head for value.
|
|
47
|
+
dropout: Dropout probability.
|
|
48
|
+
use_bias: Boolean, whether the dense layers use bias vectors/matrices.
|
|
49
|
+
output_shape: The expected shape of an output tensor, besides the batch
|
|
50
|
+
and sequence dims. If not specified, projects back to the query
|
|
51
|
+
feature dim (the query input's last dimension).
|
|
52
|
+
attention_axes: axes over which the attention is applied. `None` means
|
|
53
|
+
attention over all axes, but batch, heads, and features.
|
|
54
|
+
kernel_initializer: Initializer for dense layer kernels.
|
|
55
|
+
bias_initializer: Initializer for dense layer biases.
|
|
56
|
+
kernel_regularizer: Regularizer for dense layer kernels.
|
|
57
|
+
bias_regularizer: Regularizer for dense layer biases.
|
|
58
|
+
activity_regularizer: Regularizer for dense layer activity.
|
|
59
|
+
kernel_constraint: Constraint for dense layer kernels.
|
|
60
|
+
bias_constraint: Constraint for dense layer kernels.
|
|
61
|
+
use_causal_mask: A boolean to indicate whether to apply a causal mask to
|
|
62
|
+
prevent tokens from attending to future tokens (e.g., used in a
|
|
63
|
+
decoder Transformer).
|
|
64
|
+
return_attention_scores: A boolean to indicate whether the output should
|
|
65
|
+
be `(attention_output, attention_scores)` if `True`, or
|
|
66
|
+
`attention_output` if `False`. Defaults to `False`.
|
|
67
|
+
|
|
68
|
+
Call arguments:
|
|
69
|
+
query: Query tensor of shape `(B, T, dim)`, where `B` is the batch size,
|
|
70
|
+
`T` is the target sequence length, and dim is the feature dimension.
|
|
71
|
+
value: Value tensor of shape `(B, S, dim)`, where `B` is the batch size,
|
|
72
|
+
`S` is the source sequence length, and dim is the feature dimension.
|
|
73
|
+
key: Optional key tensor of shape `(B, S, dim)`. If not given, will
|
|
74
|
+
use `value` for both `key` and `value`, which is the most common
|
|
75
|
+
case.
|
|
76
|
+
attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
|
|
77
|
+
attention to certain positions. The boolean mask specifies which
|
|
78
|
+
query elements can attend to which key elements, 1 indicates
|
|
79
|
+
attention and 0 indicates no attention. Broadcasting can happen for
|
|
80
|
+
the missing batch dimensions and the head dimension.
|
|
81
|
+
training: Python boolean indicating whether the layer should behave in
|
|
82
|
+
training mode (adding dropout) or in inference mode (no dropout).
|
|
83
|
+
Will go with either using the training mode of the parent
|
|
84
|
+
layer/model, or `False` (inference) if there is no parent layer.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
attention_output: The result of the computation, of shape `(B, T, E)`,
|
|
88
|
+
where `T` is for target sequence shapes and `E` is the query input
|
|
89
|
+
last dimension if `output_shape` is `None`. Otherwise, the
|
|
90
|
+
multi-head outputs are projected to the shape specified by
|
|
91
|
+
`output_shape`.
|
|
92
|
+
attention_scores: (Optional) multi-head attention coefficients over
|
|
93
|
+
attention axes.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(self, params, name='multi_head_attention', reuse=None, **kwargs):
|
|
97
|
+
super(MultiHeadAttention, self).__init__(name=name, **kwargs)
|
|
98
|
+
self.supports_masking = True
|
|
99
|
+
self._num_heads = params.num_heads
|
|
100
|
+
self._key_dim = params.key_dim
|
|
101
|
+
# Cache 1.0 / math.sqrt(self._key_dim).
|
|
102
|
+
self._inverse_sqrt_key_dim = None
|
|
103
|
+
value_dim = params.get_or_default('value_dim', None)
|
|
104
|
+
self._value_dim = value_dim if value_dim else self._key_dim
|
|
105
|
+
self._dropout = params.get_or_default('dropout', 0.0)
|
|
106
|
+
self._use_bias = params.get_or_default('use_bias', True)
|
|
107
|
+
self._output_shape = params.get_or_default('output_shape', None)
|
|
108
|
+
self._kernel_initializer = initializers.get(
|
|
109
|
+
params.get_or_default('kernel_initializer', 'glorot_uniform'))
|
|
110
|
+
self._bias_initializer = initializers.get(
|
|
111
|
+
params.get_or_default('bias_initializer', 'zeros'))
|
|
112
|
+
self._kernel_regularizer = regularizers.get(
|
|
113
|
+
params.get_or_default('kernel_regularizer', None))
|
|
114
|
+
self._bias_regularizer = regularizers.get(
|
|
115
|
+
params.get_or_default('bias_regularizer', None))
|
|
116
|
+
self._activity_regularizer = regularizers.get(
|
|
117
|
+
params.get_or_default('activity_regularizer', None))
|
|
118
|
+
self._kernel_constraint = constraints.get(
|
|
119
|
+
params.get_or_default('kernel_constraint', None))
|
|
120
|
+
self._bias_constraint = constraints.get(
|
|
121
|
+
params.get_or_default('bias_constraint', None))
|
|
122
|
+
self._attention_axes = params.get_or_default('attention_axes', None)
|
|
123
|
+
self._use_causal_mask = params.get_or_default('use_causal_mask', False)
|
|
124
|
+
self._return_attention_scores = params.get_or_default(
|
|
125
|
+
'return_attention_scores', False)
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def num_heads(self):
|
|
129
|
+
return self._num_heads
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def key_dim(self):
|
|
133
|
+
return self._key_dim
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def value_dim(self):
|
|
137
|
+
return self._value_dim
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def dropout(self):
|
|
141
|
+
return self._dropout
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def use_bias(self):
|
|
145
|
+
return self._use_bias
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def output_shape(self):
|
|
149
|
+
return self._output_shape
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def attention_axes(self):
|
|
153
|
+
return self._attention_axes
|
|
154
|
+
|
|
155
|
+
def get_config(self):
|
|
156
|
+
base_config = super(MultiHeadAttention, self).get_config()
|
|
157
|
+
config = {
|
|
158
|
+
'num_heads':
|
|
159
|
+
self._num_heads,
|
|
160
|
+
'key_dim':
|
|
161
|
+
self._key_dim,
|
|
162
|
+
'value_dim':
|
|
163
|
+
self._value_dim,
|
|
164
|
+
'dropout':
|
|
165
|
+
self._dropout,
|
|
166
|
+
'use_bias':
|
|
167
|
+
self._use_bias,
|
|
168
|
+
'output_shape':
|
|
169
|
+
self._output_shape,
|
|
170
|
+
'attention_axes':
|
|
171
|
+
self._attention_axes,
|
|
172
|
+
'kernel_initializer':
|
|
173
|
+
initializers.serialize(self._kernel_initializer),
|
|
174
|
+
'bias_initializer':
|
|
175
|
+
initializers.serialize(self._bias_initializer),
|
|
176
|
+
'kernel_regularizer':
|
|
177
|
+
regularizers.serialize(self._kernel_regularizer),
|
|
178
|
+
'bias_regularizer':
|
|
179
|
+
regularizers.serialize(self._bias_regularizer),
|
|
180
|
+
'activity_regularizer':
|
|
181
|
+
regularizers.serialize(self._activity_regularizer),
|
|
182
|
+
'kernel_constraint':
|
|
183
|
+
constraints.serialize(self._kernel_constraint),
|
|
184
|
+
'bias_constraint':
|
|
185
|
+
constraints.serialize(self._bias_constraint),
|
|
186
|
+
}
|
|
187
|
+
config.update(base_config)
|
|
188
|
+
return config
|
|
189
|
+
|
|
190
|
+
def build(self, input_shape):
|
|
191
|
+
"""Builds layers and variables."""
|
|
192
|
+
if len(input_shape) == 3:
|
|
193
|
+
query_shape, value_shape, key_shape = input_shape
|
|
194
|
+
elif len(input_shape) == 2:
|
|
195
|
+
query_shape, value_shape = input_shape
|
|
196
|
+
key_shape = None
|
|
197
|
+
else:
|
|
198
|
+
raise ValueError('invalid input shape of MultiHeadAttention')
|
|
199
|
+
|
|
200
|
+
key_shape = value_shape if key_shape is None else key_shape
|
|
201
|
+
query_rank = len(query_shape)
|
|
202
|
+
value_rank = len(value_shape)
|
|
203
|
+
key_rank = len(key_shape)
|
|
204
|
+
einsum_equation, bias_axes, output_rank = _build_proj_equation(
|
|
205
|
+
query_rank - 1, bound_dims=1, output_dims=2)
|
|
206
|
+
self._query_dense = EinsumDense(
|
|
207
|
+
einsum_equation,
|
|
208
|
+
output_shape=_get_output_shape(output_rank - 1,
|
|
209
|
+
[self._num_heads, self._key_dim]),
|
|
210
|
+
bias_axes=bias_axes if self._use_bias else None,
|
|
211
|
+
name='query',
|
|
212
|
+
**self._get_common_kwargs_for_sublayer())
|
|
213
|
+
self._query_dense.build(query_shape)
|
|
214
|
+
einsum_equation, bias_axes, output_rank = _build_proj_equation(
|
|
215
|
+
key_rank - 1, bound_dims=1, output_dims=2)
|
|
216
|
+
self._key_dense = EinsumDense(
|
|
217
|
+
einsum_equation,
|
|
218
|
+
output_shape=_get_output_shape(output_rank - 1,
|
|
219
|
+
[self._num_heads, self._key_dim]),
|
|
220
|
+
bias_axes=bias_axes if self._use_bias else None,
|
|
221
|
+
name='key',
|
|
222
|
+
**self._get_common_kwargs_for_sublayer())
|
|
223
|
+
self._key_dense.build(key_shape)
|
|
224
|
+
einsum_equation, bias_axes, output_rank = _build_proj_equation(
|
|
225
|
+
value_rank - 1, bound_dims=1, output_dims=2)
|
|
226
|
+
self._value_dense = EinsumDense(
|
|
227
|
+
einsum_equation,
|
|
228
|
+
output_shape=_get_output_shape(output_rank - 1,
|
|
229
|
+
[self._num_heads, self._value_dim]),
|
|
230
|
+
bias_axes=bias_axes if self._use_bias else None,
|
|
231
|
+
name='value',
|
|
232
|
+
**self._get_common_kwargs_for_sublayer())
|
|
233
|
+
self._value_dense.build(value_shape)
|
|
234
|
+
# Builds the attention computations for multi-head dot product
|
|
235
|
+
# attention. These computations could be wrapped into the keras
|
|
236
|
+
# attention layer once it supports multi-head einsum computations.
|
|
237
|
+
self._build_attention(output_rank)
|
|
238
|
+
self._output_dense = self._make_output_dense(
|
|
239
|
+
query_shape,
|
|
240
|
+
self._get_common_kwargs_for_sublayer(),
|
|
241
|
+
'attention_output',
|
|
242
|
+
)
|
|
243
|
+
output_dense_input_shape = list(
|
|
244
|
+
self._query_dense.compute_output_shape(query_shape))
|
|
245
|
+
output_dense_input_shape[-1] = self._value_dim
|
|
246
|
+
self._output_dense.build(tuple(output_dense_input_shape))
|
|
247
|
+
self.built = True
|
|
248
|
+
print('MultiHeadAttention (%s) built' % self.name)
|
|
249
|
+
|
|
250
|
+
@property
|
|
251
|
+
def query_dense(self):
|
|
252
|
+
return self._query_dense
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def key_dense(self):
|
|
256
|
+
return self._key_dense
|
|
257
|
+
|
|
258
|
+
@property
|
|
259
|
+
def value_dense(self):
|
|
260
|
+
return self._value_dense
|
|
261
|
+
|
|
262
|
+
@property
|
|
263
|
+
def output_dense(self):
|
|
264
|
+
return self._output_dense
|
|
265
|
+
|
|
266
|
+
def _get_common_kwargs_for_sublayer(self):
|
|
267
|
+
common_kwargs = dict(
|
|
268
|
+
kernel_regularizer=self._kernel_regularizer,
|
|
269
|
+
bias_regularizer=self._bias_regularizer,
|
|
270
|
+
activity_regularizer=self._activity_regularizer,
|
|
271
|
+
kernel_constraint=self._kernel_constraint,
|
|
272
|
+
bias_constraint=self._bias_constraint,
|
|
273
|
+
dtype=tf.float32,
|
|
274
|
+
)
|
|
275
|
+
# Create new clone of kernel/bias initializer, so that we don't reuse
|
|
276
|
+
# the initializer instance, which could lead to same init value since
|
|
277
|
+
# initializer is stateless.
|
|
278
|
+
kernel_initializer = self._kernel_initializer.__class__.from_config(
|
|
279
|
+
self._kernel_initializer.get_config())
|
|
280
|
+
bias_initializer = self._bias_initializer.__class__.from_config(
|
|
281
|
+
self._bias_initializer.get_config())
|
|
282
|
+
common_kwargs['kernel_initializer'] = kernel_initializer
|
|
283
|
+
common_kwargs['bias_initializer'] = bias_initializer
|
|
284
|
+
return common_kwargs
|
|
285
|
+
|
|
286
|
+
def _make_output_dense(self, query_shape, common_kwargs, name=None):
|
|
287
|
+
"""Builds the output projection matrix.
|
|
288
|
+
|
|
289
|
+
Args:
|
|
290
|
+
query_shape: query tensor shape
|
|
291
|
+
common_kwargs: Common keyword arguments for einsum layer.
|
|
292
|
+
name: Name for the projection layer.
|
|
293
|
+
|
|
294
|
+
Returns:
|
|
295
|
+
Projection layer.
|
|
296
|
+
"""
|
|
297
|
+
query_rank = len(query_shape)
|
|
298
|
+
if self._output_shape:
|
|
299
|
+
if hasattr(self._output_shape, '__len__'):
|
|
300
|
+
output_shape = self._output_shape
|
|
301
|
+
else:
|
|
302
|
+
output_shape = [self._output_shape]
|
|
303
|
+
else:
|
|
304
|
+
output_shape = [query_shape[-1]]
|
|
305
|
+
einsum_equation, bias_axes, output_rank = _build_proj_equation(
|
|
306
|
+
query_rank - 1, bound_dims=2, output_dims=len(output_shape))
|
|
307
|
+
return EinsumDense(
|
|
308
|
+
einsum_equation,
|
|
309
|
+
output_shape=_get_output_shape(output_rank - 1, output_shape),
|
|
310
|
+
bias_axes=bias_axes if self._use_bias else None,
|
|
311
|
+
name=name,
|
|
312
|
+
**common_kwargs)
|
|
313
|
+
|
|
314
|
+
def _build_attention(self, rank):
|
|
315
|
+
"""Builds multi-head dot-product attention computations.
|
|
316
|
+
|
|
317
|
+
This function builds attributes necessary for `_compute_attention` to
|
|
318
|
+
customize attention computation to replace the default dot-product
|
|
319
|
+
attention.
|
|
320
|
+
|
|
321
|
+
Args:
|
|
322
|
+
rank: the rank of query, key, value tensors.
|
|
323
|
+
"""
|
|
324
|
+
if self._attention_axes is None:
|
|
325
|
+
self._attention_axes = tuple(range(1, rank - 2))
|
|
326
|
+
else:
|
|
327
|
+
self._attention_axes = tuple(self._attention_axes)
|
|
328
|
+
(
|
|
329
|
+
self._dot_product_equation,
|
|
330
|
+
self._combine_equation,
|
|
331
|
+
attn_scores_rank,
|
|
332
|
+
) = _build_attention_equation(
|
|
333
|
+
rank, attn_axes=self._attention_axes)
|
|
334
|
+
norm_axes = tuple(
|
|
335
|
+
range(attn_scores_rank - len(self._attention_axes), attn_scores_rank))
|
|
336
|
+
self._softmax = Softmax(
|
|
337
|
+
axis=norm_axes) if tf.__version__ >= '2.0' else MaskedSoftmax(
|
|
338
|
+
axis=norm_axes)
|
|
339
|
+
self._dropout_layer = Dropout(rate=self._dropout)
|
|
340
|
+
self._inverse_sqrt_key_dim = 1.0 / math.sqrt(float(self._key_dim))
|
|
341
|
+
|
|
342
|
+
def _masked_softmax(self, attention_scores, attention_mask=None):
|
|
343
|
+
# Normalize the attention scores to probabilities.
|
|
344
|
+
# attention_scores = [B, N, T, S]
|
|
345
|
+
if attention_mask is not None:
|
|
346
|
+
# The expand dim happens starting from the `num_heads` dimension,
|
|
347
|
+
# (<batch_dims>, num_heads, <query_attention_dims,
|
|
348
|
+
# key_attention_dims>)
|
|
349
|
+
mask_expansion_axis = -len(self._attention_axes) * 2 - 1
|
|
350
|
+
for _ in range(len(attention_scores.shape) - len(attention_mask.shape)):
|
|
351
|
+
attention_mask = tf.expand_dims(
|
|
352
|
+
attention_mask, axis=mask_expansion_axis)
|
|
353
|
+
return self._softmax(attention_scores, mask=attention_mask)
|
|
354
|
+
|
|
355
|
+
def _compute_attention(self,
|
|
356
|
+
query,
|
|
357
|
+
key,
|
|
358
|
+
value,
|
|
359
|
+
attention_mask=None,
|
|
360
|
+
training=None):
|
|
361
|
+
"""Applies Dot-product attention with query, key, value tensors.
|
|
362
|
+
|
|
363
|
+
This function defines the computation inside `call` with projected
|
|
364
|
+
multi-head Q, K, V inputs. Users can override this function for
|
|
365
|
+
customized attention implementation.
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
query: Projected query tensor of shape `(B, T, N, key_dim)`.
|
|
369
|
+
key: Projected key tensor of shape `(B, S, N, key_dim)`.
|
|
370
|
+
value: Projected value tensor of shape `(B, S, N, value_dim)`.
|
|
371
|
+
attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
|
|
372
|
+
attention to certain positions. It is generally not needed if
|
|
373
|
+
the `query` and `value` (and/or `key`) are masked.
|
|
374
|
+
training: Python boolean indicating whether the layer should behave
|
|
375
|
+
in training mode (adding dropout) or in inference mode (doing
|
|
376
|
+
nothing).
|
|
377
|
+
|
|
378
|
+
Returns:
|
|
379
|
+
attention_output: Multi-headed outputs of attention computation.
|
|
380
|
+
attention_scores: Multi-headed attention weights.
|
|
381
|
+
"""
|
|
382
|
+
# Note: Applying scalar multiply at the smaller end of einsum improves
|
|
383
|
+
# XLA performance, but may introduce slight numeric differences in
|
|
384
|
+
# the Transformer attention head.
|
|
385
|
+
query = tf.multiply(query, tf.cast(self._inverse_sqrt_key_dim, query.dtype))
|
|
386
|
+
|
|
387
|
+
# Take the dot product between "query" and "key" to get the raw
|
|
388
|
+
# attention scores.
|
|
389
|
+
attention_scores = tf.einsum(self._dot_product_equation, key, query)
|
|
390
|
+
|
|
391
|
+
attention_scores = self._masked_softmax(attention_scores, attention_mask)
|
|
392
|
+
|
|
393
|
+
# This is actually dropping out entire tokens to attend to, which might
|
|
394
|
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
|
395
|
+
if self.dropout:
|
|
396
|
+
final_attn_scores = self._dropout_layer(
|
|
397
|
+
attention_scores, training=training)
|
|
398
|
+
else:
|
|
399
|
+
final_attn_scores = attention_scores
|
|
400
|
+
|
|
401
|
+
# `context_layer` = [B, T, N, H]
|
|
402
|
+
attention_output = tf.einsum(self._combine_equation, final_attn_scores,
|
|
403
|
+
value)
|
|
404
|
+
return attention_output, attention_scores
|
|
405
|
+
|
|
406
|
+
def call(self, inputs, mask=None, training=None, **kwargs):
|
|
407
|
+
assert isinstance(
|
|
408
|
+
inputs, (tuple, list)), 'inputs of MultiHeadAttention must be a list'
|
|
409
|
+
query, value, key = (list(inputs) + [None] * 2)[:3]
|
|
410
|
+
if key is None:
|
|
411
|
+
key = value
|
|
412
|
+
if mask is None:
|
|
413
|
+
masks = [None] * 4
|
|
414
|
+
elif type(mask) in (list, tuple):
|
|
415
|
+
masks = (list(mask) + [None] * 4)[:4]
|
|
416
|
+
else:
|
|
417
|
+
masks = ([mask] + [None] * 3)[:4]
|
|
418
|
+
query_mask, value_mask, key_mask, attention_mask = masks
|
|
419
|
+
if attention_mask is None and value_mask is None:
|
|
420
|
+
value_mask = query_mask
|
|
421
|
+
attention_mask = self._compute_attention_mask(
|
|
422
|
+
query,
|
|
423
|
+
value,
|
|
424
|
+
query_mask=query_mask,
|
|
425
|
+
value_mask=value_mask,
|
|
426
|
+
key_mask=key_mask,
|
|
427
|
+
attention_mask=attention_mask,
|
|
428
|
+
use_causal_mask=self._use_causal_mask,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
# N = `num_attention_heads`
|
|
432
|
+
# H = `size_per_head`
|
|
433
|
+
# `query` = [B, T, N ,H]
|
|
434
|
+
query = self._query_dense(query)
|
|
435
|
+
|
|
436
|
+
# `key` = [B, S, N, H]
|
|
437
|
+
key = self._key_dense(key)
|
|
438
|
+
|
|
439
|
+
# `value` = [B, S, N, H]
|
|
440
|
+
value = self._value_dense(value)
|
|
441
|
+
attention_output, attention_scores = self._compute_attention(
|
|
442
|
+
query, key, value, attention_mask, training)
|
|
443
|
+
attention_output = self._output_dense(attention_output)
|
|
444
|
+
if self._return_attention_scores:
|
|
445
|
+
return attention_output, attention_scores
|
|
446
|
+
return attention_output
|
|
447
|
+
|
|
448
|
+
def _compute_attention_mask(
|
|
449
|
+
self,
|
|
450
|
+
query,
|
|
451
|
+
value,
|
|
452
|
+
query_mask=None,
|
|
453
|
+
value_mask=None,
|
|
454
|
+
key_mask=None,
|
|
455
|
+
attention_mask=None,
|
|
456
|
+
use_causal_mask=False,
|
|
457
|
+
):
|
|
458
|
+
"""Computes the attention mask, using the Keras masks of the inputs.
|
|
459
|
+
|
|
460
|
+
* The `query`'s mask is reshaped from [B, T] to [B, T, 1].
|
|
461
|
+
* The `value`'s mask is reshaped from [B, S] to [B, 1, S].
|
|
462
|
+
* The `key`'s mask is reshaped from [B, S] to [B, 1, S]. The `key`'s
|
|
463
|
+
mask is ignored if `key` is `None` or if `key is value`.
|
|
464
|
+
* If `use_causal_mask=True`, then the causal mask is computed. Its shape
|
|
465
|
+
is [1, T, S].
|
|
466
|
+
|
|
467
|
+
All defined masks are merged using a logical AND operation (`&`).
|
|
468
|
+
|
|
469
|
+
In general, if the `query` and `value` are masked, then there is no need
|
|
470
|
+
to define the `attention_mask`.
|
|
471
|
+
|
|
472
|
+
Args:
|
|
473
|
+
query: Projected query tensor of shape `(B, T, N, key_dim)`.
|
|
474
|
+
value: Projected value tensor of shape `(B, T, N, value_dim)`.
|
|
475
|
+
attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
|
|
476
|
+
attention to certain positions.
|
|
477
|
+
use_causal_mask: A boolean to indicate whether to apply a causal
|
|
478
|
+
mask to prevent tokens from attending to future tokens (e.g.,
|
|
479
|
+
used in a decoder Transformer).
|
|
480
|
+
|
|
481
|
+
Returns:
|
|
482
|
+
attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
|
|
483
|
+
attention to certain positions, based on the Keras masks of the
|
|
484
|
+
`query`, `key`, `value`, and `attention_mask` tensors, and the
|
|
485
|
+
causal mask if `use_causal_mask=True`.
|
|
486
|
+
"""
|
|
487
|
+
auto_mask = None
|
|
488
|
+
if query_mask is not None:
|
|
489
|
+
query_mask = tf.cast(query_mask, tf.bool) # defensive casting
|
|
490
|
+
# B = batch size, T = max query length
|
|
491
|
+
auto_mask = tf.expand_dims(query_mask, -1) # shape is [B, T, 1]
|
|
492
|
+
if value_mask is not None:
|
|
493
|
+
value_mask = tf.cast(value_mask, tf.bool) # defensive casting
|
|
494
|
+
# B = batch size, S == max value length
|
|
495
|
+
mask = tf.expand_dims(value_mask, -2) # shape is [B, 1, S]
|
|
496
|
+
auto_mask = mask if auto_mask is None else auto_mask & mask
|
|
497
|
+
if key_mask is not None:
|
|
498
|
+
key_mask = tf.cast(key_mask, tf.bool) # defensive casting
|
|
499
|
+
# B == batch size, S == max key length == max value length
|
|
500
|
+
mask = tf.expand_dims(key_mask, -2) # shape is [B, 1, S]
|
|
501
|
+
auto_mask = mask if auto_mask is None else auto_mask & mask
|
|
502
|
+
if use_causal_mask:
|
|
503
|
+
# the shape of the causal mask is [1, T, S]
|
|
504
|
+
mask = self._compute_causal_mask(query, value)
|
|
505
|
+
auto_mask = mask if auto_mask is None else auto_mask & mask
|
|
506
|
+
if auto_mask is not None:
|
|
507
|
+
# merge attention_mask & automatic mask, to shape [B, T, S]
|
|
508
|
+
attention_mask = (
|
|
509
|
+
auto_mask if attention_mask is None else
|
|
510
|
+
tf.cast(attention_mask, tf.bool) & auto_mask)
|
|
511
|
+
return attention_mask
|
|
512
|
+
|
|
513
|
+
def _compute_causal_mask(self, query, value=None):
|
|
514
|
+
"""Computes a causal mask (e.g., for masked self-attention layers).
|
|
515
|
+
|
|
516
|
+
For example, if query and value both contain sequences of length 4,
|
|
517
|
+
this function returns a boolean tensor equal to:
|
|
518
|
+
|
|
519
|
+
```
|
|
520
|
+
[[[True, False, False, False],
|
|
521
|
+
[True, True, False, False],
|
|
522
|
+
[True, True, True, False],
|
|
523
|
+
[True, True, True, True]]]
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
Args:
|
|
527
|
+
query: query tensor of shape `(B, T, ...)`.
|
|
528
|
+
value: value tensor of shape `(B, S, ...)` (optional, defaults to
|
|
529
|
+
query).
|
|
530
|
+
|
|
531
|
+
Returns:
|
|
532
|
+
mask: a boolean tensor of shape `(1, T, S)` containing a lower
|
|
533
|
+
triangular matrix of shape `(T, S)`.
|
|
534
|
+
"""
|
|
535
|
+
q_seq_length = tf.shape(query)[1]
|
|
536
|
+
v_seq_length = q_seq_length if value is None else tf.shape(value)[1]
|
|
537
|
+
ones_mask = tf.ones((1, q_seq_length, v_seq_length), dtype='int32')
|
|
538
|
+
row_index = tf.cumsum(ones_mask, axis=-2)
|
|
539
|
+
col_index = tf.cumsum(ones_mask, axis=-1)
|
|
540
|
+
return tf.greater_equal(row_index, col_index)
|
|
541
|
+
|
|
542
|
+
def compute_output_shape(self, input_shape):
|
|
543
|
+
if len(input_shape) == 3:
|
|
544
|
+
query_shape, value_shape, key_shape = input_shape
|
|
545
|
+
elif len(input_shape) == 2:
|
|
546
|
+
query_shape, value_shape = input_shape
|
|
547
|
+
key_shape = None
|
|
548
|
+
else:
|
|
549
|
+
raise ValueError('invalid input shape of MultiHeadAttention')
|
|
550
|
+
if key_shape is None:
|
|
551
|
+
key_shape = value_shape
|
|
552
|
+
|
|
553
|
+
if query_shape[-1] != value_shape[-1]:
|
|
554
|
+
raise ValueError(
|
|
555
|
+
'The last dimension of `query_shape` and `value_shape` '
|
|
556
|
+
'must be equal, but are {query_last_dim}, {value_last_dim}. '
|
|
557
|
+
'Received: query_shape={query_shape}, value_shape={value_shape}'
|
|
558
|
+
.format(
|
|
559
|
+
query_shape=query_shape,
|
|
560
|
+
value_shape=value_shape,
|
|
561
|
+
query_last_dim=query_shape[-1],
|
|
562
|
+
value_last_dim=value_shape[-1]))
|
|
563
|
+
|
|
564
|
+
if value_shape[1:-1] != key_shape[1:-1]:
|
|
565
|
+
raise ValueError(
|
|
566
|
+
'All dimensions of `value` and `key`, except the last one, '
|
|
567
|
+
'must be equal. Received: value_shape={value_shape} and '
|
|
568
|
+
'key_shape={key_shape}'.format(
|
|
569
|
+
key_shape=key_shape, value_shape=value_shape))
|
|
570
|
+
|
|
571
|
+
if self._output_shape:
|
|
572
|
+
if hasattr(self._output_dense, '__len__'):
|
|
573
|
+
return query_shape[:-1] + self._output_shape
|
|
574
|
+
else:
|
|
575
|
+
return query_shape[:-1] + [self._output_shape]
|
|
576
|
+
|
|
577
|
+
return query_shape
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _index_to_einsum_variable(i):
|
|
581
|
+
"""Coverts an index to a einsum variable name.
|
|
582
|
+
|
|
583
|
+
We simply map indices to lowercase characters, e.g. 0 -> 'a', 1 -> 'b'.
|
|
584
|
+
"""
|
|
585
|
+
return string.ascii_lowercase[i]
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _build_attention_equation(rank, attn_axes):
|
|
589
|
+
"""Builds einsum equations for the attention computation.
|
|
590
|
+
|
|
591
|
+
Query, key, value inputs after projection are expected to have the shape as:
|
|
592
|
+
`(bs, <non-attention dims>, <attention dims>, num_heads, channels)`.
|
|
593
|
+
`bs` and `<non-attention dims>` are treated as `<batch dims>`.
|
|
594
|
+
|
|
595
|
+
The attention operations can be generalized:
|
|
596
|
+
1. Query-key dot product:
|
|
597
|
+
(<batch dims>, <query attention dims>, num_heads, channels),
|
|
598
|
+
(<batch dims>, <key attention dims>, num_heads, channels) ->
|
|
599
|
+
(<batch dims>, num_heads, <query attention dims>, <key attention dims>)
|
|
600
|
+
2. Combination:
|
|
601
|
+
(<batch dims>, num_heads, <query attention dims>, <key attention dims>),
|
|
602
|
+
(<batch dims>, <value attention dims>, num_heads, channels) -> (<batch
|
|
603
|
+
dims>, <query attention dims>, num_heads, channels)
|
|
604
|
+
|
|
605
|
+
Args:
|
|
606
|
+
rank: Rank of query, key, value tensors.
|
|
607
|
+
attn_axes: List/tuple of axes, `[-1, rank)`,
|
|
608
|
+
that attention will be applied to.
|
|
609
|
+
|
|
610
|
+
Returns:
|
|
611
|
+
Einsum equations.
|
|
612
|
+
"""
|
|
613
|
+
target_notation = ''
|
|
614
|
+
for i in range(rank):
|
|
615
|
+
target_notation += _index_to_einsum_variable(i)
|
|
616
|
+
# `batch_dims` includes the head dim.
|
|
617
|
+
batch_dims = tuple(np.delete(range(rank), attn_axes + (rank - 1,)))
|
|
618
|
+
letter_offset = rank
|
|
619
|
+
source_notation = ''
|
|
620
|
+
for i in range(rank):
|
|
621
|
+
if i in batch_dims or i == rank - 1:
|
|
622
|
+
source_notation += target_notation[i]
|
|
623
|
+
else:
|
|
624
|
+
source_notation += _index_to_einsum_variable(letter_offset)
|
|
625
|
+
letter_offset += 1
|
|
626
|
+
|
|
627
|
+
product_notation = ''.join([target_notation[i] for i in batch_dims] +
|
|
628
|
+
[target_notation[i] for i in attn_axes] +
|
|
629
|
+
[source_notation[i] for i in attn_axes])
|
|
630
|
+
dot_product_equation = '%s,%s->%s' % (
|
|
631
|
+
source_notation,
|
|
632
|
+
target_notation,
|
|
633
|
+
product_notation,
|
|
634
|
+
)
|
|
635
|
+
attn_scores_rank = len(product_notation)
|
|
636
|
+
combine_equation = '%s,%s->%s' % (
|
|
637
|
+
product_notation,
|
|
638
|
+
source_notation,
|
|
639
|
+
target_notation,
|
|
640
|
+
)
|
|
641
|
+
return dot_product_equation, combine_equation, attn_scores_rank
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _build_proj_equation(free_dims, bound_dims, output_dims):
|
|
645
|
+
"""Builds an einsum equation for projections inside multi-head attention."""
|
|
646
|
+
input_str = ''
|
|
647
|
+
kernel_str = ''
|
|
648
|
+
output_str = ''
|
|
649
|
+
bias_axes = ''
|
|
650
|
+
letter_offset = 0
|
|
651
|
+
for i in range(free_dims):
|
|
652
|
+
char = _index_to_einsum_variable(i + letter_offset)
|
|
653
|
+
input_str += char
|
|
654
|
+
output_str += char
|
|
655
|
+
|
|
656
|
+
letter_offset += free_dims
|
|
657
|
+
for i in range(bound_dims):
|
|
658
|
+
char = _index_to_einsum_variable(i + letter_offset)
|
|
659
|
+
input_str += char
|
|
660
|
+
kernel_str += char
|
|
661
|
+
|
|
662
|
+
letter_offset += bound_dims
|
|
663
|
+
for i in range(output_dims):
|
|
664
|
+
char = _index_to_einsum_variable(i + letter_offset)
|
|
665
|
+
kernel_str += char
|
|
666
|
+
output_str += char
|
|
667
|
+
bias_axes += char
|
|
668
|
+
equation = '{input_str},{kernel_str}->{output_str}'.format(
|
|
669
|
+
input_str=input_str, kernel_str=kernel_str, output_str=output_str)
|
|
670
|
+
return equation, bias_axes, len(output_str)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _get_output_shape(output_rank, known_last_dims):
|
|
674
|
+
return [None] * (output_rank - len(known_last_dims)) + list(known_last_dims)
|
|
675
|
+
|
|
676
|
+
# def __init__(self, params, name='multi_head_attention', reuse=None, **kwargs):
|
|
677
|
+
# super(MultiHeadAttention, self).__init__(name=name, **kwargs)
|
|
678
|
+
# self.num_heads = params.num_attention_heads
|
|
679
|
+
# self.d_model = params.hidden_size
|
|
680
|
+
# if self.d_model % self.num_heads != 0:
|
|
681
|
+
# raise ValueError(
|
|
682
|
+
# 'The hidden size (%d) is not a multiple of the number of attention '
|
|
683
|
+
# 'heads (%d)' % (self.d_model, self.num_heads))
|
|
684
|
+
# self.depth = self.d_model // self.num_heads
|
|
685
|
+
# self.wq = Dense(self.d_model)
|
|
686
|
+
# self.wk = Dense(self.d_model)
|
|
687
|
+
# self.wv = Dense(self.d_model)
|
|
688
|
+
# self.dense = Dense(self.d_model)
|
|
689
|
+
# att_params = Parameter.make_from_pb(params.attention)
|
|
690
|
+
# self.attention = Attention(att_params, 'scaled_dot_product_attention')
|
|
691
|
+
#
|
|
692
|
+
# # def split_heads(self, x, batch_size):
|
|
693
|
+
# # x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
|
|
694
|
+
# # return tf.transpose(x, perm=[0, 2, 1, 3])
|
|
695
|
+
#
|
|
696
|
+
# def call(self, inputs, training=None, **kwargs):
|
|
697
|
+
# q, v, k, mask = inputs
|
|
698
|
+
# batch_size = tf.shape(q)[0]
|
|
699
|
+
#
|
|
700
|
+
# q = self.wq(q)
|
|
701
|
+
# k = self.wk(k)
|
|
702
|
+
# v = self.wv(v)
|
|
703
|
+
#
|
|
704
|
+
# # q = self.split_heads(q, batch_size)
|
|
705
|
+
# # k = self.split_heads(k, batch_size)
|
|
706
|
+
# # v = self.split_heads(v, batch_size)
|
|
707
|
+
#
|
|
708
|
+
# attn = self.attention([q, v, k], mask=[mask, mask], training=training)
|
|
709
|
+
# return_attn_score = self.attention.return_attention_scores
|
|
710
|
+
# attention, attention_scores = attn if return_attn_score else attn, None
|
|
711
|
+
#
|
|
712
|
+
# # attention = tf.transpose(attention, perm=[0, 2, 1, 3])
|
|
713
|
+
# # attention = tf.reshape(attention, (batch_size, -1, self.d_model))
|
|
714
|
+
# output = self.dense(attention)
|
|
715
|
+
# if return_attn_score:
|
|
716
|
+
# return output, attention_scores
|
|
717
|
+
# return output
|