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

相关推荐
yuanmenghao2 分钟前
Linux 性能实战 | 第 17 篇:strace 系统调用分析与性能调优 [特殊字符]
linux·python·性能优化
bst@微胖子7 分钟前
PyTorch深度学习框架项目合集一
人工智能·pytorch·python
Boxsc_midnight20 分钟前
【vLLM服务器并发能力测试程序】写一个python小程序来进行并发测试
服务器·python·vllm
深蓝电商API25 分钟前
爬虫日志分析:快速定位被封原因
爬虫·python
weixin1997010801638 分钟前
海外淘宝商品详情页前端性能优化实战
大数据·前端·python
深蓝海拓1 小时前
PySide6的QTimeLine详解
笔记·python·qt·学习·pyqt
纯.Pure_Jin(g)1 小时前
【Python练习四】Python 算法与进阶特性实战:数组、序列化与位运算专项练习(3道经典练习带你巩固基础——看完包会)
开发语言·vscode·python
龙山云仓1 小时前
No152:AI中国故事-对话祖冲之——圆周率与AI精度:数学直觉与极限探索
大数据·开发语言·人工智能·python·机器学习
琅琊榜首20201 小时前
AI+Python实操指南:用编程赋能高质量网络小说创作
开发语言·人工智能·python
Faker66363aaa1 小时前
基于YOLO13-C3k2-Strip的神经退行性疾病MRI影像自动识别
python