Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add topk arg to return topk items and scores at inference step #678

Merged
merged 10 commits into from
Apr 28, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions tests/unit/torch/test_torchscript_with_topk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import torch

import transformers4rec.torch as tr
from transformers4rec.config import transformer as tconf


def test_torchscript_with_topk(torch_yoochoose_like, yoochoose_schema):
input_module = tr.TabularSequenceFeatures.from_schema(
yoochoose_schema,
max_sequence_length=20,
d_output=64,
masking="causal",
)
prediction_task = tr.NextItemPredictionTask(weight_tying=True)
transformer_config = tconf.XLNetConfig.build(
d_model=64, n_head=8, n_layer=2, total_seq_length=20
)
model = transformer_config.to_torch_model(input_module, prediction_task)

_ = model(torch_yoochoose_like, training=False)

topk = 10
model.top_k = topk
model.eval()

traced_model = torch.jit.trace(model, torch_yoochoose_like, strict=False)

assert isinstance(traced_model, torch.jit.TopLevelTracedModule)
assert torch.allclose(
model(torch_yoochoose_like)[0], traced_model(torch_yoochoose_like)[0], rtol=1e-02
)
assert traced_model(torch_yoochoose_like)[0].shape[1] == topk
54 changes: 48 additions & 6 deletions transformers4rec/torch/model/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,10 +371,13 @@ def forward(
testing: bool = False,
targets: Union[torch.Tensor, TabularData] = None,
call_body: bool = False,
top_k: Optional[int] = -1,
**kwargs,
) -> Union[torch.Tensor, TabularData]:
outputs = {}

from transformers4rec.torch.model.prediction_task import NextItemPredictionTask

if call_body:
body_outputs = self.body(body_outputs, training=training, testing=testing, **kwargs)

Expand All @@ -400,9 +403,20 @@ def forward(
outputs = {"loss": loss, "labels": labels, "predictions": predictions}
else:
for name, task in self.prediction_task_dict.items():
outputs[name] = task(
body_outputs, targets=targets, training=training, testing=testing, **kwargs
)
if isinstance(task, NextItemPredictionTask):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the NextItemPredictionTask is always something that is created by user code. An alternative to passing to the foward method could be accepting top_k in the constructor __init__ method. That way we wouldn't need to have this condition here

Copy link
Contributor Author

@rnyak rnyak Apr 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. adding it to the NextItemPredictionTask constructor might be easier (as I show below) but, the reason we did not add this to the constructor is bcs there is no turning back changing the topK value at the inf step, once the model is trained with top_k arg. So to make it flexible, we decided to add it in the forward method of NextItemPredictionTask and constructor of the Model class.

head = tr.Head(
    body,
    tr.NextItemPredictionTask(weight_tying=True, 
                              metrics=metrics, top_k =20),
    inputs=inputs,
)

@sararb wanna add something else?

outputs[name] = task(
body_outputs,
targets=targets,
training=training,
testing=testing,
top_k=top_k,
**kwargs,
)

else:
outputs[name] = task(
body_outputs, targets=targets, training=training, testing=testing, **kwargs
)

return outputs

Expand Down Expand Up @@ -483,6 +497,7 @@ def __init__(
optimizer: Type[torch.optim.Optimizer] = torch.optim.Adam,
name: str = None,
max_sequence_length: Optional[int] = None,
top_k: Optional[int] = -1,
):
"""Model class that can aggregate one or multiple heads.
Parameters
Expand All @@ -497,9 +512,12 @@ def __init__(
Optimizer-class to use during fitting
name: str, optional
Name of the model.
max_sequence_length : int, optional
max_sequence_length: int, optional
The maximum sequence length supported by the model.
Used to truncate sequence inputs longer than this value.
top_k: int, optional
The number of items to return at the inference step once the model is deployed.
Default is -1, which will return all items.
"""
if head_weights:
if not isinstance(head_weights, list):
Expand All @@ -517,6 +535,7 @@ def __init__(
self.head_reduction = head_reduction
self.optimizer = optimizer
self.max_sequence_length = max_sequence_length
self.top_k = top_k

def forward(self, inputs: TabularData, targets=None, training=False, testing=False, **kwargs):
# Convert inputs to float32 which is the default type, expected by PyTorch
Expand Down Expand Up @@ -565,6 +584,7 @@ def forward(self, inputs: TabularData, targets=None, training=False, testing=Fal
targets=targets,
training=training,
testing=testing,
top_k=self.top_k,
**kwargs,
)
)
Expand Down Expand Up @@ -756,6 +776,8 @@ def input_schema(self):

@property
def output_schema(self):
from merlin.schema import Tags

from .prediction_task import BinaryClassificationTask, RegressionTask

# if the model has one head with one task, the output is a tensor
Expand All @@ -781,8 +803,28 @@ def output_schema(self):
properties = {
"int_domain": int_domain,
}
col_schema = ColumnSchema(name, dtype=np.float32, properties=properties, dims=dims)
output_cols.append(col_schema)
# in case one sets top_k at the inference step we return two outputs
if self.top_k > 0:
# be sure categ item-id dtype in model.input schema and output schema matches
col_name = self.input_schema.select_by_tag(Tags.ITEM_ID).column_names[0]
col_dtype = (
self.input_schema.select_by_tag(Tags.ITEM_ID)
.column_schemas[col_name]
.dtype.name
)
col_schema_scores = ColumnSchema(
"item_id_scores", dtype=np.float32, properties=properties, dims=dims
)
col_schema_ids = ColumnSchema(
"item_ids", dtype=np.dtype(col_dtype), properties=properties, dims=dims
)
output_cols.append(col_schema_scores)
output_cols.append(col_schema_ids)
else:
col_schema = ColumnSchema(
name, dtype=np.float32, properties=properties, dims=dims
)
output_cols.append(col_schema)

return Core_Schema(output_cols)

Expand Down
10 changes: 8 additions & 2 deletions transformers4rec/torch/model/prediction_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,9 @@ def build(self, body, input_size, device=None, inputs=None, task_block=None, pre
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, **kwargs):
def forward(
self, inputs: torch.Tensor, targets=None, training=False, testing=False, top_k=-1, **kwargs
):
if isinstance(inputs, (tuple, list)):
inputs = inputs[0]
x = inputs.float()
Expand Down Expand Up @@ -342,7 +344,11 @@ def forward(self, inputs: torch.Tensor, targets=None, training=False, testing=Fa
# Compute predictions probs
x, _ = self.pre(x) # type: ignore

return x
if top_k == -1:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does top_k need to be a numeric value? Would it work with with None as the default value, for example?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think -1 is a used convention but we can set it to None either. @sararb will setting it to None create any issue?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, it is just a convention. Setting it to None won't create any issue.

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)
Expand Down
6 changes: 6 additions & 0 deletions transformers4rec/torch/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,12 @@ def evaluation_loop(
else nested_concat(labels_host, labels, padding_index=0)
)
if preds is not None and self.args.predict_top_k > 0:
if self.model.top_k != -1:
raise ValueError(
"you cannot set top_k argument in the model class and the, "
"predict_top_k in the trainer at the same time. Please ensure setting "
"only predict_top_k"
)
# get outputs of next-item scores
if isinstance(preds, dict):
assert any(
Expand Down