Views
No views yet
npm i @huggingface/transformers1import { AutoModel, AutoTokenizer, matmul } from "@huggingface/transformers";
2
3// Download from the 🤗 Hub
4const model_id = "onnx-community/mdbr-leaf-mt-ONNX";
5const tokenizer = await AutoTokenizer.from_pretrained(model_id);
6const model = await AutoModel.from_pretrained(model_id, {
7 dtype: "fp32", // Options: "fp32" | "fp16" | "q8" | "q4" | "q4f16"
8});
9
10// Prepare queries and documents
11const queries = [
12 "What is machine learning?",
13 "How does neural network training work?",
14];
15const documents = [
16 "Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn from data.",
17 "Neural networks are trained through backpropagation, adjusting weights to minimize prediction errors.",
18];
19const inputs = await tokenizer([
20 ...queries.map((x) => "Represent this sentence for searching relevant passages: " + x),
21 ...documents,
22], { padding: true });
23
24// Generate embeddings
25const { sentence_embedding } = await model(inputs);
26const normalized_sentence_embedding = sentence_embedding.normalize();
27
28// Compute similarities
29const scores = await matmul(
30 normalized_sentence_embedding.slice([0, queries.length]),
31 normalized_sentence_embedding.slice([queries.length, null]).transpose(1, 0),
32);
33const scores_list = scores.tolist();
34
35for (let i = 0; i < queries.length; ++i) {
36 console.log(`Query: ${queries[i]}`);
37 for (let j = 0; j < documents.length; ++j) {
38 console.log(` Similarity: ${scores_list[i][j].toFixed(4)} | Document ${j}: ${documents[j]}`);
39 }
40 console.log();
41}Query: What is machine learning?
Similarity: 0.9063 | Document 0: Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn from data.
Similarity: 0.7287 | Document 1: Neural networks are trained through backpropagation, adjusting weights to minimize prediction errors.
Query: How does neural network training work?
Similarity: 0.6725 | Document 0: Machine learning is a subset of artificial intelligence that focuses on algorithms that can learn from data.
Similarity: 0.8287 | Document 1: Neural networks are trained through backpropagation, adjusting weights to minimize prediction errors.