PabsCanCode Claude Opus 5.5 commited on
Commit
f6e5106
·
1 Parent(s): 69f7fc6

Embed CLIP label text lazily instead of at import

Browse files

Running the CLIP text encoder in the ZeroGPU parent process at import
appears to leave torch in a state that breaks the forked GPU worker
("No CUDA GPUs are available" in worker_init). Compute the embeddings
on first use, inside the GPU worker; FastAPI warms them at startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Files changed (2) hide show
  1. app.py +1 -4
  2. main.py +23 -7
app.py CHANGED
@@ -15,14 +15,11 @@ from PIL import Image, ImageOps, UnidentifiedImageError
15
 
16
  import main as backend
17
 
18
- # Precomputed text embeddings are created on CPU by main, then moved with the models.
19
  # ZeroGPU requires CUDA placement at module scope, outside the decorated function.
 
20
  backend.disease_clf.model.to("cuda")
21
  backend.disease_clf.device = torch.device("cuda")
22
  backend.gate_model.to("cuda")
23
- backend.gate_text = backend.gate_text.to("cuda")
24
- backend.vocab_text = backend.vocab_text.to("cuda")
25
- backend.gate_scale = backend.gate_scale.to("cuda")
26
 
27
 
28
  @spaces.GPU(duration=20)
 
15
 
16
  import main as backend
17
 
 
18
  # ZeroGPU requires CUDA placement at module scope, outside the decorated function.
19
+ # Label text embeddings are computed lazily inside the GPU worker (see main.label_embeddings).
20
  backend.disease_clf.model.to("cuda")
21
  backend.disease_clf.device = torch.device("cuda")
22
  backend.gate_model.to("cuda")
 
 
 
23
 
24
 
25
  @spaces.GPU(duration=20)
main.py CHANGED
@@ -2,6 +2,7 @@ import io
2
  import json
3
  import os
4
  import secrets
 
5
 
6
  from fastapi import FastAPI, File, Header, HTTPException, UploadFile
7
  from fastapi.middleware.cors import CORSMiddleware
@@ -88,24 +89,39 @@ def _unit(features) -> torch.Tensor:
88
  def _embed_texts(texts: list[str]) -> torch.Tensor:
89
  return torch.cat([
90
  _unit(gate_model.get_text_features(**gate_processor(
91
- text=[f"a photo of {t}." for t in texts[i:i + 256]], return_tensors="pt", padding=True)))
92
  for i in range(0, len(texts), 256)
93
  ])
94
 
95
 
96
- # Label text never changes, so embed it once; each upload then costs one image pass, however many labels.
97
- with torch.no_grad():
98
- gate_text = _embed_texts([prompt for prompt, _, _ in GATE_LABELS])
99
- vocab_text = _embed_texts(NAME_VOCAB)
100
- gate_scale = gate_model.logit_scale.exp()
101
 
102
- app = FastAPI(title="Rice Disease Detection API")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  # Frontends may upload photos; storage credentials remain on the backend.
104
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST"], allow_headers=["*"])
105
 
106
 
107
  def rice_check(image: Image.Image) -> tuple[bool, float, list[dict]]:
108
  """Returns (is rice, total rice probability, top 3 distinct guesses as {label, confidence})."""
 
109
  with torch.no_grad():
110
  image_emb = _unit(gate_model.get_image_features(**gate_processor(images=image, return_tensors="pt").to(gate_model.device)))
111
  probs = (gate_scale * image_emb @ gate_text.T).softmax(-1)[0].tolist()
 
2
  import json
3
  import os
4
  import secrets
5
+ from contextlib import asynccontextmanager
6
 
7
  from fastapi import FastAPI, File, Header, HTTPException, UploadFile
8
  from fastapi.middleware.cors import CORSMiddleware
 
89
  def _embed_texts(texts: list[str]) -> torch.Tensor:
90
  return torch.cat([
91
  _unit(gate_model.get_text_features(**gate_processor(
92
+ text=[f"a photo of {t}." for t in texts[i:i + 256]], return_tensors="pt", padding=True).to(gate_model.device)))
93
  for i in range(0, len(texts), 256)
94
  ])
95
 
96
 
97
+ _label_embeddings = None
 
 
 
 
98
 
99
+
100
+ def label_embeddings() -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
101
+ """(gate_text, vocab_text, scale), embedded once per process; each upload then costs one image pass.
102
+ Not run at import: torch compute in the ZeroGPU parent process breaks the GPU worker it forks."""
103
+ global _label_embeddings
104
+ if _label_embeddings is None:
105
+ with torch.no_grad():
106
+ _label_embeddings = (_embed_texts([prompt for prompt, _, _ in GATE_LABELS]),
107
+ _embed_texts(NAME_VOCAB), gate_model.logit_scale.exp())
108
+ return _label_embeddings
109
+
110
+
111
+ @asynccontextmanager
112
+ async def lifespan(_app):
113
+ label_embeddings() # warm up on server start so the first upload isn't slow
114
+ yield
115
+
116
+
117
+ app = FastAPI(title="Rice Disease Detection API", lifespan=lifespan)
118
  # Frontends may upload photos; storage credentials remain on the backend.
119
  app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST"], allow_headers=["*"])
120
 
121
 
122
  def rice_check(image: Image.Image) -> tuple[bool, float, list[dict]]:
123
  """Returns (is rice, total rice probability, top 3 distinct guesses as {label, confidence})."""
124
+ gate_text, vocab_text, gate_scale = label_embeddings()
125
  with torch.no_grad():
126
  image_emb = _unit(gate_model.get_image_features(**gate_processor(images=image, return_tensors="pt").to(gate_model.device)))
127
  probs = (gate_scale * image_emb @ gate_text.T).softmax(-1)[0].tolist()