clarifai 10.8.3__py3-none-any.whl → 10.8.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- clarifai/__init__.py +1 -1
- clarifai/client/dataset.py +9 -3
- clarifai/constants/dataset.py +1 -1
- clarifai/datasets/upload/base.py +6 -3
- clarifai/datasets/upload/features.py +10 -0
- clarifai/datasets/upload/image.py +22 -13
- clarifai/datasets/upload/multimodal.py +70 -0
- clarifai/datasets/upload/text.py +8 -5
- clarifai/runners/utils/data_handler.py +31 -44
- clarifai/runners/utils/loader.py +6 -5
- clarifai/utils/misc.py +6 -0
- {clarifai-10.8.3.dist-info → clarifai-10.8.5.dist-info}/METADATA +2 -1
- {clarifai-10.8.3.dist-info → clarifai-10.8.5.dist-info}/RECORD +17 -60
- clarifai/models/model_serving/README.md +0 -158
- clarifai/models/model_serving/__init__.py +0 -14
- clarifai/models/model_serving/cli/__init__.py +0 -12
- clarifai/models/model_serving/cli/_utils.py +0 -53
- clarifai/models/model_serving/cli/base.py +0 -14
- clarifai/models/model_serving/cli/build.py +0 -79
- clarifai/models/model_serving/cli/clarifai_clis.py +0 -33
- clarifai/models/model_serving/cli/create.py +0 -171
- clarifai/models/model_serving/cli/example_cli.py +0 -34
- clarifai/models/model_serving/cli/login.py +0 -26
- clarifai/models/model_serving/cli/upload.py +0 -183
- clarifai/models/model_serving/constants.py +0 -21
- clarifai/models/model_serving/docs/cli.md +0 -161
- clarifai/models/model_serving/docs/concepts.md +0 -229
- clarifai/models/model_serving/docs/dependencies.md +0 -11
- clarifai/models/model_serving/docs/inference_parameters.md +0 -139
- clarifai/models/model_serving/docs/model_types.md +0 -19
- clarifai/models/model_serving/model_config/__init__.py +0 -16
- clarifai/models/model_serving/model_config/base.py +0 -369
- clarifai/models/model_serving/model_config/config.py +0 -312
- clarifai/models/model_serving/model_config/inference_parameter.py +0 -129
- clarifai/models/model_serving/model_config/model_types_config/multimodal-embedder.yaml +0 -25
- clarifai/models/model_serving/model_config/model_types_config/text-classifier.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/text-embedder.yaml +0 -20
- clarifai/models/model_serving/model_config/model_types_config/text-to-image.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/text-to-text.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/visual-classifier.yaml +0 -22
- clarifai/models/model_serving/model_config/model_types_config/visual-detector.yaml +0 -32
- clarifai/models/model_serving/model_config/model_types_config/visual-embedder.yaml +0 -19
- clarifai/models/model_serving/model_config/model_types_config/visual-segmenter.yaml +0 -19
- clarifai/models/model_serving/model_config/output.py +0 -133
- clarifai/models/model_serving/model_config/triton/__init__.py +0 -14
- clarifai/models/model_serving/model_config/triton/serializer.py +0 -136
- clarifai/models/model_serving/model_config/triton/triton_config.py +0 -182
- clarifai/models/model_serving/model_config/triton/wrappers.py +0 -281
- clarifai/models/model_serving/repo_build/__init__.py +0 -14
- clarifai/models/model_serving/repo_build/build.py +0 -198
- clarifai/models/model_serving/repo_build/static_files/_requirements.txt +0 -2
- clarifai/models/model_serving/repo_build/static_files/base_test.py +0 -169
- clarifai/models/model_serving/repo_build/static_files/inference.py +0 -26
- clarifai/models/model_serving/repo_build/static_files/sample_clarifai_config.yaml +0 -25
- clarifai/models/model_serving/repo_build/static_files/test.py +0 -40
- clarifai/models/model_serving/repo_build/static_files/triton/model.py +0 -75
- clarifai/models/model_serving/utils.py +0 -31
- {clarifai-10.8.3.dist-info → clarifai-10.8.5.dist-info}/LICENSE +0 -0
- {clarifai-10.8.3.dist-info → clarifai-10.8.5.dist-info}/WHEEL +0 -0
- {clarifai-10.8.3.dist-info → clarifai-10.8.5.dist-info}/entry_points.txt +0 -0
- {clarifai-10.8.3.dist-info → clarifai-10.8.5.dist-info}/top_level.txt +0 -0
@@ -1,281 +0,0 @@
|
|
1
|
-
# Copyright 2023 Clarifai, Inc.
|
2
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
3
|
-
# you may not use this file except in compliance with the License.
|
4
|
-
# You may obtain a copy of the License at
|
5
|
-
#
|
6
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
7
|
-
#
|
8
|
-
# Unless required by applicable law or agreed to in writing, software
|
9
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
10
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
11
|
-
# See the License for the specific language governing permissions and
|
12
|
-
# limitations under the License.
|
13
|
-
"""
|
14
|
-
Parse inference model predictions to triton inference responses
|
15
|
-
per model type.
|
16
|
-
"""
|
17
|
-
|
18
|
-
from functools import wraps
|
19
|
-
from itertools import zip_longest
|
20
|
-
from typing import Callable, Dict
|
21
|
-
import numpy as np
|
22
|
-
|
23
|
-
try:
|
24
|
-
import triton_python_backend_utils as pb_utils
|
25
|
-
except ModuleNotFoundError:
|
26
|
-
pass
|
27
|
-
|
28
|
-
|
29
|
-
def visual_detector(func: Callable):
|
30
|
-
"""
|
31
|
-
Visual detector type output parser.
|
32
|
-
"""
|
33
|
-
|
34
|
-
@wraps(func)
|
35
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
36
|
-
"""
|
37
|
-
Format predictions and return clarifai compatible output.
|
38
|
-
"""
|
39
|
-
out_bboxes = []
|
40
|
-
out_labels = []
|
41
|
-
out_scores = []
|
42
|
-
|
43
|
-
# input_data passed as list of images
|
44
|
-
preds = func(self, list(input_data[:]), *args, **kwargs)
|
45
|
-
for pred in preds:
|
46
|
-
out_bboxes.append(pred.predicted_bboxes)
|
47
|
-
out_labels.append(pred.predicted_labels)
|
48
|
-
out_scores.append(pred.predicted_scores)
|
49
|
-
|
50
|
-
if len(out_bboxes) < 1 or len(out_labels) < 1:
|
51
|
-
out_tensor_bboxes = pb_utils.Tensor("predicted_bboxes", np.zeros((0, 4), dtype=np.float32))
|
52
|
-
out_tensor_labels = pb_utils.Tensor("predicted_labels", np.zeros((0, 1), dtype=np.int32))
|
53
|
-
out_tensor_scores = pb_utils.Tensor("predicted_scores", np.zeros((0, 1), dtype=np.float32))
|
54
|
-
else:
|
55
|
-
out_tensor_bboxes = pb_utils.Tensor("predicted_bboxes",
|
56
|
-
np.asarray(out_bboxes, dtype=np.float32))
|
57
|
-
out_tensor_labels = pb_utils.Tensor("predicted_labels",
|
58
|
-
np.asarray(out_labels, dtype=np.int32))
|
59
|
-
out_tensor_scores = pb_utils.Tensor("predicted_scores",
|
60
|
-
np.asarray(out_scores, dtype=np.float32))
|
61
|
-
|
62
|
-
inference_response = pb_utils.InferenceResponse(
|
63
|
-
output_tensors=[out_tensor_bboxes, out_tensor_labels, out_tensor_scores])
|
64
|
-
|
65
|
-
return inference_response
|
66
|
-
|
67
|
-
return parse_predictions
|
68
|
-
|
69
|
-
|
70
|
-
def visual_classifier(func: Callable):
|
71
|
-
"""
|
72
|
-
Visual classifier type output parser.
|
73
|
-
"""
|
74
|
-
|
75
|
-
@wraps(func)
|
76
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
77
|
-
"""
|
78
|
-
Format predictions and return clarifai compatible output.
|
79
|
-
"""
|
80
|
-
out_scores = []
|
81
|
-
# input_data passed as list of images
|
82
|
-
preds = func(self, list(input_data[:]), *args, **kwargs)
|
83
|
-
|
84
|
-
for pred in preds:
|
85
|
-
out_scores.append(pred.predicted_scores)
|
86
|
-
|
87
|
-
out_tensor_scores = pb_utils.Tensor("softmax_predictions",
|
88
|
-
np.asarray(out_scores, dtype=np.float32))
|
89
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_tensor_scores])
|
90
|
-
|
91
|
-
return inference_response
|
92
|
-
|
93
|
-
return parse_predictions
|
94
|
-
|
95
|
-
|
96
|
-
def text_classifier(func: Callable):
|
97
|
-
"""
|
98
|
-
Text classifier type output parser.
|
99
|
-
"""
|
100
|
-
|
101
|
-
@wraps(func)
|
102
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
103
|
-
"""
|
104
|
-
Format predictions and return clarifai compatible output.
|
105
|
-
"""
|
106
|
-
out_scores = []
|
107
|
-
input_data = [in_elem[0].decode() for in_elem in input_data]
|
108
|
-
preds = func(self, input_data, *args, **kwargs)
|
109
|
-
|
110
|
-
for pred in preds:
|
111
|
-
out_scores.append(pred.predicted_scores)
|
112
|
-
|
113
|
-
out_tensor_scores = pb_utils.Tensor("softmax_predictions",
|
114
|
-
np.asarray(out_scores, dtype=np.float32))
|
115
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_tensor_scores])
|
116
|
-
|
117
|
-
return inference_response
|
118
|
-
|
119
|
-
return parse_predictions
|
120
|
-
|
121
|
-
|
122
|
-
def text_to_text(func: Callable):
|
123
|
-
"""
|
124
|
-
Text to text type output parser.
|
125
|
-
Convert a sequence of text into another e.g. text generation,
|
126
|
-
summarization or translation.
|
127
|
-
"""
|
128
|
-
|
129
|
-
@wraps(func)
|
130
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
131
|
-
"""
|
132
|
-
Format predictions and return clarifai compatible output.
|
133
|
-
"""
|
134
|
-
out_text = []
|
135
|
-
input_data = [in_elem[0].decode() for in_elem in input_data]
|
136
|
-
preds = func(self, input_data, *args, **kwargs)
|
137
|
-
|
138
|
-
for pred in preds:
|
139
|
-
out_text.append(pred.predicted_text)
|
140
|
-
|
141
|
-
out_text_tensor = pb_utils.Tensor("text", np.asarray(out_text, dtype=object))
|
142
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_text_tensor])
|
143
|
-
|
144
|
-
return inference_response
|
145
|
-
|
146
|
-
return parse_predictions
|
147
|
-
|
148
|
-
|
149
|
-
def text_embedder(func: Callable):
|
150
|
-
"""
|
151
|
-
Text embedder type output parser.
|
152
|
-
Generates embeddings for an input text.
|
153
|
-
"""
|
154
|
-
|
155
|
-
@wraps(func)
|
156
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
157
|
-
"""
|
158
|
-
Format predictions and return clarifai compatible output.
|
159
|
-
"""
|
160
|
-
out_embeddings = []
|
161
|
-
input_data = [in_elem[0].decode() for in_elem in input_data]
|
162
|
-
preds = func(self, input_data, *args, **kwargs)
|
163
|
-
|
164
|
-
for pred in preds:
|
165
|
-
out_embeddings.append(pred.embedding_vector)
|
166
|
-
|
167
|
-
out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
|
168
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
|
169
|
-
|
170
|
-
return inference_response
|
171
|
-
|
172
|
-
return parse_predictions
|
173
|
-
|
174
|
-
|
175
|
-
def visual_embedder(func: Callable):
|
176
|
-
"""
|
177
|
-
Visual embedder type output parser.
|
178
|
-
Generates embeddings for an input image.
|
179
|
-
"""
|
180
|
-
|
181
|
-
@wraps(func)
|
182
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
183
|
-
"""
|
184
|
-
Format predictions and return clarifai compatible output.
|
185
|
-
"""
|
186
|
-
out_embeddings = []
|
187
|
-
# input_data passed as list of images
|
188
|
-
preds = func(self, list(input_data[:]), *args, **kwargs)
|
189
|
-
|
190
|
-
for pred in preds:
|
191
|
-
out_embeddings.append(pred.embedding_vector)
|
192
|
-
|
193
|
-
out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
|
194
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
|
195
|
-
|
196
|
-
return inference_response
|
197
|
-
|
198
|
-
return parse_predictions
|
199
|
-
|
200
|
-
|
201
|
-
def visual_segmenter(func: Callable):
|
202
|
-
"""
|
203
|
-
Visual segmenter type output parser.
|
204
|
-
"""
|
205
|
-
|
206
|
-
@wraps(func)
|
207
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
208
|
-
"""
|
209
|
-
Format predictions and return clarifai compatible output.
|
210
|
-
"""
|
211
|
-
masks = []
|
212
|
-
# input_data passed as list of images
|
213
|
-
preds = func(self, list(input_data[:]), *args, **kwargs)
|
214
|
-
|
215
|
-
for pred in preds:
|
216
|
-
masks.append(pred.predicted_mask)
|
217
|
-
|
218
|
-
out_mask_tensor = pb_utils.Tensor("predicted_mask", np.asarray(masks, dtype=np.int64))
|
219
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_mask_tensor])
|
220
|
-
|
221
|
-
return inference_response
|
222
|
-
|
223
|
-
return parse_predictions
|
224
|
-
|
225
|
-
|
226
|
-
def text_to_image(func: Callable):
|
227
|
-
"""
|
228
|
-
Text to image type output parser.
|
229
|
-
"""
|
230
|
-
|
231
|
-
@wraps(func)
|
232
|
-
def parse_predictions(self, input_data: np.ndarray, *args, **kwargs):
|
233
|
-
"""
|
234
|
-
Format predictions and return clarifai compatible output.
|
235
|
-
"""
|
236
|
-
gen_images = []
|
237
|
-
input_data = [in_elem[0].decode() for in_elem in input_data]
|
238
|
-
preds = func(self, input_data, *args, **kwargs)
|
239
|
-
|
240
|
-
for pred in preds:
|
241
|
-
gen_images.append(pred.image)
|
242
|
-
|
243
|
-
out_image_tensor = pb_utils.Tensor("image", np.asarray(gen_images, dtype=np.uint8))
|
244
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_image_tensor])
|
245
|
-
|
246
|
-
return inference_response
|
247
|
-
|
248
|
-
return parse_predictions
|
249
|
-
|
250
|
-
|
251
|
-
def multimodal_embedder(func: Callable):
|
252
|
-
"""
|
253
|
-
Multimodal embedder type output parser.
|
254
|
-
Generates embeddings for image or text input.
|
255
|
-
"""
|
256
|
-
|
257
|
-
@wraps(func)
|
258
|
-
def parse_predictions(self, input_data: Dict[str, np.ndarray], *args, **kwargs):
|
259
|
-
"""
|
260
|
-
Format predictions and return clarifai compatible output.
|
261
|
-
"""
|
262
|
-
out_embeddings = []
|
263
|
-
model_input_data = []
|
264
|
-
for group in zip_longest(*input_data.values()):
|
265
|
-
_input_data = dict(zip(input_data, group))
|
266
|
-
for k, v in _input_data.items():
|
267
|
-
# decode np.object to string
|
268
|
-
if isinstance(v, np.ndarray) and v.dtype == np.object_:
|
269
|
-
_input_data.update({k: v[0].decode()})
|
270
|
-
model_input_data.append(_input_data)
|
271
|
-
|
272
|
-
preds = func(self, model_input_data, *args, **kwargs)
|
273
|
-
for pred in preds:
|
274
|
-
out_embeddings.append(pred.embedding_vector)
|
275
|
-
|
276
|
-
out_embed_tensor = pb_utils.Tensor("embeddings", np.asarray(out_embeddings, dtype=np.float32))
|
277
|
-
inference_response = pb_utils.InferenceResponse(output_tensors=[out_embed_tensor])
|
278
|
-
|
279
|
-
return inference_response
|
280
|
-
|
281
|
-
return parse_predictions
|
@@ -1,14 +0,0 @@
|
|
1
|
-
# Copyright 2023 Clarifai, Inc.
|
2
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
3
|
-
# you may not use this file except in compliance with the License.
|
4
|
-
# You may obtain a copy of the License at
|
5
|
-
#
|
6
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
7
|
-
#
|
8
|
-
# Unless required by applicable law or agreed to in writing, software
|
9
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
10
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
11
|
-
# See the License for the specific language governing permissions and
|
12
|
-
# limitations under the License.
|
13
|
-
from .build import RepositoryBuilder # noqa
|
14
|
-
from .static_files.base_test import BaseTest # noqa
|
@@ -1,198 +0,0 @@
|
|
1
|
-
# Copyright 2023 Clarifai, Inc.
|
2
|
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
3
|
-
# you may not use this file except in compliance with the License.
|
4
|
-
# You may obtain a copy of the License at
|
5
|
-
#
|
6
|
-
# http://www.apache.org/licenses/LICENSE-2.0
|
7
|
-
#
|
8
|
-
# Unless required by applicable law or agreed to in writing, software
|
9
|
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
10
|
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
11
|
-
# See the License for the specific language governing permissions and
|
12
|
-
# limitations under the License.
|
13
|
-
"""
|
14
|
-
Triton python backend inference model controller.
|
15
|
-
"""
|
16
|
-
|
17
|
-
import inspect
|
18
|
-
import os
|
19
|
-
import shutil
|
20
|
-
import zipfile
|
21
|
-
from dataclasses import asdict
|
22
|
-
from pathlib import Path
|
23
|
-
from typing import Iterable, Literal, Union
|
24
|
-
|
25
|
-
import yaml
|
26
|
-
from tqdm import tqdm
|
27
|
-
|
28
|
-
from ..constants import BUILT_MODEL_EXT
|
29
|
-
from ..model_config import MODEL_TYPES, ModelConfigClass, base, get_model_config, load_user_config
|
30
|
-
from ..model_config.base import * # noqa
|
31
|
-
from ..model_config.config import parse_config
|
32
|
-
from ..model_config.triton.serializer import Serializer
|
33
|
-
|
34
|
-
|
35
|
-
def __parse_type_to_class():
|
36
|
-
_t = {}
|
37
|
-
_classes = inspect.getmembers(base, inspect.isclass)
|
38
|
-
for cls_name, cls_obj in _classes:
|
39
|
-
if cls_obj.__base__ is base._BaseClarifaiModel:
|
40
|
-
_t.update({cls_obj._config.clarifai_model.type: cls_name})
|
41
|
-
return _t
|
42
|
-
|
43
|
-
|
44
|
-
_TYPE_TO_CLASS = __parse_type_to_class()
|
45
|
-
|
46
|
-
|
47
|
-
def _get_static_file_path(relative_path: str):
|
48
|
-
curr_dir = os.path.dirname(__file__)
|
49
|
-
return os.path.join(curr_dir, "static_files", relative_path)
|
50
|
-
|
51
|
-
|
52
|
-
def _read_static_file(relative_path: str):
|
53
|
-
path = _get_static_file_path(relative_path)
|
54
|
-
with open(path, "r") as f:
|
55
|
-
return f.read()
|
56
|
-
|
57
|
-
|
58
|
-
def copy_folder(src_folder, dest_folder, exclude_items=None):
|
59
|
-
|
60
|
-
if exclude_items is None:
|
61
|
-
exclude_items = set()
|
62
|
-
|
63
|
-
# Ensure the destination folder exists
|
64
|
-
if not os.path.exists(dest_folder):
|
65
|
-
os.makedirs(dest_folder)
|
66
|
-
|
67
|
-
loader = tqdm(os.listdir(src_folder))
|
68
|
-
if exclude_items:
|
69
|
-
print(f"NOTE: skipping {exclude_items}")
|
70
|
-
|
71
|
-
for item in loader:
|
72
|
-
loader.set_description(f"copying {item}...")
|
73
|
-
src_item = os.path.join(src_folder, item)
|
74
|
-
dest_item = os.path.join(dest_folder, item)
|
75
|
-
|
76
|
-
# Skip items in the exclude list
|
77
|
-
if item in exclude_items or item.endswith(BUILT_MODEL_EXT):
|
78
|
-
continue
|
79
|
-
|
80
|
-
# Copy files directly
|
81
|
-
if os.path.isfile(src_item):
|
82
|
-
shutil.copy2(src_item, dest_item)
|
83
|
-
|
84
|
-
# Copy directories using copytree
|
85
|
-
elif os.path.isdir(src_item):
|
86
|
-
shutil.copytree(src_item, dest_item, symlinks=False, ignore=None, dirs_exist_ok=True)
|
87
|
-
|
88
|
-
|
89
|
-
def zip_dir(input: Union[Path, str], zip_filename: Union[Path, str]):
|
90
|
-
"""
|
91
|
-
Zip folder without compressing
|
92
|
-
"""
|
93
|
-
# Convert to Path object
|
94
|
-
dir = Path(input)
|
95
|
-
|
96
|
-
with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_STORED) as zip_file:
|
97
|
-
for entry in dir.rglob("*"):
|
98
|
-
zip_file.write(entry, entry.relative_to(dir))
|
99
|
-
|
100
|
-
|
101
|
-
class RepositoryBuilder:
|
102
|
-
|
103
|
-
@staticmethod
|
104
|
-
def init_repository(model_type: str, working_dir: str, backend=Literal['triton'], **kwargs):
|
105
|
-
assert model_type in MODEL_TYPES
|
106
|
-
model_type = model_type
|
107
|
-
default_model_type_config: ModelConfigClass = get_model_config(model_type)
|
108
|
-
|
109
|
-
os.makedirs(working_dir, exist_ok=True)
|
110
|
-
|
111
|
-
def __write_to(filename, data):
|
112
|
-
with open(os.path.join(working_dir, filename), "w") as f:
|
113
|
-
f.write(data)
|
114
|
-
|
115
|
-
# create inference.py
|
116
|
-
_filename = "inference.py"
|
117
|
-
inference_py = _read_static_file(_filename)
|
118
|
-
inference_py = inference_py.replace("InferenceModel()",
|
119
|
-
f"InferenceModel({_TYPE_TO_CLASS[model_type]})")
|
120
|
-
inference_py = inference_py.replace("predict_docstring",
|
121
|
-
eval(_TYPE_TO_CLASS[model_type]).predict.__doc__)
|
122
|
-
# create config
|
123
|
-
config = asdict(default_model_type_config)
|
124
|
-
if backend == "triton":
|
125
|
-
max_batch_size = kwargs.get("max_batch_size", None)
|
126
|
-
image_shape = kwargs.get("image_shape", None)
|
127
|
-
if max_batch_size:
|
128
|
-
config['serving_backend']['triton']['max_batch_size'] = max_batch_size
|
129
|
-
if image_shape:
|
130
|
-
config['serving_backend']['triton']['image_shape'] = image_shape
|
131
|
-
config = parse_config(config).dump_to_user_config()
|
132
|
-
config_data = yaml.dump(config)
|
133
|
-
sample_yaml = _read_static_file("sample_clarifai_config.yaml")
|
134
|
-
config_data = sample_yaml + "\n\n" + config_data
|
135
|
-
__write_to("clarifai_config.yaml", config_data)
|
136
|
-
#
|
137
|
-
# create inference.py after checking all configs
|
138
|
-
__write_to(_filename, inference_py)
|
139
|
-
# create test.py
|
140
|
-
__write_to("test.py", _read_static_file("test.py"))
|
141
|
-
# create requirements.txt
|
142
|
-
__write_to("requirements.txt", _read_static_file("_requirements.txt"))
|
143
|
-
|
144
|
-
@staticmethod
|
145
|
-
def build(working_dir: str, output_dir: str = None, name: str = None, backend=Literal['triton']):
|
146
|
-
if not output_dir:
|
147
|
-
output_dir = working_dir
|
148
|
-
else:
|
149
|
-
os.makedirs(output_dir, exist_ok=True)
|
150
|
-
|
151
|
-
temp_folder = os.path.join(working_dir, ".cache")
|
152
|
-
os.makedirs(temp_folder, exist_ok=True)
|
153
|
-
|
154
|
-
user_config_file = os.path.join(working_dir, "clarifai_config.yaml")
|
155
|
-
assert os.path.exists(
|
156
|
-
user_config_file
|
157
|
-
), f"FileNotFound: please make sure `clarifai_config.yaml` exists in {working_dir}"
|
158
|
-
user_config = load_user_config(user_config_file)
|
159
|
-
|
160
|
-
if backend == "triton":
|
161
|
-
triton_1_ver = os.path.join(temp_folder, "1")
|
162
|
-
os.makedirs(triton_1_ver, exist_ok=True)
|
163
|
-
# check if labels exists
|
164
|
-
for output_config in user_config.serving_backend.triton.output:
|
165
|
-
if output_config.label_filename:
|
166
|
-
user_labels = user_config.clarifai_model.labels
|
167
|
-
assert user_labels, f"Model type `{user_config.clarifai_model.type}` requires labels, "\
|
168
|
-
f"but can not found value of `clarifai_model.labels` in {user_config_file}. Please update this attribute to build the model"
|
169
|
-
with open(os.path.join(temp_folder, "labels.txt"), "w") as f:
|
170
|
-
if not isinstance(user_labels, Iterable):
|
171
|
-
user_labels = [user_labels]
|
172
|
-
f.write("\n".join([str(lb) for lb in user_labels]) + "\n")
|
173
|
-
|
174
|
-
# copy model.py
|
175
|
-
shutil.copy(_get_static_file_path("triton/model.py"), triton_1_ver)
|
176
|
-
# copy requirements.txt
|
177
|
-
shutil.copy(os.path.join(working_dir, "requirements.txt"), temp_folder)
|
178
|
-
# copy all other files
|
179
|
-
copy_folder(
|
180
|
-
working_dir, triton_1_ver, exclude_items=["requirements.txt", ".cache", "__pycache__"])
|
181
|
-
# generate config.pbtxt
|
182
|
-
_config_pbtxt_serializer = Serializer(user_config.serving_backend.triton)
|
183
|
-
_config_pbtxt_serializer.to_file(temp_folder)
|
184
|
-
|
185
|
-
else:
|
186
|
-
raise ValueError(f"backend must be ['triton'], got {backend}")
|
187
|
-
|
188
|
-
clarifai_model_name = name or user_config.clarifai_model.clarifai_model_id or "model"
|
189
|
-
clarifai_model_name += BUILT_MODEL_EXT
|
190
|
-
clarifai_model_name = os.path.join(output_dir, clarifai_model_name)
|
191
|
-
|
192
|
-
print(
|
193
|
-
"Model building in progress; the duration may vary depending on the size of checkpoints/assets..."
|
194
|
-
)
|
195
|
-
zip_dir(temp_folder, clarifai_model_name)
|
196
|
-
print(f"Finished. Your model is located at {clarifai_model_name}")
|
197
|
-
|
198
|
-
return clarifai_model_name
|
@@ -1,169 +0,0 @@
|
|
1
|
-
import os
|
2
|
-
from copy import deepcopy
|
3
|
-
from typing import Dict, Iterable, List, Union
|
4
|
-
|
5
|
-
import numpy as np
|
6
|
-
import yaml
|
7
|
-
|
8
|
-
from clarifai.models.model_serving.constants import IMAGE_TENSOR_NAME, TEXT_TENSOR_NAME
|
9
|
-
from clarifai.models.model_serving.model_config import (
|
10
|
-
ClassifierOutput, EmbeddingOutput, ImageOutput, InferParam, InferParamManager, MasksOutput,
|
11
|
-
ModelTypes, TextOutput, VisualDetector, load_user_config)
|
12
|
-
|
13
|
-
_default_texts = ["Photo of a cat", "A cat is playing around", "Hello, this is test"]
|
14
|
-
|
15
|
-
_default_images = [
|
16
|
-
np.zeros((100, 100, 3), dtype='uint8'), #black
|
17
|
-
np.ones((100, 100, 3), dtype='uint8') * 255, #white
|
18
|
-
np.random.uniform(0, 255, (100, 100, 3)).astype('uint8') #noise
|
19
|
-
]
|
20
|
-
|
21
|
-
|
22
|
-
def _is_valid_logit(x: np.array):
|
23
|
-
return np.all(0 <= x) and np.all(x <= 1)
|
24
|
-
|
25
|
-
|
26
|
-
def _is_non_negative(x: np.array):
|
27
|
-
return np.all(x >= 0)
|
28
|
-
|
29
|
-
|
30
|
-
def _is_integer(x):
|
31
|
-
return np.all(np.equal(np.mod(x, 1), 0))
|
32
|
-
|
33
|
-
|
34
|
-
class BaseTest:
|
35
|
-
init_inference_parameters = {}
|
36
|
-
|
37
|
-
def __init__(self, init_inference_parameters={}) -> None:
|
38
|
-
import sys
|
39
|
-
if 'inference' in sys.modules:
|
40
|
-
del sys.modules['inference']
|
41
|
-
import inference
|
42
|
-
from inference import InferenceModel
|
43
|
-
self.model = InferenceModel()
|
44
|
-
self._base_dir = os.path.dirname(inference.__file__)
|
45
|
-
self.cfg_path = os.path.join(self._base_dir, "clarifai_config.yaml")
|
46
|
-
self.user_config = load_user_config(self.cfg_path)
|
47
|
-
self._user_labels = None
|
48
|
-
# check if labels exists
|
49
|
-
for output_config in self.user_config.serving_backend.triton.output:
|
50
|
-
if output_config.label_filename:
|
51
|
-
self._user_labels = self.user_config.clarifai_model.labels
|
52
|
-
assert self._user_labels, f"Model type `{self.user_config.clarifai_model.type}` requires labels, "\
|
53
|
-
f"but can not found value of `clarifai_model.labels` in {self.cfg_path}. Please update this attribute to build the model"
|
54
|
-
|
55
|
-
# update init vs user_defined params
|
56
|
-
user_defined_infer_params = [
|
57
|
-
InferParam(**each) for each in self.user_config.clarifai_model.inference_parameters
|
58
|
-
]
|
59
|
-
total_infer_params = []
|
60
|
-
if init_inference_parameters:
|
61
|
-
self.init_inference_parameters = init_inference_parameters
|
62
|
-
for k, v in self.init_inference_parameters.items():
|
63
|
-
_exist = False
|
64
|
-
for user_param in user_defined_infer_params:
|
65
|
-
if user_param.path == k:
|
66
|
-
if user_param.default_value != v:
|
67
|
-
print(f"Warning: Overwrite parameter `{k}` with default value `{v}`")
|
68
|
-
user_param.default_value = v
|
69
|
-
_exist = True
|
70
|
-
total_infer_params.append(user_param)
|
71
|
-
user_defined_infer_params.remove(user_param)
|
72
|
-
break
|
73
|
-
if not _exist:
|
74
|
-
total_infer_params.append(InferParamManager.from_kwargs(**{k: v}).params[0])
|
75
|
-
|
76
|
-
self.infer_param_manager = InferParamManager(
|
77
|
-
params=total_infer_params + user_defined_infer_params)
|
78
|
-
self.user_config.clarifai_model.inference_parameters = self.infer_param_manager.get_list_params(
|
79
|
-
)
|
80
|
-
self._overwrite_cfg()
|
81
|
-
|
82
|
-
@property
|
83
|
-
def user_labels(self):
|
84
|
-
return self._user_labels
|
85
|
-
|
86
|
-
def _overwrite_cfg(self):
|
87
|
-
config = yaml.dump(self.user_config.dump_to_user_config(),)
|
88
|
-
with open(self.cfg_path, "w") as f:
|
89
|
-
f.write(config)
|
90
|
-
|
91
|
-
def predict(self, input_data: Union[List[np.ndarray], List[str], Dict[str, Union[List[
|
92
|
-
np.ndarray], List[str]]]], **inference_parameters) -> Iterable:
|
93
|
-
"""
|
94
|
-
Test Prediction method is exact `InferenceModel.predict` method with
|
95
|
-
checking inference paramters.
|
96
|
-
|
97
|
-
Args:
|
98
|
-
-----
|
99
|
-
- input_data: A list of input data item to predict on. The type depends on model input type:
|
100
|
-
* `image`: List[np.ndarray]
|
101
|
-
* `text`: List[str]
|
102
|
-
* `multimodal`:
|
103
|
-
input_data is list of dict where key is input type name e.i. `image`, `text` and value is list.
|
104
|
-
{"image": List[np.ndarray], "text": List[str]}
|
105
|
-
|
106
|
-
- **inference_parameters: keyword args of your inference parameters.
|
107
|
-
|
108
|
-
Returns:
|
109
|
-
--------
|
110
|
-
List of your inference model output type
|
111
|
-
"""
|
112
|
-
infer_params = self.infer_param_manager.validate(**inference_parameters)
|
113
|
-
outputs = self.model.predict(input_data=input_data, inference_parameters=infer_params)
|
114
|
-
outputs = self._verify_outputs(outputs)
|
115
|
-
return outputs
|
116
|
-
|
117
|
-
def _verify_outputs(self, outputs: List[Union[ClassifierOutput, VisualDetector, EmbeddingOutput,
|
118
|
-
TextOutput, ImageOutput, MasksOutput]]):
|
119
|
-
"""Test output value/dims
|
120
|
-
|
121
|
-
Args:
|
122
|
-
outputs (List[Union[ClassifierOutput, VisualDetector, EmbeddingOutput, TextOutput, ImageOutput, MasksOutput]]): Outputs of `predict` method
|
123
|
-
"""
|
124
|
-
_outputs = deepcopy(outputs)
|
125
|
-
_output = _outputs[0]
|
126
|
-
|
127
|
-
if isinstance(_output, EmbeddingOutput):
|
128
|
-
# not test
|
129
|
-
pass
|
130
|
-
elif isinstance(_output, ClassifierOutput):
|
131
|
-
for each in _outputs:
|
132
|
-
assert _is_valid_logit(each.predicted_scores), "`predicted_scores` must be in range [0, 1]"
|
133
|
-
assert len(each.predicted_scores) == len(
|
134
|
-
self.user_labels
|
135
|
-
), f"`predicted_scores` dim must be equal to labels, got {len(each.predicted_scores)} != labels {len(self.user_labels)}"
|
136
|
-
elif isinstance(_output, VisualDetector):
|
137
|
-
for each in _outputs:
|
138
|
-
assert _is_valid_logit(each.predicted_scores), "`predicted_scores` must be in range [0, 1]"
|
139
|
-
assert _is_integer(each.predicted_labels), "`predicted_labels` must be integer"
|
140
|
-
assert np.all(0 <= each.predicted_labels) and np.all(each.predicted_labels < len(
|
141
|
-
self.user_labels)), f"`predicted_labels` must be in [0, {len(self.user_labels) - 1}]"
|
142
|
-
assert _is_non_negative(each.predicted_bboxes), "`predicted_bboxes` must be >= 0"
|
143
|
-
elif isinstance(_output, MasksOutput):
|
144
|
-
for each in _outputs:
|
145
|
-
assert np.all(0 <= each.predicted_mask) and np.all(each.predicted_mask < len(
|
146
|
-
self.user_labels)), f"`predicted_mask` must be in [0, {len(self.user_labels) - 1}]"
|
147
|
-
elif isinstance(_output, TextOutput):
|
148
|
-
pass
|
149
|
-
elif isinstance(_output, ImageOutput):
|
150
|
-
for each in _outputs:
|
151
|
-
assert _is_non_negative(each.image), "`image` must be >= 0"
|
152
|
-
else:
|
153
|
-
pass
|
154
|
-
|
155
|
-
return outputs
|
156
|
-
|
157
|
-
def test_with_default_inputs(self):
|
158
|
-
model_type = self.user_config.clarifai_model.type
|
159
|
-
if model_type == ModelTypes.multimodal_embedder:
|
160
|
-
self.predict(input_data=[{IMAGE_TENSOR_NAME: each} for each in _default_images])
|
161
|
-
self.predict(input_data=[{TEXT_TENSOR_NAME: each} for each in _default_texts])
|
162
|
-
self.predict(input_data=[{
|
163
|
-
TEXT_TENSOR_NAME: text,
|
164
|
-
IMAGE_TENSOR_NAME: img
|
165
|
-
} for text, img in zip(_default_texts, _default_images)])
|
166
|
-
elif model_type.startswith("visual"):
|
167
|
-
self.predict(input_data=_default_images)
|
168
|
-
else:
|
169
|
-
self.predict(input_data=_default_texts)
|
@@ -1,26 +0,0 @@
|
|
1
|
-
# User model inference script.
|
2
|
-
|
3
|
-
import os
|
4
|
-
from pathlib import Path
|
5
|
-
from typing import Dict, Union
|
6
|
-
from clarifai.models.model_serving.model_config import * # noqa
|
7
|
-
|
8
|
-
|
9
|
-
class InferenceModel():
|
10
|
-
"""User model inference class."""
|
11
|
-
|
12
|
-
def __init__(self) -> None:
|
13
|
-
"""
|
14
|
-
Load inference time artifacts that are called frequently .e.g. models, tokenizers, etc.
|
15
|
-
in this method so they are loaded only once for faster inference.
|
16
|
-
"""
|
17
|
-
# current directory
|
18
|
-
self.base_path: Path = os.path.dirname(__file__)
|
19
|
-
|
20
|
-
def predict(self,
|
21
|
-
input_data: list,
|
22
|
-
inference_parameters: Dict[str, Union[bool, str, float, int]] = {}) -> list:
|
23
|
-
"""predict_docstring
|
24
|
-
"""
|
25
|
-
|
26
|
-
raise NotImplementedError()
|