Views
No views yet
npm i @huggingface/transformers1import { AutoProcessor, AutoTokenizer, LlavaForConditionalGeneration, RawImage } from '@huggingface/transformers';
2
3// Load tokenizer, processor and model
4const model_id = 'onnx-community/nanoLLaVA-1.5';
5const tokenizer = await AutoTokenizer.from_pretrained(model_id);
6const processor = await AutoProcessor.from_pretrained(model_id);
7const model = await LlavaForConditionalGeneration.from_pretrained(model_id, {
8 dtype: {
9 embed_tokens: 'fp16', // or 'fp32' or 'q8'
10 vision_encoder: 'fp16', // or 'fp32' or 'q8'
11 decoder_model_merged: 'q4', // or 'q8'
12 },
13 // device: 'webgpu',
14});
15
16// Prepare text inputs
17const prompt = 'What does the text say?';
18const messages = [
19 { role: 'system', content: 'Answer the question.' },
20 { role: 'user', content: `<image>\n${prompt}` }
21]
22const text = tokenizer.apply_chat_template(messages, { tokenize: false, add_generation_prompt: true });
23const text_inputs = tokenizer(text);
24
25// Prepare vision inputs
26const url = 'https://huggingface.co/qnguyen3/nanoLLaVA/resolve/main/example_1.png';
27const image = await RawImage.fromURL(url);
28const vision_inputs = await processor(image);
29
30// Generate response
31const { past_key_values, sequences } = await model.generate({
32 ...text_inputs,
33 ...vision_inputs,
34 do_sample: false,
35 max_new_tokens: 64,
36 return_dict_in_generate: true,
37});
38
39// Decode output
40const answer = tokenizer.decode(
41 sequences.slice(0, [text_inputs.input_ids.dims[1], null]),
42 { skip_special_tokens: true },
43);
44console.log(answer);
45// The text on the image reads "SMALL BUT MIGHTY." This phrase is likely a play on words, combining the words "small" and "mighty," suggesting that the mouse is strong and capable, despite its size.
46
47const new_messages = [
48 ...messages,
49 { role: 'assistant', content: answer },
50 { role: 'user', content: 'How does the text correlate to the context of the image?' }
51]
52const new_text = tokenizer.apply_chat_template(new_messages, { tokenize: false, add_generation_prompt: true });
53const new_text_inputs = tokenizer(new_text);
54
55// Generate another response
56const output = await model.generate({
57 ...new_text_inputs,
58 past_key_values,
59 do_sample: false,
60 max_new_tokens: 256,
61});
62const new_answer = tokenizer.decode(
63 output.slice(0, [new_text_inputs.input_ids.dims[1], null]),
64 { skip_special_tokens: true },
65);
66console.log(new_answer);
67// The text "SMALL BUT MIGHTY" correlates to the context of the image by implying that despite its size, the mouse possesses a significant amount of strength or capability. This could be a metaphor for the mouse's ability to perform tasks or overcome challenges, especially when it comes to lifting a weight.onnx).