mirror of
https://github.com/neuml/txtai.git
synced 2026-10-12 02:19:52 +00:00
16 KiB
16 KiB
In [ ]:
%%capture
!pip install git+https://github.com/neuml/txtai#egg=txtai[pipeline-train] datasets sentence-transformers onnxruntime onnxIn [ ]:
from datasets import load_dataset
dataset = load_dataset("ag_news", split="train")In [ ]:
from transformers import AutoTokenizer
def stream(batch=10000):
for x in range(0, len(dataset), batch):
yield dataset[x: x + batch]["text"]
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tokenizer = tokenizer.train_new_from_iterator(stream(), vocab_size=500, length=len(dataset))
tokenizer.model_max_length = 512
tokenizer.save_pretrained("bert")In [ ]:
print(tokenizer.tokenize("Red Sox defeat Yankees 5-3"))['re', '##d', 'so', '##x', 'de', '##f', '##e', '##at', 'y', '##ank', '##e', '##es', '5', '-', '3']
In [ ]:
from transformers import AutoTokenizer, BertConfig, BertForMaskedLM
from txtai.pipeline import HFTrainer
config = BertConfig(
vocab_size = 500,
hidden_size = 50,
num_hidden_layers = 2,
num_attention_heads = 2,
intermediate_size = 100,
)
model = BertForMaskedLM(config)
model.save_pretrained("bert")
tokenizer = AutoTokenizer.from_pretrained("bert")
train = HFTrainer()
# Train model
train((model, tokenizer), dataset, task="language-modeling", output_dir="bert",
fp16=True, per_device_train_batch_size=128, num_train_epochs=10,
dataloader_num_workers=2)In [ ]:
%%capture
!wget https://raw.githubusercontent.com/UKPLab/sentence-transformers/master/examples/training/nli/training_nli_v2.py
!python training_nli_v2.py bert
!mv output/* bert-nliIn [ ]:
from txtai.embeddings import Embeddings
# Get list of all text
texts = dataset["text"]
embeddings = Embeddings({"path": "bert-nli", "content": True})
embeddings.index((x, text, None) for x, text in enumerate(texts))In [ ]:
embeddings.search("Boston Red Sox Cardinals World Series")[{'id': '76733',
'text': 'Red Sox sweep Cardinals to win World Series The Boston Red Sox ended their 86-year championship drought with a 3-0 win over the St. Louis Cardinals in Game Four of the World Series.',
'score': 0.8008379936218262},
{'id': '71169',
'text': 'Red Sox lead 2-0 over Cardinals of World Series The host Boston Red Sox scored a 6-2 victory over the St. Louis Cardinals, helped by Curt Schilling #39;s pitching through pain and seeping blood, in World Series Game 2 on Sunday night.',
'score': 0.7896029353141785},
{'id': '70100',
'text': 'Sports: Red Sox 9 Cardinals 7 after 7 innings BOSTON Boston has scored twice in the seventh inning to take an 9-to-7 lead over the St. Louis Cardinals in the World Series opener at Fenway Park.',
'score': 0.7735188603401184}]In [ ]:
# Show number of parameters
parameters = sum(p.numel() for p in embeddings.model.model.parameters())
print(f"Number of parameters:\t\t{parameters:,}")
print(f"% of bert-base-uncased\t\t{(parameters / 110000000) * 100:.2f}%")Number of parameters: 94,450 % of bert-base-uncased 0.09%
In [ ]:
!ls -lh bert-nli/pytorch_model.bin-rw-r--r-- 1 root root 386K Jan 11 20:52 bert-nli/pytorch_model.bin
In [ ]:
from txtai.pipeline import HFOnnx
onnx = HFOnnx()
onnx("bert-nli", task="pooling", output="bert-nli.onnx", quantize=True)In [ ]:
embeddings = Embeddings({"path": "bert-nli.onnx", "tokenizer": "bert-nli", "content": True})
embeddings.index((x, text, None) for x, text in enumerate(texts))
embeddings.search("Boston Red Sox Cardinals World Series")[{'id': '76733',
'text': 'Red Sox sweep Cardinals to win World Series The Boston Red Sox ended their 86-year championship drought with a 3-0 win over the St. Louis Cardinals in Game Four of the World Series.',
'score': 0.8008379936218262},
{'id': '71169',
'text': 'Red Sox lead 2-0 over Cardinals of World Series The host Boston Red Sox scored a 6-2 victory over the St. Louis Cardinals, helped by Curt Schilling #39;s pitching through pain and seeping blood, in World Series Game 2 on Sunday night.',
'score': 0.7896029353141785},
{'id': '70100',
'text': 'Sports: Red Sox 9 Cardinals 7 after 7 innings BOSTON Boston has scored twice in the seventh inning to take an 9-to-7 lead over the St. Louis Cardinals in the World Series opener at Fenway Park.',
'score': 0.7735188603401184}]In [ ]:
!ls -lh bert-nli.onnx-rw-r--r-- 1 root root 187K Jan 11 20:53 bert-nli.onnx