| from fastapi import FastAPI |
| from pydantic import BaseModel |
| from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig |
| import torch |
|
|
| app = FastAPI() |
|
|
| |
|
|
| MODEL_PATH = "vivekutty" |
| MAX_SEQ_LENGTH = 2048 |
| LOAD_IN_4BIT = True |
|
|
| |
| bnb_config = BitsAndBytesConfig( |
| load_in_4bit=LOAD_IN_4BIT, |
| bnb_4bit_compute_dtype=torch.float16, |
| bnb_4bit_use_double_quant=True, |
| bnb_4bit_quant_type="nf4", |
| ) |
|
|
| |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, local_files_only=True) |
| model = AutoModelForCausalLM.from_pretrained( |
| MODEL_PATH, |
| quantization_config=bnb_config if LOAD_IN_4BIT else None, |
| device_map="auto", |
| local_files_only=True |
| ) |
|
|
| |
|
|
| def generate_response(instruction: str, input_text: str, max_new_tokens: int = 128): |
| chat_prompt = f"""### Instruction: |
| {instruction} |
| ### Input: |
| {input_text} |
| ### Response: |
| """ |
|
|
| |
| inputs = tokenizer(chat_prompt, return_tensors="pt").to(model.device) |
|
|
| |
| with torch.no_grad(): |
| outputs = model.generate( |
| **inputs, |
| max_new_tokens=max_new_tokens, |
| do_sample=True, |
| temperature=0.7 |
| ) |
|
|
| |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) |
| return response |
|
|
| |
|
|
| class ChatRequest(BaseModel): |
| instruction: str = "" |
| input_text: str |
|
|
| |
|
|
| @app.post("/chat") |
| async def chat(req: ChatRequest): |
| response = generate_response(req.instruction, req.input_text) |
| return {"response": response} |
|
|
| @app.get("/") |
| async def root(): |
| return {"message": "Model API is running!"} |
|
|