forked from MeetKai/functionary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modal_server.py
103 lines (83 loc) · 2.23 KB
/
modal_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import uuid
from typing import List
import modal
from fastapi import FastAPI
from functionary.inference import generate_message
from functionary.openai_types import (
ChatCompletion,
ChatInput,
ChatMessage,
Choice,
Function,
)
stub = modal.Stub("functionary")
app = FastAPI(title="Functionary API")
MODEL = "musabgultekin/functionary-7b-v1"
LOADIN8BIT = False
def get_model():
# this is lazy should be using the modal model class
import torch
from transformers import LlamaForCausalLM, LlamaTokenizer
model = LlamaForCausalLM.from_pretrained(
MODEL,
low_cpu_mem_usage=True,
device_map="auto",
torch_dtype=torch.float16,
load_in_8bit=LOADIN8BIT,
)
tokenizer = LlamaTokenizer.from_pretrained(MODEL, use_fast=False)
return model, tokenizer
def download_model():
get_model()
image = (
modal.Image.debian_slim()
.pip_install(
"fastapi",
"pydantic",
"transformers",
"sentencepiece",
"torch",
"bitsandbytes>=0.39.0",
"accelerate",
"einops",
"scipy",
"numpy",
)
.run_function(download_model)
)
@stub.cls(gpu="A100", image=image)
class Model:
def __enter__(self):
model, tokenizer = get_model()
self.model = model
self.tokenizer = tokenizer
@modal.method()
def generate(
self,
messages: List[ChatMessage],
functions: List[Function],
temperature: float,
):
return generate_message(
messages=messages,
functions=functions,
temperature=temperature,
model=self.model, # type: ignore
tokenizer=self.tokenizer,
)
@app.post("/v1/chat/completions", response_model=ChatCompletion)
async def chat_endpoint(chat_input: ChatInput):
request_id = str(uuid.uuid4())
model = Model()
response_message = model.generate.call(
messages=chat_input.messages,
functions=chat_input.functions,
temperature=chat_input.temperature,
)
return ChatCompletion(
id=request_id, choices=[Choice.from_message(response_message)]
)
@stub.function(image=image)
@modal.asgi_app()
def fastapi_app():
return app