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 BinaryOutput #1099

Merged
merged 6 commits into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 9 additions & 1 deletion merlin/models/torch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,13 @@

from merlin.models.torch.batch import Batch, Sequence
from merlin.models.torch.block import Block
from merlin.models.torch.outputs.base import ModelOutput
from merlin.models.torch.outputs.classification import BinaryOutput

__all__ = ["Batch", "Block", "Sequence"]
__all__ = [
"Batch",
"BinaryOutput",
"Block",
"ModelOutput",
"Sequence",
]
15 changes: 15 additions & 0 deletions merlin/models/torch/outputs/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#
# Copyright (c) 2023, 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.
#
92 changes: 92 additions & 0 deletions merlin/models/torch/outputs/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#
# Copyright (c) 2023, 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.
#
from typing import Optional, Sequence

import torch
from torch import nn
from torchmetrics import Metric

from merlin.models.torch.block import Block
from merlin.schema import ColumnSchema, Schema


class ModelOutput(Block):
"""A base class for prediction tasks.

marcromeyn marked this conversation as resolved.
Show resolved Hide resolved
Parameters
----------
loss: nn.Module
The loss function used for training.
metrics: Sequence[Metric]
The metrics used for evaluation.
name: Optional[str]
The name of the model output.
schema: Optional[ColumnSchema]
The schema defining the column properties.
"""

def __init__(
self,
*module: nn.Module,
loss: nn.Module,
metrics: Sequence[Metric] = (),
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved
name: Optional[str] = None,
schema: Optional[ColumnSchema] = None,
):
"""Initializes a ModelOutput object."""
super().__init__(*module, name=name)

self.loss = loss
self.metrics = metrics
self._output_schema = None
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved

if schema:
self.setup_schema(schema)
self.register_buffer("target", torch.zeros(1, dtype=torch.float32))

def setup_schema(self, schema: Optional[ColumnSchema]):
Copy link
Contributor

Choose a reason for hiding this comment

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

Do you think we need to make things more explicit and turn this into setup_column_schema?

Copy link
Contributor Author

@edknv edknv May 18, 2023

Choose a reason for hiding this comment

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

I guess we could go either way, but I kept setup_schema in 2385020, since output_schema is a Schema not a ColumnSchema.

"""Set up the schema for the output.

Parameters
----------
schema: ColumnSchema or None
The schema defining the column properties.
"""
self._output_schema = Schema([schema])

@property
def output_schema(self):
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved
"""The schema of the output.

Returns
-------
Schema or None
The schema defining the column properties.
"""
return self._output_schema

def eval(self):
"""Sets the module in evaluation mode.

Returns
-------
nn.Module
The module in evaluation mode.
"""
# Reset target
self.target = torch.zeros(1, dtype=torch.float32)
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved

return self.train(False)
75 changes: 75 additions & 0 deletions merlin/models/torch/outputs/classification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#
# Copyright (c) 2023, 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.
#
from typing import Optional, Sequence

from torch import nn
from torchmetrics import AUROC, Accuracy, Metric, Precision, Recall

import merlin.dtypes as md
from merlin.models.torch.outputs.base import ModelOutput
from merlin.schema import ColumnSchema, Schema


class BinaryOutput(ModelOutput):
"""A prediction block for binary classification.

Parameters
----------
loss: nn.Module
The loss function used for training. Default is nn.BCEWithLogitsLoss().
metrics: Sequence[Metric]
The metrics used for evaluation. Default includes Accuracy, AUROC, Precision, and Recall.
schema: Optional[ColumnSchema])
The schema defining the column properties. Default is None.
"""

def __init__(
self,
loss=nn.BCEWithLogitsLoss(),
metrics: Sequence[Metric] = (
Accuracy(task="binary"),
AUROC(task="binary"),
Precision(task="binary"),
Recall(task="binary"),
),
schema: Optional[ColumnSchema] = None,
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved
):
"""Initializes a BinaryOutput object."""
super().__init__(
nn.LazyLinear(1),
nn.Sigmoid(),
loss=loss,
metrics=metrics,
schema=schema,
)
if schema:
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved
self.setup_schema(schema)

def setup_schema(self, target: Optional[ColumnSchema]):
"""Set up the schema for the output.

Parameters
----------
target: Optional[ColumnSchema]
The schema defining the column properties.
"""
_target = target.with_dtype(md.float32)
if "domain" not in target.properties:
_target = _target.with_properties(
{"domain": {"min": 0, "max": 1, "name": _target.name}},
)

self._output_schema = Schema([_target])
15 changes: 15 additions & 0 deletions tests/unit/torch/outputs/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#
# Copyright (c) 2023, 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.
#
73 changes: 73 additions & 0 deletions tests/unit/torch/outputs/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#
# Copyright (c) 2023, 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 numpy as np
import torch
from torch import nn
from torchmetrics import AUROC, Accuracy

import merlin.models.torch as mm
from merlin.models.torch.utils import module_utils
from merlin.schema import ColumnSchema, Schema, Tags


class TestModelOutput:
def test_init(self):
block = mm.Block()
loss = nn.BCEWithLogitsLoss()
model_output = mm.ModelOutput(block, loss=loss)

assert isinstance(model_output, mm.ModelOutput)
assert model_output.loss is loss
assert model_output.metrics == ()
assert model_output.output_schema is None

def test_identity(self):
block = mm.Block()
loss = nn.BCEWithLogitsLoss()
model_output = mm.ModelOutput(block, loss=loss)
inputs = torch.tensor([[1.0, 2.0], [3.0, 4.0]])

outputs = module_utils.module_test(model_output, inputs)

assert torch.equal(inputs, outputs)

def test_setup_metrics(self):
block = mm.Block()
loss = nn.BCEWithLogitsLoss()
metrics = (Accuracy(task="binary"), AUROC(task="binary"))
model_output = mm.ModelOutput(block, loss=loss, metrics=metrics)

assert model_output.metrics == metrics

def test_setup_schema(self):
block = mm.Block()
loss = nn.BCEWithLogitsLoss()
schema = ColumnSchema("feature", dtype=np.int32, tags=[Tags.CONTINUOUS])
model_output = mm.ModelOutput(block, loss=loss, schema=schema)

assert isinstance(model_output.output_schema, Schema)
assert model_output.output_schema.first == schema

def test_eval_resets_target(self):
block = mm.Block()
loss = nn.BCEWithLogitsLoss()
model_output = mm.ModelOutput(block, loss=loss)

assert torch.equal(model_output.target, torch.zeros(1))
model_output.target = torch.ones(1)
assert torch.equal(model_output.target, torch.ones(1))
model_output.eval()
assert torch.equal(model_output.target, torch.zeros(1))
56 changes: 56 additions & 0 deletions tests/unit/torch/outputs/test_classification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#
# Copyright (c) 2023, 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 torch
from torch import nn
from torchmetrics import AUROC, Accuracy, Precision, Recall

import merlin.dtypes as md
import merlin.models.torch as mm
from merlin.models.torch.utils import module_utils
from merlin.schema import ColumnSchema, Schema


class TestBinaryOutput:
marcromeyn marked this conversation as resolved.
Show resolved Hide resolved
def test_init(self):
binary_output = mm.BinaryOutput()

assert isinstance(binary_output, mm.BinaryOutput)
assert isinstance(binary_output.loss, nn.BCEWithLogitsLoss)
assert binary_output.metrics == (
Accuracy(task="binary"),
AUROC(task="binary"),
Precision(task="binary"),
Recall(task="binary"),
)
assert binary_output.output_schema is None

def test_identity(self):
binary_output = mm.BinaryOutput()
inputs = torch.randn(2, 3)

outputs = module_utils.module_test(binary_output, inputs)

assert outputs.shape == (2, 1)

def test_setup_schema(self):
schema = ColumnSchema("foo")
binary_output = mm.BinaryOutput(schema=schema)

assert isinstance(binary_output.output_schema, Schema)
assert binary_output.output_schema.first.dtype == md.float32
assert binary_output.output_schema.first.properties["domain"]["name"] == "foo"
assert binary_output.output_schema.first.properties["domain"]["min"] == 0
assert binary_output.output_schema.first.properties["domain"]["max"] == 1