-
Notifications
You must be signed in to change notification settings - Fork 21
/
t2i_worker.js
1510 lines (1202 loc) · 42.6 KB
/
t2i_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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AutoTokenizer,
env
} from "./tjs/transformers.min.js";
import { orta } from './i2t/ort.webgpu.min.js';
//const { ort } = await import('./i2t/ort.webgpu.min.js');
//console.log("orta: ", orta);
let ort = orta();
//console.log("ort: ", ort);
if(typeof env.backends != 'undefined'){
//console.log("env: ", env);
//console.log("env.backends: ", env.backends);
//console.log("env.backends.onnx: ", env.backends.onnx);
}
//env.backends.onnx.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/';
env.backends.onnx.wasm.wasmPaths = 'https://huggingface.co/BoscoTheDog/onnx_diffusion/resolve/main/';
// https://cdn.jsdelivr.net/npm/[email protected]/dist/ort-wasm-simd.jsep.wasm
env.allowLocalModels = false;
env.allowRemoteModels = true;
env.useBrowserCache = true;
env.backends.onnx.wasm.proxy = false;
self.device = 'webgpu';
self.supports_web_gpu16 = false;
self.supports_web_gpu32 = false;
self.task = null;
self.interrupted = false;
self.models_loaded = false;
self.busy_loading = false;
self.busy_preloading = false;
self.busy_running = false;
self.models_initialized = false;
let web_gpu_supported = false;
let web_gpu32_supported = false;
async function check_gpu() {
// CHECK WEB GPU SUPPORT
if (!navigator.gpu) {
console.error("TEXT_TO_IMAGE WORKER: WebGPU not supported!");
}
else {
//console.error("TEXT_TO_IMAGE WORKER: navigator.gpu exists: ", navigator.gpu);
const adapter = await navigator.gpu.requestAdapter();
//console.error("TEXT_TO_IMAGE 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(`TEXT_TO_IMAGE WORKER: webgpu DP4a built-in functions are not available`);
}
}
else {
console.warn("TEXT_TO_IMAGE WORKER: Web GPU: 16-bit floating-point value support is not available");
web_gpu32_supported = true;
self.supports_web_gpu32 = true;
}
}
else {
console.error("TEXT_TO_IMAGE WORKER: querying WebGPU was not a success");
}
}
if (self.supports_web_gpu16 == false && self.supports_web_gpu32 == false) {
//console.log("TEXT TO IMAGE WORKER: NO WEB GPU SUPPORT");
self.device = 'wasm';
env.backends.onnx.wasm.proxy = true;
}
}
await check_gpu();
//console.error("TEXT_TO_IMAGE WORKER: web_gpu_supported, web_gpu32_supported: ", web_gpu_supported, web_gpu32_supported);
if (self.device == "webgpu") {
env.backends.onnx.wasm.numThreads = 1;
env.backends.onnx.wasm.simd = true;
} else {
//ort.env.wasm.numThreads = config.threads;
env.backends.onnx.wasm.simd = true;
}
let opfs_supported = false;
try{
if(typeof navigator.storage != 'undefined' && typeof navigator.storage.getDirectory != 'undefined'){
const opfsRoot = await navigator.storage.getDirectory();
//console.log("TEXT TO IMAGE WORKER: OPFS storage seems supported. opfsRoot: ", opfsRoot);
opfs_supported = true;
}
}
catch(err){
console.error("TEXT TO IMAGE WORKER: caught error testing OPFS file storage: ", err);
}
self.current_huggingface_id = null;
// PROMISE WORKER
/*
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) {
if (typeof self.postMessage !== 'function') { // service worker
e.ports[0].postMessage(msg)
} else { // web worker
self.postMessage(msg)
}
}
if (error) {
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);
}
postMessage([messageId, {
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)
}
registerPromiseWorker(function(message) {
//console.log("TEXT TO IMAGE WORKER: registerPromiseWorker: GOT MESSAGE: \n", typeof message, message);
if (typeof message.action == 'string') {
//console.log("TEXT TO IMAGE WORKER: registerPromiseWorker: GOT ACTION: ", message.action);
}
if (typeof message.task == 'undefined') {
console.error("TEXT TO IMAGE PROMISE WORKER: message.task was undefined");
if (message.length && typeof message[0].task != 'undefined') {
message = message[1];
} else if (message.length > 1) {
if (typeof message[1].task != 'undefined') {
//message = message[1];
//console.log("TEXT TO IMAGE WORKER: calling run from (weird) promise-worker message");
self.task = message[1].task;
return run(self.task);
}
} else {
console.error("trying to locate task object in incoming message failed");
}
}
if (typeof message.task != 'undefined' && message.task != null && typeof message.task.type == 'string') {
//console.log("TEXT TO IMAGE WORKER: received a task: ", message.task.type, message.task);
if (message.task.type == 'text_to_image' && typeof message.task.prompt == 'string') {
//console.log("TEXT TO IMAGE WORKER: calling run from promise-worker message");
self.task = message.task;
return run(self.task);
}
}
console.error("TEXT TO IMAGE WORKER: no valid task provided");
return {
"status":"error",
"message": "No valid task object provided"
};
});
*/
function dispose_everything(){
if(textEncoderOutputsTensor && typeof textEncoderOutputsTensor.dispose == 'function'){
textEncoderOutputsTensor.dispose();
}
if(unetSampleInputsTensor && typeof unetSampleInputsTensor.dispose == 'function'){
unetSampleInputsTensor.dispose();
}
if(unetOutSampleTensor && typeof unetOutSampleTensor.dispose == 'function'){
unetOutSampleTensor.dispose();
}
if(decodedOutputsTensor && typeof decodedOutputsTensor.dispose == 'function'){
decodedOutputsTensor.dispose();
}
if(tokenizer && typeof tokenizer.dispose == 'function'){
tokenizer.dispose();
}
}
// old-school non-promise option
addEventListener('message', async (event) => {
//console.log("TEXT TO IMAGE WORKER: RECEIVED MESSAGE. event.data: ", event.data);
if(typeof event.data.action == 'string' && (event.data.action == 'interrupt' || event.data.action == 'stop' || event.data.action == 'dispose')){
if(event.data.action == 'interrupt'){
self.interrupted = true;
}
else if(event.data.action == 'stop' || event.data.action == 'dispose'){
dispose_everything();
}
self.task = null;
}
if(typeof event.data.task != 'undefined' && event.data.task != null){
//console.log("TEXT TO IMAGE WORKER: calling run from non-promise message");
self.interrupted = false;
self.task = event.data.task;
return do_run(self.task);
}
});
/*
* This file is modified based on
* https://github.com/guschmue/ort-webgpu/blob/master/sd-turbo/index.html
*/
/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
// import { ALL_NEEDED_MODEL_RESOURCES } from "./config.js";
const ALL_NEEDED_MODEL_RESOURCES = {
// summarization
"distilbart-cnn-6-6": {
linkPathPrefix: "https://huggingface.co/Xenova/distilbart-cnn-6-6/resolve/main/",
localFolderPathPrefix: "Xenova/",
resources: [
"onnx/decoder_model_merged_quantized.onnx",
"onnx/encoder_model_quantized.onnx"
]
},
// image-to-text
"vit-gpt2-image-captioning": {
linkPathPrefix: "https://huggingface.co/Xenova/vit-gpt2-image-captioning/resolve/main/",
localFolderPathPrefix: "Xenova/",
resources: [
"onnx/decoder_model_merged_quantized.onnx",
"onnx/encoder_model_quantized.onnx"
]
},
// question-answering
"distilbert-base-cased-distilled-squad": {
linkPathPrefix: "https://huggingface.co/Xenova/distilbert-base-cased-distilled-squad/resolve/main/",
localFolderPathPrefix: "Xenova/",
resources: ["onnx/model_quantized.onnx"]
},
// background-removal
"RMBG-1.4": {
linkPathPrefix: "https://huggingface.co/briaai/RMBG-1.4/resolve/main/",
localFolderPathPrefix: "briaai/",
resources: ["onnx/model.onnx"]
},
// SD-Turbo
"sd-turbo-ort-web": {
linkPathPrefix: "https://huggingface.co/schmuell/sd-turbo-ort-web/resolve/main/",
localFolderPathPrefix: "schmuell/",
resources: [
"unet/model.onnx",
"vae_decoder/model.onnx",
"text_encoder/model.onnx"
]
},
// used by SD-Turbo
"clip-vit-base-patch16": {
linkPathPrefix: "https://huggingface.co/Xenova/clip-vit-base-patch16/resolve/main/",
localFolderPathPrefix: "Xenova/",
resources: []
},
"Phi-3-mini-4k-instruct": {
linkPathPrefix: "https://huggingface.co/Xenova/Phi-3-mini-4k-instruct/resolve/main/",
localFolderPathPrefix: "Xenova/",
resources: ["onnx/model_q4.onnx", "onnx/model_q4.onnx_data"]
},
"Phi-3-mini-4k-instruct_fp16": {
linkPathPrefix: "https://huggingface.co/Xenova/Phi-3-mini-4k-instruct_fp16/resolve/main/",
localFolderPathPrefix: "Xenova/",
resources: ["onnx/model_q4.onnx", "onnx/model_q4.onnx_data"]
},
// ort web wasm
"ort-web@1_18_0": {
linkPathPrefix: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
localFolderPathPrefix: "frameworks/ort-web/",
resources: ["ort-wasm-simd.jsep.wasm"]
},
"ort-web@1_17_1": {
linkPathPrefix: "https://cdn.jsdelivr.net/npm/[email protected]/dist/",
localFolderPathPrefix: "frameworks/ort-web/",
resources: ["ort-wasm-simd.jsep.wasm"]
},
// mediapipe
"tasks-genai": {
linkPathPrefix: "https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm/",
localFolderPathPrefix: "frameworks/mediapipe/",
resources: ["genai_wasm_internal.wasm"]
}
};
var deviceWebgpu = null;
var queueWebgpu = null;
var textEncoderOutputsBuffer = null;
var textEncoderOutputsTensor = null;
var textEncoderOutputs = {};
var latentData = null;
var latentBuffer = null;
var unetSampleInputsBuffer = null;
var unetSampleInputsTensor = null;
var unetOutSampleBuffer = null;
var unetOutSampleTensor = null;
var prescaleLatentSpacePipeline = null;
var prescaleLatentSpaceBindGroup = null;
var stepLatentSpacePipeline = null;
var stepLatentSpaceBindGroup = null;
var decodedOutputsBuffer = null;
var decodedOutputsTensor = null;
const pixelHeight = 512;
const pixelWidth = 512;
var renderContext = null;
var renderPipeline = null;
var renderBindGroup = null;
const canvas = new OffscreenCanvas(512, 512); //document.getElementById(`canvas`);
canvas.width = pixelWidth;
canvas.height = pixelHeight;
const PRESCALE_LATENT_SPACE_SHADER = `
@binding(0) @group(0) var<storage, read_write> result: array<vec4<f32>>;
@binding(1) @group(0) var<storage, read> latentData: array<vec4<f32>>;
@compute @workgroup_size(128, 1, 1)
fn _start(@builtin(global_invocation_id) GlobalId : vec3<u32>) {
let index = GlobalId.x;
let value = latentData[index] / 14.64877241136608;
result[index] = value;
}
`;
const STEP_LATENT_SPACE_SHADER = `
@binding(0) @group(0) var<storage, read_write> result: array<vec4<f32>>;
@binding(1) @group(0) var<storage, read> latentData: array<vec4<f32>>;
@compute @workgroup_size(128, 1, 1)
fn _start(@builtin(global_invocation_id) GlobalId : vec3<u32>) {
let index = GlobalId.x;
let sigma_hat = 14.6146;
let latentVal = latentData[index];
let outputSampleVal = result[index];
let pred_original_sample = latentVal - 14.6146 * outputSampleVal;
let derivative = (latentVal - pred_original_sample) / 14.6146;
let dt = -14.6146;
result[index] = (latentVal + derivative * dt) / 0.18215;
}
`;
const VERTEX_SHADER = `
struct VertexOutput {
@builtin(position) Position : vec4<f32>,
@location(0) fragUV : vec2<f32>,
}
@vertex
fn main(@builtin(vertex_index) VertexIndex : u32) -> VertexOutput {
var pos = array<vec2<f32>, 6>(
vec2<f32>( 1.0, 1.0),
vec2<f32>( 1.0, -1.0),
vec2<f32>(-1.0, -1.0),
vec2<f32>( 1.0, 1.0),
vec2<f32>(-1.0, -1.0),
vec2<f32>(-1.0, 1.0)
);
var uv = array<vec2<f32>, 6>(
vec2<f32>(1.0, 0.0),
vec2<f32>(1.0, 1.0),
vec2<f32>(0.0, 1.0),
vec2<f32>(1.0, 0.0),
vec2<f32>(0.0, 1.0),
vec2<f32>(0.0, 0.0)
);
var output : VertexOutput;
output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);
output.fragUV = uv[VertexIndex];
return output;
}
`;
const PIXEL_SHADER = `
@group(0) @binding(1) var<storage, read> buf : array<f32>;
@fragment
fn main(@location(0) fragUV : vec2<f32>) -> @location(0) vec4<f32> {
// The user-facing camera is mirrored, flip horizontally.
var coord = vec2(0.0, 0.0);
if (fragUV.x < 0.5) {
coord = vec2(fragUV.x + 0.5, fragUV.y);
} else {
coord = vec2(fragUV.x - 0.5, fragUV.y);
}
let redInputOffset = 0;
let greenInputOffset = 262144;
let blueInputOffset = 524288;
let index = i32(coord.x * f32(512)) + i32(coord.y * f32(512) * f32(512)); // pixelWidth = pixelHeight= 512
let r = clamp(buf[index] / 2 + 0.5, 0.0, 1.0);
let g = clamp(buf[262144 + index] / 2 + 0.5, 0.0, 1.0);
let b = clamp(buf[524288 + index] / 2 + 0.5, 0.0, 1.0);
let a = 1.0;
var out_color = vec4<f32>(r, g, b, a);
return out_color;
}
`;
const modelName = "sd-turbo-ort-web";
const tokenizerName = "clip-vit-base-patch16";
const config = getConfig();
const models = {
unet: {
url: "unet/model.onnx",
size: 640,
// should have 'steps: 1' but will fail to create the session
opt: {
freeDimensionOverrides: {
batch_size: 1,
num_channels: 4,
height: 64,
width: 64,
sequence_length: 77
}
}
},
text_encoder: {
url: "text_encoder/model.onnx",
size: 1700,
// should have 'sequence_length: 77' but produces a bad image
opt: {
freeDimensionOverrides: {
batch_size: 1
}
}
},
vae_decoder: {
url: "vae_decoder/model.onnx",
size: 95,
opt: {
freeDimensionOverrides: {
batch_size: 1,
num_channels_latent: 4,
height_latent: 64,
width_latent: 64
}
}
}
};
let tokenizer;
let loading;
const sigma = 14.6146;
const gamma = 0;
const vae_scaling_factor = 0.18215;
let loadedCount = 0;
let fetchedModels = {};
//text.value = "Paris with the river in the background";
const STATUS = {
DEFAULT: 0,
PREPARING: 1,
RUNNING: 2,
DONE: 3
};
function getConfig() {
var config = {
model: modelName,
provider: "webgpu",
device: "gpu",
threads: 1,
images: 1
};
// Define a whitelist of allowed configuration keys
const allowedConfigKeys = new Set([
"model",
"provider",
"device",
"threads",
"images"
]);
// Parse the query string
/*
const query = window.location.search.substring(1);
const vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
let pair = vars[i].split("=");
// Check if the key is in the whitelist
if (allowedConfigKeys.has(pair[0])) {
let key = pair[0];
let value = decodeURIComponent(pair[1]);
// Additional validation for numeric values
if (key === "threads" || key === "images") {
value = parseInt(value);
if (isNaN(value) || value < 1) {
throw new Error(
`Invalid value for ${key}: must be a positive integer`
);
}
}
// Assign the validated value to the config object
config[key] = value;
} else if (pair[0].length > 0) {
throw new Error("Unknown argument: " + pair[0]);
}
}
*/
return config;
}
function randn_latents(shape, noise_sigma) {
function randn() {
// Use the Box-Muller transform
let u = Math.random();
let v = Math.random();
let z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
return z;
}
let size = 1;
shape.forEach((element) => {
size *= element;
});
let data = new Float32Array(size);
// Loop over the shape dimensions
for (let i = 0; i < size; i++) {
data[i] = randn() * noise_sigma;
}
return data;
}
let previous_download_percentage = -1;
async function fetchAndCache(name, base_url, model_path) {
//console.log("fetchAndCache: \n- name:\n", name, "\n- base_url: ", base_url, "\n- model_path: ", model_path);
//const url = `${base_url}${model_path}`;
const url = `https://huggingface.co/schmuell/sd-turbo-ort-web/resolve/main/${model_path}`;
let data = [];
//console.log("trying to fetch url: ", url);
//const statusBarElement = document.getElementById(`${name}StatusBar`);
// fetch models from origin private file system
const root = await navigator.storage.getDirectory();
//for await (let [filename, handle] of directoryHandle.entries()) {}
let fileHandle;
async function fetchFile() {
try {
//console.log("in fetchFile. url: ", url);
const response = await fetch(url);
if (response.status === 404) {
throw new Error(`${name} model not found.`);
}
const reader = response.body.getReader();
const totalLength = +response.headers.get("Content-Length");
//console.log("fetchFile: totalLength: ", totalLength);
let loaded = 0;
let chunks = [];
const startTime = new Date().getTime();
let stream = new ReadableStream({
start(controller) {
function push() {
reader.read().then(({
done,
value
}) => {
const currentTime = new Date().getTime();
const elapsedTime = (currentTime - startTime) / 1000;
if (done) {
// update status bar content when download complete
//console.log(`downloaded in ${elapsedTime}s (${formatBufferSize(totalLength)})`);
controller.close();
return;
}
loaded += value.byteLength;
let progress = Math.floor( (loaded / totalLength) * 1000);
if(progress != previous_download_percentage){
//console.log("Downloading model: ", name, progress);
previous_download_percentage = progress;
self.postMessage({
status: 'progress',
progress: (progress / 10),
file:name,
loaded:loaded,
total:totalLength,
});
}
chunks.push(value);
controller.enqueue(value);
push();
});
}
push();
}
});
let newResponse = new Response(stream);
data = await newResponse.arrayBuffer();
// save the buffer into origin private file system
fileHandle = await root.getFileHandle(name, {
create: true
});
const writable = await fileHandle.createWritable();
await writable.write(data);
await writable.close();
//console.log("stored the downloaded model in the OPFS cache");
// update status flag in model panel
return data;
} catch (err) {
console.error("caught error downloading to cache: ", err);
self.postMessage({
task: self.task,
status: "error",
message:"download error"
});
return;
}
}
try {
//console.log("attempting to load model from OPFS cache. name: ", name);
// get buffer from origin private file system
fileHandle = await root.getFileHandle(name);
const blob = await fileHandle.getFile();
const buffer = await blob.arrayBuffer();
//console.log("buffer loaded from OPFS cache: ", name, buffer);
return buffer;
} catch (err) {
console.error("no cached model found in origin private file system, fetching from origin server. Err: ", err);
// not saved in origin private file system, fetch from origin server
return await fetchFile();
}
}
function uploadToGPU(buffer, values, type) {
//console.log("Uploading data to GPU buffer ...");
const stagingBuffer = deviceWebgpu.createBuffer({
usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC,
size: values.buffer.byteLength,
mappedAtCreation: true
});
const arrayBuffer = stagingBuffer.getMappedRange();
if (type === "float32") {
new Float32Array(arrayBuffer).set(values);
} else if (type === "int32") {
new Int32Array(arrayBuffer).set(values);
}
stagingBuffer.unmap();
const encoder = deviceWebgpu.createCommandEncoder();
encoder.copyBufferToBuffer(stagingBuffer, 0, buffer, 0, values.byteLength);
deviceWebgpu.queue.submit([encoder.finish()]);
stagingBuffer.destroy();
}
function submitComputeTask(pipeline, bindGroup) {
let commandEncoderWebgpu = deviceWebgpu.createCommandEncoder();
let computePassEncoder = commandEncoderWebgpu.beginComputePass();
computePassEncoder.setPipeline(pipeline);
computePassEncoder.setBindGroup(0, bindGroup);
computePassEncoder.dispatchWorkgroups(32, 1, 1);
computePassEncoder.end();
computePassEncoder = null;
queueWebgpu.submit([commandEncoderWebgpu.finish()]);
}
async function load_models(models) {
//console.log("in load_models. models: ", models);
// NOTE: download or load models first
console.time("load_models");
for (const [name, model] of Object.entries(models)) {
//console.log("load_models: loading: ", name, model);
//const statusBarElement = document.getElementById(`${name}StatusBar`);
try {
const model_bytes = await fetchAndCache(name, config.model, model.url);
fetchedModels[name] = model_bytes;
} catch (err) {
console.error("caught error in load_models: ", err);
self.postMessage({
task: self.task,
status: "error",
message:"load_models failed"
});
}
if(self.interrupted){
return
}
}
console.timeEnd("load_models");
//console.log("loaded models: ", Object.keys(fetchedModels));
if (Object.keys(fetchedModels).length !== Object.keys(models).length) {
console.error("TEXT TO IMAGE WORKER: failed to load all models");
postMessage({
'task': self.task,
'action': 'error',
'message': 'Download_failed'
});
self.models_loaded = false;
}
else {
//console.log("TEXT TO IMAGE WORKER: MODELS LOADED SUCCESFULLY");
postMessage({
'task': self.task,
'action': 'download_complete'
});
self.models_loaded = true;
}
}
const opt = {
executionProviders: [config.provider],
enableMemPattern: false,
enableCpuMemArena: false,
extra: {
session: {
disable_prepacking: "1",
use_device_allocator_for_initializers: "1",
use_ort_model_bytes_directly: "1",
use_ort_model_bytes_for_initializers: "1"
}
}
};
switch (config.provider) {
case "webgpu":
if (!("gpu" in navigator)) {
throw new Error("webgpu is NOT supported");
}
opt.preferredOutputLocation = {
last_hidden_state: "gpu-buffer"
};
break;
case "webnn":
if (!("ml" in navigator)) {
throw new Error("webnn is NOT supported");
}
opt.executionProviders = [{
name: "webnn",
deviceType: config.device,
powerPreference: "default"
}];
break;
}
/*
const imagePrompts = [
"Paris with the river in the background",
"A serene sunset over a calm ocean",
"A bustling cityscape at night",
"A tranquil forest with a flowing river",
"A snowy mountain peak under a clear blue sky",
"A medieval castle surrounded by a moat",
"A futuristic city with flying cars",
"A desert oasis with palm trees and a camel",
"A tropical beach with crystal clear water",
"A group of penguins on an ice floe",
"A cherry blossom tree in full bloom",
"A Victorian mansion at dusk",
"A field of sunflowers under a sunny sky",
"A cozy cabin in a winter landscape",
"A bustling farmer's market with fresh produce",
"A coral reef teeming with marine life",
"A vineyard in the rolling hills of Tuscany",
"A lighthouse on a cliff overlooking the sea",
"A hot air balloon festival at sunrise",
"A tranquil Japanese garden with a koi pond",
"A space station orbiting a distant planet",
"Impressionist oil painting of a beach at sunset with a narrow aspect ratio",
"A photograph of a city skyline in the style of Edward Hopper taken from an aerial viewpoint",
"A 3D rendering of a cat sitting on a windowsill in minimalist style with high resolution",
"Graffiti-style painting of a city street with an urban look and textured surfaces",
"A sketch of a pirate ship in black-and-white with realistic textures and low resolution",
"A chalk drawing of a family picnic being attacked by ants in Central Park with a surrealist style",
"A watercolor painting of a coffee shop with surreal elements in vibrant colors",
"An oil painting of a rainbow over a rural abandoned town with classic style",
"A 3D rendering of a spaceship taking off into space with a cyberpunk look and wide aspect ratio",
"A sketch of two cats sitting on a sofa watching TV while eating spaghetti"
];
*/
async function do_run(task, initFlag=false){
//console.log("TEXT TO IMAGE WORKER: in do_run. task: ", task);
if(typeof task != 'undefined' && task != null && typeof task.prompt == 'string'){
if(self.busy_running == false && self.busy_loading == false){
if(self.models_loaded == false){
if(self.busy_loading == true){
self.postMessage({
task: task,
status: "error",
message: "already busy loading models",
});
return false
}
else{
//console.log("do_run: calling load_models first");
if(self.interrupted){
return false