Spaces:
Sleeping
Sleeping
Jekyll & Hyde Gradio demo
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
Jekyll & Hyde — Hugging Face Gradio Space (ZeroGPU).
|
| 3 |
|
| 4 |
-
import spaces BEFORE torch.
|
| 5 |
"""
|
| 6 |
|
| 7 |
from __future__ import annotations
|
|
@@ -40,7 +40,6 @@ def _hub_token() -> str | None:
|
|
| 40 |
|
| 41 |
|
| 42 |
def _load_models() -> str:
|
| 43 |
-
"""Module-scope load only (ZeroGPU packs weights at startup)."""
|
| 44 |
global _model, _tokenizer, _boot_status
|
| 45 |
if _model is not None:
|
| 46 |
return _boot_status
|
|
@@ -48,11 +47,11 @@ def _load_models() -> str:
|
|
| 48 |
import torch
|
| 49 |
from huggingface_hub import login
|
| 50 |
from peft import PeftModel
|
| 51 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 52 |
|
| 53 |
token = _hub_token()
|
| 54 |
if not token:
|
| 55 |
-
_boot_status = "Missing HF_TOKEN secret (Gemma license
|
| 56 |
return _boot_status
|
| 57 |
|
| 58 |
login(token=token, add_to_git_credential=False)
|
|
@@ -61,19 +60,14 @@ def _load_models() -> str:
|
|
| 61 |
if tokenizer.pad_token is None:
|
| 62 |
tokenizer.pad_token = tokenizer.eos_token
|
| 63 |
|
| 64 |
-
|
| 65 |
-
load_in_4bit=True,
|
| 66 |
-
bnb_4bit_quant_type="nf4",
|
| 67 |
-
bnb_4bit_compute_dtype=torch.float16,
|
| 68 |
-
bnb_4bit_use_double_quant=True,
|
| 69 |
-
)
|
| 70 |
base = AutoModelForCausalLM.from_pretrained(
|
| 71 |
BASE_MODEL,
|
| 72 |
trust_remote_code=True,
|
| 73 |
-
|
| 74 |
-
device_map="cuda",
|
| 75 |
token=token,
|
| 76 |
-
)
|
|
|
|
| 77 |
model = PeftModel.from_pretrained(base, JEKYLL_ADAPTER, adapter_name="jekyll", token=token)
|
| 78 |
model.load_adapter(HYDE_ADAPTER, adapter_name="hyde", token=token)
|
| 79 |
model.set_adapter("jekyll")
|
|
@@ -82,12 +76,11 @@ def _load_models() -> str:
|
|
| 82 |
_model = model
|
| 83 |
_tokenizer = tokenizer
|
| 84 |
on_zero = os.environ.get("SPACES_ZERO_GPU") == "1"
|
| 85 |
-
_boot_status = f"Ready · ZeroGPU={on_zero}"
|
| 86 |
return _boot_status
|
| 87 |
|
| 88 |
|
| 89 |
def _pick_adapter(jekyll_w: float, hyde_w: float) -> tuple[str, float, float]:
|
| 90 |
-
"""Switch jekyll/hyde only — weighted MoE adapters break on 4-bit in ZeroGPU workers."""
|
| 91 |
jw, hw = max(0.0, jekyll_w), max(0.0, hyde_w)
|
| 92 |
if jw + hw <= 0:
|
| 93 |
jw, hw = 1.0, 0.0
|
|
@@ -126,12 +119,7 @@ def _run_generate(prompt: str, gen_kwargs: dict) -> str:
|
|
| 126 |
|
| 127 |
|
| 128 |
@spaces.GPU(duration=60)
|
| 129 |
-
def generate_chat(
|
| 130 |
-
user_text: str,
|
| 131 |
-
mode: str,
|
| 132 |
-
history: list | None,
|
| 133 |
-
) -> tuple:
|
| 134 |
-
"""Direct Gradio handler — must be the @spaces.GPU entrypoint."""
|
| 135 |
from safety_eval.platform.decoding_entropy import decoding_for_lora_mix
|
| 136 |
from safety_eval.platform.lora_router import compute_lora_mix
|
| 137 |
from safety_eval.platform.local_model import normalize_messages
|
|
@@ -142,7 +130,7 @@ def generate_chat(
|
|
| 142 |
|
| 143 |
if _model is None or _tokenizer is None:
|
| 144 |
msg = f"Model not loaded. {_boot_status}"
|
| 145 |
-
return history + [(user_text, f"
|
| 146 |
|
| 147 |
try:
|
| 148 |
mode_key = (mode or "chat").lower()
|
|
@@ -182,7 +170,7 @@ def generate_chat(
|
|
| 182 |
return history + [(user_text, text)], "", meta, jw
|
| 183 |
except Exception:
|
| 184 |
err = traceback.format_exc(limit=8)
|
| 185 |
-
return history + [(user_text, f"
|
| 186 |
|
| 187 |
|
| 188 |
try:
|
|
@@ -193,13 +181,10 @@ except Exception as exc:
|
|
| 193 |
|
| 194 |
def build_ui() -> gr.Blocks:
|
| 195 |
with gr.Blocks(title="Jekyll & Hyde", theme=gr.themes.Soft(primary_hue="teal", secondary_hue="red")) as demo:
|
| 196 |
-
gr.Markdown(
|
| 197 |
-
"# 🎭 Jekyll & Hyde\n"
|
| 198 |
-
"Gemma 2 2B + dual LoRA · ZeroGPU demo"
|
| 199 |
-
)
|
| 200 |
mode = gr.Radio(["chat", "jekyll", "hyde", "duel"], value="chat", label="Mode")
|
| 201 |
load_status = gr.Textbox(label="Status", interactive=False, value=_boot_status)
|
| 202 |
-
blend_bar = gr.Slider(0, 1, value=0.7, label="LoRA mix
|
| 203 |
blend_meta = gr.Textbox(label="Decoding", interactive=False)
|
| 204 |
chat = gr.Chatbot(label="Chat", height=420, type="tuples")
|
| 205 |
msg = gr.Textbox(label="Message", placeholder="Ask about policy gray zones…")
|
|
|
|
| 1 |
"""
|
| 2 |
Jekyll & Hyde — Hugging Face Gradio Space (ZeroGPU).
|
| 3 |
|
| 4 |
+
import spaces BEFORE torch. fp16 load at module scope (no bitsandbytes — breaks CPU startup).
|
| 5 |
"""
|
| 6 |
|
| 7 |
from __future__ import annotations
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def _load_models() -> str:
|
|
|
|
| 43 |
global _model, _tokenizer, _boot_status
|
| 44 |
if _model is not None:
|
| 45 |
return _boot_status
|
|
|
|
| 47 |
import torch
|
| 48 |
from huggingface_hub import login
|
| 49 |
from peft import PeftModel
|
| 50 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 51 |
|
| 52 |
token = _hub_token()
|
| 53 |
if not token:
|
| 54 |
+
_boot_status = "Missing HF_TOKEN secret (accept Gemma license on HF)."
|
| 55 |
return _boot_status
|
| 56 |
|
| 57 |
login(token=token, add_to_git_credential=False)
|
|
|
|
| 60 |
if tokenizer.pad_token is None:
|
| 61 |
tokenizer.pad_token = tokenizer.eos_token
|
| 62 |
|
| 63 |
+
# fp16 ~4GB — fits ZeroGPU large; avoids bitsandbytes CUDA check at CPU startup.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
base = AutoModelForCausalLM.from_pretrained(
|
| 65 |
BASE_MODEL,
|
| 66 |
trust_remote_code=True,
|
| 67 |
+
torch_dtype=torch.float16,
|
|
|
|
| 68 |
token=token,
|
| 69 |
+
).to("cuda")
|
| 70 |
+
|
| 71 |
model = PeftModel.from_pretrained(base, JEKYLL_ADAPTER, adapter_name="jekyll", token=token)
|
| 72 |
model.load_adapter(HYDE_ADAPTER, adapter_name="hyde", token=token)
|
| 73 |
model.set_adapter("jekyll")
|
|
|
|
| 76 |
_model = model
|
| 77 |
_tokenizer = tokenizer
|
| 78 |
on_zero = os.environ.get("SPACES_ZERO_GPU") == "1"
|
| 79 |
+
_boot_status = f"Ready · ZeroGPU={on_zero} · fp16"
|
| 80 |
return _boot_status
|
| 81 |
|
| 82 |
|
| 83 |
def _pick_adapter(jekyll_w: float, hyde_w: float) -> tuple[str, float, float]:
|
|
|
|
| 84 |
jw, hw = max(0.0, jekyll_w), max(0.0, hyde_w)
|
| 85 |
if jw + hw <= 0:
|
| 86 |
jw, hw = 1.0, 0.0
|
|
|
|
| 119 |
|
| 120 |
|
| 121 |
@spaces.GPU(duration=60)
|
| 122 |
+
def generate_chat(user_text: str, mode: str, history: list | None) -> tuple:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
from safety_eval.platform.decoding_entropy import decoding_for_lora_mix
|
| 124 |
from safety_eval.platform.lora_router import compute_lora_mix
|
| 125 |
from safety_eval.platform.local_model import normalize_messages
|
|
|
|
| 130 |
|
| 131 |
if _model is None or _tokenizer is None:
|
| 132 |
msg = f"Model not loaded. {_boot_status}"
|
| 133 |
+
return history + [(user_text, f"[error] {msg}")], "", msg, 0.7
|
| 134 |
|
| 135 |
try:
|
| 136 |
mode_key = (mode or "chat").lower()
|
|
|
|
| 170 |
return history + [(user_text, text)], "", meta, jw
|
| 171 |
except Exception:
|
| 172 |
err = traceback.format_exc(limit=8)
|
| 173 |
+
return history + [(user_text, f"Error:\n{err}")], "", "error", 0.5
|
| 174 |
|
| 175 |
|
| 176 |
try:
|
|
|
|
| 181 |
|
| 182 |
def build_ui() -> gr.Blocks:
|
| 183 |
with gr.Blocks(title="Jekyll & Hyde", theme=gr.themes.Soft(primary_hue="teal", secondary_hue="red")) as demo:
|
| 184 |
+
gr.Markdown("# Jekyll & Hyde\nGemma 2 2B + dual LoRA · ZeroGPU")
|
|
|
|
|
|
|
|
|
|
| 185 |
mode = gr.Radio(["chat", "jekyll", "hyde", "duel"], value="chat", label="Mode")
|
| 186 |
load_status = gr.Textbox(label="Status", interactive=False, value=_boot_status)
|
| 187 |
+
blend_bar = gr.Slider(0, 1, value=0.7, label="LoRA mix", interactive=False)
|
| 188 |
blend_meta = gr.Textbox(label="Decoding", interactive=False)
|
| 189 |
chat = gr.Chatbot(label="Chat", height=420, type="tuples")
|
| 190 |
msg = gr.Textbox(label="Message", placeholder="Ask about policy gray zones…")
|