robell05 commited on
Commit
f6fd762
·
1 Parent(s): c6138de

adding log endpoints and changes

Browse files
Files changed (1) hide show
  1. app.py +39 -9
app.py CHANGED
@@ -1,7 +1,9 @@
1
  from fastapi import FastAPI, HTTPException
2
  import chess
3
  from contextlib import asynccontextmanager
 
4
  import sys
 
5
  import torch
6
  from pydantic import BaseModel
7
 
@@ -12,37 +14,65 @@ sys.modules["tokenizer"] = _tokenizer_module
12
 
13
  from src.model import ChessPolicyModel, PolicyModelInference
14
 
 
 
 
 
 
 
15
  ml = {}
 
16
  @asynccontextmanager
17
  async def lifespan(app: FastAPI):
18
- tokenizer = torch.load("./model/tokenizer.pt", weights_only=False, map_location=torch.device('cpu'))
 
 
 
19
 
20
- model = ChessPolicyModel(vocab_size=tokenizer.language_size)
 
 
21
  model.load_state_dict(
22
- torch.load("./model/policy_model.pt", weights_only=False, map_location=torch.device('cpu'))
23
  )
24
- ml["inference"] = PolicyModelInference(model, tokenizer, device="cpu")
25
- yield
 
 
 
26
  ml.clear()
27
 
28
  app = FastAPI(lifespan=lifespan)
29
 
30
 
31
-
32
  class InferenceRequest(BaseModel):
33
  moves: list[str]
34
 
 
 
 
 
 
 
35
  @app.post("/inference")
36
  def model_inference(req: InferenceRequest):
 
 
37
  board = chess.Board()
38
  for move in req.moves:
39
  try:
40
  board.push_uci(move)
41
  except ValueError as e:
 
42
  raise HTTPException(status_code=400, detail=f"Incorrect move {move}: {e}")
 
43
  try:
44
- return {"move" : ml["inference"](board)}
45
- except ValueError as e:
46
- raise HTTPException(status_code=500, detail=f"Model Failed to evaluate: {e}")
 
 
 
 
47
 
48
 
 
1
  from fastapi import FastAPI, HTTPException
2
  import chess
3
  from contextlib import asynccontextmanager
4
+ import logging
5
  import sys
6
+ import time
7
  import torch
8
  from pydantic import BaseModel
9
 
 
14
 
15
  from src.model import ChessPolicyModel, PolicyModelInference
16
 
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format="%(asctime)s %(levelname)s %(name)s - %(message)s",
20
+ )
21
+ log = logging.getLogger("transformer4chess")
22
+
23
  ml = {}
24
+
25
  @asynccontextmanager
26
  async def lifespan(app: FastAPI):
27
+ log.info("loading tokenizer from ./model/tokenizer.pt")
28
+ t0 = time.perf_counter()
29
+ tokenizer = torch.load("./model/tokenizer.pt", weights_only=False, map_location="cpu")
30
+ log.info("tokenizer loaded (vocab=%d) in %.2fs", tokenizer.language_size, time.perf_counter() - t0)
31
 
32
+ log.info("loading policy model from ./model/policy_model.pt")
33
+ t0 = time.perf_counter()
34
+ model = ChessPolicyModel(vocab_size=tokenizer.language_size)
35
  model.load_state_dict(
36
+ torch.load("./model/policy_model.pt", weights_only=False, map_location="cpu")
37
  )
38
+ ml["inference"] = PolicyModelInference(model, tokenizer, device="cpu")
39
+ log.info("policy model loaded in %.2fs", time.perf_counter() - t0)
40
+
41
+ yield
42
+ log.info("shutting down — clearing model cache")
43
  ml.clear()
44
 
45
  app = FastAPI(lifespan=lifespan)
46
 
47
 
 
48
  class InferenceRequest(BaseModel):
49
  moves: list[str]
50
 
51
+
52
+ @app.get("/")
53
+ def root():
54
+ return {"status": "ok", "endpoints": ["/inference", "/docs"]}
55
+
56
+
57
  @app.post("/inference")
58
  def model_inference(req: InferenceRequest):
59
+ log.info("inference request: %d moves", len(req.moves))
60
+
61
  board = chess.Board()
62
  for move in req.moves:
63
  try:
64
  board.push_uci(move)
65
  except ValueError as e:
66
+ log.warning("rejected illegal move %r: %s", move, e)
67
  raise HTTPException(status_code=400, detail=f"Incorrect move {move}: {e}")
68
+
69
  try:
70
+ t0 = time.perf_counter()
71
+ prediction = ml["inference"](board)
72
+ log.info("predicted %s in %.3fs", prediction, time.perf_counter() - t0)
73
+ return {"move": prediction}
74
+ except Exception:
75
+ log.exception("model inference failed")
76
+ raise HTTPException(status_code=500, detail="Model failed to evaluate")
77
 
78