AbstractPhil commited on
Commit
ae231bc
·
1 Parent(s): 2a83e65

probably works-ish

Browse files
Files changed (1) hide show
  1. app.py +702 -71
app.py CHANGED
@@ -1,97 +1,728 @@
 
 
 
 
 
 
1
  from __future__ import annotations
2
- import os, gc, torch
3
- from typing import Optional, Dict, Any, List
 
 
4
  import gradio as gr
5
- import spaces
6
- from transformers import AutoTokenizer, AutoModelForCausalLM
7
- from peft import PeftModel
8
 
9
- MODEL_ID = "openai/gpt-oss-20b"
10
- ADAPTER_ID = "AbstractPhil/mirel-gpt-oss-20b"
11
- ADAPTER_SUBFOLDER = "checkpoints/checkpoint-516"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  HF_TOKEN: Optional[str] = (
13
- os.getenv("HF_TOKEN")
14
- or os.getenv("HUGGING_FACE_HUB_TOKEN")
15
  or os.getenv("HUGGINGFACEHUB_API_TOKEN")
16
  or os.getenv("HF_ACCESS_TOKEN")
17
  )
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
20
 
21
- # Load tokenizer on CPU
22
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True, token=HF_TOKEN)
23
- if tokenizer.pad_token_id is None:
24
- tokenizer.pad_token_id = tokenizer.eos_token_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  @spaces.GPU(duration=120)
27
- def gpu_generate(prompt_str: str, max_new_tokens: int = 512) -> str:
28
- torch.set_grad_enabled(False)
29
- model = None
 
 
 
 
30
  try:
31
- model_kwargs = dict(
32
- attn_implementation="eager",
33
- torch_dtype="auto",
34
- use_cache=True,
35
- device_map="auto",
36
- trust_remote_code=True,
37
- low_cpu_mem_usage=True,
38
- token=HF_TOKEN,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  )
40
- model = AutoModelForCausalLM.from_pretrained(MODEL_ID, **model_kwargs)
41
- # Apply Rose LoRA (minimal)
42
- if ADAPTER_ID:
43
- peft_kwargs: Dict[str, Any] = {"is_trainable": False, "token": HF_TOKEN}
44
- if ADAPTER_SUBFOLDER:
45
- peft_kwargs["subfolder"] = ADAPTER_SUBFOLDER
46
- model = PeftModel.from_pretrained(model, ADAPTER_ID, **peft_kwargs)
47
- model = model.merge_and_unload()
48
- model.eval()
49
- model.config.pad_token_id = tokenizer.pad_token_id
50
-
51
- enc = tokenizer(prompt_str, return_tensors="pt")
52
- input_ids = enc["input_ids"].to(model.device)
53
- attention_mask = (input_ids != tokenizer.pad_token_id).long().to(model.device)
54
-
55
- prompt_len = input_ids.shape[-1]
56
- output_ids = model.generate(
57
- input_ids=input_ids,
58
- attention_mask=attention_mask,
59
- max_new_tokens=max_new_tokens,
60
- pad_token_id=tokenizer.pad_token_id,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  )
62
- new_ids = output_ids[0, prompt_len:]
63
- return tokenizer.decode(new_ids, skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  except Exception as e:
65
- return f"[Error] {type(e).__name__}: {e}"
66
  finally:
67
- del model
 
 
 
68
  gc.collect()
69
  if torch.cuda.is_available():
70
  torch.cuda.empty_cache()
71
 
72
- def ui_generate(message, history):
73
- msgs: List[Dict[str, str]] = []
74
- if isinstance(history, list):
75
- for m in history:
76
- if isinstance(m, dict) and "role" in m:
77
- msgs.append(m)
78
- elif isinstance(m, (list, tuple)) and len(m) >= 2:
79
- if m[0]:
80
- msgs.append({"role": "user", "content": str(m[0])})
81
- if m[1]:
82
- msgs.append({"role": "assistant", "content": str(m[1])})
83
- if isinstance(message, dict):
84
- msgs.append(message)
85
- else:
86
- msgs.append({"role": "user", "content": str(message)})
87
 
88
- prompt = tokenizer.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False)
89
- return gpu_generate(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
92
- gr.Markdown("""# Mirel – GPT‑OSS‑20B + Rose LoRA (ZeroGPU, Minimal)""")
93
- gr.ChatInterface(fn=ui_generate, type="messages", title="Mirel", cache_examples=False)
 
 
 
 
 
 
 
 
94
 
95
- if __name__ == "__main__":
96
- demo.queue().launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mirel Harmony Inference – HF Space (Gradio)
3
+ ZeroGPU-ready, Harmony formatting, optional Rose-guided decoding
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, threading, torch
9
+ from dataclasses import dataclass
10
+ from typing import List, Dict, Optional, Any
11
+ from datetime import datetime
12
  import gradio as gr
13
+ import spaces # required for ZeroGPU
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria, StoppingCriteriaList
 
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
+ # Config & runtime modes
36
+ # -----------------------
37
+ DTYPE_MAP = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}
38
+
39
+ MODEL_ID = os.getenv("MODEL_ID", "openai/gpt-oss-20b")
40
+ ADAPTER_ID = os.getenv("ADAPTER_ID") or None
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 before loading any models
77
+ _hf_login()
78
+
79
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
80
 
81
+ # Load Harmony encoding if available
82
+ if HARMONY_AVAILABLE:
83
+ harmony_encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
84
+ else:
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
+ # Model loading
100
+ # -----------------------
101
+ try:
102
+ from peft import PeftModel
103
+ _HAS_PEFT = True
104
+ except Exception:
105
+ _HAS_PEFT = False
106
+
107
+
108
+ def _build_model_kwargs(device_map: Optional[str]) -> Dict[str, Any]:
109
+ kw: Dict[str, Any] = dict(
110
+ torch_dtype=DTYPE,
111
+ device_map=device_map,
112
+ attn_implementation=ATTN_IMPL if device_map != "cpu" else "eager",
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
+ import bitsandbytes as _bnb
120
+ kw.update(load_in_4bit=True)
121
+ if kw["device_map"] is None:
122
+ kw["device_map"] = "auto"
123
+ except Exception:
124
+ pass
125
+ return kw
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
+ # Rose guidance
270
+ # -----------------------
271
+
272
+ def build_bias_from_tokens(tokenizer, mapping: Dict[str, float]) -> torch.Tensor:
273
+ """Create vocab bias from {token: weight}."""
274
+ vocab_size = len(tokenizer)
275
+ bias = torch.zeros(vocab_size, dtype=torch.float32)
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:
283
+ bias[t] += float(w) / max(1, len(tid))
284
+ elif isinstance(tid, int) and t >= 0:
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.7)),
368
+ top_p=float(gen_kwargs.get("top_p", 0.9)),
369
+ top_k=(int(gen_kwargs.get("top_k")) if gen_kwargs.get("top_k") and int(gen_kwargs.get("top_k")) > 0 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
+ bad_words_ids=bad_words_ids,
374
+ logits_processor=logits_processor,
375
+ repetition_penalty=float(gen_kwargs.get("repetition_penalty", 1.2)),
376
+ no_repeat_ngram_size=int(gen_kwargs.get("no_repeat_ngram_size", 8)),
377
+ stopping_criteria=sc,
378
  )
379
+
380
+ # Extract generated tokens only
381
+ out_list = out_ids[0].tolist()
382
+ gen_ids = out_list[prompt_len:]
383
+ # Truncate at first Harmony stop token if present
384
+ if HARMONY_AVAILABLE:
385
+ for sid in HARMONY_STOP_IDS:
386
+ if sid in gen_ids:
387
+ gen_ids = gen_ids[:gen_ids.index(sid)]
388
+ break
389
+
390
+ # Parse response with Harmony
391
+ if HARMONY_AVAILABLE:
392
+ try:
393
+ channels = parse_harmony_response(gen_ids)
394
+ except Exception:
395
+ # Fallback to text parsing if Harmony parser fails
396
+ decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
397
+ channels = {
398
+ "final": extract_final_channel_fallback(decoded),
399
+ "raw": decoded
400
+ }
401
+ else:
402
+ # Fallback decode + channels
403
+ decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
404
+ channels = {
405
+ "final": extract_final_channel_fallback(decoded),
406
+ "raw": decoded
407
+ }
408
+
409
+ return channels
410
+
411
+ except Exception as e:
412
+ return {"final": f"[Error] {type(e).__name__}: {str(e)}", "raw": str(e)}
413
+ finally:
414
+ # Cleanup
415
+ try:
416
+ del model
417
+ except:
418
+ pass
419
+ gc.collect()
420
+ if torch.cuda.is_available():
421
+ torch.cuda.empty_cache()
422
+
423
+ # -----------------------
424
+ # GPU Debug: Harmony Inspector
425
+ # -----------------------
426
+ @spaces.GPU(duration=120)
427
+ def zerogpu_generate_debug(full_prompt, gen_kwargs: Dict[str, Any]) -> Dict[str, Any]:
428
+ """Minimal GPU path to run a single prompt and return Harmony-parsed output
429
+ along with short token previews for debugging. Does not use Rose for clarity."""
430
+ model = None
431
+ try:
432
+ model = _load_model_on("auto")
433
+ device = next(model.parameters()).device
434
+
435
+ # Prepare inputs (tokens if Harmony renderer used, else string -> encode)
436
+ if HARMONY_AVAILABLE and not isinstance(full_prompt, str):
437
+ token_list = list(full_prompt)
438
+ if not token_list:
439
+ raise ValueError("Harmony prompt produced no tokens")
440
+ input_ids = torch.tensor([token_list], dtype=torch.long, device=device)
441
+ attention_mask = torch.ones_like(input_ids, dtype=torch.long, device=device)
442
+ inputs = {"input_ids": input_ids, "attention_mask": attention_mask}
443
+ prompt_len = input_ids.shape[1]
444
+ else:
445
+ enc = tokenizer(full_prompt, return_tensors="pt")
446
+ inputs = {k: v.to(device) for k, v in enc.items()}
447
+ if "attention_mask" not in inputs:
448
+ inputs["attention_mask"] = torch.ones_like(inputs["input_ids"], dtype=torch.long, device=device)
449
+ prompt_len = int(inputs["input_ids"].shape[1])
450
+
451
+ # Harmony stop via stopping criteria
452
+ sc = StoppingCriteriaList([StopOnTokens(HARMONY_STOP_IDS)]) if (HARMONY_AVAILABLE and HARMONY_STOP_IDS) else None
453
+
454
+ out_ids = model.generate(
455
+ **inputs,
456
+ do_sample=bool(gen_kwargs.get("do_sample", True)),
457
+ temperature=float(gen_kwargs.get("temperature", 0.7)),
458
+ top_p=float(gen_kwargs.get("top_p", 0.9)),
459
+ top_k=(int(gen_kwargs.get("top_k")) if gen_kwargs.get("top_k") and int(gen_kwargs.get("top_k")) > 0 else None),
460
+ max_new_tokens=int(gen_kwargs.get("max_new_tokens", MAX_DEF)),
461
+ pad_token_id=model.config.pad_token_id,
462
+ eos_token_id=tokenizer.eos_token_id,
463
+ bad_words_ids=bad_words_ids,
464
+ stopping_criteria=sc,
465
+ repetition_penalty=float(gen_kwargs.get("repetition_penalty", 1.15)),
466
+ no_repeat_ngram_size=int(gen_kwargs.get("no_repeat_ngram_size", 6)),
467
  )
468
+
469
+ out_list = out_ids[0].tolist()
470
+ gen_ids = out_list[prompt_len:]
471
+ # Truncate at first Harmony stop token if present
472
+ if HARMONY_AVAILABLE and HARMONY_STOP_IDS:
473
+ for sid in HARMONY_STOP_IDS:
474
+ if sid in gen_ids:
475
+ gen_ids = gen_ids[:gen_ids.index(sid)]
476
+ break
477
+
478
+ # Parse channels
479
+ if HARMONY_AVAILABLE:
480
+ try:
481
+ channels = parse_harmony_response(gen_ids)
482
+ except Exception:
483
+ decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
484
+ channels = {"final": extract_final_channel_fallback(decoded), "raw": decoded}
485
+ else:
486
+ decoded = tokenizer.decode(gen_ids, skip_special_tokens=False)
487
+ channels = {"final": extract_final_channel_fallback(decoded), "raw": decoded}
488
+
489
+ # Small previews (avoid flooding logs/UI)
490
+ preview = {
491
+ "prompt_len": int(prompt_len),
492
+ "stop_ids": list(HARMONY_STOP_IDS) if HARMONY_AVAILABLE else [],
493
+ "gen_len": int(len(gen_ids)),
494
+ "gen_ids_head": gen_ids[:48],
495
+ "decoded_head": tokenizer.decode(gen_ids[:256], skip_special_tokens=False),
496
+ "channels": channels,
497
+ }
498
+ return preview
499
  except Exception as e:
500
+ return {"error": f"{type(e).__name__}: {e}"}
501
  finally:
502
+ try:
503
+ del model
504
+ except Exception:
505
+ pass
506
  gc.collect()
507
  if torch.cuda.is_available():
508
  torch.cuda.empty_cache()
509
 
510
+ # -----------------------
511
+ # Gradio handlers
512
+ # -----------------------
 
 
 
 
 
 
 
 
 
 
 
 
513
 
514
+ def generate_response(message: str, history: List[List[str]], system_prompt: str,
515
+ temperature: float, top_p: float, top_k: int, max_new_tokens: int,
516
+ do_sample: bool, seed: Optional[int],
517
+ rose_enable: bool, rose_alpha: float, rose_score: Optional[float],
518
+ rose_tokens: str, rose_json: str,
519
+ show_thinking: bool = False,
520
+ reasoning_effort: str = "high") -> str:
521
+ """
522
+ Generate response with proper CoT handling using Harmony format.
523
+ """
524
+ try:
525
+ # Build message list
526
+ messages = [{"role": "system", "content": system_prompt or SYSTEM_DEF}]
527
+
528
+ # Add history
529
+ if history:
530
+ for turn in history:
531
+ if isinstance(turn, (list, tuple)) and len(turn) >= 2:
532
+ user_msg, assistant_msg = turn[0], turn[1]
533
+ if user_msg:
534
+ messages.append({"role": "user", "content": str(user_msg)})
535
+ if assistant_msg:
536
+ messages.append({"role": "assistant", "content": str(assistant_msg)})
537
+
538
+ # Add current message
539
+ messages.append({"role": "user", "content": str(message)})
540
+
541
+ # Create Harmony-formatted prompt
542
+ if HARMONY_AVAILABLE:
543
+ prompt = create_harmony_prompt(messages, reasoning_effort) # returns token IDs
544
+ else:
545
+ # Fallback to tokenizer template (string)
546
+ prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
547
 
548
+ # Build Rose map if enabled
549
+ rose_map: Optional[Dict[str, float]] = None
550
+ if rose_enable:
551
+ rose_map = {}
552
+ tok_str = (rose_tokens or "").strip()
553
+ if tok_str:
554
+ for p in [p.strip() for p in tok_str.split(",") if p.strip()]:
555
+ if ":" in p:
556
+ k, v = p.split(":", 1)
557
+ try:
558
+ rose_map[k.strip()] = float(v)
559
+ except:
560
+ pass
561
+ if rose_json:
562
+ try:
563
+ j = json.loads(rose_json)
564
+ if isinstance(j, dict):
565
+ for k, v in j.items():
566
+ try:
567
+ rose_map[str(k)] = float(v)
568
+ except:
569
+ pass
570
+ except:
571
+ pass
572
+ if not rose_map:
573
+ rose_map = None
574
+
575
+ # Generate with model
576
+ channels = zerogpu_generate(
577
+ prompt,
578
+ {
579
+ "do_sample": bool(do_sample),
580
+ "temperature": float(temperature),
581
+ "top_p": float(top_p),
582
+ "top_k": int(top_k) if top_k > 0 else None,
583
+ "max_new_tokens": int(max_new_tokens),
584
+ },
585
+ rose_map,
586
+ float(rose_alpha),
587
+ float(rose_score) if rose_score is not None else None,
588
+ int(seed) if seed is not None else None,
589
+ )
590
+
591
+ # Format response
592
+ if show_thinking:
593
+ # Show all channels
594
+ response = "## Chain of Thought:\n\n"
595
+ for channel, content in channels.items():
596
+ if channel != "final" and content:
597
+ response += f"### {channel.capitalize()} Channel:\n{content}\n\n"
598
+ response += f"### Final Response:\n{channels.get('final', 'No final response generated')}"
599
+ return response
600
+ else:
601
+ # Just show the final response
602
+ return channels.get("final", "No final response generated")
603
+
604
+ except Exception as e:
605
+ return f"[Error] {type(e).__name__}: {str(e)}"
606
+
607
+ # -----------------------
608
+ # Extra handler: Harmony Inspector wrapper
609
+ # -----------------------
610
+
611
+ def harmony_inspect_handler(user_prompt: str, system_prompt: str, reasoning_effort: str):
612
+ try:
613
+ msgs = [{"role": "system", "content": system_prompt or SYSTEM_DEF}, {"role": "user", "content": user_prompt or "What is 2+2?"}]
614
+ prompt = create_harmony_prompt(msgs, reasoning_effort)
615
+ return zerogpu_generate_debug(
616
+ prompt,
617
+ {"do_sample": True, "temperature": 0.7, "top_p": 0.9, "top_k": 0, "max_new_tokens": MAX_DEF}
618
+ )
619
+ except Exception as e:
620
+ return {"error": f"{type(e).__name__}: {e}"}
621
+
622
+ # -----------------------
623
+ # UI
624
+ # -----------------------
625
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
626
+ gr.Markdown(
627
+ """
628
+ # Mirel – Harmony Chain-of-Thought Inference
629
+
630
+ OSS-20B model using Harmony format with thinking channels.
631
+ The model thinks through problems in internal channels before providing a final response.
632
+
633
+ **Note:** Install `openai-harmony` for full Harmony support: `pip install openai-harmony`
634
+ """
635
+ )
636
 
637
+ with gr.Row():
638
+ system_prompt = gr.Textbox(
639
+ label="System Prompt",
640
+ value=SYSTEM_DEF,
641
+ lines=2
642
+ )
643
+
644
+ with gr.Accordion("Generation Settings", open=False):
645
+ with gr.Row():
646
+ temperature = gr.Slider(0.0, 2.0, value=0.7, step=0.05, label="Temperature")
647
+ top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.01, label="Top-p")
648
+ top_k = gr.Slider(0, 200, value=0, step=1, label="Top-k (0=disabled)")
649
+ with gr.Row():
650
+ max_new = gr.Slider(16, 4096, value=MAX_DEF, step=16, label="Max new tokens")
651
+ do_sample = gr.Checkbox(value=True, label="Do sample")
652
+ seed = gr.Number(value=None, label="Seed (optional)", precision=0)
653
+ with gr.Row():
654
+ reasoning_effort = gr.Radio(
655
+ choices=["low", "medium", "high"],
656
+ value="high",
657
+ label="Reasoning Effort",
658
+ info="How much thinking the model should do"
659
+ )
660
+ show_thinking = gr.Checkbox(
661
+ value=False,
662
+ label="Show thinking channels",
663
+ info="Display all internal reasoning channels"
664
+ )
665
+
666
+ with gr.Accordion("Rose Guidance (Optional)", open=False):
667
+ gr.Markdown("Fine-tune generation with token biases")
668
+ with gr.Row():
669
+ rose_enable = gr.Checkbox(value=False, label="Enable Rose bias")
670
+ rose_alpha = gr.Slider(0.0, 5.0, value=1.0, step=0.05, label="Alpha (strength)")
671
+ rose_score = gr.Slider(0.0, 1.0, value=1.0, step=0.01, label="Score multiplier")
672
+ rose_tokens = gr.Textbox(
673
+ label="Token:weight pairs",
674
+ placeholder="example:1.5, test:-0.5",
675
+ value=""
676
+ )
677
+ rose_json = gr.Textbox(
678
+ label="JSON weights",
679
+ placeholder='{"token": 1.0, "another": -0.5}',
680
+ value=""
681
+ )
682
 
683
+ # --- Harmony Inspector UI ---
684
+ with gr.Accordion("Harmony Inspector", open=False):
685
+ debug_prompt = gr.Textbox(label="Debug prompt", value="What is 2+2? Reply with just the number.")
686
+ run_debug = gr.Button("Run Harmony Inspect")
687
+ debug_out = gr.JSON(label="Parsed Harmony output", value={})
688
+ run_debug.click(harmony_inspect_handler, inputs=[debug_prompt, system_prompt, reasoning_effort], outputs=[debug_out])
689
+
690
+ # Chat interface - using only valid parameters
691
+ chat = gr.ChatInterface(
692
+ fn=generate_response,
693
+ type="messages",
694
+ additional_inputs=[
695
+ system_prompt, temperature, top_p, top_k, max_new,
696
+ do_sample, seed, rose_enable, rose_alpha, rose_score,
697
+ rose_tokens, rose_json, show_thinking, reasoning_effort
698
+ ],
699
+ title="Chat with Mirel",
700
+ description="A chain-of-thought model using Harmony format",
701
+ examples=[
702
+ ["Hello! Can you introduce yourself?"],
703
+ ["What is the capital of France?"],
704
+ ["Explain quantum computing in simple terms"],
705
+ ["Solve: If a train travels 120 miles in 2 hours, what is its average speed?"],
706
+ ],
707
+ cache_examples=False,
708
+ )
709
+
710
+ gr.Markdown(
711
+ """
712
+ ---
713
+ ### Configuration:
714
+ - **Model**: Set `MODEL_ID` env var (default: openai/gpt-oss-20b)
715
+ - **Adapter**: Set `ADAPTER_ID` and optionally `ADAPTER_SUBFOLDER`
716
+ - **Auth**: Set `HF_TOKEN` in Space secrets for private model access
717
+ - **Harmony**: Install with `pip install openai-harmony` for proper channel support
718
+
719
+ The model uses Harmony format with thinking channels (`thinking`, `analysis`, `final`).
720
+ """
721
+ )
722
+
723
+ if __name__ == "__main__":
724
+ demo.queue(max_size=8 if ZEROGPU else 32).launch(
725
+ server_name="0.0.0.0",
726
+ server_port=7860,
727
+ share=False
728
+ )