RWKV-Runner/backend-python/routes/config.py

150 lines
4.4 KiB
Python
Raw Normal View History

2023-05-07 17:27:54 +08:00
import pathlib
from utils.log import quick_log
2023-05-07 17:27:54 +08:00
from fastapi import APIRouter, HTTPException, Request, Response, status as Status
2023-05-07 17:27:54 +08:00
from pydantic import BaseModel
from utils.rwkv import *
from utils.torch import *
import global_var
router = APIRouter()
2023-05-17 11:39:00 +08:00
class SwitchModelBody(BaseModel):
model: str
strategy: str
2023-09-16 00:34:11 +08:00
tokenizer: Union[str, None] = None
2023-05-23 11:51:43 +08:00
customCuda: bool = False
deploy: bool = Field(
False,
description="Deploy mode. If success, will disable /switch-model, /exit and other dangerous APIs (state cache APIs, part of midi APIs)",
)
2023-05-07 17:27:54 +08:00
model_config = {
"json_schema_extra": {
2023-06-15 21:52:22 +08:00
"example": {
2023-06-20 16:07:52 +08:00
"model": "models/RWKV-4-World-3B-v1-20230619-ctx4096.pth",
2023-06-15 21:52:22 +08:00
"strategy": "cuda fp16",
2023-11-20 20:11:45 +08:00
"tokenizer": "",
2023-06-15 21:52:22 +08:00
"customCuda": False,
"deploy": False,
2023-06-15 21:52:22 +08:00
}
}
}
2023-06-15 21:52:22 +08:00
2023-05-07 17:27:54 +08:00
2023-07-26 22:24:26 +08:00
@router.post("/switch-model", tags=["Configs"])
def switch_model(body: SwitchModelBody, response: Response, request: Request):
if global_var.get(global_var.Deploy_Mode) is True:
raise HTTPException(Status.HTTP_403_FORBIDDEN)
2023-05-17 11:39:00 +08:00
if global_var.get(global_var.Model_Status) is global_var.ModelStatus.Loading:
2023-05-30 11:52:33 +08:00
response.status_code = Status.HTTP_304_NOT_MODIFIED
2023-05-07 22:48:52 +08:00
return
2023-05-07 17:27:54 +08:00
global_var.set(global_var.Model_Status, global_var.ModelStatus.Offline)
global_var.set(global_var.Model, None)
torch_gc()
2023-05-23 12:13:12 +08:00
if body.model == "":
return "success"
2023-12-08 15:28:33 +08:00
devices = set(
[
x.strip().split(" ")[0].replace("cuda:0", "cuda")
for x in body.strategy.split("->")
]
)
2023-12-12 20:29:55 +08:00
print(f"Strategy Devices: {devices}")
2023-12-08 15:28:33 +08:00
# if len(devices) > 1:
# state_cache.disable_state_cache()
# else:
try:
state_cache.enable_state_cache()
except HTTPException:
pass
2023-07-11 11:20:12 +08:00
2023-05-23 12:13:12 +08:00
os.environ["RWKV_CUDA_ON"] = "1" if body.customCuda else "0"
2023-05-07 17:27:54 +08:00
global_var.set(global_var.Model_Status, global_var.ModelStatus.Loading)
try:
2023-05-17 11:39:00 +08:00
global_var.set(
global_var.Model,
RWKV(model=body.model, strategy=body.strategy, tokenizer=body.tokenizer),
2023-05-17 11:39:00 +08:00
)
2023-05-18 21:19:13 +08:00
except Exception as e:
print(e)
2023-12-12 23:16:48 +08:00
import traceback
print(traceback.format_exc())
quick_log(request, body, f"Exception: {e}")
2023-05-07 17:27:54 +08:00
global_var.set(global_var.Model_Status, global_var.ModelStatus.Offline)
2023-06-15 21:52:22 +08:00
raise HTTPException(
Status.HTTP_500_INTERNAL_SERVER_ERROR, f"failed to load: {e}"
)
2023-05-07 17:27:54 +08:00
if body.deploy:
global_var.set(global_var.Deploy_Mode, True)
saved_model_config = global_var.get(global_var.Model_Config)
init_model_config = get_rwkv_config(global_var.get(global_var.Model))
if saved_model_config is not None:
merge_model(init_model_config, saved_model_config)
global_var.set(global_var.Model_Config, init_model_config)
2023-05-07 17:27:54 +08:00
global_var.set(global_var.Model_Status, global_var.ModelStatus.Working)
return "success"
2023-05-17 11:39:00 +08:00
def merge_model(to_model: BaseModel, from_model: BaseModel):
from_model_fields = [x for x in from_model.dict().keys()]
to_model_fields = [x for x in to_model.dict().keys()]
for field_name in from_model_fields:
if field_name in to_model_fields:
from_value = getattr(from_model, field_name)
if from_value is not None:
setattr(to_model, field_name, from_value)
2023-07-26 22:24:26 +08:00
@router.post("/update-config", tags=["Configs"])
2023-05-17 11:39:00 +08:00
def update_config(body: ModelConfigBody):
"""
Will not update the model config immediately, but set it when completion called to avoid modifications during generation
"""
model_config = global_var.get(global_var.Model_Config)
if model_config is None:
model_config = ModelConfigBody()
global_var.set(global_var.Model_Config, model_config)
merge_model(model_config, body)
2024-05-16 13:50:48 +08:00
exception = load_rwkv_state(
global_var.get(global_var.Model), model_config.state, True
)
if exception is not None:
raise exception
print("Updated Model Config:", model_config)
2023-05-17 11:39:00 +08:00
return "success"
2023-05-19 15:59:04 +08:00
2023-07-26 22:24:26 +08:00
@router.get("/status", tags=["Configs"])
2023-05-19 15:59:04 +08:00
def status():
2024-03-11 18:55:37 +08:00
try:
import GPUtil
2023-07-29 19:18:01 +08:00
2024-03-11 18:55:37 +08:00
gpus = GPUtil.getGPUs()
except:
gpus = []
2023-05-23 12:13:12 +08:00
if len(gpus) == 0:
device_name = "CPU"
else:
device_name = gpus[0].name
return {
"status": global_var.get(global_var.Model_Status),
"pid": os.getpid(),
"device_name": device_name,
}