当前位置: 首页 > news >正文

解读FastAPI异步化为transformers模型打造高性能接口解析

from fastapi import FastAPI
from transformers import AutoModel, AutoTokenizer
import numpy as np
from starlette.responses import JSONResponseapp = FastAPI()

加载模型和分词器

model = AutoModel.from_pretrained("distilbert-base-uncased")tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")

异步函数用于将输入文本转换为模型需要的格式

  async def prepare_input_for_model(text: str):inputs = tokenizer.encode(text, return_tensors='pt')return inputs

异步函数用于模型预测

 async def get_prediction(inputs):outputs = model(inputs)return outputs.logits

异步接口用于处理HTTP请求并返回预测结果

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


http://www.mrgr.cn/news/10052.html

相关文章:

  • Java---面向对象
  • 进程相关命令和函数
  • Linux云计算 |【第二阶段】SECURITY-DAY3
  • 伦敦金规则:止损让你有路可退
  • 临床试验中缺失数据的问题讨论
  • 【chips】个人笔记系列-SystemVerilog
  • 日撸Java三百行(day34:图的深度优先遍历)
  • Flask restful 前后端分离和 restful 定义
  • 趋动科技 OrionX on VMware 打造 AI 就绪平台
  • stm32之I2C通信协议
  • Swift中的蓝牙之舞:Core Bluetooth的精妙应用
  • JavaScript 中的 7 个新 Set 方法:`union()`、`intersection()`,以及其他 5 个
  • 聊聊场景及场景测试
  • 【STM32仿真】基于STM32单片机设计的秒表时钟计时器仿真系统——程序源码proteus仿真图设计文档演示视频等(文末工程资料下载)
  • ant-design 自定义选择框
  • APACHE NIFI学习之—编码解码功能
  • 2025届八股文:计算机网络高频重点面试题
  • 在CMD运行pip指令安装python的库时
  • 电商平台 API 接入的方式
  • CSRF简单介绍