-
Notifications
You must be signed in to change notification settings - Fork 103
/
transformers_helpers.py
174 lines (136 loc) · 5.57 KB
/
transformers_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
from __future__ import annotations
import importlib
from functools import lru_cache
from typing import Literal, get_args
from transformers import (
PreTrainedModel,
PreTrainedTokenizer,
PreTrainedTokenizerFast,
TFPreTrainedModel,
)
from .exception import LLMGuardValidationError
from .model import Model
from .util import device, get_logger, lazy_load_dep
LOGGER = get_logger()
def get_tokenizer(model: Model):
"""
This function loads a tokenizer given a model identifier and caches it.
Subsequent calls with the same model_identifier will return the cached tokenizer.
Args:
model (Model): The model to load the tokenizer for.
"""
transformers = lazy_load_dep("transformers")
tokenizer = transformers.AutoTokenizer.from_pretrained(
model.path, revision=model.revision, **model.tokenizer_kwargs
)
return tokenizer
@lru_cache(maxsize=None) # Unbounded cache
def is_onnx_supported() -> bool:
is_supported = importlib.util.find_spec("optimum.onnxruntime") is not None # type: ignore
if not is_supported:
LOGGER.warning(
"ONNX Runtime is not available. "
"Please install optimum: "
"`pip install llm-guard[onnxruntime]` for CPU or "
"`pip install llm-guard[onnxruntime-gpu]` for GPU to enable ONNX Runtime optimizations."
)
return is_supported
def _ort_model_for_sequence_classification(
model: Model,
):
provider = "CPUExecutionProvider"
package_name = "optimum[onnxruntime]"
if device().type == "cuda":
package_name = "optimum[onnxruntime-gpu]"
provider = "CUDAExecutionProvider"
onnxruntime = lazy_load_dep("optimum.onnxruntime", package_name)
tf_model = onnxruntime.ORTModelForSequenceClassification.from_pretrained(
model.onnx_path or model.path,
export=model.onnx_path is None,
file_name=model.onnx_filename,
subfolder=model.onnx_subfolder,
revision=model.onnx_revision,
provider=provider,
**model.kwargs,
)
LOGGER.debug("Initialized classification ONNX model", model=model, device=device())
return tf_model
def get_tokenizer_and_model_for_classification(
model: Model,
use_onnx: bool = False,
):
"""
This function loads a tokenizer and model given a model identifier and caches them.
Subsequent calls with the same model_identifier will return the cached tokenizer.
Args:
model (str): The model identifier to load the tokenizer and model for.
use_onnx (bool): Whether to use the ONNX version of the model. Defaults to False.
"""
tf_tokenizer = get_tokenizer(model)
transformers = lazy_load_dep("transformers")
if use_onnx and is_onnx_supported() is False:
LOGGER.warning("ONNX is not supported on this machine. Using PyTorch instead of ONNX.")
use_onnx = False
if use_onnx is False:
tf_model = transformers.AutoModelForSequenceClassification.from_pretrained(
model.path, subfolder=model.subfolder, revision=model.revision, **model.kwargs
)
LOGGER.debug("Initialized classification model", model=model, device=device())
return tf_tokenizer, tf_model
tf_model = _ort_model_for_sequence_classification(model)
return tf_tokenizer, tf_model
def get_tokenizer_and_model_for_ner(
model: Model,
use_onnx: bool = False,
):
"""
This function loads a tokenizer and model given a model identifier and caches them.
Subsequent calls with the same model_identifier will return the cached tokenizer.
Args:
model (str): The model identifier to load the tokenizer and model for.
use_onnx (bool): Whether to use the ONNX version of the model. Defaults to False.
"""
tf_tokenizer = get_tokenizer(model)
transformers = lazy_load_dep("transformers")
if use_onnx and is_onnx_supported() is False:
LOGGER.warning("ONNX is not supported on this machine. Using PyTorch instead of ONNX.")
use_onnx = False
if use_onnx is False:
tf_model = transformers.AutoModelForTokenClassification.from_pretrained(
model.path, subfolder=model.subfolder, revision=model.revision, **model.kwargs
)
LOGGER.debug("Initialized NER model", model=model, device=device())
return tf_tokenizer, tf_model
optimum_onnxruntime = lazy_load_dep(
"optimum.onnxruntime",
"optimum[onnxruntime]" if device().type != "cuda" else "optimum[onnxruntime-gpu]",
)
tf_model = optimum_onnxruntime.ORTModelForTokenClassification.from_pretrained(
model.onnx_path,
export=False,
subfolder=model.onnx_subfolder,
provider=("CUDAExecutionProvider" if device().type == "cuda" else "CPUExecutionProvider"),
revision=model.onnx_revision,
file_name=model.onnx_filename,
**model.kwargs,
)
LOGGER.debug("Initialized NER ONNX model", model=model, device=device())
return tf_tokenizer, tf_model
ClassificationTask = Literal["text-classification", "zero-shot-classification"]
def pipeline(
task: str,
model: PreTrainedModel | TFPreTrainedModel,
tokenizer: PreTrainedTokenizer | PreTrainedTokenizerFast,
**kwargs,
):
if task not in get_args(ClassificationTask):
raise LLMGuardValidationError(f"Invalid task. Must be one of {ClassificationTask}")
if kwargs.get("max_length", None) is None:
kwargs["max_length"] = tokenizer.model_max_length
transformers = lazy_load_dep("transformers")
return transformers.pipeline(
task,
model=model,
tokenizer=tokenizer,
**kwargs,
)