为什么我的 fastapi 或 uvicorn 会关闭?

问题描述 投票:0回答:5

我正在尝试运行一个使用简单变压器 Roberta 模型进行分类的服务。测试时,推理脚本/函数本身按预期工作。当我将其包含在快速 API 中时,它会关闭服务器。

uvicorn==0.11.8
fastapi==0.61.1
simpletransformers==0.51.6
cmd : uvicorn --host 0.0.0.0 --port 5000 src.main:app

@app.get("/article_classify")
def classification(text:str):
    """function to classify article using a deep learning model.
    Returns:
        [type]: [description]
    """

    _,_,result = inference(text)
    return result

错误:

INFO:     Started server process [8262]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:5000 (Press CTRL+C to quit)
INFO:     127.0.0.1:36454 - "GET / HTTP/1.1" 200 OK
INFO:     127.0.0.1:36454 - "GET /favicon.ico HTTP/1.1" 404 Not Found
INFO:     127.0.0.1:36454 - "GET /docs HTTP/1.1" 200 OK
INFO:     127.0.0.1:36454 - "GET /openapi.json HTTP/1.1" 200 OK
before
100%|████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 17.85it/s]
INFO:     Shutting down
INFO:     Finished server process [8262]

推理脚本:

model_name = "checkpoint-3380-epoch-20"
model = MultiLabelClassificationModel("roberta","src/outputs/"+model_name)
def inference(input_text,model_name="checkpoint-3380-epoch-20"):
    """Function to run inverence on one sample text"""
    #model = MultiLabelClassificationModel("roberta","src/outputs/"+model_name)
    all_tags =[]
    if isinstance(input_text,str):
        print("before")
        result ,output = model.predict([input_text])
        print(result)
        tags=[]
        for idx,each in enumerate(result[0]):
            if each==1:
                tags.append(classes[idx])
        all_tags.append(tags)
    elif isinstance(input_text,list):
        result ,output = model.predict(input_text)
        tags=[]
        for res in result : 
            for idx,each in enumerate(res):
                if each==1:
                    tags.append(classes[idx])
            all_tags.append(tags)

    return result,output,all_tags

更新:尝试使用 Flask,服务正在工作,但是当在 Flask 顶部添加 uvicorn 时,它陷入了重新启动的循环中。

python fastapi multilabel-classification uvicorn simpletransformers
5个回答
4
投票

虽然已接受的解决方案有效,但我想建议一个不那么老套的解决方案,使用

uvicorn
工作人员来代替。

您可能想尝试将

--workers 4
添加到您的
CMD
中,使其显示为:

uvicorn --host 0.0.0.0 --port 5000 --workers 4 src.main:app

3
投票

我通过显式使用多处理启动进程池解决了这个问题。

from multiprocessing import set_start_method
from multiprocessing import Process, Manager
try:
    set_start_method('spawn')
except RuntimeError:
    pass
@app.get("/article_classify")
def classification(text:str):
    """function to classify article using a deep learning model.
    Returns:
        [type]: [description]
    """
    manager = Manager()

    return_result = manager.dict()
    # as the inference is failing 
    p = Process(target = inference,args=(text,return_result,))
    p.start()
    p.join()
    # print(return_result)
    result = return_result['all_tags']
    return result

1
投票

我最近遇到了类似的问题。我的情况可能有点不同,但希望提供作为参考。我使用的句子转换器需要下载大重量的文件,下载过程需要 o(10) 秒。然而,默认的独角兽有一个设置

timeout_notify=30
。通过阅读源码,似乎是导致服务器不断重启的原因,因为下载时间较长(接近30秒)。

后来,我使用不同的方式来加快下载速度,重启问题就消失了。


1
投票

根据https://github.com/ThilinaRajapakse/simpletransformers/issues/761它与多重处理有关。

我设置了 args={'use_multiprocessing': False} 并且网络服务器不再关闭。


-1
投票

将整个函数放在

try-except
块下并显示输出,以便我们可以调查真正的问题。

import logging

@app.get("/article_classify")
def classification(text:str):
    """function to classify article using a deep learning model.
    Returns:
        [type]: [description]
    """
    try:
    _,_,result = inference(text)
    except:
        logging.exception("something bad happened")  # automatically print exception info

    return result
© www.soinside.com 2019 - 2024. All rights reserved.