Debian Codegraph @

examples/inference/pippy/t5.py

raw
1 # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import time
15
16 import torch
17 from packaging import version
18 from transformers import AutoModelForSeq2SeqLM
19
20 from accelerate import PartialState, prepare_pippy
21 from accelerate import __version__ as accelerate_version
22 from accelerate.test_utils import torch_device
23 from accelerate.utils import set_seed
24
25
26 synchronize_func = getattr(torch, torch_device, torch.cuda).synchronize
27
28 if version.parse(accelerate_version) > version.parse("0.33.0"):
29 raise RuntimeError(
30 "Using encoder/decoder models is not supported with the `torch.pipelining` integration or accelerate>=0.34.0. "
31 "Please use a lower accelerate version and `torchpippy`, which this example uses."
32 )
33
34
35 # Set the random seed to have reproducable outputs
36 set_seed(42)
37
38 # Create an example model
39 model = AutoModelForSeq2SeqLM.from_pretrained("t5-small")
40 model.eval()
41
42 # Input configs
43 # Create example inputs for the model
44 input = torch.randint(
45 low=0,
46 high=model.config.vocab_size,
47 size=(2, 1024), # bs x seq_len
48 device="cpu",
49 dtype=torch.int64,
50 requires_grad=False,
51 )
52
53 example_inputs = {"input_ids": input, "decoder_input_ids": input}
54
55 # Create a pipeline stage from the model
56 # Using `auto` is equivalent to letting `device_map="auto"` figure
57 # out device mapping and will also split the model according to the
58 # number of total GPUs available if it fits on one GPU
59 model = prepare_pippy(
60 model,
61 no_split_module_classes=["T5Block"],
62 example_kwargs=example_inputs,
63 )
64
65 # You can pass `gather_output=True` to have the output from the model
66 # available on all GPUs
67 # model = prepare_pippy(
68 # model,
69 # no_split_module_classes=["T5Block"],
70 # example_kwargs=example_inputs,
71 # gather_outputs=True
72 # )
73
74 # The model expects a tuple during real inference
75 # with the data on the first device
76 args = (example_inputs["input_ids"].to(0), example_inputs["decoder_input_ids"].to(0))
77
78 # Take an average of 5 times
79 # Measure first batch
80 synchronize_func()
81 start_time = time.time()
82 with torch.no_grad():
83 output = model(*args)
84 synchronize_func()
85 end_time = time.time()
86 first_batch = end_time - start_time
87
88 # Now that device is init, measure after
89 synchronize_func()
90 start_time = time.time()
91 for i in range(5):
92 with torch.no_grad():
93 output = model(*args)
94 synchronize_func()
95 end_time = time.time()
96
97 # The outputs are only on the final process by default
98 if PartialState().is_last_process:
99 output = torch.stack(tuple(output[0]))
100 print(f"Time of first pass: {first_batch}")
101 print(f"Average time per batch: {(end_time - start_time) / 5}")
102 PartialState().destroy_process_group()