oleh13 commited on
Commit
197dbda
·
verified ·
1 Parent(s): 7cf6c76

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from fastapi import FastAPI, HTTPException
3
+ from pydantic import BaseModel
4
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
5
+
6
+ app = FastAPI()
7
+
8
+ model_id = "sagawa/ReactionT5v2-retrosynthesis-USPTO_50k"
9
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
10
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
11
+
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ model = model.to(device)
14
+
15
+ class CompletionRequest(BaseModel):
16
+ model: str
17
+ prompt: str
18
+ max_tokens: int = 128
19
+ temperature: float = 0.0
20
+
21
+ @app.post("/v1/completions")
22
+ async def text_completions(request: CompletionRequest):
23
+ try:
24
+ inputs = tokenizer(request.prompt, return_tensors="pt").to(device)
25
+
26
+ with torch.no_grad():
27
+ outputs = model.generate(
28
+ **inputs,
29
+ max_new_tokens=request.max_tokens,
30
+ do_sample=request.temperature > 0,
31
+ temperature=request.temperature if request.temperature > 0 else None
32
+ )
33
+
34
+ raw_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
35
+
36
+ return {
37
+ "id": "cmpl-raw-123",
38
+ "object": "text_completion",
39
+ "model": request.model,
40
+ "choices": [{
41
+ "text": raw_response,
42
+ "index": 0,
43
+ "logprobs": None,
44
+ "finish_reason": "stop"
45
+ }]
46
+ }
47
+ except Exception as e:
48
+ raise HTTPException(status_code=500, detail=str(e))
49
+
50
+ @app.get("/")
51
+ def health():
52
+ return {"status": "healthy"}