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

Reintroduce SetFitModel.to #236

Merged
merged 1 commit into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 16 additions & 0 deletions src/setfit/modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,22 @@ def predict_proba(self, x_test: List[str]) -> Union[torch.Tensor, np.ndarray]:
embeddings = self.model_body.encode(x_test, normalize_embeddings=self.normalize_embeddings)
return self.model_head.predict_proba(embeddings)

def to(self, device: Union[str, torch.device]) -> "SetFitModel":
"""Move this SetFitModel to `device`, and then return `self`. This method does not copy.

Args:
device (Union[str, torch.device]): The identifier of the device to move the model to.

Returns:
SetFitModel: Returns the original model, but now on the desired device.
"""
self.model_body = self.model_body.to(device)

if isinstance(self.model_head, torch.nn.Module):
self.model_head = self.model_head.to(device)

return self

def __call__(self, inputs):
return self.predict(inputs)

Expand Down
28 changes: 28 additions & 0 deletions tests/test_modeling.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from unittest import TestCase

import numpy as np
import torch
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from sklearn.linear_model import LogisticRegression
Expand Down Expand Up @@ -209,3 +210,30 @@ def test_setfit_from_pretrained_local_model_with_head(tmp_path):
model = SetFitModel.from_pretrained(str(tmp_path.absolute()))

assert isinstance(model, SetFitModel)


def test_to_logistic_head():
model = SetFitModel.from_pretrained("sentence-transformers/paraphrase-albert-small-v2")
devices = (
[torch.device("cpu"), torch.device("cuda", 0), torch.device("cpu")]
if torch.cuda.is_available()
else [torch.device("cpu")]
)
for device in devices:
model.to(device)
assert model.model_body.device == device


def test_to_torch_head():
model = SetFitModel.from_pretrained(
"sentence-transformers/paraphrase-albert-small-v2", use_differentiable_head=True
)
devices = (
[torch.device("cpu"), torch.device("cuda", 0), torch.device("cpu")]
if torch.cuda.is_available()
else [torch.device("cpu")]
)
for device in devices:
model.to(device)
assert model.model_body.device == device
assert model.model_head.device == device