|
| 1 | +import * as ort from 'onnxruntime-web/webgpu'; |
| 2 | + |
| 3 | +ort.env.wasm.numThreads = 1; |
| 4 | +ort.env.wasm.simd = true; |
| 5 | +ort.env.wasm.wasmPaths = document.location.pathname.replace('index.html', '') + 'dist/'; |
| 6 | + |
| 7 | + |
| 8 | +function log(i) { console.log(i); document.getElementById('status').innerText += `\n${i}`; } |
| 9 | + |
| 10 | +// |
| 11 | +// load file from server or cache |
| 12 | +// |
| 13 | +async function fetchAndCache(url) { |
| 14 | + try { |
| 15 | + const cache = await caches.open("onnx"); |
| 16 | + let cachedResponse = await cache.match(url); |
| 17 | + if (cachedResponse === undefined) { |
| 18 | + log(`${url} (network)`); |
| 19 | + const buffer = await fetch(url).then(response => response.arrayBuffer()); |
| 20 | + try { |
| 21 | + await cache.put(url, new Response(buffer)); |
| 22 | + } catch (error) { |
| 23 | + console.error(error); |
| 24 | + } |
| 25 | + return buffer; |
| 26 | + } |
| 27 | + log(`${url} (cached)`); |
| 28 | + const data = await cachedResponse.arrayBuffer(); |
| 29 | + return data; |
| 30 | + } catch (error) { |
| 31 | + log(`can't fetch ${url}`); |
| 32 | + throw error; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// |
| 37 | +// class to handle a large language model on top of onnxruntime-web |
| 38 | +// |
| 39 | +export class LLM { |
| 40 | + sess = undefined; |
| 41 | + profiler = false; |
| 42 | + feed = {}; |
| 43 | + output_tokens = []; |
| 44 | + eos = 2; |
| 45 | + need_position_ids = true; |
| 46 | + stop = false; |
| 47 | + kv_dims = []; |
| 48 | + dtype = "float16"; |
| 49 | + max_tokens = 9999; |
| 50 | + |
| 51 | + constructor() { |
| 52 | + } |
| 53 | + |
| 54 | + async load(model, options) { |
| 55 | + const provider = options.provider || "webgpu"; |
| 56 | + const verbose = options.verbose; |
| 57 | + const local = options.local; |
| 58 | + const hasFP16 = (provider === "wasm") ? false : options.hasFP16; |
| 59 | + this.profiler = options.profiler; |
| 60 | + |
| 61 | + const model_path = (local) ? "models/" + model.path : "https://huggingface.co/" + model.path + "/resolve/main"; |
| 62 | + let model_file = model.file || "model"; |
| 63 | + model_file = (hasFP16) ? model_file + "_q4f16.onnx" : model_file + "_q4.onnx"; |
| 64 | + |
| 65 | + log(`loading... ${model.name}, ${provider}`); |
| 66 | + const json_bytes = await fetchAndCache(model_path + "/config.json"); |
| 67 | + let textDecoder = new TextDecoder(); |
| 68 | + const model_config = JSON.parse(textDecoder.decode(json_bytes)); |
| 69 | + |
| 70 | + const model_bytes = await fetchAndCache(model_path + "/onnx/" + model_file); |
| 71 | + const externaldata = (model.externaldata) ? await fetchAndCache(model_path + "/onnx/" + model_file + '_data') : false; |
| 72 | + let modelSize = model_bytes.byteLength; |
| 73 | + if (externaldata) { |
| 74 | + modelSize += externaldata.byteLength; |
| 75 | + } |
| 76 | + log(`model size ${Math.round(modelSize / 1024 / 1024)} MB`); |
| 77 | + |
| 78 | + const opt = { |
| 79 | + executionProviders: [provider], |
| 80 | + preferredOutputLocation: {}, |
| 81 | + } |
| 82 | + |
| 83 | + switch (provider) { |
| 84 | + case "webgpu": |
| 85 | + for (let i = 0; i < model_config.num_hidden_layers; ++i) { |
| 86 | + opt.preferredOutputLocation[`present.${i}.key`] = 'gpu-buffer'; |
| 87 | + opt.preferredOutputLocation[`present.${i}.value`] = 'gpu-buffer'; |
| 88 | + } |
| 89 | + break; |
| 90 | + } |
| 91 | + |
| 92 | + if (externaldata !== undefined) { |
| 93 | + opt.externalData = [ |
| 94 | + { |
| 95 | + data: externaldata, |
| 96 | + path: model_file + "_data", |
| 97 | + }, |
| 98 | + ] |
| 99 | + } |
| 100 | + if (verbose) { |
| 101 | + opt.logSeverityLevel = 0; |
| 102 | + opt.logVerbosityLevel = 0; |
| 103 | + ort.env.logLevel = "verbose"; |
| 104 | + } |
| 105 | + |
| 106 | + ort.env.webgpu.profiling = {} |
| 107 | + if (this.profiler) { |
| 108 | + opt.enableProfiling = true; |
| 109 | + ort.env.webgpu.profilingMode = 'default'; |
| 110 | + ort.env.webgpu.profiling.mode = 'default'; |
| 111 | + } |
| 112 | + |
| 113 | + this.sess = await ort.InferenceSession.create(model_bytes, opt); |
| 114 | + this.eos = model_config.eos_token_id; |
| 115 | + this.kv_dims = [1, model_config.num_key_value_heads, 0, model_config.hidden_size / model_config.num_attention_heads]; |
| 116 | + this.dtype = (hasFP16) ? "float16" : "float32"; |
| 117 | + this.num_layers = model_config.num_hidden_layers; |
| 118 | + this.initilize_feed(); |
| 119 | + } |
| 120 | + |
| 121 | + initilize_feed() { |
| 122 | + const feed = this.feed; |
| 123 | + |
| 124 | + // dispose of previous gpu buffers |
| 125 | + for (const name in feed) { |
| 126 | + const t = feed[name]; |
| 127 | + if (t.location === 'gpu-buffer') { |
| 128 | + t.dispose(); |
| 129 | + } |
| 130 | + } |
| 131 | + this.feed = {}; |
| 132 | + // key value cache is zero copy, just pass gpu buffer as referece |
| 133 | + const empty = (this.dtype === "float16") ? new Uint16Array() : []; |
| 134 | + for (let i = 0; i < this.num_layers; ++i) { |
| 135 | + this.feed[`past_key_values.${i}.key`] = new ort.Tensor(this.dtype, empty, this.kv_dims) |
| 136 | + this.feed[`past_key_values.${i}.value`] = new ort.Tensor(this.dtype, empty, this.kv_dims) |
| 137 | + } |
| 138 | + this.output_tokens = []; |
| 139 | + } |
| 140 | + |
| 141 | + // |
| 142 | + // poor mens argmax |
| 143 | + argmax(t) { |
| 144 | + const arr = t.data; |
| 145 | + const start = t.dims[2] * (t.dims[1] - 1); |
| 146 | + let max = arr[start]; |
| 147 | + let maxidx = 0; |
| 148 | + |
| 149 | + for (let i = 0; i < t.dims[2]; i++) { |
| 150 | + const val = arr[i + start]; |
| 151 | + if (!isFinite(val)) { |
| 152 | + throw new Error("found infinitive in logits"); |
| 153 | + } |
| 154 | + if (val > max) { |
| 155 | + max = arr[i + start]; |
| 156 | + maxidx = i; |
| 157 | + } |
| 158 | + } |
| 159 | + return maxidx; |
| 160 | + } |
| 161 | + |
| 162 | + // |
| 163 | + // update key value cache |
| 164 | + // |
| 165 | + update_kv_cache(feed, outputs) { |
| 166 | + for (const name in outputs) { |
| 167 | + if (name.startsWith('present')) { |
| 168 | + let newName = name.replace('present', 'past_key_values'); |
| 169 | + // dispose previous gpu buffers |
| 170 | + const t = feed[newName]; |
| 171 | + if (t.location === 'gpu-buffer') { |
| 172 | + t.dispose(); |
| 173 | + } |
| 174 | + feed[newName] = outputs[name]; |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + // |
| 180 | + // tell generate to stop() |
| 181 | + // |
| 182 | + abort() { |
| 183 | + this.stop = true; |
| 184 | + } |
| 185 | + |
| 186 | + // |
| 187 | + // prefill prompt and generate tokens, greedy search only |
| 188 | + // |
| 189 | + async generate(tokens, callback, options) { |
| 190 | + const max_tokens = options.max_tokens || 256; |
| 191 | + const feed = this.feed; |
| 192 | + const input_ids = new ort.Tensor('int64', BigInt64Array.from(tokens.map(BigInt)), [1, tokens.length]); |
| 193 | + feed['input_ids'] = input_ids; |
| 194 | + this.stop = false; |
| 195 | + |
| 196 | + this.output_tokens.push(...input_ids.data); |
| 197 | + |
| 198 | + let last_token = 0n; |
| 199 | + let seqlen = this.output_tokens.length; |
| 200 | + const input_len = input_ids.size; |
| 201 | + |
| 202 | + if (this.need_position_ids) { |
| 203 | + feed['position_ids'] = new ort.Tensor('int64', BigInt64Array.from({ length: input_len }, (_, i) => BigInt(seqlen - input_len + i)), [1, input_len]); |
| 204 | + } |
| 205 | + |
| 206 | + while (last_token != this.eos && last_token != 32007 && seqlen < max_tokens && !this.stop) { |
| 207 | + seqlen = this.output_tokens.length; |
| 208 | + feed['attention_mask'] = new ort.Tensor('int64', BigInt64Array.from({ length: seqlen }, () => 1n), [1, seqlen]); |
| 209 | + const outputs = await this.sess.run(feed); |
| 210 | + last_token = BigInt(this.argmax(outputs.logits)); |
| 211 | + this.output_tokens.push(last_token); |
| 212 | + if (callback && !this.profiler) { |
| 213 | + callback(this.output_tokens); |
| 214 | + } |
| 215 | + this.update_kv_cache(feed, outputs); |
| 216 | + feed['input_ids'] = new ort.Tensor('int64', BigInt64Array.from([last_token]), [1, 1]); |
| 217 | + if (this.need_position_ids) { |
| 218 | + feed['position_ids'] = new ort.Tensor('int64', BigInt64Array.from([BigInt(seqlen)]), [1, 1]); |
| 219 | + } |
| 220 | + } |
| 221 | + if (this.profiler) { |
| 222 | + this.sess.endProfiling(); |
| 223 | + } |
| 224 | + return this.output_tokens; |
| 225 | + } |
| 226 | +} |
0 commit comments