-
Notifications
You must be signed in to change notification settings - Fork 21
/
musicgen_worker.js
573 lines (466 loc) · 16.9 KB
/
musicgen_worker.js
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import { AutoTokenizer, MusicgenForConditionalGeneration, BaseStreamer, StoppingCriteria, env } from './tjs/transformers.min.js';
try{
//import wavefile from './wavefile.js';
//import { wavefile } from './js/wavefile.js';
//var wav = new wavefile.WaveFile();
//console.log("wavefile wav: ", wav);
}
catch(e){
console.error("WHY DOES THIS FAIL? ", e);
}
//console.log("HELLO FROM MUSICGEN WORKER");
// Do local model checks
env.allowLocalModels = false;
env.allowRemoteModels = true;
env.useBrowserCache = true;
self.device = 'wasm';
self.supports_web_gpu16 = false;
self.supports_web_gpu32 = false;
self.task = null;
self.busy_generating = false;
class InterruptableStoppingCriteria extends StoppingCriteria {
constructor() {
super();
this.interrupted = false;
}
interrupt() {
this.interrupted = true;
}
reset() {
this.interrupted = false;
}
_call(input_ids, scores) {
return new Array(input_ids.length).fill(this.interrupted);
}
}
const stopping_criteria = new InterruptableStoppingCriteria();
function minFramesForTargetMS(targetDuration, frameSamples, sr = 16e3) {
return Math.ceil(targetDuration * sr / 1e3 / frameSamples);
}
function arrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function encodeWAV(samples, format = 3, sampleRate = 16e3, numChannels = 1, bitDepth = 32) {
var bytesPerSample = bitDepth / 8;
var blockAlign = numChannels * bytesPerSample;
var buffer = new ArrayBuffer(44 + samples.length * bytesPerSample);
var view = new DataView(buffer);
writeString(view, 0, "RIFF");
view.setUint32(4, 36 + samples.length * bytesPerSample, true);
writeString(view, 8, "WAVE");
writeString(view, 12, "fmt ");
view.setUint32(16, 16, true);
view.setUint16(20, format, true);
view.setUint16(22, numChannels, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * blockAlign, true);
view.setUint16(32, blockAlign, true);
view.setUint16(34, bitDepth, true);
writeString(view, 36, "data");
view.setUint32(40, samples.length * bytesPerSample, true);
if (format === 1) {
floatTo16BitPCM(view, 44, samples);
} else {
writeFloat32(view, 44, samples);
}
return buffer;
}
function writeFloat32(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 4) {
output.setFloat32(offset, input[i], true);
}
}
function floatTo16BitPCM(output, offset, input) {
for (var i = 0; i < input.length; i++, offset += 2) {
var s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 32768 : s * 32767, true);
}
}
function writeString(view, offset, string) {
for (let i = 0; i < string.length; ++i) {
view.setUint8(offset + i, string.charCodeAt(i))
}
}
class CallbackStreamer extends BaseStreamer {
constructor(callback_fn) {
super();
this.callback_fn = callback_fn;
}
put(value) {
return this.callback_fn(value);
}
end() {
return this.callback_fn();
}
}
function isPromise (obj) {
// via https://unpkg.com/[email protected]/index.js
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
function registerPromiseWorker (callback) {
function postOutgoingMessage (e, messageId, error, result) {
function postMessage (msg) {
/* istanbul ignore if */
if (typeof self.postMessage !== 'function') { // service worker
e.ports[0].postMessage(msg)
} else { // web worker
self.postMessage(msg)
}
}
if (error) {
/* istanbul ignore else */
if (typeof console !== 'undefined' && 'error' in console) {
// This is to make errors easier to debug. I think it's important
// enough to just leave here without giving the user an option
// to silence it.
console.error('Promise worker caught an error:',error);
//const error_string = '' + error.error;
//console.error("error string: ", typeof error_string, error_string);
//postMessage({'task':self.task,'status':'error','error':error_string});
postMessage(error);
}
postMessage([messageId, {
task:self.task,
message: error.message
}])
} else {
postMessage([messageId, null, result])
}
}
function tryCatchFunc (callback, message) {
try {
return { res: callback(message) }
} catch (e) {
return { err: e }
}
}
function handleIncomingMessage (e, callback, messageId, message) {
console.log("registerPromiseWorker: in handleIncomingMessage")
var result = tryCatchFunc(callback, message)
if (result.err) {
postOutgoingMessage(e, messageId, result.err)
} else if (!isPromise(result.res)) {
postOutgoingMessage(e, messageId, null, result.res)
} else {
result.res.then(function (finalResult) {
postOutgoingMessage(e, messageId, null, finalResult)
}, function (finalError) {
postOutgoingMessage(e, messageId, finalError)
})
}
}
function onIncomingMessage (e) {
console.log("registerPromiseWorker: onIncomingMessage: e.data: ", e.data);
var payload = e.data
if (!Array.isArray(payload) || payload.length !== 2) {
console.log("onIncomingMessage: ignoring message with wrong format");
// message doens't match communication format; ignore
return
}
var messageId = payload[0]
var message = payload[1]
if (typeof callback !== 'function') {
postOutgoingMessage(e, messageId, new Error(
'Please pass a function into register().'))
} else {
handleIncomingMessage(e, callback, messageId, message)
}
}
self.addEventListener('message', onIncomingMessage)
}
console.log("MUSICGEN (PROMISE) WORKER EXISTS");
//console.log("MUSICGEN (PROMISE) WORKER: registerPromiseWorker: ", registerPromiseWorker);
// Load tokenizer
//self.tokenizer = AutoTokenizer.from_pretrained('Xenova/musicgen-small');
// Prepare for model
self.model = null;
self.tokenizer = null;
self.duration = 30;
self.guidance_scale = 3;
self.temperature = 1;
registerPromiseWorker((message) => {
console.log("MUSICGEN WORKER: registerPromiseWorker: RECEIVED MESSAGE: ", message);
try{
return new Promise((resolve, reject) => {
self.task = null;
const do_musicgen = (sentence) => {
console.log("MUSICGEN WORKER: in do_musicgen. sentence: ", sentence);
self.postMessage({
'status':'ready'
});
if(sentence == 'papegai_preload'){
console.log("MUSICGEN WORKER: prompt was papegai_preload. Stopping here.")
const preload_done_message = {
'task':message.task,
'status':'preloaded'
}
self.postMessage(preload_done_message);
resolve(preload_done_message);
return
}
const max_length = Math.min(
Math.max(Math.floor(self.duration * 50), 1) + 4,
self.model.generation_config.max_length ?? 1500,
);
const inputs = self.tokenizer(sentence);
function generationProgressCallback(x){
//console.log("musicgen worker: generationProgressCallback: ", x);
self.postMessage(x);
}
let num_tokens = 0;
const streamer = new CallbackStreamer((value) => {
try{
//console.log("MUSICGEN WORKER: in callback streamer. value: ", value);
const percent = value === undefined ? 1 : ++num_tokens / max_length;
//console.log("MUSICGEN WORKER: streamer: percent: ", percent);
self.postMessage({
'task':message.task,
'status':'musicgen_progress',
'progress':percent
});
}
catch(err){
console.error("musigen_worker: caught error in callback streamer: ", err);
}
//setStatusText(`Generating (${(percent * 100).toFixed()}%)...`);
//setProgress(percent * 100);
});
const guidance_scale = self.guidance_scale;
const temperature = self.temperature;
self.model.generate({
// Inputs
...inputs,
// Generation parameters
max_length, // duration, as number of tokens.
guidance_scale,
temperature,
// Outputs
streamer,
//stopping_criteria,
})
.then((audio_values) => {
//console.log("MUSICGEN WORKER: \n\ngenerated audio_values: ", audio_values);
//console.warn("MUSICGEN WORKER: audio_values.data: ", audio_values.data);
// console.log("audio_values.ort_tensor.cpuData: ", audio_values.ort_tensor.cpuData);
if(audio_values.data){
const wav = encodeWAV(audio_values.data, 3, 32000, 1, 32);
// Send the output back to the main thread
let result = {
task: message.task,
status: 'complete',
big_audio_array: audio_values.data,
wav_blob: new Blob([wav], { type: 'audio/wav' }),
}
self.postMessage(result);
self.busy_generating = false;
self.task = null;
resolve(result);
}
else{
console.error("MUSICGEN WORKER: issue getting audio_values.data? audio_values:", audio_values);
reject({"status":"error","error":"Caught error: missing audio_values.data?","task": message.task});
}
})
.catch((err) => {
console.error("MUSICGEN_WORKER: caught error generating audio_values: ", err);
reject({"status":"error","error":"Caught error generating audio values or wav file","task": message.task});
self.busy_generating = false;
self.task = null;
return err
})
}
let sentence = null;
if(typeof message.task == 'object'){
console.log("MUSICGEN WORKER: received a task: ", message.task);
if(self.busy_generating){
reject({"status":"already_busy", "error":"musigen worker already busy"});
return false
}
self.busy_generating = true;
self.task = message.task;
self.temperature = 1;
if(typeof message.task.temperature == 'number'){
//console.log("MUSICGEN WORKER: got temperature from task: ", message.task.temperature);
self.temperature = message.task.temperature;
}
self.guidance_scale = 3;
if(typeof message.task.guidance_scale == 'number'){
//console.log("MUSICGEN WORKER: got guidance_scale from task: ", message.task.guidance_scale);
self.guidance_scale = message.task.guidance_scale;
}
self.duration = 30;
if(typeof message.task.music_duration == 'number' && message.task.music_duration > 1 && message.task.music_duration < 31){
//console.log("MUSICGEN WORKER: got intended music duration from task: ", message.task.music_duration);
self.duration = message.task.music_duration;
}
if(typeof message.task.prompt == 'string' && message.task.prompt.length){
//console.log("MUSICGEN_WORKER: task has prompt, using that as the input sentence: ", message.task.prompt);
sentence = message.task.prompt; // simpler shortcut option for simple tasks
}
else if(typeof message.task.sentence == 'string' && message.task.sentence.length){
//console.log("MUSICGEN_WORKER: task had no prompt, but does have sentence. Using that as musicgen input. ", message.task.sentence);
sentence = message.task.sentence;
}
else if(typeof message.task.text == 'string' && message.task.text.length){
//console.log("MUSICGEN_WORKER: task had no sentence, but does have text. Using that as musicgen input. ", message.task.text);
sentence = message.task.text;
}
if(typeof sentence == 'string' && sentence.length){
//console.log("MUSICGEN WORKER: OK, sentence was string with length: ", sentence);
// Progress callback
/*
function progressCallback(x){
//console.log("musicgen worker: progressCallback: ", x);
self.postMessage(x);
}
*/
if(self.tokenizer == null || self.model == null){
AutoTokenizer.from_pretrained('Xenova/musicgen-small')
.then((tokenizer) => {
self.tokenizer = tokenizer;
if(self.device == 'wasm'){
return MusicgenForConditionalGeneration.from_pretrained('Xenova/musicgen-small', {
progress_callback: (progress_data) => {
//console.log("MUSICGEN WORKER: model download progress_callback: progress_data: ", progress_data);
if (progress_data.status !== 'progress') return;
//setLoadProgress(prev => ({ ...prev, [data.file]: data }))
///setLoadProgress(data);
self.postMessage(progress_data);
},
dtype: {
text_encoder: 'q8',
decoder_model_merged: 'q8',
encodec_decode: 'fp32',
},
device: 'wasm',
});
}
else{
return MusicgenForConditionalGeneration.from_pretrained('Xenova/musicgen-small', {
progress_callback: (progress_data) => {
//console.log("MUSICGEN WORKER: model download progress_callback: progress_data: ", progress_data);
if (progress_data.status !== 'progress') return;
//setLoadProgress(prev => ({ ...prev, [data.file]: data }))
///setLoadProgress(data);
self.postMessage(progress_data);
},
dtype: {
text_encoder: 'q8',
decoder_model_merged: 'q8',
encodec_decode: 'fp32',
},
device: 'webgpu',
});
}
})
.then((model) => {
//console.log("MUSICGEN WORKER: created model: ", model);
self.model = model;
do_musicgen(sentence);
})
.catch((err) => {
console.error("MUSICGEN_WORKER: caught error creating tokenizer: ", err);
reject({"status":"error", "error":"Caught error creating MusicGen tokenizer or model: " + err, "task": message.task});
self.busy_generating = false;
self.task = null;
return err
})
}
else{
do_musicgen(sentence);
}
}
else{
//console.log("MUSICGEN WORKER: PROMPT TO GENERATE MUSIC FROM NOT LONG ENOUGH OR INVALID: ", sentence);
//postMessage({"error":"Invalid sentence provided",'task': message.task});
reject({"error":"Invalid sentence provided","task": message.task});
self.busy_generating = false;
self.task = null;
}
}
else{
console.error("MUSICGEN WORKER: no valid task provided");
//postMessage({"error":"No valid task object provided"});
reject({"error":"No valid task object provided"});
self.busy_generating = false;
self.task = null;
}
});
}
catch(err){
console.error("CAUGHT GENERAL MUSICGEN WORKER ERROR:", err);
self.busy_generating = false;
self.task = null;
}
});
// Listen for messages from the main thread
self.addEventListener('message', async (e) => {
const { action } = e.data;
console.log("musicgen_worker: received non-promise-worker message: ", e.data);
switch (action) {
/*
case 'load':
load();
break;
case 'generate':
stopping_criteria.reset();
generate(data);
break;
*/
case 'interrupt':
//console.log("musicgen_worker: doing stopping_criteria.interrupt");
stopping_criteria.interrupt();
postMessage({'task':self.task,'action':'interrupt'});
self.task = null;
break;
case 'stop':
stopping_criteria.reset();
if(self.model != null){
//console.log("musicgen worker: disposing of model");
await self.model.dispose();
}
postMessage({'task':self.task,'action':'stop'});
self.task = null;
break;
}
});
async function check_gpu(){
// CHECK WEB GPU SUPPORT
if (!navigator.gpu) {
//console.error("MUSICGEN WORKER: WebGPU not supported.");
}
else{
//console.error("MUSICGEN WORKER: navigator.gpu exists: ", navigator.gpu);
const adapter = await navigator.gpu.requestAdapter();
console.error("MUSICGEN WORKER: adapter,adapter.features: ", adapter, adapter.features);
if (typeof adapter != 'undefined' && adapter != null && typeof adapter.features != 'undefined') {
if(adapter.features.has("shader-f16")){
//web_gpu_supported = true;
self.supports_web_gpu16 = true;
if (navigator.gpu.wgslLanguageFeatures && !navigator.gpu.wgslLanguageFeatures.has("packed_4x8_integer_dot_product")) {
//console.log(`MUSICGEN WORKER: webgpu DP4a built-in functions are not available`);
}
}
else{
console.warn("MUSICGEN WORKER: Web GPU: 16-bit floating-point value support is not available");
//web_gpu32_supported = true;
self.supports_web_gpu32 = true;
}
}
else{
console.error("MUSICGEN WORKER: querying WebGPU was not a success");
}
}
}
//await check_gpu();
console.error("MUSICGEN WORKER: self.supports_web_gpu16, self.supports_web_gpu32: ", self.supports_web_gpu16, self.supports_web_gpu32);
if(self.supports_web_gpu16 || self.supports_web_gpu32){
//console.log("MUSICGEN WORKER: WEBGPU SUPPORTED");
self.device = 'webgpu';
}