AnminBhu commited on
Commit
ff0de1c
·
verified ·
1 Parent(s): 3b04c43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -60
app.py CHANGED
@@ -1,60 +1,60 @@
1
- import os
2
- import torch
3
- from fastapi import FastAPI, Request
4
- from pydantic import BaseModel
5
- from transformers import AutoTokenizer, AutoModelForCausalLM
6
-
7
- # ----------- Config -----------
8
- MODEL_DIR = "distilgpt2" # Path to the model directory
9
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
-
11
- # ----------- App Init -----------
12
- app = FastAPI(title="AnmoraAI Chatbot API")
13
-
14
- # ----------- Model Load -----------
15
- if not os.path.isdir(MODEL_DIR):
16
- raise SystemExit(f"[ERROR] Model dir '{MODEL_DIR}' not found.")
17
-
18
- # Load quantized or normal model
19
- load_kwargs = {}
20
- try:
21
- from transformers import BitsAndBytesConfig
22
- load_kwargs = {"quantization_config": BitsAndBytesConfig(load_in_4bit=True)}
23
- print("[INFO] Loading in 4-bit mode (bitsandbytes).")
24
- except ImportError:
25
- print("[INFO] bitsandbytes not found. Loading in full precision.")
26
- load_kwargs = {"torch_dtype": torch.float16 if DEVICE == "cuda" else torch.float32}
27
-
28
- tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
29
- model = AutoModelForCausalLM.from_pretrained(MODEL_DIR, device_map="auto", **load_kwargs)
30
- model.eval()
31
-
32
- # ----------- Request Model -----------
33
- class ChatRequest(BaseModel):
34
- message: str
35
-
36
- # ----------- Endpoint -----------
37
- @app.post("/chat")
38
- async def chat(request: ChatRequest):
39
- user_input = request.message.strip()
40
-
41
- if not user_input:
42
- return {"response": "Please enter a valid message."}
43
-
44
- prompt = f"### Instruction:\n{user_input}\n\n### Response:\n"
45
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
46
-
47
- with torch.no_grad():
48
- outputs = model.generate(
49
- **inputs,
50
- max_new_tokens=128,
51
- repetition_penalty=1.15,
52
- pad_token_id=tokenizer.eos_token_id,
53
- )
54
-
55
- gen_text = tokenizer.decode(outputs[0][inputs.input_ids.size(1):], skip_special_tokens=True).strip()
56
-
57
- if "###" in gen_text:
58
- gen_text = gen_text.split("###")[0].strip()
59
-
60
- return {"response": gen_text}
 
1
+ import os
2
+ import torch
3
+ from fastapi import FastAPI, Request
4
+ from pydantic import BaseModel
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+
7
+ # ----------- Config -----------
8
+ MODEL_DIR = "distilgpt2" # Path to the model directory
9
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
10
+
11
+ # ----------- App Init -----------
12
+ app = FastAPI(title="AnmoraAI Chatbot API")
13
+
14
+ # ----------- Model Load -----------
15
+ # if not os.path.isdir(MODEL_DIR):
16
+ # raise SystemExit(f"[ERROR] Model dir '{MODEL_DIR}' not found.")
17
+
18
+ # Load quantized or normal model
19
+ load_kwargs = {}
20
+ try:
21
+ from transformers import BitsAndBytesConfig
22
+ load_kwargs = {"quantization_config": BitsAndBytesConfig(load_in_4bit=True)}
23
+ print("[INFO] Loading in 4-bit mode (bitsandbytes).")
24
+ except ImportError:
25
+ print("[INFO] bitsandbytes not found. Loading in full precision.")
26
+ load_kwargs = {"torch_dtype": torch.float16 if DEVICE == "cuda" else torch.float32}
27
+
28
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
29
+ model = AutoModelForCausalLM.from_pretrained(MODEL_DIR, device_map="auto", **load_kwargs)
30
+ model.eval()
31
+
32
+ # ----------- Request Model -----------
33
+ class ChatRequest(BaseModel):
34
+ message: str
35
+
36
+ # ----------- Endpoint -----------
37
+ @app.post("/chat")
38
+ async def chat(request: ChatRequest):
39
+ user_input = request.message.strip()
40
+
41
+ if not user_input:
42
+ return {"response": "Please enter a valid message."}
43
+
44
+ prompt = f"### Instruction:\n{user_input}\n\n### Response:\n"
45
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
46
+
47
+ with torch.no_grad():
48
+ outputs = model.generate(
49
+ **inputs,
50
+ max_new_tokens=128,
51
+ repetition_penalty=1.15,
52
+ pad_token_id=tokenizer.eos_token_id,
53
+ )
54
+
55
+ gen_text = tokenizer.decode(outputs[0][inputs.input_ids.size(1):], skip_special_tokens=True).strip()
56
+
57
+ if "###" in gen_text:
58
+ gen_text = gen_text.split("###")[0].strip()
59
+
60
+ return {"response": gen_text}