/
prediction_task.py
861 lines (739 loc) · 32.6 KB
/
prediction_task.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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
#
# http://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.
#
import logging
from math import sqrt
from typing import Dict, Iterable, Optional, Sequence, Tuple
import torch
import torchmetrics as tm
from ..block.base import Block, BuildableBlock, SequentialBlock
from ..block.mlp import MLPBlock
from ..masking import MaskedLanguageModeling
from ..ranking_metric import AvgPrecisionAt, NDCGAt, RecallAt
from ..utils.torch_utils import LambdaModule
from .base import BlockType, PredictionTask
LOG = logging.getLogger("transformers4rec")
class BinaryClassificationPrepareBlock(BuildableBlock):
"""Prepares the output layer of the binary classification prediction task.
The output layer is a SequentialBlock of a torch linear
layer followed by a sigmoid activation and a squeeze operation.
"""
def build(self, input_size) -> SequentialBlock:
"""Builds the output layer of binary classification based on the input_size.
Parameters
----------
input_size: Tuple[int]
The size of the input tensor, specifically the last dimension is
used for setting the input dimension of the linear layer.
Returns
-------
SequentialBlock
A SequentialBlock consisting of a linear layer (with input dimension equal to the last
dimension of input_size), a sigmoid activation, and a squeeze operation.
"""
return SequentialBlock(
torch.nn.Linear(input_size[-1], 1, bias=False),
torch.nn.Sigmoid(),
LambdaModule(lambda x: torch.squeeze(x, -1)),
output_size=[
None,
],
)
class BinaryClassificationTask(PredictionTask):
"""Returns a ``PredictionTask`` for binary classification.
Example usage::
# Define the input module to process the tabular input features.
input_module = tr.TabularSequenceFeatures.from_schema(
schema,
max_sequence_length=max_sequence_length,
continuous_projection=d_model,
aggregation="concat",
masking=None,
)
# Define XLNetConfig class and set default parameters for HF XLNet config.
transformer_config = tr.XLNetConfig.build(
d_model=d_model, n_head=4, n_layer=2, total_seq_length=max_sequence_length
)
# Define the model block including: inputs, masking, projection and transformer block.
body = tr.SequentialBlock(
input_module,
tr.MLPBlock([64]),
tr.TransformerBlock(
transformer_config,
masking=input_module.masking
)
)
# Define a head with BinaryClassificationTask.
head = tr.Head(
body,
tr.BinaryClassificationTask(
"click",
summary_type="mean",
metrics=[
tm.Precision(task='binary'),
tm.Recall(task='binary'),
tm.Accuracy(task='binary'),
tm.F1Score(task='binary')
]
),
inputs=input_module,
)
# Get the end-to-end Model class.
model = tr.Model(head)
Parameters
----------
target_name: Optional[str] = None
Specifies the variable name that represents the positive and negative values.
task_name: Optional[str] = None
Specifies the name of the prediction task. If this parameter is not specified,
a name is automatically constructed based on ``target_name`` and the Python
class name of the model.
task_block: Optional[BlockType] = None
Specifies a module to transform the input tensor before computing predictions.
loss: torch.nn.Module
Specifies the loss function for the task.
The default class is ``torch.nn.BCELoss``.
metrics: Tuple[torch.nn.Module, ...]
Specifies the metrics to calculate during training and evaluation.
The default metrics are ``Precision``, ``Recall``, and ``Accuracy``.
summary_type: str
Summarizes a sequence into a single tensor. Accepted values are:
- ``last`` -- Take the last token hidden state (like XLNet)
- ``first`` -- Take the first token hidden state (like Bert)
- ``mean`` -- Take the mean of all tokens hidden states
- ``cls_index`` -- Supply a Tensor of classification token position (GPT/GPT-2)
- ``attn`` -- Not implemented now, use multi-head attention
"""
DEFAULT_LOSS = torch.nn.BCELoss()
DEFAULT_METRICS = (
tm.Precision(num_classes=2, task="binary"),
tm.Recall(num_classes=2, task="binary"),
tm.Accuracy(task="binary"),
# TODO: Fix this: tm.AUC()
)
def __init__(
self,
target_name: Optional[str] = None,
task_name: Optional[str] = None,
task_block: Optional[BlockType] = None,
loss=DEFAULT_LOSS,
metrics=DEFAULT_METRICS,
summary_type="first",
):
self.target_dim = 1
super().__init__(
loss=loss,
metrics=metrics,
target_name=target_name,
task_name=task_name,
summary_type=summary_type,
task_block=task_block,
pre=BinaryClassificationPrepareBlock(),
forward_to_prediction_fn=lambda x: torch.round(x).int(),
)
class RegressionPrepareBlock(BuildableBlock):
"""Prepares the output layer of the regression prediction task.
The output layer is a SequentialBlock of a torch linear
layer followed by a squeeze operation.
"""
def build(self, input_size) -> SequentialBlock:
"""Builds the output layer of regression based on the input_size.
Parameters
----------
input_size: Tuple[int]
The size of the input tensor, specifically the last dimension is
used for setting the input dimension of the linear layer.
Returns
-------
SequentialBlock
A SequentialBlock consisting of a linear layer (with input dimension equal to
the last dimension of input_size), and a squeeze operation.
"""
return SequentialBlock(
torch.nn.Linear(input_size[-1], 1),
LambdaModule(lambda x: torch.squeeze(x, -1)),
output_size=[
None,
],
)
class RegressionTask(PredictionTask):
"""Returns a ``PredictionTask`` for regression.
Example usage::
# Define the input module to process the tabular input features.
input_module = tr.TabularSequenceFeatures.from_schema(
schema,
max_sequence_length=max_sequence_length,
continuous_projection=d_model,
aggregation="concat",
masking=None,
)
# Define XLNetConfig class and set default parameters for HF XLNet config.
transformer_config = tr.XLNetConfig.build(
d_model=d_model, n_head=4, n_layer=2, total_seq_length=max_sequence_length
)
# Define the model block including: inputs, projection and transformer block.
body = tr.SequentialBlock(
input_module,
tr.MLPBlock([64]),
tr.TransformerBlock(
transformer_config,
)
)
# Define a head with BinaryClassificationTask.
head = tr.Head(
body,
tr.RegressionTask(
"watch_time",
summary_type="mean",
metrics=[tm.regression.MeanSquaredError()]
),
inputs=input_module,
)
# Get the end-to-end Model class.
model = tr.Model(head)
Parameters
----------
target_name: Optional[str]
Specifies the variable name that represents the continuous value to predict.
By default None
task_name: Optional[str]
Specifies the name of the prediction task. If this parameter is not specified,
a name is automatically constructed based on ``target_name`` and the Python
class name of the model.
By default None
task_block: Optional[BlockType] = None
Specifies a module to transform the input tensor before computing predictions.
loss: torch.nn.Module
Specifies the loss function for the task.
The default class is ``torch.nn.MSELoss``.
metrics: Tuple[torch.nn.Module, ...]
Specifies the metrics to calculate during training and evaluation.
The default metric is MeanSquaredError.
summary_type: str
Summarizes a sequence into a single tensor. Accepted values are:
- ``last`` -- Take the last token hidden state (like XLNet)
- ``first`` -- Take the first token hidden state (like Bert)
- ``mean`` -- Take the mean of all tokens hidden states
- ``cls_index`` -- Supply a Tensor of classification token position (GPT/GPT-2)
- ``attn`` -- Not implemented now, use multi-head attention
"""
DEFAULT_LOSS = torch.nn.MSELoss()
DEFAULT_METRICS = (tm.regression.MeanSquaredError(),)
def __init__(
self,
target_name: Optional[str] = None,
task_name: Optional[str] = None,
task_block: Optional[BlockType] = None,
loss=DEFAULT_LOSS,
metrics=DEFAULT_METRICS,
summary_type="first",
):
self.target_dim = 1
super().__init__(
loss=loss,
metrics=metrics,
target_name=target_name,
task_name=task_name,
summary_type=summary_type,
task_block=task_block,
pre=RegressionPrepareBlock(),
)
class NextItemPredictionTask(PredictionTask):
"""This block performs item prediction task for session and sequential-based models.
It requires a body containing a masking schema to use for training and target generation.
For the supported masking schemes, please refers to:
https://nvidia-merlin.github.io/Transformers4Rec/stable/model_definition.html#sequence-masking
Parameters
----------
loss: torch.nn.Module
Loss function to use. Defaults to NLLLos.
metrics: Iterable[torchmetrics.Metric]
List of ranking metrics to use for evaluation.
task_block:
Module to transform input tensor before computing predictions.
task_name: str, optional
Name of the prediction task, if not provided a name will be automatically constructed based
on the target-name & class-name.
weight_tying: bool
The item id embedding table weights are shared with the prediction network layer.
softmax_temperature: float
Softmax temperature, used to reduce model overconfidence, so that softmax(logits / T).
Value 1.0 reduces to regular softmax.
padding_idx: int
pad token id.
target_dim: int
vocabulary size of item ids
sampled_softmax: Optional[bool]
Enables sampled softmax. By default False
max_n_samples: Optional[int]
Number of samples for sampled softmax. By default 100
"""
DEFAULT_METRICS = (
# default metrics suppose labels are int encoded
NDCGAt(top_ks=[10, 20], labels_onehot=True),
AvgPrecisionAt(top_ks=[10, 20], labels_onehot=True),
RecallAt(top_ks=[10, 20], labels_onehot=True),
)
def __init__(
self,
loss: torch.nn.Module = torch.nn.CrossEntropyLoss(),
metrics: Iterable[tm.Metric] = DEFAULT_METRICS,
task_block: Optional[BlockType] = None,
task_name: str = "next-item",
weight_tying: bool = False,
softmax_temperature: float = 1,
padding_idx: int = 0,
target_dim: int = None,
sampled_softmax: Optional[bool] = False,
max_n_samples: Optional[int] = 100,
):
super().__init__(loss=loss, metrics=metrics, task_block=task_block, task_name=task_name)
self.softmax_temperature = softmax_temperature
self.weight_tying = weight_tying
self.padding_idx = padding_idx
self.target_dim = target_dim
self.sampled_softmax = sampled_softmax
self.max_n_samples = max_n_samples
self.item_embedding_table = None
self.masking = None
def build(self, body, input_size, device=None, inputs=None, task_block=None, pre=None):
"""Build method, this is called by the `Head`."""
if not len(input_size) == 3 or isinstance(input_size, dict):
raise ValueError(
"NextItemPredictionTask needs a 3-dim vector as input, found:" f"{input_size}"
)
# Retrieve the embedding module to get the name of itemid col and its related table
if not inputs:
inputs = body.inputs
if not getattr(inputs, "item_id", None):
raise ValueError(
"For Item Prediction task a categorical_module "
"including an item_id column is required."
)
self.embeddings = inputs.categorical_module
if not self.target_dim:
self.target_dim = self.embeddings.item_embedding_table.num_embeddings
if self.weight_tying:
self.item_embedding_table = self.embeddings.item_embedding_table
item_dim = self.item_embedding_table.weight.shape[1]
if input_size[-1] != item_dim and not task_block:
LOG.warning(
f"Projecting inputs of NextItemPredictionTask to'{item_dim}' "
f"As weight tying requires the input dimension '{input_size[-1]}' "
f"to be equal to the item-id embedding dimension '{item_dim}'"
)
# project input tensors to same dimension as item-id embeddings
task_block = MLPBlock([item_dim], activation=None)
# Retrieve the masking from the input block
self.masking = inputs.masking
if not self.masking:
raise ValueError(
"The input block should contain a masking schema for training and evaluation"
)
self.padding_idx = self.masking.padding_idx
pre = NextItemPredictionPrepareBlock(
target_dim=self.target_dim,
weight_tying=self.weight_tying,
item_embedding_table=self.item_embedding_table,
softmax_temperature=self.softmax_temperature,
sampled_softmax=self.sampled_softmax,
max_n_samples=self.max_n_samples,
min_id=self.padding_idx + 1,
)
super().build(
body, input_size, device=device, inputs=inputs, task_block=task_block, pre=pre
)
def forward(
self,
inputs: torch.Tensor,
targets=None,
training=False,
testing=False,
top_k=None,
**kwargs,
):
if isinstance(inputs, (tuple, list)):
inputs = inputs[0]
x = inputs.float()
if self.task_block:
x = self.task_block(x) # type: ignore
# Retrieve labels from masking
if training or testing:
labels = self.masking.masked_targets # type: ignore
trg_flat = labels.flatten()
non_pad_mask = trg_flat != self.padding_idx
labels_all = torch.masked_select(trg_flat, non_pad_mask).long()
# remove padded items, keep only masked positions
x = self.remove_pad_3d(x, non_pad_mask)
y = labels_all
x, y = self.pre(x, targets=y, training=training, testing=testing) # type: ignore
loss = self.loss(x, y)
return {
"loss": loss,
"labels": y,
"predictions": x,
}
else:
# Get the hidden position to use for predicting the next item
labels = self.embeddings.item_seq
non_pad_mask = labels != self.padding_idx
rows_ids = torch.arange(labels.size(0), dtype=torch.long, device=labels.device)
if isinstance(self.masking, MaskedLanguageModeling):
last_item_sessions = non_pad_mask.sum(dim=1)
else:
last_item_sessions = non_pad_mask.sum(dim=1) - 1
x = x[rows_ids, last_item_sessions]
# Compute predictions probs
x, _ = self.pre(x) # type: ignore
if top_k is None:
return x
else:
preds_sorted_item_scores, preds_sorted_item_ids = torch.topk(x, k=top_k, dim=-1)
return preds_sorted_item_scores, preds_sorted_item_ids
def remove_pad_3d(self, inp_tensor, non_pad_mask):
# inp_tensor: (n_batch x seqlen x emb_dim)
inp_tensor = inp_tensor.flatten(end_dim=1)
inp_tensor_fl = torch.masked_select(
inp_tensor, non_pad_mask.unsqueeze(1).expand_as(inp_tensor)
)
out_tensor = inp_tensor_fl.view(-1, inp_tensor.size(1))
return out_tensor
def calculate_metrics(self, predictions, targets) -> Dict[str, torch.Tensor]: # type: ignore
if isinstance(targets, dict) and self.target_name:
targets = targets[self.target_name]
outputs = {}
predictions = self.forward_to_prediction_fn(predictions)
for metric in self.metrics:
result = metric(predictions, targets)
outputs[self.metric_name(metric)] = result
return outputs
def compute_metrics(self):
metrics = {
self.metric_name(metric): metric.compute()
for metric in self.metrics
if getattr(metric, "top_ks", None)
}
# Explode metrics for each cut-off
# TODO make result generic:
# To accept a mix of ranking metrics and others not requiring top_ks ?
topks = {self.metric_name(metric): metric.top_ks for metric in self.metrics}
results = {}
for name, metric in metrics.items():
# Fix for when using a single cut-off, as torch metrics convert results to scalar
# when a single element vector is returned
if len(metric.size()) == 0:
metric = metric.unsqueeze(0)
for measure, k in zip(metric, topks[name]):
results[f"{name}_{k}"] = measure
return results
class NextItemPredictionPrepareBlock(BuildableBlock):
"""Prepares the output layer of the next item prediction task.
The output layer is a an instance of `_NextItemPredictionTask` class.
Parameters
----------
target_dim: int
The output dimension for next-item predictions.
weight_tying: bool, optional
If true, ties the weights of the prediction layer and the item embedding layer.
By default False.
item_embedding_table: torch.nn.Module, optional
The module containing the item embedding table.
By default None.
softmax_temperature: float, optional
The temperature to be applied to the softmax function. Defaults to 0.
sampled_softmax: bool, optional
If true, sampled softmax is used for approximating the full softmax function.
By default False.
max_n_samples: int, optional
The maximum number of samples when using sampled softmax.
By default 100.
min_id: int, optional
The minimum value of the range for the log-uniform sampling.
By default 0.
"""
def __init__(
self,
target_dim: int,
weight_tying: bool = False,
item_embedding_table: Optional[torch.nn.Module] = None,
softmax_temperature: float = 0,
sampled_softmax: Optional[bool] = False,
max_n_samples: Optional[int] = 100,
min_id: Optional[int] = 0,
):
super().__init__()
self.target_dim = target_dim
self.weight_tying = weight_tying
self.item_embedding_table = item_embedding_table
self.softmax_temperature = softmax_temperature
self.sampled_softmax = sampled_softmax
self.max_n_samples = max_n_samples
self.min_id = min_id
def build(self, input_size) -> Block:
"""Builds the output layer of next-item prediction based on the input_size.
Parameters
----------
input_size : Tuple[int]
The size of the input tensor, specifically the last dimension is
used for setting the input dimension of the output layer.
Returns
-------
Block[_NextItemPredictionTask]
an instance of _NextItemPredictionTask
"""
return Block(
_NextItemPredictionTask(
input_size,
self.target_dim,
self.weight_tying,
self.item_embedding_table,
self.softmax_temperature,
self.sampled_softmax,
self.max_n_samples,
self.min_id,
),
[-1, self.target_dim],
)
class _NextItemPredictionTask(torch.nn.Module):
"""Predict the interacted item-id probabilities.
- During inference, the task consists of predicting the next item.
- During training, the class supports the following Language modeling tasks:
Causal LM, Masked LM, Permutation LM and Replacement Token Detection
Parameters:
-----------
input_size: int
Input size of this module.
target_dim: int
Dimension of the target.
weight_tying: bool
The item id embedding table weights are shared with the prediction network layer.
item_embedding_table: torch.nn.Module
Module that's used to store the embedding table for the item.
softmax_temperature: float
Softmax temperature, used to reduce model overconfidence, so that softmax(logits / T).
Value 1.0 reduces to regular softmax.
sampled_softmax: Optional[bool]
Enables sampled softmax. By default False
max_n_samples: Optional[int]
Number of samples for sampled softmax. By default 100
min_id : Optional[int]
The minimum value of the range for the log-uniform sampling. By default 0.
"""
def __init__(
self,
input_size: Sequence,
target_dim: int,
weight_tying: bool = False,
item_embedding_table: Optional[torch.nn.Module] = None,
softmax_temperature: float = 0,
sampled_softmax: Optional[bool] = False,
max_n_samples: Optional[int] = 100,
min_id: Optional[int] = 0,
):
super().__init__()
self.input_size = input_size
self.target_dim = target_dim
self.weight_tying = weight_tying
self.item_embedding_table = item_embedding_table
self.softmax_temperature = softmax_temperature
self.sampled_softmax = sampled_softmax
if not self.weight_tying:
self.output_layer = torch.nn.Parameter(torch.empty(self.target_dim, input_size[-1]))
torch.nn.init.kaiming_uniform_(self.output_layer, a=sqrt(5))
if self.sampled_softmax:
self.sampler = LogUniformSampler(
max_n_samples=max_n_samples,
max_id=target_dim,
min_id=min_id,
unique_sampling=True,
)
def forward(
self,
inputs: torch.Tensor,
targets: Optional[torch.Tensor] = None,
training=False,
testing=False,
**kwargs,
) -> Tuple[torch.Tensor, torch.Tensor]:
if self.weight_tying:
output_weights = self.item_embedding_table.weight
else:
output_weights = self.output_layer
if self.sampled_softmax and training:
logits, targets = self.sampled(inputs, targets, output_weights)
else:
logits = inputs @ output_weights.t() # type: ignore
if self.softmax_temperature:
# Softmax temperature to reduce model overconfidence
# and better calibrate probs and accuracy
logits = torch.div(logits, self.softmax_temperature)
return logits, targets
def sampled(self, inputs, targets, output_weights):
"""Returns logits using sampled softmax"""
neg_samples, targets_probs, samples_probs = self.sampler.sample(targets)
positive_weights = output_weights[targets]
negative_weights = output_weights[neg_samples]
positive_scores = (inputs * positive_weights).sum(dim=-1, keepdim=True)
negative_scores = inputs @ negative_weights.t()
# logQ correction, to not overpenalize popular items for being sampled
# more often as negatives
epsilon = 1e-16
positive_scores -= torch.unsqueeze(torch.log(targets_probs + epsilon), dim=-1)
negative_scores -= torch.unsqueeze(torch.log(samples_probs + epsilon), dim=0)
# Remove accidental matches
accidental_hits = torch.unsqueeze(targets, -1) == torch.unsqueeze(neg_samples, 0)
negative_scores[accidental_hits] = torch.finfo(torch.float16).min / 100.0
logits = torch.cat([positive_scores, negative_scores], axis=1)
new_targets = torch.zeros(logits.shape[0], dtype=torch.int64, device=targets.device)
return logits, new_targets
def _get_name(self) -> str:
return "NextItemPredictionTask"
class LogUniformSampler(torch.nn.Module):
def __init__(
self,
max_n_samples: int,
max_id: int,
min_id: Optional[int] = 0,
unique_sampling: bool = True,
n_samples_multiplier_before_unique: int = 2,
):
"""LogUniformSampler samples negative samples based on a log-uniform distribution.
`P(class) = (log(class + 2) - log(class + 1)) / log(max_id + 1)`
This implementation is based on to:
https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/utils/log_uniform_sampler.py
TensorFlow Reference:
https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/ops/candidate_sampling_ops.py
LogUniformSampler assumes item ids are sorted decreasingly by their frequency.
if `unique_sampling==True`, then only unique sampled items will be returned.
The actual # samples will vary from run to run if `unique_sampling==True`,
as sampling without replacement (`torch.multinomial(..., replacement=False)`) is slow,
so we use `torch.multinomial(..., replacement=True).unique()` which doesn't guarantee
the same number of unique sampled items. You can try to increase
n_samples_multiplier_before_unique to increase the chances to have more
unique samples in that case.
Parameters
----------
max_n_samples : int
The maximum desired number of negative samples. The number of samples might be
smaller than that if `unique_sampling==True`, as explained above.
max_id : int
The maximum value of the range for the log-uniform distribution.
min_id : Optional[int]
The minimum value of the range for the log-uniform sampling. By default 0.
unique_sampling : bool
Whether to return unique samples. By default True
n_samples_multiplier_before_unique : int
If unique_sampling=True, it is not guaranteed that the number of returned
samples will be equal to max_n_samples, as explained above.
You can increase n_samples_multiplier_before_unique to maximize
chances that a larger number of unique samples is returned.
"""
super().__init__()
if max_id <= 0:
raise ValueError("max_id must be a positive integer.")
if max_n_samples <= 0:
raise ValueError("n_sample must be a positive integer.")
self.max_id = max_id
self.unique_sampling = unique_sampling
self.max_n_samples = max_n_samples
self.n_sample = max_n_samples
if self.unique_sampling:
self.n_sample = int(self.n_sample * n_samples_multiplier_before_unique)
with torch.no_grad():
dist = self.get_log_uniform_distr(max_id, min_id)
self.register_buffer("dist", dist)
unique_sampling_dist = self.get_unique_sampling_distr(dist, self.n_sample)
self.register_buffer("unique_sampling_dist", unique_sampling_dist)
def get_log_uniform_distr(self, max_id: int, min_id: int = 0) -> torch.Tensor:
"""Approximates the items frequency distribution with log-uniform probability distribution
with P(class) = (log(class + 2) - log(class + 1)) / log(max_id + 1).
It assumes item ids are sorted decreasingly by their frequency.
Parameters
----------
max_id : int
Maximum discrete value for sampling (e.g. cardinality of the item id)
Returns
-------
torch.Tensor
Returns the log uniform probability distribution
"""
log_indices = torch.arange(1.0, max_id - min_id + 2.0, 1.0).log_()
probs = (log_indices[1:] - log_indices[:-1]) / log_indices[-1]
if min_id > 0:
probs = torch.cat(
[torch.zeros([min_id], dtype=probs.dtype), probs], axis=0
) # type: ignore
return probs
def get_unique_sampling_distr(self, dist, n_sample):
"""Returns the probability that each item is sampled at least once
given the specified number of trials. This is meant to be used when
self.unique_sampling == True.
That probability can be approximated by by 1 - (1 - p)^n
and we use a numerically stable version: -expm1(num_tries * log1p(-p))
"""
return (-(-dist.double().log1p_() * n_sample).expm1_()).float()
def sample(self, labels: torch.Tensor):
"""Sample negative samples and calculate their probabilities.
If `unique_sampling==True`, then only unique sampled items will be returned.
The actual # samples will vary from run to run if `unique_sampling==True`,
as sampling without replacement (`torch.multinomial(..., replacement=False)`) is slow,
so we use `torch.multinomial(..., replacement=True).unique()`
which doesn't guarantee the same number of unique sampled items.
You can try to increase n_samples_multiplier_before_unique
to increase the chances to have more unique samples in that case.
Parameters
----------
labels : torch.Tensor, dtype=torch.long, shape=(batch_size,)
The input labels for which negative samples should be generated.
Returns
-------
neg_samples : torch.Tensor, dtype=torch.long, shape=(n_samples,)
The unique negative samples drawn from the log-uniform distribution.
true_probs : torch.Tensor, dtype=torch.float32, shape=(batch_size,)
The probabilities of the input labels according
to the log-uniform distribution (depends on self.unique_sampling choice).
samp_log_probs : torch.Tensor, dtype=torch.float32, shape=(n_samples,)
The probabilities of the sampled negatives according
to the log-uniform distribution (depends on self.unique_sampling choice).
"""
if not torch.is_tensor(labels):
raise TypeError("Labels must be a torch.Tensor.")
if labels.dtype != torch.long:
raise ValueError("Labels must be a tensor of dtype long.")
if labels.dim() > 2 or (labels.dim() == 2 and min(labels.shape) > 1):
raise ValueError(
"Labels must be a 1-dimensional tensor or a 2-dimensional tensor"
"with one of the dimensions equal to 1."
)
if labels.size(0) == 0:
raise ValueError("Labels must not be an empty tensor.")
if (labels < 0).any() or (labels > self.max_id).any():
raise ValueError("All label values must be within the range [0, max_id].")
n_tries = self.n_sample
with torch.no_grad():
neg_samples = torch.multinomial(
self.dist, n_tries, replacement=True # type: ignore
).unique()[: self.max_n_samples]
device = labels.device
neg_samples = neg_samples.to(device)
if self.unique_sampling:
dist = self.unique_sampling_dist
else:
dist = self.dist
true_probs = dist[labels] # type: ignore
samples_probs = dist[neg_samples] # type: ignore
return neg_samples, true_probs, samples_probs
def forward(self, labels):
return self.sample(labels)