Views
No views yet
1# create an XTR index
2config = ldb.Configuration()
3config.num_subquantizers = 64
4config.dim = 128
5config.nbits = 4
6config.quantizer_type = ldb.IndexEncoding_XTR
7index = ldb.IndexIVF(f"experiments/goog", config)
8
9# build a collection on top of the index
10opts = ldb.CollectionOptions()
11opts.model_file = "assets/xtr/encoder.onnx"
12opts.tokenizer_file = "assets/xtr/spiece.model"
13
14collection = ldb.Collection(index, opts)
15
16collection.train(chunks, 50, 10)
17
18for i, snip in enumerate(chunks):
19 collection.add(0, i, snip, {'docid': f'{i}'})1from sentence_transformers import SentenceTransformer
2from sentence_transformers import models
3import torch
4import torch.nn as nn
5import onnx
6import numpy as np
7from transformers import T5EncoderModel
8from pathlib import Path
9from transformers import AutoTokenizer
10
11# https://github.com/huggingface/optimum/issues/1519
12
13class CombinedModel(nn.Module):
14 def __init__(self, transformer_model, dense_model):
15 super(CombinedModel, self).__init__()
16 self.transformer = transformer_model
17 self.dense = dense_model
18
19 def forward(self, input_ids, attention_mask):
20 outputs = self.transformer(input_ids, attention_mask=attention_mask)
21 token_embeddings = outputs['last_hidden_state']
22 return self.dense({'sentence_embedding': token_embeddings})
23
24
25save_directory = "onnx/"
26
27# Load a model from transformers and export it to ONNX
28tokenizer = AutoTokenizer.from_pretrained(path)
29
30# load the t5 base encoder model.
31transformer_model = T5EncoderModel.from_pretrained(path)
32
33dense_model = models.Dense(
34 in_features=768,
35 out_features=128,
36 bias=False,
37 activation_function= nn.Identity()
38)
39
40state_dict = torch.load(os.path.join(path, '2_Dense', dense_filename))
41dense_model.load_state_dict(state_dict)
42
43model = CombinedModel(transformer_model, dense_model)
44
45model.eval()
46
47input_text = "Who founded google"
48inputs = tokenizer(input_text, padding='longest', truncation=True, max_length=128, return_tensors='pt')
49
50input_ids = inputs['input_ids']
51attention_mask = inputs['attention_mask']
52
53torch.onnx.export(
54 model,
55 (input_ids, attention_mask),
56 "combined_model.onnx",
57 export_params=True,
58 opset_version=17,
59 do_constant_folding=True,
60 input_names = ['input_ids', 'attention_mask'],
61 output_names = ['contextual'],
62 dynamic_axes={
63 'input_ids': {0 : 'batch_size', 1: 'seq_length'}, # variable length axes
64 'attention_mask': {0 : 'batch_size', 1: 'seq_length'},
65 'contextual' : {0 : 'batch_size', 1: 'seq_length'}
66 }
67)
68
69onnx.checker.check_model("combined_model.onnx")
70
71combined_model = onnx.load("combined_model.onnx")
72
73import onnxruntime as ort
74ort_session = ort.InferenceSession("combined_model.onnx")
75output = ort_session.run(None, {'input_ids': input_ids.numpy(), 'attention_mask': attention_mask.numpy()})
76
77
78# Run the PyTorch model
79pytorch_output = model(input_ids, attention_mask)
80print(pytorch_output['sentence_embedding'])
81
82print(output[0])
83# Compare the outputs
84# print("Are the outputs close?", np.allclose(pytorch_output.detach().numpy(), output[0], atol=1e-6))
85
86# Calculate the differences between the outputs
87differences = pytorch_output['sentence_embedding'].detach().numpy() - output[0]
88
89# Print the standard deviation of the differences
90print("Standard deviation of the differences:", np.std(differences))
91
92print("pytorch_output size:", pytorch_output['sentence_embedding'].size())
93print("onnx_output size:", output[0].shape)