File size: 35,283 Bytes
9b6025f
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c460d2
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c460d2
d29779d
 
 
 
 
 
 
 
 
 
 
1c460d2
 
 
 
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c460d2
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b6025f
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Base Checker</title>
<meta name="description" content="Catch a wrong base_model before merging LLMs. Lineage-aware model merging, from the weights alone.">
<style>
:root {
  color-scheme: light;
  --page: #f9f9f7; --surface: #fcfcfb; --raise: #ffffff;
  --ink: #0b0b0b; --ink-2: #52514e; --muted: #898781;
  --grid: #e1e0d9; --axis: #c3c2b7; --border: rgba(11,11,11,0.10);
  --s1: #2a78d6; --s2: #eb6834;
  --good: #0ca30c; --warning: #fab219; --serious: #ec835a; --critical: #d03b3b;
  --good-ink: #006300;
  --wash-good: rgba(12,163,12,0.08); --wash-warning: rgba(250,178,25,0.14);
  --wash-serious: rgba(236,131,90,0.12); --wash-critical: rgba(208,59,59,0.09); --wash-info: rgba(42,120,214,0.08);
  --code: #f1f0ec;
}
@media (prefers-color-scheme: dark) {
  :root:where(:not([data-theme="light"])) {
    color-scheme: dark;
    --page: #0d0d0d; --surface: #1a1a19; --raise: #20201f;
    --ink: #f0efec; --ink-2: #c3c2b7; --muted: #898781;
    --grid: #2c2c2a; --axis: #383835; --border: rgba(255,255,255,0.10);
    --s1: #3987e5; --s2: #d95926; --good-ink: #0ca30c;
    --wash-good: rgba(12,163,12,0.14); --wash-warning: rgba(250,178,25,0.12);
    --wash-serious: rgba(236,131,90,0.14); --wash-critical: rgba(208,59,59,0.16); --wash-info: rgba(57,135,229,0.14);
    --code: #262624;
  }
}
:root[data-theme="dark"] {
  color-scheme: dark;
  --page: #0d0d0d; --surface: #1a1a19; --raise: #20201f;
  --ink: #f0efec; --ink-2: #c3c2b7; --muted: #898781;
  --grid: #2c2c2a; --axis: #383835; --border: rgba(255,255,255,0.10);
  --s1: #3987e5; --s2: #d95926; --good-ink: #0ca30c;
  --wash-good: rgba(12,163,12,0.14); --wash-warning: rgba(250,178,25,0.12);
  --wash-serious: rgba(236,131,90,0.14); --wash-critical: rgba(208,59,59,0.16); --wash-info: rgba(57,135,229,0.14);
  --code: #262624;
}
* { box-sizing: border-box; }
html, body { margin: 0; background: var(--page); color: var(--ink); }
body { font: 16px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
.wrap { max-width: 1040px; margin: 0 auto; padding: 0 16px; }
header { padding: 48px 0 8px; }
.eyebrow { font-size: 13px; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 0 0 8px; }
h1 { font-size: clamp(30px, 5vw, 44px); line-height: 1.1; margin: 0 0 14px; letter-spacing: -0.01em; }
h2 { font-size: 22px; margin: 0 0 6px; }
h3 { font-size: 16px; margin: 0 0 8px; }
p { margin: 0 0 12px; }
.lede { font-size: 18px; color: var(--ink-2); max-width: 720px; }
a { color: var(--s1); }
section { padding: 28px 0; }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 20px; }
.hero-compare { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 22px 0 6px; max-width: 720px; }
.stat { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 16px 18px; }
.stat .k { font-size: 13px; color: var(--ink-2); }
.stat .v { font-size: 34px; font-weight: 650; font-variant-numeric: tabular-nums; line-height: 1.15; margin-top: 4px; }
.stat .v small { font-size: 15px; font-weight: 500; color: var(--ink-2); }
.stat .tag { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; margin-top: 6px; color: var(--ink-2); }
.dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; flex: none; }
.note { font-size: 14px; color: var(--ink-2); }

/* checker */
.grid-2 { display: grid; grid-template-columns: minmax(0, 340px) minmax(0, 1fr); gap: 16px; align-items: start; }
@media (max-width: 820px) { .grid-2 { grid-template-columns: minmax(0, 1fr); } .hero-compare { grid-template-columns: minmax(0, 1fr); } }
.presets { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0 18px; }
button, select, input { font: inherit; color: inherit; }
.chip { border: 1px solid var(--border); background: var(--raise); border-radius: 999px; padding: 6px 12px; font-size: 14px; cursor: pointer; }
.chip:hover { border-color: var(--axis); }
.chip[aria-pressed="true"] { border-color: var(--ink); font-weight: 600; }
label.field { display: block; font-size: 13px; color: var(--ink-2); margin: 0 0 4px; }
select { width: 100%; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--raise); }
.fieldset { margin: 0 0 14px; }
.models { display: grid; gap: 6px; }
.mrow { display: grid; grid-template-columns: 20px minmax(0, 1fr) 64px; gap: 8px; align-items: center; font-size: 14px; }
.mrow input[type=number] { width: 64px; padding: 4px 6px; border-radius: 6px; border: 1px solid var(--border); background: var(--raise); font-variant-numeric: tabular-nums; }
.mrow input[type=number]:disabled { opacity: .4; }
.mrow .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.check-inline { display: flex; gap: 8px; align-items: center; font-size: 14px; }

.verdict { border-radius: 10px; padding: 14px 16px; border: 1px solid var(--border); margin-bottom: 14px; }
.verdict .vh { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 17px; margin-bottom: 4px; }
.verdict .vh svg { flex: none; }
.verdict p { margin: 0; color: var(--ink); }
.v-OK { background: var(--wash-good); } .v-INFO { background: var(--wash-info); }
.v-WARNING { background: var(--wash-warning); } .v-WRONG_BASE { background: var(--wash-critical); } .v-TOO_FAR { background: var(--wash-serious); }
.evidence { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-bottom: 14px; }
@media (max-width: 560px) { .evidence { grid-template-columns: minmax(0, 1fr); } }
.mini { background: var(--raise); border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; }
.mini .k { font-size: 13px; color: var(--ink-2); margin-bottom: 8px; }
.barrow { display: grid; grid-template-columns: 116px minmax(0, 1fr) 46px; gap: 8px; align-items: center; font-size: 13px; margin: 6px 0; }
.track { height: 10px; background: var(--grid); border-radius: 4px; overflow: hidden; }
.fill { height: 100%; border-radius: 4px; }
.num { font-variant-numeric: tabular-nums; text-align: right; }
table { border-collapse: collapse; width: 100%; font-size: 14px; }
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--grid); }
th { font-weight: 600; color: var(--ink-2); font-size: 13px; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
.table-scroll { overflow-x: auto; }
pre { background: var(--code); border-radius: 8px; padding: 12px; font-size: 13px; overflow-x: auto; margin: 0; }
.yaml-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
@media (max-width: 680px) { .yaml-grid { grid-template-columns: minmax(0, 1fr); } }
.tree-box { background: var(--raise); border: 1px solid var(--border); border-radius: 10px; padding: 8px; margin-bottom: 14px; }
.tree-box svg { width: 100%; height: auto; display: block; }
.legend { display: flex; flex-wrap: wrap; gap: 14px; font-size: 13px; color: var(--ink-2); padding: 4px 8px 8px; }
.legend span { display: inline-flex; align-items: center; gap: 6px; }

/* charts */
.charts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
.charts .wide { grid-column: 1 / -1; }
@media (max-width: 820px) { .charts { grid-template-columns: minmax(0, 1fr); } }
.chart svg { width: 100%; height: auto; display: block; }
.chart .sub { font-size: 14px; color: var(--ink-2); margin: 0 0 10px; }
.clegend { display: flex; gap: 16px; font-size: 13px; color: var(--ink-2); margin: 0 0 6px; flex-wrap: wrap; }
.clegend span { display: inline-flex; gap: 6px; align-items: center; }
details { margin-top: 8px; font-size: 14px; }
summary { cursor: pointer; color: var(--ink-2); }
.tip { position: fixed; pointer-events: none; background: var(--raise); color: var(--ink); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; font-size: 13px; box-shadow: 0 4px 16px rgba(0,0,0,.12); opacity: 0; transition: opacity .08s; z-index: 10; max-width: 260px; }
.tip b { font-variant-numeric: tabular-nums; }
.steps { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; counter-reset: s; }
@media (max-width: 820px) { .steps { grid-template-columns: minmax(0, 1fr); } }
.step { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px; font-size: 14px; }
.step::before { counter-increment: s; content: counter(s); display: inline-grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: var(--ink); color: var(--page); font-weight: 700; font-size: 13px; margin-bottom: 8px; }
.step b { display: block; margin-bottom: 4px; }
#chart-base, #chart-cos, #chart-sweep, .tree-box { overflow-x: auto; }
@media (max-width: 600px) {
  #chart-base svg { min-width: 680px; } #chart-cos svg, #chart-sweep svg { min-width: 460px; } .tree-box svg { min-width: 640px; }
}
footer { padding: 28px 0 48px; color: var(--ink-2); font-size: 14px; border-top: 1px solid var(--grid); margin-top: 20px; }
.err { color: var(--critical); font-size: 14px; }
</style>
</head>
<body>
<div class="tip" id="tip" role="status" aria-live="polite"></div>

<header class="wrap">
  <p class="eyebrow">Lineage-aware model merging</p>
  <h1>Is your merge base the right one?</h1>
  <p class="lede">Model merging adds up each model's change from a <b>base model</b> that you type by hand. If the models share a closer ancestor, its training gets added again and again, and the merge breaks. This page checks the base using the model weights alone.</p>
  <div class="hero-compare" aria-label="Same three models, same method, different base">
    <div class="stat">
      <div class="k">Base = their closest common ancestor (Instruct)</div>
      <div class="v">68.0 <small>/ 48.0</small></div>
      <div class="tag"><span class="dot" style="background:var(--s1)"></span>GSM8K / MBPP accuracy, %</div>
    </div>
    <div class="stat">
      <div class="k">Base = Qwen2.5-1.5B (the usual choice)</div>
      <div class="v">6.5 <small>/ 0.0</small></div>
      <div class="tag"><span class="dot" style="background:var(--s2)"></span>GSM8K / MBPP accuracy, %</div>
    </div>
  </div>
  <p class="note">Three Qwen2.5-1.5B-Instruct fine-tunes (QwQ, MBPP, Business) merged with Task Arithmetic. Only the base differs.</p>
</header>

<main>
<section class="wrap" id="try">
  <h2>Try the Base Checker</h2>
  <p class="note">Runs in your browser on real data from the 7 models below (196 weight matrices each, measured on Kaggle). No data, no GPU. Pick a preset or build your own merge.</p>
  <div class="presets" role="group" aria-label="Presets">
    <button class="chip" data-preset="mistake">The real mistake</button>
    <button class="chip" data-preset="fixed">Same merge, right base</button>
    <button class="chip" data-preset="ties">TIES, wrong base</button>
    <button class="chip" data-preset="far">Coder + Instruct</button>
  </div>
  <div class="grid-2">
    <form class="card" id="form" onsubmit="return false">
      <div class="fieldset">
        <label class="field" for="method">merge_method</label>
        <select id="method">
          <option value="task_arithmetic">task_arithmetic</option>
          <option value="ties">ties</option>
          <option value="dare_ties">dare_ties</option>
          <option value="dare_linear">dare_linear</option>
          <option value="linear">linear</option>
        </select>
      </div>
      <div class="fieldset">
        <label class="field" for="base">base_model</label>
        <select id="base"></select>
      </div>
      <div class="fieldset">
        <span class="field" id="models-label">models to merge, with weight</span>
        <div class="models" id="models" aria-labelledby="models-label"></div>
      </div>
      <label class="check-inline"><input type="checkbox" id="normalize"> normalize (mergekit default: on for ties, della, sce)</label>
    </form>
    <div id="out" aria-live="polite"></div>
  </div>
</section>

<section class="wrap" id="results">
  <h2>What we measured</h2>
  <p class="note">Qwen2.5-1.5B family on a Kaggle T4. Accuracy is the average of GSM8K and MBPP (first 200 test questions each). 42 merges in total; full tables on GitHub.</p>
  <div class="charts">
    <div class="card chart wide">
      <h3>Choosing the right base fixes Task Arithmetic merges</h3>
      <p class="sub">Same models and method; only the base changes. Lineage base wins 5 of 5.</p>
      <div class="clegend"><span><span class="dot" style="background:var(--s1)"></span>Base = closest common ancestor (Instruct)</span><span><span class="dot" style="background:var(--s2)"></span>Base = Qwen2.5-1.5B</span></div>
      <div id="chart-base"></div>
      <details><summary>Show as table</summary><div class="table-scroll" id="table-base"></div></details>
    </div>
    <div class="card chart">
      <h3>The wrong base makes task vectors look alike</h3>
      <p class="sub">Cosine between two models' changes. Near 1: the same ancestor update counted twice.</p>
      <div class="clegend"><span><span class="dot" style="background:var(--s1)"></span>From Instruct</span><span><span class="dot" style="background:var(--s2)"></span>From Qwen2.5-1.5B</span></div>
      <div id="chart-cos"></div>
      <details><summary>Show as table</summary><div class="table-scroll" id="table-cos"></div></details>
    </div>
    <div class="card chart">
      <h3>How far is too far</h3>
      <p class="sub">Stepping from Instruct towards Coder: healthy up to 10%, then it breaks.</p>
      <div id="chart-sweep"></div>
      <details><summary>Show as table</summary><div class="table-scroll" id="table-sweep"></div></details>
    </div>
  </div>
</section>

<section class="wrap" id="how">
  <h2>How it works</h2>
  <p class="note">Everything comes from the weight files. No test questions are used at any step.</p>
  <div class="steps">
    <div class="step"><b>Measure distance</b>How much two models' weights differ, averaged over 196 attention and MLP matrices.</div>
    <div class="step"><b>Draw the family tree</b>Join the closest relatives first (minimum spanning tree), following MoTHer (ICLR 2025).</div>
    <div class="step"><b>Find the ancestor</b>On the tree paths between the models you merge, pick the model closest to all of them.</div>
    <div class="step"><b>Check double counting</b>Cosine between the models' changes from your base. High means a shared update is repeated.</div>
    <div class="step"><b>Distance gate</b>If even the best base is more than 10% away from a model, the merge is unsafe from any base.</div>
  </div>
</section>
</main>

<footer class="wrap">
  <p><b>Lineage-Aware Model Merging for Large Language Models.</b> B.Tech (AI &amp; Data Science) major project, Sikkim Manipal Institute of Technology, 2026. Gourabdipta Ghosh and Arko Chakraborty; guide Mr. Suraj Dey.</p>
  <p>Code, results and the command-line Base Checker for mergekit configs: <a href="https://github.com/GourabDG36/lineage-aware-merging">github.com/GourabDG36/lineage-aware-merging</a>.</p>
  <p>Related work: model family trees from weights (MoTHer, ICLR 2025; modelDNA, arXiv 2607.10617); grouping and routing a model zoo (Model-GLUE, arXiv 2410.05357); predicting merge collapse with a fixed base (arXiv 2610.03199). To our knowledge, none of these uses model lineage to choose the merge base.</p>
  <p>This page checks only the 7 models listed. For any other models, run <code>base_checker.py</code> from the repository.</p>
</footer>

<script src="data.js"></script>
<script src="checker.js"></script>
<script>
(function () {
  "use strict";
  var D = window.LAM_DATA, C = window.LAMChecker, N = D.names.length;
  var SHORT = D.short, $ = function (id) { return document.getElementById(id); };
  var idx = {}; D.names.forEach(function (n, i) { idx[n] = i; });
  var BASE = idx["Qwen/Qwen2.5-1.5B"], INSTRUCT = idx["Qwen/Qwen2.5-1.5B-Instruct"];
  var QWQ = idx["micaebe/Qwen2.5-1.5B-Instruct-QwQ"], MBPP = idx["jahyungu/Qwen2.5-1.5B-Instruct_mbpp"],
      BUS = idx["joyboy5656n/business-assistant-llm"], CODER = idx["Qwen/Qwen2.5-Coder-1.5B-Instruct"];
  var ORDER = [BASE, INSTRUCT, QWQ, MBPP, BUS, idx["Qwen/Qwen2.5-Coder-1.5B"], CODER];

  function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]; }); }
  function shortOf(name) { return SHORT[idx[name]] || name; }

  // ---------------- form
  ORDER.forEach(function (i) {
    var o = document.createElement("option"); o.value = i; o.textContent = SHORT[i]; $("base").appendChild(o);
    var row = document.createElement("div"); row.className = "mrow";
    row.innerHTML = '<input type="checkbox" id="m' + i + '" aria-label="merge ' + esc(SHORT[i]) + '">' +
      '<label class="nm" for="m' + i + '" title="' + esc(D.names[i]) + '">' + esc(SHORT[i]) + '</label>' +
      '<input type="number" id="w' + i + '" min="0" max="5" step="0.05" value="1" aria-label="weight of ' + esc(SHORT[i]) + '">';
    $("models").appendChild(row);
  });

  var PRESETS = {
    mistake: { method: "task_arithmetic", base: BASE, models: [[QWQ, 1], [MBPP, 1], [BUS, 1]], normalize: false },
    fixed: { method: "task_arithmetic", base: INSTRUCT, models: [[QWQ, 1], [MBPP, 1], [BUS, 1]], normalize: false },
    ties: { method: "ties", base: BASE, models: [[QWQ, 1], [MBPP, 1], [BUS, 1]], normalize: true },
    far: { method: "task_arithmetic", base: BASE, models: [[CODER, 0.5], [INSTRUCT, 0.5]], normalize: false }
  };
  function applyPreset(key) {
    var p = PRESETS[key];
    $("method").value = p.method; $("base").value = p.base; $("normalize").checked = p.normalize;
    ORDER.forEach(function (i) { $("m" + i).checked = false; $("w" + i).value = 1; });
    p.models.forEach(function (m) { $("m" + m[0]).checked = true; $("w" + m[0]).value = m[1]; });
    document.querySelectorAll("[data-preset]").forEach(function (b) { b.setAttribute("aria-pressed", b.dataset.preset === key ? "true" : "false"); });
    run();
  }
  document.querySelectorAll("[data-preset]").forEach(function (b) { b.addEventListener("click", function () { applyPreset(b.dataset.preset); }); });
  $("method").addEventListener("change", function () {     // follow mergekit's default for the chosen method
    $("normalize").checked = !!C.NORMALIZE_DEFAULT[$("method").value];
    run();
  });
  $("form").addEventListener("input", function () {
    document.querySelectorAll("[data-preset]").forEach(function (b) { b.setAttribute("aria-pressed", "false"); });
    run();
  });

  function readForm() {
    var base = +$("base").value, models = [];
    ORDER.forEach(function (i) {
      var on = $("m" + i).checked; $("w" + i).disabled = !on || i === base;
      if (on && i !== base) { var w = parseFloat($("w" + i).value); models.push({ index: i, weight: isFinite(w) ? w : 1 }); }
    });
    return { method: $("method").value, base: base, models: models, normalize: $("normalize").checked };
  }

  // ---------------- output
  var ICONS = {
    OK: '<path d="M5 10.5l3 3 7-7" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>',
    INFO: '<path d="M10 9v5M10 6.2v.1" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/>',
    WARNING: '<path d="M10 5.5v5.5M10 14.2v.1" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/>',
    WRONG_BASE: '<path d="M6.5 6.5l7 7M13.5 6.5l-7 7" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/>',
    TOO_FAR: '<path d="M6 10h8" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/>'
  };
  var VCOLOR = { OK: "var(--good)", INFO: "var(--s1)", WARNING: "var(--warning)", WRONG_BASE: "var(--critical)", TOO_FAR: "var(--serious)" };
  var VLABEL = { OK: "OK: right base", INFO: "INFO: base not used by this method", WARNING: "WARNING: a better base exists",
    WRONG_BASE: "WRONG BASE: the merge will double count", TOO_FAR: "STOP: too far apart to merge" };
  var VINK = { WARNING: "#0b0b0b" };

  function verdictHtml(r) {
    var msg = r.message;
    D.names.slice().sort(function (a, b) { return b.length - a.length; })
      .forEach(function (n) { msg = msg.split(n).join("\u0000" + idx[n] + "\u0000"); });
    msg = msg.replace(/\u0000(\d+)\u0000/g, function (_, i) { return SHORT[+i]; });
    return '<div class="verdict v-' + r.verdict + '"><div class="vh">' +
      '<svg width="22" height="22" viewBox="0 0 20 20" aria-hidden="true"><circle cx="10" cy="10" r="10" fill="' + VCOLOR[r.verdict] + '"/>' +
      '<g style="color:' + (VINK[r.verdict] || "#ffffff") + '">' + ICONS[r.verdict] + '</g></svg>' +
      esc(VLABEL[r.verdict]) + '</div><p>' + esc(msg) + '</p></div>';
  }

  function evidenceHtml(r, cfg) {
    var parts = [];
    if (r.task_vector_cos_from_ancestor != null) {
      var rows = [];
      if (r.task_vector_cos_from_declared_base != null)
        rows.push(["From your base", r.task_vector_cos_from_declared_base, "var(--s2)"]);
      rows.push(["From the ancestor", r.task_vector_cos_from_ancestor, "var(--s1)"]);
      parts.push('<div class="mini"><div class="k">Double-counting score (task-vector cosine, 0 = independent, 1 = same update repeated)</div>' +
        rows.map(function (x) {
          var v = Math.max(0, Math.min(1, x[1]));
          return '<div class="barrow"><span>' + x[0] + '</span><span class="track"><span class="fill" style="display:block;width:' + (v * 100).toFixed(1) + '%;background:' + x[2] + '"></span></span><span class="num">' + x[1].toFixed(2) + '</span></div>';
        }).join("") + '</div>');
    }
    var counted = r.ancestor_update_counted_times;
    parts.push('<div class="mini"><div class="k">Settings</div><div style="font-size:14px">' +
      'Closest common ancestor: <b>' + esc(shortOf(r.closest_common_ancestor)) + '</b><br>' +
      'Weights sum to <b>' + (Math.round(r.weights_sum * 1000) / 1000) + '</b>' + (r.normalize ? ' (normalised)' : '') +
      ((r.verdict === "WRONG_BASE" || r.verdict === "WARNING") && (r.method_kind === "sum" || r.method_kind === "trim") ?
        '<br>Shared update added <b>' + (Math.round(counted * 1000) / 1000) + '</b> time' + (counted === 1 ? '' : 's') : '') +
      '</div></div>');
    var t = '<div class="mini" style="grid-column:1/-1"><div class="k">Distance of each merged model (relative weight change; gate ' + Math.round(r.gate * 100) + '%)</div><div class="table-scroll"><table><thead><tr><th>Model</th><th class="num">From ancestor</th>' +
      (r.distance_from_declared_base ? '<th class="num">From your base</th>' : '') + '</tr></thead><tbody>';
    Object.keys(r.distance_from_ancestor).forEach(function (n) {
      t += '<tr><td>' + esc(shortOf(n)) + '</td><td class="num">' + r.distance_from_ancestor[n].toFixed(4) + '</td>' +
        (r.distance_from_declared_base ? '<td class="num">' + r.distance_from_declared_base[n].toFixed(4) + '</td>' : '') + '</tr>';
    });
    parts.push(t + '</tbody></table></div></div>');
    return '<div class="evidence">' + parts.join("") + '</div>';
  }

  // ---------------- family tree (drawn from the checker's tree; laid out from Qwen2.5-1.5B for reading)
  function treeSvg(r, cfg) {
    var adj = []; for (var i = 0; i < N; i++) adj.push([]);
    r.edges.forEach(function (e) { adj[e[0]].push(e[1]); adj[e[1]].push(e[0]); });
    var root = BASE, depth = {}, kids = {}, q = [root]; depth[root] = 0;
    while (q.length) { var u = q.shift(); kids[u] = []; adj[u].forEach(function (v) { if (!(v in depth)) { depth[v] = depth[u] + 1; kids[u].push(v); q.push(v); } }); }
    var x = {}, slot = 0;
    function place(u) { if (!kids[u].length) { x[u] = slot++; return; } kids[u].forEach(place); x[u] = (x[kids[u][0]] + x[kids[u][kids[u].length - 1]]) / 2; }
    place(root);
    var maxD = Math.max.apply(null, Object.keys(depth).map(function (k) { return depth[k]; }));
    var W = Math.max(slot, 1) * 150, H = (maxD + 1) * 96 + 20;
    function px(i) { return 75 + x[i] * 150; } function py(i) { return 34 + depth[i] * 96; }
    var members = {}; cfg.models.forEach(function (m) { members[m.index] = true; });
    var s = '<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="Family tree of the 7 models, drawn from their weights">';
    r.edges.forEach(function (e) {
      var a = e[0], b = e[1], d = r.D[a][b], far = d > r.gate;
      s += '<line x1="' + px(a) + '" y1="' + py(a) + '" x2="' + px(b) + '" y2="' + py(b) + '" stroke="var(--axis)" stroke-width="2"' + (far ? ' stroke-dasharray="5 5"' : '') + '/>';
      s += '<text x="' + ((px(a) + px(b)) / 2 + 6) + '" y="' + ((py(a) + py(b)) / 2) + '" font-size="12" fill="var(--muted)">' + (far ? 'far ' : '') + d.toFixed(4) + '</text>';
    });
    for (var k = 0; k < N; k++) {
      var isM = members[k], isB = k === cfg.base, isA = k === r.best_index;
      var ring = isA ? 'var(--good)' : (isB ? 'var(--critical)' : 'none');
      if (ring !== 'none') s += '<circle cx="' + px(k) + '" cy="' + py(k) + '" r="15" fill="none" stroke="' + ring + '" stroke-width="3"/>';
      s += '<circle cx="' + px(k) + '" cy="' + py(k) + '" r="9" fill="' + (isM ? 'var(--ink)' : 'var(--surface)') + '" stroke="var(--ink)" stroke-width="2"/>';
      s += '<text x="' + px(k) + '" y="' + (py(k) + 32) + '" font-size="13" text-anchor="middle" fill="var(--ink)">' + esc(SHORT[k]) + '</text>';
    }
    return '<div class="tree-box"><div class="legend"><span><span class="dot" style="background:var(--ink)"></span>merged</span>' +
      '<span><span class="dot" style="border:3px solid var(--good)"></span>closest common ancestor</span>' +
      (cfg.base !== r.best_index ? '<span><span class="dot" style="border:3px solid var(--critical)"></span>your base</span>' : '') +
      '<span>dashed = more than ' + Math.round(r.gate * 100) + '% apart</span></div>' + s + '</svg></div>';
  }

  function yaml(cfg, base) {
    var y = "merge_method: " + cfg.method + "\nbase_model: " + D.names[base] + "\n";
    y += "parameters:\n  normalize: " + (cfg.normalize ? "true" : "false") + "\n";
    y += "models:\n";
    cfg.models.forEach(function (m) { y += "  - model: " + D.names[m.index] + "\n    parameters: {weight: " + m.weight + "}\n"; });
    return y + "dtype: bfloat16\n";
  }

  function run() {
    var cfg = readForm(), out = $("out");
    if (!cfg.models.length) { out.innerHTML = '<div class="card"><p class="err">Tick at least one model to merge (other than the base).</p></div>'; return; }
    var r;
    try { r = C.check(D.G, D.names, cfg); } catch (e) { out.innerHTML = '<div class="card"><p class="err">' + esc(e.message) + '</p></div>'; return; }
    var html = verdictHtml(r) + evidenceHtml(r, cfg) + treeSvg(r, cfg);
    var fix = (r.verdict === "WRONG_BASE" || r.verdict === "WARNING") && r.best_index !== cfg.base;
    html += '<div class="yaml-grid"><div><h3>Your mergekit config</h3><pre>' + esc(yaml(cfg, cfg.base)) + '</pre></div>' +
      (fix ? '<div><h3>Corrected config</h3><pre>' + esc(yaml(cfg, r.best_index)) + '</pre></div>' : '') + '</div>';
    out.innerHTML = html;
  }

  // ---------------- charts (measured results)
  var tip = $("tip");
  function showTip(e, html) { tip.innerHTML = html; tip.style.opacity = 1; moveTip(e); }
  function moveTip(e) {
    var x = e.clientX + 14, y = e.clientY + 14, w = tip.offsetWidth, h = tip.offsetHeight;
    if (x + w > innerWidth - 8) x = e.clientX - w - 14; if (y + h > innerHeight - 8) y = e.clientY - h - 14;
    tip.style.left = x + "px"; tip.style.top = y + "px";
  }
  function hideTip() { tip.style.opacity = 0; }
  function bindTips(container) {
    container.querySelectorAll("[data-tip]").forEach(function (el) {
      el.addEventListener("mouseenter", function (e) { showTip(e, el.getAttribute("data-tip")); });
      el.addEventListener("mousemove", moveTip);
      el.addEventListener("mouseleave", hideTip);
    });
  }
  function bar(x, y, w, h) { // rounded top (4px), square at the baseline
    var r = Math.min(4, w / 2, h);
    return "M" + x + "," + (y + h) + "V" + (y + r) + "Q" + x + "," + y + " " + (x + r) + "," + y + "H" + (x + w - r) + "Q" + (x + w) + "," + y + " " + (x + w) + "," + (y + r) + "V" + (y + h) + "Z";
  }
  function grouped(el, cats, a, b, opts) {
    var W = opts.W, H = 260, L = 40, R = 10, T = 14, B = 46, ih = H - T - B, iw = W - L - R, max = opts.max;
    var gw = iw / cats.length, bw = Math.min(28, (gw - 18) / 2);
    var s = '<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + esc(opts.label) + '">';
    opts.ticks.forEach(function (t) {
      var y = T + ih - t / max * ih;
      s += '<line x1="' + L + '" x2="' + (W - R) + '" y1="' + y + '" y2="' + y + '" stroke="' + (t === 0 ? 'var(--axis)' : 'var(--grid)') + '" stroke-width="1"/>';
      s += '<text x="' + (L - 6) + '" y="' + (y + 4) + '" font-size="11" text-anchor="end" fill="var(--muted)">' + opts.fmt(t) + '</text>';
    });
    cats.forEach(function (c, i) {
      var cx = L + gw * i + gw / 2;
      [[a[i], "var(--s1)", -1, opts.na], [b[i], "var(--s2)", 1, opts.nb]].forEach(function (v) {
        var h = Math.max(v[0] / max * ih, 1), x = v[2] < 0 ? cx - bw - 1 : cx + 1, y = T + ih - h;
        var t = '<b>' + esc(c) + '</b><br>' + esc(v[3]) + ': <b>' + opts.fmt2(v[0]) + '</b>';
        s += '<path d="' + bar(x, y, bw, h) + '" fill="' + v[1] + '"/>';
        s += '<rect x="' + (x - 3) + '" y="' + T + '" width="' + (bw + 6) + '" height="' + ih + '" fill="transparent" data-tip="' + esc(t) + '"/>';
      });
      if (opts.label1 && opts.label1(i)) s += '<text x="' + (cx + 2) + '" y="' + (T + ih - Math.max(b[i] / max * ih, 1) - 6) + '" font-size="12" text-anchor="start" fill="var(--ink)" font-weight="600">' + opts.fmt2(b[i]) + '</text>';
      if (opts.labelA && opts.labelA(i)) s += '<text x="' + (cx - 2) + '" y="' + (T + ih - 6) + '" font-size="12" text-anchor="end" fill="var(--ink)" font-weight="600">' + opts.labelA(i) + '</text>';
      s += '<text x="' + cx + '" y="' + (H - B + 18) + '" font-size="12" text-anchor="middle" fill="var(--ink-2)">' + esc(c) + '</text>';
      if (opts.sub) s += '<text x="' + cx + '" y="' + (H - B + 33) + '" font-size="11" text-anchor="middle" fill="var(--muted)">' + esc(opts.sub[i]) + '</text>';
    });
    el.innerHTML = s + '</svg>'; bindTips(el);
  }
  function table(el, head, rows) {
    el.innerHTML = '<table><thead><tr>' + head.map(function (h, i) { return '<th' + (i ? ' class="num"' : '') + '>' + esc(h) + '</th>'; }).join("") +
      '</tr></thead><tbody>' + rows.map(function (r) { return '<tr>' + r.map(function (c, i) { return '<td' + (i ? ' class="num"' : '') + '>' + esc(c) + '</td>'; }).join("") + '</tr>'; }).join("") + '</tbody></table>';
  }

  var SETS = ["QwQ+MBPP", "QwQ+Business", "MBPP+Legal", "Business+Legal", "QwQ+MBPP+Business"];
  var TA_I = [56.5, 57.5, 50.25, 45.75, 58.0], TA_B = [46.5, 38.5, 39.5, 33.75, 3.25];
  var RAW_I = ["70.0 / 43.0", "69.5 / 45.5", "58.0 / 42.5", "54.5 / 37.0", "68.0 / 48.0"], RAW_B = ["62.0 / 31.0", "40.0 / 37.0", "51.0 / 28.0", "41.0 / 26.5", "6.5 / 0.0"];
  grouped($("chart-base"), SETS, TA_I, TA_B, { W: 900, max: 60, ticks: [0, 20, 40, 60], label: "Average accuracy of Task Arithmetic merges with the two bases",
    fmt: function (t) { return t + "%"; }, fmt2: function (v) { return v.toFixed(2).replace(/\.?0+$/, "") + "%"; },
    na: "Base = Instruct", nb: "Base = Qwen2.5-1.5B", label1: function (i) { return i === 4; },
    sub: SETS.map(function (_, i) { return "+" + (TA_I[i] - TA_B[i]).toFixed(2).replace(/\.?0+$/, "") + " pts"; }) });
  table($("table-base"), ["Merge (Task Arithmetic, sum)", "Base = Instruct (GSM8K / MBPP)", "Base = Qwen2.5-1.5B (GSM8K / MBPP)", "Gain, points"],
    SETS.map(function (s, i) { return [s, RAW_I[i], RAW_B[i], "+" + (TA_I[i] - TA_B[i]).toFixed(2)]; }));

  var PAIRS = ["QwQ+MBPP", "QwQ+Bus.", "QwQ+Legal", "MBPP+Bus.", "MBPP+Legal", "Bus.+Legal"];
  var COS_I = [0.0046, 0.0001, 0.0001, 0.0043, 0.0043, 0.0054], COS_B = [0.9151, 0.8001, 0.8734, 0.8615, 0.9403, 0.8249];
  grouped($("chart-cos"), PAIRS, COS_I, COS_B, { W: 520, max: 1, ticks: [0, 0.5, 1], label: "Task-vector cosine from each base",
    fmt: function (t) { return t.toFixed(1); }, fmt2: function (v) { return v.toFixed(4); }, na: "From Instruct", nb: "From Qwen2.5-1.5B",
    labelA: function (i) { return i === 0 ? "≈0" : ""; } });
  table($("table-cos"), ["Pair", "From Instruct", "From Qwen2.5-1.5B"], PAIRS.map(function (p, i) { return [p, COS_I[i].toFixed(4), COS_B[i].toFixed(4)]; }));

  (function sweep() {
    var pts = [[0, 56.5, "75.0 / 38.0", "Instruct"], [5, 54.5, "67.0 / 42.0"], [10, 54.0, "67.5 / 40.5"], [20, 47.75, "61.0 / 34.5"],
      [30, 35.25, "44.0 / 26.5", "199 of 200 maths answers run to the length limit"], [50, 0, "0.0 / 0.0", "collapsed"], [100, 51.25, "50.0 / 52.5", "Coder"]];
    var W = 520, H = 260, L = 40, R = 14, T = 14, B = 40, iw = W - L - R, ih = H - T - B;
    function X(v) { return L + v / 100 * iw; } function Y(v) { return T + ih - v / 60 * ih; }
    var s = '<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="Average accuracy while stepping from Instruct towards Coder">';
    [0, 20, 40, 60].forEach(function (t) {
      s += '<line x1="' + L + '" x2="' + (W - R) + '" y1="' + Y(t) + '" y2="' + Y(t) + '" stroke="' + (t === 0 ? 'var(--axis)' : 'var(--grid)') + '"/>' +
        '<text x="' + (L - 6) + '" y="' + (Y(t) + 4) + '" font-size="11" text-anchor="end" fill="var(--muted)">' + t + '%</text>';
    });
    [0, 10, 20, 30, 50, 100].forEach(function (t) {
      s += '<text x="' + X(t) + '" y="' + (H - B + 18) + '" font-size="11" text-anchor="middle" fill="var(--muted)">' + t + '%</text>';
    });
    s += '<text x="' + (L + iw / 2) + '" y="' + (H - 6) + '" font-size="12" text-anchor="middle" fill="var(--ink-2)">step from Instruct towards Coder</text>';
    s += '<line x1="' + X(10) + '" x2="' + X(10) + '" y1="' + T + '" y2="' + (T + ih) + '" stroke="var(--ink-2)" stroke-dasharray="4 4"/>' +
      '<text x="' + (X(10) + 6) + '" y="' + (T + 12) + '" font-size="12" fill="var(--ink-2)">gate 10%</text>';
    s += '<polyline fill="none" stroke="var(--s1)" stroke-width="2" stroke-linejoin="round" points="' + pts.map(function (p) { return X(p[0]) + "," + Y(p[1]); }).join(" ") + '"/>';
    pts.forEach(function (p) {
      s += '<circle cx="' + X(p[0]) + '" cy="' + Y(p[1]) + '" r="4.5" fill="var(--s1)" stroke="var(--surface)" stroke-width="2"/>';
      var t = '<b>' + p[0] + '% step</b>' + (p[3] ? ' (' + esc(p[3]) + ')' : '') + '<br>GSM8K / MBPP: <b>' + p[2] + '</b><br>average <b>' + p[1] + '%</b>';
      s += '<circle cx="' + X(p[0]) + '" cy="' + Y(p[1]) + '" r="14" fill="transparent" data-tip="' + esc(t) + '"/>';
    });
    s += '<text x="' + (X(50) + 8) + '" y="' + (Y(0) - 8) + '" font-size="12" fill="var(--ink)" font-weight="600">0%</text>';
    $("chart-sweep").innerHTML = s + '</svg>'; bindTips($("chart-sweep"));
    table($("table-sweep"), ["Step towards Coder", "GSM8K / MBPP", "Average"], pts.map(function (p) { return [p[0] + "%", p[2], p[1] + "%"]; }));
  })();

  applyPreset("mistake");
})();
</script>
</body>
</html>