Views
No views yet
npm i @huggingface/transformers1import { pipeline, matmul } from "@huggingface/transformers";
2
3// Create a feature extraction pipeline
4const extractor = await pipeline(
5 "feature-extraction",
6 "onnx-community/Qwen3-Embedding-0.6B-ONNX",
7 {
8 dtype: "fp32", // Options: "fp32", "fp16", "q8"
9 // device: "webgpu",
10 },
11);
12
13function get_detailed_instruct(task_description, query) {
14 return `Instruct: ${task_description}\nQuery:${query}`;
15}
16
17// Each query must come with a one-sentence instruction that describes the task
18const task = "Given a web search query, retrieve relevant passages that answer the query";
19const queries = [
20 get_detailed_instruct(task, "What is the capital of China?"),
21 get_detailed_instruct(task, "Explain gravity"),
22];
23
24// No need to add instruction for retrieval documents
25const documents = [
26 "The capital of China is Beijing.",
27 "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
28];
29const input_texts = [...queries, ...documents];
30
31// Extract embeddings for queries and documents
32const output = await extractor(input_texts, {
33 pooling: "last_token",
34 normalize: true,
35});
36const scores = await matmul(
37 output.slice([0, queries.length]), // Query embeddings
38 output.slice([queries.length, null]).transpose(1, 0), // Document embeddings
39);
40console.log(scores.tolist());
41// [
42// [ 0.7645590305328369, 0.14142560958862305 ],
43// [ 0.13549776375293732, 0.599955141544342 ]
44// ]onnx).