Skip to content

Commit 2cb2ea3

Browse files
authored
Accepting real pytorch device as arguments. (huggingface#17318)
* Accepting real pytorch device as arguments. * is_torch_available.
1 parent 1c9d1f4 commit 2cb2ea3

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/transformers/pipelines/base.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -693,7 +693,7 @@ def predict(self, X):
693693
Reference to the object in charge of parsing supplied pipeline parameters.
694694
device (`int`, *optional*, defaults to -1):
695695
Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on
696-
the associated CUDA device id.
696+
the associated CUDA device id. You can pass native `torch.device` too.
697697
binary_output (`bool`, *optional*, defaults to `False`):
698698
Flag indicating if the output the pipeline should happen in a binary format (i.e., pickle) or as raw text.
699699
"""
@@ -750,7 +750,10 @@ def __init__(
750750
self.feature_extractor = feature_extractor
751751
self.modelcard = modelcard
752752
self.framework = framework
753-
self.device = device if framework == "tf" else torch.device("cpu" if device < 0 else f"cuda:{device}")
753+
if is_torch_available() and isinstance(device, torch.device):
754+
self.device = device
755+
else:
756+
self.device = device if framework == "tf" else torch.device("cpu" if device < 0 else f"cuda:{device}")
754757
self.binary_output = binary_output
755758

756759
# Special handling

tests/pipelines/test_pipelines_text_classification.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,20 @@ def test_small_model_pt(self):
3939
outputs = text_classifier("This is great !")
4040
self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}])
4141

42+
@require_torch
43+
def test_accepts_torch_device(self):
44+
import torch
45+
46+
text_classifier = pipeline(
47+
task="text-classification",
48+
model="hf-internal-testing/tiny-random-distilbert",
49+
framework="pt",
50+
device=torch.device("cpu"),
51+
)
52+
53+
outputs = text_classifier("This is great !")
54+
self.assertEqual(nested_simplify(outputs), [{"label": "LABEL_0", "score": 0.504}])
55+
4256
@require_tf
4357
def test_small_model_tf(self):
4458
text_classifier = pipeline(

0 commit comments

Comments
 (0)