解读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,我们能够处理并行任务,有效利用服务器资源。这样的设计模式对于需要处理大量并发请求的应用程序非常有用。

相关推荐
诸葛老刘1 分钟前
国密python调java服务
java·python·国密·sm2
WL_Aurora3 分钟前
Python 算法基础篇之排序算法(二):希尔、快速、归并
python·算法·排序算法
RSCompany13 分钟前
Frida 17 以后 Python API 跑旧版 JS 报 Java is not defined ?一行 import 直接恢复 Frida 16 体验
开发语言·python·逆向·hook·frida·android逆向·frida17
张道宁16 分钟前
从零开始训练YOLO手机检测模型:完整实战教程
python·yolo
快乐的哈士奇16 分钟前
对话框打字机效果:Vur + Java/Python 实现
java·开发语言·python
malog_23 分钟前
PyTorch图像数据加载实战指南
图像处理·人工智能·pytorch·python
博.闻广见23 分钟前
AI_Python基础-4.标准库与IO
开发语言·python
程序猿编码23 分钟前
大模型的“文字障眼法“:FlipAttack 文本反转越狱技术全解析
linux·python·ai·大模型
晚烛29 分钟前
CANN 数据流与内存优化:L1/L2 缓存机制与计算重叠深度解析
人工智能·python·缓存
xiao5kou4chang6kai429 分钟前
如何用Python处理气象海洋数据?台风数据爬取、SST的EOF分析、WRF剖面图绘制
python·气象·台风·wrf·海洋