Views
No views yet
npm i @huggingface/transformers1import {
2 AutoTokenizer,
3 CLIPTextModelWithProjection,
4 AutoProcessor,
5 CLIPVisionModelWithProjection,
6 RawImage,
7 dot,
8 softmax,
9} from '@huggingface/transformers';
10
11const model_id = 'Xenova/mobileclip_blt';
12
13// Load tokenizer and text model
14const tokenizer = await AutoTokenizer.from_pretrained(model_id);
15const text_model = await CLIPTextModelWithProjection.from_pretrained(model_id);
16
17// Load processor and vision model
18const processor = await AutoProcessor.from_pretrained(model_id);
19const vision_model = await CLIPVisionModelWithProjection.from_pretrained(model_id);
20
21// Run tokenization
22const texts = ['cats', 'dogs', 'birds'];
23const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });
24
25// Compute text embeddings
26const { text_embeds } = await text_model(text_inputs);
27const normalized_text_embeds = text_embeds.normalize().tolist();
28
29// Read image and run processor
30const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
31const image = await RawImage.read(url);
32const image_inputs = await processor(image);
33
34// Compute vision embeddings
35const { image_embeds } = await vision_model(image_inputs);
36const normalized_image_embeds = image_embeds.normalize().tolist();
37
38// Compute probabilities
39const probabilities = normalized_image_embeds.map(
40 x => softmax(normalized_text_embeds.map(y => 100 * dot(x, y)))
41);
42console.log(probabilities); // [[ 0.9999057403656509, 0.00009141888000214805, 0.0000028407543469763894 ]]