/
ranking_policy.py
357 lines (311 loc) · 12.1 KB
/
ranking_policy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Ranking policy."""
from typing import Optional, Sequence, Text
import numpy as np
import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import
import tensorflow_probability as tfp
from tf_agents.policies import tf_policy
from tf_agents.policies import utils as policy_utils
from tf_agents.specs import bandit_spec_utils
from tf_agents.specs import tensor_spec
from tf_agents.trajectories import policy_step
from tf_agents.typing import types
tfd = tfp.distributions
class PenalizedPlackettLuce(tfd.PlackettLuce):
"""A distribution that samples permutations and penalizes item scores.
This distribution samples elements of a permutation incrementally, and after
every sample it penalizes the scores of the remaining items by the similarity
of already chosen items.
"""
def __init__(
self,
features: types.Tensor,
num_slots: int,
logits: types.Tensor,
penalty_mixture_coefficient: float = 1.0,
):
"""Initializes an instance of PenalizedPlackettLuce.
Args:
features: Item features based on which similarity is calculated.
num_slots: The number of slots to fill: this many items will be sampled.
logits: Unnormalized log probabilities for the PlackettLuce distribution.
Shape is `[num_items]`.
penalty_mixture_coefficient: A parameter responsible for the balance
between selecting high scoring items and enforcing diverisity.
"""
self._features = features
self._num_slots = num_slots
self._penalty_mixture_coefficient = penalty_mixture_coefficient
super(PenalizedPlackettLuce, self).__init__(scores=logits)
def _penalizer_fn(
self,
logits: types.Float,
features: types.Float,
slots: Sequence[types.Int],
):
"""Downscores items by their similarity to already selected items.
Args:
logits: The current logits of all items.
features: the feature vectors of the items.
slots: list of indices of already selected items.
Returns:
New logits.
"""
raise NotImplementedError()
def _sample_n(self, n, seed=None):
logits = tf.convert_to_tensor(self.scores)
sample_shape = tf.concat([[n], tf.shape(logits)], axis=0)
slots = []
for _ in range(self._num_slots):
items = tfd.Categorical(logits=logits).sample()
slots.append(items)
logits -= tf.one_hot(items, sample_shape[-1], on_value=np.inf)
logits = self._penalizer_fn(logits, self._features, slots)
sample = tf.expand_dims(tf.stack(slots, axis=-1), axis=0)
return sample
def _event_shape(self, scores=None):
return self._num_slots
class CosinePenalizedPlackettLuce(PenalizedPlackettLuce):
"""A distribution that samples items based on scores and cosine similarity."""
def _penalizer_fn(self, logits, features, slots):
num_items = logits.shape[-1]
num_slotted = len(slots)
slot_tensor = tf.stack(slots, axis=-1)
# The tfd.Categorical distribution will give the sample `num_items` if all
# the logits are `-inf`. Hence, we need to apply minimum. This happens when
# `num_actions` is less than `num_slots`. To this end, the action taken by
# the policy always has to be taken together with the `num_actions`
# observation, to know how many slots are filled with valid items.
slotted_features = tf.gather(
features, tf.minimum(slot_tensor, num_items - 1), batch_dims=1
)
# Calculate the similarity between all pairs from
# `slotted_features x all_features`.
all_sims = (
tf.keras.losses.cosine_similarity(
tf.repeat(features, num_slotted, axis=1),
tf.tile(slotted_features, [1, num_items, 1]),
)
- 1
)
sim_matrix = tf.reshape(all_sims, shape=[-1, num_items, num_slotted])
similarity_boosts = tf.reduce_min(sim_matrix, axis=-1)
adjusted_logits = logits + (
self._penalty_mixture_coefficient * similarity_boosts
)
return adjusted_logits
class NoPenaltyPlackettLuce(tfd.PlackettLuce):
"""Identical to PlackettLuce, with input signature modified to our needs."""
def __init__(
self,
features: types.Tensor,
num_slots: int,
logits: types.Tensor,
penalty_mixture_coefficient: float = 1.0,
):
"""Initializes an instance of NoPenaltyPlackettLuce.
Args:
features: Unused for this distribution.
num_slots: The number of slots to fill: this many items will be sampled.
logits: Unnormalized log probabilities for the PlackettLuce distribution.
Shape is `[num_items]`.
penalty_mixture_coefficient: Unused for this distribution.
"""
self._num_slots = num_slots
super(NoPenaltyPlackettLuce, self).__init__(scores=tf.math.exp(logits))
def sample(self, sample_shape=(), seed=None, name='sample', **kwargs):
return super(NoPenaltyPlackettLuce, self).sample(
sample_shape, seed, name, **kwargs
)[:, : self._num_slots]
class RankingPolicy(tf_policy.TFPolicy):
"""A class implementing ranking policies in TF Agents.
The ranking policy needs at initialization the number of items per round to
rank, a scorer network, and a score penalizer function. This function should
ensure that similar items don't all get high scores and thus a diverse set of
items is recommended.
In the case the number of items to rank varies from iteration to iteration,
the observation contains a `num_actions` value, that specifies the number of
items available. Note that in this case it can happen that the number of
ranked items is less than the number of slots. Thus, consumers of the output
of `policy.action` should always use the `num_actions` value to determine what
part of the output is the action ranking.
If `num_actions` field is not used, the policy is always presented with
`num_items` many items, which should be greater than or equal to `num_slots`.
"""
def __init__(
self,
num_items: int,
num_slots: int,
time_step_spec: types.TimeStep,
network: types.Network,
item_sampler: tfd.Distribution,
penalty_mixture_coefficient: float = 1.0,
logits_temperature: float = 1.0,
name: Optional[Text] = None,
):
"""Initializes an instance of `RankingPolicy`.
Args:
num_items: The number of items the policy can choose from, to be slotted.
num_slots: The number of recommendation slots presented to the user, i.e.,
chosen by the policy.
time_step_spec: The time step spec.
network: The network that estimates scores of items, given global and item
features.
item_sampler: A distibution that takes scores and item features, and
samples an ordered list of `num_slots` items. Similarity penalization
can be implemented within this sampler.
penalty_mixture_coefficient: A parameter responsible for the balance
between selecting high scoring items and enforcing diverisity.
logits_temperature: The "temperature" parameter for sampling. All the
logits will be divided by this float value. This value must be positive.
name: The name of this policy instance.
"""
action_spec = tensor_spec.BoundedTensorSpec(
shape=(num_slots,), dtype=tf.int32, minimum=0, maximum=num_items - 1
)
info_spec = policy_utils.PolicyInfo(
predicted_rewards_mean=tensor_spec.TensorSpec(
shape=(num_slots,), dtype=tf.float32
)
)
network.create_variables()
self._network = network
assert num_slots <= num_items, (
'The number of slots have to be less than or equal to the number of '
'items.'
)
self._num_slots = num_slots
self._num_items = num_items
self._item_sampler = item_sampler
self._penalty_mixture_coefficient = penalty_mixture_coefficient
if logits_temperature <= 0:
raise ValueError(
f'logits_temperature must be positive; was {logits_temperature}'
)
self._logits_temperature = logits_temperature
if bandit_spec_utils.NUM_ACTIONS_FEATURE_KEY in time_step_spec.observation:
self._use_num_actions = True
else:
self._use_num_actions = False
super(RankingPolicy, self).__init__(
time_step_spec=time_step_spec,
action_spec=action_spec,
name=name,
info_spec=info_spec,
)
@property
def num_slots(self):
return self._num_slots
def _distribution(self, time_step, policy_state):
observation = time_step.observation
scores, _ = self._network(observation, time_step.step_type, policy_state)
if self._use_num_actions:
num_actions = time_step.observation[
bandit_spec_utils.NUM_ACTIONS_FEATURE_KEY
]
masked_scores = tf.where(
tf.sequence_mask(num_actions, maxlen=self._num_items),
scores,
tf.fill(tf.shape(scores), -np.inf),
)
else:
masked_scores = scores
masked_scores = masked_scores / self._logits_temperature
return policy_step.PolicyStep(
self._item_sampler(
observation[bandit_spec_utils.PER_ARM_FEATURE_KEY],
self._num_slots,
masked_scores,
self._penalty_mixture_coefficient,
),
(),
# TODO(b/197787556): potentially add other side info tensors
policy_utils.PolicyInfo(predicted_rewards_mean=scores),
)
class PenalizeCosineDistanceRankingPolicy(RankingPolicy):
"""A Ranking policy that penalizes scores based on cosine distance.
Note that this is a rough first implementation, and thus it is very slow and
also misses tunable parameters such as weights of the penalties vs raw scores.
"""
def __init__(
self,
num_items: int,
num_slots: int,
time_step_spec: types.TimeStep,
network: types.Network,
penalty_mixture_coefficient: float = 1.0,
logits_temperature: float = 1.0,
name: Optional[Text] = None,
):
super(PenalizeCosineDistanceRankingPolicy, self).__init__(
num_items=num_items,
num_slots=num_slots,
time_step_spec=time_step_spec,
network=network,
item_sampler=CosinePenalizedPlackettLuce,
penalty_mixture_coefficient=penalty_mixture_coefficient,
logits_temperature=logits_temperature,
name=name,
)
class NoPenaltyRankingPolicy(RankingPolicy):
def __init__(
self,
num_items: int,
num_slots: int,
time_step_spec: types.TimeStep,
network: types.Network,
logits_temperature: float = 1.0,
name: Optional[Text] = None,
):
super(NoPenaltyRankingPolicy, self).__init__(
num_items=num_items,
num_slots=num_slots,
time_step_spec=time_step_spec,
network=network,
item_sampler=NoPenaltyPlackettLuce,
logits_temperature=logits_temperature,
name=name,
)
class DescendingScoreSampler(tf.Module):
def __init__(
self,
unused_features: types.Tensor,
num_slots: int,
scores: types.Tensor,
unused_penalty_mixture_coefficient: float,
):
self._scores = scores
self._num_slots = num_slots
def sample(self, shape=(), seed=None):
return tf.math.top_k(self._scores, k=self._num_slots).indices
class DescendingScoreRankingPolicy(RankingPolicy):
"""A policy that is deterministically ranks elements based on their scores."""
def __init__(
self,
num_items: int,
num_slots: int,
time_step_spec: types.TimeStep,
network: types.Network,
name: Optional[Text] = None,
):
super(DescendingScoreRankingPolicy, self).__init__(
num_items=num_items,
num_slots=num_slots,
time_step_spec=time_step_spec,
network=network,
item_sampler=DescendingScoreSampler,
name=name,
)