解读FastAPI异步化为transformers模型打造高性能接口解析

bash 复制代码
from fastapi import FastAPI
from transformers import AutoModel, AutoTokenizer
import numpy as np
from starlette.responses import JSONResponse
 
 app = FastAPI()

加载模型和分词器

bash 复制代码
model = AutoModel.from_pretrained("distilbert-base-uncased")
  tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")

异步函数用于将输入文本转换为模型需要的格式

bash 复制代码
  async def prepare_input_for_model(text: str):
       inputs = tokenizer.encode(text, return_tensors='pt')
           return inputs

异步函数用于模型预测

bash 复制代码
 async def get_prediction(inputs):
        outputs = model(inputs)
        return outputs.logits

异步接口用于处理HTTP请求并返回预测结果

bash 复制代码
   @app.post("/predict")
   async def predict(text: str):
             inputs = await prepare_input_for_model(text)
             outputs = await get_prediction(inputs)
             predictions = np.argmax(outputs.numpy(), axis=-1)
             return JSONResponse(content={"prediction": predictions[0]})

这段代码展示了如何使用FastAPI框架的异步功能来提高性能。通过异步函数prepare_input_for_model和get_prediction,我们能够处理并行任务,有效利用服务器资源。这样的设计模式对于需要处理大量并发请求的应用程序非常有用。

相关推荐
吴佳浩4 小时前
GPU 编号进阶:CUDA\_VISIBLE\_DEVICES、多进程与容器化陷阱
人工智能·pytorch·python
全栈凯哥4 小时前
18.Python中的导入类完全指南
python
sunwenjian8865 小时前
Java进阶——IO 流
java·开发语言·python
guts3505 小时前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集
森林猿5 小时前
java-modbus-读取-modbus4j
java·网络·python
2401_879693876 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
chushiyunen6 小时前
python chatTts实现tts文本转语音、音频
python
FreakStudio6 小时前
把 Flask 搬进 ESP32,高中生自研嵌入式 Web 框架 MicroFlask !
python·单片机·嵌入式·cortex-m3·异步编程·电子diy
love530love7 小时前
OpenClaw 手机直连配置全流程
人工智能·windows·python·智能手机·c#·agent·openclaw
chushiyunen7 小时前
python中的内置属性 todo
开发语言·javascript·python