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

CrossEncoder device #2463

Merged
merged 14 commits into from
Feb 1, 2024
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
20 changes: 2 additions & 18 deletions sentence_transformers/SentenceTransformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import shutil
from collections import OrderedDict
import warnings
from typing import List, Dict, Tuple, Iterable, Type, Union, Callable, Optional, Literal, TYPE_CHECKING
from typing import List, Dict, Tuple, Iterable, Type, Union, Callable, Optional, TYPE_CHECKING
import numpy as np
from numpy import ndarray
import transformers
Expand All @@ -29,6 +29,7 @@
load_dir_path,
load_file_path,
save_to_hub_args_decorator,
get_device_name,
)
from .models import Transformer, Pooling, Normalize
from .model_card_templates import ModelCardTemplate
Expand All @@ -41,23 +42,6 @@
from sentence_transformers.readers import InputExample


def get_device_name() -> Literal["mps", "cuda", "cpu"]:
"""
Returns the name of the device where this module is running on.
It's simple implementation that doesn't cover cases when more powerful GPUs are available and
not a primary device ('cuda:0') or MPS device is available, but not configured properly:
https://pytorch.org/docs/master/notes/mps.html

:return: Device name, like 'cuda' or 'cpu'
"""
if torch.cuda.is_available():
return "cuda"
elif torch.backends.mps.is_available():
return "mps"
else:
return "cpu"


class SentenceTransformer(nn.Sequential):
"""
Loads or creates a SentenceTransformer model that can be used to map sentences / text to embeddings.
Expand Down
3 changes: 2 additions & 1 deletion sentence_transformers/cross_encoder/CrossEncoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from tqdm.autonotebook import tqdm, trange
from .. import SentenceTransformer, util
from ..evaluation import SentenceEvaluator
from ..util import get_device_name


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -73,7 +74,7 @@ def __init__(
self.max_length = max_length

if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
device = get_device_name()
logger.info("Use pytorch device: {}".format(device))

self._target_device = torch.device(device)
Expand Down
19 changes: 18 additions & 1 deletion sentence_transformers/util.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import functools
import requests
from torch import Tensor, device
from typing import List, Callable
from typing import List, Callable, Literal
from tqdm.autonotebook import tqdm
import sys
import importlib
Expand Down Expand Up @@ -556,3 +556,20 @@ def wrapper(self, *args, **kwargs):
return func(self, *args, **kwargs)

return wrapper


def get_device_name() -> Literal["mps", "cuda", "cpu"]:
"""
Returns the name of the device where this module is running on.
It's simple implementation that doesn't cover cases when more powerful GPUs are available and
not a primary device ('cuda:0') or MPS device is available, but not configured properly:
https://pytorch.org/docs/master/notes/mps.html

:return: Device name, like 'cuda' or 'cpu'
"""
if torch.cuda.is_available():
return "cuda"
elif torch.backends.mps.is_available():
return "mps"
else:
return "cpu"
Loading