Spaces:
Running
on
Zero
Running
on
Zero
AbstractPhil
commited on
Commit
·
73c138b
1
Parent(s):
4e7580d
super condensed test
Browse files
app.py
CHANGED
@@ -1,282 +1,75 @@
|
|
1 |
"""
|
2 |
-
Mirel
|
3 |
-
ZeroGPU-
|
4 |
-
Chain-of-thought model with proper channel extraction using openai_harmony
|
5 |
Single file: app.py
|
6 |
"""
|
7 |
from __future__ import annotations
|
8 |
-
import os, gc, json,
|
9 |
-
from
|
10 |
-
from typing import List, Dict, Optional, Any
|
11 |
-
from datetime import datetime
|
12 |
import gradio as gr
|
13 |
-
import spaces
|
14 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
15 |
-
|
16 |
-
# Import Harmony components
|
17 |
-
try:
|
18 |
-
from openai_harmony import (
|
19 |
-
Author,
|
20 |
-
Conversation,
|
21 |
-
HarmonyEncodingName,
|
22 |
-
Message,
|
23 |
-
Role,
|
24 |
-
SystemContent,
|
25 |
-
DeveloperContent,
|
26 |
-
load_harmony_encoding,
|
27 |
-
ReasoningEffort
|
28 |
-
)
|
29 |
-
HARMONY_AVAILABLE = True
|
30 |
-
except ImportError:
|
31 |
-
print("[WARNING] openai_harmony not installed. Install with: pip install openai-harmony")
|
32 |
-
HARMONY_AVAILABLE = False
|
33 |
|
34 |
# -----------------------
|
35 |
-
#
|
36 |
# -----------------------
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
ADAPTER_SUBFOLDER = os.getenv("ADAPTER_SUBFOLDER") or None
|
42 |
-
ATTN_IMPL = os.getenv("ATTN_IMPL", "eager")
|
43 |
-
DTYPE = DTYPE_MAP.get(os.getenv("DTYPE", "bf16").lower(), torch.bfloat16)
|
44 |
-
SYSTEM_DEF = os.getenv("SYSTEM_PROMPT", "You are Mirel, a memory-stable symbolic assistant.")
|
45 |
-
MAX_DEF = int(os.getenv("MAX_NEW_TOKENS", "256"))
|
46 |
-
ZEROGPU = os.getenv("ZEROGPU", os.getenv("ZERO_GPU", "0")) == "1"
|
47 |
-
LOAD_4BIT = os.getenv("LOAD_4BIT", "0") == "1"
|
48 |
-
|
49 |
-
# Harmony channels for CoT
|
50 |
-
REQUIRED_CHANNELS = ["analysis", "final"]
|
51 |
-
|
52 |
-
# HF Auth - properly handle multiple token env var names
|
53 |
HF_TOKEN: Optional[str] = (
|
54 |
-
os.getenv("HF_TOKEN")
|
55 |
-
or os.getenv("HUGGING_FACE_HUB_TOKEN")
|
56 |
or os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
57 |
or os.getenv("HF_ACCESS_TOKEN")
|
58 |
)
|
59 |
|
60 |
-
def _hf_login() -> None:
|
61 |
-
"""Login to HF Hub using common env secret names."""
|
62 |
-
if HF_TOKEN:
|
63 |
-
try:
|
64 |
-
from huggingface_hub import login, whoami
|
65 |
-
login(token=HF_TOKEN, add_to_git_credential=True)
|
66 |
-
try:
|
67 |
-
who = whoami(token=HF_TOKEN)
|
68 |
-
print(f"[HF Auth] Logged in as: {who.get('name') or who.get('fullname') or who.get('id', 'unknown')}")
|
69 |
-
except Exception:
|
70 |
-
print("[HF Auth] Login successful but couldn't get user info")
|
71 |
-
except Exception as e:
|
72 |
-
print(f"[HF Auth] Login failed: {e}")
|
73 |
-
else:
|
74 |
-
print("[HF Auth] No token found in environment variables")
|
75 |
-
|
76 |
-
# Login is handled by Space OAuth/session; avoid explicit CLI login here to prevent OAuth var errors
|
77 |
-
# _hf_login()
|
78 |
-
|
79 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
80 |
|
81 |
-
#
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
harmony_encoding = None
|
86 |
-
|
87 |
-
# Stop tokens per Harmony spec: <|return|> (200002), <|call|> (200012)
|
88 |
-
HARMONY_STOP_IDS = harmony_encoding.stop_tokens_for_assistant_actions() if HARMONY_AVAILABLE else []
|
89 |
-
|
90 |
-
# Tokenizer is lightweight; load once
|
91 |
-
try:
|
92 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True, token=HF_TOKEN)
|
93 |
-
print(f"[Model] Successfully loaded tokenizer from {MODEL_ID}")
|
94 |
-
except Exception as e:
|
95 |
-
print(f"[Model] Failed to load tokenizer: {e}")
|
96 |
-
raise
|
97 |
|
98 |
# -----------------------
|
99 |
-
#
|
100 |
# -----------------------
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
trust_remote_code=True,
|
114 |
-
low_cpu_mem_usage=True,
|
115 |
-
token=HF_TOKEN,
|
116 |
-
)
|
117 |
-
if LOAD_4BIT and device_map != "cpu":
|
118 |
try:
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
123 |
except Exception:
|
124 |
pass
|
125 |
-
return
|
126 |
-
|
127 |
-
|
128 |
-
def _load_model_on(device_map: Optional[str]) -> AutoModelForCausalLM:
|
129 |
-
print(f"[Model] Loading base model from {MODEL_ID}...")
|
130 |
-
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, **_build_model_kwargs(device_map))
|
131 |
-
|
132 |
-
if ADAPTER_ID:
|
133 |
-
if not _HAS_PEFT:
|
134 |
-
raise RuntimeError("peft is required when ADAPTER_ID is set.")
|
135 |
-
print(f"[Model] Loading adapter from {ADAPTER_ID}...")
|
136 |
-
peft_kwargs: Dict[str, Any] = {"token": HF_TOKEN}
|
137 |
-
if ADAPTER_SUBFOLDER:
|
138 |
-
peft_kwargs["subfolder"] = ADAPTER_SUBFOLDER
|
139 |
-
model = PeftModel.from_pretrained(model, ADAPTER_ID, is_trainable=False, **peft_kwargs)
|
140 |
-
|
141 |
-
model.eval()
|
142 |
-
# Ensure a valid pad_token_id is set; some OSS checkpoints reuse eos as pad
|
143 |
-
if getattr(model.config, "pad_token_id", None) is None:
|
144 |
-
model.config.pad_token_id = tokenizer.pad_token_id or tokenizer.eos_token_id
|
145 |
-
model.config.use_cache = True
|
146 |
-
print("[Model] Model loaded successfully")
|
147 |
-
return model
|
148 |
-
|
149 |
-
# -----------------------
|
150 |
-
# Harmony formatting
|
151 |
-
# -----------------------
|
152 |
-
|
153 |
-
def create_harmony_prompt(messages: List[Dict[str, str]], reasoning_effort: str = "high") -> Any:
|
154 |
-
"""Build a Harmony-formatted prompt. If Harmony is available, return **token IDs**
|
155 |
-
rendered by `openai_harmony` (authoritative). Otherwise fall back to the
|
156 |
-
tokenizer's chat template and return a string.
|
157 |
-
"""
|
158 |
-
if HARMONY_AVAILABLE and harmony_encoding is not None:
|
159 |
-
effort_map = {"low": ReasoningEffort.LOW, "medium": ReasoningEffort.MEDIUM, "high": ReasoningEffort.HIGH}
|
160 |
-
effort = effort_map.get(str(reasoning_effort).lower(), ReasoningEffort.HIGH)
|
161 |
-
|
162 |
-
system_content = (
|
163 |
-
SystemContent.new()
|
164 |
-
.with_model_identity("You are ChatGPT, a large language model trained by OpenAI.")
|
165 |
-
.with_reasoning_effort(effort)
|
166 |
-
.with_conversation_start_date(datetime.now().strftime("%Y-%m-%d"))
|
167 |
-
.with_knowledge_cutoff("2024-06")
|
168 |
-
.with_required_channels(REQUIRED_CHANNELS)
|
169 |
-
)
|
170 |
-
|
171 |
-
# Use first system message as developer instructions if present, else SYSTEM_DEF
|
172 |
-
sys_text = SYSTEM_DEF
|
173 |
-
rest: List[Dict[str, str]] = messages or []
|
174 |
-
if rest and rest[0].get("role") == "system":
|
175 |
-
sys_text = rest[0].get("content") or SYSTEM_DEF
|
176 |
-
rest = rest[1:]
|
177 |
-
|
178 |
-
harmony_messages = [Message.from_role_and_content(Role.SYSTEM, system_content)]
|
179 |
-
dev = DeveloperContent.new().with_instructions(sys_text)
|
180 |
-
harmony_messages.append(Message.from_role_and_content(Role.DEVELOPER, dev))
|
181 |
-
|
182 |
-
for m in rest:
|
183 |
-
role = m.get("role"); content = m.get("content", "")
|
184 |
-
if role == "user":
|
185 |
-
harmony_messages.append(Message.from_role_and_content(Role.USER, content))
|
186 |
-
elif role == "assistant":
|
187 |
-
harmony_messages.append(
|
188 |
-
Message.from_role_and_content(Role.ASSISTANT, content).with_channel("final")
|
189 |
-
)
|
190 |
-
|
191 |
-
convo = Conversation.from_messages(harmony_messages)
|
192 |
-
rendered = harmony_encoding.render_conversation_for_completion(convo, Role.ASSISTANT)
|
193 |
-
# Ensure assistant header includes a final channel + message start to avoid 'assistantassistant...' loops
|
194 |
-
try:
|
195 |
-
_tail = tokenizer.decode(list(rendered)[-64:], skip_special_tokens=False)
|
196 |
-
if '<|channel|>final<|message|>' not in _tail:
|
197 |
-
rendered = list(rendered) + tokenizer.encode('<|channel|>final<|message|>', add_special_tokens=False)
|
198 |
-
except Exception:
|
199 |
-
rendered = list(rendered)
|
200 |
-
return rendered
|
201 |
-
|
202 |
-
# Fallback: tokenizer chat template -> string prompt
|
203 |
-
if not messages or messages[0].get("role") != "system":
|
204 |
-
messages = [{"role": "system", "content": SYSTEM_DEF}] + (messages or [])
|
205 |
-
return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
|
206 |
-
|
207 |
-
def parse_harmony_response(tokens: List[int]) -> Dict[str, str]:
|
208 |
-
"""Parse response tokens using Harmony format to extract channels."""
|
209 |
-
if not HARMONY_AVAILABLE:
|
210 |
-
# Fallback: just decode and extract final channel manually
|
211 |
-
text = tokenizer.decode(tokens, skip_special_tokens=False)
|
212 |
-
return {"final": extract_final_channel_fallback(text), "raw": text}
|
213 |
-
|
214 |
-
# Parse messages from completion tokens
|
215 |
-
parsed_messages = harmony_encoding.parse_messages_from_completion_tokens(tokens, Role.ASSISTANT)
|
216 |
-
|
217 |
-
# Extract content by channel
|
218 |
-
channels = {}
|
219 |
-
for msg in parsed_messages:
|
220 |
-
channel = msg.channel if hasattr(msg, 'channel') else "final"
|
221 |
-
if channel not in channels:
|
222 |
-
channels[channel] = ""
|
223 |
-
channels[channel] += "".join([getattr(part, "text", str(part)) for part in (msg.content if isinstance(msg.content, list) else [msg.content])])
|
224 |
-
|
225 |
-
# Ensure we have a final channel
|
226 |
-
if "final" not in channels:
|
227 |
-
channels["final"] = " ".join(channels.values())
|
228 |
-
|
229 |
-
return channels
|
230 |
-
|
231 |
-
def extract_final_channel_fallback(text: str) -> str:
|
232 |
-
"""Robustly extract the <final> channel from decoded Harmony text.
|
233 |
-
Works even if parsing fails or the model emits extra headers.
|
234 |
-
"""
|
235 |
-
try:
|
236 |
-
chunks: Dict[str, str] = {}
|
237 |
-
pieces = text.split("<|channel|>")
|
238 |
-
for seg in pieces[1:]:
|
239 |
-
name_end = seg.find("<|message|>")
|
240 |
-
if name_end <= 0:
|
241 |
-
continue
|
242 |
-
ch = seg[:name_end].strip()
|
243 |
-
body_start = name_end + len("<|message|>")
|
244 |
-
# end at next channel/end/return marker
|
245 |
-
next_pos = len(seg)
|
246 |
-
for delim in ("<|channel|>", "<|end|>", "<|return|>"):
|
247 |
-
p = seg.find(delim, body_start)
|
248 |
-
if p != -1:
|
249 |
-
next_pos = min(next_pos, p)
|
250 |
-
body = seg[body_start:next_pos]
|
251 |
-
chunks[ch] = chunks.get(ch, "") + body
|
252 |
-
final_txt = (chunks.get("final", "").strip())
|
253 |
-
if final_txt:
|
254 |
-
return final_txt
|
255 |
-
# Fallback: everything after last final marker up to a terminator
|
256 |
-
if "<|channel|>final<|message|>" in text:
|
257 |
-
tail = text.split("<|channel|>final<|message|>")[-1]
|
258 |
-
for delim in ("<|return|>", "<|end|>", "<|channel|>"):
|
259 |
-
idx = tail.find(delim)
|
260 |
-
if idx != -1:
|
261 |
-
tail = tail[:idx]
|
262 |
-
break
|
263 |
-
return tail.strip()
|
264 |
-
except Exception:
|
265 |
-
pass
|
266 |
-
return text.strip()
|
267 |
|
268 |
-
|
269 |
-
|
270 |
-
|
|
|
|
|
|
|
|
|
271 |
|
272 |
-
def
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
for tok, w in mapping.items():
|
277 |
-
if tok is None:
|
278 |
-
continue
|
279 |
-
tid = tokenizer.convert_tokens_to_ids(tok)
|
280 |
if isinstance(tid, list):
|
281 |
for t in tid:
|
282 |
if isinstance(t, int) and t >= 0:
|
@@ -285,184 +78,71 @@ def build_bias_from_tokens(tokenizer, mapping: Dict[str, float]) -> torch.Tensor
|
|
285 |
bias[tid] += float(w)
|
286 |
return bias
|
287 |
|
288 |
-
class RoseGuidedLogits(torch.nn.Module):
|
289 |
-
def __init__(self, bias_vec: torch.Tensor, alpha: float = 1.0):
|
290 |
-
super().__init__()
|
291 |
-
self.bias_vec = bias_vec
|
292 |
-
self.alpha = float(alpha)
|
293 |
-
|
294 |
-
def forward(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
295 |
-
return scores + self.alpha * self.bias_vec.to(scores.device)
|
296 |
-
|
297 |
-
class StopOnTokens(StoppingCriteria):
|
298 |
-
def __init__(self, stop_ids: List[int]):
|
299 |
-
self.stop_ids = set(int(s) for s in (stop_ids or []))
|
300 |
-
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs):
|
301 |
-
return int(input_ids[0, -1]) in self.stop_ids
|
302 |
-
|
303 |
-
@spaces.GPU(duration=120)
|
304 |
-
def zerogpu_generate(full_prompt,
|
305 |
-
gen_kwargs: Dict[str, Any],
|
306 |
-
rose_map: Optional[Dict[str, float]],
|
307 |
-
rose_alpha: float,
|
308 |
-
rose_score: Optional[float],
|
309 |
-
seed: Optional[int]) -> Dict[str, str]:
|
310 |
-
"""Run inference on GPU and return parsed channels."""
|
311 |
-
try:
|
312 |
-
if seed is not None:
|
313 |
-
torch.manual_seed(int(seed))
|
314 |
-
|
315 |
-
# Load model
|
316 |
-
model = _load_model_on("auto")
|
317 |
-
|
318 |
-
# Setup logits processor for Rose guidance
|
319 |
-
logits_processor = None
|
320 |
-
if rose_map:
|
321 |
-
bias = build_bias_from_tokens(tokenizer, rose_map).to(next(model.parameters()).device)
|
322 |
-
eff_alpha = float(rose_alpha) * (float(rose_score) if rose_score is not None else 1.0)
|
323 |
-
logits_processor = [RoseGuidedLogits(bias, eff_alpha)]
|
324 |
-
|
325 |
-
# Tokenize / prepare inputs
|
326 |
-
device = next(model.parameters()).device
|
327 |
-
if HARMONY_AVAILABLE and not isinstance(full_prompt, str):
|
328 |
-
# Accept list/tuple or any iterable of ints from openai_harmony
|
329 |
-
try:
|
330 |
-
token_list = list(full_prompt)
|
331 |
-
except TypeError:
|
332 |
-
token_list = list(getattr(full_prompt, "ids", getattr(full_prompt, "token_ids", [])))
|
333 |
-
if not token_list:
|
334 |
-
raise ValueError("Harmony prompt produced no tokens")
|
335 |
-
input_ids = torch.tensor([token_list], dtype=torch.long, device=device)
|
336 |
-
attention_mask = torch.ones_like(input_ids, dtype=torch.long, device=device)
|
337 |
-
inputs = {"input_ids": input_ids, "attention_mask": attention_mask}
|
338 |
-
prompt_len = input_ids.shape[1]
|
339 |
-
else:
|
340 |
-
enc = tokenizer(full_prompt, return_tensors="pt")
|
341 |
-
inputs = {k: v.to(device) for k, v in enc.items()}
|
342 |
-
prompt_len = int(inputs["input_ids"].shape[1])
|
343 |
-
if "attention_mask" not in inputs:
|
344 |
-
inputs["attention_mask"] = torch.ones_like(inputs["input_ids"], dtype=torch.long, device=device)
|
345 |
-
|
346 |
-
# Prepare stopping
|
347 |
-
sc = None
|
348 |
-
if HARMONY_AVAILABLE and HARMONY_STOP_IDS:
|
349 |
-
sc = StoppingCriteriaList([StopOnTokens(HARMONY_STOP_IDS)])
|
350 |
-
|
351 |
-
# Generate
|
352 |
-
# Disallow degenerate header loops
|
353 |
-
bad_words_ids = None
|
354 |
-
try:
|
355 |
-
_B = []
|
356 |
-
for s in ("assistantassistant", "assistant", "<|assistant|>"):
|
357 |
-
ids = tokenizer.encode(s, add_special_tokens=False)
|
358 |
-
if ids:
|
359 |
-
_B.append(ids)
|
360 |
-
bad_words_ids = _B if _B else None
|
361 |
-
except Exception:
|
362 |
-
pass
|
363 |
-
|
364 |
-
out_ids = model.generate(
|
365 |
-
**inputs,
|
366 |
-
do_sample=bool(gen_kwargs.get("do_sample", True)),
|
367 |
-
temperature=float(gen_kwargs.get("temperature", 0.6)),
|
368 |
-
top_p=(float(gen_kwargs.get("top_p")) if gen_kwargs.get("top_p") is not None else None),
|
369 |
-
top_k=(int(gen_kwargs.get("top_k")) if gen_kwargs.get("top_k") else None),
|
370 |
-
max_new_tokens=int(gen_kwargs.get("max_new_tokens", MAX_DEF)),
|
371 |
-
pad_token_id=model.config.pad_token_id,
|
372 |
-
eos_token_id=tokenizer.eos_token_id,
|
373 |
-
repetition_penalty=float(gen_kwargs.get("repetition_penalty", 1.1)),
|
374 |
-
no_repeat_ngram_size=int(gen_kwargs.get("no_repeat_ngram_size", 6)),
|
375 |
-
logits_processor=logits_processor,
|
376 |
-
stopping_criteria=sc,
|
377 |
-
)
|
378 |
-
|
379 |
-
# Extract generated tokens only
|
380 |
-
out_list = out_ids[0].tolist()
|
381 |
-
gen_ids = out_list[prompt_len:]
|
382 |
-
# Truncate at first Harmony stop token if present
|
383 |
-
if HARMONY_AVAILABLE:
|
384 |
-
for sid in HARMONY_STOP_IDS:
|
385 |
-
if sid in gen_ids:
|
386 |
-
gen_ids = gen_ids[:gen_ids.index(sid)]
|
387 |
-
break
|
388 |
-
|
389 |
-
# Parse response with Harmony
|
390 |
-
if HARMONY_AVAILABLE:
|
391 |
-
try:
|
392 |
-
channels = parse_harmony_response(gen_ids)
|
393 |
-
except Exception:
|
394 |
-
# Fallback to text parsing if Harmony parser fails
|
395 |
-
decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
|
396 |
-
channels = {
|
397 |
-
"final": extract_final_channel_fallback(decoded),
|
398 |
-
"raw": decoded
|
399 |
-
}
|
400 |
-
else:
|
401 |
-
# Fallback decode + channels
|
402 |
-
decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
|
403 |
-
channels = {
|
404 |
-
"final": extract_final_channel_fallback(decoded),
|
405 |
-
"raw": decoded
|
406 |
-
}
|
407 |
-
|
408 |
-
return channels
|
409 |
-
|
410 |
-
except Exception as e:
|
411 |
-
return {"final": f"[Error] {type(e).__name__}: {str(e)}", "raw": str(e)}
|
412 |
-
finally:
|
413 |
-
# Cleanup
|
414 |
-
try:
|
415 |
-
del model
|
416 |
-
except:
|
417 |
-
pass
|
418 |
-
gc.collect()
|
419 |
-
if torch.cuda.is_available():
|
420 |
-
torch.cuda.empty_cache()
|
421 |
-
|
422 |
# -----------------------
|
423 |
-
#
|
424 |
# -----------------------
|
425 |
@spaces.GPU(duration=120)
|
426 |
-
def
|
427 |
-
|
428 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
429 |
model = None
|
430 |
try:
|
431 |
if seed is not None:
|
432 |
torch.manual_seed(int(seed))
|
433 |
-
model = _load_model_on("auto")
|
434 |
-
device = next(model.parameters()).device
|
435 |
|
436 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
437 |
enc = tokenizer(prompt_str, return_tensors="pt")
|
438 |
inputs = {k: v.to(device) for k, v in enc.items()}
|
439 |
-
prompt_len = int(inputs["input_ids"].shape[1])
|
440 |
if "attention_mask" not in inputs:
|
441 |
inputs["attention_mask"] = torch.ones_like(inputs["input_ids"], dtype=torch.long, device=device)
|
|
|
442 |
|
443 |
-
#
|
444 |
logits_processor = None
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
logits_processor = [
|
449 |
|
450 |
-
|
451 |
**inputs,
|
452 |
-
do_sample=
|
453 |
-
temperature=float(
|
454 |
-
|
455 |
-
top_k=(int(gen_kwargs.get("top_k")) if gen_kwargs.get("top_k") else None),
|
456 |
-
max_new_tokens=int(gen_kwargs.get("max_new_tokens", MAX_DEF)),
|
457 |
pad_token_id=model.config.pad_token_id,
|
458 |
logits_processor=logits_processor,
|
459 |
)
|
460 |
-
|
461 |
-
new_ids =
|
462 |
-
text = tokenizer.decode(new_ids, skip_special_tokens=True)
|
463 |
-
return {"final": text}
|
464 |
except Exception as e:
|
465 |
-
return
|
466 |
finally:
|
467 |
try:
|
468 |
del model
|
@@ -473,345 +153,58 @@ def zerogpu_generate_simple(prompt_str: str, gen_kwargs: Dict[str, Any], rose_ma
|
|
473 |
torch.cuda.empty_cache()
|
474 |
|
475 |
# -----------------------
|
476 |
-
#
|
477 |
-
# -----------------------
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
prompt_len = input_ids.shape[1]
|
496 |
-
else:
|
497 |
-
enc = tokenizer(full_prompt, return_tensors="pt")
|
498 |
-
inputs = {k: v.to(device) for k, v in enc.items()}
|
499 |
-
if "attention_mask" not in inputs:
|
500 |
-
inputs["attention_mask"] = torch.ones_like(inputs["input_ids"], dtype=torch.long, device=device)
|
501 |
-
prompt_len = int(inputs["input_ids"].shape[1])
|
502 |
-
|
503 |
-
# Harmony stop via stopping criteria
|
504 |
-
sc = StoppingCriteriaList([StopOnTokens(HARMONY_STOP_IDS)]) if (HARMONY_AVAILABLE and HARMONY_STOP_IDS) else None
|
505 |
-
|
506 |
-
out_ids = model.generate(
|
507 |
-
**inputs,
|
508 |
-
do_sample=bool(gen_kwargs.get("do_sample", True)),
|
509 |
-
temperature=float(gen_kwargs.get("temperature", 0.7)),
|
510 |
-
top_p=float(gen_kwargs.get("top_p", 0.9)),
|
511 |
-
top_k=(int(gen_kwargs.get("top_k")) if gen_kwargs.get("top_k") and int(gen_kwargs.get("top_k")) > 0 else None),
|
512 |
-
max_new_tokens=int(gen_kwargs.get("max_new_tokens", MAX_DEF)),
|
513 |
-
pad_token_id=model.config.pad_token_id,
|
514 |
-
eos_token_id=tokenizer.eos_token_id,
|
515 |
-
stopping_criteria=sc,
|
516 |
-
repetition_penalty=float(gen_kwargs.get("repetition_penalty", 1.15)),
|
517 |
-
no_repeat_ngram_size=int(gen_kwargs.get("no_repeat_ngram_size", 6)),
|
518 |
-
)
|
519 |
-
|
520 |
-
out_list = out_ids[0].tolist()
|
521 |
-
gen_ids = out_list[prompt_len:]
|
522 |
-
# Truncate at first Harmony stop token if present
|
523 |
-
if HARMONY_AVAILABLE and HARMONY_STOP_IDS:
|
524 |
-
for sid in HARMONY_STOP_IDS:
|
525 |
-
if sid in gen_ids:
|
526 |
-
gen_ids = gen_ids[:gen_ids.index(sid)]
|
527 |
-
break
|
528 |
-
|
529 |
-
# Parse channels
|
530 |
-
if HARMONY_AVAILABLE:
|
531 |
-
try:
|
532 |
-
channels = parse_harmony_response(gen_ids)
|
533 |
-
except Exception:
|
534 |
-
decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
|
535 |
-
channels = {"final": extract_final_channel_fallback(decoded), "raw": decoded}
|
536 |
-
else:
|
537 |
-
decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
|
538 |
-
channels = {"final": extract_final_channel_fallback(decoded), "raw": decoded}
|
539 |
-
|
540 |
-
# Small previews (avoid flooding logs/UI)
|
541 |
-
preview = {
|
542 |
-
"prompt_len": int(prompt_len),
|
543 |
-
"stop_ids": list(HARMONY_STOP_IDS) if HARMONY_AVAILABLE else [],
|
544 |
-
"gen_len": int(len(gen_ids)),
|
545 |
-
"gen_ids_head": gen_ids[:48],
|
546 |
-
"decoded_head": tokenizer.decode(gen_ids[:256], skip_special_tokens=False),
|
547 |
-
"channels": channels,
|
548 |
-
}
|
549 |
-
return preview
|
550 |
-
except Exception as e:
|
551 |
-
return {"error": f"{type(e).__name__}: {e}"}
|
552 |
-
finally:
|
553 |
-
try:
|
554 |
-
del model
|
555 |
-
except Exception:
|
556 |
-
pass
|
557 |
-
gc.collect()
|
558 |
-
if torch.cuda.is_available():
|
559 |
-
torch.cuda.empty_cache()
|
560 |
-
|
561 |
-
# -----------------------
|
562 |
-
# Gradio handlers
|
563 |
-
# -----------------------
|
564 |
-
|
565 |
-
def generate_response(message: str, history: List[List[str]], system_prompt: str,
|
566 |
-
temperature: float, top_p: float, top_k: int, max_new_tokens: int,
|
567 |
-
do_sample: bool, seed: Optional[int],
|
568 |
-
rose_enable: bool, rose_alpha: float, rose_score: Optional[float],
|
569 |
-
rose_tokens: str, rose_json: str,
|
570 |
-
show_thinking: bool = False,
|
571 |
-
simple_mode: bool = True, # NEW: default to simple chat_template path
|
572 |
-
reasoning_effort: str = "high") -> str:
|
573 |
-
"""
|
574 |
-
Generate response with proper CoT handling using Harmony format.
|
575 |
-
"""
|
576 |
-
try:
|
577 |
-
# Build messages robustly for Gradio type='messages' or legacy tuple format
|
578 |
-
messages = [{"role": "system", "content": system_prompt or SYSTEM_DEF}]
|
579 |
-
|
580 |
-
# Add prior turns
|
581 |
-
if history:
|
582 |
-
if isinstance(history, list) and history and isinstance(history[0], dict):
|
583 |
-
# history is already a flat list of {'role','content'} dicts
|
584 |
-
for m in history:
|
585 |
-
role = m.get("role")
|
586 |
-
content = m.get("content", "")
|
587 |
-
if role in ("user", "assistant"):
|
588 |
-
messages.append({"role": role, "content": str(content)})
|
589 |
-
else:
|
590 |
-
for turn in history:
|
591 |
-
if isinstance(turn, (list, tuple)) and len(turn) >= 2:
|
592 |
-
u, a = turn[0], turn[1]
|
593 |
-
if u:
|
594 |
-
messages.append({"role": "user", "content": str(u)})
|
595 |
-
if a:
|
596 |
-
messages.append({"role": "assistant", "content": str(a)})
|
597 |
-
|
598 |
-
# Current user message
|
599 |
-
if isinstance(message, dict):
|
600 |
-
user_text = message.get("content", "")
|
601 |
-
else:
|
602 |
-
user_text = str(message)
|
603 |
-
messages.append({"role": "user", "content": user_text})
|
604 |
-
|
605 |
-
# FAST PATH: simple chat_template prompt (recommended)
|
606 |
-
if simple_mode:
|
607 |
-
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
|
608 |
-
# Harmony path (optional)
|
609 |
-
elif HARMONY_AVAILABLE:
|
610 |
-
prompt = create_harmony_prompt(messages, reasoning_effort) # returns token IDs
|
611 |
-
else:
|
612 |
-
# Fallback to tokenizer template (string)
|
613 |
-
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
|
614 |
-
|
615 |
-
# Build Rose map if enabled
|
616 |
-
rose_map: Optional[Dict[str, float]] = None
|
617 |
-
if rose_enable:
|
618 |
-
rose_map = {}
|
619 |
-
tok_str = (rose_tokens or "").strip()
|
620 |
-
if tok_str:
|
621 |
-
for p in [p.strip() for p in tok_str.split(",") if p.strip()]:
|
622 |
-
if ":" in p:
|
623 |
-
k, v = p.split(":", 1)
|
624 |
-
try:
|
625 |
-
rose_map[k.strip()] = float(v)
|
626 |
-
except:
|
627 |
-
pass
|
628 |
-
if rose_json:
|
629 |
-
try:
|
630 |
-
j = json.loads(rose_json)
|
631 |
-
if isinstance(j, dict):
|
632 |
-
for k, v in j.items():
|
633 |
-
try:
|
634 |
-
rose_map[str(k)] = float(v)
|
635 |
-
except:
|
636 |
-
pass
|
637 |
-
except:
|
638 |
-
pass
|
639 |
-
if not rose_map:
|
640 |
-
rose_map = None
|
641 |
-
|
642 |
-
# Generate with model
|
643 |
-
if simple_mode:
|
644 |
-
channels = zerogpu_generate_simple(
|
645 |
-
prompt,
|
646 |
-
{
|
647 |
-
"do_sample": bool(do_sample),
|
648 |
-
"temperature": float(temperature),
|
649 |
-
"top_p": float(top_p) if top_p is not None else None,
|
650 |
-
"top_k": int(top_k) if top_k > 0 else None,
|
651 |
-
"max_new_tokens": int(max_new_tokens),
|
652 |
-
},
|
653 |
-
rose_map,
|
654 |
-
float(rose_alpha),
|
655 |
-
float(rose_score) if rose_score is not None else None,
|
656 |
-
int(seed) if seed is not None else None,
|
657 |
-
)
|
658 |
-
else:
|
659 |
-
channels = zerogpu_generate(
|
660 |
-
prompt,
|
661 |
-
{
|
662 |
-
"do_sample": bool(do_sample),
|
663 |
-
"temperature": float(temperature),
|
664 |
-
"top_p": float(top_p),
|
665 |
-
"top_k": int(top_k) if top_k > 0 else None,
|
666 |
-
"max_new_tokens": int(max_new_tokens),
|
667 |
-
},
|
668 |
-
rose_map,
|
669 |
-
float(rose_alpha),
|
670 |
-
float(rose_score) if rose_score is not None else None,
|
671 |
-
int(seed) if seed is not None else None,
|
672 |
-
)
|
673 |
-
|
674 |
-
# Format response
|
675 |
-
if show_thinking:
|
676 |
-
# Show all channels
|
677 |
-
response = "## Chain of Thought:\n\n"
|
678 |
-
for channel, content in channels.items():
|
679 |
-
if channel != "final" and content:
|
680 |
-
response += f"### {channel.capitalize()} Channel:\n{content}\n\n"
|
681 |
-
response += f"### Final Response:\n{channels.get('final', 'No final response generated')}"
|
682 |
-
return response
|
683 |
-
else:
|
684 |
-
# Just show the final response
|
685 |
-
return channels.get("final", "No final response generated")
|
686 |
-
|
687 |
-
except Exception as e:
|
688 |
-
return f"[Error] {type(e).__name__}: {str(e)}"
|
689 |
|
690 |
-
# -----------------------
|
691 |
-
# Extra handler: Harmony Inspector wrapper
|
692 |
-
# -----------------------
|
693 |
|
694 |
-
def
|
695 |
try:
|
696 |
-
msgs =
|
697 |
-
prompt =
|
698 |
-
return
|
699 |
-
prompt,
|
700 |
-
{"do_sample": True, "temperature": 0.7, "top_p": 0.9, "top_k": 0, "max_new_tokens": MAX_DEF}
|
701 |
-
)
|
702 |
except Exception as e:
|
703 |
-
return
|
704 |
|
705 |
-
# -----------------------
|
706 |
-
# UI
|
707 |
-
# -----------------------
|
708 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
709 |
-
gr.Markdown(
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
""
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
with gr.Accordion("Generation Settings ", open=False):
|
728 |
-
# NEW: toggle to bypass Harmony and use plain chat_template like your minimal script
|
729 |
-
simple_mode = gr.Checkbox(
|
730 |
-
value=True,
|
731 |
-
label="Use simple chat_template (no Harmony)",
|
732 |
-
info="Matches the minimal HF example; safest path for now"
|
733 |
-
)
|
734 |
-
with gr.Row():
|
735 |
-
temperature = gr.Slider(0.0, 2.0, value=0.7, step=0.05, label="Temperature")
|
736 |
-
top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.01, label="Top-p")
|
737 |
-
top_k = gr.Slider(0, 200, value=0, step=1, label="Top-k (0=disabled)")
|
738 |
-
with gr.Row():
|
739 |
-
max_new = gr.Slider(16, 4096, value=MAX_DEF, step=16, label="Max new tokens")
|
740 |
-
do_sample = gr.Checkbox(value=True, label="Do sample")
|
741 |
-
seed = gr.Number(value=None, label="Seed (optional)", precision=0)
|
742 |
-
with gr.Row():
|
743 |
-
reasoning_effort = gr.Radio(
|
744 |
-
choices=["low", "medium", "high"],
|
745 |
-
value="high",
|
746 |
-
label="Reasoning Effort",
|
747 |
-
info="How much thinking the model should do"
|
748 |
-
)
|
749 |
-
show_thinking = gr.Checkbox(
|
750 |
-
value=False,
|
751 |
-
label="Show thinking channels",
|
752 |
-
info="Display all internal reasoning channels"
|
753 |
-
)
|
754 |
-
|
755 |
-
with gr.Accordion("Rose Guidance (Optional)", open=False):
|
756 |
-
gr.Markdown("Fine-tune generation with token biases")
|
757 |
-
with gr.Row():
|
758 |
-
rose_enable = gr.Checkbox(value=False, label="Enable Rose bias")
|
759 |
-
rose_alpha = gr.Slider(0.0, 5.0, value=1.0, step=0.05, label="Alpha (strength)")
|
760 |
-
rose_score = gr.Slider(0.0, 1.0, value=1.0, step=0.01, label="Score multiplier")
|
761 |
-
rose_tokens = gr.Textbox(
|
762 |
-
label="Token:weight pairs",
|
763 |
-
placeholder="example:1.5, test:-0.5",
|
764 |
-
value=""
|
765 |
-
)
|
766 |
-
rose_json = gr.Textbox(
|
767 |
-
label="JSON weights",
|
768 |
-
placeholder='{"token": 1.0, "another": -0.5}',
|
769 |
-
value=""
|
770 |
-
)
|
771 |
-
|
772 |
-
# --- Harmony Inspector UI ---
|
773 |
-
with gr.Accordion("Harmony Inspector", open=False):
|
774 |
-
debug_prompt = gr.Textbox(label="Debug prompt", value="What is 2+2? Reply with just the number.")
|
775 |
-
run_debug = gr.Button("Run Harmony Inspect")
|
776 |
-
debug_out = gr.JSON(label="Parsed Harmony output", value={})
|
777 |
-
run_debug.click(harmony_inspect_handler, inputs=[debug_prompt, system_prompt, reasoning_effort], outputs=[debug_out])
|
778 |
-
|
779 |
-
# Chat interface - using only valid parameters
|
780 |
-
chat = gr.ChatInterface(
|
781 |
-
fn=generate_response,
|
782 |
type="messages",
|
783 |
-
additional_inputs=[
|
784 |
-
|
785 |
-
do_sample, seed, rose_enable, rose_alpha, rose_score,
|
786 |
-
rose_tokens, rose_json, show_thinking, simple_mode, reasoning_effort
|
787 |
-
],
|
788 |
-
title="Chat with Mirel",
|
789 |
-
description="A chain-of-thought model using Harmony format",
|
790 |
-
examples=[
|
791 |
-
["Hello! Can you introduce yourself?"],
|
792 |
-
["What is the capital of France?"],
|
793 |
-
["Explain quantum computing in simple terms"],
|
794 |
-
["Solve: If a train travels 120 miles in 2 hours, what is its average speed?"],
|
795 |
-
],
|
796 |
cache_examples=False,
|
797 |
)
|
798 |
|
799 |
-
gr.Markdown(
|
800 |
-
"""
|
801 |
-
---
|
802 |
-
### Configuration:
|
803 |
-
- **Model**: Set `MODEL_ID` env var (default: openai/gpt-oss-20b)
|
804 |
-
- **Adapter**: Set `ADAPTER_ID` and optionally `ADAPTER_SUBFOLDER`
|
805 |
-
- **Auth**: Set `HF_TOKEN` in Space secrets for private model access
|
806 |
-
- **Harmony**: Install with `pip install openai-harmony` for proper channel support
|
807 |
-
|
808 |
-
The model uses Harmony format with thinking channels (`thinking`, `analysis`, `final`).
|
809 |
-
"""
|
810 |
-
)
|
811 |
-
|
812 |
if __name__ == "__main__":
|
813 |
-
demo.queue(max_size=
|
814 |
-
server_name="0.0.0.0",
|
815 |
-
server_port=7860,
|
816 |
-
share=False
|
817 |
-
)
|
|
|
1 |
"""
|
2 |
+
Mirel – Minimal Rose LoRA Inference (HF Space)
|
3 |
+
ZeroGPU-only, no Harmony, no extra config
|
|
|
4 |
Single file: app.py
|
5 |
"""
|
6 |
from __future__ import annotations
|
7 |
+
import os, gc, json, torch
|
8 |
+
from typing import Optional, Dict, Any, List
|
|
|
|
|
9 |
import gradio as gr
|
10 |
+
import spaces
|
11 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# -----------------------
|
14 |
+
# Constants / Env
|
15 |
# -----------------------
|
16 |
+
MODEL_ID = os.getenv("MODEL_ID", "openai/gpt-oss-20b")
|
17 |
+
# Default to your Rose LoRA
|
18 |
+
ADAPTER_ID = os.getenv("ADAPTER_ID", "AbstractPhil/mirel-gpt-oss-20b")
|
19 |
+
ADAPTER_SUBFOLDER = os.getenv("ADAPTER_SUBFOLDER", "checkpoints/checkpoint-516")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
HF_TOKEN: Optional[str] = (
|
21 |
+
os.getenv("HF_TOKEN")
|
22 |
+
or os.getenv("HUGGING_FACE_HUB_TOKEN")
|
23 |
or os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
24 |
or os.getenv("HF_ACCESS_TOKEN")
|
25 |
)
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
28 |
|
29 |
+
# Tokenizer is lightweight; OK to load on CPU at import time
|
30 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True, token=HF_TOKEN)
|
31 |
+
if tokenizer.pad_token_id is None:
|
32 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
# -----------------------
|
35 |
+
# Rose helpers
|
36 |
# -----------------------
|
37 |
+
def _parse_rose_inputs(rose_tokens: str, rose_json: str) -> Optional[Dict[str, float]]:
|
38 |
+
"""Merge "token:weight, ..." and JSON {token: weight} into a dict."""
|
39 |
+
mapping: Dict[str, float] = {}
|
40 |
+
if rose_tokens:
|
41 |
+
for part in [p.strip() for p in rose_tokens.split(",") if p.strip()]:
|
42 |
+
if ":" in part:
|
43 |
+
k, v = part.split(":", 1)
|
44 |
+
try:
|
45 |
+
mapping[k.strip()] = float(v)
|
46 |
+
except Exception:
|
47 |
+
pass
|
48 |
+
if rose_json:
|
|
|
|
|
|
|
|
|
|
|
49 |
try:
|
50 |
+
j = json.loads(rose_json)
|
51 |
+
if isinstance(j, dict):
|
52 |
+
for k, v in j.items():
|
53 |
+
try:
|
54 |
+
mapping[str(k)] = float(v)
|
55 |
+
except Exception:
|
56 |
+
pass
|
57 |
except Exception:
|
58 |
pass
|
59 |
+
return mapping or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
+
class _RoseLogits(torch.nn.Module):
|
62 |
+
def __init__(self, bias_vec: torch.Tensor, alpha: float = 1.0):
|
63 |
+
super().__init__()
|
64 |
+
self.bias_vec = bias_vec
|
65 |
+
self.alpha = float(alpha)
|
66 |
+
def forward(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
67 |
+
return scores + self.alpha * self.bias_vec.to(scores.device)
|
68 |
|
69 |
+
def _bias_from_tokens(tok, mapping: Dict[str, float]) -> torch.Tensor:
|
70 |
+
bias = torch.zeros(len(tok), dtype=torch.float32)
|
71 |
+
for s, w in mapping.items():
|
72 |
+
tid = tok.convert_tokens_to_ids(s)
|
|
|
|
|
|
|
|
|
73 |
if isinstance(tid, list):
|
74 |
for t in tid:
|
75 |
if isinstance(t, int) and t >= 0:
|
|
|
78 |
bias[tid] += float(w)
|
79 |
return bias
|
80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
# -----------------------
|
82 |
+
# ZeroGPU inference (GPU work ONLY inside this function)
|
83 |
# -----------------------
|
84 |
@spaces.GPU(duration=120)
|
85 |
+
def gpu_generate(prompt_str: str,
|
86 |
+
temperature: float,
|
87 |
+
max_new_tokens: int,
|
88 |
+
rose_tokens: str,
|
89 |
+
rose_json: str,
|
90 |
+
rose_alpha: float,
|
91 |
+
seed: Optional[int]) -> str:
|
92 |
+
"""Run a single completion on GPU and return only the generated text.
|
93 |
+
No Harmony. Uses chat template; slices completion by prompt length.
|
94 |
+
"""
|
95 |
+
torch.set_grad_enabled(False)
|
96 |
model = None
|
97 |
try:
|
98 |
if seed is not None:
|
99 |
torch.manual_seed(int(seed))
|
|
|
|
|
100 |
|
101 |
+
from peft import PeftModel
|
102 |
+
# Load base model on GPU via accelerate's device_map
|
103 |
+
model = AutoModelForCausalLM.from_pretrained(
|
104 |
+
MODEL_ID,
|
105 |
+
device_map="auto",
|
106 |
+
torch_dtype="auto",
|
107 |
+
trust_remote_code=True,
|
108 |
+
low_cpu_mem_usage=True,
|
109 |
+
token=HF_TOKEN,
|
110 |
+
)
|
111 |
+
if ADAPTER_ID:
|
112 |
+
peft_kwargs: Dict[str, Any] = {"is_trainable": False, "token": HF_TOKEN}
|
113 |
+
if ADAPTER_SUBFOLDER:
|
114 |
+
peft_kwargs["subfolder"] = ADAPTER_SUBFOLDER
|
115 |
+
model = PeftModel.from_pretrained(model, ADAPTER_ID, **peft_kwargs)
|
116 |
+
model.eval()
|
117 |
+
if getattr(model.config, "pad_token_id", None) is None:
|
118 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
119 |
+
|
120 |
+
device = next(model.parameters()).device
|
121 |
enc = tokenizer(prompt_str, return_tensors="pt")
|
122 |
inputs = {k: v.to(device) for k, v in enc.items()}
|
|
|
123 |
if "attention_mask" not in inputs:
|
124 |
inputs["attention_mask"] = torch.ones_like(inputs["input_ids"], dtype=torch.long, device=device)
|
125 |
+
prompt_len = int(inputs["input_ids"].shape[1])
|
126 |
|
127 |
+
# Rose bias (optional)
|
128 |
logits_processor = None
|
129 |
+
mapping = _parse_rose_inputs(rose_tokens, rose_json)
|
130 |
+
if mapping:
|
131 |
+
bias = _bias_from_tokens(tokenizer, mapping).to(device)
|
132 |
+
logits_processor = [_RoseLogits(bias, float(rose_alpha))]
|
133 |
|
134 |
+
out = model.generate(
|
135 |
**inputs,
|
136 |
+
do_sample=True,
|
137 |
+
temperature=float(temperature),
|
138 |
+
max_new_tokens=int(max_new_tokens),
|
|
|
|
|
139 |
pad_token_id=model.config.pad_token_id,
|
140 |
logits_processor=logits_processor,
|
141 |
)
|
142 |
+
new_ids = out[0, prompt_len:]
|
143 |
+
return tokenizer.decode(new_ids, skip_special_tokens=True)
|
|
|
|
|
144 |
except Exception as e:
|
145 |
+
return f"[Error] {type(e).__name__}: {e}"
|
146 |
finally:
|
147 |
try:
|
148 |
del model
|
|
|
153 |
torch.cuda.empty_cache()
|
154 |
|
155 |
# -----------------------
|
156 |
+
# Gradio glue (no streaming; minimal controls)
|
157 |
+
# -----------------------
|
158 |
+
def _build_messages(message, history) -> List[Dict[str, str]]:
|
159 |
+
msgs: List[Dict[str, str]] = []
|
160 |
+
# Keep it simple: prepend a small system to steady tone
|
161 |
+
msgs.append({"role": "system", "content": "You are Mirel."})
|
162 |
+
if isinstance(history, list):
|
163 |
+
for m in history:
|
164 |
+
if isinstance(m, dict) and "role" in m:
|
165 |
+
msgs.append({"role": m["role"], "content": str(m.get("content", ""))})
|
166 |
+
elif isinstance(m, (list, tuple)) and len(m) >= 2:
|
167 |
+
u, a = m[0], m[1]
|
168 |
+
if u: msgs.append({"role": "user", "content": str(u)})
|
169 |
+
if a: msgs.append({"role": "assistant", "content": str(a)})
|
170 |
+
if isinstance(message, dict):
|
171 |
+
msgs.append({"role": message.get("role", "user"), "content": str(message.get("content", ""))})
|
172 |
+
else:
|
173 |
+
msgs.append({"role": "user", "content": str(message)})
|
174 |
+
return msgs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
175 |
|
|
|
|
|
|
|
176 |
|
177 |
+
def ui_generate(message, history, temperature, max_new_tokens, rose_alpha, rose_tokens, rose_json, seed):
|
178 |
try:
|
179 |
+
msgs = _build_messages(message, history)
|
180 |
+
prompt = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
|
181 |
+
return gpu_generate(prompt, float(temperature), int(max_new_tokens), rose_tokens or "", rose_json or "", float(rose_alpha), int(seed) if seed is not None else None)
|
|
|
|
|
|
|
182 |
except Exception as e:
|
183 |
+
return f"[Error] {type(e).__name__}: {e}"
|
184 |
|
|
|
|
|
|
|
185 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
186 |
+
gr.Markdown("""
|
187 |
+
# Mirel – Rose LoRA Inference (ZeroGPU)
|
188 |
+
Minimal chat using your Rose LoRA adapter. No Harmony. GPU work runs under ZeroGPU.
|
189 |
+
""")
|
190 |
+
|
191 |
+
with gr.Accordion("Generation", open=True):
|
192 |
+
temperature = gr.Slider(0.0, 2.0, value=0.6, step=0.05, label="Temperature")
|
193 |
+
max_new = gr.Slider(16, 2048, value=512, step=8, label="Max new tokens")
|
194 |
+
seed = gr.Number(value=None, label="Seed (optional)", precision=0)
|
195 |
+
|
196 |
+
with gr.Accordion("Rose guidance", open=False):
|
197 |
+
rose_alpha = gr.Slider(0.0, 5.0, value=1.0, step=0.05, label="Alpha (strength)")
|
198 |
+
rose_tokens = gr.Textbox(label="token:weight comma list", placeholder="e.g. reason:1.2, simple:-0.4", value="")
|
199 |
+
rose_json = gr.Textbox(label="JSON {token: weight}", placeholder='{"reason": 1.0, "ramble": -0.8}', value="")
|
200 |
+
|
201 |
+
gr.ChatInterface(
|
202 |
+
fn=ui_generate,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
type="messages",
|
204 |
+
additional_inputs=[temperature, max_new, rose_alpha, rose_tokens, rose_json, seed],
|
205 |
+
title="Mirel",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
cache_examples=False,
|
207 |
)
|
208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
if __name__ == "__main__":
|
210 |
+
demo.queue(max_size=16).launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|