pratikgx's picture
Add CellGemma E4B Mac mini benchmark (official transformers MPS, card example tasks)
e25ad54 verified
Raw History Blame Contribute Delete
11.7 kB
#!/usr/bin/env python3
"""One clean chart per key CellGemma result. Google brand colors, white background,
Helvetica Neue, and the words 'Mac mini' on every chart."""
from __future__ import annotations
import json
import sys
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
# Official Google brand colors
BLUE = (66, 133, 244, 255) # #4285F4
RED = (234, 67, 53, 255) # #EA4335
YELLOW = (251, 188, 5, 255) # #FBBC05
GREEN = (52, 168, 83, 255) # #34A853
INK = (32, 33, 36, 255) # #202124
MUTED = (95, 99, 104, 255) # #5F6368
SOFT = (128, 134, 139, 255)
LINE = (232, 234, 237, 255)
TRACK = (241, 243, 244, 255)
WHITE = (255, 255, 255, 255)
CARD = (248, 249, 250, 255)
W, H = 1600, 1000
S = 2 # render 2x then downsample
# Helvetica Neue on macOS; Inter on the box as a last-resort fallback.
FONT_CANDIDATES = [
"/System/Library/Fonts/HelveticaNeue.ttc",
"/Library/Fonts/HelveticaNeue.ttc",
"/System/Library/Fonts/Helvetica.ttc",
"/usr/share/fonts/truetype/sand-box/google/Inter/Inter-VariableFont_opsz,wght.ttf",
]
def pick_font_path() -> str:
for p in FONT_CANDIDATES:
if Path(p).exists():
return p
raise FileNotFoundError("No Helvetica Neue or Inter font found")
FONT_PATH = pick_font_path()
def font(size: float, index: int = 0) -> ImageFont.FreeTypeFont:
"""Helvetica Neue.ttc indexes: 0 UltraLight, 1 Thin, 2 Light, 3 Regular,
4 Medium, 5 Bold, 6 Condensed Bold, etc. Prefer Regular/Medium/Bold."""
try:
return ImageFont.truetype(FONT_PATH, int(size * S), index=index)
except OSError:
return ImageFont.truetype(FONT_PATH, int(size * S))
def font_regular(size):
# ttc: try Regular (often 3); Inter has no index meaning
for idx in (3, 0):
try:
return font(size, idx)
except Exception:
continue
return ImageFont.truetype(FONT_PATH, int(size * S))
def font_medium(size):
for idx in (4, 3, 0):
try:
return font(size, idx)
except Exception:
continue
return font_regular(size)
def font_bold(size):
for idx in (5, 4, 0):
try:
return font(size, idx)
except Exception:
continue
return font_medium(size)
def font_light(size):
for idx in (2, 3, 0):
try:
return font(size, idx)
except Exception:
continue
return font_regular(size)
def rounded(draw, box, r, fill=None, outline=None, width=1):
draw.rounded_rectangle(box, radius=int(r * S), fill=fill, outline=outline,
width=int(width * S) if outline else 0)
def text_w(draw, s, f):
return draw.textbbox((0, 0), s, font=f)[2]
def fmt_num(v, unit=""):
if v is None:
return "n/a"
if abs(v) >= 100:
s = f"{v:.0f}"
elif abs(v) >= 10:
s = f"{v:.1f}"
elif abs(v) >= 1:
s = f"{v:.2f}"
else:
s = f"{v:.3f}"
return f"{s}{unit}"
def base_canvas(title: str, subtitle: str, footer: str):
img = Image.new("RGBA", (W * S, H * S), WHITE)
d = ImageDraw.Draw(img)
tfont = font_bold(40)
sfont = font_regular(20)
ffont = font_regular(16)
d.text((80 * S, 56 * S), title, font=tfont, fill=INK)
d.text((80 * S, 116 * S), subtitle, font=sfont, fill=MUTED)
# footer rule
d.rectangle((80 * S, (H - 78) * S, (W - 80) * S, (H - 77) * S), fill=LINE)
d.text((80 * S, (H - 58) * S), footer, font=ffont, fill=MUTED)
# Always include the words "Mac mini"
brand = font_medium(16)
label = "Mac mini"
tw = text_w(d, label, brand)
d.text(((W - 80) * S - tw, (H - 58) * S), label, font=brand, fill=INK)
return img, d
def downsample(img: Image.Image) -> Image.Image:
return img.resize((W, H), Image.Resampling.LANCZOS).convert("RGB")
def single_metric(path: Path, title, subtitle, footer, value, unit, caption, color=BLUE):
img, d = base_canvas(title, subtitle, footer)
# Big number
nfont = font_bold(140)
cfont = font_regular(22)
text = fmt_num(value, " " + unit if unit else "")
# Center the number in the card area
bbox = d.textbbox((0, 0), text, font=nfont)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
x = (W * S - tw) // 2
y = int(320 * S)
# Soft card behind the number
pad_x, pad_y = int(80 * S), int(50 * S)
rounded(d, (x - pad_x, y - pad_y, x + tw + pad_x, y + th + pad_y + int(70 * S)), 28, fill=CARD)
d.text((x, y), text, font=nfont, fill=color)
cap_w = text_w(d, caption, cfont)
d.text(((W * S - cap_w) // 2, y + th + int(24 * S)), caption, font=cfont, fill=MUTED)
downsample(img).save(path, "PNG", optimize=True)
print("wrote", path)
def grouped_bars(path: Path, title, subtitle, footer, series, unit, caption=None):
"""series: list of {label, value, color}."""
img, d = base_canvas(title, subtitle, footer)
left, right = 160 * S, (W - 120) * S
top, bottom = 220 * S, (H - 160) * S
vals = [s["value"] for s in series if s["value"] is not None]
vmax = max(vals) if vals else 1
# headroom
vmax = vmax * 1.18 if vmax > 0 else 1
n = len(series)
gap = int(48 * S)
usable = (right - left)
bar_w = int((usable - gap * (n + 1)) / max(n, 1))
bar_w = min(bar_w, int(240 * S))
# center the group
total_w = n * bar_w + (n - 1) * gap
x0 = left + (usable - total_w) // 2
# track
lfont = font_regular(18)
nfont = font_bold(28)
labelf = font_medium(18)
for i, s in enumerate(series):
x = x0 + i * (bar_w + gap)
v = s["value"]
h = 0 if not v else int((v / vmax) * (bottom - top))
y = bottom - h
# track
rounded(d, (x, top, x + bar_w, bottom), 16, fill=TRACK)
color = s.get("color", BLUE)
if h > 0:
rounded(d, (x, y, x + bar_w, bottom), 16, fill=color)
# re-fill bottom corners as square so only the top is rounded when bar is short
if h < 32 * S:
d.rectangle((x, y + h // 2, x + bar_w, bottom), fill=color)
# value on top
label = fmt_num(v, unit)
tw = text_w(d, label, nfont)
d.text((x + (bar_w - tw) // 2, y - int(48 * S)), label, font=nfont, fill=INK)
# category
cat = s["label"]
# wrap long labels
cw = text_w(d, cat, labelf)
d.text((x + (bar_w - cw) // 2, bottom + int(18 * S)), cat, font=labelf, fill=MUTED)
if caption:
cfont = font_regular(16)
d.text((80 * S, (H - 110) * S), caption, font=cfont, fill=SOFT)
downsample(img).save(path, "PNG", optimize=True)
print("wrote", path)
def median(xs):
xs = sorted(xs)
n = len(xs)
if n == 0:
return None
mid = n // 2
return xs[mid] if n % 2 else (xs[mid - 1] + xs[mid]) / 2.0
def main():
workdir = Path(sys.argv[1] if len(sys.argv) > 1 else "/workspace/cellgemma-bench")
summary_path = Path(sys.argv[2]) if len(sys.argv) > 2 else workdir / "results" / "summary.json"
out = Path(sys.argv[3]) if len(sys.argv) > 3 else workdir / "charts"
out.mkdir(parents=True, exist_ok=True)
data = json.loads(summary_path.read_text())
raw_path = summary_path.parent / "raw_runs.json"
raw = json.loads(raw_path.read_text()) if raw_path.exists() else []
headline = data["headline"]
tasks = data["tasks"]
load = data["load"]
versions = data.get("versions", {})
settings = data.get("settings", {})
dtype = settings.get("dtype", "bf16")
footer = (
f"M5 Pro 64GB · transformers {versions.get('transformers', '')} · "
f"torch {versions.get('torch', '')} · {dtype} · background app on"
)
colors = [BLUE, GREEN, RED, YELLOW]
labels = {
"tahoe_panobinostat": "Tahoe Panobinostat",
"k562_myc_knockdown": "K562 MYC knockdown",
}
names = list(tasks.keys())
def series_for(metric_key, value_map=None):
ser = []
for i, name in enumerate(names):
val = value_map[name] if value_map is not None else tasks[name].get(metric_key, {}).get("median")
ser.append({
"label": labels.get(name, tasks[name].get("label", name)),
"value": val,
"color": colors[i % len(colors)],
})
return ser
# TTFT-derived prefill (generate path, not the full-logits probe)
prefill_ttft = {}
for r in raw:
if r.get("phase") != "timed":
continue
g = r.get("generate") or {}
v = g.get("prefill_tok_s_from_ttft")
if v is None and g.get("ttft_s"):
v = r.get("input_tokens", 0) / g["ttft_s"]
prefill_ttft.setdefault(r["task"], []).append(v)
prefill_med = {k: median(vs) for k, vs in prefill_ttft.items()}
# 1. Load time
load_s = load.get("total_load_s", {}).get("median")
vals = load.get("total_load_s", {}).get("values") or []
cap = "Median of 3 loads"
if len(vals) == 3:
cap = f"Median of 3 loads. First load {vals[0]:.1f}s, then {vals[1]:.1f}s and {vals[2]:.1f}s from a warm cache."
single_metric(
out / "01_load_time.png",
"Load time",
"google/cellgemma-e4b · official transformers path, bf16, MPS",
footer,
load_s,
"s",
cap,
BLUE,
)
# 2. Peak memory - honest working-set numbers, not the MPS allocator's climb
grouped_bars(
out / "02_peak_memory.png",
"Peak memory",
"This process and the loaded weights · background app was also running",
footer,
[
{"label": "Model weights", "value": load.get("param_gb"), "color": BLUE},
{"label": "MPS driver at load", "value": load.get("peak_mps_driver_gb", {}).get("median"), "color": GREEN},
{"label": "RSS, Tahoe generate", "value": tasks["tahoe_panobinostat"]["peak_rss_gb"]["median"], "color": YELLOW},
],
" GB",
"RSS is this Python process. MPS driver later climbed to 41 GB after long 8,192-token runs (KV cache plus allocator growth).",
)
# 3. Prefill from TTFT
grouped_bars(
out / "03_prefill_toks.png",
"Prefill speed",
"Official card prompts, measured as prompt tokens divided by time to first token",
footer,
series_for("prefill_tok_s", prefill_med),
" tok/s",
"Tahoe prompt 4,128 tokens, K562 prompt 4,484 tokens. First runs were slower and are included in the median.",
)
# 4. Decode
grouped_bars(
out / "04_decode_toks.png",
"Decode speed",
"Tokens after the first · official sampling, temperature 0.7",
footer,
series_for("decode_tok_s"),
" tok/s",
"Median of 3 timed runs after one warmup. Spread was under 6%.",
)
# 5. TTFT
grouped_bars(
out / "05_ttft.png",
"Time to first token",
"Includes prefill of the official card prompt",
footer,
series_for("ttft_s"),
" s",
"Tahoe prompt 4,128 tokens, K562 prompt 4,484 tokens.",
)
# 6. Virtual screen e2e - call out the 8192 cap
grouped_bars(
out / "06_virtual_screen_time.png",
"Time per virtual screen",
"End to end: generate the ranked gene list and run the ExpressionDecoder",
footer,
series_for("e2e_virtual_screen_s"),
" s",
"Tahoe hit the card's 8,192-token cap on every run. K562 stopped on its own (median 934 tokens).",
)
print("all charts written to", out)
if prefill_med:
print("ttft-derived prefill medians:", prefill_med)
if __name__ == "__main__":
main()