Spaces:
Configuration error

File size: 1,901 Bytes
43a816b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from fastapi import FastAPI
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, GenerationConfig
import torch
from huggingface_hub import login

if "HF_TOKEN" in os.environ:
    login(token=os.environ["HF_TOKEN"])


app = FastAPI()

# Paths
model_name = "Chuxia-sys/finetuned_model"
base_model = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"  # Parent model

# Try loading tokenizer from fine-tuned repo; fallback to base
try:
    tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
except Exception:
    tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)

# Load model
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
    device_map="auto" if torch.cuda.is_available() else None,
    low_cpu_mem_usage=True,
    trust_remote_code=True,
    ignore_mismatched_sizes=True,
)

# ✅ Load generation_config.json automatically and attach to model
try:
    generation_config = GenerationConfig.from_pretrained(model_name)
except Exception:
    generation_config = GenerationConfig.from_pretrained(base_model)

model.generation_config = generation_config  # 👈 attach config to model

# Create pipeline (no need to pass generation_config again)
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
)

@app.post("/generate")
async def generate(prompt: str):
    try:
        result = pipe(prompt)
        return {"response": result[0]["generated_text"]}
    except Exception as e:
        return {"error": str(e)}

@app.get("/health")
async def health():
    return {"status": "ok"}

# Add fallback for $PORT
if __name__ == "__main__":
    import uvicorn
    port = int(os.environ.get("PORT", 8000))
    uvicorn.run(app, host="0.0.0.0", port=port)