File size: 1,813 Bytes
59cd1f7
45d388a
 
 
 
 
 
 
 
 
 
59cd1f7
 
 
 
 
 
 
 
 
 
 
 
45d388a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59cd1f7
 
 
 
 
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
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Khởi tạo FastAPI
app = FastAPI()

# Tải model và tokenizer khi ứng dụng khởi động
model_name = "Qwen/Qwen2.5-0.5B"
try:
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        torch_dtype="auto",
        device_map="auto",
        attn_implementation="eager"  # Tránh cảnh báo sdpa
    )
    print("Model and tokenizer loaded successfully!")
except Exception as e:
    print(f"Error loading model: {e}")
    raise

# Định nghĩa request body
class TextInput(BaseModel):
    prompt: str
    max_length: int = 100

# API endpoint để sinh văn bản
@app.post("/generate")
async def generate_text(input: TextInput):
    try:
        # Mã hóa đầu vào
        inputs = tokenizer(input.prompt, return_tensors="pt").to(model.device)
        
        # Sinh văn bản
        outputs = model.generate(
            inputs["input_ids"],
            max_length=input.max_length,
            num_return_sequences=1,
            no_repeat_ngram_size=2,
            do_sample=True,
            top_k=50,
            top_p=0.95
        )
        
        # Giải mã kết quả
        generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
        return {"generated_text": generated_text}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Endpoint kiểm tra sức khỏe
@app.get("/")
async def root():
    return {"message": "Qwen2.5-0.5B API is running!"}

# Chạy server khi file được gọi trực tiếp
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)