File size: 3,939 Bytes
48441eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Solstice LoRAs (.safetensors, W += strength * alpha/rank * B @ A) fed to a LoRA-input export
// (tools/add_lora_inputs.py) as stacked low-rank factors. Several LoRAs are concatenated along the rank axis.

import { constTensor } from './runtime.js';

function bf16ToF32(u16) {
  const out = new Float32Array(u16.length);
  const u32 = new Uint32Array(out.buffer);
  for (let i = 0; i < u16.length; i++) u32[i] = u16[i] << 16;
  return out;
}

function f16ToF32(u16) {
  const out = new Float32Array(u16.length);
  for (let i = 0; i < u16.length; i++) {
    const h = u16[i];
    const s = h & 0x8000 ? -1 : 1;
    const e = (h >> 10) & 0x1f;
    const f = h & 0x3ff;
    out[i] = e === 0 ? s * 2 ** -14 * (f / 1024) : e === 31 ? (f ? NaN : s * Infinity) : s * 2 ** (e - 15) * (1 + f / 1024);
  }
  return out;
}

export function parseSafetensors(bytes) {
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const n = Number(view.getBigUint64(0, true));
  const header = JSON.parse(new TextDecoder().decode(bytes.subarray(8, 8 + n)));
  const meta = header.__metadata__ || {};
  delete header.__metadata__;
  const base = 8 + n;
  const tensors = new Map();
  for (const [name, t] of Object.entries(header)) {
    const [a, b] = t.data_offsets;
    const raw = bytes.slice(base + a, base + b);
    let data;
    if (t.dtype === 'F32') data = new Float32Array(raw.buffer);
    else if (t.dtype === 'F16') data = f16ToF32(new Uint16Array(raw.buffer));
    else if (t.dtype === 'BF16') data = bf16ToF32(new Uint16Array(raw.buffer));
    else throw new Error(`unsupported LoRA dtype ${t.dtype} (${name})`);
    tensors.set(name, { shape: t.shape, data });
  }
  return { meta, tensors };
}

// Describe a parsed LoRA: rank, alpha, trigger, and how many of the spec's linears it covers.
export function describeLora(lora, spec) {
  const rank = parseInt(lora.meta.rank || '0', 10) || inferRank(lora);
  const alpha = parseFloat(lora.meta.alpha || String(rank));
  let covered = 0;
  let total = 0;
  for (const g of spec) {
    for (let b = 0; b < g.blocks; b++) {
      total++;
      if (lora.tensors.has(`${g.stack}.${b}.${g.layer}.A`)) covered++;
    }
  }
  return { rank, alpha, trigger: lora.meta.trigger || '', covered, total, base: lora.meta.base || '' };
}

function inferRank(lora) {
  for (const [k, t] of lora.tensors) if (k.endsWith('.A')) return t.shape[0];
  return 0;
}

// active: [{ lora (parsed), strength }]. Returns { name: ort.Tensor } for every LoRA input of the export.
export async function loraFeeds(spec, active, backend) {
  const used = active.filter((a) => a.strength !== 0);
  const infos = used.map((a) => ({ ...a, info: describeLora(a.lora, spec) }));
  const R = Math.max(1, infos.reduce((s, a) => s + a.info.rank, 0));
  const feeds = {};
  for (const g of spec) {
    const A = new Float32Array(g.blocks * g.in * R);
    const B = new Float32Array(g.blocks * R * g.out);
    let off = 0;
    for (const { lora, strength, info } of infos) {
      const r = info.rank;
      const scale = (strength * info.alpha) / r;
      for (let b = 0; b < g.blocks; b++) {
        const ta = lora.tensors.get(`${g.stack}.${b}.${g.layer}.A`); // [r, in]
        const tb = lora.tensors.get(`${g.stack}.${b}.${g.layer}.B`); // [out, r]
        if (!ta || !tb) continue;
        if (ta.shape[1] !== g.in || tb.shape[0] !== g.out) {
          throw new Error(`LoRA shape mismatch at ${g.stack}.${b}.${g.layer}: A ${ta.shape}, B ${tb.shape}`);
        }
        for (let k = 0; k < r; k++) {
          for (let i = 0; i < g.in; i++) A[(b * g.in + i) * R + off + k] = ta.data[k * g.in + i];
          for (let o = 0; o < g.out; o++) B[(b * R + off + k) * g.out + o] = scale * tb.data[o * r + k];
        }
      }
      off += r;
    }
    feeds[g.A] = await constTensor(backend, A, [g.blocks, g.in, R]);
    feeds[g.B] = await constTensor(backend, B, [g.blocks, R, g.out]);
  }
  return feeds;
}