google-research
61 строка · 1.9 Кб
1# coding=utf-8
2# Copyright 2024 The Google Research Authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""A collection of retrieval functions for negative mining.
17
18Retrieval functions take in a matrix of scores and return a batch x `k` set of
19indices indicating the `k` items retrieved.
20"""
21import abc
22import tensorflow.compat.v2 as tf
23
24
25class AbstractRetrievalFn(tf.Module, metaclass=abc.ABCMeta):
26
27@abc.abstractmethod
28def __call__(self, scores):
29pass
30
31
32class MaxScoreRetrievalFn(AbstractRetrievalFn):
33
34def __call__(self, scores):
35indices = tf.argmax(scores, axis=1)
36return tf.expand_dims(indices, 1)
37
38
39def _sample_gumbel(shape):
40uniform_vals = tf.random.uniform(shape)
41gumbel_vals = -tf.math.log(-tf.math.log(uniform_vals))
42return gumbel_vals
43
44
45class GumbelMaxRetrievalFn(AbstractRetrievalFn):
46"""Creates a retrieval function that uses Gumbel-max sampling.
47
48Gumbel-max sampling is an approach to sample from the softmax distribution of
49a set of scores by perturbing the scores then taking the argmax. The scores
50are first scaled by `inv_temp` then perturbed by adding Gumbel noise.
51"""
52
53def __init__(self, inv_temp=1.0):
54super(GumbelMaxRetrievalFn, self).__init__()
55self.inv_temp = inv_temp
56
57def __call__(self, scores):
58gumbel_vals = _sample_gumbel(tf.shape(scores))
59perturbed_scores = self.inv_temp * scores + gumbel_vals
60indices = tf.argmax(perturbed_scores, axis=1)
61return tf.expand_dims(indices, 1)
62