Views
No views yet
npm i @xenova/transformers1import {
2 AutoTokenizer,
3 CLIPTextModelWithProjection,
4 AutoProcessor,
5 CLIPVisionModelWithProjection,
6 RawImage,
7 dot,
8 softmax,
9} from '@xenova/transformers';
10
11const model_id = 'Xenova/mobileclip_s0';
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 quantized: false, // NOTE: vision model is sensitive to quantization.
21});
22
23// Run tokenization
24const texts = ['cats', 'dogs', 'birds'];
25const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true });
26
27// Compute text embeddings
28const { text_embeds } = await text_model(text_inputs);
29const normalized_text_embeds = text_embeds.normalize().tolist();
30
31// Read image and run processor
32const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg';
33const image = await RawImage.read(url);
34const image_inputs = await processor(image);
35
36// Compute vision embeddings
37const { image_embeds } = await vision_model(image_inputs);
38const normalized_image_embeds = image_embeds.normalize().tolist();
39
40// Compute probabilities
41const probabilities = normalized_image_embeds.map(
42 x => softmax(normalized_text_embeds.map(y => 100 * dot(x, y)))
43);
44console.log(probabilities); // [[ 0.9989384093386391, 0.001060433633052551, 0.000001157028308360134 ]]