File size: 5,959 Bytes
faca43f
0015338
6e8146a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0015338
 
6e8146a
 
 
 
 
 
 
 
 
 
0015338
6e8146a
 
 
 
 
 
 
 
 
 
0015338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a073fd
0015338
 
 
 
faca43f
 
5528541
faca43f
 
5528541
faca43f
5528541
 
 
 
 
 
 
faca43f
 
 
 
 
0015338
6e8146a
0015338
faca43f
 
0015338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faca43f
0015338
 
 
5528541
faca43f
0015338
 
 
 
 
 
 
 
faca43f
0015338
 
 
 
 
 
 
 
 
 
 
 
6e8146a
 
 
0015338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faca43f
0015338
 
 
 
 
 
 
 
 
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
import { pipeline, env } from "@xenova/transformers";
import init, { Model } from "./phi/m.js";
import URI from "urijs"

// Shamelessly stolen from Transformers.js

export async function tryCache(cache, ...names) {
    for (let name of names) {
        try {
			console.log(name)
            let result = await cache.match(name);
            if (result) return result;
        } catch (e) {
            continue;
        }
    }
    return undefined;
}

async function read_stream(url, response) {
	const reader = response.body.getReader();
	const contentLength = +response.headers.get('Content-Length');
	let receivedLength = 0;
	let chunks = []; 
	let uri = new URI(url)

	while(true) {
		const {done, value} = await reader.read();
		if (done) {
			break;
		}
		chunks.push(value);
		receivedLength += value.length;
		let percent = (receivedLength / contentLength) * 100
		self.postMessage({ status: "progress", file: uri.filename(), progress: percent });
	}

	let chunksAll = new Uint8Array(receivedLength); 
	let position = 0;
	for(let chunk of chunks) {
		chunksAll.set(chunk, position); 
		position += chunk.length;
	}
	return chunksAll
}

async function fetchArrayBuffer(url) {
	let cache = await caches.open('transformers-cache');

	const response = await tryCache(cache, url);
	if (response != undefined) {
		console.log(url)
		let res = await read_stream(url, response)
		cache.put(url, new Response(res, {
            headers: response.headers
        }));
		return new Uint8Array(res);
	}
	else {
		const response = await fetch(url);
		let res = await read_stream(url, response)
		cache.put(url, new Response(res, {
            headers: response.headers,
        }));
		return new Uint8Array(res);
	}


}

class Phi {
	static instance = {};
  
	static async getInstance(weightsURL, modelID, tokenizerURL, quantized) {
	  // load individual modelID only once
	  if (!this.instance[modelID]) {
		await init();
  
		self.postMessage({ status: "loading", message: "Loading Model" });
  
		const [weightsArrayU8, tokenizerArrayU8] = await Promise.all([
		  fetchArrayBuffer(weightsURL),
		  fetchArrayBuffer(tokenizerURL),
		]);

		self.postMessage({ status: "init_model" });
  
		this.instance[modelID] = new Model(
		  weightsArrayU8,
		  tokenizerArrayU8,
		  quantized
		);
		self.postMessage({ status: "ready", model: "phi-1_5" });
	  }
	  return this.instance[modelID];
	}
 }

export class FlanPipeline {
	static curr_model = "";
	static instance = null;

	static async getInstance(progress_callback = null, model, task) {
		if (this.instance === null) {
			this.instance = pipeline(task, model, { progress_callback });
			this.curr_model = model;
		} else {
			if (this.curr_model != model) {
				this.instance = pipeline(task, model, { progress_callback });
				this.curr_model = model;
			}
		}
		return this.instance;
	}
}

let controller = null;
let phi_model = null;

// Listen for messages from the main thread
self.addEventListener("message", async (event) => {
	if (event.data.command != "abort") {
		if (event.data.is_phi) {
			controller = new AbortController();
			generate_phi(event.data);
		}
		else {
			let pipe = await FlanPipeline.getInstance(
				(x) => {
					self.postMessage(x);
				},
				event.data.model,
				event.data.task
			);
		
			let output = await pipe(event.data.text, {
				max_new_tokens: event.data.max_new_tokens,
				temperature: event.data.temperature,
				callback_function: (x) => {
					self.postMessage({
						status: "update",
						output: pipe.tokenizer.decode(x[0].output_token_ids, { skip_special_tokens: true }),
						id_now: event.data.id_now,
					});
				},
			});
		
			// Send the output back to the main thread
			self.postMessage({
				status: "complete",
				output: output,
				searchID: event.data.searchID,
				id_now: event.data.id_now,
			});
		}
	}
	else {
		if (controller != null)
			controller.abort();
	}
});



async function generate_phi(data) {
	const tokenizerURL = "https://huggingface.co/microsoft/phi-1_5/raw/main/tokenizer.json";
	const weightsURL = "https://huggingface.co/lmz/candle-quantized-phi/resolve/main/model-q4k.gguf";
	let prompt = data.text
	let maxSeqLen = data.max_new_tokens
	let temp = data.temperature
	let modelID = 0;
	let quantized = true;
	let top_p = 1;
	let repeatPenalty = 1.1;
	let seed = 299792458;

	self.postMessage({ status: "initiate", file: "tokenizer.json", name: "phi-1_5" }); // Fake init

	try {
	  const model = await Phi.getInstance(
		weightsURL,
		modelID,
		tokenizerURL,
		quantized
	  );
  
	  const firstToken = model.init_with_prompt(
		prompt,
		temp,
		top_p,
		repeatPenalty,
		64,
		BigInt(seed)
	  );
	  const seq_len = 2048;
  
	  let sentence = firstToken;
	  let maxTokens = maxSeqLen ? maxSeqLen : seq_len - prompt.length - 1;
	  let startTime = performance.now();
	  let tokensCount = 0;

	  while (tokensCount < maxTokens) {
		await new Promise(async (resolve) => {
		  if (controller && controller.signal.aborted) {
			self.postMessage({
			  status: "aborted",
			  message: "Aborted",
			  output: sentence,
			  searchID: data.searchID,
			  id_now: data.id_now,
			});
			return;
		  }
		  const token = await model.next_token();
		  if (token === "<|endoftext|>") {
			self.postMessage({
			  status: "complete",
			  output: sentence,
			  searchID: data.searchID,
			  id_now: data.id_now,
			});
			return;
		  }
		  const tokensSec =
			((tokensCount + 1) / (performance.now() - startTime)) * 1000;
  
		  sentence += token;
		  self.postMessage({
			status: "update",
			message: "Generating token",
			token: token,
			output: sentence,
			totalTime: performance.now() - startTime,
			tokensSec,
			prompt: prompt,
			id_now: data.id_now,
		  });
		  setTimeout(resolve, 0);
		});
		tokensCount++;
	  }
	  self.postMessage({
		status: "complete",
		output: sentence,
		searchID: data.searchID,
		id_now: data.id_now,
	  });
	} catch (e) {
      console.log(e)
	  self.postMessage({ error: e });
	}
  }