diff --git a/docs/examples/huggingface/.gitignore b/docs/examples/huggingface/.gitignore new file mode 100644 index 000000000..e6ee07331 --- /dev/null +++ b/docs/examples/huggingface/.gitignore @@ -0,0 +1 @@ +mlruns diff --git a/docs/examples/huggingface/README.ipynb b/docs/examples/huggingface/README.ipynb new file mode 100644 index 000000000..383d90a78 --- /dev/null +++ b/docs/examples/huggingface/README.ipynb @@ -0,0 +1,261 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "8c519626", + "metadata": {}, + "source": [ + "# Serving HuggingFace Transformer Models\n", + "\n", + "Out of the box, MLServer supports the deployment and serving of HuggingFace Transformer models with the following features:\n", + "\n", + "- Loading of Transformer Model artifacts from Hub.\n", + "- Supports Optimized models using Optimum library\n", + "\n", + "In this example, we will showcase some of this features using an example model." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "655ea442", + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.core.magic import register_line_cell_magic\n", + "\n", + "@register_line_cell_magic\n", + "def writetemplate(line, cell):\n", + " with open(line, 'w') as f:\n", + " f.write(cell.format(**globals()))" + ] + }, + { + "cell_type": "markdown", + "id": "f1fed35e", + "metadata": {}, + "source": [ + "## Serving\n", + "\n", + "Now that we have trained and serialised our model, we are ready to start serving it.\n", + "For that, the initial step will be to set up a `model-settings.json` that instructs MLServer to load our artifact using the HuggingFace Inference Runtime." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "6df62443", + "metadata": {}, + "outputs": [], + "source": [ + "%%writetemplate ./model-settings.json\n", + "{{\n", + " \"name\": \"gpt2-model\",\n", + " \"implementation\": \"mlserver_huggingface.HuggingFaceRuntime\",\n", + " \"parallel_workers\": 0,\n", + " \"parameters\": {{\n", + " \"extra\": {{\n", + " \"task\": \"text-generation\",\n", + " \"pretrained_model\": \"distilgpt2\"\n", + " }}\n", + " }}\n", + "}}" + ] + }, + { + "cell_type": "markdown", + "id": "c6a6e8b2", + "metadata": {}, + "source": [ + "Now that we have our config in-place, we can start the server by running `mlserver start .`. This needs to either be ran from the same directory where our config files are or pointing to the folder where they are.\n", + "\n", + "```shell\n", + "mlserver start .\n", + "```\n", + "\n", + "Since this command will start the server and block the terminal, waiting for requests, this will need to be ran in the background on a separate terminal." + ] + }, + { + "cell_type": "markdown", + "id": "b664c591", + "metadata": {}, + "source": [ + "### Send test inference request\n" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "759ad7df", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'model_name': 'gpt2-model',\n", + " 'model_version': None,\n", + " 'id': 'f65f1b35-840e-4872-83b8-270271501b6c',\n", + " 'parameters': None,\n", + " 'outputs': [{'name': 'huggingface',\n", + " 'shape': [1],\n", + " 'datatype': 'BYTES',\n", + " 'parameters': None,\n", + " 'data': ['[[{\"generated_text\": \"this is a test of this. Once it is finished, it will generate a clean and easy clean install page and the build file will be loaded in the terminal. I need to install the build files for this project.\\\\n\\\\nNow to have my\"}]]']}]}" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import requests\n", + "\n", + "inference_request = {\n", + " \"inputs\": [\n", + " {\n", + " \"name\": \"huggingface\",\n", + " \"shape\": [1],\n", + " \"datatype\": \"BYTES\",\n", + " \"data\": [\"this is a test\"],\n", + " }\n", + " ]\n", + "}\n", + "\n", + "endpoint = \"http://localhost:8080/v2/models/gpt2-model/infer\"\n", + "response = requests.post(endpoint, json=inference_request)\n", + "\n", + "response.json()" + ] + }, + { + "cell_type": "markdown", + "id": "0edbcf72", + "metadata": {}, + "source": [ + "### Using Optimum Optimized Models\n", + "\n", + "We can also leverage the Optimum library that allows us to access quantized and optimized models. \n", + "\n", + "We can download pretrained optimized models from the hub if available by enabling the `optimum_model` flag:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "6d185281", + "metadata": {}, + "outputs": [], + "source": [ + "%%writetemplate ./model-settings.json\n", + "{{\n", + " \"name\": \"gpt2-model\",\n", + " \"implementation\": \"mlserver_huggingface.HuggingFaceRuntime\",\n", + " \"parallel_workers\": 0,\n", + " \"parameters\": {{\n", + " \"extra\": {{\n", + " \"task\": \"text-generation\",\n", + " \"pretrained_model\": \"distilgpt2\",\n", + " \"optimum_model\": true\n", + " }}\n", + " }}\n", + "}}" + ] + }, + { + "cell_type": "markdown", + "id": "90925ef0", + "metadata": {}, + "source": [ + "Once again, you are able to run the model using the MLServer CLI. As before this needs to either be ran from the same directory where our config files are or pointing to the folder where they are.\n", + "\n", + "```shell\n", + "mlserver start .\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "6945db96", + "metadata": {}, + "source": [ + "### Send Test Request to Optimum Optimized Model" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "39d8b438", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'model_name': 'gpt2-model',\n", + " 'model_version': None,\n", + " 'id': 'fdce1497-6b14-4fc6-a414-d437ca7783c6',\n", + " 'parameters': None,\n", + " 'outputs': [{'name': 'huggingface',\n", + " 'shape': [1],\n", + " 'datatype': 'BYTES',\n", + " 'parameters': None,\n", + " 'data': ['[[{\"generated_text\": \"this is a test case where I get a message telling me not to let the system know.\\\\nThis post was created using the \\\\\"Help Coding Standard\\\\\" tool. You can find information about the standard version of the Coding Standard here.\"}]]']}]}" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import requests\n", + "\n", + "inference_request = {\n", + " \"inputs\": [\n", + " {\n", + " \"name\": \"huggingface\",\n", + " \"shape\": [1],\n", + " \"datatype\": \"BYTES\",\n", + " \"data\": [\"this is a test\"],\n", + " }\n", + " ]\n", + "}\n", + "\n", + "endpoint = \"http://localhost:8080/v2/models/gpt2-model/infer\"\n", + "response = requests.post(endpoint, json=inference_request)\n", + "\n", + "response.json()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d7aaf365", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.7.10" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/examples/huggingface/README.md b/docs/examples/huggingface/README.md new file mode 100644 index 000000000..f7f5e40e6 --- /dev/null +++ b/docs/examples/huggingface/README.md @@ -0,0 +1,158 @@ +# Serving HuggingFace Transformer Models + +Out of the box, MLServer supports the deployment and serving of HuggingFace Transformer models with the following features: + +- Loading of Transformer Model artifacts from Hub. +- Supports Optimized models using Optimum library + +In this example, we will showcase some of this features using an example model. + + +```python +from IPython.core.magic import register_line_cell_magic + +@register_line_cell_magic +def writetemplate(line, cell): + with open(line, 'w') as f: + f.write(cell.format(**globals())) +``` + +## Serving + +Now that we have trained and serialised our model, we are ready to start serving it. +For that, the initial step will be to set up a `model-settings.json` that instructs MLServer to load our artifact using the HuggingFace Inference Runtime. + + +```python +%%writetemplate ./model-settings.json +{{ + "name": "gpt2-model", + "implementation": "mlserver_huggingface.HuggingFaceRuntime", + "parallel_workers": 0, + "parameters": {{ + "extra": {{ + "task": "text-generation", + "pretrained_model": "distilgpt2" + }} + }} +}} +``` + +Now that we have our config in-place, we can start the server by running `mlserver start .`. This needs to either be ran from the same directory where our config files are or pointing to the folder where they are. + +```shell +mlserver start . +``` + +Since this command will start the server and block the terminal, waiting for requests, this will need to be ran in the background on a separate terminal. + +### Send test inference request + + + +```python +import requests + +inference_request = { + "inputs": [ + { + "name": "huggingface", + "shape": [1], + "datatype": "BYTES", + "data": ["this is a test"], + } + ] +} + +endpoint = "http://localhost:8080/v2/models/gpt2-model/infer" +response = requests.post(endpoint, json=inference_request) + +response.json() +``` + + + + + {'model_name': 'gpt2-model', + 'model_version': None, + 'id': 'f65f1b35-840e-4872-83b8-270271501b6c', + 'parameters': None, + 'outputs': [{'name': 'huggingface', + 'shape': [1], + 'datatype': 'BYTES', + 'parameters': None, + 'data': ['[[{"generated_text": "this is a test of this. Once it is finished, it will generate a clean and easy clean install page and the build file will be loaded in the terminal. I need to install the build files for this project.\\n\\nNow to have my"}]]']}]} + + + +### Using Optimum Optimized Models + +We can also leverage the Optimum library that allows us to access quantized and optimized models. + +We can download pretrained optimized models from the hub if available by enabling the `optimum_model` flag: + + +```python +%%writetemplate ./model-settings.json +{{ + "name": "gpt2-model", + "implementation": "mlserver_huggingface.HuggingFaceRuntime", + "parallel_workers": 0, + "parameters": {{ + "extra": {{ + "task": "text-generation", + "pretrained_model": "distilgpt2", + "optimum_model": true + }} + }} +}} +``` + +Once again, you are able to run the model using the MLServer CLI. As before this needs to either be ran from the same directory where our config files are or pointing to the folder where they are. + +```shell +mlserver start . +``` + +### Send Test Request to Optimum Optimized Model + + +```python +import requests + +inference_request = { + "inputs": [ + { + "name": "huggingface", + "shape": [1], + "datatype": "BYTES", + "data": ["this is a test"], + } + ] +} + +endpoint = "http://localhost:8080/v2/models/gpt2-model/infer" +response = requests.post(endpoint, json=inference_request) + +response.json() +``` + + + + + {'model_name': 'gpt2-model', + 'model_version': None, + 'id': 'fdce1497-6b14-4fc6-a414-d437ca7783c6', + 'parameters': None, + 'outputs': [{'name': 'huggingface', + 'shape': [1], + 'datatype': 'BYTES', + 'parameters': None, + 'data': ['[[{"generated_text": "this is a test case where I get a message telling me not to let the system know.\\nThis post was created using the \\"Help Coding Standard\\" tool. You can find information about the standard version of the Coding Standard here."}]]']}]} + + + + +```python + +``` diff --git a/docs/examples/huggingface/model-settings.json b/docs/examples/huggingface/model-settings.json new file mode 100644 index 000000000..06a263aeb --- /dev/null +++ b/docs/examples/huggingface/model-settings.json @@ -0,0 +1,11 @@ +{ + "name": "gpt2-model", + "implementation": "mlserver_huggingface.HuggingFaceRuntime", + "parallel_workers": 0, + "parameters": { + "extra": { + "task": "text-generation", + "pretrained_model": "distilgpt2" + } + } +} diff --git a/docs/runtimes/huggingface.md b/docs/runtimes/huggingface.md new file mode 100644 index 000000000..f2fba3955 --- /dev/null +++ b/docs/runtimes/huggingface.md @@ -0,0 +1,3 @@ +```{include} ../../runtimes/huggingface/README.md +:relative-docs: ../../docs/ +``` diff --git a/docs/runtimes/index.md b/docs/runtimes/index.md index 3745110b1..cee078ce0 100644 --- a/docs/runtimes/index.md +++ b/docs/runtimes/index.md @@ -26,6 +26,7 @@ class in your `model-settings.json` file. | ------------ | ----------------------- | ------------------------------------------ | ---------------------------------------------------------- | ---------------------------------------------------------------- | | Scikit-Learn | `mlserver-sklearn` | `mlserver_sklearn.SKLearnModel` | [Scikit-Learn example](../examples/sklearn/README.md) | [MLServer SKLearn](./sklearn) | | XGBoost | `mlserver-xgboost` | `mlserver_xgboost.XGBoostModel` | [XGBoost example](../examples/xgboost/README.md) | [MLServer XGBoost](./xgboost) | +| HuggingFace | `mlserver-huggingface` | `mlserver_huggingface.HuggingFaceRuntime` | [HuggingFace example](../examples/huggingface/README.md) | [MLServer HuggingFace](./huggingface) | | Spark MLlib | `mlserver-mllib` | `mlserver_mllib.MLlibModel` | Coming Soon | [MLServer MLlib](./mllib) | | LightGBM | `mlserver-lightgbm` | `mlserver_lightgbm.LightGBMModel` | [LightGBM example](../examples/lightgbm/README.md) | [MLServer LightGBM](./lightgbm) | | Tempo | `tempo` | `tempo.mlserver.InferenceRuntime` | [Tempo example](../examples/tempo/README.md) | [`github.com/SeldonIO/tempo`](https://github.com/SeldonIO/tempo) | diff --git a/runtimes/huggingface/LICENSE b/runtimes/huggingface/LICENSE new file mode 100644 index 000000000..30effed50 --- /dev/null +++ b/runtimes/huggingface/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Seldon Technologies Ltd. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/runtimes/huggingface/README.md b/runtimes/huggingface/README.md new file mode 100644 index 000000000..24a5098ef --- /dev/null +++ b/runtimes/huggingface/README.md @@ -0,0 +1,14 @@ +# HuggingFace runtime for MLServer + +This package provides a MLServer runtime compatible with HuggingFace Transformers. + +## Usage + +You can install the runtime, alongside `mlserver`, as: + +```bash +pip install mlserver mlserver-huggingface +``` + +For further information on how to use MLServer with HuggingFace, you can check +out this [worked out example](../../docs/examples/huggingface/README.md). diff --git a/runtimes/huggingface/mlserver_huggingface/__init__.py b/runtimes/huggingface/mlserver_huggingface/__init__.py new file mode 100644 index 000000000..c307ab86c --- /dev/null +++ b/runtimes/huggingface/mlserver_huggingface/__init__.py @@ -0,0 +1,3 @@ +from .runtime import HuggingFaceRuntime + +__all__ = ["HuggingFaceRuntime"] diff --git a/runtimes/huggingface/mlserver_huggingface/common.py b/runtimes/huggingface/mlserver_huggingface/common.py new file mode 100644 index 000000000..fee52b801 --- /dev/null +++ b/runtimes/huggingface/mlserver_huggingface/common.py @@ -0,0 +1,96 @@ +import os +import json +from typing import Optional, Dict +from distutils.util import strtobool + +from pydantic import BaseSettings +from mlserver.errors import MLServerError + +from optimum.onnxruntime import ( + ORTModelForCausalLM, + ORTModelForFeatureExtraction, + ORTModelForQuestionAnswering, + ORTModelForSequenceClassification, + ORTModelForTokenClassification, +) + + +HUGGINGFACE_TASK_TAG = "task" + +ENV_PREFIX_HUGGINGFACE_SETTINGS = "MLSERVER_MODEL_HUGGINGFACE_" +HUGGINGFACE_PARAMETERS_TAG = "huggingface_parameters" +PARAMETERS_ENV_NAME = "PREDICTIVE_UNIT_PARAMETERS" + +SUPPORTED_OPTIMIZED_TASKS = { + "feature-extraction": ORTModelForFeatureExtraction, + "sentiment-analysis": ORTModelForSequenceClassification, + "ner": ORTModelForTokenClassification, + "question-answering": ORTModelForQuestionAnswering, + "text-generation": ORTModelForCausalLM, +} + + +class InvalidTranformerInitialisation(MLServerError): + def __init__(self, code: int, reason: str): + super().__init__( + f"Huggingface server failed with {code}, {reason}", + status_code=code, + ) + + +class HuggingFaceSettings(BaseSettings): + """ + Parameters that apply only to alibi huggingface models + """ + + class Config: + env_prefix = ENV_PREFIX_HUGGINGFACE_SETTINGS + + task: str = "" + pretrained_model: Optional[str] = None + pretrained_tokenizer: Optional[str] = None + optimum_model: bool = False + + +def parse_parameters_from_env() -> Dict: + """ + TODO + """ + parameters = json.loads(os.environ.get(PARAMETERS_ENV_NAME, "[]")) + + type_dict = { + "INT": int, + "FLOAT": float, + "DOUBLE": float, + "STRING": str, + "BOOL": bool, + } + + parsed_parameters = {} + for param in parameters: + name = param.get("name") + value = param.get("value") + type_ = param.get("type") + if type_ == "BOOL": + parsed_parameters[name] = bool(strtobool(value)) + else: + try: + parsed_parameters[name] = type_dict[type_](value) + except ValueError: + raise InvalidTranformerInitialisation( + "Bad model parameter: " + + name + + " with value " + + value + + " can't be parsed as a " + + type_, + reason="MICROSERVICE_BAD_PARAMETER", + ) + except KeyError: + raise InvalidTranformerInitialisation( + "Bad model parameter type: " + + type_ + + " valid are INT, FLOAT, DOUBLE, STRING, BOOL", + reason="MICROSERVICE_BAD_PARAMETER", + ) + return parsed_parameters diff --git a/runtimes/huggingface/mlserver_huggingface/runtime.py b/runtimes/huggingface/mlserver_huggingface/runtime.py new file mode 100644 index 000000000..e9b760023 --- /dev/null +++ b/runtimes/huggingface/mlserver_huggingface/runtime.py @@ -0,0 +1,119 @@ +import json +from mlserver.codecs import ( + StringCodec, +) +from mlserver.codecs.string import StringRequestCodec +from mlserver.model import MLModel +from mlserver.settings import ModelSettings +from mlserver.types import ( + InferenceRequest, + InferenceResponse, +) +from mlserver_huggingface.common import ( + HuggingFaceSettings, + HUGGINGFACE_PARAMETERS_TAG, + parse_parameters_from_env, + InvalidTranformerInitialisation, + SUPPORTED_OPTIMIZED_TASKS, +) +from transformers.pipelines.base import Pipeline +from transformers.pipelines import pipeline, SUPPORTED_TASKS +from transformers import AutoTokenizer + + +class HuggingFaceRuntime(MLModel): + """Runtime class for specific Huggingface models""" + + def __init__(self, settings: ModelSettings): + env_params = parse_parameters_from_env() + if not env_params and ( + not settings.parameters or not settings.parameters.extra + ): + raise InvalidTranformerInitialisation( + 500, + "Settings parameters not provided via config file nor env variables", + ) + + extra = env_params or settings.parameters.extra # type: ignore + self.hf_settings = HuggingFaceSettings(**extra) # type: ignore + + if self.hf_settings.task not in SUPPORTED_TASKS: + raise InvalidTranformerInitialisation( + 500, + ( + f"Invalid transformer task: {self.hf_settings.task}." + f" Available tasks: {SUPPORTED_TASKS.keys()}" + ), + ) + + if self.hf_settings.optimum_model: + if self.hf_settings.task not in SUPPORTED_OPTIMIZED_TASKS: + raise InvalidTranformerInitialisation( + 500, + ( + f"Invalid transformer task for " + f"OPTIMUM model: {self.hf_settings.task}. " + f"Supported Optimum tasks: {SUPPORTED_OPTIMIZED_TASKS.keys()}" + ), + ) + + super().__init__(settings) + + async def load(self) -> bool: + self._model = self._load_from_settings() + self.ready = True + return self.ready + + async def predict(self, payload: InferenceRequest) -> InferenceResponse: + """ + TODO + """ + + # TODO: convert and validate? + input_data = self.decode_request(payload, default_codec=StringRequestCodec) + + params = payload.parameters + kwarg_params = dict() + if params is not None: + params_dict = params.dict() + if HUGGINGFACE_PARAMETERS_TAG in params_dict: + kwarg_params = params_dict[HUGGINGFACE_PARAMETERS_TAG] + + prediction = self._model(input_data, **kwarg_params) + + # TODO: Convert hf output to v2 protocol, for now we use to_json + prediction_encoded = StringCodec.encode( + payload=[json.dumps(prediction)], name="huggingface" + ) + + return InferenceResponse( + model_name=self.name, + model_version=self.version, + outputs=[prediction_encoded], + ) + + def _load_from_settings(self) -> Pipeline: + """ + TODO + """ + # TODO: Support URI for locally downloaded artifacts + # uri = model_parameters.uri + model = self.hf_settings.pretrained_model + tokenizer = self.hf_settings.pretrained_tokenizer + + if model and not tokenizer: + tokenizer = model + + if self.hf_settings.optimum_model: + optimum_class = SUPPORTED_OPTIMIZED_TASKS[self.hf_settings.task] + model = optimum_class.from_pretrained( + self.hf_settings.pretrained_model, from_transformers=True + ) + tokenizer = AutoTokenizer.from_pretrained(tokenizer) + + pp = pipeline( + self.hf_settings.task, + model=model, + tokenizer=tokenizer, + ) + return pp diff --git a/runtimes/huggingface/mlserver_huggingface/version.py b/runtimes/huggingface/mlserver_huggingface/version.py new file mode 100644 index 000000000..f102a9cad --- /dev/null +++ b/runtimes/huggingface/mlserver_huggingface/version.py @@ -0,0 +1 @@ +__version__ = "0.0.1" diff --git a/runtimes/huggingface/setup.py b/runtimes/huggingface/setup.py new file mode 100644 index 000000000..a2f3cf8bd --- /dev/null +++ b/runtimes/huggingface/setup.py @@ -0,0 +1,46 @@ +import os + +from typing import Dict +from setuptools import setup, find_packages + +ROOT_PATH = os.path.dirname(__file__) +PKG_NAME = "mlserver-huggingface" +PKG_PATH = os.path.join(ROOT_PATH, PKG_NAME.replace("-", "_")) + + +def _load_version() -> str: + version = "" + version_path = os.path.join(PKG_PATH, "version.py") + with open(version_path) as fp: + version_module: Dict[str, str] = {} + exec(fp.read(), version_module) + version = version_module["__version__"] + + return version + + +def _load_description() -> str: + readme_path = os.path.join(ROOT_PATH, "README.md") + with open(readme_path) as fp: + return fp.read() + + +setup( + name=PKG_NAME, + version=_load_version(), + url="https://github.com/SeldonIO/MLServer.git", + author="Seldon Technologies Ltd.", + author_email="hello@seldon.io", + description="HuggingFace runtime for MLServer", + packages=find_packages(exclude=["tests", "tests.*"]), + install_requires=[ + "mlserver", + "optimum[onnxruntime]", + ], + dependency_links=[ + "git+https://github.com/huggingface/optimum.git#egg=optimum[onnxruntime]" + ], + long_description=_load_description(), + long_description_content_type="text/markdown", + license="Apache 2.0", +)