ajit3259 commited on
Commit
593e278
Β·
1 Parent(s): d39ce87

feat(space): wire Qwen2.5-VL-7B via hf_local provider (stage 2)

Browse files

In-process model on ZeroGPU: model + processor load lazily to CPU, the forward
pass runs inside a @spaces.GPU-wrapped _generate (duration 180) that moves to
cuda. Translates our OpenAI-format content (image_url data URLs + text) into
Qwen2.5-VL chat messages via qwen-vl-utils. On the Space, default
CHALCHITRA_PROVIDER=hf_local and model=Qwen/Qwen2.5-VL-7B-Instruct (overridable
via Space Variables); local stays on LM Studio. Adds transformers/torchvision/
accelerate/qwen-vl-utils.

Files changed (3) hide show
  1. app.py +7 -0
  2. backend/providers.py +97 -28
  3. requirements.txt +5 -4
app.py CHANGED
@@ -29,6 +29,13 @@ from backend.providers import get_provider
29
 
30
  load_dotenv()
31
 
 
 
 
 
 
 
 
32
  HERE = Path(__file__).parent
33
  DIST = HERE / "frontend" / "dist"
34
 
 
29
 
30
  load_dotenv()
31
 
32
+ # On the Space, run the model in-process on ZeroGPU (Qwen2.5-VL) by default.
33
+ # Locally these stay unset, so we keep talking to LM Studio. setdefault lets a
34
+ # Space Variable still override either value from the Settings UI.
35
+ if os.environ.get("SPACE_ID"):
36
+ os.environ.setdefault("CHALCHITRA_PROVIDER", "hf_local")
37
+ os.environ.setdefault("CHALCHITRA_MODEL", "Qwen/Qwen2.5-VL-7B-Instruct")
38
+
39
  HERE = Path(__file__).parent
40
  DIST = HERE / "frontend" / "dist"
41
 
backend/providers.py CHANGED
@@ -86,34 +86,100 @@ class OpenAICompatibleProvider:
86
  return resp.choices[0].message.content or ""
87
 
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  class HFLocalProvider:
90
- """Run a vision model in-process on ZeroGPU via transformers (HF deploy path).
91
-
92
- This is the deploy target: the Space loads the model itself and runs it on a
93
- ZeroGPU-allocated GPU. The seam matches OpenAICompatibleProvider exactly, so
94
- app code never branches on which path we took β€” only the env config changes.
95
-
96
- Implementation plan (deferred until we move off LM Studio), mirroring the
97
- proven pattern in the sibling Mycelium Space:
98
- * Put a module-level `@spaces.GPU def _warmup(): pass` in app.py and call
99
- launch() so ZeroGPU initializes at startup.
100
- * Define `_gpu(fn)` that applies `spaces.GPU(duration=...)` only when the
101
- `spaces` package is importable, else returns fn unchanged β€” so this exact
102
- code path also runs locally without a GPU.
103
- * Load the processor + model once at startup on CPU; move tensors to cuda
104
- inside the `_gpu`-wrapped forward pass (ZeroGPU only grants the GPU there).
105
- * Translate our OpenAI-format `content` (text + image_url data URLs) into
106
- the model's chat template + decoded PIL images.
107
-
108
- The earlier worry β€” whether @spaces.GPU allocates when the call comes from a
109
- FastAPI route rather than a Gradio event β€” is resolved: Mycelium drives
110
- `_gpu`-wrapped functions straight from `@app.post` routes on the launched
111
- app, and ZeroGPU allocates correctly. No vLLM fallback needed.
112
  """
113
 
114
- def __init__(self, model: str, **_: Any) -> None:
115
  self.name = "hf_local"
116
  self.model = model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  def complete(
119
  self,
@@ -122,10 +188,10 @@ class HFLocalProvider:
122
  max_tokens: int,
123
  temperature: float | None = None,
124
  ) -> str:
125
- raise NotImplementedError(
126
- "HFLocalProvider (ZeroGPU/transformers) is not implemented yet. While "
127
- "developing, use CHALCHITRA_PROVIDER=openai_compatible against LM Studio."
128
- )
129
 
130
 
131
  def get_provider() -> Provider:
@@ -149,7 +215,10 @@ def get_provider() -> Provider:
149
  timeout=float(os.environ.get("CHALCHITRA_TIMEOUT", "120")),
150
  )
151
  if kind == "hf_local":
152
- return HFLocalProvider(model=model)
 
 
 
153
 
154
  raise ValueError(
155
  f"Unknown CHALCHITRA_PROVIDER={kind!r}. Use 'openai_compatible' or 'hf_local'."
 
86
  return resp.choices[0].message.content or ""
87
 
88
 
89
+ # ── ZeroGPU plumbing for the in-process model path ────────────────────────────
90
+ # `_gpu` applies @spaces.GPU only when running on a Space (where `spaces` is
91
+ # installed); locally it's a no-op so the same code imports without a GPU. The
92
+ # decorated `_generate` is defined at module level so it's registered for
93
+ # ZeroGPU's startup scan.
94
+ try:
95
+ import spaces as _spaces
96
+
97
+ def _gpu(fn):
98
+ return _spaces.GPU(duration=180)(fn)
99
+ except ImportError:
100
+ def _gpu(fn):
101
+ return fn
102
+
103
+ GPU_MAX_NEW_TOKENS = 2048
104
+
105
+
106
+ def _to_qwen_messages(system: str, content: list[dict[str, Any]]):
107
+ """Translate our OpenAI-format content into Qwen2.5-VL chat messages.
108
+
109
+ image_url blocks (data URLs) become {"type":"image","image": <data url>},
110
+ which qwen-vl-utils decodes; text blocks pass through.
111
+ """
112
+ user_content: list[dict[str, Any]] = []
113
+ for block in content:
114
+ if block.get("type") == "image_url":
115
+ user_content.append({"type": "image", "image": block["image_url"]["url"]})
116
+ elif block.get("type") == "text":
117
+ user_content.append({"type": "text", "text": block["text"]})
118
+ return [
119
+ {"role": "system", "content": system},
120
+ {"role": "user", "content": user_content},
121
+ ]
122
+
123
+
124
+ @_gpu
125
+ def _generate(model, processor, messages, max_new_tokens: int, temperature: float) -> str:
126
+ """The GPU-bound forward pass. Runs inside a ZeroGPU allocation on the Space."""
127
+ import torch
128
+ from qwen_vl_utils import process_vision_info
129
+
130
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
131
+ image_inputs, video_inputs = process_vision_info(messages)
132
+ inputs = processor(
133
+ text=[text],
134
+ images=image_inputs,
135
+ videos=video_inputs,
136
+ padding=True,
137
+ return_tensors="pt",
138
+ )
139
+ model.to("cuda")
140
+ inputs = inputs.to("cuda")
141
+ with torch.no_grad():
142
+ generated = model.generate(
143
+ **inputs,
144
+ max_new_tokens=max_new_tokens,
145
+ do_sample=temperature > 0,
146
+ temperature=temperature if temperature > 0 else None,
147
+ top_p=0.9,
148
+ )
149
+ trimmed = [out[len(inp):] for inp, out in zip(inputs.input_ids, generated)]
150
+ decoded = processor.batch_decode(
151
+ trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
152
+ )
153
+ return decoded[0] if decoded else ""
154
+
155
+
156
  class HFLocalProvider:
157
+ """Run Qwen2.5-VL in-process on ZeroGPU via transformers (the HF deploy path).
158
+
159
+ The Space loads the model itself and runs it on a ZeroGPU-allocated GPU. The
160
+ seam matches OpenAICompatibleProvider exactly, so app code never branches on
161
+ which path we took β€” only the env config changes. The model + processor load
162
+ lazily to CPU on first request; the forward pass moves to cuda inside the
163
+ `_gpu`-wrapped `_generate` (ZeroGPU only grants the GPU there).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  """
165
 
166
+ def __init__(self, model: str, temperature: float = 0.8, **_: Any) -> None:
167
  self.name = "hf_local"
168
  self.model = model
169
+ self.temperature = temperature
170
+ self._model = None
171
+ self._processor = None
172
+
173
+ def _ensure_loaded(self) -> None:
174
+ if self._model is not None:
175
+ return
176
+ import torch
177
+ from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration
178
+
179
+ self._processor = AutoProcessor.from_pretrained(self.model)
180
+ self._model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
181
+ self.model, torch_dtype=torch.bfloat16
182
+ )
183
 
184
  def complete(
185
  self,
 
188
  max_tokens: int,
189
  temperature: float | None = None,
190
  ) -> str:
191
+ self._ensure_loaded()
192
+ messages = _to_qwen_messages(system, content)
193
+ temp = self.temperature if temperature is None else temperature
194
+ return _generate(self._model, self._processor, messages, max_tokens, temp)
195
 
196
 
197
  def get_provider() -> Provider:
 
215
  timeout=float(os.environ.get("CHALCHITRA_TIMEOUT", "120")),
216
  )
217
  if kind == "hf_local":
218
+ return HFLocalProvider(
219
+ model=model,
220
+ temperature=float(os.environ.get("CHALCHITRA_TEMPERATURE", "0.8")),
221
+ )
222
 
223
  raise ValueError(
224
  f"Unknown CHALCHITRA_PROVIDER={kind!r}. Use 'openai_compatible' or 'hf_local'."
requirements.txt CHANGED
@@ -5,7 +5,8 @@ python-dotenv>=1.0
5
  pillow>=10.0 # server-side image validation + re-encode (sanitize.py)
6
  spaces>=0.20 # ZeroGPU: @spaces.GPU at module level (required on the Space)
7
 
8
- # --- hf_local provider (in-process Qwen2.5-VL on ZeroGPU) β€” stage 2 ---
9
- # transformers>=4.49
10
- # torchvision
11
- # accelerate
 
 
5
  pillow>=10.0 # server-side image validation + re-encode (sanitize.py)
6
  spaces>=0.20 # ZeroGPU: @spaces.GPU at module level (required on the Space)
7
 
8
+ # --- hf_local provider: in-process Qwen2.5-VL on ZeroGPU ---
9
+ transformers>=4.49
10
+ torchvision
11
+ accelerate
12
+ qwen-vl-utils