-
Notifications
You must be signed in to change notification settings - Fork 21
/
image_to_text_worker.js
924 lines (681 loc) · 25.9 KB
/
image_to_text_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
//import { pipeline } from './tjs/transformers.js';
//import { env, Tensor, AutoTokenizer, SpeechT5ForTextToSpeech, SpeechT5HifiGan } from '@xenova/transformers';
//import { env, Tensor, AutoTokenizer, SpeechT5ForTextToSpeech, SpeechT5HifiGan } from './tjs/transformers.js';
//console.log("HELLO FROM IMAGE TO TEXT WORKER");
// Great example: https://github.com/xenova/transformers.js/blob/046b292ac50a0de594d9916bbe2f9b1ffcbbd752/examples/webgpu-vlm/src/worker.js
import { AutoProcessor, AutoTokenizer, Moondream1ForConditionalGeneration, LlavaForConditionalGeneration, Florence2ForConditionalGeneration, TextStreamer, StoppingCriteria, RawImage, env } from './tjs/transformers.min.js';
/*
import {
Florence2ForConditionalGeneration,
AutoProcessor,
AutoTokenizer,
RawImage,
TextStreamer,
StoppingCriteria,
env
} from '@xenova/transformers';
*/
// Tensor
// full
const MAX_NEW_TOKENS = 256;
env.allowLocalModels = false;
env.allowRemoteModels = true;
env.useBrowserCache = true;
self.device = 'webgpu';
let gpu_checked = false;
self.supports_web_gpu16 = false;
self.supports_web_gpu32 = false;
self.current_huggingface_id = null;
self.output_so_far = '';
self.task = null;
self.busy = false;
// Load processor, tokenizer and model
self.processor = null;
self.tokenizer = null;
self.model = null;
let web_gpu_supported = false;
let web_gpu32_supported = false;
function delay(millisec) {
return new Promise(resolve => {
setTimeout(() => { resolve('') }, millisec);
})
}
async function hasFp16() {
try {
const adapter = await navigator.gpu.requestAdapter();
console.error("IMAGE_TO_TEXT WORKER: GPU adapter: ", adapter);
if (typeof adapter != 'undefined' && adapter != null && typeof adapter.features != 'undefined') {
self.supports_web_gpu32 = true;
self.device = 'webgpu';
}
return adapter.features.has('shader-f16');
} catch (err) {
console.error("IMAGE_TO_TEXT WORKER: caught error trying to determine GPU support: ", err);
return false;
}
}
self.supports_web_gpu16 ??= await hasFp16();
//const MAX_NEW_TOKENS = 256;
//console.log("env.backends.onnx.wasm.proxy before: ", env.backends.onnx.wasm.proxy);
env.backends.onnx.wasm.proxy = self.device !== 'webgpu';
//console.log("env.backends.onnx.wasm.proxy after: ", env.backends.onnx.wasm.proxy);
class TextGenerationPipeline {
static huggingface_id = 'Xenova/moondream2';
static tokenizer = null;
static processor = null;
static model = null;
static supportsFp16 = null;
static instance_exists(){
//console.log("returning if instance exists");
return this.model != null;
}
static set_to_null(var_to_null=null) {
if(typeof var_to_null == 'string' && typeof this[var_to_null] != 'undefined'){
this[var_to_null] = null;
//console.log("WHISPER WORKER: ASR PipelineFactory: set_to_null: ", var_to_null);
}
}
static async getInstance(progress_callback = null, huggingface_id='Xenova/moondream2') {
this.huggingface_id = huggingface_id;
this.tokenizer ??= AutoTokenizer.from_pretrained(this.huggingface_id, {
progress_callback,
});
this.processor ??= AutoProcessor.from_pretrained(this.huggingface_id);
// Choose the model based on whether fp16 is available
this.supportsFp16 ??= await hasFp16();
/*
this.model ??= Moondream1ForConditionalGeneration.from_pretrained(this.huggingface_id, {
dtype: {
embed_tokens: this.supportsFp16 ? 'fp16' : 'fp32', // or 'fp32'
vision_encoder: this.supportsFp16 ? 'fp16' : 'fp32', // or 'q8'
decoder_model_merged: 'q4', // or 'q4f16' or 'q8'
},
device: DEVICE,
progress_callback,
});
*/
if(this.model == null ){ // && huggingface_id.indexOf('moondream') != -1
let dtype_settings = {
embed_tokens: self.supports_web_gpu16 ? 'fp16' : 'fp32', // or 'fp32'
vision_encoder: self.supports_web_gpu16 ? 'fp16' : 'fp32', // or 'q8'
decoder_model_merged: 'q4', // or 'q4f16' or 'q8'
/*
embed_tokens: 'fp16', // or 'fp32'
vision_encoder: 'fp16', // or 'q8'
decoder_model_merged: 'q4', // or 'q4f16' or 'q8'
*/
}
//console.log("IMAGE TO TEXT WORKER: dtype_settings: ", JSON.stringify(dtype_settings,null,4));
//console.log("IMAGE TO TEXT WORKER: LOADING huggingface_id: ", huggingface_id);
if(huggingface_id.indexOf('nanoLLaVA') != -1){
//self.model = await Moondream1ForConditionalGeneration.from_pretrained(huggingface_id, {
//console.log("IMAGE TO TEXT WORKER: self.device,dtype_settings: ", self.device, JSON.stringify(dtype_settings,null,4));
this.model = LlavaForConditionalGeneration.from_pretrained(this.huggingface_id, {
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT 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: dtype_settings,
//quantized:true,
device: self.device,
});
}
else if(huggingface_id.indexOf('moondream') != -1){
//console.log("IMAGE TO TEXT WORKER: moondream. self.device,dtype_settings: ", self.device, JSON.stringify(dtype_settings,null,4));
this.model = Moondream1ForConditionalGeneration.from_pretrained(this.huggingface_id, {
//self.model = await LlavaForConditionalGeneration.from_pretrained(huggingface_id, {
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT 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: dtype_settings,
quantized: true,
device: self.device,
//device: 'wasm',
});
}
else{
//console.log("IMAGE TO TEXT WORKER: using Florence. self.device: ", self.devicef);
this.model = await Florence2ForConditionalGeneration.from_pretrained(this.huggingface_id, {
//dtype: 'fp32',
dtype: {
embed_tokens: 'fp16',
vision_encoder: 'fp32',
encoder_model: 'fp16',
decoder_model_merged: 'q8', // q4
},
//quantized:true,
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT WORKER: Florence 2 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);
},
//device: 'wasm',
});
}
}
return Promise.all([this.tokenizer, this.processor, this.model]);
}
}
class CallbackTextStreamer extends TextStreamer {
constructor(tokenizer, cb) {
super(tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
});
this.cb = cb;
}
on_finalized_text(text) {
this.cb(text);
}
}
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();
/*
async function generate(messages) {
// Only support a single image for now
const images = messages.filter(x => x.image).map(x => x.image);
if (images.length > 1) {
self.postMessage({
status: 'error',
error: 'Currently, at most one image is supported.',
});
return;
}
// Retrieve the text-generation pipeline.
const [tokenizer, processor, model] = await TextGenerationPipeline.getInstance();
// Construct and tokenize prompt
const prompt = messages.map(x => `${x.image ? '<image>\n\n' : ''}${x.role === 'user' ? 'Question: ' : 'Answer: '}${x.content.trim()}`).join('\n\n') + '\n\nAnswer:'
let inputs = tokenizer(prompt);
if (images.length > 0) {
const image = await RawImage.fromURL(images[0]);
const vision_inputs = await processor(image);
inputs = { ...inputs, ...vision_inputs };
}
let startTime;
let numTokens = 0;
const cb = (output) => {
startTime ??= performance.now();
let tps;
if (numTokens++ > 0) {
tps = numTokens / (performance.now() - startTime) * 1000;
}
self.postMessage({
status: 'update',
output, tps, numTokens,
});
}
const streamer = new CallbackTextStreamer(tokenizer, cb);
// Tell the main thread we are starting
self.postMessage({ status: 'start' });
const outputs = await model.generate({
...inputs,
max_new_tokens: MAX_NEW_TOKENS,
streamer,
stopping_criteria,
});
const outputText = tokenizer.batch_decode(outputs, { skip_special_tokens: false });
// Send the output back to the main thread
self.postMessage({
status: 'complete',
output: outputText,
});
}
async function load() {
self.postMessage({
status: 'loading',
data: 'Loading model...'
});
// Load the pipeline and save it for future use.
const [tokenizer, processor, model] = await TextGenerationPipeline.getInstance(x => {
// We also add a progress callback to the pipeline so that we can
// track model loading.
self.postMessage(x);
});
self.postMessage({
status: 'loading',
data: 'Compiling shaders and warming up model...'
});
// Run model with dummy input to compile shaders
const text_inputs = tokenizer('a');
const vision_inputs = {
pixel_values: full([1, 3, 378, 378], 0.0)
}
const inputs = { ...text_inputs, ...vision_inputs };
await model.generate({ ...inputs, max_new_tokens: 1 });
self.postMessage({ status: 'ready' });
}
*/
// Listen for messages from the main thread
self.addEventListener('message', async (e) => {
//console.log("IMAGE_TO_TEXT_WORKER: received message: ", e.data);
if(typeof e.data.action == 'string'){
//console.log("IMAGE_TO_TEXT_WORKER: received non-prommise message: action: ", action);
switch (e.data.action) {
case 'interrupt':
stopping_criteria.interrupt();
postMessage({'task':self.task,'output_so_far':self.output_so_far,'action':'interrupt'});
self.output_so_far = '';
break;
case 'dispose':
stopping_criteria.reset();
if(self.model){
await self.model.dispose();
}
else if(TextGenerationPipeline.instance_exists() === true){
//console.log("image_to_text worker: disposing of model");
//await self.model.dispose();
await dispose();
}
//postMessage({'task':self.task,'output_so_far':self.output_so_far,'action':'reset'});
postMessage({'status':'disposed'});
self.output_so_far = '';
break;
}
}
else if(typeof e.data.task != 'undefined' && e.data.task != null){
stopping_criteria.reset();
const decoded = await image_to_text(e.data.task);
self.postMessage({
task: e.data.task,
status: "complete",
result: decoded,
});
}
else{
self.postMessage({
status: 'error',
error: 'No action or task provided',
});
}
});
/*
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();
}
}
*/
const cb = (chunk) => {
self.output_so_far += chunk;
self.postMessage({
status: 'update',
output_so_far,
chunk,
});
}
// not used
async function check_gpu(){
// CHECK WEB GPU SUPPORT
if (!navigator.gpu) {
console.error("IMAGE_TO_TEXT WORKER: WebGPU not supported.");
}
else{
//console.error("IMAGE_TO_TEXT WORKER: navigator.gpu exists: ", navigator.gpu);
const adapter = await navigator.gpu.requestAdapter();
//console.error("IMAGE_TO_TEXT 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(`IMAGE_TO_TEXT WORKER: webgpu DP4a built-in functions are not available`);
}
}
else{
console.warn("IMAGE_TO_TEXT WORKER: Web GPU: 16-bit floating-point value support is not available");
web_gpu32_supported = true;
self.supports_web_gpu32 = true;
}
}
else{
console.error("IMAGE_TO_TEXT WORKER: querying WebGPU failed");
}
}
if(self.supports_web_gpu16 == false && self.supports_web_gpu32 == false){
//console.log("IMAGE TO TEXT WORKER: NO WEB GPU SUPPORT");
self.device = 'wasm';
}
}
//await check_gpu();
//console.error("IMAGE_TO_TEXT WORKER: web_gpu_supported, web_gpu32_supported: ", web_gpu_supported ,web_gpu32_supported);
async function image_to_text(task=null){
//console.log("IMAGE TO TEXT WORKER: in image_to_text. task: ",task);
try{
if(task == null || typeof task.prompt != 'string' || typeof task.image_blob == 'undefined' || typeof task.type != 'string'){
console.error("IMAGE TO TEXT WORKER: image_to_text: missing inputs (prompt,image_blog,type). task: ", task);
self.postMessage({
'task':task,
'status':'error',
'error':'invalid input provided',
});
return null
}
if(self.busy){
console.error("IMAGE TO TEXT WORKER: image_to_text: was already busy. Aborting image_to_text");
self.postMessage({
'task':task,
'status':'error',
'error':'was already busy',
});
return false
}
self.busy = true;
if(gpu_checked == false){
gpu_checked = true;
await check_gpu();
}
//console.log("self.device: ", self.device)
//console.log("env.backends.onnx.wasm.proxy before: ", env.backends.onnx.wasm.proxy);
env.backends.onnx.wasm.proxy = self.device !== 'webgpu';
//console.log("env.backends.onnx.wasm.proxy after: ", env.backends.onnx.wasm.proxy);
//await preload_image_to_text(task.huggingface_id);
/*
self.postMessage({
'task':task,
'status':'preloaded'
});
*/
let huggingface_id = 'Xenova/moondream2';
if(typeof task.huggingface_id == 'string'){
huggingface_id = task.huggingface_id;
}
if(typeof self.current_huggingface_id == 'string' && self.current_huggingface_id != huggingface_id){
console.warn("IMAGE TO TEXT WORKER: SWITCHING TO DIFFERENT MODEL: ", self.current_huggingface_id, " -> ", huggingface_id);
//await dispose();
self.processor = null;
self.tokenizer = null;
if(self.model != null){
//console.log("IMAGE TO TEXT WORKER: Disposing of old model first");
await self.model.dispose();
}
self.model = null;
}
await preload_image_to_text(huggingface_id);
await delay(10);
self.postMessage({
'task':task,
'status':'preloaded'
});
self.current_huggingface_id = huggingface_id;
/*
const [processor,tokenizer,model] = await TextGenerationPipeline.getInstance(x => {
self.postMessage(x);
},self.current_huggingface_id);
//console.log("typeof model: ", typeof model);
*/
const image = await RawImage.fromBlob(task.image_blob);
const vision_inputs = await self.processor(image);
const streamer = new CallbackTextStreamer(tokenizer, cb);
self.output_so_far = '';
let prompt = 'Describe this image.';
if(typeof task.prompt == 'string'){
prompt = task.prompt;
}
// Prepare prompt text inputs
let text = 'Describe with a paragraph what is shown in the image.';
//let text = `<image>\n\nQuestion: ${prompt}\n\nAnswer:`;
if(self.current_huggingface_id.indexOf('nanoLLaVA') != -1){
//console.log("IMAGE TO TEXT WORKER: Applying nanoLlava template");
const messages = [
{ role: 'system', content: 'Answer the question.' },
{ role: 'user', content: `<image>\n${prompt}` }
]
text = self.tokenizer.apply_chat_template(messages, { tokenize: false, add_generation_prompt: true });
}
else if(self.current_huggingface_id.indexOf('moondream') != -1){
//console.log("IMAGE TO TEXT WORKER: Using Moondream template");
text = `<image>\n\nQuestion: ${prompt}\n\nAnswer:`;
}
else{
//console.log("IMAGE TO TEXT WORKER: Using Florence template");
// Florence
text = prompt;
}
//console.log("IMAGE TO TEXT WORKER: input prompt text: ", text);
const text_inputs = self.tokenizer(text);
// Prepare vision inputs
//const url = 'https://huggingface.co/vikhyatk/moondream1/resolve/main/assets/demo-1.jpg';
/*
const streamer = new CallbackStreamer((value) => {
//console.log("IMAGE TO TEXT WORKER: in callback streamer. value: ", value);
//const percent = value === undefined ? 1 : value[0].length / max_length;
//console.log("MUSICGEN WORKER: streamer: percent: ", percent);
self.postMessage({
'task':message.task,
'status':'musicgen_progress',
'progress':percent
});
//setStatusText(`Generating (${(percent * 100).toFixed()}%)...`);
//setProgress(percent * 100);
});
function progressCallback(x){
//console.log("image_to_text worker: progressCallback: ", x);
self.postMessage(x);
}
*/
let generate_this = {
...text_inputs,
...vision_inputs,
//do_sample: false,
max_new_tokens: 1000,
streamer,
stopping_criteria,
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT WORKER: model generate progress_callback: progress_data: ", progress_data);
//if (progress_data.status !== 'progress') return;
//setLoadProgress(prev => ({ ...prev, [data.file]: data }))
///setLoadProgress(data);
self.postMessage(progress_data);
},
}
if(self.current_huggingface_id.indexOf('lorence') == -1){
generate_this['do_sample'] = false;
//generate_this['streamer'] = streamer;
//generate_this['stopping_criteria'] = stopping_criteria;
//generate_this['max_new_tokens'] = 1000;
}
//console.log("image_to_text worker: calling self.model.generate with: ", generate_this);
// Generate response
const output = await model.generate(generate_this);
//console.log("image_to_text worker: OK, got output from the model");
let decoded = null;
// NanoLlava
if(self.current_huggingface_id.indexOf('nanoLLaVA') != -1){
decoded = self.tokenizer.decode( // TODO should there be await here?
output.slice(0, [text_inputs.input_ids.dims[1], null]),
{ skip_special_tokens: true },
);
}
// Moondream 2 and Florence 2
else{
//console.log("decoding output for moondream or florence");
decoded = self.tokenizer.batch_decode(output, { skip_special_tokens: true }); // TODO should there be await here?
}
//console.log("IMAGE TO TEXT WORKER: self.current_huggingface_id,decoded: ", self.current_huggingface_id, decoded);
if(typeof task.image_blob != 'undefined'){
delete task.image_blob; // no need to send all that data back to the main thread
}
self.busy = false;
return decoded;
}
catch (err){
console.error("IMAGE TO TEXT WORKER: caught general error in image_to_text: ", err);
self.busy = false;
return null
}
}
async function dispose(dispose_type='all') {
//console.log("image_to_text_worker: in dispose");
return false
self.busy_disposing_models = true;
/*
const p = AutomaticSpeechRecognitionPipelineFactory;
try{
(await p.getInstance()).dispose();
p.instance = null;
//console.log("dispose: ASR should now be disposed");
}
catch(err){
console.error("caught error trying to dispose of ASR: ", err);
}
*/
try{
const [processor,tokenizer,model] = await TextGenerationPipeline.getInstance(null, self.current_huggingface_id);
if(processor != null && typeof processor.dispose == 'function'){
//console.log("image_to_text_worker: dispose: disposing of processor");
await processor.dispose();
}
if(tokenizer != null && typeof tokenizer.dispose == 'function'){
//console.log("image_to_text_worker: dispose: disposing of tokenizer");
await tokenizer.dispose();
}
if(model != null && typeof model.dispose == 'function'){
//console.log("image_to_text_worker: dispose: disposing of model");
await model.dispose();
}
TextGenerationPipeline.set_to_null('processor');
TextGenerationPipeline.set_to_null('tokenizer');
TextGenerationPipeline.set_to_null('model');
return true
}
catch(err){
console.error("caught error trying to dispose of image_to_text: ", err);
}
self.busy_disposing_models = false;
return false
}
async function preload_image_to_text(task){
//console.log("IMAGE TO TEXT WORKER: in preload_image_to_text. task: ",task);
self.busy_preloading = true;
//let huggingface_id = 'onnx-community/Florence-2-base-ft';
let huggingface_id = 'Xenova/moondream2';
if(typeof task != 'undefined' && task != null && typeof task.huggingface_id == 'string' && task.huggingface_id.length > 4){
console.warn("image_to_text worker: task contained a huggingface_id: ", task.huggingface_id);
huggingface_id = task.huggingface_id;
}
if(typeof self.current_huggingface_id == 'string' && self.current_huggingface_id != huggingface_id){
console.warn("IMAGE TO TEXT WORKER: SWITCHING TO DIFFERENT MODEL: ", huggingface_id);
self.processor = null;
self.tokenizer = null;
if(self.model != null){
//console.log("IMAGE TO TEXT WORKER: Disposing of old model first");
await self.model.dispose();
}
self.model = null;
}
self.current_huggingface_id = huggingface_id;
//console.log("IMAGE TO TEXT WORKER: preload_image_to_text: huggingface_id: ",huggingface_id);
if(self.processor == null){
//console.log("IMAGE TO TEXT WORKER: preload_image_to_text: huggingface_id -> creating processor for ", huggingface_id);
self.processor = await AutoProcessor.from_pretrained(huggingface_id);
}
if(self.tokenizer == null){
//console.log("IMAGE TO TEXT WORKER: preload_image_to_text: huggingface_id -> creating tokenizer for ", huggingface_id);
self.tokenizer = await AutoTokenizer.from_pretrained(huggingface_id);
}
if(self.model == null ){ // && huggingface_id.indexOf('moondream') != -1
let dtype_settings = {
embed_tokens: self.supports_web_gpu16 ? 'fp16' : 'fp32', // or 'fp32'
vision_encoder: self.supports_web_gpu16 ? 'fp16' : 'fp32', // or 'q8'
decoder_model_merged: 'q4', // or 'q4f16' or 'q8'
/*
embed_tokens: 'fp16', // or 'fp32'
vision_encoder: 'fp16', // or 'q8'
decoder_model_merged: 'q4', // or 'q4f16' or 'q8'
*/
}
//console.log("IMAGE TO TEXT WORKER: dtype_settings: ", JSON.stringify(dtype_settings,null,4));
//console.log("IMAGE TO TEXT WORKER: LOADING huggingface_id: ", huggingface_id);
if(huggingface_id.indexOf('nanoLLaVA') != -1){
//self.model = await Moondream1ForConditionalGeneration.from_pretrained(huggingface_id, {
//console.log("IMAGE TO TEXT WORKER: self.device,dtype_settings: ", self.device, JSON.stringify(dtype_settings,null,4));
self.model = await LlavaForConditionalGeneration.from_pretrained(huggingface_id, {
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT 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: dtype_settings,
//quantized:true,
device: self.device,
});
}
else if(huggingface_id.indexOf('moondream') != -1){
//console.log("IMAGE TO TEXT WORKER: moondream. self.device,dtype_settings: ", self.device, JSON.stringify(dtype_settings,null,4));
self.model = await Moondream1ForConditionalGeneration.from_pretrained(huggingface_id, {
//self.model = await LlavaForConditionalGeneration.from_pretrained(huggingface_id, {
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT 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: dtype_settings,
quantized:true,
device: self.device,
//device: 'wasm',
});
}
else{
//console.log("IMAGE TO TEXT WORKER: using Florence. self.device: ", self.devicef);
self.model = await Florence2ForConditionalGeneration.from_pretrained(huggingface_id, {
//dtype: 'fp32',
dtype: {
embed_tokens: 'fp16',
vision_encoder: 'fp32',
encoder_model: 'fp16',
decoder_model_merged: 'q8', // q4
},
//quantized:true,
progress_callback: (progress_data) => {
//console.log("IMAGE TO TEXT WORKER: Florence 2 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);
},
//device: 'wasm',
});
}
self.postMessage({
'status':'ready'
});
}
self.busy_preloading = false;
return true
}
console.log("IMAGE TO TEXT WORKER EXISTS");
postMessage({"status":"exists"});