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

相关推荐
贝壳6904 分钟前
9.13.12 那三个新功能,我一个一个跑了一遍:两个真香,一个有前提
python
2601_967980115 分钟前
Python 与云计算:AWS、GCP、Azure 实践
python·云计算·azure·aws·gcp
屿华AI26 分钟前
AUTOSAR 实战-诊断工具 | 基于 Python 与 USB-CANFD 的 UDS 诊断测试工具设计与实现
开发语言·python·测试工具
贝壳69030 分钟前
三家 AI 把我的实测数据判成造假,我在同一台机器上重跑了五组
python
用户019027581611 小时前
Telegram Bot 股票到价提醒:AlphaFeed 轮询 + sendMessage
python
黑客笔记2 小时前
Python 进程池和线程池:用等待任务理解并发
开发语言·python
卷无止境2 小时前
Python 开发中的资源管理:统一生命周期,保留资源差异
后端·python
新*2 小时前
520 万数据迁移实战:Elasticsearch 索引重建与"改名"的完整踩坑记录
python·mysql·elasticsearch·数据迁移
吴名氏.3 小时前
Java转AI Agent教程(第十五周)政策时效:过期政策不该被召回,也不能被删掉
java·人工智能·python·ai·ai agent
黑客笔记13 小时前
python小工具win7翻车事故现场
python