#!/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""" {body} """, 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'{esc(title)}' f'{esc(subtitle)}' ) 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 += '' 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'' for title, l1, l2, x, y, color in nodes: body += f'' body += f'' body += f'{esc(title)}' body += f'{esc(l1)}' body += f'{esc(l2)}' 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'' body += f'{max_mem*i/4:.0f} GB' body += f'' body += f'' 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'' body += f'{row["peak_memory_gb"]:.1f}' body += f'g{row["group_size"]}' ty = top + chart_h - chart_h * row["elapsed_s"] / max_time time_points.append((cx, ty)) body += f'' for (cx, ty), row in zip(time_points, rows): body += f'' body += f'{row["elapsed_s"]:.0f}s' body += f'' body += f'' body += f'55 GB target' body += f'60 GB hard stop' body += f'Peak memory, GB' body += f'Elapsed seconds' body += f'Selected default group size' 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'' body += f'{max_total*i/4:.0f}' 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'' body += f'' body += f'{kept}' body += f'total {total}' body += f'{esc(label)}' body += f'Kept at 10K cap' body += f'Dropped from 16K artifact' 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'' body += f'{i*20}%' 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'' body += f'{val}' y0 = top + chart_h + 26 for line in label.split("\n"): body += f'{esc(line)}' y0 += 15 body += f'Overall pass rate' body += f'Structured tool-call pass rate' 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'' body += f'{max_size*i/4:.1f} GiB' 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'' body += f'{gib:.1f} GiB' body += f'{esc(label)}' body += f'43/43 pass' 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'Stored mixed checkpoint estimate: {total:.2f} GB' cur = x0 for label, value, color in parts: w = max_w * value / total body += f'' body += f'{value:.2f} GB' cur += w legend_y = y0 + 80 lx = x0 for label, _, color in parts: body += f'{esc(label)}' 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'Gradient/update pressure alternatives' for idx, (label, value, color) in enumerate(bars): y = by + idx * 54 w = bw_max * value / max_g body += f'{esc(label)}' body += f'' body += f'{value:.1f} GB' 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'' body += f'{i*20}%' 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'' body += f'{passed}/{total}' body += f'{esc(label)}' 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()