multimodalart HF Staff commited on
Commit
331dbbf
·
verified ·
1 Parent(s): f6df285

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +13 -6
  2. app.py +476 -0
  3. requirements.txt +2 -0
README.md CHANGED
@@ -1,13 +1,20 @@
1
  ---
2
- title: Arithmetic Slm
3
- emoji: 🏃
4
- colorFrom: blue
5
  colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.19.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
1
  ---
2
+ title: Arithmetic-SLM Playground
3
+ emoji: 🧮
4
+ colorFrom: green
5
  colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.19.0
 
8
  app_file: app.py
9
+ short_description: Tiny 31.7M-param arithmetic model playground
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 30m
12
  ---
13
 
14
+ # Arithmetic-SLM Playground
15
+
16
+ A Gradio demo for [WhirlwindAI/Arithmetic-SLM](https://huggingface.co/WhirlwindAI/Arithmetic-SLM),
17
+ a tiny 31.7M-parameter language model specialized for arithmetic continuation.
18
+
19
+ Enter an arithmetic expression ending with `=` (e.g. `(10 + 28) * 3 =`) and the model
20
+ completes it with the answer. Supports `+`, `-`, `*`, `/`, parentheses, and decimals.
app.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces # MUST come before torch / any CUDA-touching import
2
+ import random
3
+ from typing import List, Optional, Set, Dict
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import gradio as gr
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer
9
+
10
+ MODEL_ID = "WhirlwindAI/Arithmetic-SLM"
11
+
12
+ IM_START = "[IM_START]"
13
+ IM_END = "[IM_END]"
14
+ NO_THINK = "/no think"
15
+
16
+ # ============================================================
17
+ # Model + tokenizer loaded at module scope
18
+ # ============================================================
19
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
20
+ model = AutoModelForCausalLM.from_pretrained(
21
+ MODEL_ID,
22
+ dtype=torch.bfloat16,
23
+ trust_remote_code=True,
24
+ ).to("cuda")
25
+ model.eval()
26
+
27
+ # ============================================================
28
+ # Sampling utilities (ported from the model's inference.py)
29
+ # ============================================================
30
+
31
+ def apply_repetition_penalty(logits: torch.Tensor, generated_ids: List[int], penalty: float) -> torch.Tensor:
32
+ if penalty is None or penalty == 1.0:
33
+ return logits
34
+ if penalty <= 0:
35
+ raise ValueError("repetition_penalty must be > 0")
36
+ for tid in set(generated_ids):
37
+ if tid < 0 or tid >= logits.numel():
38
+ continue
39
+ if logits[tid] > 0:
40
+ logits[tid] = logits[tid] / penalty
41
+ else:
42
+ logits[tid] = logits[tid] * penalty
43
+ return logits
44
+
45
+
46
+ def apply_frequency_presence_penalty(
47
+ logits: torch.Tensor,
48
+ generated_ids: List[int],
49
+ frequency_penalty: float,
50
+ presence_penalty: float,
51
+ ) -> torch.Tensor:
52
+ if not generated_ids:
53
+ return logits
54
+ if frequency_penalty == 0.0 and presence_penalty == 0.0:
55
+ return logits
56
+ counts: Dict[int, int] = {}
57
+ for tid in generated_ids:
58
+ counts[tid] = counts.get(tid, 0) + 1
59
+ for tid, count in counts.items():
60
+ if tid < 0 or tid >= logits.numel():
61
+ continue
62
+ if frequency_penalty:
63
+ logits[tid] -= frequency_penalty * count
64
+ if presence_penalty:
65
+ logits[tid] -= presence_penalty
66
+ return logits
67
+
68
+
69
+ def get_banned_ngram_tokens(generated_ids: List[int], no_repeat_ngram_size: int) -> Set[int]:
70
+ n = no_repeat_ngram_size
71
+ banned: Set[int] = set()
72
+ if n <= 0:
73
+ return banned
74
+ if len(generated_ids) + 1 < n:
75
+ return banned
76
+ prefix_len = n - 1
77
+ current_prefix = tuple(generated_ids[-prefix_len:])
78
+ ngram_map: Dict[tuple, Set[int]] = {}
79
+ for i in range(len(generated_ids) - n + 1):
80
+ prefix = tuple(generated_ids[i : i + prefix_len])
81
+ next_token = generated_ids[i + prefix_len]
82
+ if prefix not in ngram_map:
83
+ ngram_map[prefix] = set()
84
+ ngram_map[prefix].add(next_token)
85
+ banned.update(ngram_map.get(current_prefix, set()))
86
+ return banned
87
+
88
+
89
+ def apply_no_repeat_ngram(logits: torch.Tensor, generated_ids: List[int], no_repeat_ngram_size: int) -> torch.Tensor:
90
+ if no_repeat_ngram_size <= 0:
91
+ return logits
92
+ banned = get_banned_ngram_tokens(generated_ids, no_repeat_ngram_size)
93
+ for tid in banned:
94
+ if 0 <= tid < logits.numel():
95
+ logits[tid] = -float("inf")
96
+ return logits
97
+
98
+
99
+ def apply_top_k(logits: torch.Tensor, top_k: int) -> torch.Tensor:
100
+ if top_k is None or top_k <= 0:
101
+ return logits
102
+ top_k = min(top_k, logits.size(-1))
103
+ values, _ = torch.topk(logits, top_k)
104
+ cutoff = values[-1]
105
+ logits[logits < cutoff] = -float("inf")
106
+ return logits
107
+
108
+
109
+ def apply_top_p(logits: torch.Tensor, top_p: float) -> torch.Tensor:
110
+ if top_p is None or top_p >= 1.0:
111
+ return logits
112
+ if top_p <= 0:
113
+ raise ValueError("top_p must be > 0")
114
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
115
+ sorted_probs = F.softmax(sorted_logits, dim=-1)
116
+ cumulative = torch.cumsum(sorted_probs, dim=-1)
117
+ remove = cumulative > top_p
118
+ remove[1:] = remove[:-1].clone()
119
+ remove[0] = False
120
+ indices_to_remove = sorted_indices[remove]
121
+ logits[indices_to_remove] = -float("inf")
122
+ return logits
123
+
124
+
125
+ def build_stop_sequences(stop_strings: List[str]) -> List[List[int]]:
126
+ out: List[List[int]] = []
127
+ for s in stop_strings:
128
+ ids = tokenizer.encode(s, add_special_tokens=False)
129
+ if ids:
130
+ out.append(ids)
131
+ return out
132
+
133
+
134
+ def endswith_sequence(ids: List[int], suffix: List[int]) -> bool:
135
+ if not suffix:
136
+ return False
137
+ if len(ids) < len(suffix):
138
+ return False
139
+ return ids[-len(suffix) :] == suffix
140
+
141
+
142
+ def sample_next_token(
143
+ logits: torch.Tensor,
144
+ generated_ids: List[int],
145
+ temperature: float,
146
+ top_k: int,
147
+ top_p: float,
148
+ repetition_penalty: float,
149
+ frequency_penalty: float,
150
+ presence_penalty: float,
151
+ no_repeat_ngram_size: int,
152
+ ) -> int:
153
+ logits = logits.float().clone()
154
+ logits = apply_repetition_penalty(logits, generated_ids, repetition_penalty)
155
+ logits = apply_frequency_presence_penalty(logits, generated_ids, frequency_penalty, presence_penalty)
156
+ logits = apply_no_repeat_ngram(logits, generated_ids, no_repeat_ngram_size)
157
+ if temperature <= 0:
158
+ return int(torch.argmax(logits).item())
159
+ logits = logits / temperature
160
+ logits = apply_top_k(logits, top_k)
161
+ logits = apply_top_p(logits, top_p)
162
+ probs = F.softmax(logits, dim=-1)
163
+ if torch.isnan(probs).any() or torch.isinf(probs).any() or probs.sum() <= 0:
164
+ return int(torch.argmax(logits).item())
165
+ return int(torch.multinomial(probs, num_samples=1).item())
166
+
167
+
168
+ def model_forward_logits(input_ids: torch.Tensor) -> torch.Tensor:
169
+ out = model(input_ids=input_ids)
170
+ if hasattr(out, "logits"):
171
+ return out.logits
172
+ if isinstance(out, tuple):
173
+ return out[0]
174
+ raise RuntimeError("Could not get logits from model output.")
175
+
176
+
177
+ @torch.no_grad()
178
+ def generate_manual(
179
+ input_ids: torch.Tensor,
180
+ max_new_tokens: int,
181
+ min_new_tokens: int,
182
+ temperature: float,
183
+ top_k: int,
184
+ top_p: float,
185
+ repetition_penalty: float,
186
+ frequency_penalty: float,
187
+ presence_penalty: float,
188
+ no_repeat_ngram_size: int,
189
+ ctx_len: int,
190
+ stop_strings: List[str],
191
+ ) -> List[int]:
192
+ idx = input_ids
193
+ generated_after_prompt: List[int] = []
194
+ stop_sequences = build_stop_sequences(stop_strings)
195
+ eos_id = tokenizer.eos_token_id
196
+
197
+ for step in range(max_new_tokens):
198
+ idx_cond = idx[:, -ctx_len:] if ctx_len > 0 else idx
199
+ logits = model_forward_logits(idx_cond)
200
+ logits = logits[:, -1, :][0]
201
+
202
+ if step < min_new_tokens:
203
+ if eos_id is not None and 0 <= eos_id < logits.numel():
204
+ logits[eos_id] = -float("inf")
205
+ for seq in stop_sequences:
206
+ if len(seq) == 1:
207
+ tid = seq[0]
208
+ if 0 <= tid < logits.numel():
209
+ logits[tid] = -float("inf")
210
+
211
+ next_id = sample_next_token(
212
+ logits=logits,
213
+ generated_ids=generated_after_prompt,
214
+ temperature=temperature,
215
+ top_k=top_k,
216
+ top_p=top_p,
217
+ repetition_penalty=repetition_penalty,
218
+ frequency_penalty=frequency_penalty,
219
+ presence_penalty=presence_penalty,
220
+ no_repeat_ngram_size=no_repeat_ngram_size,
221
+ )
222
+
223
+ next_tensor = torch.tensor([[next_id]], dtype=torch.long, device=idx.device)
224
+ idx = torch.cat([idx, next_tensor], dim=1)
225
+ generated_after_prompt.append(next_id)
226
+
227
+ if step >= min_new_tokens:
228
+ if eos_id is not None and next_id == eos_id:
229
+ break
230
+ full_ids = idx[0].tolist()
231
+ should_stop = False
232
+ for seq in stop_sequences:
233
+ if endswith_sequence(full_ids, seq):
234
+ should_stop = True
235
+ break
236
+ if should_stop:
237
+ break
238
+
239
+ return idx[0].tolist()
240
+
241
+
242
+ def build_prompt(expression: str, use_no_think: bool) -> str:
243
+ """Build the prompt for the model.
244
+
245
+ Args:
246
+ expression: arithmetic expression (e.g. '(10 + 28) * 3 =').
247
+ use_no_think: if True, wrap in the /no think chat template for production use.
248
+ """
249
+ if use_no_think:
250
+ return (
251
+ f"{IM_START}user\n"
252
+ f"{expression} {NO_THINK}"
253
+ f"{IM_END}\n"
254
+ f"{IM_START}assistant\n"
255
+ "⚠️\n</think>\n\n"
256
+ )
257
+ return expression
258
+
259
+
260
+ def extract_completion(full_text: str, prompt: str) -> str:
261
+ """Extract the completion (model output) from the full generated text."""
262
+ if full_text.startswith(prompt):
263
+ return full_text[len(prompt):]
264
+ pos = full_text.rfind(prompt)
265
+ if pos != -1:
266
+ return full_text[pos + len(prompt):]
267
+ return full_text
268
+
269
+
270
+ def strip_after_stop_text(text: str, stop_strings: List[str]) -> str:
271
+ """Strip everything after the first stop string."""
272
+ best = None
273
+ for s in stop_strings:
274
+ if not s:
275
+ continue
276
+ pos = text.find(s)
277
+ if pos != -1:
278
+ if best is None or pos < best:
279
+ best = pos
280
+ if best is None:
281
+ return text
282
+ return text[:best]
283
+
284
+
285
+ # ============================================================
286
+ # Gradio inference function
287
+ # ============================================================
288
+
289
+ @spaces.GPU(duration=30)
290
+ def solve(
291
+ expression: str,
292
+ use_no_think: bool,
293
+ max_new_tokens: int,
294
+ temperature: float,
295
+ top_k: int,
296
+ top_p: float,
297
+ repetition_penalty: float,
298
+ frequency_penalty: float,
299
+ no_repeat_ngram_size: int,
300
+ seed: int,
301
+ ):
302
+ """Solve an arithmetic expression using the Arithmetic-SLM model.
303
+
304
+ Args:
305
+ expression: an arithmetic expression ending with '=' (e.g. '59 + 45 =').
306
+ use_no_think: use the /no think chat template (recommended for production).
307
+ max_new_tokens: maximum number of tokens to generate.
308
+ temperature: sampling temperature (lower = more deterministic).
309
+ top_k: top-k sampling filter.
310
+ top_p: nucleus sampling filter.
311
+ repetition_penalty: penalty for repeated tokens.
312
+ frequency_penalty: penalty based on token frequency.
313
+ no_repeat_ngram_size: ban repeating n-grams of this size.
314
+ seed: random seed (-1 for random).
315
+ """
316
+ if not expression or not expression.strip():
317
+ return "Please enter an arithmetic expression ending with '='.", ""
318
+
319
+ # Set seed
320
+ if seed is not None and seed >= 0:
321
+ random.seed(seed)
322
+ torch.manual_seed(seed)
323
+ if torch.cuda.is_available():
324
+ torch.cuda.manual_seed_all(seed)
325
+ else:
326
+ seed = random.randint(0, 2**31 - 1)
327
+ random.seed(seed)
328
+ torch.manual_seed(seed)
329
+ if torch.cuda.is_available():
330
+ torch.cuda.manual_seed_all(seed)
331
+
332
+ prompt = build_prompt(expression.strip(), use_no_think)
333
+ stop_strings = [IM_END, IM_START]
334
+
335
+ encoded = tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
336
+ encoded.pop("token_type_ids", None)
337
+ input_ids = encoded["input_ids"].to("cuda")
338
+
339
+ output_ids = generate_manual(
340
+ input_ids=input_ids,
341
+ max_new_tokens=max_new_tokens,
342
+ min_new_tokens=1,
343
+ temperature=temperature,
344
+ top_k=top_k,
345
+ top_p=top_p,
346
+ repetition_penalty=repetition_penalty,
347
+ frequency_penalty=frequency_penalty,
348
+ presence_penalty=0.0,
349
+ no_repeat_ngram_size=no_repeat_ngram_size,
350
+ ctx_len=2048,
351
+ stop_strings=stop_strings,
352
+ )
353
+
354
+ full_text = tokenizer.decode(output_ids, skip_special_tokens=False)
355
+ completion = extract_completion(full_text, prompt)
356
+ completion = strip_after_stop_text(completion, stop_strings)
357
+ completion = completion.strip()
358
+
359
+ # Build a nice display: show the expression + completion
360
+ if use_no_think:
361
+ display = f"**Prompt (no-think template):**\n```\n{prompt}\n```\n\n**Model output:**\n```\n{completion}\n```"
362
+ else:
363
+ display = f"**Prompt:** `{prompt}`\n\n**Model output:** `{completion}`"
364
+
365
+ full_display = f"{expression.strip()} {completion}".strip()
366
+
367
+ return full_display, display
368
+
369
+
370
+ # ============================================================
371
+ # Gradio UI
372
+ # ============================================================
373
+
374
+ CSS = """
375
+ #col-container { max-width: 900px; margin: 0 auto; }
376
+ .dark .gradio-container { color: var(--body-text-color); }
377
+ """
378
+
379
+ with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
380
+ gr.Markdown(
381
+ "# 🧮 Arithmetic-SLM Playground\n"
382
+ "**WhirlwindAI/Arithmetic-SLM** — a tiny 31.7M-parameter model specialized for arithmetic. "
383
+ "Enter an expression ending with `=` and the model completes it with the answer.\n\n"
384
+ "Supports `+`, `-`, `*`, `/`, parentheses, and decimals. "
385
+ "[Model card](https://huggingface.co/WhirlwindAI/Arithmetic-SLM)"
386
+ )
387
+
388
+ with gr.Column(elem_id="col-container"):
389
+ with gr.Row():
390
+ expression_input = gr.Textbox(
391
+ label="Arithmetic expression",
392
+ placeholder="e.g. (10 + 28) * 3 =",
393
+ scale=4,
394
+ show_label=False,
395
+ )
396
+ solve_btn = gr.Button("Solve", variant="primary", scale=1)
397
+
398
+ output_text = gr.Textbox(label="Result", interactive=False, show_copy_button=True)
399
+ output_detail = gr.Textbox(label="Details", interactive=False, visible=True)
400
+
401
+ with gr.Accordion("Advanced settings", open=False):
402
+ use_no_think = gr.Checkbox(
403
+ label="Use /no think template (recommended)",
404
+ value=True,
405
+ info="Wraps the expression in the model's production chat template for cleaner outputs.",
406
+ )
407
+ with gr.Row():
408
+ max_new_tokens = gr.Slider(1, 128, value=48, step=1, label="Max new tokens")
409
+ temperature = gr.Slider(0.0, 2.0, value=0.6, step=0.05, label="Temperature")
410
+ with gr.Row():
411
+ top_k = gr.Slider(0, 100, value=50, step=1, label="Top-k")
412
+ top_p = gr.Slider(0.01, 1.0, value=0.97, step=0.01, label="Top-p")
413
+ with gr.Row():
414
+ repetition_penalty = gr.Slider(0.1, 2.0, value=1.0, step=0.05, label="Repetition penalty")
415
+ frequency_penalty = gr.Slider(0.0, 2.0, value=0.0, step=0.05, label="Frequency penalty")
416
+ with gr.Row():
417
+ no_repeat_ngram_size = gr.Slider(0, 10, value=4, step=1, label="No-repeat n-gram size")
418
+ seed = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)
419
+
420
+ gr.Examples(
421
+ examples=[
422
+ ["59 + 45 =", True],
423
+ ["(10 + 28) * 3 =", True],
424
+ ["16 + 4 * 3 =", True],
425
+ ["3 * 9 + 12 / 1 =", True],
426
+ ["(132 / 12) + (46 - 15) =", True],
427
+ ["0.5 * 0.5 =", True],
428
+ ["8 * 5 + 4 / 4 =", True],
429
+ ["(85 - 45) + 56 =", True],
430
+ ],
431
+ inputs=[expression_input, use_no_think],
432
+ outputs=[output_text, output_detail],
433
+ fn=solve,
434
+ cache_examples=True,
435
+ cache_mode="lazy",
436
+ )
437
+
438
+ solve_btn.click(
439
+ fn=solve,
440
+ inputs=[
441
+ expression_input,
442
+ use_no_think,
443
+ max_new_tokens,
444
+ temperature,
445
+ top_k,
446
+ top_p,
447
+ repetition_penalty,
448
+ frequency_penalty,
449
+ no_repeat_ngram_size,
450
+ seed,
451
+ ],
452
+ outputs=[output_text, output_detail],
453
+ api_name="solve",
454
+ )
455
+
456
+ expression_input.submit(
457
+ fn=solve,
458
+ inputs=[
459
+ expression_input,
460
+ use_no_think,
461
+ max_new_tokens,
462
+ temperature,
463
+ top_k,
464
+ top_p,
465
+ repetition_penalty,
466
+ frequency_penalty,
467
+ no_repeat_ngram_size,
468
+ seed,
469
+ ],
470
+ outputs=[output_text, output_detail],
471
+ api_name="solve_submit",
472
+ )
473
+
474
+
475
+ if __name__ == "__main__":
476
+ demo.launch(mcp_server=True)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ transformers
2
+ safetensors