| 1 |
# Copyright 2022 The HuggingFace 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 |
|
| 15 |
import argparse |
| 16 |
import time |
| 17 |
|
| 18 |
import torch |
| 19 |
import transformers |
| 20 |
from measures_util import end_measure, log_measures, start_measure |
| 21 |
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer |
| 22 |
|
| 23 |
from accelerate.utils import compute_module_sizes |
| 24 |
|
| 25 |
|
| 26 |
DEFAULT_MODELS = { |
| 27 |
"gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"}, |
| 28 |
"gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"}, |
| 29 |
"opt": {"is_causal": True, "model": "facebook/opt-30b"}, |
| 30 |
"T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"}, |
| 31 |
} |
| 32 |
|
| 33 |
PROMPTS = [ |
| 34 |
"Hello, my name is", |
| 35 |
"Are unicorns real? Unicorns are", |
| 36 |
"For the first time in several years,", |
| 37 |
"My name is Julien and I am", |
| 38 |
"The goal of life is", |
| 39 |
"Whenever I'm sad, I like to", |
| 40 |
] |
| 41 |
|
| 42 |
|
| 43 |
def parse_args(): |
| 44 |
parser = argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate.") |
| 45 |
parser.add_argument("model_name", type=str, default=None, help="The name of the model to try.") |
| 46 |
parser.add_argument( |
| 47 |
"--tokenizer_name", type=str, default=None, help="The name of the tokenizer (if different from the model." |
| 48 |
) |
| 49 |
parser.add_argument("--is_causal", type=bool, default=None, help="Whether or not the model is causal.") |
| 50 |
parser.add_argument( |
| 51 |
"--model_revision", type=str, default=None, help="The revision to use for the model checkpoint." |
| 52 |
) |
| 53 |
parser.add_argument("--torch_dtype", type=str, default=None, help="The dtype for the model.") |
| 54 |
parser.add_argument("--disk_offload", action="store_true") |
| 55 |
|
| 56 |
args = parser.parse_args() |
| 57 |
|
| 58 |
# Sanitize args |
| 59 |
if args.model_name in DEFAULT_MODELS: |
| 60 |
defaults = DEFAULT_MODELS[args.model_name] |
| 61 |
args.model_name = defaults["model"] |
| 62 |
if args.tokenizer_name is None: |
| 63 |
args.tokenizer_name = defaults.get("tokenizer", args.model_name) |
| 64 |
if args.is_causal is None: |
| 65 |
args.is_causal = defaults["is_causal"] |
| 66 |
if args.model_revision is None: |
| 67 |
args.model_revision = defaults.get("model_revision", "main") |
| 68 |
|
| 69 |
if args.is_causal is None: |
| 70 |
raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it.") |
| 71 |
if args.tokenizer_name is None: |
| 72 |
args.tokenizer_name = args.model_name |
| 73 |
if args.model_revision is None: |
| 74 |
args.model_revision = "main" |
| 75 |
|
| 76 |
return args |
| 77 |
|
| 78 |
|
| 79 |
def main(): |
| 80 |
transformers.utils.logging.set_verbosity_error() |
| 81 |
args = parse_args() |
| 82 |
|
| 83 |
if args.torch_dtype is None: |
| 84 |
config = AutoConfig.from_pretrained(args.model_name) |
| 85 |
torch_dtype = getattr(config, "torch_dtype", torch.float32) |
| 86 |
else: |
| 87 |
torch_dtype = getattr(torch, args.torch_dtype) |
| 88 |
model_cls = AutoModelForCausalLM if args.is_causal else AutoModelForSeq2SeqLM |
| 89 |
kwargs = { |
| 90 |
"torch_dtype": torch_dtype, |
| 91 |
"revision": args.model_revision, |
| 92 |
} |
| 93 |
if args.disk_offload: |
| 94 |
kwargs["offload_folder"] = "tmp_offload" |
| 95 |
kwargs["offload_state_dict"] = True |
| 96 |
|
| 97 |
start_measures = start_measure() |
| 98 |
model = model_cls.from_pretrained(args.model_name, device_map="auto", **kwargs) |
| 99 |
end_measures = end_measure(start_measures) |
| 100 |
log_measures(end_measures, "Model loading") |
| 101 |
|
| 102 |
module_sizes = compute_module_sizes(model) |
| 103 |
device_size = {v: 0 for v in model.hf_device_map.values()} |
| 104 |
for module, device in model.hf_device_map.items(): |
| 105 |
device_size[device] += module_sizes[module] |
| 106 |
message = "\n".join([f"- {device}: {size // 2**20}MiB" for device, size in device_size.items()]) |
| 107 |
print(f"\nTheoretical use:\n{message}") |
| 108 |
|
| 109 |
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name) |
| 110 |
|
| 111 |
start_measures = start_measure() |
| 112 |
generation_times = [] |
| 113 |
gen_tokens = [] |
| 114 |
texts_outs = [] |
| 115 |
for prompt in PROMPTS: |
| 116 |
inputs = tokenizer(prompt, return_tensors="pt").to(0) |
| 117 |
tokens = inputs["input_ids"][0].tolist() |
| 118 |
before_generate = time.time() |
| 119 |
outputs = model.generate(inputs["input_ids"]) |
| 120 |
after_generate = time.time() |
| 121 |
outputs = outputs[0].tolist() |
| 122 |
num_gen_tokens = len(outputs) if outputs[: len(tokens)] != tokens else len(outputs) - len(tokens) |
| 123 |
generation_time = after_generate - before_generate |
| 124 |
|
| 125 |
text_out = tokenizer.decode(outputs, skip_special_tokens=True) |
| 126 |
texts_outs.append(text_out) |
| 127 |
generation_times.append(generation_time) |
| 128 |
gen_tokens.append(num_gen_tokens) |
| 129 |
print(f"Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n") |
| 130 |
|
| 131 |
end_measures = end_measure(start_measures) |
| 132 |
log_measures(end_measures, "Model generation") |
| 133 |
|
| 134 |
generation_times_per_token = [gen / tok for gen, tok in zip(generation_times, gen_tokens)] |
| 135 |
avg_gen = sum(generation_times_per_token) / len(generation_times) |
| 136 |
print(f"Average time of generation per token: {avg_gen:.2f}s") |
| 137 |
print(f"First generation (avg time per token): {generation_times_per_token[0]:.2f}s") |
| 138 |
avg_gen = sum(generation_times_per_token[1:]) / (len(generation_times_per_token) - 1) |
| 139 |
print(f"Average time of generation per token (excluding the first): {avg_gen:.2f}s") |
| 140 |
|
| 141 |
|
| 142 |
if __name__ == "__main__": |
| 143 |
main() |