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

相关推荐
满怀冰雪8 分钟前
17-正则化方法:Dropout、权重衰减与过拟合控制
人工智能·python·深度学习·机器学习·paddlepaddle
2603_9651481110 分钟前
抖音/快手直播选品:用API快速匹配爆款与低价货源
开发语言·python·自动化·api
用户70887690393817 分钟前
RAG检索优化实战:从67%到92%,我做了这4步
python
GEOshijie12319 分钟前
智能家居品牌做GEO推荐哪家供应商?品类词抢占案例复盘
人工智能·python·智能家居
天天爱吃肉821834 分钟前
行业笔记|高压连接器瞬态接触退化通用检测方法论
人工智能·笔记·python·功能测试·学习·汽车
卷无止境41 分钟前
用FastAPI和PyCasbin搭一套能扛住数据中台复杂权限需求的鉴权中枢
后端·python
卷无止境44 分钟前
Python Web开发权限控制方案全景:从RBAC到策略引擎
后端·python
禁默1 小时前
信创实战:Python + SQLAlchemy 接入金仓数据库(从驱动安装到完整 CRUD)
开发语言·数据库·python
淼澄研学1 小时前
NVIDIA NeMo Guardrails 2.0实战:大模型安全护栏集成指南
人工智能·python·安全
测试老哥1 小时前
软件测试:单元测试详解
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例