Spaces:
Configuration error
Configuration error
Download main.py from Chuxia-sys/tinyllama: direct link, hf CLI and curl.
- Browser
- Download file 1.9 kB
-
https://huggingface.co/spaces/Chuxia-sys/tinyllama/resolve/main/main.py
- Command line
-
hf download hf://spaces/Chuxia-sys/tinyllama/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Chuxia-sys/tinyllama/resolve/main/main.py
1.9 kB
| 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, | |
| ) | |
| async def generate(prompt: str): | |
| try: | |
| result = pipe(prompt) | |
| return {"response": result[0]["generated_text"]} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| 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) | |