lfm25-hermes-tool-trace-analysis / scripts /build_visual_assets.py
sjakek's picture
Update Hermes-tuned KXL naming and visuals
23a6592 verified
Raw
History Blame Contribute Delete
19.6 kB
#!/usr/bin/env python3
"""Build small SVG visualizations for the Hugging Face analysis repo.
The renderer intentionally avoids third-party plotting dependencies so the
figures can be regenerated on a fresh Mac with only the standard library.
"""
from __future__ import annotations
import html
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "visuals"
BG = "#ffffff"
INK = "#1f2937"
MUTED = "#6b7280"
GRID = "#e5e7eb"
BLUE = "#2563eb"
TEAL = "#0891b2"
GREEN = "#059669"
ORANGE = "#d97706"
RED = "#dc2626"
PURPLE = "#7c3aed"
SLATE = "#475569"
def esc(value: object) -> str:
return html.escape(str(value), quote=True)
def write_svg(path: Path, width: int, height: int, body: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
f"""<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img">
<rect width="100%" height="100%" fill="{BG}"/>
<style>
.title {{ font: 700 22px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {INK}; }}
.subtitle {{ font: 400 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {MUTED}; }}
.label {{ font: 600 12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {INK}; }}
.small {{ font: 400 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {MUTED}; }}
.axis {{ stroke: {GRID}; stroke-width: 1; }}
.tick {{ font: 400 10px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {MUTED}; }}
.value {{ font: 700 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {INK}; }}
.node-title {{ font: 700 13px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {INK}; }}
.node-text {{ font: 400 11px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; fill: {MUTED}; }}
</style>
{body}
</svg>
""",
encoding="utf-8",
)
def load_json(rel: str) -> dict:
return json.loads((ROOT / rel).read_text(encoding="utf-8"))
def header(title: str, subtitle: str) -> str:
return (
f'<text x="32" y="38" class="title">{esc(title)}</text>'
f'<text x="32" y="60" class="subtitle">{esc(subtitle)}</text>'
)
def line_chart_path(points: list[tuple[float, float]]) -> str:
if not points:
return ""
start = f"M {points[0][0]:.1f} {points[0][1]:.1f}"
rest = " ".join(f"L {x:.1f} {y:.1f}" for x, y in points[1:])
return f"{start} {rest}"
def render_pipeline() -> None:
width, height = 1240, 560
nodes = [
("Base model", "LiquidAI LFM2.5-8B-A1B", "BF16 MLX source", 34, 96, BLUE),
("Mixed core", "Quantize MoE experts to int8", "Routers/non-experts stay BF16", 274, 96, TEAL),
("Grouped training", "3 epochs, 1,746 steps", "overlapping groups g4/s3 at 10K cap", 514, 96, GREEN),
("Direct checkpoint", "step_01746_final", "experts + routers changed", 754, 96, ORANGE),
("Repair adapters", "Iter01 to Iter10 LoRA", "structured tool-call targets", 994, 96, PURPLE),
("Parser-disabled evals", "MLX fixed-Hermes 43/43", "0 text-tool leaks", 274, 328, GREEN),
("Export path", "Fuse + dequantize", "HF/safetensors source for GGUF", 514, 328, BLUE),
("XL GGUF quants", "Q4/Q5/Q6/Q8 KXL", "all pass 43-case llama.cpp eval", 754, 328, TEAL),
]
body = header(
"End-to-end local Mac fine-tuning pipeline",
"Mixed int8-expert training creates the base behavioral change; LoRA repairs tool-call formatting and routing; GGUF export validates llama.cpp.",
)
body += '<defs><marker id="arrow" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto"><path d="M0,0 L0,6 L9,3 z" fill="#94a3b8"/></marker></defs>'
arrows = [
(214, 172, 270, 172),
(454, 172, 510, 172),
(694, 172, 750, 172),
(934, 172, 990, 172),
(1084, 254, 420, 324),
(454, 404, 510, 404),
(694, 404, 750, 404),
]
for x1, y1, x2, y2 in arrows:
body += f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="#94a3b8" stroke-width="2" marker-end="url(#arrow)"/>'
for title, l1, l2, x, y, color in nodes:
body += f'<rect x="{x}" y="{y}" width="210" height="152" rx="8" fill="#f8fafc" stroke="{color}" stroke-width="2"/>'
body += f'<circle cx="{x+22}" cy="{y+25}" r="7" fill="{color}"/>'
body += f'<text x="{x+40}" y="{y+31}" class="node-title">{esc(title)}</text>'
body += f'<text x="{x+18}" y="{y+72}" class="node-text">{esc(l1)}</text>'
body += f'<text x="{x+18}" y="{y+96}" class="node-text">{esc(l2)}</text>'
write_svg(OUT / "pipeline_overview.svg", width, height, body)
def render_group_sweep() -> None:
data = load_json("reports/group_sweep_10k.json")
rows = [r for r in data["results"] if r.get("ok")]
width, height = 980, 520
left, top, chart_w, chart_h = 72, 100, 820, 300
max_mem = max(r["peak_memory_gb"] for r in rows) * 1.08
max_time = max(r["elapsed_s"] for r in rows) * 1.08
x_step = chart_w / len(rows)
bar_w = 54
body = header(
"Group size sweep at 10K tokens",
"Larger simultaneous layer groups improve elapsed time, but group size 11 brushes the hard 60 GB limit.",
)
for i in range(0, 5):
y = top + chart_h - i * chart_h / 4
body += f'<line x1="{left}" y1="{y:.1f}" x2="{left+chart_w}" y2="{y:.1f}" class="axis"/>'
body += f'<text x="{left-10}" y="{y+4:.1f}" text-anchor="end" class="tick">{max_mem*i/4:.0f} GB</text>'
body += f'<line x1="{left}" y1="{top}" x2="{left}" y2="{top+chart_h}" stroke="{GRID}"/>'
body += f'<line x1="{left+chart_w}" y1="{top}" x2="{left+chart_w}" y2="{top+chart_h}" stroke="{GRID}"/>'
time_points = []
for idx, row in enumerate(rows):
cx = left + x_step * idx + x_step / 2
mem_h = chart_h * row["peak_memory_gb"] / max_mem
x = cx - bar_w / 2
y = top + chart_h - mem_h
fill = GREEN if row["group_size"] == data["recommended_group_size"] else BLUE
body += f'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_w}" height="{mem_h:.1f}" rx="4" fill="{fill}" opacity="0.86"/>'
body += f'<text x="{cx:.1f}" y="{y-8:.1f}" text-anchor="middle" class="value">{row["peak_memory_gb"]:.1f}</text>'
body += f'<text x="{cx:.1f}" y="{top+chart_h+28}" text-anchor="middle" class="label">g{row["group_size"]}</text>'
ty = top + chart_h - chart_h * row["elapsed_s"] / max_time
time_points.append((cx, ty))
body += f'<path d="{line_chart_path(time_points)}" fill="none" stroke="{ORANGE}" stroke-width="3"/>'
for (cx, ty), row in zip(time_points, rows):
body += f'<circle cx="{cx:.1f}" cy="{ty:.1f}" r="5" fill="{ORANGE}"/>'
body += f'<text x="{cx:.1f}" y="{ty-12:.1f}" text-anchor="middle" class="small">{row["elapsed_s"]:.0f}s</text>'
body += f'<line x1="{left}" y1="{top+chart_h*(1-55/max_mem):.1f}" x2="{left+chart_w}" y2="{top+chart_h*(1-55/max_mem):.1f}" stroke="{GREEN}" stroke-dasharray="6 5" stroke-width="2"/>'
body += f'<line x1="{left}" y1="{top+chart_h*(1-60/max_mem):.1f}" x2="{left+chart_w}" y2="{top+chart_h*(1-60/max_mem):.1f}" stroke="{RED}" stroke-dasharray="6 5" stroke-width="2"/>'
body += f'<text x="{left+chart_w+12}" y="{top+chart_h*(1-55/max_mem)+4:.1f}" class="small">55 GB target</text>'
body += f'<text x="{left+chart_w+12}" y="{top+chart_h*(1-60/max_mem)+4:.1f}" class="small">60 GB hard stop</text>'
body += f'<rect x="{left}" y="{height-58}" width="14" height="14" fill="{BLUE}" opacity="0.86"/><text x="{left+22}" y="{height-46}" class="small">Peak memory, GB</text>'
body += f'<circle cx="{left+180}" cy="{height-51}" r="5" fill="{ORANGE}"/><text x="{left+192}" y="{height-46}" class="small">Elapsed seconds</text>'
body += f'<rect x="{left+332}" y="{height-58}" width="14" height="14" fill="{GREEN}" opacity="0.86"/><text x="{left+354}" y="{height-46}" class="small">Selected default group size</text>'
write_svg(OUT / "group_sweep_memory_time.svg", width, height, body)
def render_dataset_filtering() -> None:
data = load_json("datasets/hermes_filtered_text_10k_manifest.json")["splits"]
width, height = 880, 460
left, top, chart_w, chart_h = 86, 100, 680, 260
labels = list(data.keys())
max_total = max(v["kept"] + v["dropped_from_16k_artifact"] for v in data.values())
body = header(
"10K token-cap dataset retained the shorter Hermes traces",
"The cap is per training example, not a total-token cap; longer rows were excluded from the 16K artifact.",
)
for i in range(5):
y = top + chart_h - i * chart_h / 4
body += f'<line x1="{left}" y1="{y:.1f}" x2="{left+chart_w}" y2="{y:.1f}" class="axis"/>'
body += f'<text x="{left-12}" y="{y+4:.1f}" text-anchor="end" class="tick">{max_total*i/4:.0f}</text>'
slot = chart_w / len(labels)
bar_w = 86
for idx, label in enumerate(labels):
kept = data[label]["kept"]
dropped = data[label]["dropped_from_16k_artifact"]
total = kept + dropped
x = left + idx * slot + slot / 2 - bar_w / 2
kept_h = chart_h * kept / max_total
drop_h = chart_h * dropped / max_total
y_kept = top + chart_h - kept_h
y_drop = y_kept - drop_h
body += f'<rect x="{x:.1f}" y="{y_drop:.1f}" width="{bar_w}" height="{drop_h:.1f}" fill="{ORANGE}" opacity="0.72"/>'
body += f'<rect x="{x:.1f}" y="{y_kept:.1f}" width="{bar_w}" height="{kept_h:.1f}" fill="{GREEN}" opacity="0.88"/>'
body += f'<text x="{x+bar_w/2:.1f}" y="{y_kept+18:.1f}" text-anchor="middle" class="value" fill="#fff">{kept}</text>'
body += f'<text x="{x+bar_w/2:.1f}" y="{y_drop-8:.1f}" text-anchor="middle" class="small">total {total}</text>'
body += f'<text x="{x+bar_w/2:.1f}" y="{top+chart_h+28}" text-anchor="middle" class="label">{esc(label)}</text>'
body += f'<rect x="{left}" y="{height-54}" width="14" height="14" fill="{GREEN}" opacity="0.88"/><text x="{left+22}" y="{height-42}" class="small">Kept at 10K cap</text>'
body += f'<rect x="{left+172}" y="{height-54}" width="14" height="14" fill="{ORANGE}" opacity="0.72"/><text x="{left+194}" y="{height-42}" class="small">Dropped from 16K artifact</text>'
write_svg(OUT / "dataset_filtering_10k.svg", width, height, body)
def render_eval_progression() -> None:
colloquial = load_json("reports/colloquial_tool_router_repair_report.json")["eval_summaries"]
iter04 = colloquial["iter04_masked_colloquial_openai_parser_disabled"]
stages = [
("Direct\ncheckpoint", 5, 6, 2, 3),
("Iter01\nLoRA", 6, 6, 3, 3),
("Iter04\ncolloquial", iter04["passed"], iter04["total"], iter04["structured_tool_cases_passed"], iter04["tool_cases"]),
("Iter10\nfixed Hermes", 43, 43, 28, 28),
("GGUF XL\nquants", 43, 43, 28, 28),
]
width, height = 1020, 520
left, top, chart_w, chart_h = 78, 102, 820, 292
body = header(
"Tool-call reliability improved in stages",
"The broad colloquial loop exposed routing failures; structured fixed-Hermes data closed the release suite.",
)
for i in range(6):
y = top + chart_h - i * chart_h / 5
body += f'<line x1="{left}" y1="{y:.1f}" x2="{left+chart_w}" y2="{y:.1f}" class="axis"/>'
body += f'<text x="{left-12}" y="{y+4:.1f}" text-anchor="end" class="tick">{i*20}%</text>'
slot = chart_w / len(stages)
for idx, (label, passed, total, tool_passed, tool_total) in enumerate(stages):
cx = left + idx * slot + slot / 2
overall = passed / total
structured = tool_passed / tool_total
for j, (rate, color, val) in enumerate([(overall, BLUE, f"{passed}/{total}"), (structured, GREEN, f"{tool_passed}/{tool_total}")]):
bw = 44
x = cx - 50 + j * 56
h = chart_h * rate
y = top + chart_h - h
body += f'<rect x="{x:.1f}" y="{y:.1f}" width="{bw}" height="{h:.1f}" rx="4" fill="{color}" opacity="0.88"/>'
body += f'<text x="{x+bw/2:.1f}" y="{y-8:.1f}" text-anchor="middle" class="value">{val}</text>'
y0 = top + chart_h + 26
for line in label.split("\n"):
body += f'<text x="{cx:.1f}" y="{y0:.1f}" text-anchor="middle" class="small">{esc(line)}</text>'
y0 += 15
body += f'<rect x="{left}" y="{height-54}" width="14" height="14" fill="{BLUE}" opacity="0.88"/><text x="{left+22}" y="{height-42}" class="small">Overall pass rate</text>'
body += f'<rect x="{left+178}" y="{height-54}" width="14" height="14" fill="{GREEN}" opacity="0.88"/><text x="{left+200}" y="{height-42}" class="small">Structured tool-call pass rate</text>'
write_svg(OUT / "eval_progression.svg", width, height, body)
def render_quant_size() -> None:
data = load_json("release_summary.json")
rows = []
for name, item in data["gguf_quants"].items():
if "Q4" in name:
label = "Q4KXL"
elif "Q5" in name:
label = "Q5KXL"
elif "Q6" in name:
label = "Q6KXL"
else:
label = "Q8KXL"
rows.append((label, item["bytes"] / 1024**3))
rows.sort(key=lambda x: x[1])
width, height = 900, 460
left, top, chart_w, chart_h = 90, 96, 680, 260
max_size = max(v for _, v in rows) * 1.16
body = header(
"GGUF Hermes-tuned KXL size/quality tradeoff",
"All four stock llama.cpp KXL quants passed the same 43-case fixed-Hermes suite at 64K context.",
)
for i in range(5):
y = top + chart_h - i * chart_h / 4
body += f'<line x1="{left}" y1="{y:.1f}" x2="{left+chart_w}" y2="{y:.1f}" class="axis"/>'
body += f'<text x="{left-12}" y="{y+4:.1f}" text-anchor="end" class="tick">{max_size*i/4:.1f} GiB</text>'
slot = chart_w / len(rows)
for idx, (label, gib) in enumerate(rows):
cx = left + idx * slot + slot / 2
h = chart_h * gib / max_size
x = cx - 48
y = top + chart_h - h
color = [GREEN, TEAL, BLUE, PURPLE][idx]
body += f'<rect x="{x:.1f}" y="{y:.1f}" width="96" height="{h:.1f}" rx="4" fill="{color}" opacity="0.88"/>'
body += f'<text x="{cx:.1f}" y="{y-10:.1f}" text-anchor="middle" class="value">{gib:.1f} GiB</text>'
body += f'<text x="{cx:.1f}" y="{top+chart_h+28}" text-anchor="middle" class="label">{esc(label)}</text>'
body += f'<text x="{cx:.1f}" y="{top+chart_h+48}" text-anchor="middle" class="small">43/43 pass</text>'
write_svg(OUT / "gguf_quant_size_quality.svg", width, height, body)
def render_memory_model() -> None:
data = load_json("reports/memory_estimate.json")
stored = data["stored_weights_gb"]
gradients = data["training_gradient_pressure_gb"]
width, height = 980, 500
body = header(
"Why mixed quantization made local Mac training plausible",
"Storing experts as int8 reduces persistent weight size, but naive simultaneous gradients would still be too large.",
)
x0, y0 = 76, 128
max_w = 760
total = stored["total_estimate"][1]
parts = [
("Experts int8", stored["experts_int8"], GREEN),
("Non-experts BF16", stored["non_experts_bf16"], BLUE),
("Scales/metadata", stored["scale_metadata_estimate"][1], ORANGE),
]
body += f'<text x="{x0}" y="{y0-18}" class="label">Stored mixed checkpoint estimate: {total:.2f} GB</text>'
cur = x0
for label, value, color in parts:
w = max_w * value / total
body += f'<rect x="{cur:.1f}" y="{y0}" width="{w:.1f}" height="52" fill="{color}" opacity="0.86"/>'
body += f'<text x="{cur+w/2:.1f}" y="{y0+31}" text-anchor="middle" class="value" fill="#fff">{value:.2f} GB</text>'
cur += w
legend_y = y0 + 80
lx = x0
for label, _, color in parts:
body += f'<rect x="{lx}" y="{legend_y}" width="13" height="13" fill="{color}" opacity="0.86"/><text x="{lx+20}" y="{legend_y+11}" class="small">{esc(label)}</text>'
lx += 180
bars = [
("Naive STE FP32 expert gradients", gradients["expert_grad_float32_if_naive_ste"], RED),
("BF16 expert gradients if supported", gradients["expert_grad_bf16_if_supported"], ORANGE),
("Compressed int8/sign update target", gradients["expert_grad_int8_sign_if_custom_optimizer"], GREEN),
]
bx, by, bw_max, bh = 76, 286, 760, 34
max_g = max(v for _, v, _ in bars)
body += f'<text x="{bx}" y="{by-22}" class="label">Gradient/update pressure alternatives</text>'
for idx, (label, value, color) in enumerate(bars):
y = by + idx * 54
w = bw_max * value / max_g
body += f'<text x="{bx}" y="{y-6}" class="small">{esc(label)}</text>'
body += f'<rect x="{bx}" y="{y}" width="{w:.1f}" height="{bh}" rx="4" fill="{color}" opacity="0.82"/>'
body += f'<text x="{bx+w+10:.1f}" y="{y+23}" class="value">{value:.1f} GB</text>'
write_svg(OUT / "memory_model.svg", width, height, body)
def render_category_eval() -> None:
summary = load_json("evals/iter10_fused_all_fixed_hermes_parser_disabled.json")["summary"]
metrics = summary["category_metrics"]
rows = [(k, v["passed"], v["total"]) for k, v in metrics.items()]
width, height = 900, 460
left, top, chart_w, chart_h = 80, 98, 690, 260
body = header(
"Fixed-Hermes parser-disabled eval coverage",
"The final fused MLX model passed browser, terminal, file, finalization, and no-tool categories with structured tool_calls.",
)
for i in range(6):
y = top + chart_h - i * chart_h / 5
body += f'<line x1="{left}" y1="{y:.1f}" x2="{left+chart_w}" y2="{y:.1f}" class="axis"/>'
body += f'<text x="{left-12}" y="{y+4:.1f}" text-anchor="end" class="tick">{i*20}%</text>'
slot = chart_w / len(rows)
for idx, (label, passed, total) in enumerate(rows):
rate = passed / total
cx = left + idx * slot + slot / 2
h = chart_h * rate
x = cx - 42
y = top + chart_h - h
body += f'<rect x="{x:.1f}" y="{y:.1f}" width="84" height="{h:.1f}" rx="4" fill="{BLUE}" opacity="0.86"/>'
body += f'<text x="{cx:.1f}" y="{y-9:.1f}" text-anchor="middle" class="value">{passed}/{total}</text>'
body += f'<text x="{cx:.1f}" y="{top+chart_h+28}" text-anchor="middle" class="label">{esc(label)}</text>'
write_svg(OUT / "fixed_hermes_category_eval.svg", width, height, body)
def main() -> None:
render_pipeline()
render_group_sweep()
render_dataset_filtering()
render_eval_progression()
render_quant_size()
render_memory_model()
render_category_eval()
summary = {
"generated": [
"visuals/pipeline_overview.svg",
"visuals/group_sweep_memory_time.svg",
"visuals/dataset_filtering_10k.svg",
"visuals/eval_progression.svg",
"visuals/gguf_quant_size_quality.svg",
"visuals/memory_model.svg",
"visuals/fixed_hermes_category_eval.svg",
],
"sources": [
"reports/group_sweep_10k.json",
"datasets/hermes_filtered_text_10k_manifest.json",
"reports/colloquial_tool_router_repair_report.json",
"release_summary.json",
"reports/memory_estimate.json",
"evals/iter10_fused_all_fixed_hermes_parser_disabled.json",
],
}
(OUT / "visual_manifest.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
if __name__ == "__main__":
main()