Views
No views yet
1import txtai
2
3# Create embeddings
4embeddings = txtai.Embeddings(
5 path="neuml/pubmedbert-base-embeddings-100K",
6 content=True,
7)
8embeddings.index(documents())
9
10# Run a query
11embeddings.search("query to run")1from sentence_transformers import SentenceTransformer
2from sentence_transformers.models import StaticEmbedding
3
4# Initialize a StaticEmbedding module
5static = StaticEmbedding.from_model2vec("neuml/pubmedbert-base-embeddings-100K")
6model = SentenceTransformer(modules=[static])
7
8sentences = ["This is an example sentence", "Each sentence is converted"]
9embeddings = model.encode(sentences)
10print(embeddings)1from model2vec import StaticModel
2
3# Load a pretrained Model2Vec model
4model = StaticModel.from_pretrained("neuml/pubmedbert-base-embeddings-100K")
5
6# Compute text embeddings
7sentences = ["This is an example sentence", "Each sentence is converted"]
8embeddings = model.encode(sentences)
9print(embeddings)| Model | PubMed QA | PubMed Subset | PubMed Summary | Average |
|---|---|---|---|---|
| pubmedbert-base-embeddings-8M-M2V (No training) | 69.84 | 70.77 | 71.30 | 70.64 |
| pubmedbert-base-embeddings-100K | 74.56 | 84.65 | 81.84 | 80.35 |
| pubmedbert-base-embeddings-500K | 86.03 | 91.71 | 91.25 | 89.66 |
| pubmedbert-base-embeddings-1M | 87.87 | 92.80 | 92.87 | 91.18 |
| pubmedbert-base-embeddings-2M | 88.62 | 93.08 | 93.24 | 91.65 |
1from datasets import load_dataset
2from tqdm import tqdm
3from txtai import Embeddings
4
5ds = load_dataset("ccdv/pubmed-summarization", split="train")
6
7embeddings = Embeddings(path="path to model", content=True, backend="numpy")
8embeddings.index(tqdm(ds["abstract"]))| Model | Model Size (MB) | Index time (s) |
|---|---|---|
| pubmedbert-base-embeddings-100K | 0.2 | 19 |
| pubmedbert-base-embeddings-500K | 1.0 | 17 |
| pubmedbert-base-embeddings-1M | 2.0 | 17 |
| pubmedbert-base-embeddings-2M | 7.5 | 17 |
int16 precision. This can be beneficial to smaller/lower powered embedded devices and could lead to faster vectorization times.1import json
2import os
3
4from collections import Counter
5from pathlib import Path
6
7import numpy as np
8
9from model2vec import StaticModel
10from more_itertools import batched
11from sklearn.decomposition import PCA
12from tokenlearn.train import collect_means_and_texts
13from tokenizers import Tokenizer
14from tqdm import tqdm
15from txtai.scoring import ScoringFactory
16
17def tokenize(tokenizer):
18 # Tokenize into dataset
19 dataset = []
20 for t in tqdm(batched(texts, 1024)):
21 encodings = tokenizer.encode_batch_fast(t, add_special_tokens=False)
22 for e in encodings:
23 dataset.append((None, e.ids, None))
24
25 return dataset
26
27def tokenweights(tokenizer):
28 dataset = tokenize(tokenizer)
29
30 # Build scoring index
31 scoring = ScoringFactory.create({"method": "bm25", "terms": True})
32 scoring.index(dataset)
33
34 # Calculate mean value of weights array per token
35 tokens = np.zeros(tokenizer.get_vocab_size())
36 for x in scoring.idf:
37 tokens[x] = np.mean(scoring.terms.weights(x)[1])
38
39 return tokens
40
41# See PubMedBERT Embeddings 2M model for details on this data
42features = "features"
43paths = sorted(Path(features).glob("*.json"))
44texts, _ = collect_means_and_texts(paths)
45
46# Output model parameters
47output = "output path"
48params, dims = 100000, 64
49
50path = "pubmedbert-base-embeddings-2M_unweighted"
51model = StaticModel.from_pretrained(path)
52
53os.makedirs(output, exist_ok=True)
54
55with open(f"{path}/tokenizer.json", "r", encoding="utf-8") as f:
56 config = json.load(f)
57
58# Calculate number of tokens to keep
59tokencount = params // model.dim
60
61# Calculate term frequency
62freqs = Counter()
63for _, ids, _ in tokenize(model.tokenizer):
64 freqs.update(ids)
65
66# Select top N most common tokens
67uids = set(x for x, _ in freqs.most_common(tokencount))
68uids = [uid for token, uid in config["model"]["vocab"].items() if uid in uids or token.startswith("[")]
69
70# Get embeddings for uids
71model.embedding = model.embedding[uids]
72
73# Select pruned tokens
74pairs, index = [], 0
75for token, uid in config["model"]["vocab"].items():
76 if uid in uids:
77 pairs.append((token, index))
78 index += 1
79
80config["model"]["vocab"] = dict(pairs)
81
82# Write new tokenizer
83with open(f"{output}/tokenizer.json", "w", encoding="utf-8") as f:
84 json.dump(config, f, indent=2)
85
86model.tokenizer = Tokenizer.from_file(f"{output}/tokenizer.json")
87
88# Re-weight tokens
89weights = tokenweights(model.tokenizer)
90
91# Remove NaNs from embedding, if any
92embedding = np.nan_to_num(model.embedding)
93
94# Apply PCA
95embedding = PCA(n_components=dims).fit_transform(embedding)
96
97# Apply weights
98embedding *= weights[:, None]
99
100# Update model embedding and normalize
101model.embedding, model.normalize = embedding.astype(np.int16), True
102
103model.save_pretrained(output)