PyTorch
File size: 11,641 Bytes
bd992b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""
AI genned because it's just simple UI n' stuff.
"""

import json
from pathlib import Path

# Otherwise dll error
import torch

from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QFont
from PyQt6.QtWidgets import (
    QApplication,
    QComboBox,
    QFormLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QMainWindow,
    QPushButton,
    QScrollArea,
    QSizePolicy,
    QSpinBox,
    QStatusBar,
    QVBoxLayout,
    QWidget,
)

from benchmarks.registry import ModelEntry, all_models, all_tasks

from benchmarks.run import PARAM_COUNTS

# Empty statement so that jetbrains doesn't get rid of torch import
torch.cuda.is_available()

CONFIGS_PATH = Path(__file__).parent / "configs.json"

# Tolerance band shown in the UI (green/yellow/red)
TOLERANCE_GREEN = 0.05  # within 5%
TOLERANCE_YELLOW = 0.15  # within 15%

# Debounce delay for live recount (ms)
RECOUNT_DELAY = 200


def load_configs() -> dict:
    if CONFIGS_PATH.exists():
        with open(CONFIGS_PATH) as f:
            return json.load(f)
    return {}


def save_configs(configs: dict) -> None:
    with open(CONFIGS_PATH, "w") as f:
        json.dump(configs, f, indent=2)


def get_saved(configs: dict, arch: str, n_params: int) -> dict | None:
    return configs.get(arch, {}).get(str(n_params))


def put_saved(configs: dict, arch: str, n_params: int, kwargs: dict) -> None:
    configs.setdefault(arch, {})[str(n_params)] = kwargs


class FieldEditor(QWidget):
    """
    A form of integer spinboxes for one arch's config kwargs.
    """

    def __init__(self, defaults: dict, saved: dict | None, parent=None):
        super().__init__(parent)
        self._fields: dict[str, QSpinBox] = {}

        layout = QFormLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        for key, default in defaults.items():
            spin = QSpinBox()
            spin.setMinimum(1)
            spin.setMaximum(1_000_000)
            spin.setValue(saved[key] if (saved and key in saved) else default)
            spin.setGroupSeparatorShown(True)
            self._fields[key] = spin
            layout.addRow(key, spin)

    def values(self) -> dict:
        return {k: s.value() for k, s in self._fields.items()}

    def connect_changed(self, slot) -> None:
        for spin in self._fields.values():
            spin.valueChanged.connect(slot)


class ConfigUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Benchmark Config Tester")
        self.resize(700, 520)

        self._configs = load_configs()
        self._archs = all_models()
        self._recount_timer = QTimer(self)
        self._recount_timer.setSingleShot(True)
        self._recount_timer.timeout.connect(self._recount)

        self._build_ui()
        self._populate_arch_list()

        if self._arch_combo.count():
            self._on_arch_changed(0)

    def _build_ui(self) -> None:
        root = QWidget()
        self.setCentralWidget(root)
        root_layout = QVBoxLayout(root)
        root_layout.setContentsMargins(12, 12, 12, 12)
        root_layout.setSpacing(10)

        top = QHBoxLayout()

        self._arch_combo = QComboBox()
        self._arch_combo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self._arch_combo.currentIndexChanged.connect(self._on_arch_changed)
        top.addWidget(QLabel("Architecture:"))
        top.addWidget(self._arch_combo)

        top.addSpacing(20)

        self._tier_combo = QComboBox()
        for t in PARAM_COUNTS:
            self._tier_combo.addItem(f"{t:,}", userData=t)
        self._tier_combo.currentIndexChanged.connect(self._on_tier_changed)
        top.addWidget(QLabel("Target params:"))
        top.addWidget(self._tier_combo)

        root_layout.addLayout(top)

        self._range_label = QLabel("param range computed across all registered tasks")
        self._range_label.setStyleSheet("color: grey; font-size: 10px;")
        root_layout.addWidget(self._range_label)

        self._fields_group = QGroupBox("Architecture kwargs")
        fields_outer = QVBoxLayout(self._fields_group)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(scroll.Shape.NoFrame)
        self._fields_inner = QWidget()
        self._fields_layout = QVBoxLayout(self._fields_inner)
        self._fields_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        scroll.setWidget(self._fields_inner)
        fields_outer.addWidget(scroll)

        root_layout.addWidget(self._fields_group, stretch=1)

        count_group = QGroupBox("Param count")
        count_layout = QHBoxLayout(count_group)

        self._count_label = QLabel("—")
        self._count_label.setFont(QFont("Monospace", 14, QFont.Weight.Bold))
        self._delta_label = QLabel("")
        self._delta_label.setFont(QFont("Monospace", 11))

        count_layout.addWidget(self._count_label)
        count_layout.addSpacing(30)
        count_layout.addWidget(self._delta_label)
        count_layout.addStretch()

        root_layout.addWidget(count_group)

        btn_row = QHBoxLayout()

        self._save_btn = QPushButton("Save config for this tier")
        self._save_btn.clicked.connect(self._save_current)
        btn_row.addWidget(self._save_btn)

        self._save_all_btn = QPushButton("Save all unsaved")
        self._save_all_btn.setToolTip("Saves current field values for every tier that has no saved config yet")
        self._save_all_btn.clicked.connect(self._save_all_missing)
        btn_row.addWidget(self._save_all_btn)

        btn_row.addStretch()

        self._status_bar = QStatusBar()
        root_layout.addLayout(btn_row)
        root_layout.addWidget(self._status_bar)

        self._field_editor: FieldEditor | None = None

    def _populate_arch_list(self) -> None:
        self._arch_combo.blockSignals(True)
        self._arch_combo.clear()
        for name, entry in self._archs.items():
            if entry.config_tester is not None:
                self._arch_combo.addItem(name, userData=name)
        self._arch_combo.blockSignals(False)

    def _current_arch_entry(self) -> ModelEntry | None:
        name = self._arch_combo.currentData()
        return self._archs.get(name) if name else None

    def _current_tier(self) -> int:
        return self._tier_combo.currentData() or PARAM_COUNTS[0]

    def _on_arch_changed(self, _index: int) -> None:
        entry = self._current_arch_entry()
        if entry is None or entry.config_defaults is None:
            return
        self._rebuild_fields(entry)
        self._recount()

    def _on_tier_changed(self, _index: int) -> None:
        entry = self._current_arch_entry()
        if entry is None or entry.config_defaults is None:
            return

        # Load saved values for this tier if they exist
        saved = get_saved(self._configs, entry.name, self._current_tier())
        self._rebuild_fields(entry, saved_override=saved)
        self._recount()

    def _rebuild_fields(self, entry: ModelEntry, saved_override: dict | None = None) -> None:
        # Remove old editor
        if self._field_editor is not None:
            self._fields_layout.removeWidget(self._field_editor)
            self._field_editor.deleteLater()
            self._field_editor = None

        saved = saved_override or get_saved(self._configs, entry.name, self._current_tier())
        editor = FieldEditor(entry.config_defaults, saved)
        editor.connect_changed(self._schedule_recount)
        self._fields_layout.addWidget(editor)
        self._field_editor = editor

    def _schedule_recount(self) -> None:
        self._recount_timer.start(RECOUNT_DELAY)

    def _get_task_bounds(self) -> tuple[int, int, int, int]:
        """(min_vocab, max_vocab, min_seq, max_seq) across all registered tasks."""
        tasks = all_tasks()
        if not tasks:
            return 64, 512, 64, 512  # fallback if no tasks registered yet
        vocabs, seqs = [], []
        for entry in tasks.values():
            v = entry.vocab_size(128) if callable(entry.vocab_size) else entry.vocab_size
            vocabs.append(v)
            seqs.append(128)  # seq_len is runtime — use benchmark default as proxy
        return min(vocabs), max(vocabs), min(seqs), max(seqs)

    def _recount(self) -> None:
        entry = self._current_arch_entry()
        if entry is None or entry.config_tester is None or self._field_editor is None:
            return

        kwargs = self._field_editor.values()
        target = self._current_tier()
        min_vocab, max_vocab, min_seq, max_seq = self._get_task_bounds()

        try:
            count_lo = entry.config_tester(vocab_size=min_vocab, seq_len=min_seq, **kwargs)
            count_hi = entry.config_tester(vocab_size=max_vocab, seq_len=max_seq, **kwargs)
        except Exception as e:
            self._count_label.setText("error")
            self._delta_label.setText(str(e))
            return

        # Sort in case vocab/seq don't correlate cleanly with param count
        count_lo, count_hi = min(count_lo, count_hi), max(count_lo, count_hi)

        pct_lo = (count_lo - target) / target * 100
        pct_hi = (count_hi - target) / target * 100
        sign_lo = "+" if pct_lo >= 0 else ""
        sign_hi = "+" if pct_hi >= 0 else ""

        max_deviation = max(abs(pct_lo), abs(pct_hi))

        self._count_label.setText(f"{count_lo:,} – {count_hi:,}")
        self._delta_label.setText(
            f"({sign_lo}{pct_lo:.1f}% – {sign_hi}{pct_hi:.1f}%  vs target {target:,})"
        )
        self._range_label.setText(
            f"range from vocab∈[{min_vocab}, {max_vocab}], seq∈[{min_seq}, {max_seq}] across {len(all_tasks())} task(s)"
        )

        if max_deviation <= 5.0:
            colour = "#2ecc71"
        elif max_deviation <= 15.0:
            colour = "#f39c12"
        else:
            colour = "#e74c3c"

        self._count_label.setStyleSheet(f"color: {colour};")
        self._delta_label.setStyleSheet(f"color: {colour};")

    def _save_current(self) -> None:
        entry = self._current_arch_entry()
        if entry is None or self._field_editor is None:
            return
        tier = self._current_tier()
        kwargs = self._field_editor.values()
        put_saved(self._configs, entry.name, tier, kwargs)
        save_configs(self._configs)
        self._status_bar.showMessage(
            f"Saved {entry.name} @ {tier:,} params → {kwargs}", 5000
        )

    def _save_all_missing(self) -> None:
        entry = self._current_arch_entry()
        if entry is None or entry.config_defaults is None or self._field_editor is None:
            return

        saved_count = 0

        for tier in PARAM_COUNTS:
            if get_saved(self._configs, entry.name, tier) is not None:
                continue
            # Use whatever is currently in the fields for each missing tier
            kwargs = self._field_editor.values()
            put_saved(self._configs, entry.name, tier, kwargs)
            saved_count += 1

        if saved_count:
            save_configs(self._configs)
            self._status_bar.showMessage(
                f"Saved {saved_count} missing tier(s) for {entry.name}", 5000
            )
        else:
            self._status_bar.showMessage("All tiers already have saved configs.", 3000)


def main() -> None:
    from run import MODELS_DIR, TASKS_DIR, _import_dir
    _import_dir(MODELS_DIR)
    _import_dir(TASKS_DIR)

    app = QApplication([])
    app.setStyle("Fusion")

    window = ConfigUI()
    window.show()
    app.exec()


if __name__ == "__main__":
    main()