Hugging Face 社区教程:GCP 部署无服务器情感分析
这是一篇由 Hugging Face 社区成员撰写的教程,展示了如何在 Google Cloud 上部署基于 Transformers 库的情感分析管道。文章记录了从本地开发到云端无服务器架构的迁移过程,重点在于利用现有预训练模型实现 Discord 评论的正负面自动检测。
报道正文
本文目录3 个章节
我在 Google Cloud 上部署 Serverless Transformers Pipeline 的历程
发布于 2021 年 3 月 18 日 在 GitHub 上更新 点赞 2
Dominici Maxence 客座作者
社区成员 Maxence Dominici 的客座博客文章
本文将分享我在 Google Cloud 上部署 transformers 情感分析 pipeline 的历程。我们将从 transformers 的快速介绍开始,然后进入技术实现部分。最后,我们将总结这一实现过程并回顾所取得的成果。
目标
我想创建一个微服务,用于自动检测用户在 Discord 上留下的客户评论是正面还是负面的。这将使我能够相应地处理评论并改善客户体验。例如,如果评论是负面的,我可以创建一个功能来联系客户,为服务质量不佳致歉,并告知他们我们的支持团队将尽快与其联系以协助解决问题。由于我预计每月请求量不会超过 2,000 次,因此我没有对响应时间和可扩展性施加任何性能约束。
Transformers 库
起初下载 .h5 文件时,我感到有些困惑。我以为它兼容 tensorflow.keras.models.load_model,但事实并非如此。经过几分钟的研究,我发现该文件是一个权重检查点(weights checkpoint),而不是一个 Keras 模型。之后,我尝试了 Hugging Face 提供的 API,并进一步阅读了其 pipeline 功能的相关文档。由于 API 和 pipeline 的效果都非常出色,我决定在自己的服务器上通过 pipeline 提供服务。
以下是来自 Transformers GitHub 页面的官方示例。
from transformers import pipeline
classifier = pipeline('sentiment-analysis') classifier('We are very happy to include pipeline into the transformers repository.') [{'label': 'POSITIVE', 'score': 0.9978193640708923}]
## 将 Transformers 部署到 Google Cloud
> 选择 GCP 是因为它是我所在个人组织使用的云环境。
### 步骤 1 - 调研
我早已知道可以使用类似 `flask` 的 API 服务来托管 `transformers` 模型。我在 Google Cloud AI 文档中搜索,发现了一个名为 [AI-Platform Prediction](https://cloud.google.com/ai-platform/prediction/docs) 的服务,用于托管 TensorFlow 模型。我还找到了 [App Engine](https://cloud.google.com/appengine) 和 [Cloud Run](https://cloud.google.com/run),但我担心 App Engine 的内存占用问题,而且我对 Docker 不太熟悉。
### 步骤 2 - 在 AI-Platform Prediction 上测试
由于该模型不是“纯 TensorFlow”保存模型(saved model),而是一个检查点(checkpoint),且我无法将其转换为“纯 TensorFlow 模型”,因此我发现 [此页面](https://cloud.google.com/ai-platform/prediction/docs/deploying-models) 上的示例无法运行。从那里我了解到可以编写一些自定义代码,从而允许我加载 `pipeline`,而不必手动处理模型,这似乎更简单。我还学到可以定义预预测和后预测操作,这在将来根据客户需求对数据进行预处理或后处理时会很有用。我遵循了 Google 的指南,但遇到了一个问题,因为该服务仍处于 beta 阶段,一切尚未稳定。这个问题在 [这里](https://github.com/huggingface/transformers/issues/9926) 有详细说明。
### 步骤 3 - 在 App Engine 上测试
我转向了 Google 的 [App Engine](https://cloud.google.com/appengine),因为这是我熟悉的服务,但由于缺少系统依赖文件,我在安装 TensorFlow 时遇到了问题。随后我尝试使用 PyTorch,它在 F4_1G 实例上运行正常,但同一实例无法处理超过 2 个请求,从性能角度来看并不理想。
### 步骤 4 - 在 Cloud Run 上测试
最后,我使用 Docker 镜像迁移到了 [Cloud Run](https://cloud.google.com/run)。我遵循了 [此指南](https://cloud.google.com/run/docs/quickstarts/build-and-deploy#python) 以了解其工作原理。在 Cloud Run 中,我可以配置更高的内存和更多的 vCPU,以便使用 PyTorch 执行预测。我放弃了 TensorFlow,因为 PyTorch 加载模型的速度似乎更快。
## Implementation of the serverless pipeline
The final solution consists of four different components:
- `main.py` handling the request to the pipeline
- `Dockerfile` used to create the image that will be deployed on Cloud Run.
- Model folder having the `pytorch_model.bin`, `config.json` and `vocab.txt`.
- Model : [DistilBERT base uncased finetuned SST-2](https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english)
- To download the model folder, follow the instructions in the button. [](https://huggingface.co/blog/assets/14_how_to_deploy_a_pipeline_to_google_clouds/Download_instructions_button.png)
- You don't need to keep the `rust_model.ot` or the `tf_model.h5` as we will use [PyTorch](https://pytorch.org/).
- `requirement.txt` for installing the dependencies
The content on the `main.py` is really simple. The idea is to receive a `GET` request containing two fields. First the review that needs to be analysed, second the API key to "protect" the service. The second parameter is optional, I used it to avoid setting up the oAuth2 of Cloud Run. After these arguments are provided, we load the pipeline which is built based on the model `distilbert-base-uncased-finetuned-sst-2-english` (provided above). In the end, the best match is returned to the client.
import os from flask import Flask, jsonify, request from transformers import pipeline
app = Flask(name)
model_path = "./model"
@app.route('/') def classify_review(): review = request.args.get('review') api_key = request.args.get('api_key') if review is None or api_key != "MyCustomerApiKey": return jsonify(code=403, message="bad request") classify = pipeline("sentiment-analysis", model=model_path, tokenizer=model_path) return classify("that was great")[0]
if name == 'main':
app.run(debug=False, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
Then the `DockerFile` which will be used to create a docker image of the service. We specify that our service runs with python:3.7, plus that we need to install our requirements. Then we use `gunicorn` to handle our process on the port `5000`.
FROM python.7
ENV PYTHONUNBUFFERED True
COPY requirements.txt / RUN pip install -r requirements.txt
COPY . /app
EXPOSE 5000 ENV PORT 5000 WORKDIR /app
CMD exec gunicorn --bind :$PORT main --workers 1 --threads 1 --timeout 0
It is important to note the arguments `--workers 1 --threads 1` which means that I want to execute my app on only one worker (= 1 process) with a single thread. This is because I don't want to have 2 instances up at once because it might increase the billing. One of the downsides is that it will take more time to process if the service receives two requests at once. After that, I put the limit to one thread due to the memory usage needed for loading the model into the pipeline. If I were using 4 threads, I might have 4 Gb / 4 = 1 Gb only to perform the full process, which is not enough and would lead to a memory error.
Finally, the `requirement.txt` file
Flask==1.1.2 torch===1.7.1 transformers~=4.2.0 gunicorn>=20.0.0
## Deployment instructions
First, you will need to meet some requirements such as having a project on Google Cloud, enabling the billing and installing the `gcloud` cli. You can find more details about it in the [Google's guide - Before you begin](https://cloud.google.com/run/docs/quickstarts/build-and-deploy#before-you-begin),
Second, we need to build the docker image and deploy it to cloud run by selecting the correct project (replace `PROJECT-ID`) and set the name of the instance such as `ai-customer-review`. You can find more information about the deployment on [Google's guide - Deploying to](https://cloud.google.com/run/docs/quickstarts/build-and-deploy#deploying_to).
gcloud builds submit --tag gcr.io/PROJECT-ID/ai-customer-review gcloud run deploy --image gcr.io/PROJECT-ID/ai-customer-review --platform managed
After a few minutes, you will also need to upgrade the memory allocated to your Cloud Run instance from 256 MB to 4 Gb. To do so, head over to the [Cloud Run Console](https://console.cloud.google.com/run) of your project.
There you should find your instance, click on it.
[](https://huggingface.co/blog/assets/14_how_to_deploy_a_pipeline_to_google_clouds/Cloud_run_instance.png)
After that you will have a blue button labelled "edit and deploy new revision" on top of the screen, click on it and you'll be prompt many configuration fields. At the bottom you should find a "Capacity" section where you can specify the memory.
> *[注:本文篇幅超长,以上为核心前篇精译,后续内容保留原文呈现]*
[](https://huggingface.co/blog/assets/14_how_to_deploy_a_pipeline_to_google_clouds/Edit_memory.png)
## Performances
[](https://huggingface.co/blog/assets/14_how_to_deploy_a_pipeline_to_google_clouds/Request_Result.png)
Handling a request takes less than five seconds from the moment you send the request including loading the model into the pipeline, and prediction. The cold start might take up an additional 10 seconds more or less.
We can improve the request handling performance by warming the model, it means loading it on start-up instead on each request (global variable for example), by doing so, we win time and memory usage.
## Costs
I simulated the cost based on the Cloud Run instance configuration with [Google pricing simulator](https://cloud.google.com/products/calculator#id=cd314cba-1d9a-4bc6-a7c0-740bbf6c8a78) [](https://huggingface.co/blog/assets/14_how_to_deploy_a_pipeline_to_google_clouds/Estimate_of_the_monthly_cost.png)
For my micro-service, I am planning to near 1,000 requests per month, optimistically. 500 may more likely for my usage. That's why I considered 2,000 requests as an upper bound when designing my microservice. Due to that low number of requests, I didn't bother so much regarding the scalability but might come back into it if my billing increases.
Nevertheless, it's important to stress that you will pay the storage for each Gigabyte of your build image. It's roughly €0.10 per Gb per month, which is fine if you don't keep all your versions on the cloud since my version is slightly above 1 Gb (Pytorch for 700 Mb & the model for 250 Mb).
## Conclusion
By using Transformers' sentiment analysis pipeline, I saved a non-negligible amount of time. Instead of training/fine-tuning a model, I could find one ready to be used in production and start the deployment in my system. I might fine-tune it in the future, but as shown on my test, the accuracy is already amazing! I would have liked a "pure TensorFlow" model, or at least a way to load it in TensorFlow without Transformers dependencies to use the AI platform. It would also be great to have a lite version.