-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinf.py
67 lines (58 loc) · 2.1 KB
/
inf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import tensorflow # to workaround a protobuf version conflict issue
import torch
import torch.neuron
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
import transformers
import os
import warnings
# Setting up NeuronCore groups for inf1.6xlarge with 16 cores
num_cores = 4 # This value should be 4 on inf1.xlarge and inf1.2xlarge
os.environ["NEURON_RT_NUM_CORES"] = str(num_cores)
# Build tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-cased-finetuned-mrpc", return_dict=False
)
# Setup some example inputs
sequence_0 = "The company HuggingFace is based in New York City"
sequence_1 = "Apples are especially bad for your health"
sequence_2 = "HuggingFace's headquarters are situated in Manhattan"
max_length = 128
paraphrase = tokenizer.encode_plus(
sequence_0,
sequence_2,
max_length=max_length,
padding="max_length",
truncation=True,
return_tensors="pt",
)
not_paraphrase = tokenizer.encode_plus(
sequence_0,
sequence_1,
max_length=max_length,
padding="max_length",
truncation=True,
return_tensors="pt",
)
# Run the original PyTorch model on compilation exaple
paraphrase_classification_logits = model(**paraphrase)[0]
# Convert example inputs to a format that is compatible with TorchScript tracing
example_inputs_paraphrase = (
paraphrase["input_ids"],
paraphrase["attention_mask"],
paraphrase["token_type_ids"],
)
example_inputs_not_paraphrase = (
not_paraphrase["input_ids"],
not_paraphrase["attention_mask"],
not_paraphrase["token_type_ids"],
)
# Run torch.neuron.trace to generate a TorchScript that is optimized by AWS Neuron
model_neuron = torch.neuron.trace(model, example_inputs_paraphrase)
# Verify the TorchScript works on both example inputs
paraphrase_classification_logits_neuron = model_neuron(*example_inputs_paraphrase)
not_paraphrase_classification_logits_neuron = model_neuron(
*example_inputs_not_paraphrase
)
# Save the TorchScript for later use
model_neuron.save("bert_neuron.pt")