File size: 12,388 Bytes
a04c389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eea347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a04c389
6eea347
a04c389
 
 
 
 
 
 
6eea347
a04c389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eea347
 
a04c389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe55445
a04c389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe55445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a04c389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe55445
a04c389
 
fe55445
a04c389
 
fe55445
 
a04c389
fe55445
a04c389
 
 
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
const PARAM_U32_COUNT = 12;
const PARAM_BUFFER_BYTES = PARAM_U32_COUNT * 4;
const shaderTextCache = new Map();
const pipelineCache = new WeakMap();

function align4(value) {
  return (value + 3) & ~3;
}

function packedWeightToWords(packedWeight) {
  const bytes = packedWeight instanceof Uint8Array ? packedWeight : new Uint8Array(packedWeight);
  const padded = new Uint8Array(align4(bytes.byteLength));
  padded.set(bytes);
  return new Uint32Array(padded.buffer);
}

function createStorageBuffer(device, data, usage = GPUBufferUsage.STORAGE) {
  const source = ArrayBuffer.isView(data) ? data : new Uint8Array(data);
  const buffer = device.createBuffer({
    size: align4(source.byteLength),
    usage: usage | GPUBufferUsage.COPY_DST,
  });
  device.queue.writeBuffer(buffer, 0, source.buffer, source.byteOffset, source.byteLength);
  return buffer;
}

function createOutputBuffer(device, byteLength) {
  return device.createBuffer({
    size: align4(byteLength),
    usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,
  });
}

function createReadbackBuffer(device, byteLength) {
  return device.createBuffer({
    size: align4(byteLength),
    usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
  });
}

function normalizeLayout(layoutHeader) {
  if (!layoutHeader || layoutHeader.length < 13) {
    throw new Error("BitNet layout_header must contain at least 13 entries");
  }
  const header = Array.from(layoutHeader, Number);
  if (header[0] !== 1 || header[1] !== 16 || header[2] !== 32 || header[9] !== 1) {
    throw new Error("Unsupported BitNet browser layout; expected v1 16x32 interleave mode 1");
  }
  return {
    logicalOut: header[3],
    logicalIn: header[4],
    paddedOut: header[5],
    paddedIn: header[6],
    scaleGranularity: header[7],
    scaleGroupSize: header[8],
    segmentCount: header[11],
  };
}

function resolveUrl(path, baseUrl) {
  return new URL(path, baseUrl).toString();
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function fetchWithRetry(url, options = {}) {
  const attempts = Math.max(1, Number(options.attempts || 5));
  let lastError = null;
  for (let attempt = 0; attempt < attempts; attempt += 1) {
    try {
      const response = await fetch(url);
      if (response.ok) return response;
      if (response.status < 500 && response.status !== 408 && response.status !== 429) {
        throw new Error(`failed to fetch ${url}: ${response.status}`);
      }
      lastError = new Error(`failed to fetch ${url}: ${response.status}`);
    } catch (error) {
      lastError = error;
    }
    if (attempt < attempts - 1) {
      await sleep(Math.min(2000, 150 * 2 ** attempt));
    }
  }
  throw lastError || new Error(`failed to fetch ${url}`);
}

async function fetchJson(url) {
  const response = await fetchWithRetry(url);
  if (!response.ok) {
    throw new Error(`failed to fetch ${url}: ${response.status}`);
  }
  return response.json();
}

async function fetchText(url) {
  const response = await fetchWithRetry(url);
  if (!response.ok) {
    throw new Error(`failed to fetch ${url}: ${response.status}`);
  }
  return response.text();
}

async function fetchTextCached(url) {
  if (!shaderTextCache.has(url)) {
    shaderTextCache.set(url, fetchText(url));
  }
  return shaderTextCache.get(url);
}

async function getBitNetPipeline(device, shaderCode, cacheKey) {
  let deviceCache = pipelineCache.get(device);
  if (!deviceCache) {
    deviceCache = new Map();
    pipelineCache.set(device, deviceCache);
  }
  if (!deviceCache.has(cacheKey)) {
    deviceCache.set(cacheKey, (async () => {
      const module = device.createShaderModule({ code: shaderCode });
      const descriptor = {
        layout: "auto",
        compute: { module, entryPoint: "bitnet_linear_main" },
      };
      const pipeline = typeof device.createComputePipelineAsync === "function"
        ? await device.createComputePipelineAsync(descriptor)
        : device.createComputePipeline(descriptor);
      return { module, pipeline };
    })());
  }
  return deviceCache.get(cacheKey);
}

async function fetchTensor(entry, baseUrl, TypedArray) {
  const url = resolveUrl(entry.path, baseUrl);
  const response = await fetchWithRetry(url);
  if (!response.ok) {
    throw new Error(`failed to fetch ${entry.path}: ${response.status}`);
  }
  return new TypedArray(await response.arrayBuffer());
}

function tensorType(entry) {
  if (entry.dtype === "uint8") {
    return Uint8Array;
  }
  if (entry.dtype === "int32") {
    return Int32Array;
  }
  if (entry.dtype === "float32") {
    return Float32Array;
  }
  throw new Error(`unsupported tensor dtype: ${entry.dtype}`);
}

export async function createBitNetWebGPUDevice() {
  if (!globalThis.navigator?.gpu) {
    throw new Error("WebGPU is not available in this browser");
  }
  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw new Error("WebGPU adapter request failed");
  }
  const device = await adapter.requestDevice();
  return { adapter, device };
}

export class BitNetLinearWebGPU {
  constructor(device, bundle) {
    this.device = device;
    this.layout = normalizeLayout(bundle.layoutHeader);
    this.hasBias = bundle.bias != null;
    this.inputQuantMode = bundle.inputQuantMode ?? 0;
    this.inputQuantBits = bundle.inputQuantBits ?? 8;
    this.inputScaleRows = bundle.inputScaleRows ?? 1;

    if (!bundle.shaderCode && !bundle.pipeline) {
      throw new Error("BitNetLinearWebGPU requires shaderCode or pipeline; use fromManifestLayer() or fromManifestUrl()");
    }
    if (bundle.pipeline) {
      this.module = bundle.module || null;
      this.pipeline = bundle.pipeline;
    } else {
      this.module = device.createShaderModule({ code: bundle.shaderCode });
      this.pipeline = device.createComputePipeline({
        layout: "auto",
        compute: { module: this.module, entryPoint: "bitnet_linear_main" },
      });
    }

    this.packedWeightBuffer = createStorageBuffer(device, packedWeightToWords(bundle.packedWeight));
    this.scaleBuffer = createStorageBuffer(device, new Float32Array(bundle.scaleValues));
    this.segmentOffsetBuffer = createStorageBuffer(device, new Uint32Array(bundle.segmentOffsets));
    this.biasBuffer = createStorageBuffer(
      device,
      this.hasBias ? new Float32Array(bundle.bias) : new Float32Array([0]),
    );
    this.inputScaleBuffer = createStorageBuffer(
      device,
      bundle.inputScales ? new Float32Array(bundle.inputScales) : new Float32Array([1]),
    );
    this.paramsBuffer = device.createBuffer({
      size: PARAM_BUFFER_BYTES,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
    });
    this.runCache = new Map();
  }

  static async fromManifestLayer(device, manifest, layer, manifestUrl, options = {}) {
    const progress = typeof options.progress === "function" ? options.progress : () => {};
    const index = Number(options.index || 0);
    const total = Number(options.total || 0);
    const name = String(options.name || layer.name || "layer");
    const label = total ? `${index}/${total}: ${name}` : name;
    const baseUrl = new URL(".", manifestUrl).toString();
    const shaderUrl = resolveUrl(manifest.runtime.files.wgsl, baseUrl);
    const runtimeBaseUrl = resolveUrl(".", shaderUrl);
    progress({ phase: "layer_shader", index, total, name, message: `Loading shader for BitNet layer ${label}` });
    const shaderCode = options.shaderCode || await fetchTextCached(shaderUrl);
    progress({ phase: "layer_pipeline", index, total, name, message: `Preparing WebGPU pipeline for BitNet layer ${label}` });
    const pipelineBundle = options.pipeline
      ? { module: options.module || null, pipeline: options.pipeline }
      : await getBitNetPipeline(device, shaderCode, shaderUrl);
    const tensors = layer.tensors;
    const layersBaseUrl = resolveUrl("layers/", baseUrl);
    progress({ phase: "layer_tensors", index, total, name, message: `Loading tensors for BitNet layer ${label}` });
    const [packedWeight, scaleValues, segmentOffsets, bias, inputScales] = await Promise.all([
      fetchTensor(tensors.packed_weight, layersBaseUrl, Uint8Array),
      fetchTensor(tensors.scale_values, layersBaseUrl, Float32Array),
      fetchTensor(tensors.segment_offsets, layersBaseUrl, Int32Array),
      tensors.bias ? fetchTensor(tensors.bias, layersBaseUrl, Float32Array) : Promise.resolve(null),
      fetchTensor(tensors.act_scale, layersBaseUrl, tensorType(tensors.act_scale)),
    ]);
    progress({ phase: "layer_upload", index, total, name, message: `Uploading BitNet layer ${label}` });
    return new BitNetLinearWebGPU(device, {
      shaderCode,
      module: pipelineBundle.module,
      pipeline: pipelineBundle.pipeline,
      layoutHeader: layer.layout_header,
      packedWeight,
      scaleValues,
      segmentOffsets,
      bias,
      inputScales,
      inputQuantMode: layer.act_quant_mode === "none" ? 0 : 1,
      inputQuantBits: layer.act_quant_bits,
      inputScaleRows: layer.act_quant_mode === "static_int8" ? 1 : 1,
      runtimeBaseUrl,
    });
  }

  static async fromManifestUrl(device, manifestUrl, layerName) {
    const manifest = await fetchJson(manifestUrl);
    const layer = manifest.layers.find((candidate) => candidate.name === layerName);
    if (!layer) {
      throw new Error(`BitNet layer not found in manifest: ${layerName}`);
    }
    return BitNetLinearWebGPU.fromManifestLayer(device, manifest, layer, manifestUrl);
  }

  async run(input, rows = 1) {
    const x = input instanceof Float32Array ? input : new Float32Array(input);
    if (x.length !== rows * this.layout.logicalIn) {
      throw new Error(`BitNet input length mismatch: got ${x.length}, expected ${rows * this.layout.logicalIn}`);
    }

    const outputLength = rows * this.layout.logicalOut;
    const inputBytes = x.byteLength;
    const outputBytes = outputLength * Float32Array.BYTES_PER_ELEMENT;
    const cacheKey = `${rows}:${this.layout.logicalIn}:${this.layout.logicalOut}`;
    let cache = this.runCache.get(cacheKey);
    if (!cache) {
      const inputBuffer = this.device.createBuffer({
        size: align4(inputBytes),
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
      });
      const outputBuffer = createOutputBuffer(this.device, outputBytes);
      const readbackBuffer = createReadbackBuffer(this.device, outputBytes);
      const bindGroup = this.device.createBindGroup({
        layout: this.pipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: { buffer: inputBuffer } },
          { binding: 1, resource: { buffer: this.packedWeightBuffer } },
          { binding: 2, resource: { buffer: this.scaleBuffer } },
          { binding: 3, resource: { buffer: this.segmentOffsetBuffer } },
          { binding: 4, resource: { buffer: this.biasBuffer } },
          { binding: 5, resource: { buffer: this.inputScaleBuffer } },
          { binding: 6, resource: { buffer: outputBuffer } },
          { binding: 7, resource: { buffer: this.paramsBuffer } },
        ],
      });
      cache = { inputBuffer, outputBuffer, readbackBuffer, bindGroup };
      this.runCache.set(cacheKey, cache);
    }
    this.device.queue.writeBuffer(cache.inputBuffer, 0, x.buffer, x.byteOffset, x.byteLength);

    const params = new Uint32Array([
      rows,
      this.layout.logicalIn,
      this.layout.logicalOut,
      this.layout.paddedIn,
      this.layout.scaleGranularity,
      this.layout.scaleGroupSize,
      this.layout.segmentCount,
      this.hasBias ? 1 : 0,
      this.inputQuantMode,
      this.inputQuantBits,
      this.inputScaleRows,
      0,
    ]);
    this.device.queue.writeBuffer(this.paramsBuffer, 0, params);

    const encoder = this.device.createCommandEncoder();
    const pass = encoder.beginComputePass();
    pass.setPipeline(this.pipeline);
    pass.setBindGroup(0, cache.bindGroup);
    pass.dispatchWorkgroups(Math.ceil(this.layout.logicalOut / 8), Math.ceil(rows / 8), 1);
    pass.end();
    encoder.copyBufferToBuffer(cache.outputBuffer, 0, cache.readbackBuffer, 0, outputBytes);
    this.device.queue.submit([encoder.finish()]);

    await cache.readbackBuffer.mapAsync(GPUMapMode.READ);
    const mapped = cache.readbackBuffer.getMappedRange();
    const result = new Float32Array(mapped.slice(0));
    cache.readbackBuffer.unmap();
    return result;
  }
}