File size: 11,025 Bytes
c1013dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#!/usr/bin/env python3
"""Rebuild the localLLMrig open dataset from the public site API and the showdown file.

Usage:
  python3 scripts/build.py            # use the JSON snapshots in snapshot/
  python3 scripts/build.py --fetch    # refresh snapshot/ from https://localllmrig.com first

Only the Python standard library is used. Every speed number written by this
script is a formula ESTIMATE (estimated=true), except the showdown CPU numbers,
which are measurements of one run on a CPU-only cloud VM.
"""
import csv, json, statistics, sys, urllib.request
from datetime import date
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SNAP = ROOT / "snapshot"
DATA = ROOT / "data"
BASE = "https://localllmrig.com"
SNAP_DATE = "2026-10-17"

# Mirrors lib/formula.ts on localllmrig.com (priceAsOf 2026-10-14). Assumptions, not measurements.
FORMULA = {
    "quantBytesPerParam": {"Q4": 0.60, "Q5": 0.71, "Q8": 1.07, "FP16": 2.0},
    "overheadGb": 0.8,
    "gpuContextReserveGb": 0.6,
    "systemRamReserveGb": 8,
    "utilization": {"nvidia": 0.78, "amd": 0.4, "apple": 0.48, "mixed": 0.5},
    "multiGpuBandwidthFactor": 0.55,
    "cpuBandwidthUtilization": 0.45,
    "perTokenOverheadSec": 0.0002,
}
# Not exposed by /api/hardware; copied from data/hardware.ts on the site (gpus[].count, cpuBandwidthGbps).
GPU_COUNT = {"build-dual-3090": 2, "build-dual-4090": 2}
CPU_BW = {"build-3060": 51, "build-3090": 51, "build-dual-3090": 51,
          "build-4060ti": 90, "build-7900xtx": 90, "build-4090": 90, "build-5090": 90, "build-dual-4090": 90}
QUANT_NAME = {"Q4": "Q4_K_M", "Q5": "Q5 (~0.71 bytes/param)", "Q8": "Q8", "FP16": "FP16"}


def fetch(path, out):
    req = urllib.request.Request(BASE + path, headers={"User-Agent": "localllmrig-data-build"})
    out.write_bytes(urllib.request.urlopen(req, timeout=60).read())


def mac_reserve(gb):
    return 6 if gb <= 16 else 7 if gb <= 24 else 8 if gb <= 36 else 10 if gb <= 64 else 12


def gpu_count(h):
    if h["memoryKind"] == "unified":
        return 0
    return GPU_COUNT.get(h["id"], 1)


def usable_gb(h):
    if h["memoryKind"] == "unified":
        return max(0.0, h["memoryGb"] - mac_reserve(h["memoryGb"]))
    return max(0.0, h["memoryGb"] - FORMULA["gpuContextReserveGb"] * max(1, gpu_count(h)))


def offload_gb(h):
    if h["memoryKind"] == "unified" or h["systemRamGb"] <= 0:
        return usable_gb(h)
    return usable_gb(h) + max(0, h["systemRamGb"] - FORMULA["systemRamReserveGb"])


def fit_kind(h, total):
    if h.get("addressableMemoryKnown") is False:
        return "unscored"
    if total <= usable_gb(h):
        return "full"
    if h["memoryKind"] == "vram" and total <= offload_gb(h):
        return "offload"
    return "no"


def tok_s(h, weights, kv, fit):
    if h.get("bandwidthGbps") in (None, 0):
        return None
    multi = FORMULA["multiGpuBandwidthFactor"] if gpu_count(h) > 1 and h["memoryKind"] == "vram" else 1
    bw = max(h["bandwidthGbps"] * FORMULA["utilization"][h["vendor"]] * multi, 0.1)
    streamed = weights + kv
    if fit == "full":
        return 1 / (streamed / bw + FORMULA["perTokenOverheadSec"])
    usable = max(usable_gb(h), 0)
    gpu_s = min(streamed, usable)
    cpu_s = max(0, streamed - gpu_s)
    cpu_bw = max(CPU_BW.get(h["id"], 0) * FORMULA["cpuBandwidthUtilization"], 1)
    return 1 / (gpu_s / bw + cpu_s / cpu_bw + FORMULA["perTokenOverheadSec"])


def precise_kv(m, ctx, api_kv):
    """Full-attention KV cache in FP16. Used only when it rounds to the API value;
    otherwise (sliding-window or hybrid models) the API's rounded kvGb is kept."""
    kv = 2 * m["kvHeads"] * m["headDim"] * 2 * m["layers"] * ctx / 1e9
    return kv if round(kv, 2) == api_kv else api_kv


def write_csv(path, rows, fields):
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        w.writeheader()
        for r in rows:
            w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in fields})


def main():
    models_file = SNAP / f"api-models-{SNAP_DATE}.json"
    hw_file = SNAP / f"api-hardware-{SNAP_DATE}.json"
    if "--fetch" in sys.argv:
        fetch("/api/models", models_file)
        fetch("/api/hardware", hw_file)
    mj = json.loads(models_file.read_text())
    hj = json.loads(hw_file.read_text())
    sd = json.loads((SNAP / "showdown-2026-10-17.json").read_text())
    DATA.mkdir(exist_ok=True)
    (DATA / "showdown").mkdir(exist_ok=True)
    ctx = mj["contextTokens"]

    # models
    mrows = []
    for m in mj["models"]:
        r = {k: m.get(k) for k in ["id", "name", "family", "paramsB", "activeParamsB", "paramsEstimated",
                                   "layers", "kvHeads", "headDim", "maxContext", "architectureSourceUrl"]}
        for q, v in m["memory"]["quants"].items():
            r[f"mem_{q}_total_gb_est"] = v["totalGb"]
        r["context_tokens"] = ctx
        r["page_url"] = f"{BASE}/models/{m['id']}?utm_source=github&utm_medium=dataset&utm_campaign=open_data"
        mrows.append(r)
    write_csv(DATA / "models.csv", mrows, list(mrows[0].keys()))

    # hardware + prices
    hrows = []
    for h in hj["hardware"]:
        p = h["price"]
        hrows.append({
            "id": h["id"], "name": h["name"], "kind": h["kind"], "vendor": h["vendor"],
            "memory_kind": h["memoryKind"], "memory_gb": h["memoryGb"],
            "addressable_memory_known": h.get("addressableMemoryKnown"),
            "usable_gb_assumed": round(usable_gb(h), 2) if h.get("addressableMemoryKnown") is not False else None,
            "gpu_count": gpu_count(h), "bandwidth_gbps": h.get("bandwidthGbps"),
            "bandwidth_source_url": h.get("bandwidthSourceUrl"), "system_ram_gb": h["systemRamGb"],
            "used_market": h["usedMarket"],
            "price_eur_incl_vat": p.get("amountEur"), "price_usd_fx_estimate": p.get("amountUsd"),
            "price_label": p.get("amountLabel"), "price_verified": p.get("verified"),
            "price_as_of": p.get("asOf"), "price_source_name": p.get("sourceName"),
            "price_source_url": p.get("sourceUrl"), "price_note": p.get("note"),
            "page_url": f"{BASE}/hardware/{h['id']}?utm_source=github&utm_medium=dataset&utm_campaign=open_data",
        })
    write_csv(DATA / "hardware.csv", hrows, list(hrows[0].keys()))

    # price per GB of memory, cards only, priced, verified source
    pv = []
    for h, r in zip(hj["hardware"], hrows):
        if h["kind"] != "card" or r["price_eur_incl_vat"] is None:
            continue
        pv.append({**r, "eur_per_gb_vram": round(r["price_eur_incl_vat"] / h["memoryGb"], 2)})
    pv.sort(key=lambda r: r["eur_per_gb_vram"])
    write_csv(DATA / "gpu-price-per-gb-vram.csv", pv,
              ["id", "name", "memory_gb", "price_eur_incl_vat", "eur_per_gb_vram", "price_label",
               "price_verified", "price_as_of", "price_source_name", "price_source_url"])

    # fit + estimated decode speed matrix
    erows = []
    for m in mj["models"]:
        for q, v in m["memory"]["quants"].items():
            weights = m["paramsB"] * FORMULA["quantBytesPerParam"][q]
            kv = precise_kv(m, ctx, v["kvGb"])
            total = weights + kv + FORMULA["overheadGb"]
            for h in hj["hardware"]:
                fit = fit_kind(h, total)
                est = tok_s(h, weights, kv, fit) if fit in ("full", "offload") else None
                erows.append({
                    "model_id": m["id"], "hardware_id": h["id"], "quant": q, "quant_name": QUANT_NAME[q],
                    "context_tokens": ctx, "need_gb_est": round(total, 2),
                    "usable_gb_assumed": round(usable_gb(h), 2) if fit != "unscored" else None,
                    "fit": fit, "est_decode_tok_s": round(est, 1) if est else None,
                    "estimated": True, "method": "localllmrig formula 2026-10-14 (bandwidth-bound decode)",
                })
    write_csv(DATA / "fit-estimates.csv", erows, list(erows[0].keys()))

    # community measurements (third party, labelled)
    crow = []
    for m in mj["models"]:
        cm = m.get("communityMeasurement")
        if not cm:
            continue
        for row in cm["rows"]:
            crow.append({"model_id": m["id"], "hardware": row["hardware"], "tok_s": row["tokensPerSec"],
                         "label": cm["label"], "source_name": cm["sourceName"], "source_url": cm["sourceUrl"],
                         "published": cm["published"], "note": cm["note"]})
    if crow:
        write_csv(DATA / "community-measurements.csv", crow, list(crow[0].keys()))

    # showdown
    srow, orow = [], []
    for m in sd["models"]:
        s = m["speed"]
        srow.append({"model_id": m["id"], "name": m["name"], "maker": m["maker"], "params_b": m["params_b"],
                     "license": m["license"], "license_url": m["license_url"], "gguf_file": m["gguf_file"],
                     "gguf_url": m["gguf_url"], "gguf_sha256": m["gguf_sha256"],
                     "gen_tok_s_median": s["gen_tok_per_s_median"], "gen_tok_s_min": s["gen_tok_per_s_min"],
                     "gen_tok_s_max": s["gen_tok_per_s_max"], "prompt_tok_s_median": s["prompt_tok_per_s_median"],
                     "truncated_outputs": sum(1 for o in m["outputs"] if o.get("truncated_at_cap")),
                     "speed_label": s["label"]})
        for o in m["outputs"]:
            orow.append({"model_id": m["id"], "prompt_id": o["prompt_id"], "finish_reason": o["finish_reason"],
                         "truncated_at_cap": o["truncated_at_cap"], "generated_tokens": o["generated_tokens"],
                         "prompt_tokens": o["prompt_tokens"], "gen_tok_s": o["gen_tok_per_s"],
                         "check": o.get("check"), "output": o["output"]})
    write_csv(DATA / "showdown" / "speeds-2026-10-17.csv", srow, list(srow[0].keys()))
    write_csv(DATA / "showdown" / "outputs-2026-10-17.csv", orow, list(orow[0].keys()))
    write_csv(DATA / "showdown" / "prompts-2026-10-17.csv", sd["prompts"], ["id", "category", "prompt", "reference_answer"])
    (DATA / "showdown" / "showdown-2026-10-17.json").write_text(json.dumps(sd, ensure_ascii=False, indent=1))

    bundle = {
        "name": "localLLMrig open data", "license": "CC-BY-4.0",
        "attribution": "Data: localLLMrig (https://localllmrig.com), CC BY 4.0",
        "snapshot_date": SNAP_DATE, "built": date.today().isoformat(),
        "estimatesAreNotMeasurements": True, "formula": FORMULA, "context_tokens": ctx,
        "models": mrows, "hardware": hrows, "gpu_price_per_gb_vram": pv,
        "fit_estimates": erows, "community_measurements": crow, "showdown_speeds": srow,
    }
    (DATA / "localllmrig-data.json").write_text(json.dumps(bundle, ensure_ascii=False, indent=1))
    print(f"models={len(mrows)} hardware={len(hrows)} price_rows={len(pv)} fit_rows={len(erows)} "
          f"community={len(crow)} showdown_models={len(srow)} outputs={len(orow)}")


if __name__ == "__main__":
    main()