├── LICENSE ├── README.md ├── channel_selector.py ├── data_reader.py ├── hyper_param.py ├── id_allocator.py ├── layer_util.py ├── sample.data.part1 ├── sample.data.part2 └── sample.data.part3 /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## HRL-Rec 3 | 4 | Integrated recommendation aims to jointly recommend heterogeneous items in the main feed from different sources via multiple channels, which needs to capture user preferences on both item and channel levels. 5 | It has been widely used in practical systems by billions of users, while few works concentrate on the integrated recommendation systematically. 6 | 7 | In this work, we propose a novel Hierarchical reinforcement learning framework for integrated recommendation (HRL-Rec), which divides the integrated recommendation into two tasks to recommend channels and items sequentially. 8 | 9 | The low-level agent is a channel selector, which generates a personalized channel list. The high-level agent is an item recommender, which recommends specific items from heterogeneous channels under the channel constraints. 10 | 11 | HRL-Rec has also been deployed on WeChat Top Stories, affecting millions of users. 12 | 13 | ### Requirements: 14 | - Python 3.9 15 | - Tensorflow 2.5.0-rc0 16 | 17 | ## Note 18 | 19 | In the actual online system, HRL-Rec is a complex re-ranking framework implemented in C++. All models are trained based on a deeply customized version of distributed tensorflow supporting large-scale sparse features. 20 | 21 | Without massive data and machine resources, training HRL-Rec is not realistic. 22 | 23 | Therefore, the open source code here only implements a simplified version of its core ideas for the reference of interested researchers. If there are any errors, please contact me. Thanks! 24 | 25 | ## About 26 | 27 | "Hierarchical Reinforcement Learning for Integrated Recommendation" ([AAAI 2020](https://ojs.aaai.org/index.php/AAAI/article/view/16580)) 28 | -------------------------------------------------------------------------------- /channel_selector.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a simplified implementation of channel selector. 3 | 4 | February 2020 5 | modric10zhang@gmail.com 6 | 7 | """ 8 | 9 | import os 10 | import numpy as np 11 | import tensorflow.compat.v1 as tf 12 | from layer_util import * 13 | from data_reader import DataReader 14 | from hyper_param import param_dict as pd 15 | 16 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 17 | tf.disable_eager_execution() 18 | 19 | g_working_mode = 'local_train' 20 | g_training = False 21 | g_dr = DataReader(pd['batch_size']) 22 | 23 | 24 | class PolicyNetwork(object): 25 | def __init__(self): 26 | # placeholder 27 | self.sph_user = tf.sparse_placeholder(tf.int32, name='sph_user') 28 | self.sph_doc = tf.sparse_placeholder(tf.int32, name='sph_doc') 29 | self.sph_con = tf.sparse_placeholder(tf.int32, name='sph_con') 30 | # policy gradient 31 | self.a_grads = tf.placeholder(tf.float32) 32 | # policy network 33 | self.doc_embed, self.mpa, self.mea = self.build_net('main') 34 | # target network 35 | _, self.tpa, self.tea = self.build_net('target') 36 | # optional supervised signal, to avoid instability of actions in extreme cases 37 | self.loss = tf.losses.mean_squared_error(self.doc_embed, self.mea) 38 | params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='main/policy') 39 | params.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='main/feat_embedding')) 40 | self.grads = tf.clip_by_global_norm(tf.gradients(self.loss, params), pd['grad_clip'])[0] 41 | policy_grads = \ 42 | tf.clip_by_global_norm(tf.gradients(ys=self.mea, xs=params, grad_ys=self.a_grads), pd['grad_clip'])[0] 43 | opt1 = tf.train.AdamOptimizer(-pd['lr']) 44 | opt2 = tf.train.AdamOptimizer(pd['lr']) 45 | with tf.variable_scope("train_policy"): 46 | self.opt_a1 = opt1.apply_gradients(zip(policy_grads, params)) 47 | self.opt_a2 = opt2.apply_gradients(zip(self.grads, params)) 48 | self.m_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="main/policy") 49 | self.m_params.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='main/feat_embedding')) 50 | self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="target/policy") 51 | self.t_params.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target/feat_embedding')) 52 | alpha = pd['double_networks_sync_step'] 53 | self.sync_op = [tf.assign(t, (1.0 - alpha) * t + alpha * m) for t, m in zip(self.t_params, self.m_params)] 54 | self.total_loss, self.batch_counter = 0.0, 0 55 | 56 | def encode(self, seq_embed, query_embed): 57 | q = tf.layers.dropout(query_embed, rate=pd['dropout'], training=g_training) 58 | kv = tf.layers.dropout(seq_embed, rate=pd['dropout'], training=g_training) 59 | for i in range(pd['encoder_layer']): 60 | with tf.variable_scope('encoder_%d' % (i + 1)): 61 | # self-attention 62 | enc = multihead_attention(queries=q, keys=kv, values=kv, num_heads=pd['head_num'], 63 | dropout_rate=pd['dropout'], 64 | training=g_training, causality=False, scope='mha') 65 | ff_dim = enc.get_shape().as_list()[-1] 66 | # feed forward 67 | enc = feed_forward(enc, num_units=[ff_dim, ff_dim], activation=tf.nn.tanh, scope='ff') 68 | return enc 69 | 70 | def build_net(self, var_scope): 71 | with tf.variable_scope(var_scope, reuse=tf.AUTO_REUSE): 72 | feat_dict = get_embeddings(g_dr.unique_feature_num(), 73 | pd['feat_dim'], 74 | scope='feat_embedding', 75 | zero_pad=False) 76 | with tf.variable_scope('policy'): 77 | usr_embed = tf.reshape( 78 | tf.nn.embedding_lookup_sparse(feat_dict, self.sph_user, sp_weights=None, combiner='mean'), 79 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['user_field_num'] * pd['feat_dim']]) 80 | doc_embed = tf.reshape( 81 | tf.nn.embedding_lookup_sparse(feat_dict, self.sph_doc, sp_weights=None, combiner='mean'), 82 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['doc_field_num'] * pd['feat_dim']]) 83 | con_embed = tf.reshape( 84 | tf.nn.embedding_lookup_sparse(feat_dict, self.sph_con, sp_weights=None, combiner='mean'), 85 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['con_field_num'] * pd['feat_dim']]) 86 | fi_embed = tf.concat([usr_embed, con_embed], axis=2) 87 | with tf.variable_scope('feature_interaction'): 88 | fi_embed = self.encode(fi_embed, fi_embed) 89 | fi_layer = tf.reshape(fi_embed, [pd['batch_size'], pd['rnn_max_len'], -1]) 90 | gru = tf.nn.rnn_cell.GRUCell(fi_layer.get_shape().as_list()[-1]) 91 | drop = tf.nn.rnn_cell.DropoutWrapper(gru, output_keep_prob=1.0 - pd['dropout'] if g_training else 1.) 92 | cell = tf.nn.rnn_cell.MultiRNNCell([drop for _ in range(pd['rnn_layer'])]) 93 | init_state = cell.zero_state(pd['batch_size'], tf.float32) 94 | outputs, state = tf.nn.dynamic_rnn(cell, fi_layer, initial_state=init_state, time_major=False) 95 | rnn_out = tf.reshape(outputs, [pd['batch_size'] * pd['rnn_max_len'], -1]) 96 | hdd_out = tf.layers.dropout(rnn_out, rate=pd['dropout'], training=g_training) 97 | p_action = tf.layers.dense(hdd_out, pd['doc_field_num'] * pd['feat_dim'], activation=tf.nn.tanh) 98 | p_action = tf.reshape(p_action, shape=[pd['batch_size'], pd['rnn_max_len'], -1]) 99 | explore_action = tf.truncated_normal( 100 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['doc_field_num'] * pd['feat_dim']], 101 | mean=0, 102 | stddev=pd['actor_explore_range'], 103 | dtype=tf.float32) 104 | # action with exploration 105 | e_action = p_action + explore_action 106 | return doc_embed, p_action, e_action 107 | 108 | def act(self, sess, ph_dict): 109 | return sess.run(self.mea if g_training else self.mpa, feed_dict={self.sph_user: ph_dict['user'], 110 | self.sph_con: ph_dict['con']}) 111 | 112 | def learn(self, sess, ph_dict): 113 | loss, _, _ = sess.run([self.loss, self.opt_a1, self.opt_a2], feed_dict={self.a_grads: ph_dict['a_grads'], 114 | self.sph_user: ph_dict['user'], 115 | self.sph_doc: ph_dict['doc'], 116 | self.sph_con: ph_dict['con']}) 117 | self.batch_counter += 1 118 | self.total_loss += loss 119 | 120 | 121 | class ValueNetwork(object): 122 | def __init__(self): 123 | # placeholder 124 | self.sph_user = tf.sparse_placeholder(tf.int32, name='sph_user') 125 | self.sph_doc = tf.sparse_placeholder(tf.int32, name='sph_doc') 126 | self.sph_con = tf.sparse_placeholder(tf.int32, name='sph_con') 127 | self.ph_reward = tf.placeholder(tf.float32, name='ph_reward') 128 | self.ph_nq = tf.placeholder(tf.float32, shape=[pd['batch_size'], pd['rnn_max_len']], name='ph_nq') 129 | # main networks 130 | self.dst_embed, self.mq = self.build_net('main') 131 | # target networks 132 | _, self.tq = self.build_net('target') 133 | diff = tf.reshape(self.ph_reward, [-1]) + tf.scalar_mul(tf.constant(pd['gamma']), 134 | tf.reshape(self.ph_nq, [-1])) - tf.reshape(self.mq, 135 | [-1]) 136 | self.loss = tf.reduce_mean(tf.square(diff)) 137 | self.a_grads = tf.clip_by_global_norm(tf.gradients(self.mq, self.dst_embed), pd['grad_clip'])[0] 138 | vs = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='main/value') 139 | vs.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='main/feat_embedding')) 140 | self.grads = tf.clip_by_global_norm(tf.gradients(self.loss, vs), pd['grad_clip'])[0] 141 | with tf.variable_scope('train_value'): 142 | optimizer = tf.train.AdamOptimizer(pd['lr']) 143 | self.opt = optimizer.apply_gradients(zip(self.grads, vs)) 144 | self.m_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="main/value") 145 | self.m_params.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='main/feat_embedding')) 146 | self.t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="target/value") 147 | self.t_params.extend(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target/feat_embedding')) 148 | alpha = pd['double_networks_sync_step'] 149 | self.sync_op = [tf.assign(t, (1.0 - alpha) * t + alpha * m) for t, m in zip(self.t_params, self.m_params)] 150 | self.total_loss, self.batch_counter = 0.0, 0 151 | 152 | def encode(self, seq_embed, query_embed): 153 | q = tf.layers.dropout(query_embed, rate=pd['dropout'], training=g_training) 154 | kv = tf.layers.dropout(seq_embed, rate=pd['dropout'], training=g_training) 155 | for i in range(pd['encoder_layer']): 156 | with tf.variable_scope('encoder_%d' % (i + 1)): 157 | # self-attention 158 | enc = multihead_attention(queries=q, keys=kv, values=kv, num_heads=pd['head_num'], 159 | dropout_rate=pd['dropout'], 160 | training=g_training, causality=False, scope='mha') 161 | ff_dim = enc.get_shape().as_list()[-1] 162 | # feed forward 163 | enc = feed_forward(enc, num_units=[ff_dim, ff_dim], activation=tf.nn.tanh, scope='ff') 164 | return enc 165 | 166 | def build_net(self, var_scope): 167 | with tf.variable_scope(var_scope, reuse=tf.AUTO_REUSE): 168 | feat_dict = get_embeddings(g_dr.unique_feature_num(), 169 | pd['feat_dim'], 170 | scope='feat_embedding', 171 | zero_pad=False) 172 | with tf.variable_scope('value'): 173 | usr_embed = tf.reshape( 174 | tf.nn.embedding_lookup_sparse(feat_dict, self.sph_user, sp_weights=None, combiner='mean'), 175 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['user_field_num'] * pd['feat_dim']]) 176 | doc_embed = tf.reshape( 177 | tf.nn.embedding_lookup_sparse(feat_dict, self.sph_doc, sp_weights=None, combiner='mean'), 178 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['doc_field_num'] * pd['feat_dim']]) 179 | con_embed = tf.reshape( 180 | tf.nn.embedding_lookup_sparse(feat_dict, self.sph_con, sp_weights=None, combiner='mean'), 181 | shape=[pd['batch_size'], pd['rnn_max_len'], pd['con_field_num'] * pd['feat_dim']]) 182 | fi_embed = tf.concat([usr_embed, doc_embed, con_embed], axis=2) 183 | with tf.variable_scope('feature_interaction'): 184 | fi_embed = self.encode(fi_embed, fi_embed) 185 | fi_layer = tf.reshape(fi_embed, [pd['batch_size'], pd['rnn_max_len'], -1]) 186 | gru = tf.nn.rnn_cell.GRUCell(fi_layer.get_shape().as_list()[-1]) 187 | drop = tf.nn.rnn_cell.DropoutWrapper(gru, output_keep_prob=1.0 - pd['dropout'] if g_training else 1.) 188 | cell = tf.nn.rnn_cell.MultiRNNCell([drop for _ in range(pd['rnn_layer'])]) 189 | init_state = cell.zero_state(pd['batch_size'], tf.float32) 190 | outputs, state = tf.nn.dynamic_rnn(cell, fi_layer, initial_state=init_state, time_major=False) 191 | rnn_out = tf.reshape(outputs, [pd['batch_size'] * pd['rnn_max_len'], -1]) 192 | hdd_out = tf.layers.dropout(rnn_out, rate=pd['dropout'], training=g_training) 193 | q = tf.layers.dense(hdd_out, 1, activation=tf.nn.relu) 194 | q = tf.reshape(q, [pd['batch_size'], pd['rnn_max_len']]) 195 | return doc_embed, q 196 | 197 | def critic(self, sess, ph_dict): 198 | return sess.run(self.mq, feed_dict={self.dst_embed: ph_dict['action'], 199 | self.sph_user: ph_dict['user'], 200 | self.sph_con: ph_dict['con']}) 201 | 202 | def predict_for_train(self, sess, ph_dict): 203 | return sess.run(self.tq, feed_dict={self.sph_user: ph_dict['user'], 204 | self.sph_doc: ph_dict['doc'], 205 | self.sph_con: ph_dict['con']}) 206 | 207 | def predict_for_eval(self, sess, ph_dict): 208 | return sess.run(self.mq, feed_dict={self.sph_user: ph_dict['user'], 209 | self.sph_doc: ph_dict['doc'], 210 | self.sph_con: ph_dict['con']}) 211 | 212 | def learn(self, sess, ph_dict): 213 | loss, _ = sess.run([self.loss, self.opt], feed_dict={self.ph_nq: ph_dict['next_q'], 214 | self.ph_reward: ph_dict['reward'], 215 | self.sph_user: ph_dict['user'], 216 | self.sph_doc: ph_dict['doc'], 217 | self.sph_con: ph_dict['con']}) 218 | self.batch_counter += 1 219 | self.total_loss += loss 220 | 221 | # policy gradient 222 | def pg(self, sess, ph_dict): 223 | return sess.run(self.a_grads, feed_dict={self.dst_embed: ph_dict['action'], 224 | self.sph_user: ph_dict['user'], 225 | self.sph_con: ph_dict['con']}) 226 | 227 | 228 | def handle(sess, actor, critic, sess_data): 229 | def gen_sparse_tensor(fs): 230 | global g_dr 231 | kk, vv = [], [] 232 | for i in range(len(fs)): 233 | ff = fs[i] 234 | assert (isinstance(ff, set)) 235 | ff = list(ff) 236 | for k in range(len(ff)): 237 | kk.append(np.array([i, k], dtype=np.int32)) 238 | vv.append(ff[k]) 239 | return tf.SparseTensorValue(kk, vv, [len(fs), g_dr.unique_feature_num()]) 240 | 241 | if len(sess_data) != pd['batch_size'] * pd['rnn_max_len']: 242 | return 243 | user, doc, con, rwd, rtn = [], [], [], [], [] 244 | # [sid, offset, user, doc, con, reward, return] 245 | for i in range(len(sess_data)): 246 | user.append(sess_data[i][2]) 247 | doc.append(sess_data[i][3]) 248 | con.append(sess_data[i][4]) 249 | rwd.append(sess_data[i][5]) 250 | rtn.append(sess_data[i][6]) 251 | phd = {} 252 | user = np.array(user).reshape(pd['batch_size'] * pd['rnn_max_len'] * pd['user_field_num']) 253 | phd['user'] = gen_sparse_tensor(user) 254 | doc = np.array(doc).reshape(pd['batch_size'] * pd['rnn_max_len'] * pd['doc_field_num']) 255 | phd['doc'] = gen_sparse_tensor(doc) 256 | con = np.array(con).reshape(pd['batch_size'] * pd['rnn_max_len'] * pd['con_field_num']) 257 | phd['con'] = gen_sparse_tensor(con) 258 | phd['reward'] = rwd 259 | if g_training: 260 | next_q = critic.predict_for_train(sess, phd) 261 | next_q = np.append(next_q[:, 1:], np.array([[0] for i in range(pd['batch_size'])], dtype=np.float32), 1) 262 | phd['next_q'] = next_q 263 | critic.learn(sess, phd) 264 | if critic.batch_counter % pd['double_networks_sync_freq'] == 0: 265 | print('>>> start run soft replacement for value networks...') 266 | sess.run(critic.sync_op) 267 | phd['action'] = actor.act(sess, phd) 268 | phd['a_grads'] = critic.pg(sess, phd) 269 | actor.learn(sess, phd) 270 | if actor.batch_counter % pd['double_networks_sync_freq'] == 0: 271 | print('>>> start run soft replacement for policy networks...') 272 | sess.run(actor.sync_op) 273 | else: 274 | cq = critic.predict_for_eval(sess, phd).reshape([-1]) 275 | phd['action'] = actor.act(sess, phd) 276 | aq = critic.critic(sess, phd).reshape([-1]) 277 | for i in range(len(rwd)): 278 | print('>>> reward:%f return:%f actor:%f critic:%f', rwd[i], rtn[i], aq[i], cq[i]) 279 | 280 | 281 | def work(): 282 | sess = tf.Session() 283 | # build networks 284 | actor = PolicyNetwork() 285 | critic = ValueNetwork() 286 | saver = tf.train.Saver(max_to_keep=1) 287 | g_init_op = tf.global_variables_initializer() 288 | if os.path.exists('./ckpt') and len(os.listdir('./ckpt')): 289 | model_file = tf.train.latest_checkpoint('./ckpt') 290 | saver.restore(sess, model_file) 291 | else: 292 | sess.run(g_init_op) 293 | os.system('mkdir ckpt') 294 | for k in range(pd['num_epochs'] if g_training else 1): 295 | if k > 0: 296 | g_dr.load('sample.data') 297 | data = g_dr.next() 298 | batch_cnt = 0 299 | while data is not None: 300 | handle(sess, actor, critic, data) 301 | data = g_dr.next() 302 | batch_cnt += 1 303 | if g_training and batch_cnt % 10 == 0: 304 | print('>>> average loss --- epoch %d --- batch %d --- %f --- %f' % ( 305 | k, batch_cnt, actor.total_loss / (actor.batch_counter + 1e-6), 306 | critic.total_loss / (critic.batch_counter + 1e-6))) 307 | saver.save(sess, 'ckpt/lra.ckpt') 308 | 309 | 310 | if __name__ == '__main__': 311 | g_dr.load('sample.data') 312 | if g_working_mode == 'local_train': 313 | g_training = True 314 | elif g_working_mode == 'local_predict': 315 | g_training = False 316 | else: 317 | raise Exception('invalid working mode') 318 | work() 319 | -------------------------------------------------------------------------------- /data_reader.py: -------------------------------------------------------------------------------- 1 | #!encoding=utf-8 2 | """ 3 | Data Reader 4 | 5 | February 2020 6 | modric10zhang@gmail.com 7 | """ 8 | import sys 9 | from id_allocator import IdAllocator 10 | from hyper_param import param_dict as pd 11 | 12 | 13 | def normalize_recommend(rec_list, max_len): 14 | """ 15 | If len(rec_list) < max_len, rec_list will be dropped. 16 | Otherwise, rec_list will be truncated. 17 | """ 18 | if len(rec_list) < max_len: 19 | return [] 20 | else: 21 | return rec_list[-max_len:] 22 | 23 | 24 | class DataReader(object): 25 | def __init__(self, batch_num): 26 | self._id_tool = IdAllocator() 27 | self._data = [] 28 | self._batch = batch_num * pd['rnn_max_len'] 29 | 30 | def unique_feature_num(self): 31 | return self._id_tool.unique_id_num() 32 | 33 | def parse_feature(self, raw_feature): 34 | feature = set() 35 | for f in raw_feature.split(','): 36 | feature.add(self._id_tool.allocate(f)) 37 | if len(feature) == 0: 38 | feature.add(0) 39 | return feature 40 | 41 | def load(self, sample_path): 42 | with open(sample_path, 'r') as fp: 43 | for line in fp: 44 | info = line.strip().split('\t') 45 | if len(info) != 3: 46 | raise Exception('invalid data!') 47 | sid = '' 48 | offset = 0 49 | clk_seq, rec_list = [], [] 50 | for ii in info: 51 | pos = ii.find(':') 52 | if pos <= 0: 53 | raise Exception('invalid data!') 54 | kk, vv = ii[:pos], ii[pos + 1:] 55 | if kk == 'sid': 56 | sid = vv 57 | elif kk == 'offset': 58 | offset = vv 59 | elif kk == 'rec_list': 60 | for doc in vv.split('|'): 61 | feats, rwd, rtn = [], 0.0, 0.0 62 | for ff in doc.split(' '): 63 | pos = ff.find(':') 64 | if pos <= 0: 65 | raise Exception('invalid data') 66 | fk, fv = ff[:pos], ff[pos + 1:] 67 | if fk == 'reward': 68 | rwd = float(fv) 69 | elif fk == 'return': 70 | rtn = float(fv) 71 | elif 'field' in fk: 72 | feats.append(self.parse_feature(fv)) 73 | rec_list.append([feats, rwd, rtn]) 74 | nrl = normalize_recommend(rec_list, pd['rnn_max_len']) 75 | if len(nrl): 76 | for doc in rec_list: 77 | offset1 = pd['user_field_num'] 78 | offset2 = pd['user_field_num'] + pd['doc_field_num'] 79 | self._data.append([sid, offset, 80 | doc[0][:offset1], 81 | doc[0][offset1:offset2], 82 | doc[0][offset2:], 83 | doc[1], 84 | doc[2]]) 85 | 86 | def next(self): 87 | nb = None 88 | if len(self._data) <= 0: 89 | return nb 90 | else: 91 | idx = len(self._data) if len(self._data) <= self._batch else self._batch 92 | nb = self._data[:idx] 93 | self._data = self._data[idx:] 94 | return nb 95 | -------------------------------------------------------------------------------- /hyper_param.py: -------------------------------------------------------------------------------- 1 | """ 2 | Model Hyper Parameter Dict 3 | 4 | February 2020 5 | modric10zhang@gmail.com 6 | 7 | """ 8 | 9 | param_dict = { 10 | 'num_epochs': 10, # training epoch 11 | 'feat_dim': 32, # feature embedding dimension 12 | 'field_num': 9, # number of user feature fields 13 | 'user_field_num': 3, # field number of user 14 | 'doc_field_num': 3, # field number of doc 15 | 'con_field_num': 3, # field number of context 16 | 'max_clk_seq': 10, # max click sequence 17 | 'rnn_max_len': 10, # max length of sequence in RNN 18 | 'rnn_layer': 1, # layer number of RNN 19 | 'batch_size': 16, # batch size 20 | 'gamma': 0.3, # discounted factor 21 | 'double_networks_sync_step': 0.1, # double networks sync step 22 | 'double_networks_sync_freq': 30, # double networks sync frequency 23 | 'actor_explore_range': 0.01, # exploration range for policy networks 24 | 'encoder_layer': 1, # encoder layer number 25 | 'head_num': 4, # head number for self-attention 26 | 'lr': 0.0002, # learning rate of network 27 | 'dropout': 0.3, # dropout ratio 28 | 'grad_clip': 5.0, # grad clip 29 | } 30 | -------------------------------------------------------------------------------- /id_allocator.py: -------------------------------------------------------------------------------- 1 | class IdAllocator(object): 2 | def __init__(self): 3 | self._id = 1 4 | self._tbl = {} 5 | 6 | def allocate(self, x): 7 | if type(x) is not str: 8 | raise Exception('only str is supported in IdAllocator.') 9 | if x not in self._tbl: 10 | self._id += 1 11 | self._tbl[x] = self._id 12 | return self._tbl[x] 13 | 14 | def unique_id_num(self): 15 | return self._id 16 | -------------------------------------------------------------------------------- /layer_util.py: -------------------------------------------------------------------------------- 1 | #!encoding=utf-8 2 | import tensorflow.compat.v1 as tf 3 | 4 | ''' 5 | The implementation of multi-head attention mechanism 6 | refers to Kyubyong/transformer(https://github.com/Kyubyong/transformer) 7 | 8 | February 2020 9 | modric10zhang@gmail.com 10 | 11 | ''' 12 | 13 | 14 | def layer_norm(inputs, scope='ln'): 15 | '''Applies layer normalization. See https://arxiv.org/abs/1607.06450. 16 | inputs: A tensor with 2 or more dimensions, where the first dimension has `batch_size`. 17 | epsilon: A floating number. A very small number for preventing ZeroDivision Error. 18 | scope: Optional scope for `variable_scope`. 19 | 20 | Returns: 21 | A tensor with the same shape and data dtype as `inputs`. 22 | ''' 23 | epsilon = 1e-8 24 | with tf.variable_scope(scope): 25 | inputs_shape = inputs.get_shape() 26 | params_shape = inputs_shape[-1:] 27 | # [-1] means last dimension 28 | mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True) 29 | beta = tf.get_variable("beta", params_shape, initializer=tf.zeros_initializer()) 30 | gamma = tf.get_variable("gamma", params_shape, initializer=tf.ones_initializer()) 31 | normalized = (inputs - mean) / ((variance + epsilon) ** (.5)) 32 | outputs = gamma * normalized + beta 33 | return outputs 34 | 35 | 36 | def get_embeddings(dict_size, num_units, scope, zero_pad=True, partitioner=None): 37 | '''Constructs token embedding matrix. 38 | Note that the column of index 0's are set to zeros. 39 | dict_size: scalar. V. 40 | num_units: embedding dimensionalty. E. 41 | zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero 42 | To apply query/key masks easily, zero pad is turned on. 43 | 44 | Returns 45 | weight variable: (V, E) 46 | ''' 47 | with tf.variable_scope(scope): 48 | w_init = tf.truncated_normal_initializer(mean=0, stddev=0.1) 49 | embeddings = tf.get_variable('w', 50 | dtype=tf.float32, 51 | shape=(dict_size, num_units), 52 | initializer=w_init, 53 | partitioner=partitioner) 54 | # initializer=tf.contrib.layers.xavier_initializer()) 55 | if zero_pad: 56 | embeddings = tf.concat((tf.zeros(shape=[1, num_units]), 57 | embeddings[1:, :]), 0) 58 | return embeddings 59 | 60 | 61 | def mask(inputs, queries=None, keys=None, type=None): 62 | """Masks paddings on keys or queries to inputs 63 | inputs: 3d tensor. (N, T_q, T_k) 64 | queries: 3d tensor. (N, T_q, d) 65 | keys: 3d tensor. (N, T_k, d) 66 | 67 | e.g., 68 | >> queries = tf.constant([[[1.], 69 | [2.], 70 | [0.]]], tf.float32) # (1, 3, 1) 71 | >> keys = tf.constant([[[4.], 72 | [0.]]], tf.float32) # (1, 2, 1) 73 | >> inputs = tf.constant([[[4., 0.], 74 | [8., 0.], 75 | [0., 0.]]], tf.float32) 76 | >> mask(inputs, queries, keys, "key") 77 | array([[[ 4.0000000e+00, -4.2949673e+09], 78 | [ 8.0000000e+00, -4.2949673e+09], 79 | [ 0.0000000e+00, -4.2949673e+09]]], dtype=float32) 80 | >> inputs = tf.constant([[[1., 0.], 81 | [1., 0.], 82 | [1., 0.]]], tf.float32) 83 | >> mask(inputs, queries, keys, "query") 84 | array([[[1., 0.], 85 | [1., 0.], 86 | [0., 0.]]], dtype=float32) 87 | """ 88 | padding_num = -2 ** 32 + 1 89 | #### 将keys对应的padding部分的权重设置成很大的一个负数(等价于不存在对应位置的attention) 90 | if type in ("k", "key", "keys"): 91 | # Generate masks 92 | masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1)) # (N, T_k) 93 | masks = tf.expand_dims(masks, 1) # (N, 1, T_k) 94 | masks = tf.tile(masks, [1, tf.shape(queries)[1], 1]) # (N, T_q, T_k) 95 | 96 | # Apply masks to inputs 97 | paddings = tf.ones_like(inputs) * padding_num 98 | outputs = tf.where(tf.equal(masks, 0), paddings, inputs) # (N, T_q, T_k) 99 | elif type in ("q", "query", "queries"): 100 | # Generate masks 101 | masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1)) # (N, T_q) 102 | masks = tf.expand_dims(masks, -1) # (N, T_q, 1) 103 | masks = tf.tile(masks, [1, 1, tf.shape(keys)[1]]) # (N, T_q, T_k) 104 | 105 | # Apply masks to inputs 106 | outputs = inputs * masks 107 | elif type in ("f", "future", "right"): 108 | diag_vals = tf.ones_like(inputs[0, :, :]) # (T_q, T_k) 109 | # tril = tf.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense() # (T_q, T_k) 110 | tril = tf.linalg.band_part(diag_vals, -1, 0) # (T_q, T_k) 111 | masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(inputs)[0], 1, 1]) # (N, T_q, T_k) 112 | 113 | paddings = tf.ones_like(masks) * padding_num 114 | outputs = tf.where(tf.equal(masks, 0), paddings, inputs) 115 | else: 116 | print("Check if you entered type correctly!") 117 | 118 | return outputs 119 | 120 | 121 | def scaled_dot_product_attention(Q, K, V, 122 | causality=False, dropout_rate=0., 123 | training=True, 124 | scope="sdpa"): 125 | '''See 3.2.1. 126 | Q: Packed queries. 3d tensor. [N, T_q, d_k]. 127 | K: Packed keys. 3d tensor. [N, T_k, d_k]. 128 | V: Packed values. 3d tensor. [N, T_k, d_v]. 129 | causality: If True, applies masking for future blinding 130 | dropout_rate: A floating point number of [0, 1]. 131 | training: boolean for controlling droput 132 | scope: Optional scope for `variable_scope`. 133 | ''' 134 | with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): 135 | d_k = Q.get_shape().as_list()[-1] 136 | # dot product 137 | outputs = tf.matmul(Q, tf.transpose(K, [0, 2, 1])) # (N, T_q, T_k) 138 | # scale 139 | outputs /= d_k ** 0.5 140 | # key masking 141 | outputs = mask(outputs, Q, K, type="key") 142 | # causality or future blinding masking 143 | if causality: 144 | outputs = mask(outputs, type="future") 145 | # softmax 146 | outputs = tf.nn.softmax(outputs) 147 | attention = tf.transpose(outputs, [0, 2, 1]) 148 | tf.summary.image("attention", tf.expand_dims(attention[:1], -1)) 149 | # query masking 150 | outputs = mask(outputs, Q, K, type="query") 151 | # dropout 152 | outputs = tf.layers.dropout(outputs, rate=dropout_rate, training=training) 153 | # weighted sum (context vectors) 154 | outputs = tf.matmul(outputs, V) # (N, T_q, d_v) 155 | return outputs 156 | 157 | 158 | def multihead_attention(queries, keys, values, 159 | num_heads=4, dropout_rate=0., 160 | training=True, 161 | causality=False, 162 | scope="mha"): 163 | '''Applies multihead attention. See 3.2.2 164 | queries: A 3d tensor with shape of [N, T_q, d_model]. 165 | keys: A 3d tensor with shape of [N, T_k, d_model]. 166 | values: A 3d tensor with shape of [N, T_k, d_model]. 167 | num_heads: An int. Number of heads. 168 | training: Boolean. Controller of mechanism for dropout. 169 | causality: Boolean. If true, units that reference the future are masked. 170 | scope: Optional scope for `variable_scope`. 171 | 172 | Returns 173 | A 3d tensor with shape of (N, T_q, C) 174 | ''' 175 | d_model = queries.get_shape().as_list()[-1] 176 | with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): 177 | # Linear projections 178 | Q = tf.layers.dense(queries, d_model, use_bias=False) # (N, T_q, d_model) 179 | K = tf.layers.dense(keys, d_model, use_bias=False) # (N, T_k, d_model) 180 | V = tf.layers.dense(values, d_model, use_bias=False) # (N, T_k, d_model) 181 | # Split and concat 182 | Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, d_model/h) 183 | K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h) 184 | V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h) 185 | # Attention 186 | outputs = scaled_dot_product_attention(Q_, K_, V_, causality, dropout_rate, training) 187 | # Restore shape 188 | outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2) # (N, T_q, d_model) 189 | # Residual connection 190 | outputs += queries 191 | # Normalize 192 | outputs = layer_norm(outputs) 193 | return outputs 194 | 195 | 196 | def feed_forward(inputs, num_units, activation, scope="positionwise_feedforward"): 197 | '''position-wise feed forward net. See 3.3 198 | 199 | inputs: A 3d tensor with shape of [N, T, C]. 200 | num_units: A list of two integers. 201 | scope: Optional scope for `variable_scope`. 202 | 203 | Returns: 204 | A 3d tensor with the same shape and dtype as inputs 205 | ''' 206 | with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): 207 | # Inner layer 208 | outputs = tf.layers.dense(inputs, num_units[0], activation=activation) 209 | # Outer layer 210 | outputs = tf.layers.dense(outputs, num_units[1]) 211 | # Residual connection 212 | outputs += inputs 213 | # Normalize 214 | outputs = layer_norm(outputs) 215 | return outputs 216 | --------------------------------------------------------------------------------