File size: 7,377 Bytes
0bcd139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2353a55
 
 
0bcd139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2353a55
 
 
 
 
 
 
 
 
 
 
0bcd139
 
 
 
2353a55
0bcd139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build monorepo-level dashboard from models/*/derived/summary.json + registry.json.

stdlib only — offline safe (no pip/network).
"""
from __future__ import annotations

import json
import sys
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "shared" / "scripts"))
from write_json_stable import write_json_stable  # noqa: E402
import sync_readme  # noqa: E402

MODELS_DIR = ROOT / "models"
OUT = ROOT / "derived"
REGISTRY = MODELS_DIR / "registry.json"


def load_registry() -> dict:
    if not REGISTRY.exists():
        return {"models": []}
    return json.loads(REGISTRY.read_text())


def discover_models() -> list[str]:
    return sorted(
        p.name
        for p in MODELS_DIR.iterdir()
        if p.is_dir() and (p / "Makefile").exists() and (p / "derived" / "summary.json").exists()
    )


def load_summary(model_id: str) -> dict:
    path = MODELS_DIR / model_id / "derived" / "summary.json"
    data = json.loads(path.read_text())
    data.setdefault("model_id", model_id)
    return data


def normalize_row(model_id: str, summary: dict, reg_entry: dict | None) -> dict:
    reg = reg_entry or {}
    # Prefer explicit common fields; fall back to model-specific shapes
    total = summary.get("total_params") or summary.get("total_parameters")
    if not total and summary.get("n_routed_experts"):
        # inkling-style: not in summary historically — use registry notes / fixed
        total = reg.get("total_params") or "975B (reported)"
    active = summary.get("active_params") or summary.get("active_parameters")
    if active is None and model_id == "inkling":
        active = "41B (reported)"
    if active is None and model_id == "kimi-k3":
        active = "undisclosed"

    context = summary.get("context_tokens") or summary.get("model_max_length")
    experts = None
    if summary.get("n_experts") and summary.get("experts_activated"):
        experts = f"{summary['experts_activated']}/{summary['n_experts']}"
        s = summary.get("n_shared_experts")
        if s:
            experts += f"+{s} shared"
    elif summary.get("n_routed_experts"):
        k = summary.get("num_experts_per_tok")
        s = summary.get("n_shared_experts")
        experts = f"{k}/{summary['n_routed_experts']}" + (f"+{s} shared" if s else "")

    return {
        "model_id": model_id,
        "display_name": summary.get("display_name")
        or summary.get("model")
        or reg.get("display_name")
        or model_id,
        "org": reg.get("org") or summary.get("org") or "—",
        "status": reg.get("status") or summary.get("status") or "unknown",
        "total_params": total or "—",
        "active_params": active or "—",
        "context_tokens": context,
        "experts": experts or "—",
        "hub": reg.get("hub"),
        "api_model_id": reg.get("api_model_id") or summary.get("api_model_id"),
        "generated_at_utc": summary.get("generated_at_utc"),
        "notes": reg.get("notes") or "",
        "path": f"models/{model_id}",
        "raw": summary,
    }


def render_md(rows: list[dict], generated: str) -> str:
    lines = [
        "# Study dashboard",
        "",
        f"> Auto-generated by `shared/scripts/build_dashboard.py` · {generated}",
        ">",
        "> Do not hand-edit. Run `make dashboard` or `make check`.",
        "",
        "## Models",
        "",
        "| ID | Name | Org | Status | Total | Active | Context | Experts | Package |",
        "|---|---|---|---|---|---|---:|---|---|",
    ]
    for r in rows:
        ctx = f"{r['context_tokens']:,}" if isinstance(r["context_tokens"], int) else (r["context_tokens"] or "—")
        hub = f"[hub](https://huggingface.co/{r['hub']})" if r.get("hub") else "—"
        lines.append(
            f"| `{r['model_id']}` | {r['display_name']} | {r['org']} | `{r['status']}` | "
            f"{r['total_params']} | {r['active_params']} | {ctx} | {r['experts']} | "
            f"[{r['path']}](../{r['path']}/) |"
        )
    lines += [
        "",
        "## Links",
        "",
    ]
    for r in rows:
        bits = [f"- **{r['display_name']}** (`{r['model_id']}`)"]
        bits.append(f"  - study: [`{r['path']}`](../{r['path']}/)")
        if r.get("hub"):
            bits.append(f"  - hub: https://huggingface.co/{r['hub']}")
        if r.get("api_model_id"):
            bits.append(f"  - api: `{r['api_model_id']}`")
        if r.get("notes"):
            bits.append(f"  - {r['notes']}")
        lines.extend(bits)

    cmp_dir = ROOT / "shared" / "comparisons"
    cmp_links = []
    for name, label in (
        ("laguna-s-vs-inkling-vs-kimi.md", "Laguna · Inkling · Kimi"),
        ("inkling-vs-kimi-k3.md", "Inkling · Kimi"),
    ):
        if (cmp_dir / name).exists():
            cmp_links.append(f"- [{label}](../shared/comparisons/{name})")
    if not cmp_links:
        cmp_links = ["- (no comparison notes yet)"]

    lines += [
        "",
        "## Cross-model",
        "",
        *cmp_links,
        "",
        "## Freshness",
        "",
        "| Model | summary generated_at_utc |",
        "|---|---|",
    ]
    for r in rows:
        lines.append(f"| `{r['model_id']}` | {r.get('generated_at_utc') or '—'} |")
    lines.append("")
    return "\n".join(lines)


def main() -> int:
    reg = load_registry()
    reg_by_id = {m["id"]: m for m in reg.get("models") or [] if "id" in m}
    model_ids = discover_models()
    if not model_ids:
        print("No model summaries found", file=sys.stderr)
        return 1

    rows = []
    for mid in model_ids:
        summary = load_summary(mid)
        rows.append(normalize_row(mid, summary, reg_by_id.get(mid)))

    generated = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    OUT.mkdir(parents=True, exist_ok=True)

    status = {
        "generated_at_utc": generated,
        "models": [{k: v for k, v in r.items() if k != "raw"} for r in rows],
    }
    if write_json_stable(OUT / "STATUS.json", status):
        print("  STATUS.json updated")
    else:
        print("  STATUS.json unchanged (semantic)")
        if (OUT / "STATUS.json").exists():
            status = json.loads((OUT / "STATUS.json").read_text())
            generated = status.get("generated_at_utc", generated)

    md_rows = rows
    if status.get("models") and len(status["models"]) == len(rows):
        # prefer stored models list when reusing timestamp
        md_rows = [{**m, "raw": {}} for m in status["models"]]

    new_dash = render_md(md_rows, generated)
    dash_path = OUT / "DASHBOARD.md"
    if not dash_path.exists() or dash_path.read_text() != new_dash:
        dash_path.write_text(new_dash)
        print("  DASHBOARD.md updated")
    else:
        print("  DASHBOARD.md unchanged")

    (OUT / "README.md").write_text(
        "# Monorepo derived/\n\n"
        "> Generated. Do not hand-edit.\n\n"
        "| File | Purpose |\n"
        "|---|---|\n"
        "| [DASHBOARD.md](DASHBOARD.md) | Human status table |\n"
        "| [STATUS.json](STATUS.json) | Machine status |\n"
    )
    sync_readme.main()
    print(f"✓ dashboard: {len(rows)} models")
    for r in rows:
        print(f"  - {r['model_id']}: {r['display_name']} [{r['status']}]")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())