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

feat: use gpu if available #15

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from collections import defaultdict
from typing import Dict, List, Optional, Union

import torch
from sparv import api as sparv_api # type: ignore [import-untyped]
from transformers import ( # type: ignore [import-untyped]
AutoModelForSequenceClassification,
Expand All @@ -23,6 +24,20 @@
MAX_LENGTH: int = 700


def _get_dtype() -> torch.dtype:
if torch.cuda.is_available():
logger.info("Using GPU (cuda)")
dtype = torch.float16
else:
logger.warning("Using CPU, is cuda available?")
dtype = torch.float32
return dtype


def _get_device_map() -> Optional[str]:
return "auto" if torch.cuda.is_available() and torch.cuda.device_count() > 1 else None


class SentimentAnalyzer:
"""Sentiment analyzer."""

Expand All @@ -45,8 +60,19 @@ def __init__(
self.tokenizer = self._default_tokenizer() if tokenizer is None else tokenizer
self.model = self._default_model() if model is None else model
self.num_decimals = num_decimals

if torch.cuda.is_available() and torch.cuda.device_count() == 1:
logger.info("Using GPU (cuda)")
self.model = self.model.cuda() # type: ignore
else:
logger.warning("Using CPU, is cuda available?")

self.classifier = pipeline(
"sentiment-analysis", model=self.model, tokenizer=self.tokenizer
"sentiment-analysis",
model=self.model,
tokenizer=self.tokenizer,
torch_dtype=_get_dtype(),
device_map=_get_device_map(),
)

@classmethod
Expand All @@ -56,7 +82,10 @@ def _default_tokenizer(cls) -> PreTrainedTokenizerFast:
@classmethod
def _default_model(cls) -> MegatronBertForSequenceClassification:
return AutoModelForSequenceClassification.from_pretrained(
MODEL_NAME, revision=MODEL_REVISION
MODEL_NAME,
revision=MODEL_REVISION,
torch_dtype=_get_dtype(),
device_map=_get_device_map(),
)

@classmethod
Expand Down