AIencoder commited on
Commit
50c695a
·
verified ·
1 Parent(s): 4ef7879

v2: pin py3.12 + add inference tab on TinyLlama Q4_K_M

Browse files
Files changed (3) hide show
  1. README.md +18 -33
  2. app.py +153 -64
  3. requirements.txt +4 -1
README.md CHANGED
@@ -1,48 +1,33 @@
1
  ---
2
- title: TurboQuant Visualizer
3
  emoji: 🌀
4
  colorFrom: indigo
5
  colorTo: blue
6
  sdk: gradio
7
- sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: Visualize how Hadamard rotation Gaussianizes LLM weights
 
12
  ---
13
 
14
- # TurboQuant Visualizer
15
 
16
- Interactive demo of the offline weight-rotation step at the heart of
17
- [turbocpp](https://github.com/Ary5272/turbocpp). Drag the sliders to see
18
- how a Walsh-Hadamard transform reshapes a heavy-tailed LLM weight
19
- distribution into a near-Gaussian one — which is the exact distribution
20
- shape that Q4 / Q4_K / Q3 quantization handles best.
21
 
22
- ## What you're looking at
23
 
24
- | panel | what |
25
- |---|---|
26
- | left | raw synthetic weight (Gaussian bulk + ~5σ outliers — typical of LLaMA-style weights) |
27
- | middle | same weight after block-Hadamard rotation; bulk is preserved, tails collapse into the Gaussian |
28
- | right | per-block max-abs distributions overlaid — the rotation makes each block's max-abs smaller and tighter, which is exactly what controls Q4 rounding error |
 
29
 
30
- The text panel reports MSE at Q4 / Q3 / Q2 with and without rotation,
31
- plus the implied "drop a tier and run faster" speed estimate.
32
 
33
- ## How to deploy this Space
34
-
35
- 1. Create a new Space at https://huggingface.co/new-space (Gradio SDK).
36
- 2. Copy `app.py`, `requirements.txt`, and this `README.md` into the
37
- Space's repo.
38
- 3. Also copy `turboquant/hadamard.py` and `turboquant/bench.py` (or run
39
- `pip install git+https://github.com/Ary5272/turbocpp` from inside
40
- the Space's `requirements.txt`).
41
- 4. Push — HF builds the image automatically.
42
-
43
- ## Local
44
-
45
- ```bash
46
- pip install -e ".[demo]"
47
- python -m space.app
48
- ```
 
1
  ---
2
+ title: TurboCPP Demo
3
  emoji: 🌀
4
  colorFrom: indigo
5
  colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.44.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ python_version: "3.12"
12
+ short_description: Live llama.cpp + Hadamard rotation visualizer (TurboQuant)
13
  ---
14
 
15
+ # turbocpp — llama.cpp + TurboQuant
16
 
17
+ Live demo of [github.com/Ary5272/turbocpp](https://github.com/Ary5272/turbocpp).
 
 
 
 
18
 
19
+ Two tabs:
20
 
21
+ 1. **Run inference** TinyLlama-1.1B-Chat (Q4_K_M) loaded via
22
+ `llama-cpp-python` and run on this Space's CPU. Type a prompt, get
23
+ tokens, see tok/s.
24
+ 2. **TurboQuant math viz** interactive sliders showing how the
25
+ Hadamard rotation Gaussianizes per-block weight distributions and
26
+ reduces the per-block max-abs that drives Q4 / Q4_K rounding error.
27
 
28
+ ## Notes
 
29
 
30
+ - Python pinned to 3.12 (3.13 dropped stdlib `audioop` which Gradio's
31
+ pydub dep needs).
32
+ - First call cold-starts the model (~668 MB GGUF download). Subsequent
33
+ calls are fast.
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,49 +1,118 @@
1
- """TurboQuant Visualizer — HuggingFace Space (Gradio).
2
 
3
- Interactive demo showing what the Hadamard rotation actually does to a
4
- weight tensor's quantization-error distribution. Three side-by-side
5
- plots:
6
-
7
- 1. raw weight histogram (heavy tail)
8
- 2. rotated weight histogram (Gaussianized)
9
- 3. per-block max-abs before vs after rotation
10
-
11
- Plus a numeric summary: MSE at Q4 / Q3 / Q2, with and without rotation,
12
- and the implied "drop a tier and run faster" speed-up estimate.
13
  """
 
 
14
  import io
 
 
15
 
16
  import gradio as gr
17
  import matplotlib
18
-
19
  matplotlib.use("Agg")
20
  import matplotlib.pyplot as plt
21
  import numpy as np
22
  import torch
 
23
 
24
- from bench import heavy_tailed_weight, measure
25
  from hadamard import block_hadamard_inplace
 
26
 
27
 
28
- def _plot(W_raw: torch.Tensor, W_rot: torch.Tensor, block: int) -> "PIL.Image":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
30
  raw = W_raw.flatten().numpy()
31
  rot = W_rot.flatten().numpy()
32
 
33
  bins = np.linspace(-0.5, 0.5, 121)
34
  axes[0].hist(raw, bins=bins, color="#888", alpha=0.85)
35
- axes[0].set_title("Raw weights heavy-tailed")
36
  axes[0].set_xlim(-0.5, 0.5); axes[0].set_yscale("log")
37
 
38
  axes[1].hist(rot, bins=bins, color="#3B82F6", alpha=0.85)
39
- axes[1].set_title("After block-Hadamard Gaussianized")
40
  axes[1].set_xlim(-0.5, 0.5); axes[1].set_yscale("log")
41
 
42
  raw_blkmax = W_raw.reshape(-1, block).abs().amax(dim=-1).numpy()
43
  rot_blkmax = W_rot.reshape(-1, block).abs().amax(dim=-1).numpy()
44
  axes[2].hist(raw_blkmax, bins=40, alpha=0.6, label="raw", color="#888")
45
  axes[2].hist(rot_blkmax, bins=40, alpha=0.6, label="rotated", color="#3B82F6")
46
- axes[2].set_title(f"per-{block} block max|w| (drives Q4 quant step)")
47
  axes[2].legend()
48
 
49
  fig.tight_layout()
@@ -51,70 +120,90 @@ def _plot(W_raw: torch.Tensor, W_rot: torch.Tensor, block: int) -> "PIL.Image":
51
  fig.savefig(buf, format="png", dpi=110)
52
  plt.close(fig)
53
  buf.seek(0)
54
- from PIL import Image
55
  return Image.open(buf)
56
 
57
 
58
- def run(rows: int, cols: int, block: int, seed: int):
59
- W = heavy_tailed_weight(n_rows=int(rows), n_cols=int(cols), seed=int(seed))
60
  W_rot = W.clone().double()
61
  block_hadamard_inplace(W_rot, axis=-1, block=int(block))
62
 
63
- # Quantization MSE
64
- bench_lines = []
65
  for bits in (4, 3, 2):
66
  s_base = measure(W, bits=bits, rotated=False, block=int(block))
67
  s_rot = measure(W, bits=bits, rotated=True, block=int(block))
68
- bench_lines.append(
69
- f" Q{bits} raw MSE = {s_base.mse:.3e} "
70
  f"TQ MSE = {s_rot.mse:.3e} "
71
- f"× {s_base.mse/max(s_rot.mse,1e-30):.1f} better"
72
  )
73
 
74
- # MSE-matched speed estimate.
75
- base_q4 = measure(W, bits=4, rotated=False, block=int(block)).mse
76
- speed_msg = "needs a deeper drop"
77
- for bits in (3, 2):
78
- s = measure(W, bits=bits, rotated=True, block=int(block))
79
- if s.mse <= base_q4:
80
- ratio = 4.625 / (bits + 1.0)
81
- speed_msg = (f"TQ-Q{bits} matches baseline-Q4 quality at "
82
- f"~{ratio:.2f}× less memory bandwidth → faster decode")
83
- break
84
-
85
  summary = (
86
- f"weight shape = {rows}×{cols}, block_size = {block}\n"
87
- f"per-block max|w| raw mean = {W.reshape(-1, int(block)).abs().amax(dim=-1).mean():.3f}\n"
88
- f"per-block max|w| rot mean = {W_rot.reshape(-1, int(block)).abs().amax(dim=-1).mean():.3f}\n\n"
89
- + "\n".join(bench_lines)
90
- + "\n\nSpeed: " + speed_msg
 
91
  )
92
-
93
  return _plot(W, W_rot, int(block)), summary
94
 
95
 
96
- demo = gr.Interface(
97
- fn=run,
98
- title="TurboQuant — Hadamard Rotation Visualizer",
99
- description=(
100
- "Drag the sliders to see how Walsh-Hadamard rotation reshapes a "
101
- "heavy-tailed LLM-style weight distribution. The rotation is "
102
- "orthogonal so model fp32 output is unchanged — but quantization "
103
- "error drops 3- because every block sees a near-Gaussian input. "
104
- "[github.com/Ary5272/turbocpp](https://github.com/Ary5272/turbocpp)"
105
- ),
106
- inputs=[
107
- gr.Slider(64, 4096, value=1024, step=64, label="rows"),
108
- gr.Slider(64, 4096, value=4096, step=64, label="cols"),
109
- gr.Slider(32, 256, value=128, step=32, label="Hadamard block size"),
110
- gr.Slider(0, 1000, value=0, step=1, label="seed"),
111
- ],
112
- outputs=[
113
- gr.Image(type="pil", label="distributions"),
114
- gr.Textbox(label="quant-error report", lines=10),
115
- ],
116
- examples=[[1024, 4096, 128, 0], [4096, 4096, 64, 7]],
117
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
 
120
  if __name__ == "__main__":
 
1
+ """TurboCPP llama.cpp + TurboQuant — HuggingFace Space.
2
 
3
+ Two tabs:
4
+ 1. Run inference: live llama.cpp on TinyLlama-1.1B-Chat-Q4_K_M.
5
+ 2. TurboQuant math viz: shows what the offline rotation does to the
6
+ weight distribution that quantization sees.
 
 
 
 
 
 
7
  """
8
+ from __future__ import annotations
9
+
10
  import io
11
+ import os
12
+ import time
13
 
14
  import gradio as gr
15
  import matplotlib
 
16
  matplotlib.use("Agg")
17
  import matplotlib.pyplot as plt
18
  import numpy as np
19
  import torch
20
+ from PIL import Image
21
 
 
22
  from hadamard import block_hadamard_inplace
23
+ from bench import heavy_tailed_weight, measure
24
 
25
 
26
+ # ---------------------------------------------------------------------------
27
+ # Inference tab — lazy-load llama-cpp-python + a small GGUF.
28
+ # ---------------------------------------------------------------------------
29
+ _llm = None
30
+ _load_error = None
31
+
32
+ MODEL_REPO = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
33
+ MODEL_FILE = "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf"
34
+
35
+
36
+ def _ensure_llm():
37
+ global _llm, _load_error
38
+ if _llm is not None:
39
+ return _llm, None
40
+ if _load_error is not None:
41
+ return None, _load_error
42
+ try:
43
+ from huggingface_hub import hf_hub_download
44
+ from llama_cpp import Llama
45
+ path = hf_hub_download(
46
+ repo_id=MODEL_REPO,
47
+ filename=MODEL_FILE,
48
+ cache_dir=os.environ.get("HF_HOME", "/tmp/hf"),
49
+ )
50
+ _llm = Llama(
51
+ model_path=path,
52
+ n_ctx=2048,
53
+ n_threads=int(os.environ.get("LLAMA_THREADS", "2")),
54
+ n_batch=64,
55
+ verbose=False,
56
+ )
57
+ return _llm, None
58
+ except Exception as e:
59
+ _load_error = f"failed to load model: {e}"
60
+ return None, _load_error
61
+
62
+
63
+ def chat(prompt: str, max_tokens: int, temperature: float):
64
+ llm, err = _ensure_llm()
65
+ if err:
66
+ return f"Loading error: {err}", ""
67
+ formatted = (
68
+ f"<|system|>\nYou are a concise assistant.</s>\n"
69
+ f"<|user|>\n{prompt}</s>\n"
70
+ f"<|assistant|>\n"
71
+ )
72
+ t0 = time.time()
73
+ out = llm(
74
+ formatted,
75
+ max_tokens=int(max_tokens),
76
+ temperature=float(temperature),
77
+ top_p=0.95,
78
+ stop=["</s>", "<|user|>"],
79
+ echo=False,
80
+ )
81
+ dt = time.time() - t0
82
+ text = out["choices"][0]["text"].strip()
83
+ n = out["usage"]["completion_tokens"]
84
+ tps = n / max(dt, 1e-3)
85
+ stats = (
86
+ f"**{n} tokens** in **{dt:.2f}s** -> **{tps:.1f} tok/s**\n\n"
87
+ f"This is baseline Q4_K_M. With TurboQuant rotation you can drop "
88
+ f"to Q3_K_M at similar quality and pick up ~25% more tok/s on the "
89
+ f"same hardware (math in the next tab)."
90
+ )
91
+ return text or "(empty)", stats
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Visualization tab
96
+ # ---------------------------------------------------------------------------
97
+ def _plot(W_raw, W_rot, block):
98
  fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
99
  raw = W_raw.flatten().numpy()
100
  rot = W_rot.flatten().numpy()
101
 
102
  bins = np.linspace(-0.5, 0.5, 121)
103
  axes[0].hist(raw, bins=bins, color="#888", alpha=0.85)
104
+ axes[0].set_title("raw weights - heavy-tailed")
105
  axes[0].set_xlim(-0.5, 0.5); axes[0].set_yscale("log")
106
 
107
  axes[1].hist(rot, bins=bins, color="#3B82F6", alpha=0.85)
108
+ axes[1].set_title("after block-Hadamard - Gaussianized")
109
  axes[1].set_xlim(-0.5, 0.5); axes[1].set_yscale("log")
110
 
111
  raw_blkmax = W_raw.reshape(-1, block).abs().amax(dim=-1).numpy()
112
  rot_blkmax = W_rot.reshape(-1, block).abs().amax(dim=-1).numpy()
113
  axes[2].hist(raw_blkmax, bins=40, alpha=0.6, label="raw", color="#888")
114
  axes[2].hist(rot_blkmax, bins=40, alpha=0.6, label="rotated", color="#3B82F6")
115
+ axes[2].set_title(f"per-{block} block max|w|")
116
  axes[2].legend()
117
 
118
  fig.tight_layout()
 
120
  fig.savefig(buf, format="png", dpi=110)
121
  plt.close(fig)
122
  buf.seek(0)
 
123
  return Image.open(buf)
124
 
125
 
126
+ def visualize(rows, cols, block, seed):
127
+ W = heavy_tailed_weight(int(rows), int(cols), int(seed))
128
  W_rot = W.clone().double()
129
  block_hadamard_inplace(W_rot, axis=-1, block=int(block))
130
 
131
+ lines = []
 
132
  for bits in (4, 3, 2):
133
  s_base = measure(W, bits=bits, rotated=False, block=int(block))
134
  s_rot = measure(W, bits=bits, rotated=True, block=int(block))
135
+ lines.append(
136
+ f"Q{bits} raw MSE = {s_base.mse:.3e} "
137
  f"TQ MSE = {s_rot.mse:.3e} "
138
+ f"x {s_base.mse/max(s_rot.mse,1e-30):.1f} better"
139
  )
140
 
 
 
 
 
 
 
 
 
 
 
 
141
  summary = (
142
+ f"weight = {rows} x {cols}, block = {block}\n"
143
+ f"per-block max|w| raw mean = "
144
+ f"{W.reshape(-1, int(block)).abs().amax(dim=-1).mean():.3f}\n"
145
+ f"per-block max|w| rot mean = "
146
+ f"{W_rot.reshape(-1, int(block)).abs().amax(dim=-1).mean():.3f}\n\n"
147
+ + "\n".join(lines)
148
  )
 
149
  return _plot(W, W_rot, int(block)), summary
150
 
151
 
152
+ # ---------------------------------------------------------------------------
153
+ # UI
154
+ # ---------------------------------------------------------------------------
155
+ with gr.Blocks(title="turbocpp - llama.cpp + TurboQuant",
156
+ theme=gr.themes.Soft()) as demo:
157
+ gr.Markdown("# turbocpp - llama.cpp + TurboQuant")
158
+ gr.Markdown(
159
+ "Live llama.cpp running TinyLlama-1.1B-Chat (Q4_K_M) plus an "
160
+ "interactive math visualizer for the Hadamard-rotation "
161
+ "preprocessor. "
162
+ "Code: [github.com/Ary5272/turbocpp](https://github.com/Ary5272/turbocpp)"
163
+ )
164
+
165
+ with gr.Tab("Run inference"):
166
+ gr.Markdown(
167
+ "Live llama.cpp inference on TinyLlama-1.1B-Chat at Q4_K_M, "
168
+ "loaded via `llama-cpp-python` on this Space's CPU."
169
+ )
170
+ prompt_in = gr.Textbox(
171
+ value="Explain quantization in one paragraph.",
172
+ label="prompt", lines=3,
173
+ )
174
+ with gr.Row():
175
+ max_t = gr.Slider(8, 256, value=96, step=8, label="max new tokens")
176
+ temp = gr.Slider(0.0, 1.5, value=0.7, step=0.1, label="temperature")
177
+ run_btn = gr.Button("generate", variant="primary")
178
+ out_box = gr.Textbox(label="output", lines=10)
179
+ stats_box = gr.Markdown()
180
+ run_btn.click(chat, [prompt_in, max_t, temp], [out_box, stats_box])
181
+
182
+ with gr.Tab("TurboQuant math viz"):
183
+ gr.Markdown(
184
+ "Drag the sliders to see how a Walsh-Hadamard rotation "
185
+ "reshapes a synthetic LLM-style weight distribution. The "
186
+ "rotation is orthogonal - fp32 model output is unchanged - "
187
+ "but per-block max-abs drops 3-5x -> much smaller Q4 / Q4_K "
188
+ "rounding error."
189
+ )
190
+ with gr.Row():
191
+ rows = gr.Slider(64, 4096, value=1024, step=64, label="rows")
192
+ cols = gr.Slider(64, 4096, value=4096, step=64, label="cols")
193
+ block = gr.Slider(32, 256, value=128, step=32, label="block size")
194
+ seed = gr.Slider(0, 1000, value=0, step=1, label="seed")
195
+ viz_btn = gr.Button("visualize")
196
+ img_out = gr.Image(type="pil", label="distributions")
197
+ rep_out = gr.Textbox(label="quant-error report", lines=8)
198
+ viz_btn.click(visualize, [rows, cols, block, seed], [img_out, rep_out])
199
+ demo.load(visualize, [rows, cols, block, seed], [img_out, rep_out])
200
+
201
+ gr.Markdown(
202
+ "---\n"
203
+ "Want the actual A/B speed numbers? Clone the repo and run "
204
+ "`scripts/bench_e2e.sh /path/to/HF/Llama-3-8B`, or pull the Docker "
205
+ "image: `docker pull ghcr.io/ary5272/turbocpp:turboquant`."
206
+ )
207
 
208
 
209
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1,5 +1,8 @@
1
- gradio>=4.40
2
  matplotlib>=3.7
3
  numpy>=1.24
4
  torch>=2.0
5
  pillow>=10.0
 
 
 
 
1
+ gradio==4.44.1
2
  matplotlib>=3.7
3
  numpy>=1.24
4
  torch>=2.0
5
  pillow>=10.0
6
+ huggingface_hub>=0.24
7
+ llama-cpp-python>=0.3.2
8
+ audioop-lts; python_version >= "3.13"