File size: 9,078 Bytes
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be920c
 
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be920c
d29779d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1be920c
d29779d
 
 
1be920c
d29779d
 
1be920c
 
 
d29779d
 
 
 
 
 
 
 
 
1be920c
d29779d
 
 
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
/*
 * Base Checker logic, ported line by line from lineage.py and base_checker.py
 * (github.com/GourabDG36/lineage-aware-merging). Works in the browser and in Node.
 * Input: Gram matrices G[c][i][j] = <W_i, W_j> for every attention/MLP matrix c.
 */
(function (root) {
  "use strict";

  var METHODS = {
    task_arithmetic: "sum", dare_linear: "sum", breadcrumbs: "sum", della_linear: "sum",
    ties: "trim", dare_ties: "trim", breadcrumbs_ties: "trim", della: "trim", sce: "trim",
    linear: "none", slerp: "none", nuslerp: "none", passthrough: "none", karcher: "none",
    model_stock: "other", nearswap: "other"
  };
  var DEFAULT_GATE = 0.10, DEFAULT_COS = 0.30;
  // mergekit defaults (merge_methods/registry.py, checked 21 Nov 2026); sce always normalises
  var NORMALIZE_DEFAULT = { linear: true, ties: true, della: true, sce: true };

  function sqDist(G, i, j) {
    return G.map(function (m) { return Math.max(m[i][i] + m[j][j] - 2 * m[i][j], 0); });
  }
  function mean(a) { var s = 0; for (var k = 0; k < a.length; k++) s += a[k]; return s / a.length; }

  function distanceMatrix(G) {
    var N = G[0].length, D = [];
    for (var i = 0; i < N; i++) { D.push(new Array(N).fill(0)); }
    for (i = 0; i < N; i++) {
      for (var j = i + 1; j < N; j++) {
        var sq = sqDist(G, i, j);
        var v = mean(G.map(function (m, c) { return Math.sqrt(sq[c]) / Math.sqrt((m[i][i] + m[j][j]) / 2); }));
        D[i][j] = D[j][i] = v;
      }
    }
    return D;
  }

  function relFrom(G, k, r) {
    if (k === r) return 0;
    var sq = sqDist(G, k, r);
    return mean(G.map(function (m, c) { return Math.sqrt(sq[c]) / Math.sqrt(m[r][r]); }));
  }

  function tauCos(G, a, b, r) {
    if (r === a || r === b) return NaN;
    var sa = sqDist(G, a, r), sb = sqDist(G, b, r), vals = [];
    G.forEach(function (m, c) {
      var na = Math.sqrt(sa[c]), nb = Math.sqrt(sb[c]);
      if (na > 0 && nb > 0) vals.push((m[a][b] - m[a][r] - m[b][r] + m[r][r]) / (na * nb));
    });
    return vals.length ? mean(vals) : NaN;
  }

  function minimumSpanningTree(D) {
    var N = D.length, inTree = [0], edges = [];
    while (inTree.length < N) {
      var best = null, order = inTree.slice().sort(function (x, y) { return x - y; });
      order.forEach(function (i) {
        for (var j = 0; j < N; j++) {
          if (inTree.indexOf(j) < 0 && (best === null || D[i][j] < D[best[0]][best[1]])) best = [i, j];
        }
      });
      edges.push([Math.min(best[0], best[1]), Math.max(best[0], best[1])]);
      inTree.push(best[1]);
    }
    return edges.sort(function (x, y) { return x[0] - y[0] || x[1] - y[1]; });
  }

  function adjacency(edges, N) {
    var adj = []; for (var i = 0; i < N; i++) adj.push([]);
    edges.forEach(function (e) { adj[e[0]].push(e[1]); adj[e[1]].push(e[0]); });
    return adj;
  }

  function steinerNodes(edges, N, members) {
    var adj = adjacency(edges, N);
    function path(a, b) {
      var prev = {}; prev[a] = -1; var q = [a];
      while (q.length) {
        var u = q.shift();
        adj[u].forEach(function (v) { if (!(v in prev)) { prev[v] = u; q.push(v); } });
      }
      var out = [], u2 = b;
      while (u2 !== -1) { out.push(u2); u2 = prev[u2]; }
      return out;
    }
    var nodes = {};
    members.forEach(function (m) { nodes[m] = true; });
    for (var k = 1; k < members.length; k++) path(members[0], members[k]).forEach(function (n) { nodes[n] = true; });
    return Object.keys(nodes).map(Number).sort(function (x, y) { return x - y; });
  }

  function chooseReference(G, edges, members, gate) {
    var N = G[0].length, cands = steinerNodes(edges, N, members), cost = {};
    cands.forEach(function (r) { cost[r] = Math.max.apply(null, members.map(function (m) { return relFrom(G, m, r); })); });
    var best = cands.slice().sort(function (x, y) { return cost[x] - cost[y] || x - y; })[0];
    return { best: best, cost: cost[best], candidates: cands };
  }

  /*
   * cfg = {method, base (index or null), models: [{index, weight}], normalize (bool or null)}
   * Returns the same report fields as base_checker.check().
   */
  function check(G, names, cfg, opts) {
    opts = opts || {};
    var gate = opts.gate == null ? DEFAULT_GATE : opts.gate, cosThr = opts.cos == null ? DEFAULT_COS : opts.cos;
    var kind = METHODS[cfg.method] || "other";
    var models = cfg.models.filter(function (m) { return m.index !== cfg.base; });
    if (!models.length) throw new Error("choose at least one model to merge (other than the base)");
    var mi = models.map(function (m) { return m.index; });
    var normalize = (cfg.normalize == null || cfg.method === "sce") ? !!NORMALIZE_DEFAULT[cfg.method] : !!cfg.normalize;
    var D = distanceMatrix(G), edges = minimumSpanningTree(D);
    var ch = chooseReference(G, edges, mi, gate), best = ch.best, cost = ch.cost, di = cfg.base;

    function pairCos(r) {
      var v = [];
      for (var x = 0; x < mi.length; x++) for (var y = x + 1; y < mi.length; y++) {
        var t = tauCos(G, mi[x], mi[y], r); if (isFinite(t)) v.push(t);
      }
      return v.length ? mean(v) : null;
    }
    var wsum = models.reduce(function (s, m) { return s + m.weight; }, 0);
    var counted = normalize ? 1 : wsum;
    var rep = {
      method: cfg.method, method_kind: kind, declared_base: di == null ? null : names[di],
      closest_common_ancestor: names[best], best_index: best,
      candidates_on_tree_path: ch.candidates.map(function (c) { return names[c]; }),
      tree_links: edges.map(function (e) { return [names[e[0]], names[e[1]], D[e[0]][e[1]]]; }),
      edges: edges, D: D,
      distance_from_ancestor: {}, task_vector_cos_from_ancestor: pairCos(best),
      weights_sum: wsum, normalize: normalize, ancestor_update_counted_times: counted, gate: gate
    };
    mi.forEach(function (i) { rep.distance_from_ancestor[names[i]] = relFrom(G, i, best); });
    if (di != null) {
      rep.distance_from_declared_base = {};
      mi.forEach(function (i) { rep.distance_from_declared_base[names[i]] = relFrom(G, i, di); });
      rep.task_vector_cos_from_declared_base = pairCos(di);
    }

    if (cost > gate) {
      var far = mi.filter(function (i) { return relFrom(G, i, best) > gate; }).map(function (i) { return names[i]; });
      rep.verdict = "TOO_FAR";
      rep.message = "No common ancestor is close enough: " + far.join(", ") + (far.length === 1 ? " is" : " are") +
        " more than " + Math.round(gate * 100) + "% away from the best base (" + names[best] +
        "). Merging is unsafe from any base; keep these models separate.";
      return rep;
    }
    if (di == null) { rep.verdict = "WARNING"; rep.message = "No base_model given; the closest common ancestor is " + names[best] + "."; return rep; }
    if (di === best) { rep.verdict = "OK"; rep.message = "base_model " + names[di] + " is the closest common ancestor of the merged models."; return rep; }
    if (kind === "none") {
      rep.verdict = "INFO";
      rep.message = cfg.method + " does not use the base to form task vectors, so the base choice does not cause double counting. (Closest ancestor: " + names[best] + ".)";
      return rep;
    }
    var shared = rep.task_vector_cos_from_declared_base;
    var sharedTxt = (shared != null && rep.task_vector_cos_from_ancestor != null) ?
      " Measured from " + names[di] + ", the task vectors have cosine " + shared.toFixed(2) +
      " (from " + names[best] + ": " + rep.task_vector_cos_from_ancestor.toFixed(2) + ")." : "";
    if ((kind === "sum" || kind === "trim") && counted > 1.05 && (shared == null || shared > cosThr)) {
      rep.verdict = "WRONG_BASE";
      rep.message = "The merged models share a closer ancestor, " + names[best] + ". With base_model " + names[di] +
        ", every task vector contains that ancestor's own update, and " + cfg.method + " adds them with total weight " +
        fmt(counted) + " (no normalisation), so the update is counted " + fmt(counted) + " times instead of once." + sharedTxt +
        " Use base_model: " + names[best] + ".";
    } else {
      var tv = (kind === "sum" || kind === "trim");
      var why = (normalize && tv) ? cfg.method + " divides the task vectors by their summed weights (normalisation), so the shared update is added about once" :
        (tv ? "the weights sum to 1 or less" : "the effect on " + cfg.method + " was not measured");
      rep.verdict = "WARNING";
      rep.message = "A closer common ancestor exists: " + names[best] + " (declared: " + names[di] + "). The risk is lower because " +
        why + ", but " + names[best] + " is still the better base." + sharedTxt;
    }
    return rep;
  }

  function fmt(x) { return String(Math.round(x * 1e6) / 1e6); }

  var api = { METHODS: METHODS, NORMALIZE_DEFAULT: NORMALIZE_DEFAULT, distanceMatrix: distanceMatrix, relFrom: relFrom, tauCos: tauCos,
    minimumSpanningTree: minimumSpanningTree, steinerNodes: steinerNodes, chooseReference: chooseReference, check: check };
  if (typeof module !== "undefined" && module.exports) module.exports = api; else root.LAMChecker = api;
})(this);