clarifai 10.0.0__py3-none-any.whl → 10.1.0__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.
Files changed (74) hide show
  1. clarifai/client/base.py +8 -1
  2. clarifai/client/dataset.py +77 -21
  3. clarifai/client/input.py +6 -6
  4. clarifai/client/model.py +1 -1
  5. clarifai/client/module.py +1 -1
  6. clarifai/client/workflow.py +1 -1
  7. clarifai/datasets/upload/features.py +3 -0
  8. clarifai/datasets/upload/image.py +57 -26
  9. clarifai/datasets/upload/loaders/xview_detection.py +4 -0
  10. clarifai/datasets/upload/utils.py +23 -7
  11. clarifai/models/model_serving/README.md +113 -121
  12. clarifai/models/model_serving/__init__.py +2 -0
  13. clarifai/models/model_serving/cli/_utils.py +53 -0
  14. clarifai/models/model_serving/cli/base.py +14 -0
  15. clarifai/models/model_serving/cli/build.py +79 -0
  16. clarifai/models/model_serving/cli/clarifai_clis.py +33 -0
  17. clarifai/models/model_serving/cli/create.py +171 -0
  18. clarifai/models/model_serving/cli/example_cli.py +34 -0
  19. clarifai/models/model_serving/cli/login.py +26 -0
  20. clarifai/models/model_serving/cli/upload.py +182 -0
  21. clarifai/models/model_serving/constants.py +20 -0
  22. clarifai/models/model_serving/docs/cli.md +150 -0
  23. clarifai/models/model_serving/docs/concepts.md +229 -0
  24. clarifai/models/model_serving/docs/dependencies.md +1 -1
  25. clarifai/models/model_serving/docs/inference_parameters.md +112 -107
  26. clarifai/models/model_serving/docs/model_types.md +16 -17
  27. clarifai/models/model_serving/model_config/__init__.py +4 -2
  28. clarifai/models/model_serving/model_config/base.py +369 -0
  29. clarifai/models/model_serving/model_config/config.py +219 -224
  30. clarifai/models/model_serving/model_config/inference_parameter.py +5 -0
  31. clarifai/models/model_serving/model_config/model_types_config/multimodal-embedder.yaml +25 -24
  32. clarifai/models/model_serving/model_config/model_types_config/text-classifier.yaml +19 -18
  33. clarifai/models/model_serving/model_config/model_types_config/text-embedder.yaml +20 -18
  34. clarifai/models/model_serving/model_config/model_types_config/text-to-image.yaml +19 -18
  35. clarifai/models/model_serving/model_config/model_types_config/text-to-text.yaml +19 -18
  36. clarifai/models/model_serving/model_config/model_types_config/visual-classifier.yaml +22 -18
  37. clarifai/models/model_serving/model_config/model_types_config/visual-detector.yaml +32 -28
  38. clarifai/models/model_serving/model_config/model_types_config/visual-embedder.yaml +19 -18
  39. clarifai/models/model_serving/model_config/model_types_config/visual-segmenter.yaml +19 -18
  40. clarifai/models/model_serving/{models → model_config}/output.py +8 -0
  41. clarifai/models/model_serving/model_config/triton/__init__.py +14 -0
  42. clarifai/models/model_serving/model_config/{serializer.py → triton/serializer.py} +3 -1
  43. clarifai/models/model_serving/model_config/triton/triton_config.py +182 -0
  44. clarifai/models/model_serving/{models/model_types.py → model_config/triton/wrappers.py} +4 -4
  45. clarifai/models/model_serving/{models → repo_build}/__init__.py +2 -0
  46. clarifai/models/model_serving/repo_build/build.py +198 -0
  47. clarifai/models/model_serving/repo_build/static_files/_requirements.txt +2 -0
  48. clarifai/models/model_serving/repo_build/static_files/base_test.py +169 -0
  49. clarifai/models/model_serving/repo_build/static_files/inference.py +26 -0
  50. clarifai/models/model_serving/repo_build/static_files/sample_clarifai_config.yaml +25 -0
  51. clarifai/models/model_serving/repo_build/static_files/test.py +40 -0
  52. clarifai/models/model_serving/{models/pb_model.py → repo_build/static_files/triton/model.py} +15 -14
  53. clarifai/models/model_serving/utils.py +21 -0
  54. clarifai/rag/rag.py +45 -12
  55. clarifai/rag/utils.py +3 -2
  56. clarifai/utils/logging.py +7 -0
  57. clarifai/versions.py +1 -1
  58. {clarifai-10.0.0.dist-info → clarifai-10.1.0.dist-info}/METADATA +28 -5
  59. clarifai-10.1.0.dist-info/RECORD +114 -0
  60. clarifai-10.1.0.dist-info/entry_points.txt +2 -0
  61. clarifai/models/model_serving/cli/deploy_cli.py +0 -123
  62. clarifai/models/model_serving/cli/model_zip.py +0 -61
  63. clarifai/models/model_serving/cli/repository.py +0 -89
  64. clarifai/models/model_serving/docs/custom_config.md +0 -33
  65. clarifai/models/model_serving/docs/output.md +0 -28
  66. clarifai/models/model_serving/models/default_test.py +0 -281
  67. clarifai/models/model_serving/models/inference.py +0 -50
  68. clarifai/models/model_serving/models/test.py +0 -64
  69. clarifai/models/model_serving/pb_model_repository.py +0 -108
  70. clarifai-10.0.0.dist-info/RECORD +0 -103
  71. clarifai-10.0.0.dist-info/entry_points.txt +0 -4
  72. {clarifai-10.0.0.dist-info → clarifai-10.1.0.dist-info}/LICENSE +0 -0
  73. {clarifai-10.0.0.dist-info → clarifai-10.1.0.dist-info}/WHEEL +0 -0
  74. {clarifai-10.0.0.dist-info → clarifai-10.1.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,26 @@
1
+ import argparse
2
+
3
+ from ..constants import CLARIFAI_PAT_PATH
4
+ from ..utils import _persist_pat
5
+ from .base import BaseClarifaiCli
6
+
7
+
8
+ class LoginCli(BaseClarifaiCli):
9
+
10
+ @staticmethod
11
+ def register(parser: argparse._SubParsersAction):
12
+ upload_parser = parser.add_parser("login", help="Login to Clarifai and save PAT locally")
13
+ upload_parser.set_defaults(func=LoginCli)
14
+
15
+ def __init__(self, args: argparse.Namespace) -> None:
16
+ pass
17
+
18
+ def _parse_config(self):
19
+ # do something with self.config_path
20
+ raise NotImplementedError()
21
+
22
+ def run(self):
23
+ msg = "Get your PAT from https://clarifai.com/settings/security and pass it here: "
24
+ _pat = input(msg)
25
+ _persist_pat(_pat)
26
+ print(f"Your PAT is saved at {CLARIFAI_PAT_PATH}")
@@ -0,0 +1,182 @@
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
+ """Commandline interface for model upload utils."""
14
+ import argparse
15
+ import os
16
+ import subprocess
17
+ from typing import Union
18
+
19
+ from clarifai.client.auth.helper import ClarifaiAuthHelper
20
+ from clarifai.models.api import Models
21
+ from clarifai.models.model_serving.model_config import (MODEL_TYPES, get_model_config,
22
+ load_user_config)
23
+ from clarifai.models.model_serving.model_config.inference_parameter import InferParamManager
24
+
25
+ from ..utils import login
26
+ from .base import BaseClarifaiCli
27
+
28
+
29
+ class UploadCli(BaseClarifaiCli):
30
+
31
+ @staticmethod
32
+ def register(parser: argparse._SubParsersAction):
33
+ creator_parser = parser.add_parser("upload", help="Upload component to Clarifai platform")
34
+ sub_creator_parser = creator_parser.add_subparsers()
35
+
36
+ UploadModelSubCli.register(sub_creator_parser)
37
+
38
+ creator_parser.set_defaults(func=UploadCli)
39
+
40
+
41
+ class UploadModelSubCli(BaseClarifaiCli):
42
+
43
+ @staticmethod
44
+ def register(parser: argparse._SubParsersAction):
45
+ upload_parser = parser.add_parser("model", help="Upload Clarifai model")
46
+ upload_parser.add_argument(
47
+ "path",
48
+ type=str,
49
+ nargs='?',
50
+ help=
51
+ "Path to working dir to get clarifai_config.yaml or path to yaml. Default is current directory",
52
+ default=".")
53
+ upload_parser.add_argument(
54
+ "--url", type=str, required=True, help="Direct download url of zip file")
55
+ upload_parser.add_argument("--id", type=str, required=False, help="Model ID")
56
+ upload_parser.add_argument(
57
+ "--user-app",
58
+ type=str,
59
+ required=False,
60
+ help="User ID and App ID separated by '/', e.g., <user_id>/<app_id>")
61
+ upload_parser.add_argument(
62
+ "--no-test",
63
+ action="store_true",
64
+ help="Trigger this flag to skip testing before uploading")
65
+
66
+ upload_parser.add_argument(
67
+ "--update-version",
68
+ action="store_true",
69
+ required=False,
70
+ help="Update exist model with new version")
71
+
72
+ upload_parser.set_defaults(func=UploadModelSubCli)
73
+
74
+ def __init__(self, args: argparse.Namespace) -> None:
75
+ self.no_test = args.no_test
76
+
77
+ working_dir_or_config = args.path
78
+ # if input a config file, then not running test
79
+ if working_dir_or_config.endswith(".yaml"):
80
+ config_yaml_path = working_dir_or_config
81
+ self.test_path = None
82
+ self.no_test = True
83
+ # if it is a directory - working dir then it must contain config and test
84
+ else:
85
+ config_yaml_path = os.path.join(working_dir_or_config, "clarifai_config.yaml")
86
+ self.test_path = os.path.join(working_dir_or_config, "test.py")
87
+
88
+ assert os.path.exists(config_yaml_path), FileNotFoundError(
89
+ f"`{config_yaml_path}` does not exist")
90
+ self.config = load_user_config(cfg_path=config_yaml_path)
91
+
92
+ self.user_id, self.app_id = "", ""
93
+ user_app = args.user_app
94
+ self.url: str = args.url
95
+ self.update_version = args.update_version
96
+ assert self.url.startswith("http") or self.url.startswith(
97
+ "s3"), f"Invalid url supported http or s3 url. Got {self.url}"
98
+
99
+ clarifai_cfg = self.config.clarifai_model
100
+ self.url: str = args.url
101
+ self.id = args.id or clarifai_cfg.clarifai_model_id
102
+ self.type = clarifai_cfg.type
103
+ self.desc = clarifai_cfg.description
104
+ self.infer_param = clarifai_cfg.inference_parameters
105
+ user_app = user_app or clarifai_cfg.clarifai_user_app_id
106
+
107
+ if user_app:
108
+ user_app = user_app.split('/')
109
+ assert len(
110
+ user_app
111
+ ) == 2, f"id must be combination of user_id and app_id separated by `/`, e.g. <user_id>/<app_id>. Got {args.id}"
112
+ self.user_id, self.app_id = user_app
113
+
114
+ if self.user_id:
115
+ os.environ["CLARIFAI_USER_ID"] = self.user_id
116
+ if self.app_id:
117
+ os.environ["CLARIFAI_APP_ID"] = self.app_id
118
+
119
+ _user_id = os.environ.get("CLARIFAI_USER_ID", None)
120
+ _app_id = os.environ.get("CLARIFAI_APP_ID", None)
121
+ assert _user_id or _app_id, f"Missing user-id or app-id, got user-id {_user_id} and app-id {_app_id}"
122
+ login()
123
+
124
+ def run(self):
125
+
126
+ # Run test before uploading
127
+ if not self.no_test:
128
+ assert os.path.exists(self.test_path), FileNotFoundError(f"Not found {self.test_path}")
129
+ result = subprocess.run(f"pytest -s --log-level=INFO {self.test_path}")
130
+ assert result.returncode == 0, "Test has failed. Please make sure no error exists in your code."
131
+
132
+ deploy(
133
+ model_url=self.url,
134
+ model_id=self.id,
135
+ desc=self.desc,
136
+ model_type=self.type,
137
+ update_version=self.update_version,
138
+ inference_parameters=self.infer_param)
139
+
140
+
141
+ def deploy(model_url,
142
+ model_id: str = None,
143
+ model_type: str = None,
144
+ desc: str = "",
145
+ update_version: bool = False,
146
+ inference_parameters: Union[dict, str] = None):
147
+ # init Auth from env vars
148
+ auth = ClarifaiAuthHelper.from_env()
149
+ # init api
150
+ model_api = Models(auth)
151
+ # key map
152
+ assert model_type in MODEL_TYPES, f"model_type should be one of {MODEL_TYPES}"
153
+ clarifai_key_map = get_model_config(model_type=model_type).clarifai_model.field_maps
154
+ # inference parameters
155
+ if isinstance(inference_parameters, str) and os.path.isfile(inference_parameters):
156
+ inference_parameters = InferParamManager(json_path=inference_parameters).get_list_params()
157
+ # if updating new version of existing model
158
+ if update_version:
159
+ resp = model_api.post_model_version(
160
+ model_id=model_id,
161
+ model_zip_url=model_url,
162
+ input=clarifai_key_map.input_fields_map,
163
+ outputs=clarifai_key_map.output_fields_map,
164
+ param_specs=inference_parameters)
165
+ # creating new model
166
+ else:
167
+ # post model
168
+ resp = model_api.upload_model(
169
+ model_id=model_id,
170
+ model_zip_url=model_url,
171
+ model_type=model_type,
172
+ input=clarifai_key_map.input_fields_map,
173
+ outputs=clarifai_key_map.output_fields_map,
174
+ description=desc,
175
+ param_specs=inference_parameters)
176
+ # response
177
+ if resp["status"]["code"] != "SUCCESS":
178
+ raise Exception("Post models failed, details: {}, {}".format(resp["status"]["description"],
179
+ resp["status"]["details"]))
180
+ else:
181
+ print("Success!")
182
+ print(f'Model version: {resp["model"]["model_version"]["id"]}')
@@ -1 +1,21 @@
1
+ import os
2
+
1
3
  MAX_HW_DIM = 1024
4
+ IMAGE_TENSOR_NAME = "image"
5
+ TEXT_TENSOR_NAME = "text"
6
+
7
+ BUILT_MODEL_EXT = ".clarifai"
8
+
9
+ default_home = os.path.join(os.path.expanduser("~"), ".cache")
10
+ CLARIFAI_HOME = os.path.expanduser(
11
+ os.getenv(
12
+ "CLARIFAI_HOME",
13
+ os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "clarifai"),
14
+ ))
15
+ os.makedirs(CLARIFAI_HOME, exist_ok=True)
16
+ CLARIFAI_PAT_PATH = os.path.join(CLARIFAI_HOME, "pat")
17
+
18
+ CLARIFAI_EXAMPLES_REPO = "https://github.com/Clarifai/examples.git"
19
+ repo_name = CLARIFAI_EXAMPLES_REPO.split("/")[-1].replace(".git", "")
20
+ CLARIFAI_EXAMPLES_REPO_PATH = os.path.join(CLARIFAI_HOME, repo_name)
21
+ MODEL_UPLOAD_EXAMPLE_FOLDER = "model_upload"
@@ -0,0 +1,150 @@
1
+ # CLI helpers
2
+
3
+ Supported cli:
4
+
5
+ ```bash
6
+ $ clarifai -h
7
+ upload Upload component to Clarifai platform
8
+ create Create component of Clarifai platform
9
+ login Login to Clarifai and save PAT locally
10
+ example Download/List examples of model upload
11
+ build Build clarifai model for uploading
12
+ ```
13
+
14
+ 1. Login
15
+
16
+ ```bash
17
+ $ clarifai login
18
+ Get your PAT from https://clarifai.com/settings/security and pass it here: <your pat>
19
+ ```
20
+
21
+ 2. Create model repository
22
+
23
+ Initialize template for specify model type in provided directory
24
+
25
+ * `From scratch`:
26
+
27
+ ```bash
28
+ $ clarifai create model --type <model-type> --working-dir <your_working_dir>
29
+ ```
30
+
31
+ * `From example`:
32
+
33
+ ```bash
34
+ $ clarifai create model --from-example --working-dir <your_working_dir>
35
+ ? Select an example:
36
+ ❯ multimodal_embedder/clip
37
+ text_classifier/xlm-roberta
38
+ text_embedder/instructor-xl
39
+ ...
40
+ ```
41
+
42
+ Then will see below output
43
+
44
+ ```bash
45
+ ---------------------------------------------------------------------------
46
+ * Created repository at: ./<your_working_dir>
47
+ <your_working_dir>
48
+ ├── clarifai_config.yaml
49
+ ├── inference.py
50
+ ├── requirements.txt
51
+ └── test.py
52
+
53
+ 0 directories, 4 files
54
+
55
+ * Please make sure your code is tested using `test.py` before uploading
56
+ ---------------------------------------------------------------------------
57
+ ```
58
+
59
+ > NOTE: if working-dir exists, need to set --overwrite flag otherwise an error arises
60
+
61
+ Full arguments
62
+
63
+ ```bash
64
+ $ clarifai create model -h
65
+ --working-dir Path to your working dir. Create new dir if it does not exist
66
+ --from-example Create repository from example
67
+ --example-id Example id, run `clarifai example list` to list of examples
68
+ --type Clarifai supported model types.
69
+ --image-shape list of H W dims for models with an image input type. H and W each have a max value of 1024
70
+ --max-bs Max batch size
71
+ --overwrite Overwrite working-dir if exists
72
+ ```
73
+
74
+ 3. See available examples
75
+
76
+ ```bash
77
+ $ clarifai example list
78
+ Found 11 examples
79
+ * multimodal_embedder/clip
80
+ * text_classifier/xlm-roberta
81
+ * text_embedder/instructor-xl
82
+ ....
83
+ ```
84
+
85
+ 4. Build
86
+
87
+ This step will run `test.py` in provided working dir as default before building
88
+
89
+ ```
90
+ $ clarifai build model <your_working_dir> --name model-name
91
+ $ tree <your_working_dir> -a
92
+ <your_working_dir>
93
+ ├── .cache # (*)
94
+ │ ├── 1
95
+ │ │ ├── clarifai_config.yaml
96
+ │ │ ├── inference.py
97
+ │ │ ├── model.py
98
+ │ │ ├── test.py
99
+ │ │ └── ...
100
+ │ ├── config.pbtxt
101
+ │ └── requirements.txt
102
+ ├── clarifai_config.yaml
103
+ ├── inference.py
104
+ ├── model-name.clarifai # (**)
105
+ ├── requirements.txt
106
+ ├── test.py
107
+ └── ...
108
+ ```
109
+
110
+ **NOTE:**
111
+
112
+ (*): Build cache, user can simply ignore it.
113
+
114
+ (**): zipped of .cache
115
+
116
+ Full arguments
117
+
118
+ ```bash
119
+ $ clarifai build model -h
120
+ positional arguments:
121
+ path Path to working directory, default is current directory
122
+ optional arguments:
123
+ --out-path Output path of built model
124
+ --name Name of built file, default is `clarifai_model_id` in config if set or`model`
125
+ --no-test Trigger this flag to skip testing before uploading
126
+ ```
127
+
128
+ 5. Upload
129
+
130
+ This step will run `test.py` in provided working dir as default before building
131
+
132
+ ```bash
133
+ $ clarifai upload model <your_working_dir> --url <your url>
134
+ ```
135
+
136
+ Full arguments
137
+
138
+ ```bash
139
+ $ clarifai upload model -h
140
+ positional arguments:
141
+ path Path to working dir to get clarifai_config.yaml or path to yaml. Default is current directory
142
+
143
+ optional arguments:
144
+ --url Direct download url of zip file
145
+ --id Model ID
146
+ --user-app User ID and App ID separated by '/', e.g., <user_id>/<app_id>
147
+ --update-version Update exist model with new version
148
+ --no-test Trigger this flag to skip testing before uploading
149
+
150
+ ```
@@ -0,0 +1,229 @@
1
+ # Overview
2
+
3
+ Model Serving is a straightforward interface that links user model implementations in Python with a high-performance serving framework (tritonserver). It seamlessly integrates with the Clarifai Platform, allowing users to deploy their models without any prerequisites in the serving framework.
4
+
5
+ ```plaintext
6
+
7
+ |Model code in Python| ---> |Model Serving + Clarifai Platform| ---> |Served model|
8
+
9
+ ```
10
+
11
+ # Understanding the concepts
12
+
13
+ While functioning as an interface, it comes with certain constraints that must be adhered to throughout the process.
14
+
15
+ ## Model repository
16
+
17
+ First of all, the model repository structure obtained by running
18
+
19
+ ```bash
20
+ clarifai create model --type ... --working-dir ...
21
+ ```
22
+
23
+ In your working dir:
24
+
25
+ ```bash
26
+ ├── inference.py
27
+ ├── clarifai_config.yaml
28
+ ├── test.py
29
+ └── requirements.txt
30
+ ```
31
+ Where:
32
+
33
+ * [inference.py](): The crucial file where users need to implement their Python code.
34
+ * [clarifai_config.yaml](): Contains all necessary configurations for model `test`, `build` and `upload`
35
+ * [test.py](): Predefined test cases to evaluate `inference.py`.
36
+ * [requirements.text](): Equivalent to a normal Python project's requirements.txt.
37
+
38
+ ## inference.py
39
+ Includes the ModelInference class, inherited from one of the Clarifai Models, providing utility wrapper functions and docstring to ensure that customized models work seamlessly within the platform server. The specific Clairfai Model is determined by the --type argument provided by users in the clarifai create model command.
40
+
41
+ Sample for `text-to-text` model
42
+
43
+ ```python
44
+ class InferenceModel(TextToText):
45
+ """User model inference class."""
46
+
47
+ def __init__(self) -> None:
48
+ """
49
+ Load inference time artifacts that are called frequently .e.g. models, tokenizers, etc.
50
+ in this method so they are loaded only once for faster inference.
51
+ """
52
+ # current directory
53
+ self.base_path: Path = os.path.dirname(__file__)
54
+
55
+ def predict(self, input_data: list,
56
+ inference_parameters: Dict[str, Union[str, float, int, bool]]) -> list:
57
+ """ Custom prediction function for `text-to-text` (also called as `text generation`) model.
58
+
59
+ Args:
60
+ input_data (List[str]): List of text
61
+ inference_parameters (Dict[str, Union[str, float, int, bool]]): your inference parameters
62
+
63
+ Returns:
64
+ list of TextOutput
65
+
66
+ """
67
+
68
+ raise NotImplementedError()
69
+
70
+ ```
71
+
72
+ Users are required to implement two functions:
73
+
74
+ * `__init__`: a method to load the model, called once.
75
+ * `predict`: a function designed to generate predictions based on the provided inputs and inference parameters. This method includes a docstring inherited from its parent, providing information on input, parameters, and output types. Refer to the docstring to confirm that the outputs of this method adhere to the correct [Clarifai Output Type](../model_config/output.py), as errors may occur otherwise.
76
+
77
+ When making predictions through the Clarifai API, user inputs are transmitted to input_data as a List of strings for text input or a List of NumPy arrays for RGB image input, where each array has a shape of [W, H, 3]. Additionally, all inference parameters are conveyed through the inference_parameters argument of the predict method.
78
+ ```plaintext
79
+
80
+ list of user inputs e.g. inference parameters e.g.
81
+ `text-to-text` will be {'top_k': 5, 'temperature': 0.7, 'do_sample': False, ...}
82
+ ['text', 'test text',] |
83
+ | |
84
+ | |
85
+ | |
86
+ v v
87
+ def predict(self, input_data:list, inference_parameters: Dict[str, str | float | int | bool]) -> list:
88
+ ...
89
+ # Predict with input data
90
+ outputs = self.model(input_data, **inference_parameters)
91
+ # Convert to Clarifai Output Type
92
+ return [TextOutput(each) for each in outputs]
93
+ |
94
+ |
95
+ |
96
+ v
97
+ Outputs are handled by the module -> platform backend to delivery back to user
98
+ ```
99
+
100
+ For testing the implementation, it's recommended to execute pytest test.py or directly call the predict method of a ModelInference instance.
101
+
102
+ ## clarifai_config.yaml
103
+
104
+ `yaml` file for essential configs
105
+
106
+ ```yaml
107
+ clarifai_model:
108
+ clarifai_model_id:
109
+ clarifai_user_app_id:
110
+ description:
111
+ inference_parameters: (*)
112
+ labels: (*)
113
+ type: (**)
114
+ serving_backend:
115
+ triton: (***)
116
+ max_batch_size:
117
+ image_shape:
118
+ ```
119
+
120
+ Explanation:
121
+
122
+ `clarifai_model`: configs for building/testing/uploading process
123
+
124
+ * `clarifai_model_id` (str, optional): Model ID on the platform.
125
+ * `clarifai_user_app_id` (str, optional): User ID and App ID on the platform seperated by `/` for example `user_1/app_1`.
126
+ * `description` (str, optional): Model description.
127
+ > These 3 attributes are used to upload model. If not provided, they can be passed in *upload* command.
128
+
129
+ * (*) `inference_parameters` (List[Dict], optional): inference parameters for your model prediction method. This attribute is used to *test* and *upload* if provided. Two ways to insert it:
130
+
131
+ * Manual: Follow this [doc](./inference_parameters.md)
132
+ * Semi Manual: in *test.py*, init BaseTest with dict of your desired parameters. Learn more about [test.py]()
133
+
134
+ * (*) `labels` (list): insert manually list of concept names ***required by*** these model types **visual-classifier**, **visual-detector**, **visual-segmenter** and **text-classifier**.
135
+
136
+ * (**) `type` (str): type of your model, generated when init working dir. ***MUST NOT MODIFY IT***
137
+
138
+ `serving_backend`: custom config for serving
139
+
140
+ * `triton`: (optional)
141
+
142
+ * `max_batch_size` (int): Maximum number of inputs will go to `predict`. The default value is 1. Since `predict` method receives a list of inputs, if your model supports batch inference, you can set it to a value greater than 1 to leverage high-performance computation on the GPU.
143
+
144
+ * `image_shape` (list): Applicable only for image input models. It is a list of the width and height of the input image. The default is [-1, -1], which means it accepts any size.
145
+ > These 2 attributes can be set when initialize using **clarifai create model** command.
146
+
147
+ ## test.py
148
+ The file is generated when initializing to test InfercenceModel in inference.py.
149
+
150
+ This test offers two essential features to enhance the testing and validation process:
151
+
152
+ **1. Implementation Validation**
153
+
154
+ Prior to initiating the build or upload processes, users can leverage this feature to thoroughly validate their implementation. This ensures the correctness and readiness of the model for deployment.
155
+
156
+ The test involves the validation of custom configuration in clarifai_config.yaml:
157
+
158
+ * Confirming that labels are provided for concept-output models.
159
+ * Verifying the format of inference_parameters.
160
+
161
+ Additionally, it validates the InferenceModel implementation:
162
+
163
+ * Ensuring the model is loaded correctly.
164
+ * Testing predict with dummy inputs.
165
+
166
+ **2. Inference Parameter Management**
167
+
168
+ Users can conveniently add or update inference parameters directly in the clarifai_config.yaml file. Additionally, the system performs automatic validation during the inference, ensuring the accuracy and compatibility of these parameters with the model's requirements. The test ensures **you can only use defined inference parameters with appropriate value**
169
+
170
+ ### file structure
171
+
172
+ ```python
173
+ class CustomTest(unittest.TestCase):
174
+
175
+ def setUp(self) -> None:
176
+ your_infer_parameter = dict()
177
+ self.model = BaseTest(your_infer_parameter)
178
+
179
+ def test_default_cases(self):
180
+ self.model.test_with_default_inputs()
181
+
182
+ ```
183
+
184
+ Explanation:
185
+
186
+ * `your_infer_parameter = dict()`: define your inference parameters as dict with key is parameter name and value is default value of it. For example, define params for hf text-generation model:
187
+
188
+ ```python
189
+ your_infer_parameter = dict(top_p=0.95, temperature=1, return_text=False, prefix="test")
190
+ ```
191
+
192
+ * `self.model = BaseTest(your_infer_parameter)` Loaded implemented model and convert inference parameters to *Clarifai inference parameters` format and save it in `clarifai_config.yaml`. See more [doc](./inference_parameters.md)
193
+
194
+ * `def test_default_cases(self):` Test your model with dummy input. If these dummy input value fails your model, kindly remove or comment out this function
195
+
196
+ Define new test:
197
+
198
+ Create a function with 'test' prefix, see `pytest` document to understand how to make a test case.
199
+ Call predict by `self.model.predict([list of input data], inference_paramters)`. For instance:
200
+
201
+ * Text input:
202
+
203
+ ```python
204
+ def test_text_input(self):
205
+ text: list = ["Tell me about Clarifai", "How deploy model to Clarifai"]
206
+ outputs = self.model.predict(text, temperature=0.9) # In term of inference parameters for the above example, it will PASSED
207
+ outputs = self.model.predict(text, top_k=10) # And this one will FAILED since `top_k` param is not defined when init self.model
208
+
209
+ ```
210
+
211
+ * Image input:
212
+
213
+ ```python
214
+ def test_image(self):
215
+ image = cv2.imread("path/to/image")
216
+ image = image[:, :, ::-1] # convert to RGB
217
+ out = self.model.predict([image])
218
+ ```
219
+
220
+ * MultiModal input:
221
+
222
+ ```python
223
+ def test_image_and_text(self):
224
+ image = cv2.imread("path/to/image")
225
+ image = image[:, :, ::-1]
226
+ text = "this is text"
227
+ input = dict(text=text, image=image)
228
+ out = self.model.predict([input])
229
+ ```
@@ -5,7 +5,7 @@ An execution environment is created for each model to be deployed on Clarifai an
5
5
 
6
6
  ## Supported python and torch versions
7
7
 
8
- Currently, models must use python 3.8 (any 3.8.x). Supported torch versions are 1.13.1 and 2.0.1.
8
+ Currently, models must use python 3.8 (any 3.8.x). Supported torch versions are 1.13.1, 2.0.1 and 2.1.1.
9
9
  If your model depends on torch, torch must be listed in your requirements.txt file (even if it is
10
10
  already a dependency of another package). An appropriate supported torch version will be selected
11
11
  based on your requirements.txt.