John6666 commited on
Commit
a58a3d1
·
verified ·
1 Parent(s): b2f6f44

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +5 -5
  2. app.py +188 -0
  3. requirements.txt +7 -0
README.md CHANGED
@@ -1,12 +1,12 @@
1
  ---
2
- title: Meltemi Chat Test
3
- emoji: 🏆
4
- colorFrom: pink
5
  colorTo: blue
6
  sdk: gradio
7
  sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Basic Chat Skelton (Zero GPU friendly)
3
+ emoji: 🌀
4
+ colorFrom: indigo
5
  colorTo: blue
6
  sdk: gradio
7
  sdk_version: 5.49.1
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
+ short_description: A minimal Gradio 5 chat demo
12
  ---
 
 
app.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Gradio 5 + ZeroGPU-ready chat.
4
+ - Streams tokens with TextIteratorStreamer
5
+ Refs:
6
+ - ZeroGPU docs (per-call GPU, 60s default, dynamic duration, effect-free on non-ZeroGPU):
7
+ https://huggingface.co/docs/hub/en/spaces-zerogpu
8
+ - Using GPU Spaces:
9
+ https://huggingface.co/docs/hub/en/spaces-gpus
10
+ - Gradio ChatInterface (type="messages"):
11
+ https://www.gradio.app/docs/gradio/chatinterface
12
+ - Transformers chat templating:
13
+ https://huggingface.co/docs/transformers/en/chat_templating
14
+ - TextIteratorStreamer:
15
+ https://huggingface.co/docs/transformers/en/internal/generation_utils
16
+ - Meltemi Instruct v1.5 (Zephyr prompt format):
17
+ https://huggingface.co/ilsp/Meltemi-7B-Instruct-v1.5
18
+ """
19
+ import os, threading, gc, re
20
+ from typing import Iterable, List, Dict, Any
21
+
22
+ import gradio as gr
23
+ import spaces
24
+ import torch
25
+ from transformers import (
26
+ AutoModelForCausalLM,
27
+ AutoTokenizer,
28
+ TextIteratorStreamer,
29
+ )
30
+
31
+ HAS_CUDA = bool(torch.cuda.is_available())
32
+ IS_ZEROGPU = True if os.getenv("SPACES_ZERO_GPU", None) else False
33
+ if IS_ZEROGPU:
34
+ torch.compiler.set_stance("force_eager")
35
+ torch.set_float32_matmul_precision("high")
36
+ torch.backends.cuda.matmul.allow_tf32 = True
37
+
38
+ # ------------------------- Config --------------------------------------------
39
+ MODEL_ID = "ilsp/Meltemi-7B-v1.5" if HAS_CUDA else "HuggingFaceTB/SmolLM2-135M-Instruct"
40
+ SYSTEM_PROMPT = "You are a helpful, concise assistant. Reply in the user's language when possible."
41
+
42
+ ZEROGPU_DURATION_BASE = 20
43
+ ZEROGPU_DURATION_CAP = 60
44
+ CPU_MAX_NEW_TOKENS = 128
45
+
46
+ # Base defaults aim to respect ZeroGPU's 60s window.
47
+ MAX_NEW_TOKENS = 256
48
+ TEMPERATURE = 0.7
49
+ TOP_P = 0.95
50
+ TOP_K = 50
51
+ REPETITION_PENALTY = 1.05
52
+
53
+ # ------------------------- Load model/tokenizer ------------------------
54
+ # Use bf16 on CUDA, fall back to fp32 on CPU for compatibility.
55
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
56
+ model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=dtype)
57
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=True)
58
+ if tokenizer.pad_token_id is None and tokenizer.eos_token_id is not None: tokenizer.pad_token_id = tokenizer.eos_token_id
59
+
60
+ def clear_cache():
61
+ if HAS_CUDA:
62
+ try:
63
+ torch.cuda.empty_cache()
64
+ except Exception:
65
+ pass
66
+ gc.collect()
67
+
68
+ def build_messages(user_text: str, history: List[Dict[str, str]], system_message: str) -> List[Dict[str, str]]:
69
+ """Merge system + history + user into HF messages format."""
70
+ msgs: List[Dict[str, str]] = []
71
+ if not history and system_message: msgs.append({"role": "system", "content": system_message})
72
+ msgs.extend(history or [])
73
+ msgs.append({"role": "user", "content": user_text})
74
+ return msgs
75
+
76
+ def to_model_inputs(messages: List[Dict[str, str]]) -> Dict[str, torch.Tensor]:
77
+ """
78
+ Create tokenized inputs.
79
+ - If a chat template exists,
80
+ use apply_chat_template(..., add_generation_prompt=True).
81
+ - Otherwise fall back to a simple joined text prompt for base models.
82
+ """
83
+ if getattr(tokenizer, "chat_template", None):
84
+ return tokenizer.apply_chat_template(
85
+ messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt"
86
+ )
87
+ # Fallback: last user only, no headings that induce lists
88
+ print("Chat template not found.")
89
+ last_user = next((m["content"] for m in reversed(messages) if m["role"]=="user"), "")
90
+ prompt = (messages[0]["content"] + "\n\n" if messages and messages[0]["role"]=="system" else "") + last_user
91
+ return tokenizer(prompt, return_tensors="pt")
92
+
93
+ CHATML_HEAD = re.compile(r'^\s*<\|im_start\|>\s*assistant\s*\n?', re.IGNORECASE)
94
+ CHATML_TAIL = re.compile(r'\s*<\|im_end\|>\s*$', re.IGNORECASE)
95
+ GEN_TAIL = re.compile(r'\s*(</s>|<\|end_of_text\|>)\s*$', re.IGNORECASE)
96
+
97
+ def _clean_stream_chunk(text: str) -> str:
98
+ t = CHATML_HEAD.sub("", text)
99
+ t = CHATML_TAIL.sub("", t)
100
+ t = GEN_TAIL.sub("", t)
101
+ return t
102
+
103
+ def estimate_duration(max_new_tokens: int) -> int:
104
+ """
105
+ Heuristic duration budget for ZeroGPU (seconds).
106
+ Shorter durations improve queue priority.
107
+ """
108
+ secs = int(float(ZEROGPU_DURATION_BASE) * float(max_new_tokens) / float(MAX_NEW_TOKENS))
109
+ cap = int(ZEROGPU_DURATION_CAP)
110
+ return min(secs, cap)
111
+
112
+ @spaces.GPU(duration=lambda message, history, system_message, max_new_tokens, temperature, top_k, top_p, repetition_penalty: estimate_duration(max_new_tokens if max_new_tokens else MAX_NEW_TOKENS))
113
+ @torch.inference_mode()
114
+ def generate_on_accelerator(message: str, history: List[Dict[str, str]], system_message: str, max_new_tokens: int, temperature: float, top_k: int, top_p: float, repetition_penalty: float) -> Iterable[str]:
115
+ """
116
+ ChatInterface callback that works both on ZeroGPU and CPU-only Spaces.
117
+ The decorator is effect-free outside ZeroGPU, so this still runs on CPU.
118
+ """
119
+ try:
120
+ device = torch.device("cuda" if HAS_CUDA else "cpu")
121
+ if device != model.device: model.to(device)
122
+
123
+ messages = build_messages(message, history, system_message)
124
+ inputs = to_model_inputs(messages)
125
+ inputs = {k: v.to(device) for k, v in inputs.items()}
126
+
127
+ # Reduce generation length on CPU to keep latency reasonable.
128
+ eff_max_new_tokens = max_new_tokens if HAS_CUDA else min(max_new_tokens, CPU_MAX_NEW_TOKENS)
129
+
130
+ streamer = TextIteratorStreamer(
131
+ tokenizer,
132
+ skip_prompt=True,
133
+ decode_kwargs={"skip_special_tokens": True},
134
+ )
135
+
136
+ gen_kwargs = dict(
137
+ **inputs,
138
+ streamer=streamer,
139
+ max_new_tokens=eff_max_new_tokens,
140
+ do_sample=True,
141
+ temperature=temperature,
142
+ top_p=top_p,
143
+ top_k=top_k,
144
+ repetition_penalty=repetition_penalty,
145
+ pad_token_id=tokenizer.pad_token_id,
146
+ eos_token_id=tokenizer.eos_token_id,
147
+ cache_implementation="static", # https://github.com/huggingface/transformers/issues/38501
148
+ )
149
+
150
+ # Run generation in a background thread and yield chunks as they arrive.
151
+ thread = threading.Thread(target=model.generate, kwargs=gen_kwargs)
152
+ thread.start()
153
+
154
+ new_response = ""
155
+ for text in streamer:
156
+ new_response += text
157
+ new_response = _clean_stream_chunk(new_response)
158
+ yield new_response
159
+ except Exception as e:
160
+ print(e)
161
+ raise gr.Error(e)
162
+ finally:
163
+ # Move back to CPU and free CUDA cache when using a GPU.
164
+ if not HAS_CUDA: model.to("cpu")
165
+ clear_cache()
166
+
167
+ demo = gr.ChatInterface(
168
+ fn=generate_on_accelerator,
169
+ type="messages", # OpenAI-style histories: [{"role": "...", "content": "..."}]
170
+ title=f"{MODEL_ID} Chat",
171
+ description=(f"Chat with {MODEL_ID}"),
172
+ additional_inputs=[
173
+ gr.Textbox(value=SYSTEM_PROMPT, label="System message"),
174
+ gr.Slider(minimum=1, maximum=2048, value=MAX_NEW_TOKENS, step=1, label="Max new tokens"),
175
+ gr.Slider(minimum=0.1, maximum=4.0, value=TEMPERATURE, step=0.1, label="Temperature"),
176
+ gr.Slider(minimum=0, maximum=360, value=TOP_K, step=1, label="Top-k"),
177
+ gr.Slider(minimum=0.1, maximum=1.0, value=TOP_P, step=0.05, label="Top-p"),
178
+ gr.Slider(minimum=0.0, maximum=2.0, value=REPETITION_PENALTY, step=0.05, label="Repetition penalty"),
179
+ ],
180
+ examples=[
181
+ ["Summarize the following paragraph in Greek."],
182
+ ["Translate this into English: Καλημέρα, τι κάνεις;"],
183
+ ["Write a short outline about Greek islands."],
184
+ ],
185
+ cache_examples=False,
186
+ )
187
+
188
+ demo.queue().launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ spaces
3
+ torch
4
+ transformers
5
+ accelerate
6
+ sentencepiece
7
+ pydantic==2.10.6