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

相关推荐
月光船幽幽29 分钟前
真实即粗糙,光滑是伪造
人工智能·python
一次旅行34 分钟前
Attention机制从数学到工程:拆解缩放点积+多头注意力|附可运行PyTorch实现与踩坑指南
人工智能·pytorch·python
泡干脆面就番茄37 分钟前
NumPy 科学计算完全指南:从数组创建到广播机制
python·numpy
denggun123451 小时前
信号量(DispatchSemaphore vs AsyncSemaphore)、swift协作式线程池 and python信号量
开发语言·python·swift
起光1 小时前
Python类与对象(一)
python
阿童木写作1 小时前
跨马翻译:AI批量图片翻译工具,视频字幕翻译与智能抠图一站式解决
大数据·人工智能·python·音视频
Zane19941 小时前
只改一个方向的引用,循环引用就能立刻被回收?一文讲透 weakref 弱引用
后端·python
陈年老古董1 小时前
OpenCV图像处理笔记:图像拼接、答题卡识别与目标提取
人工智能·笔记·python·opencv·计算机视觉
CTA终结者2 小时前
2026年程序员量化开发学习:用示例、拆解和练习入门
人工智能·python