|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2020 The HuggingFace Inc. team. All rights reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +import argparse |
| 16 | +import json |
| 17 | +import pathlib |
| 18 | +import time |
| 19 | +from itertools import chain |
| 20 | + |
| 21 | +import numpy as np |
| 22 | +import torch |
| 23 | +from transformers import ( |
| 24 | + AutoModelForCausalLM, |
| 25 | + AutoTokenizer, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +def trace_handler(profile_obj): |
| 30 | + print(profile_obj.key_averages().table(sort_by="self_xpu_time_total", row_limit=-1)) |
| 31 | + |
| 32 | + |
| 33 | +parser = argparse.ArgumentParser("LLM generation (greedy search) script for inductor torch.compile path", |
| 34 | + add_help=False) |
| 35 | +parser.add_argument( |
| 36 | + "-m", |
| 37 | + "--model-name-or-path", |
| 38 | + default="meta-llama/Llama-2-7b-hf", |
| 39 | + type=str, |
| 40 | + help="path to model or model name in HF hub", |
| 41 | +) |
| 42 | +parser.add_argument( |
| 43 | + "--dtype", |
| 44 | + type=str, |
| 45 | + choices=["fp32", "bf16", "fp16"], |
| 46 | + help="bf16 or fp32", |
| 47 | + default="bf16", |
| 48 | +) |
| 49 | +parser.add_argument("--max-new-tokens", default=32, type=int, help="output max new tokens") |
| 50 | +parser.add_argument("--input-tokens", default="32", type=str) |
| 51 | +parser.add_argument("--page-size", default=32, type=int) |
| 52 | +parser.add_argument("--prompt", default=None, type=str) |
| 53 | +parser.add_argument("--num-iter", default=1, type=int, help="num iter") |
| 54 | +parser.add_argument("--num-warmup", default=0, type=int, help="num warmup") |
| 55 | +parser.add_argument("--batch-size", default=1, type=int, help="batch size") |
| 56 | +parser.add_argument("--device", default="xpu", type=str) |
| 57 | +parser.add_argument("--profile", action="store_true") |
| 58 | +parser.add_argument("--compile", action="store_true") |
| 59 | +args = parser.parse_args() |
| 60 | + |
| 61 | +if args.dtype == "bf16": |
| 62 | + amp_enabled = True |
| 63 | + load_dtype = torch.bfloat16 |
| 64 | +elif args.dtype == "fp32": |
| 65 | + amp_enabled = False |
| 66 | + load_dtype = torch.float |
| 67 | +elif args.dtype == "fp16": |
| 68 | + amp_enabled = True |
| 69 | + load_dtype = torch.float16 |
| 70 | +else: |
| 71 | + assert False, "This script only support bf16 and fp32 as dtype" |
| 72 | + |
| 73 | +attn_type = "flex_attention" |
| 74 | +tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) |
| 75 | +model = AutoModelForCausalLM.from_pretrained(args.model_name_or_path, torch_dtype=load_dtype, |
| 76 | + attn_implementation=attn_type).to(args.device) |
| 77 | +if attn_type == "paged_attention": |
| 78 | + model.generation_config.cache_implementation = "paged" |
| 79 | + model.config.page_size = args.page_size |
| 80 | + |
| 81 | +if args.compile: |
| 82 | + with torch.no_grad(), torch.autocast(enabled=amp_enabled, device_type=args.device, dtype=load_dtype): |
| 83 | + print("compile Enabled") |
| 84 | + model.forward = torch.compile(model.forward, dynamic=True) |
| 85 | + |
| 86 | +# greedy search |
| 87 | +generate_kwargs = { |
| 88 | + "do_sample": False, |
| 89 | + "temperature": 0.9, |
| 90 | + "num_beams": 1, |
| 91 | + "token_latency": True, |
| 92 | +} |
| 93 | +current_path = pathlib.Path(__file__).parent.resolve() |
| 94 | +if args.prompt is not None: |
| 95 | + prompt = args.prompt |
| 96 | +else: |
| 97 | + with open(str(current_path) + "/prompt.json", encoding="utf-8") as f: |
| 98 | + prompt_pool = json.load(f) |
| 99 | + if "llama" in prompt_pool and args.input_tokens in prompt_pool["llama"]: |
| 100 | + prompt = prompt_pool["llama"]["2048"] |
| 101 | + else: |
| 102 | + raise SystemExit( |
| 103 | + "[ERROR] No such input_tokens prompt in prompt.json, Please use --prompt if want to use custom input.") |
| 104 | + |
| 105 | +prompt = [prompt] * args.batch_size |
| 106 | +inputs = tokenizer(prompt, return_tensors="pt", max_length=int(args.input_tokens)) |
| 107 | +input_ids = inputs.input_ids.to(args.device) |
| 108 | +attention_mask = inputs.attention_mask.to(args.device) |
| 109 | + |
| 110 | +input_size = input_ids.size(dim=1) |
| 111 | +print(f"---- Prompt size: {input_size}") |
| 112 | + |
| 113 | +# warmup |
| 114 | +with torch.no_grad(), torch.autocast(enabled=amp_enabled, device_type=args.device, dtype=load_dtype): |
| 115 | + for _ in range(args.num_warmup): |
| 116 | + model.generate(input_ids, attention_mask=attention_mask, max_new_tokens=args.max_new_tokens, **generate_kwargs) |
| 117 | + |
| 118 | +if args.profile: |
| 119 | + with torch.profiler.profile(activities=[ |
| 120 | + torch.profiler.ProfilerActivity.CPU, |
| 121 | + torch.profiler.ProfilerActivity.XPU, |
| 122 | + ], schedule=torch.profiler.schedule(wait=0, warmup=2, active=5), on_trace_ready=trace_handler, |
| 123 | + record_shapes=True) as prof: |
| 124 | + with torch.no_grad(), torch.autocast(enabled=amp_enabled, device_type=args.device, dtype=load_dtype): |
| 125 | + for i in range(7): |
| 126 | + |
| 127 | + model.generate(input_ids, attention_mask=attention_mask, max_new_tokens=args.max_new_tokens, |
| 128 | + **generate_kwargs) |
| 129 | + prof.step() |
| 130 | +# benchmark |
| 131 | +num_iter = args.num_iter - args.num_warmup |
| 132 | +total_time = 0.0 |
| 133 | +total_list = [] |
| 134 | +gen_text = None |
| 135 | +with torch.no_grad(), torch.autocast(enabled=amp_enabled, device_type=args.device, dtype=load_dtype): |
| 136 | + for _ in range(num_iter): |
| 137 | + torch.xpu.synchronize() |
| 138 | + tic = time.time() |
| 139 | + output = model.generate(input_ids, attention_mask=attention_mask, max_new_tokens=args.max_new_tokens, |
| 140 | + **generate_kwargs) |
| 141 | + gen_ids = output[0] |
| 142 | + gen_text = tokenizer.batch_decode(gen_ids, skip_special_tokens=True) |
| 143 | + torch.xpu.synchronize() |
| 144 | + toc = time.time() |
| 145 | + total_time += toc - tic |
| 146 | + total_list.append(output[1]) |
| 147 | + |
| 148 | +print(gen_text, flush=True) |
| 149 | +print("\n", "-" * 10, "Summary:", "-" * 10) |
| 150 | +latency = total_time / num_iter |
| 151 | +print(f"inference-latency: {latency:.3f} sec.") |
| 152 | +first_latency = np.mean([x[0] for x in total_list]) |
| 153 | +if args.max_new_tokens > 1: |
| 154 | + next_latency_list = list(chain(*[x[1:] for x in total_list])) |
| 155 | + next_latency_list.sort() |
| 156 | + average_next_latency = np.mean(next_latency_list) |
| 157 | + p90_latency = np.percentile(next_latency_list, 90) |
| 158 | +print(f"first-token-latency: {first_latency:.3f} sec.") |
| 159 | +if args.max_new_tokens > 1: |
| 160 | + print(f"rest-token-latency: {average_next_latency:.3f} sec.") |
| 161 | + print(f"P90-rest-token-latency: {p90_latency:.3f} sec.") |
0 commit comments