├── gptq ├── download_chatglm2_6b.py ├── requirements.txt ├── run_chatglm2_gptq.py └── README.md ├── requirements.txt ├── convert_to_fp16_ir.py ├── README.md ├── utils.py ├── inference_engine.py ├── LICENSE ├── benchmark.py ├── modeling.py └── convert.py /gptq/download_chatglm2_6b.py: -------------------------------------------------------------------------------- 1 | from modelscope import AutoTokenizer, AutoModelForCausalLM, snapshot_download 2 | model_dir = snapshot_download("ZhipuAI/chatglm2-6b", revision = 'v1.0.12', cache_dir=".") 3 | -------------------------------------------------------------------------------- /gptq/requirements.txt: -------------------------------------------------------------------------------- 1 | huggingface_hub 2 | transformers==4.35.0 3 | optimum==1.14.0 4 | git+https://github.com/huggingface/optimum-intel@f248835b16ce4ec054d6d4d629dff4213fe94157 5 | auto-gptq==0.5.1 6 | torch==2.0.0 7 | tokenizers==0.14.0 8 | modelscope>=1.9.0 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | --extra-index-url https://download.pytorch.org/whl/cpu 2 | openvino>=2023.2.0 3 | openvino-dev>=2023.2.0 4 | torch 5 | transformers==4.34.0 6 | tokenizers==0.14.1 7 | accelerate 8 | werkzeug 9 | numpy 10 | optimum==1.14.1 11 | git+https://github.com/huggingface/optimum-intel.git@f248835b16ce4ec054d6d4d629dff4213fe94157 12 | nncf 13 | onnx>=1.11.0 14 | onnxruntime 15 | tiktoken 16 | psutil 17 | einops 18 | huggingface_hub 19 | hf_transfer 20 | auto-gptq==0.5.1 21 | transformers_stream_generator 22 | -------------------------------------------------------------------------------- /convert_to_fp16_ir.py: -------------------------------------------------------------------------------- 1 | import openvino.runtime as ov 2 | from openvino.tools.mo import convert_model 3 | from openvino._offline_transformations import apply_moc_transformations, compress_model_transformation 4 | 5 | fp32_model_path = "llm_models/Qwen-7B-Chat-GPTQ_INT4_FP16/openvino_model.xml" 6 | fp16_model_path = "llm_models/Qwen-7B-Chat-GPTQ_INT4_FP16/openvino_model_fp16.xml" 7 | 8 | core = ov.Core() 9 | print("Read FP32 OV Model ...") 10 | ov_model = core.read_model(fp32_model_path) 11 | 12 | print("Convert FP32 OV Model to FP16 OV Model...") 13 | apply_moc_transformations(ov_model, cf=False) 14 | compress_model_transformation(ov_model) 15 | 16 | print(f"Serialize Converted FP16 Model as {fp16_model_path}") 17 | ov.serialize(ov_model, fp16_model_path) 18 | 19 | print("Done.") 20 | -------------------------------------------------------------------------------- /gptq/run_chatglm2_gptq.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig 2 | import argparse 3 | 4 | parser = argparse.ArgumentParser( 5 | 'LLM GPTQ INT4 quantization tool', add_help=True, formatter_class=argparse.RawTextHelpFormatter) 6 | parser.add_argument( 7 | '-m', '--model_id', default="ZhipuAI/chatglm2-6b", help='model folder to original ChatGLM FP16 pytorch model', required=TabError) 8 | parser.add_argument( 9 | '-o', '--output_dir', default="ChatGLM2-GPTQ-INT4", help='model folder to save quantized GPTQ INT4 pytorch model', required=TabError) 10 | args = parser.parse_args() 11 | 12 | tokenizer = AutoTokenizer.from_pretrained(args.model_id, use_fast=True, trust_remote_code=True) 13 | quantize_config = GPTQConfig( 14 | bits=4, 15 | dataset=[ 16 | "新風系統是透過系統設計送風和排風使室內空氣存在一定的壓差", 17 | "向室內提供足夠的新風並排出室內汙濁空氣 ", 18 | "無需開窗全天持續不斷有組織的向室內引入新風", 19 | "為室內人員呼吸代謝提供所需氧氣", 20 | "使用超过2.4万亿tokens的数据进行预训练, 包含高质量中、英、多语言、代码、数学等数据,涵盖通用及专业领域的训练语料。通过大量对比实验对预训练语料分布进行了优化" 21 | "相比目前以中英词表为主的开源模型, Qwen-7B使用了约15万大小的词表。该词表对多语言更加友好, 方便用户在不扩展词表的情况下对部分语种进行能力增强和扩展。", 22 | ], 23 | tokenizer=tokenizer, 24 | block_name_to_quantize="transformer.encoder.layers", 25 | cache_block_outputs=False 26 | ) 27 | 28 | model = AutoModelForCausalLM.from_pretrained( 29 | args.model_id, quantization_config=quantize_config, device_map="auto", trust_remote_code=True 30 | ) 31 | model.save_pretrained(args.output_dir) 32 | #tokenizer.save_pretrained(args.output_dir) 33 | -------------------------------------------------------------------------------- /gptq/README.md: -------------------------------------------------------------------------------- 1 | ## System Requirment 2 | This example has following requirements 3 | - Latest chatglm2-6b model from [hugging-face](https://hf-mirror.com/THUDM/chatglm2-6b) or [model scope](https://modelscope.cn/models/ZhipuAI/chatglm2-6b/summary) 4 | - Request Nvidia GPU for GPTQ quantization, GPU memory >= 12GB 5 | - Verified system: Ubuntu 18.04, Nvidia 1080TI,Driver Version: 520.61.05, CUDA Version:11.8, GPU memory 24 GB 6 | - Transformer 4.35.0, optimum 1.14.0, auto-gptp 0.5.1, optimum-intel 1.13.0.dev0 7 | 8 | So this python environment is not compatible with `ov_llm_bench` for model conversion and benchmark, please create new python environment for better environment maintenance 9 | 10 | ## Setup Environment 11 | ```bash 12 | conda deactivate 13 | conda create -n chatglm2-gptq python=3.10 14 | conda activate chatglm2-gptq 15 | python -m pip install -r requirements.txt 16 | ``` 17 | 18 | ## Download ChatGLM2-6B FP16 original model 19 | ```python 20 | python download_chatglm2_6b.py 21 | ``` 22 | 23 | ## Run GPTQ INT4 Quantization on Nvidia GPU 24 | ```python 25 | python run_chatglm2_gptq.py --model_id ZhipuAI/chatglm2-6b --output_dir ChatGLM2-GPTQ-INT4 26 | ``` 27 | 28 | ## Copy tokenzier related files from chatglm2-6b to ChatGLM2-GPTQ-INT4 29 | ```bash 30 | cp ZhipuAI/chatglm2-6b/tokenizer.model ChatGLM2-GPTQ-INT4/ 31 | cp ZhipuAI/chatglm2-6b/tokenizer_config.json ChatGLM2-GPTQ-INT4/ 32 | cp ZhipuAI/chatglm2-6b/tokenization_chatglm.py ChatGLM2-GPTQ-INT4/ 33 | ``` 34 | 35 | Please note, ChatGLM2 tokenzier has issue with tranformer 4.35.0 to save tokenizer via `tokenizer.save_pretrained(args.output_dir)`: [Issue 152](https://github.com/THUDM/ChatGLM3/issues/152), [Issue 199](https://github.com/InternLM/xtuner/issues/199) 36 | 37 | Because GPTQ method only apply to pytorch model, tokenzier itself remain unchanged. So we manually copy tokenzier related files from original chatglm2-6b to quantized ChatGLM2-GPTQ-INT4 38 | 39 | 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ov_llm_bench 2 | OpenVINO LLM Benchmark, including model conversion and benchmark script, required minimum openvino version>=2023.2 3 | 4 | 5 | ## Setup Python Environment 6 | ```bash 7 | conda create -n ov_llm_bench python=3.10 8 | conda activate ov_llm_bench 9 | pip install -r requirements.txt 10 | ``` 11 | 12 | 13 | ## Llama-2-7B-Chat-GPTQ 14 | #### Download Llama-2-7B-Chat-GPTQ Pytorch INT4-FP16 Model locally via HF mirror in PRC: 15 | ```bash 16 | export HF_ENDPOINT=https://hf-mirror.com 17 | huggingface-cli download --resume-download TheBloke/Llama-2-7B-Chat-GPTQ --local-dir Llama-2-7B-Chat-GPTQ 18 | ``` 19 | 20 | #### Convert Llama-2-7B-Chat-GPTQ Pytorch Model to OpenVINO INT4-FP16 model 21 | ```python 22 | python convert.py --model_id Llama-2-7B-Chat-GPTQ/ --output_dir Llama-2-7B-Chat-GPTQ-OV --precision FP16 23 | ``` 24 | 25 | #### Run benchmark with OpenVINO INT4-FP16 model with prompt length 9/32/256/512/1024 on intel CPU/GPU 26 | ```python 27 | python benchmark.py -m Llama-2-7B-Chat-GPTQ-OV/GPTQ_INT4-FP16 -d CPU -pl 9 28 | ``` 29 | 30 | 31 | ## ChatGLM3-6B-GPTQ-INT4 32 | #### Download ChatGLM3-6B-GPTQ-INT4 Pytorch INT4-FP16 Model locally via HF mirror in PRC: 33 | ```bash 34 | export HF_ENDPOINT=https://hf-mirror.com 35 | huggingface-cli download --resume-download ranchlai/chatglm3-6B-gptq-4bit --local-dir ChatGLM3-6B-GPTQ-INT4 36 | ``` 37 | 38 | #### Convert ChatGLM3-6B-GPTQ-INT4 Pytorch Model to OpenVINO INT4-FP16 model 39 | ```python 40 | python convert.py --model_id ChatGLM3-6B-GPTQ-INT4 --output_dir ChatGLM3-6B-GPTQ-INT4-OV --precision FP16 41 | ``` 42 | #### Run benchmark with OpenVINO INT4-FP16 model with prompt length 9/32/256/512/1024 on intel CPU/GPU 43 | ```python 44 | python benchmark.py -m ChatGLM3-6B-GPTQ-INT4-OV/GPTQ_INT4-FP16 -d CPU -pl 9 45 | ``` 46 | 47 | For ChatGLM2 GPTQ INT4 model support, here is a [gptq quantization example](https://github.com/sammysun0711/ov_llm_bench/tree/main/gptq) to run GPTQ INT4 quatization on original FP16 ChatGLM model with GPU. Then quantized ChatGLM2 GPTQ INT4 model can be converted with `convert.py` script to OpenVINO model. 48 | 49 | 50 | 51 | ## Qwen-7B-Chat-Int4 52 | #### Download Qwen-7B-Chat-Int4 Pytorch INT4-FP16 locally via HF mirror in PRC: 53 | ``` 54 | export HF_ENDPOINT=https://hf-mirror.com 55 | huggingface-cli download --resume-download Qwen/Qwen-7B-Chat-Int4 --local-dir Qwen-7B-Chat-Int4 56 | ``` 57 | #### Modify Qwen-7B-Chat-Int4/modeling_qwen.py to enable export on CPU only mode 58 | ```python 59 | #SUPPORT_CUDA = torch.cuda.is_available() 60 | SUPPORT_CUDA = False 61 | #SUPPORT_TORCH2 = hasattr(torch, '__version__') and int(torch.__version__.split(".")[0]) >= 2 62 | SUPPORT_TORCH2=False 63 | ``` 64 | #### Convert Qwen-7B-Chat-Int4 Pytorch Model to OpenVINO INT4-FP16 model 65 | ```python 66 | python convert.py --model_id Qwen-7B-Chat-Int4 --output_dir Qwen-7B-Chat-Int4-OV --precision FP16 67 | ``` 68 | #### Copy generation_config.json to Qwen-7B-Chat-Int4-OV 69 | ```bash 70 | cp Qwen-7B-Chat-Int4/generation_config.json Qwen-7B-Chat-Int4-OV/GPTQ_INT4-FP16 71 | ``` 72 | #### Run benchmark with OpenVINO INT4-FP16 model with prompt length 9/32/256/512/1024 on intel CPU/GPU 73 | ```python 74 | python benchmark.py -m Qwen-7B-Chat-Int4-OV/GPTQ_INT4-FP16 -d CPU -pl 9 75 | ``` 76 | 77 | 78 | ## OpenVINO nightly build 79 | In case you want try out latest openvino nightly build, Please note, nightly build provide feature preview, which is not go through the whole validation process, which may not reach product quality. 80 | 81 | #### PYPI 82 | ``` 83 | python -m pip install -U pip 84 | python -m pip install openvino-nightly 85 | ``` 86 | #### Bulid OpenVINO github master from source 87 | ##### Build OpenVINO on Linux: 88 | ```bash 89 | git clone https://github.com/openvinotoolkit/openvino.git 90 | cd openvino && git submodule update --init --recursive 91 | python -m pip install -U pip 92 | python -m pip install -r ./src/bindings/python/src/compatibility/openvino/requirements-dev.txt 93 | python -m pip install -r ./src/bindings/python/wheel/requirements-dev.txt 94 | python -m pip install -r ./src/bindings/python/requirements.txt 95 | mkdir build && cd build 96 | cmake -DENABLE_INTEL_GNA=OFF -DENABLE_PYTHON=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX= .. 97 | make --jobs=$(nproc --all) 98 | make install 99 | cd /tools/ 100 | python -m pip install openvino*.whl 101 | ``` 102 | 103 | ##### Build OpenVINO on Windows: 104 | ```bash 105 | git clone https://github.com/openvinotoolkit/openvino.git 106 | cd openvino && git submodule update --init --recursive 107 | python -m pip install -U pip 108 | python -m pip install -r ./src/bindings/python/src/compatibility/openvino/requirements-dev.txt 109 | python -m pip install -r ./src/bindings/python/wheel/requirements-dev.txt 110 | python -m pip install -r ./src/bindings/python/requirements.txt 111 | mkdir build && cd build 112 | cmake -G "Visual Studio 17 2022" -DENABLE_INTEL_GNA=OFF -DENABLE_PYTHON=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX= .. 113 | cmake --build . --config Release --verbose -j8 114 | cmake --install . 115 | cd /tools/ 116 | python -m pip install openvino*.whl 117 | ``` 118 | 119 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2018-2023 Intel Corporation 3 | # SPDX-License-Identifier: Apache-2.0 4 | from threading import Event, Thread 5 | import psutil, time, os 6 | from datetime import timedelta 7 | import numpy as np 8 | 9 | def print_perf_counters(perf_counts_list): 10 | max_print_length = 20 11 | for ni in range(len(perf_counts_list)): 12 | perf_counts = perf_counts_list[ni] 13 | total_time = timedelta() 14 | total_time_cpu = timedelta() 15 | print(f"Performance counts for {ni}-th infer request") 16 | for pi in perf_counts: 17 | print(f"{pi.node_name[:max_print_length - 4] + '...' if (len(pi.node_name) >= max_print_length) else pi.node_name:<20} " 18 | f"{str(pi.status):<20} " 19 | f"layerType: {pi.node_type[:max_print_length - 4] + '...' if (len(pi.node_type) >= max_print_length) else pi.node_type:<20} " 20 | f"execType: {pi.exec_type:<20} " 21 | f"realTime (ms): {pi.real_time / timedelta(milliseconds=1):<10.3f} " 22 | f"cpuTime (ms): {pi.cpu_time / timedelta(milliseconds=1):<10.3f}") 23 | 24 | total_time += pi.real_time 25 | total_time_cpu += pi.cpu_time 26 | print(f'Total time: {total_time / timedelta(milliseconds=1)} milliseconds') 27 | print(f'Total CPU time: {total_time_cpu / timedelta(milliseconds=1)} milliseconds\n') 28 | 29 | def print_detail_result(result_list): 30 | """ Print_perf_counters_sort result 31 | """ 32 | max_print_length = 20 33 | for tmp_result in result_list: 34 | node_name = tmp_result[0] 35 | layerStatus = tmp_result[1] 36 | layerType = tmp_result[2] 37 | real_time = tmp_result[3] 38 | cpu_time = tmp_result[4] 39 | real_proportion = "%.2f" % (tmp_result[5] * 100) 40 | if real_proportion == "0.00": 41 | real_proportion = "N/A" 42 | execType = tmp_result[6] 43 | print(f"{node_name[:max_print_length - 4] + '...' if (len(node_name) >= max_print_length) else node_name:<20} " 44 | f"{str(layerStatus):<20} " 45 | f"layerType: {layerType[:max_print_length - 4] + '...' if (len(layerType) >= max_print_length) else layerType:<20} " 46 | f"execType: {execType:<20} " 47 | f"realTime (ms): {real_time / 1000:<10.3f} " 48 | f"cpuTime (ms): {cpu_time / 1000:<10.3f}" 49 | f"proportion: {str(real_proportion +'%'):<8}") 50 | 51 | def print_perf_counters_sort(perf_counts_list,sort_flag="sort"): 52 | """ Print opts time cost and can be sorted according by each opts time cost 53 | """ 54 | for ni in range(len(perf_counts_list)): 55 | perf_counts = perf_counts_list[ni] 56 | total_time = timedelta() 57 | total_time_cpu = timedelta() 58 | print(f"Performance counts sorted for {ni}-th infer request") 59 | for pi in perf_counts: 60 | total_time += pi.real_time 61 | total_time_cpu += pi.cpu_time 62 | 63 | total_time = total_time.microseconds 64 | total_time_cpu = total_time_cpu.microseconds 65 | total_real_time_proportion = 0 66 | total_detail_data=[] 67 | for pi in perf_counts: 68 | node_name = pi.node_name 69 | layerStatus = pi.status 70 | layerType = pi.node_type 71 | real_time = pi.real_time.microseconds 72 | cpu_time = pi.cpu_time.microseconds 73 | real_proportion = round(real_time/total_time,4) 74 | execType = pi.exec_type 75 | tmp_data=[node_name,layerStatus,layerType,real_time,cpu_time,real_proportion,execType] 76 | total_detail_data.append(tmp_data) 77 | total_real_time_proportion += real_proportion 78 | total_detail_data = np.array(total_detail_data) 79 | if sort_flag=="sort": 80 | total_detail_data = sorted(total_detail_data,key=lambda tmp_data:tmp_data[-4],reverse=True) 81 | elif sort_flag=="no_sort": 82 | total_detail_data = total_detail_data 83 | elif sort_flag=="simple_sort": 84 | total_detail_data = sorted(total_detail_data,key=lambda tmp_data:tmp_data[-4],reverse=True) 85 | total_detail_data = [tmp_data for tmp_data in total_detail_data if str(tmp_data[1])!="Status.NOT_RUN"] 86 | print_detail_result(total_detail_data) 87 | print(f'Total time: {total_time / 1000:.3f} milliseconds') 88 | print(f'Total CPU time: {total_time_cpu / 1000:.3f} milliseconds') 89 | print(f'Total proportion: {"%.2f"%(round(total_real_time_proportion)*100)} % \n') 90 | return total_detail_data 91 | 92 | ''' 93 | class MemConsumption: 94 | def __init__(self): 95 | """Initialize MemConsumption.""" 96 | self.g_exit_get_mem_thread = False 97 | self.g_end_collect_mem = False 98 | self.g_max_rss_mem_consumption = -1 99 | self.g_max_shared_mem_consumption = -1 100 | self.g_event = Event() 101 | self.g_data_event = Event() 102 | 103 | def collect_memory_consumption(self): 104 | """Collect the data.""" 105 | while self.g_exit_get_mem_thread is False: 106 | self.g_event.wait() 107 | while True: 108 | process = psutil.Process(os.getpid()) 109 | rss_mem_data = process.memory_info().rss / float(2**20) 110 | try: 111 | shared_mem_data = process.memory_info().shared / float(2**20) 112 | except Exception: 113 | shared_mem_data = -1 114 | if rss_mem_data > self.g_max_rss_mem_consumption: 115 | self.g_max_rss_mem_consumption = rss_mem_data 116 | if shared_mem_data > self.g_max_shared_mem_consumption: 117 | self.g_max_shared_mem_consumption = shared_mem_data 118 | self.g_data_event.set() 119 | if self.g_end_collect_mem is True: 120 | self.g_event.set() 121 | self.g_event.clear() 122 | self.g_end_collect_mem = False 123 | break 124 | time.sleep(500 / 1000) 125 | 126 | def start_collect_memory_consumption(self): 127 | """Start collect.""" 128 | self.g_end_collect_mem = False 129 | self.g_event.set() 130 | 131 | def end_collect_momory_consumption(self): 132 | """Stop collect.""" 133 | self.g_end_collect_mem = True 134 | self.g_event.wait() 135 | 136 | def get_max_memory_consumption(self): 137 | """Return the data.""" 138 | self.g_data_event.wait() 139 | self.g_data_event.clear() 140 | return self.g_max_rss_mem_consumption, self.g_max_shared_mem_consumption 141 | 142 | def clear_max_memory_consumption(self): 143 | """Clear MemConsumption.""" 144 | self.g_max_rss_mem_consumption = -1 145 | self.g_max_shared_mem_consumption = -1 146 | 147 | def start_collect_mem_consumption_thread(self): 148 | """Start the thread.""" 149 | self.t_mem_thread = Thread(target=self.collect_memory_consumption) 150 | self.t_mem_thread.start() 151 | 152 | def end_collect_mem_consumption_thread(self): 153 | """End the thread.""" 154 | self.g_event.set() 155 | self.g_data_event.set() 156 | self.g_end_collect_mem = True 157 | self.g_exit_get_mem_thread = True 158 | self.t_mem_thread.join() 159 | ''' 160 | -------------------------------------------------------------------------------- /inference_engine.py: -------------------------------------------------------------------------------- 1 | import time 2 | from transformers import AutoTokenizer, TextIteratorStreamer, AutoConfig, GenerationConfig 3 | import gc 4 | from optimum.intel.openvino import OVModelForCausalLM 5 | from threading import Thread, Event 6 | from time import perf_counter 7 | from typing import List 8 | import numpy as np 9 | from modeling import OVQwenModel, OVChatGLM2Model 10 | from utils import print_perf_counters_sort 11 | 12 | """ 13 | from utils import MemConsumption 14 | mem_consumption = MemConsumption() 15 | max_rss_mem_consumption = '' 16 | max_shared_mem_consumption = '' 17 | """ 18 | 19 | 20 | class InferenceEngine: 21 | def __init__(self, args=None, ov_config=None): 22 | self.args = args 23 | 24 | self.config = AutoConfig.from_pretrained( 25 | self.args.model_id, trust_remote_code=True) 26 | s = time.time() 27 | if self.config.model_type == "llama": 28 | print("Loading Llama2 model") 29 | self.tokenizer = AutoTokenizer.from_pretrained( 30 | self.args.model_id, trust_remote_code=True) 31 | 32 | self.ov_model = OVModelForCausalLM.from_pretrained(self.args.model_id, 33 | compile=False, 34 | device=self.args.device, 35 | ov_config=ov_config, 36 | trust_remote_code=True) 37 | 38 | elif self.config.model_type == "chatglm": 39 | print("Loading ChatGLM2 model") 40 | self.tokenizer = AutoTokenizer.from_pretrained( 41 | self.args.model_id, 42 | padding_side='left', 43 | trust_remote_code=True) 44 | self.ov_model = OVChatGLM2Model.from_pretrained(self.args.model_id, 45 | config=self.config, 46 | compile=False, 47 | device=self.args.device, 48 | pad_token_id=self.tokenizer.pad_token_id, 49 | ov_config=ov_config, 50 | trust_remote_code=True) 51 | 52 | elif self.config.model_type == "qwen": 53 | print("Loading Qwen model") 54 | self.tokenizer = AutoTokenizer.from_pretrained( 55 | self.args.model_id, 56 | pad_token='<|extra_0|>', 57 | eos_token='<|endoftext|>', 58 | padding_side='left', 59 | trust_remote_code=True) 60 | 61 | self.ov_model = OVQwenModel.from_pretrained(self.args.model_id, 62 | config=self.config, 63 | compile=False, 64 | device=self.args.device, 65 | ov_config=ov_config, 66 | pad_token_id=self.tokenizer.pad_token_id, 67 | trust_remote_code=True) 68 | self.ov_model.generation_config = GenerationConfig.from_pretrained(self.args.model_id, pad_token_id=self.tokenizer.pad_token_id) 69 | 70 | print("read model time: {:.3f} s".format(time.time() - s)) 71 | 72 | s = time.time() 73 | self.ov_model.compile() 74 | print("compile model time: {:.3f} s".format(time.time() - s)) 75 | 76 | print("intial model successed") 77 | gc.collect() 78 | 79 | def chat_stream(self, text): 80 | print("Original input text: ", text) 81 | if self.args.use_prompt_template: 82 | text = self.build_inputs(text) 83 | print("Updated input text with model specific prompt template:\n", text) 84 | prompt=text 85 | self.model_inputs = self.tokenizer(prompt, return_tensors="pt") 86 | self.model_inputs.pop("token_type_ids", None) 87 | streamer = TextIteratorStreamer(self.tokenizer, 88 | skip_prompt=True, 89 | skip_special_tokens=True) 90 | generate_kwargs = dict(self.model_inputs, 91 | streamer=streamer, 92 | max_new_tokens=self.args.max_new_tokens, 93 | do_sample=self.args.do_sample, 94 | top_p=self.args.top_p, 95 | temperature=self.args.temperature, 96 | top_k=self.args.top_k, 97 | repetition_penalty=self.args.repetition_penalty, 98 | eos_token_id=self.tokenizer.eos_token_id) 99 | stream_complete = Event() 100 | 101 | def generate_and_signal_complete(): 102 | """ 103 | genration function for single thread 104 | """ 105 | self.ov_model.generate(**generate_kwargs) 106 | stream_complete.set() 107 | 108 | # t = Thread(target=self.ov_model.generate, kwargs=generate_kwargs) 109 | t = Thread(target=generate_and_signal_complete) 110 | t.start() 111 | 112 | # Pull the generated text from the streamer, and update the model output. 113 | model_output = "" 114 | perf_text = "" 115 | per_token_time = [] 116 | tokens_per_second = [] 117 | 118 | num_tokens = 0 119 | start = perf_counter() 120 | 121 | for new_text in streamer: 122 | if len(new_text) == 0: 123 | continue 124 | current_time = perf_counter() - start 125 | if num_tokens == 0: 126 | print(f"first token time: {current_time:.3f} s") 127 | perf_text, num_tokens, current_tokens_per_second = self.estimate_latency(current_time, perf_text, 128 | new_text, per_token_time, 129 | num_tokens) 130 | if current_tokens_per_second is not None: tokens_per_second.append(current_tokens_per_second) 131 | yield new_text 132 | start = perf_counter() 133 | 134 | self.generate_num_tokens = num_tokens 135 | print("Skip last average token per second to avoid outlier") 136 | self.average_tokens_per_second = np.mean(tokens_per_second[:-1]) 137 | gc.collect() 138 | # torch.cuda.empty_cache() 139 | 140 | def generate(self, text): 141 | ''' 142 | if self.args.enable_memory_profiling: 143 | mem_consumption.start_collect_memory_consumption() 144 | ''' 145 | out = "" 146 | for output in self.chat_stream(text): 147 | out += output 148 | print(f"Input num tokens: {len(self.model_inputs.input_ids[0])}, generated num tokens: {self.generate_num_tokens}") 149 | print(f"Total average generaton speed: {self.average_tokens_per_second:.3f} tokens/s") 150 | print(f"Generated response: {out}") 151 | # yield output 152 | ''' 153 | if self.args.enable_memory_profiling: 154 | mem_consumption.end_collect_momory_consumption() 155 | max_rss_mem_consumption, max_shared_mem_consumption = mem_consumption.get_max_memory_consumption() 156 | mem_consumption.clear_max_memory_consumption() 157 | print("Max RSS memory consumption: ", max_rss_mem_consumption) 158 | print("Max Shared memory consumption: ", max_shared_mem_consumption) 159 | ''' 160 | 161 | def build_inputs(self, query): 162 | prompt = None 163 | 164 | if self.config.model_type == "llama": 165 | system_message = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions." 166 | prompt = f"[INST] <>\n{system_message}\n<>\n\n{query} [/INST]" 167 | 168 | elif self.config.model_type == "chatglm": 169 | if "chatglm2" in self.args.model_id.lower(): 170 | prompt = f"[Round 0]\n\n问:{query}\n\n答:\n\n" 171 | elif "chatglm3" in self.args.model_id.lower(): 172 | system_message = "You are ChatGLM3, a large language model trained by Zhipu.AI. Follow the user's instructions carefully. Respond using markdown." 173 | prompt = f"<|system|>\n{system_message}\n<|user|>{query}<|assistant|>" 174 | 175 | elif self.config.model_type == "qwen": 176 | im_start = "<|im_start|>" 177 | im_end = "<|im_end|>" 178 | system_message = "You are a helpful assistant." 179 | query = query.lstrip("\n").rstrip() 180 | prompt = f"{im_start}system\n{system_message}{im_end}" 181 | prompt += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n" 182 | 183 | return prompt 184 | 185 | def estimate_latency(self, current_time: float, current_perf_text: str, 186 | new_gen_text: str, per_token_time: List[float], 187 | num_tokens: int): 188 | """ 189 | Helper function for performance estimation 190 | 191 | Parameters: 192 | current_time (float): This step time in seconds. 193 | current_perf_text (str): Current content of performance UI field. 194 | new_gen_text (str): New generated text. 195 | per_token_time (List[float]): history of performance from previous steps. 196 | num_tokens (int): Total number of generated tokens. 197 | 198 | Returns: 199 | update for performance text field 200 | update for a total number of tokens 201 | """ 202 | current_tokens = self.tokenizer.encode(new_gen_text, add_special_tokens=False) 203 | num_current_toks = len(current_tokens) 204 | 205 | num_tokens += num_current_toks 206 | per_token_time.append(num_current_toks / current_time) 207 | if len(per_token_time) > 10 and len(per_token_time) % 4 == 0: 208 | current_bucket = per_token_time[-10:] 209 | tokens_per_second = np.mean(current_bucket) 210 | current_perf_text = f"Average generaton speed: {tokens_per_second:.2f} tokens/s. Total generated tokens: {num_tokens}" 211 | print(current_perf_text) 212 | return current_perf_text, num_tokens, tokens_per_second 213 | return current_perf_text, num_tokens, None 214 | 215 | def get_profiling_data(self): 216 | perfs_count_list = self.ov_model.request.profiling_info 217 | total_sorted_list = print_perf_counters_sort( 218 | [perfs_count_list], sort_flag="simple_sort") 219 | 220 | return total_sorted_list 221 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /benchmark.py: -------------------------------------------------------------------------------- 1 | from inference_engine import InferenceEngine 2 | from openvino.runtime import properties, get_version 3 | import argparse 4 | import gc 5 | 6 | chinese_sentence = { 7 | "9": "介绍下清华大学", 8 | "32":"若我有一亿美元,在人工智能盛行的今天,我怎样投资才能收益最大化?", 9 | "256":"糕点商店里原本有三种蛋糕:草莓奶油蛋糕,巧克力椰蓉蛋糕,和红丝绒布朗尼蛋糕。如名字所描述的那样,每种蛋糕都有两种成分:草莓奶油蛋糕包含草莓和奶油两个成分,巧克力椰蓉蛋糕包含巧克力和椰蓉两种成分,红丝绒布朗尼蛋糕包含红丝绒和布朗尼两种成分。在蛋糕制作完成后,往往每>种成分的材料都会有所剩余。为了减少浪费,商店常常会把多出来的成分两两搭配,做成新的小商品卖出去。比如草莓和巧克力可以做成草莓味巧克力酱,布朗尼和椰蓉可以做成布朗尼椰蓉饼干。以此类推可知,如果所有的成分都可以两两组合,那么最终商店能做出哪些小商品出来?", 10 | "512":"桌子有左中右3个抽屉;张三,李四,王五,赵六都看到桌子上有一袋巧克力。张三让李四和王五出门后,在赵六面前把这袋巧克力放进了右抽屉;王五回来后,张三让赵六出门去找李四,并在王五面前从左抽屉拿出一盒饼干放进中抽屉里;等李四和赵六返回,张三又让王五和赵六出去买酱油,等二人走后,他告诉李四刚才已将一盒饼干放进中抽屉;张三等了很久,发现王五和赵六还没回来,就派李四去寻找,可最后只有王五和李四回来了。王五告诉张三,一开始他们没有找到卖酱油的店,所以只好分头去买,后来赵六走丢了;回来的路上,王五碰上了李四,两人便先赶了回来。于是,张三让两人出门去找赵六;为防再次走丢,张三叮嘱李四和王五要时刻同行,就算酱油买不到,也要找回赵六。结果,李四和王五在外面找到了赵六,发现他已经买了酱油。三人觉得张三从来不出门跑腿,十分气愤,讨论并达成共识,回去见到张三后,不要告诉他买到了酱油的事情,并让王五把酱油藏到自己的背包里。等三人一同回来后,他们按照计划谎称没有买到酱油,并希望张三以后买东西也要一同出门,不能偷懒,张三答应了。当大家最后站在桌子前,四人分别写下自己知道的物品清单和物品所在位置。问,这四人写下的物品和位置信息是否一致,为什么?", 11 | "1024":"折纸的过程看似简单,其实想要做好,还是需要一套很复杂的工艺。以折一支玫瑰花为例,我们可以将整个折纸过程分成三个阶段,即:创建栅格折痕,制作立体基座,完成花瓣修饰。首先是创建栅格折痕:这一步有点像我们折千纸鹤的第一步,即通过对称州依次对折,然后按照长和宽两个维度,依次进行多等分的均匀折叠;最终在两个方向上的折痕会交织成一套完整均匀的小方格拼接图案;这些小方格就组成了类似二维坐标系的参考系统,使得我们在该平面上,通过组合临近折痕的方式从二维小方格上折叠出三维的高台或凹陷,以便于接下来的几座制作过程。需要注意的是,在建立栅格折痕的过程中,可能会出现折叠不对成的情况,这种错误所带来的后果可能是很严重的,就像是蝴蝶效应,一开始只是毫厘之差,最后可能就是天壤之别。然后是制作立体基座:在这一步,我们需要基于栅格折痕折出对称的三维高台或凹陷。从对称性分析不难发现,玫瑰花会有四个周对称的三维高台和配套凹陷。所以,我们可以先折出四分之一的凹陷和高台图案,然后以这四分之一的部分作为摸板,再依次折出其余三个部分的重复图案。值得注意的是,高台的布局不仅要考虑长和宽这两个唯独上的规整衬度和对称分布,还需要同时保证高这个维度上的整齐。与第一阶段的注意事项类似,请处理好三个维度上的所有折角,确保它们符合计划中所要求的那种布局,以免出现三维折叠过程中的蝴蝶效应;为此,我们常常会在折叠第一个四分之一图案的过程中,与成品玫瑰花进行反复比较,以便在第一时间排除掉所有可能的错误。最后一个阶段是完成花瓣修饰。在这个阶段,我们往往强调一个重要名词,叫用心折叠。这里的用心已经不是字面上的认真这个意思,而是指通过我们对于大自然中玫瑰花外型的理解,借助自然的曲线去不断修正花瓣的形状,以期逼近现实中的玫瑰花瓣外形。请注意,在这个阶段的最后一步,我们需要通过拉扯已经弯折的四个花瓣,来调整玫瑰花中心的绽放程度。这个过程可能会伴随玫瑰花整体结构的崩塌,所以,一定要控制好调整的力道,以免出现不可逆的后果。最终,经过三个阶段的折叠,我们会得到一支栩栩如生的玫瑰花冠。如果条件允许,我们可以在一根拉直的铁丝上缠绕绿色纸条,并将玫瑰花冠插在铁丝的一段。这样,我们就得到了一支手工玫瑰花。总之,通过创建栅格折痕,制作立体基座,以及完成花瓣修饰,我们从二维的纸面上创作出了一支三维的花朵。这个过程虽然看似简单,但它确实我们人类借助想象力和常见素材而创作出的艺术品。请赏析以上内容的精妙之处。" 12 | } 13 | 14 | english_sentence = { 15 | "9": "What is OpenVINO?", 16 | "32": "If I have 100 million dollars, what kinds of projects should I invest to maximize my benefits in background of a growing number of artificial intelligence technologies?", 17 | "256": "Originally, There were three types of cake in the cake store: Strawberry Cream Cake, Chocolate Coconut Cake, and Red Velvet Brownie Cake. Customer number is large enough so that no cake would be left every day when the store close. As the name suggested, each cake has two ingredients: Strawberry Cream Cake with strawberries and cream, Chocolate Coconut Cake with chocolate and coconut, and Red Velvet Brownie Cake with red velvet and brownie. Different ingredients can be compatibly mixed with each other without any issue. After the cake is made, there are often some leftover materials for each ingredient. In order to reduce waste, the store often combine the extra ingredients in pairs to make new small gifts to gain extra sales. For example, strawberries and chocolate can be mixed to create strawberry-flavored chocolate sauce, and brownies and shredded coconut can be mixed to create brownie coconut cookies. Only two ingredients can be mixed, and mixture with more than two ingredients can cost a lot of time and will not be adopted. In order to decrease the problem complexity, the store will also prevent from careful decorations or other difficult steps as in procedure of making cakes, so that time cost can be omited. By analogy, if all the ingredients can be combined in pairs, what small products can the store make in the end?", 18 | "512": "There is a table, which contains three drawers: left drawer, middle drawer and right drawer; Tom Ethan, Elbert Alex, Jack Johnson, and Mario Thompson all saw a bag of chocolates on the table. Tom Ethan asked Elbert Alex and Jack Johnson to go out, and after that, he put the bag of chocolates in the right drawer in front of Mario Thompson; after Jack Johnson came back, Tom Ethan asked Mario Thompson to go out to find Elbert Alex, and took it from the left drawer in front of Jack Johnson. Then He take out a box of biscuits and put them in the middle drawer; when Elbert Alex and Mario Thompson returned, Tom Ethan asked Jack Johnson and Mario Thompson to go out to buy a bottle of soy sauce. Tom Ethan waited for a long time, and found that Jack Johnson and Mario Thompson had not returned, so he sent Elbert Alex to look for them, but in the end only Jack Johnson and Elbert Alex came back. Jack Johnson told Tom Ethan that at first they could not find any shop that is providing soy sauce, so they had to separate to search other shops, which is why Mario Thompson got lost; on the way back, Jack Johnson ran into Elbert Alex, and they rushed back first. Therefore, Tom Ethan asked them to go out to find Mario Thompson again; in order to prevent getting lost again, Tom Ethan told Elbert Alex and Jack Johnson to walk together at all time, and even if they could not get the soy sauce, they had to find and get back with Mario Thompson. As a result, Elbert Alex and Jack Johnson found Mario Thompson outside and found that he had bought a bottle of soy sauce. The three felt that Tom Ethan never went out to do anthing but they are busy all the time. So they were very angry. They discussed and made a conclusion. After going back to see Tom Ethan, they should not tell him about the soy sauce they bought, and asked Jack Johnson to hide the soy sauce in his backpack. After the three of them came back together, they pretended to claim that they did not foudn and bought soy sauce according to the plan, and hoped that Tom Ethan would go out together to buy things in the future, and he should not be so lazy. Tom Ethan agreed and felt sory about that. When everyone finally stood in front of the table, the four of them wrote down the list of items they knew and the location of the items. So the question is: is the information writen by these four people consistent, and why?", 19 | "1024": "The process of Origami seems simple at the first glance, but in fact, it still requires a very complicated process to do it well. Taking folding a rose as an example, we can divide the entire process into three stages, including: firstly creating a grid of creases, secondly making a three-dimensional base, and thirdly finishing petal decoration. The first step is to create a grid of creases: this step is a bit like the first step of folding a gift of thousand-paper-crane. That is to say, we can fold the paper in half (or namedly equal-folds) through the symmetrical axis, and repeat such step in the other symmetrical axis. And then apply multiple equal-folds in sequence relative to each smaller rectangle divided by the two creases; After that, the creases in each direction will interweave into a complete set of uniform small square splicing patterns; these small squares form a reference space similar to a two-dimensional coordinate system, allowing us to combine adjacent creases on the plane from Three-dimensional high platforms or depressions are folded on the two-dimensional small squares to facilitate the next steps of folding. It should be noted that, in the process of creating grid creases, there may be rare cases when the folds are not aligned. The consequences of this error can be very serious. And just like the butterfly effect, it is only a slight difference at the beginning , and in the end it may generate a disaster world which is completely different from plan. Anyway, let's continue. The second step is make the three-dimensional base: In this step, we need to fold a set of symmetrical three-dimensional high platforms or depressions based on the grid creases. From the symmetry analysis, it is not difficult to find that the rose will have four symmetrical three-dimensional high platforms and supporting depressions. Therefore, we can firstly fold out a quarter of the depression and plateau patterns, which would help build a base to compose into a complex 3D structure. And then, we use this quarter as a template, and fold out the repeating patterns on the remaining three parts of the whole structure in turn. It is worth noting that the layout of the high platform not only needs to consider the regular contrast and symmetrical distribution of the length and width, but also needs to ensure the orderliness of the height dimension. This is very important, since we will never go back to this step after all parts were made, and you would better start from first step if you make anything wrong in the this step. Similar to the precautions in the first stage, please handle all the corners in three dimensions to ensure that they conform to the layout required in the plan, which would help us avoid the butterfly effect and increase the robustness in the process of three-dimensional folding. Just like building a skyscrapper in the real world, people usually take a lot of time when building the base but soon get finished when extending the structure after that. Time is worth to cost in the base, but would be saved in the future after you succeed in base. Anyway, let's continue. During the first quarter of the pattern, repeated comparisons with the finished rose were made to eliminate any possible errors in the first place. The final stage is to finish the petal grooming. At this stage, we often emphasize an important term called folding-by-heart. The intention here is no longer literally serious, but focus is moved to our understanding of the shape of a rose in nature, and we usually use natural curves to continuously correct the shape of petals in order to approach the shape of rose petals in reality. One more comment: this is also the cause of randomness to the art, which can be generated differently by different people. Recall that rose should be adjusted close to reality, so in the last step of this stage, we need to open the bloom in the center of the rose, by pulling on the four petals that have been bent. This process may be accompanied by the collapse of the overall structure of the rose, so we should be very careful to save strength of adjustment, and it must be well controlled to avoid irreversible consequences. Ultimately, after three stages of folding, we end up with a crown of rose with a similar shape close to reality. If condition is permited, we can wrap a green paper strip twisted on a straightened iron wire, and insert the rose crown we just created onto one side of the iron wire. In this way, we got a hand-made rose with a green stem. We can also repeat the steps above to increase the number of rose, so that it can be made into a cluster. Different color of rose is usually more attractive and can be considered as a better plan of gift to your friend. In summary, by creating a grid of creases, making a three-dimensional base, and finishing with petals, we created a three-dimensional rose from a two-dimensional paper. Although this process may seem simple, it is indeed a work of art created by us humans with the help of imagination and common materials. At last, Please comment to assess the above content.", 20 | } 21 | 22 | if __name__ == "__main__": 23 | parser = argparse.ArgumentParser( 24 | 'LLM benchmarking tool', add_help=True, formatter_class=argparse.RawTextHelpFormatter) 25 | parser.add_argument( 26 | '-m', '--model_id', help='model folder including OpenVINO IR files', required=TabError) 27 | parser.add_argument( 28 | '-d', '--device', default='CPU', help='inference device') 29 | parser.add_argument( 30 | '-p', '--prompt', default="", type=str, help='one prompt') 31 | parser.add_argument( 32 | '-pl', '--prompt_length', default=9, type=int, help='Input prompt length for text generation') 33 | # parser.add_argument( 34 | # '-pf', '--prompt_file', default=None, help='Prompt file in jsonl format') 35 | parser.add_argument( 36 | '-mnt', '--max_new_tokens', default=256, type=int, help="Limit the max new generated token count") 37 | parser.add_argument( 38 | '-tp', '--top_p', default=0.92, type=float, help="Top P for text generation") 39 | parser.add_argument( 40 | '-ds', '--do_sample', default=1, type=int, help="Wether do sample for text generation") 41 | parser.add_argument( 42 | '-t', '--temperature', default=0.1, type=float, help="Temperature for text generation") 43 | parser.add_argument( 44 | '-tk', '--top_k', default=0, type=int, help="Top K for text generation") 45 | parser.add_argument( 46 | '-rp', '--repetition_penalty', default=1.0, type=float, help="Penalize tokens based on how frequently they occur in the text, default 1 means no penalty") 47 | parser.add_argument( 48 | '-cb', '--enable_cpu_pinning', default=1, type=int, help="Whether to enable OpenVINO cpu pinning") 49 | parser.add_argument( 50 | '-ht', '--enable_hyper_threading', default=0, type=int, help="Whether to enable OpenVINO CPU hyper threading") 51 | parser.add_argument( 52 | '-cd', '--cache_dir', default="model_cache", type=str, help="Cache diretory to save OpenVINO model cache") 53 | parser.add_argument( 54 | '-pp', '--enable_perf_profiling', default=0, type=int, help="Whether to enable OpenVINO performance profiling") 55 | parser.add_argument( 56 | '-pt', '--use_prompt_template', default=1, type=int, help="Whether to use model related prompt template") 57 | parser.add_argument( 58 | '-l', '--language', default="english", type=str, help="Specifiy to use which language for test input prompt, avaliable option inculde 'english', 'en', 'chinese', ch") 59 | parser.add_argument("--bf16", action="store_true", help="Whether to enable bf16 inference precision on SPR or later Xeon platform") 60 | #parser.add_argument( 61 | # '-mp', '--enable_mem_profiling', default=False, type=bool, help="Whether to enable memory profiling") # Not work now, need to fix 62 | 63 | args = parser.parse_args() 64 | 65 | ov_config = None 66 | if "CPU" in args.device.upper(): 67 | ov_config = {properties.cache_dir(): args.cache_dir, 68 | properties.hint.scheduling_core_type(): properties.hint.SchedulingCoreType.PCORE_ONLY, 69 | properties.hint.enable_hyper_threading(): True if args.enable_hyper_threading else False, 70 | properties.hint.enable_cpu_pinning(): True if args.enable_cpu_pinning else False, 71 | properties.hint.inference_precision(): "bf16" if args.bf16 else "f32", 72 | properties.enable_profiling(): "YES" if args.enable_perf_profiling else "NO", 73 | } 74 | 75 | if "GPU" in args.device.upper(): 76 | ov_config = {properties.cache_dir(): args.cache_dir, 77 | properties.intel_gpu.hint.queue_throttle(): properties.intel_gpu.hint.ThrottleLevel.MEDIUM, 78 | properties.intel_gpu.hint.queue_priority(): properties.hint.Priority.MEDIUM, 79 | properties.intel_gpu.hint.host_task_priority(): properties.hint.Priority.HIGH, 80 | properties.hint.enable_cpu_pinning(): True if args.enable_cpu_pinning else False, 81 | properties.enable_profiling(): "YES" if args.enable_perf_profiling else "NO", 82 | } 83 | print(f"OpenVINO version: {get_version()}\nargs: {args}\nov_config: {ov_config}") 84 | engine = InferenceEngine(args, ov_config) 85 | # Use user input prmpt 86 | if args.prompt: 87 | engine.generate(args.prompt) 88 | # Use predefined input prompt 89 | else: 90 | prompt = None 91 | if args.language.lower() == "english" or args.language.lower() == "en": 92 | prompt = english_sentence[str(args.prompt_length)] 93 | elif args.language.lower() == "chinese" or args.language.lower() == "ch": 94 | prompt = chinese_sentence[str(args.prompt_length)] 95 | engine.generate(prompt) 96 | if args.enable_perf_profiling: 97 | total_sorted_list = engine.get_profiling_data() 98 | del engine 99 | gc.collect() 100 | -------------------------------------------------------------------------------- /modeling.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import Optional, Union, Dict, List, Tuple, Callable, Iterable 3 | import numpy as np 4 | import torch 5 | from optimum.intel.openvino import OVModelForCausalLM 6 | from optimum.utils import NormalizedTextConfig, NormalizedConfigManager 7 | from openvino.runtime import Model, Core, Tensor, Type 8 | from transformers import PretrainedConfig 9 | from optimum.intel.openvino.utils import ONNX_WEIGHTS_NAME, OV_XML_FILE_NAME 10 | from tempfile import TemporaryDirectory 11 | from transformers.modeling_outputs import CausalLMOutputWithPast 12 | from transformers import GenerationConfig, StoppingCriteriaList 13 | from transformers.generation.logits_process import LogitsProcessorList, LogitsProcessor 14 | from transformers.generation.utils import GenerateOutput 15 | 16 | 17 | class StopWordsLogitsProcessor(LogitsProcessor): 18 | """ 19 | :class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration. 20 | Args: 21 | stop_words_ids (:obj:`List[List[int]]`): 22 | List of list of token ids of stop ids. In order to get the tokens of the words 23 | that should not appear in the generated text, use :obj:`tokenizer(bad_word, 24 | add_prefix_space=True).input_ids`. 25 | eos_token_id (:obj:`int`): 26 | The id of the `end-of-sequence` token. 27 | """ 28 | 29 | def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int): 30 | 31 | if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0: 32 | raise ValueError( 33 | f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}." 34 | ) 35 | if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids): 36 | raise ValueError( 37 | f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}." 38 | ) 39 | if any( 40 | any( 41 | (not isinstance(token_id, (int, np.integer)) or token_id < 0) 42 | for token_id in stop_word_ids 43 | ) 44 | for stop_word_ids in stop_words_ids 45 | ): 46 | raise ValueError( 47 | f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}." 48 | ) 49 | 50 | self.stop_words_ids = list( 51 | filter( 52 | lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids 53 | ) 54 | ) 55 | self.eos_token_id = eos_token_id 56 | for stop_token_seq in self.stop_words_ids: 57 | assert ( 58 | len(stop_token_seq) > 0 59 | ), "Stop words token sequences {} cannot have an empty list".format( 60 | stop_words_ids 61 | ) 62 | 63 | def __call__( 64 | self, input_ids: torch.LongTensor, scores: torch.FloatTensor 65 | ) -> torch.FloatTensor: 66 | stopped_samples = self._calc_stopped_samples(input_ids) 67 | for i, should_stop in enumerate(stopped_samples): 68 | if should_stop: 69 | scores[i, self.eos_token_id] = float(2**15) 70 | return scores 71 | 72 | def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool: 73 | if len(tokens) == 0: 74 | # if bad word tokens is just one token always ban it 75 | return True 76 | elif len(tokens) > len(prev_tokens): 77 | # if bad word tokens are longer then prev input_ids they can't be equal 78 | return False 79 | elif prev_tokens[-len(tokens) :].tolist() == tokens: 80 | # if tokens match 81 | return True 82 | else: 83 | return False 84 | 85 | def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]: 86 | stopped_samples = [] 87 | for prev_input_ids_slice in prev_input_ids: 88 | match = False 89 | for stop_token_seq in self.stop_words_ids: 90 | if self._tokens_match(prev_input_ids_slice, stop_token_seq): 91 | # if tokens do not match continue 92 | match = True 93 | break 94 | stopped_samples.append(match) 95 | 96 | return stopped_samples 97 | 98 | 99 | class OVQwenModel(OVModelForCausalLM): 100 | def __init__( 101 | self, 102 | model: Model, 103 | config: PretrainedConfig = None, 104 | device: str = 'CPU', 105 | dynamic_shapes: bool = True, 106 | ov_config: Optional[Dict[str, str]] = None, 107 | model_save_dir: Optional[Union[str, Path, TemporaryDirectory]] = None, 108 | **kwargs, 109 | ): 110 | NormalizedConfigManager._conf['qwen'] = NormalizedTextConfig.with_args( 111 | num_layers='num_layers', num_attention_heads='num_attention_heads') 112 | super().__init__(model, config, device, dynamic_shapes, 113 | ov_config, model_save_dir, **kwargs) 114 | 115 | def _reshape( 116 | self, 117 | model: Model, 118 | batch_size: int, 119 | sequence_length: int, 120 | height: int = None, 121 | width: int = None, 122 | ): 123 | shapes = {} 124 | for inputs in model.inputs: 125 | shapes[inputs] = inputs.get_partial_shape() 126 | shapes[inputs][0] = -1 127 | shapes[inputs][1] = -1 128 | model.reshape(shapes) 129 | return model 130 | 131 | @classmethod 132 | def _from_pretrained( 133 | cls, 134 | model_id: Union[str, Path], 135 | config: PretrainedConfig, 136 | use_auth_token: Optional[Union[bool, str, None]] = None, 137 | revision: Optional[Union[str, None]] = None, 138 | force_download: bool = False, 139 | cache_dir: Optional[str] = None, 140 | file_name: Optional[str] = None, 141 | subfolder: str = "", 142 | from_onnx: bool = False, 143 | local_files_only: bool = False, 144 | load_in_8bit: bool = False, 145 | **kwargs, 146 | ): 147 | model_path = Path(model_id) 148 | default_file_name = ONNX_WEIGHTS_NAME if from_onnx else OV_XML_FILE_NAME 149 | file_name = file_name or default_file_name 150 | 151 | model_cache_path = cls._cached_file( 152 | model_path=model_path, 153 | use_auth_token=use_auth_token, 154 | revision=revision, 155 | force_download=force_download, 156 | cache_dir=cache_dir, 157 | file_name=file_name, 158 | subfolder=subfolder, 159 | local_files_only=local_files_only, 160 | ) 161 | 162 | model = cls.load_model(model_cache_path, load_in_8bit=load_in_8bit) 163 | init_cls = OVQwenModel 164 | 165 | return init_cls(model=model, config=config, model_save_dir=model_cache_path.parent, **kwargs) 166 | 167 | def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs): 168 | past_key_values = past_key_values or kwargs.get("past", None) 169 | 170 | # `past_key_values` may be in the stardard format (e.g. in contrastive search), converts to bloom's format if needed 171 | if past_key_values is not None and self.config.model_type == "bloom": 172 | if past_key_values[0][0].shape[0] == input_ids.shape[0]: 173 | past_key_values = self._convert_to_bloom_cache(past_key_values) 174 | 175 | attention_mask = kwargs.get("attention_mask", None) 176 | position_ids = kwargs.get("position_ids", None) 177 | if attention_mask is not None and position_ids is None: 178 | # create position_ids on the fly for batch generation 179 | position_ids = attention_mask.long().cumsum(-1) - 1 180 | position_ids.masked_fill_(attention_mask == 0, 1) 181 | if past_key_values: 182 | position_ids = position_ids[:, -1].unsqueeze(-1) 183 | return { 184 | "input_ids": input_ids, 185 | "past_key_values": past_key_values, 186 | "use_cache": self.use_cache, 187 | "position_ids": position_ids, 188 | "attention_mask": attention_mask, 189 | "token_type_ids": None, 190 | } 191 | 192 | def _update_model_kwargs_for_generation( 193 | self, 194 | outputs: "ModelOutput", 195 | model_kwargs: Dict[str, "Any"], 196 | is_encoder_decoder: bool = False, 197 | standardize_cache_format: bool = False, 198 | ) -> Dict[str, "Any"]: 199 | # update past_key_values 200 | model_kwargs["past_key_values"] = self._extract_past_from_model_output( 201 | outputs, standardize_cache_format=standardize_cache_format 202 | ) 203 | 204 | # update attention mask 205 | if "attention_mask" in model_kwargs: 206 | attention_mask = model_kwargs["attention_mask"] 207 | model_kwargs["attention_mask"] = torch.cat( 208 | [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1 209 | ) 210 | 211 | # update position ids 212 | if "position_ids" in model_kwargs: 213 | position_ids = model_kwargs["position_ids"] 214 | new_position_id = position_ids[..., -1:].clone() 215 | new_position_id += 1 216 | model_kwargs["position_ids"] = torch.cat([position_ids, new_position_id], dim=-1) 217 | 218 | model_kwargs["is_first_forward"] = False 219 | return model_kwargs 220 | 221 | 222 | def generate( 223 | self, 224 | inputs: Optional[torch.Tensor] = None, 225 | generation_config: Optional[GenerationConfig] = None, 226 | logits_processor: Optional[LogitsProcessorList] = None, 227 | stopping_criteria: Optional[StoppingCriteriaList] = None, 228 | prefix_allowed_tokens_fn: Optional[ 229 | Callable[[int, torch.Tensor], List[int]] 230 | ] = None, 231 | synced_gpus: Optional[bool] = None, 232 | #assistant_model: Optional["PreTrainedModel"] = None, 233 | #streamer: Optional["BaseStreamer"] = None, 234 | **kwargs, 235 | ) -> Union[GenerateOutput, torch.LongTensor]: 236 | generation_config = generation_config if generation_config is not None else self.generation_config 237 | 238 | # Process stop_words_ids. 239 | stop_words_ids = kwargs.pop("stop_words_ids", [[151643]]) 240 | if stop_words_ids is None and generation_config is not None: 241 | stop_words_ids = getattr(generation_config, "stop_words_ids", None) 242 | if stop_words_ids is None: 243 | stop_words_ids = getattr(generation_config, "stop_words_ids", None) 244 | 245 | if stop_words_ids is not None: 246 | stop_words_logits_processor = StopWordsLogitsProcessor( 247 | stop_words_ids=stop_words_ids, 248 | eos_token_id=generation_config.eos_token_id, 249 | ) 250 | if logits_processor is None: 251 | logits_processor = LogitsProcessorList([stop_words_logits_processor]) 252 | else: 253 | logits_processor.append(stop_words_logits_processor) 254 | 255 | return super().generate( 256 | inputs, 257 | generation_config=generation_config, 258 | logits_processor=logits_processor, 259 | stopping_criteria=stopping_criteria, 260 | prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, 261 | synced_gpus=synced_gpus, 262 | **kwargs, 263 | ) 264 | 265 | 266 | class OVChatGLM2Model(OVModelForCausalLM): 267 | def __init__( 268 | self, 269 | model: Model, 270 | config: PretrainedConfig = None, 271 | device: str = 'CPU', 272 | dynamic_shapes: bool = True, 273 | ov_config: Optional[Dict[str, str]] = None, 274 | model_save_dir: Optional[Union[str, Path, TemporaryDirectory]] = None, 275 | **kwargs, 276 | ): 277 | NormalizedConfigManager._conf['chatglm'] = NormalizedTextConfig.with_args( 278 | num_layers='num_layers', num_attention_heads='num_attention_heads') 279 | super().__init__(model, config, device, dynamic_shapes, 280 | ov_config, model_save_dir, **kwargs) 281 | 282 | def _reshape( 283 | self, 284 | model: Model, 285 | batch_size: int, 286 | sequence_length: int, 287 | height: int = None, 288 | width: int = None, 289 | ): 290 | shapes = {} 291 | for inputs in model.inputs: 292 | shapes[inputs] = inputs.get_partial_shape() 293 | shapes[inputs][0] = -1 294 | input_name = inputs.get_any_name() 295 | if input_name.startswith('past_key_values'): 296 | shapes[inputs][1] = -1 297 | shapes[inputs][2] = 2 298 | else: 299 | shapes[inputs][1] = -1 300 | model.reshape(shapes) 301 | return model 302 | 303 | def forward( 304 | self, 305 | input_ids: torch.LongTensor, 306 | attention_mask: Optional[torch.LongTensor] = None, 307 | past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, 308 | position_ids: Optional[torch.LongTensor] = None, 309 | **kwargs, 310 | ) -> CausalLMOutputWithPast: 311 | self.compile() 312 | 313 | if self.use_cache and past_key_values is not None: 314 | input_ids = input_ids[:, -1:] 315 | 316 | inputs = {} 317 | if past_key_values is not None: 318 | if self._pkv_precision == Type.bf16: 319 | # numpy does not support bf16, pretending f16, should change to bf16 320 | past_key_values = tuple( 321 | Tensor(past_key_value, past_key_value.shape, Type.bf16) for pkv_per_layer in past_key_values for past_key_value in pkv_per_layer 322 | ) 323 | else: 324 | # Flatten the past_key_values 325 | past_key_values = tuple( 326 | past_key_value for pkv_per_layer in past_key_values for past_key_value in pkv_per_layer) 327 | # Add the past_key_values to the decoder inputs 328 | inputs = dict(zip(self.key_value_input_names, past_key_values)) 329 | 330 | # Create empty past_key_values for decoder_with_past first generation step 331 | elif self.use_cache: 332 | for input_name in self.key_value_input_names: 333 | model_inputs = self.model.input(input_name) 334 | shape = model_inputs.get_partial_shape() 335 | shape[0] = 0 336 | if shape[1].is_dynamic: 337 | shape[1] = 1 338 | inputs[input_name] = Tensor( 339 | model_inputs.get_element_type(), shape.get_shape()) 340 | 341 | inputs['input_ids'] = np.array(input_ids) 342 | 343 | if 'position_ids' in self.input_names and position_ids is not None: 344 | inputs['position_ids'] = np.array(position_ids) 345 | 346 | # Add the attention_mask inputs when needed 347 | if 'attention_mask' in self.input_names and attention_mask is not None: 348 | inputs['attention_mask'] = np.array(attention_mask) 349 | 350 | # Run inference 351 | self.request.start_async(inputs, share_inputs=True) 352 | self.request.wait() 353 | 354 | logits = torch.from_numpy( 355 | self.request.get_tensor('logits').data).to(self.device) 356 | 357 | if self.use_cache: 358 | # Tuple of length equal to : number of layer * number of past_key_value per decoder layer (2 corresponds to the self-attention layer) 359 | past_key_values = tuple(self.request.get_tensor( 360 | key).data for key in self.key_value_output_names) 361 | # Tuple of tuple of length `n_layers`, with each tuple of length equal to 2 (k/v of self-attention) 362 | past_key_values = tuple( 363 | past_key_values[i: i + self.num_pkv] for i in range(0, len(past_key_values), self.num_pkv)) 364 | else: 365 | past_key_values = None 366 | 367 | return CausalLMOutputWithPast(logits=logits, past_key_values=past_key_values) 368 | 369 | def get_position_ids(self, input_ids, device): 370 | batch_size, seq_length = input_ids.shape 371 | position_ids = torch.arange( 372 | seq_length, dtype=torch.long, device=device).unsqueeze(0).repeat(batch_size, 1) 373 | return position_ids 374 | 375 | def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs): 376 | past_key_values = past_key_values or kwargs.get("past", None) 377 | 378 | # `past_key_values` may be in the stardard format (e.g. in contrastive search), converts to bloom's format if needed 379 | if past_key_values is not None and self.config.model_type == "bloom": 380 | if past_key_values[0][0].shape[0] == input_ids.shape[0]: 381 | past_key_values = self._convert_to_bloom_cache(past_key_values) 382 | 383 | attention_mask = kwargs.get("attention_mask", None) 384 | position_ids = kwargs.get("position_ids", None) 385 | if attention_mask is not None and position_ids is None: 386 | # create position_ids on the fly for batch generation 387 | position_ids = attention_mask.long().cumsum(-1) - 1 388 | position_ids.masked_fill_(attention_mask == 0, 1) 389 | if past_key_values: 390 | position_ids = position_ids[:, -1].unsqueeze(-1) 391 | return { 392 | "input_ids": input_ids, 393 | "past_key_values": past_key_values, 394 | "use_cache": self.use_cache, 395 | "position_ids": position_ids, 396 | "attention_mask": attention_mask, 397 | "token_type_ids": None, 398 | } 399 | 400 | def _update_model_kwargs_for_generation( 401 | self, 402 | outputs: "ModelOutput", 403 | model_kwargs: Dict[str, "Any"], 404 | is_encoder_decoder: bool = False, 405 | standardize_cache_format: bool = False, 406 | ) -> Dict[str, "Any"]: 407 | # update past_key_values 408 | model_kwargs["past_key_values"] = self._extract_past_from_model_output( 409 | outputs, standardize_cache_format=standardize_cache_format 410 | ) 411 | 412 | # update attention mask 413 | if "attention_mask" in model_kwargs: 414 | attention_mask = model_kwargs["attention_mask"] 415 | model_kwargs["attention_mask"] = torch.cat( 416 | [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1 417 | ) 418 | 419 | # update position ids 420 | if "position_ids" in model_kwargs: 421 | position_ids = model_kwargs["position_ids"] 422 | new_position_id = position_ids[..., -1:].clone() 423 | new_position_id += 1 424 | model_kwargs["position_ids"] = torch.cat( 425 | [position_ids, new_position_id], dim=-1) 426 | 427 | model_kwargs["is_first_forward"] = False 428 | return model_kwargs 429 | 430 | @classmethod 431 | def _from_pretrained( 432 | cls, 433 | model_id: Union[str, Path], 434 | config: PretrainedConfig, 435 | use_auth_token: Optional[Union[bool, str, None]] = None, 436 | revision: Optional[Union[str, None]] = None, 437 | force_download: bool = False, 438 | cache_dir: Optional[str] = None, 439 | file_name: Optional[str] = None, 440 | subfolder: str = "", 441 | from_onnx: bool = False, 442 | local_files_only: bool = False, 443 | load_in_8bit: bool = False, 444 | **kwargs, 445 | ): 446 | model_path = Path(model_id) 447 | default_file_name = ONNX_WEIGHTS_NAME if from_onnx else OV_XML_FILE_NAME 448 | file_name = file_name or default_file_name 449 | 450 | model_cache_path = cls._cached_file( 451 | model_path=model_path, 452 | use_auth_token=use_auth_token, 453 | revision=revision, 454 | force_download=force_download, 455 | cache_dir=cache_dir, 456 | file_name=file_name, 457 | subfolder=subfolder, 458 | local_files_only=local_files_only, 459 | ) 460 | 461 | model = cls.load_model(model_cache_path, load_in_8bit=load_in_8bit) 462 | init_cls = OVChatGLM2Model 463 | 464 | return init_cls(model=model, config=config, model_save_dir=model_cache_path.parent, **kwargs) 465 | -------------------------------------------------------------------------------- /convert.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2018-2023 Intel Corporation 3 | # SPDX-License-Identifier: Apache-2.0 4 | import sys 5 | import gc 6 | import time 7 | import logging as log 8 | from argparse import ArgumentParser 9 | from enum import Enum 10 | from functools import wraps 11 | from pathlib import Path 12 | import types 13 | from typing import Tuple, Dict, Optional 14 | import torch 15 | from nncf import compress_weights 16 | from openvino import Type, PartialShape, save_model, convert_model 17 | from openvino.runtime import Core 18 | from optimum.exporters import TasksManager 19 | from optimum.exporters.tasks import make_backend_config_constructor_for_task 20 | from optimum.exporters.onnx.config import TextDecoderOnnxConfig 21 | from optimum.utils import ( 22 | NormalizedTextConfig, NormalizedConfigManager, DEFAULT_DUMMY_SHAPES, 23 | DummyPastKeyValuesGenerator, 24 | DummyTextInputGenerator, 25 | DummyInputGenerator 26 | ) 27 | from optimum.exporters.openvino import export_models 28 | from optimum.intel.utils.modeling_utils import _prepare_decoder_attention_mask 29 | from optimum.intel.openvino import ( 30 | OVModelForCausalLM, 31 | OVQuantizer) 32 | 33 | from optimum.exporters.onnx import __main__ as optimum_main 34 | try: 35 | from optimum.exporters.openvino.__main__ import _get_submodels_and_export_configs 36 | except ImportError: 37 | from optimum.exporters.onnx.__main__ import _get_submodels_and_onnx_configs as _get_submodels_and_export_configs 38 | 39 | from transformers import AutoTokenizer, AutoConfig, AutoModelForCausalLM, AutoModel, PreTrainedModel 40 | from transformers.modeling_outputs import BaseModelOutputWithPast 41 | 42 | class BackendType(Enum): 43 | PYTORCH = 'pytorch' 44 | OPENVINO = 'openvino' 45 | 46 | def save_tokenizer(tokenizer, out_dir): 47 | try: 48 | tokenizer.save_pretrained(out_dir) 49 | except Exception as e: 50 | log.error(f'tokenizer loading failed with {e}') 51 | 52 | def compress_ov_model_weights_helper(ov_model, tok, config, out_path, fp16=False): 53 | compressed_ov_model = compress_weights(ov_model) 54 | save_ov_model_helper(compressed_ov_model, out_path, fp16=fp16, tok=tok, config=config) 55 | 56 | 57 | def save_ov_model_helper(ov_model, out_path, model_name='openvino_model', fp16=False, tok=None, config=None): 58 | save_model(ov_model, Path(out_path) / f'{model_name}.xml', compress_to_fp16=fp16) 59 | if tok is not None: 60 | save_tokenizer(tok, out_path) 61 | if config is not None: 62 | config.save_pretrained(out_path) 63 | 64 | 65 | def is_gptq(config): 66 | config_dict = config.to_dict() 67 | quantization_config = config_dict.get("quantization_config", None) 68 | return quantization_config and quantization_config["quant_method"] == "gptq" 69 | 70 | 71 | def patch_gptq(config): 72 | do_gptq_patching = False 73 | config_dict = config.to_dict() 74 | quantization_config = config_dict.get("quantization_config", None) 75 | do_gptq_patching = quantization_config and quantization_config["quant_method"] == "gptq" 76 | orig_cuda_check = torch.cuda.is_available 77 | orig_post_init_model = None 78 | if do_gptq_patching: 79 | torch.set_default_dtype(torch.float32) 80 | torch.cuda.is_available = lambda: True 81 | 82 | from optimum.gptq import GPTQQuantizer 83 | 84 | orig_post_init_model = GPTQQuantizer.post_init_model 85 | 86 | def post_init_model(self, model): 87 | from auto_gptq import exllama_set_max_input_length 88 | 89 | class StoreAttr(object): 90 | pass 91 | 92 | model.quantize_config = StoreAttr() 93 | model.quantize_config.desc_act = self.desc_act 94 | if self.desc_act and not self.disable_exllama and self.max_input_length is not None: 95 | model = exllama_set_max_input_length(model, self.max_input_length) 96 | return model 97 | 98 | GPTQQuantizer.post_init_model = post_init_model 99 | return orig_cuda_check, orig_post_init_model 100 | 101 | 102 | def unpatch_gptq(orig_cuda_check, orig_post_init_model): 103 | from optimum.gptq import GPTQQuantizer 104 | torch.cuda.is_available = orig_cuda_check 105 | GPTQQuantizer.post_init_model = orig_post_init_model 106 | 107 | 108 | @torch.jit.script_if_tracing 109 | def _chatglm2_get_context_layer(query_layer: torch.Tensor, key_layer: torch.Tensor, value_layer: torch.Tensor): 110 | mask = torch.zeros((query_layer.shape[-2], key_layer.shape[-2]), dtype=query_layer.dtype) 111 | if query_layer.shape[2] == key_layer.shape[2]: 112 | tmp_mask = torch.ones((query_layer.shape[-2], key_layer.shape[-2]), dtype=torch.bool).triu(diagonal=1) 113 | mask.masked_fill_(tmp_mask, float("-inf")) 114 | 115 | context_layer = torch.nn.functional.scaled_dot_product_attention(query_layer, key_layer, value_layer, attn_mask=mask) 116 | return context_layer 117 | 118 | @torch.jit.script_if_tracing 119 | def _get_chatglm_attention_mask(input_ids, past_key): 120 | mask = torch.zeros((input_ids.shape[1], past_key.shape[0] + input_ids.shape[1]), dtype=past_key.dtype) 121 | if past_key.shape[0] == 0: 122 | tmp_mask = torch.ones((input_ids.shape[1], past_key.shape[0] + input_ids.shape[1]), dtype=torch.bool).triu(diagonal=1) 123 | mask.masked_fill_(tmp_mask, float("-inf")) 124 | return mask 125 | 126 | 127 | def _chatglm_transformer_forward( 128 | self, 129 | input_ids, 130 | position_ids: Optional[torch.Tensor] = None, 131 | attention_mask: Optional[torch.BoolTensor] = None, 132 | full_attention_mask: Optional[torch.BoolTensor] = None, 133 | past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None, 134 | inputs_embeds: Optional[torch.Tensor] = None, 135 | use_cache: Optional[bool] = None, 136 | output_hidden_states: Optional[bool] = None, 137 | return_dict: Optional[bool] = None 138 | ): 139 | output_hidden_states = ( 140 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states 141 | ) 142 | use_cache = use_cache if use_cache is not None else self.config.use_cache 143 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 144 | 145 | batch_size, seq_length = input_ids.shape 146 | 147 | if inputs_embeds is None: 148 | inputs_embeds = self.embedding(input_ids) 149 | 150 | if self.pre_seq_len is not None: 151 | if past_key_values is None: 152 | past_key_values = self.get_prompt(batch_size=batch_size, device=input_ids.device, 153 | dtype=inputs_embeds.dtype) 154 | if attention_mask is not None: 155 | attention_mask = torch.cat([attention_mask.new_ones((batch_size, self.pre_seq_len)), attention_mask], dim=-1) 156 | 157 | if full_attention_mask is None: 158 | if (attention_mask is not None and not attention_mask.all()) or (past_key_values and seq_length != 1): 159 | full_attention_mask = self.get_masks(input_ids, past_key_values, padding_mask=attention_mask) 160 | elif past_key_values is not None: 161 | full_attention_mask = _get_chatglm_attention_mask(input_ids, past_key_values[0][0]) 162 | 163 | # Rotary positional embeddings 164 | rotary_pos_emb = self.rotary_pos_emb(self.seq_length) 165 | if position_ids is not None: 166 | rotary_pos_emb = rotary_pos_emb[position_ids] 167 | else: 168 | rotary_pos_emb = rotary_pos_emb[None, :seq_length] 169 | rotary_pos_emb = rotary_pos_emb.transpose(0, 1).contiguous() 170 | 171 | # Run encoder. 172 | hidden_states, presents, all_hidden_states, all_self_attentions = self.encoder( 173 | inputs_embeds, full_attention_mask, rotary_pos_emb=rotary_pos_emb, 174 | kv_caches=past_key_values, use_cache=use_cache, output_hidden_states=output_hidden_states 175 | ) 176 | 177 | if not return_dict: 178 | return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None) 179 | 180 | return BaseModelOutputWithPast( 181 | last_hidden_state=hidden_states, 182 | past_key_values=presents, 183 | hidden_states=all_hidden_states, 184 | attentions=all_self_attentions, 185 | ) 186 | 187 | 188 | def _core_attention_forward(self, query_layer, key_layer, value_layer, attention_mask): 189 | query_layer, key_layer, value_layer = [k.permute(1, 2, 0, 3) for k in [query_layer, key_layer, value_layer]] 190 | if attention_mask is None: 191 | context_layer = _chatglm2_get_context_layer(query_layer, key_layer, value_layer) 192 | else: 193 | context_layer = torch.nn.functional.scaled_dot_product_attention( 194 | query_layer, key_layer, value_layer, attention_mask 195 | ) 196 | context_layer = context_layer.permute(2, 0, 1, 3) 197 | new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size_per_partition,) 198 | context_layer = context_layer.reshape(*new_context_layer_shape) 199 | 200 | return context_layer 201 | 202 | 203 | def _patch_chatglm_core_attention_forward(model: "PreTrainedModel"): 204 | model.transformer.forward = types.MethodType(_chatglm_transformer_forward, model.transformer) 205 | for block in model.transformer.encoder.layers: 206 | block.self_attention.core_attention.forward = types.MethodType( 207 | _core_attention_forward, block.self_attention.core_attention 208 | ) 209 | 210 | 211 | def _update_qwen_rotary_embedding_cache(model): 212 | #model.transformer.rotary_emb(model.config.seq_length) 213 | model.transformer.rotary_emb(2048) # WA, patch Qwen sequence length from 8K to 2K to save system compute memory 214 | 215 | 216 | def patch_model_for_optimum_export(model): 217 | if model.config.model_type == "chatglm": 218 | _patch_chatglm_core_attention_forward(model) 219 | elif model.config.model_type == "qwen": 220 | _update_qwen_rotary_embedding_cache(model) 221 | return model 222 | 223 | 224 | def convert_optimum_causallm_base(model, args): 225 | tok = AutoTokenizer.from_pretrained(args.model_id, trust_remote_code=True) 226 | model = patch_model_for_optimum_export(model) 227 | model_config = model.config 228 | gptq_applied = is_gptq(model_config) 229 | precision = args.precision if not gptq_applied else f"GPTQ_INT4-{args.precision}" 230 | if gptq_applied and args.compress_weights: 231 | log.info("Weights compression will be skipped for GPTQ models") 232 | pt_compress_weights = args.compress_weights and BackendType.PYTORCH.value in args.compress_weights_backends 233 | if args.save_orig: 234 | pt_out_dir = Path(args.output_dir) / 'pytorch' 235 | model.save_pretrained(pt_out_dir) 236 | save_tokenizer(tok, pt_out_dir) 237 | dummy_shapes = DEFAULT_DUMMY_SHAPES 238 | onnx_config, models_and_onnx_configs = _get_submodels_and_export_configs( 239 | model=model, 240 | task="text-generation-with-past", 241 | custom_onnx_configs={}, 242 | custom_architecture=None, 243 | fn_get_submodels=None, 244 | preprocessors=None, 245 | _variant="default", 246 | monolith=False 247 | ) 248 | if "decoder_with_past_model" in models_and_onnx_configs: 249 | models_and_onnx_configs = {"model": models_and_onnx_configs["decoder_with_past_model"]} 250 | ov_out_dir = Path(args.output_dir) / precision 251 | model.config.save_pretrained(ov_out_dir) 252 | files_subpaths = ["openvino_" + model_name + ".xml" for model_name in models_and_onnx_configs.keys()] 253 | export_models( 254 | models_and_onnx_configs=models_and_onnx_configs, 255 | output_dir=ov_out_dir, 256 | output_names=files_subpaths, 257 | input_shapes=dummy_shapes, 258 | device="cpu", 259 | fp16=args.precision == "FP16", 260 | int8=False, 261 | model_kwargs={}, 262 | ) 263 | save_tokenizer(tok, ov_out_dir) 264 | if args.compress_weights and BackendType.OPENVINO.value in args.compress_weights_backends and not gptq_applied: 265 | ov_int8_dir = Path(args.output_dir) / 'compressed_weights' / f'OV_{args.precision}-INT8' 266 | model.config.save_pretrained(ov_int8_dir) 267 | export_models( 268 | models_and_onnx_configs=models_and_onnx_configs, 269 | output_dir=ov_int8_dir, 270 | output_names=files_subpaths, 271 | input_shapes=dummy_shapes, 272 | device="cpu", 273 | fp16=args.precision == "FP16", 274 | int8=True, 275 | model_kwargs={}, 276 | ) 277 | save_tokenizer(tok, ov_int8_dir) 278 | if pt_compress_weights and not gptq_applied: 279 | compressed_model = compress_weights(model) 280 | onnx_config, models_and_onnx_configs = _get_submodels_and_export_configs( 281 | model=compressed_model, 282 | task="text-generation-with-past", 283 | custom_onnx_configs={}, 284 | custom_architecture=None, 285 | fn_get_submodels=None, 286 | preprocessors=None, 287 | _variant="default", 288 | monolith=False 289 | ) 290 | pt_out_dir = Path(args.output_dir) / 'compressed_weights' / f'PT_{args.precision}-INT8' 291 | model.config.save_pretrained(pt_out_dir) 292 | export_models( 293 | models_and_onnx_configs=models_and_onnx_configs, 294 | output_dir=pt_out_dir, 295 | output_names=files_subpaths, 296 | input_shapes=dummy_shapes, 297 | device="cpu", 298 | fp16=args.precision == "FP16", 299 | int8=False, 300 | model_kwargs={}, 301 | ) 302 | save_tokenizer(tok, pt_out_dir) 303 | return 304 | 305 | 306 | def convert_causal_lm(args): 307 | tok = AutoTokenizer.from_pretrained(args.model_id, trust_remote_code=True) 308 | pt_compress_weights = args.compress_weights and BackendType.PYTORCH.value in args.compress_weights_backends 309 | model_config = AutoConfig.from_pretrained(args.model_id, trust_remote_code=True) 310 | gptq_applied = is_gptq(model_config) 311 | precision = args.precision if not gptq_applied else f"GPTQ_INT4-{args.precision}" 312 | if gptq_applied and args.compress_weights: 313 | log.info("Weights compression will be skipped for GPTQ models") 314 | 315 | start = time.perf_counter() 316 | if args.save_orig or pt_compress_weights: 317 | pt_model = AutoModelForCausalLM.from_pretrained( 318 | args.model_id, 319 | trust_remote_code=True, 320 | config=AutoConfig.from_pretrained(args.model_id, trust_remote_code=True), 321 | ) 322 | if args.save_orig: 323 | pt_out_dir = Path(args.output_dir) / 'pytorch' 324 | pt_model.save_pretrained(pt_out_dir) 325 | save_tokenizer(tok, pt_out_dir) 326 | if pt_compress_weights and not gptq_applied: 327 | feature = 'text-generation' 328 | quantizer = OVQuantizer.from_pretrained(pt_model, task=feature) 329 | pt_out_dir = Path(args.output_dir) / 'compressed_weights' / f'PT_{args.precision}-INT8' 330 | quantizer.quantize(save_directory=pt_out_dir, weights_only=True) 331 | save_tokenizer(tok, pt_out_dir) 332 | del pt_model 333 | gc.collect() 334 | 335 | model = OVModelForCausalLM.from_pretrained( 336 | args.model_id, 337 | export=True, 338 | compile=False, 339 | trust_remote_code=True, 340 | load_in_8bit=False, 341 | config=AutoConfig.from_pretrained(args.model_id, trust_remote_code=True), 342 | ) 343 | end = time.perf_counter() 344 | 345 | log.info(f'Conversion total time {end - start}s') 346 | if args.precision == 'FP16': 347 | model.half() 348 | ov_out_dir = Path(args.output_dir) / precision 349 | save_tokenizer(tok, ov_out_dir) 350 | 351 | start1 = time.perf_counter() 352 | model.save_pretrained(ov_out_dir) 353 | end1 = time.perf_counter() 354 | log.info(f'Serialization total time {end1 - start1}s') 355 | 356 | if args.compress_weights and BackendType.OPENVINO.value in args.compress_weights_backends and not gptq_applied: 357 | ov_int8_dir = Path(args.output_dir) / 'compressed_weights' / f'OV_{args.precision}-INT8' 358 | model.model = compress_weights(model.model) 359 | model.save_pretrained(ov_int8_dir) 360 | save_tokenizer(tok, ov_int8_dir) 361 | 362 | del model 363 | gc.collect() 364 | 365 | def convert_chatglm2(args): 366 | class ChatGLM2NormalizedConfig(NormalizedTextConfig): 367 | NUM_LAYERS = "num_layers" 368 | VOCAB_SIZE = "padded_vocab_size" 369 | 370 | class ChatGLM2DummyTextInputGenerator(DummyTextInputGenerator): 371 | SUPPORTED_INPUT_NAMES = { 372 | "input_ids", 373 | "attention_mask", 374 | "token_type_ids", 375 | "position_ids", 376 | } 377 | 378 | def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"): 379 | input = super().generate(input_name, framework, int_dtype, float_dtype) 380 | if input_name == "attention_mask": 381 | input = torch.ones(input.shape, dtype=input.dtype) 382 | if input_name == "position_ids": 383 | bs = input.shape[0] 384 | input = torch.range(0, input.shape[1], dtype=input.dtype).repeat(bs, 1) 385 | return input 386 | 387 | class ChatGLM2DummyPastKeyValuesGenerator(DummyPastKeyValuesGenerator): 388 | def __init__( 389 | self, 390 | task: str, 391 | normalized_config: NormalizedTextConfig, 392 | batch_size: int = DEFAULT_DUMMY_SHAPES["batch_size"], 393 | sequence_length: int = DEFAULT_DUMMY_SHAPES["sequence_length"], 394 | random_batch_size_range: Optional[Tuple[int, int]] = None, 395 | random_sequence_length_range: Optional[Tuple[int, int]] = None, 396 | **kwargs, 397 | ): 398 | super().__init__( 399 | task=task, 400 | normalized_config=normalized_config, 401 | batch_size=batch_size, 402 | sequence_length=sequence_length, 403 | random_batch_size_range=random_batch_size_range, 404 | random_sequence_length_range=random_sequence_length_range, 405 | ) 406 | self.multi_query_group_num = normalized_config.multi_query_group_num 407 | self.head_dim = self.hidden_size // self.num_attention_heads 408 | 409 | def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"): 410 | past_key_shape = ( 411 | self.sequence_length, 412 | self.batch_size, 413 | self.multi_query_group_num, 414 | self.head_dim, 415 | ) 416 | past_value_shape = ( 417 | self.sequence_length, 418 | self.batch_size, 419 | self.multi_query_group_num, 420 | self.head_dim, 421 | ) 422 | return [ 423 | ( 424 | self.random_float_tensor(past_key_shape, framework=framework, dtype=float_dtype), 425 | self.random_float_tensor(past_value_shape, framework=framework, dtype=float_dtype), 426 | ) 427 | for _ in range(self.num_layers) 428 | ] 429 | 430 | class ChatGLM2OpenVINOConfig(TextDecoderOnnxConfig): 431 | NORMALIZED_CONFIG_CLASS = ChatGLM2NormalizedConfig 432 | DUMMY_INPUT_GENERATOR_CLASSES = (ChatGLM2DummyTextInputGenerator, ChatGLM2DummyPastKeyValuesGenerator) 433 | DUMMY_PKV_GENERATOR_CLASS = ChatGLM2DummyPastKeyValuesGenerator 434 | no_position_ids = False 435 | 436 | def generate_dummy_inputs(self, framework: str = "pt", **kwargs): 437 | dummy_inputs_generators = self._create_dummy_input_generator_classes(**kwargs) 438 | 439 | dummy_inputs = {} 440 | input_names = [key for key in self.inputs.keys() if not key.startswith("past_key_values")] 441 | if self.use_past_in_inputs and self.use_cache_branch is not False: 442 | input_names.append("past_key_values") 443 | 444 | for input_name in input_names: 445 | input_was_inserted = False 446 | for dummy_input_gen in dummy_inputs_generators: 447 | if dummy_input_gen.supports_input(input_name): 448 | dummy_inputs[input_name] = self.overwrite_shape_and_generate_input( 449 | dummy_input_gen, 450 | input_name, 451 | framework, 452 | input_shapes=kwargs, 453 | ) 454 | input_was_inserted = True 455 | break 456 | if not input_was_inserted: 457 | raise RuntimeError( 458 | f'Could not generate dummy input for "{input_name}". Try adding a proper dummy input generator to the model ONNX config.' 459 | ) 460 | 461 | # refer to https://github.com/huggingface/optimum/pull/764 462 | cond1 = self.use_past_in_inputs 463 | cond2 = self.PAD_ATTENTION_MASK_TO_PAST 464 | cond3 = self.use_cache_branch is not False 465 | cond4 = "attention_mask" in dummy_inputs 466 | if (cond1 and cond2 and cond3 and cond4): 467 | # Obtain the past sequence length from the value instead of the key (Bloom). 468 | past_length = dummy_inputs["past_key_values"][0][1].shape[0] 469 | for k, v in dummy_inputs.items(): 470 | if k not in ["attention_mask", "past_key_values"]: 471 | dummy_inputs[k] = v[:, -1:] 472 | 473 | dummy_inputs["attention_mask"] = DummyInputGenerator.pad_input_on_dim( 474 | dummy_inputs["attention_mask"], 475 | desired_length=past_length + 1, 476 | dim=1, 477 | dtype=dummy_inputs["attention_mask"].dtype, 478 | ) 479 | 480 | return dummy_inputs 481 | 482 | @property 483 | def inputs(self) -> Dict[str, Dict[int, str]]: 484 | common_inputs = super().inputs 485 | if not self.no_position_ids and self.task == "text-generation": 486 | common_inputs["position_ids"] = {0: "batch_size", 1: "sequence_length"} 487 | 488 | return common_inputs 489 | 490 | def add_past_key_values(self, inputs_or_outputs: Dict[str, Dict[int, str]], direction: str): 491 | """ 492 | Fills `input_or_outputs` mapping with past_key_values dynamic axes considering the direction. 493 | 494 | Args: 495 | inputs_or_outputs (`Dict[str, Dict[int, str]]`): The mapping to fill. 496 | direction (`str`): 497 | either "inputs" or "outputs", it specifies whether `input_or_outputs` is the input mapping or the 498 | output mapping, this is important for axes naming. 499 | """ 500 | if direction not in ["inputs", "outputs"]: 501 | raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given') 502 | 503 | if direction == "inputs": 504 | decoder_sequence_name = "past_sequence_length" 505 | name = "past_key_values" 506 | else: 507 | decoder_sequence_name = "past_sequence_length + 1" 508 | name = "present" 509 | 510 | for i in range(self._normalized_config.num_layers): 511 | inputs_or_outputs[f"{name}.{i}.key"] = {1: "batch_size", 0: decoder_sequence_name} 512 | inputs_or_outputs[f"{name}.{i}.value"] = {1: "batch_size", 0: decoder_sequence_name} 513 | 514 | config = AutoConfig.from_pretrained(args.model_id, trust_remote_code=True) 515 | cuda, post_init = patch_gptq(config) 516 | pt_model = AutoModelForCausalLM.from_pretrained( 517 | args.model_id, 518 | trust_remote_code=True, 519 | config=config, 520 | torch_dtype=torch.float32 521 | ) 522 | try: 523 | pt_model.to(torch.float32) 524 | except Exception: 525 | pass 526 | 527 | NormalizedConfigManager._conf[pt_model.config.model_type] = NormalizedTextConfig.with_args( 528 | num_layers="num_hidden_layers", num_attention_heads="num_attention_heads" 529 | ) 530 | export_config = ChatGLM2OpenVINOConfig 531 | TasksManager._SUPPORTED_MODEL_TYPE[pt_model.config.model_type] = { 532 | 'onnx': { 533 | 'text-generation': make_backend_config_constructor_for_task(export_config, 'text-generation'), 534 | 'text-generation-with-past': make_backend_config_constructor_for_task(export_config, 'text-generation-with-past'), 535 | }, 536 | 'openvino': { 537 | 'text-generation': make_backend_config_constructor_for_task(export_config, 'text-generation'), 538 | 'text-generation-with-past': make_backend_config_constructor_for_task(export_config, 'text-generation-with-past'), 539 | }, 540 | } 541 | convert_optimum_causallm_base(pt_model, args) 542 | if post_init is not None: 543 | unpatch_gptq(cuda, post_init) 544 | 545 | 546 | def convert_chatglm(args): 547 | def convert_to_ov(pt_model, tok, out_path, compress_to_fp16=False): 548 | pt_model.config.torchscript = True 549 | last_token = torch.tensor([[130328]]) 550 | past = torch.zeros(28, 2, 5, 1, 32, 128) 551 | position_ids = torch.tensor([[[2], [4]]]) 552 | dummy_input = { 553 | 'input_ids': last_token, 554 | 'past_key_values': past, 555 | 'position_ids': position_ids, 556 | } 557 | ov_model = convert_model(pt_model, example_input=dummy_input) 558 | ov_model.outputs[0].get_tensor().set_names({'logits'}) 559 | for i in range(1, len(ov_model.outputs), 2): 560 | idx = (i - 1) // 2 561 | ov_model.outputs[i].get_tensor().set_names({f'present.{int(idx)}.key'}) 562 | ov_model.outputs[i + 1].get_tensor().set_names({f'present.{int(idx)}.value'}) 563 | save_ov_model_helper(ov_model, out_path, fp16=compress_to_fp16, tok=tok, config=pt_model.config) 564 | 565 | pt_model = AutoModel.from_pretrained( 566 | args.model_id, 567 | trust_remote_code=True, 568 | config=AutoConfig.from_pretrained(args.model_id, trust_remote_code=True), 569 | ) 570 | pt_model.config.use_cache = True 571 | pt_model.to(torch.float32) 572 | pt_model.eval() 573 | tok = AutoTokenizer.from_pretrained(args.model_id, trust_remote_code=True) 574 | 575 | compress_to_fp16 = args.precision == 'FP16' 576 | ov_out_path = Path(args.output_dir) / args.precision 577 | convert_to_ov(pt_model, tok, ov_out_path, compress_to_fp16=compress_to_fp16) 578 | 579 | if args.compress_weights: 580 | ov_model_path = ov_out_path / 'openvino_model.xml' 581 | ov_model = Core().read_model(ov_model_path) 582 | ov_compressed_path = Path(args.output_dir) / 'compressed_weights' / f'OV_{args.precision}-INT8' 583 | compress_ov_model_weights_helper(ov_model, tok, pt_model.config, ov_compressed_path, compress_to_fp16) 584 | 585 | def convert_qwen(args): 586 | config = AutoConfig.from_pretrained(args.model_id, trust_remote_code=True) 587 | cuda, post_init = patch_gptq(config) 588 | revision = "c02ede58c0ab0045f5e4788c35842bec6a7baa0a" if post_init is not None else "2abd8e5777bb4ce9c8ab4be7dbbd0fe4526db78d" 589 | normalized_config = NormalizedTextConfig.with_args(num_layers='num_hidden_layers', num_attention_heads='num_attention_heads', hidden_size='hidden_size') 590 | model = AutoModelForCausalLM.from_pretrained(args.model_id, trust_remote_code=True, torch_dtype=torch.float32, revision=revision) 591 | try: 592 | model.to(torch.float32) 593 | except Exception: 594 | pass 595 | 596 | class QwenDummyInputsGenerator(DummyTextInputGenerator): 597 | SUPPORTED_INPUT_NAMES = { 598 | "input_ids", 599 | "attention_mask", 600 | "token_type_ids", 601 | "position_ids", 602 | } 603 | 604 | def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"): 605 | input = super().generate(input_name, framework, int_dtype, float_dtype) 606 | if input_name == "input_ids": 607 | input = torch.tensor([[1583]]) 608 | if input_name == "attention_mask": 609 | input = torch.ones((1, 7), dtype=input.dtype) 610 | if input_name == "position_ids": 611 | input = torch.tensor([[6]]) 612 | return input 613 | 614 | class QwenDummyPastKeyValuesGenerator(DummyPastKeyValuesGenerator): 615 | def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"): 616 | shape = ( 617 | 1, 618 | 6, 619 | self.num_attention_heads, 620 | self.hidden_size // self.num_attention_heads, 621 | ) 622 | return [ 623 | ( 624 | torch.zeros(shape, dtype=torch.float32), 625 | torch.zeros(shape, dtype=torch.float32), 626 | ) 627 | for _ in range(self.num_layers) 628 | ] 629 | 630 | class QwenOpenVINOConfig(TextDecoderOnnxConfig): 631 | DEFAULT_ONNX_OPSET = 13 632 | NORMALIZED_CONFIG_CLASS = normalized_config 633 | DUMMY_INPUT_GENERATOR_CLASSES = (QwenDummyInputsGenerator, QwenDummyPastKeyValuesGenerator) 634 | DUMMY_PKV_GENERATOR_CLASS = QwenDummyPastKeyValuesGenerator 635 | 636 | def generate_dummy_inputs(self, framework: str = "pt", **kwargs): 637 | dummy_inputs_generators = self._create_dummy_input_generator_classes(**kwargs) 638 | 639 | dummy_inputs = {} 640 | input_names = [key for key in self.inputs.keys() if not key.startswith("past_key_values")] 641 | if self.use_past_in_inputs and self.use_cache_branch is not False: 642 | input_names.append("past_key_values") 643 | 644 | for input_name in input_names: 645 | input_was_inserted = False 646 | for dummy_input_gen in dummy_inputs_generators: 647 | if dummy_input_gen.supports_input(input_name): 648 | dummy_inputs[input_name] = self.overwrite_shape_and_generate_input( 649 | dummy_input_gen, 650 | input_name, 651 | framework, 652 | input_shapes=kwargs, 653 | ) 654 | input_was_inserted = True 655 | break 656 | if not input_was_inserted: 657 | raise RuntimeError( 658 | f'Could not generate dummy input for "{input_name}". Try adding a proper dummy input generator to the model ONNX config.' 659 | ) 660 | 661 | # refer to https://github.com/huggingface/optimum/pull/764 662 | cond1 = self.use_past_in_inputs 663 | cond2 = self.PAD_ATTENTION_MASK_TO_PAST 664 | cond3 = self.use_cache_branch is not False 665 | cond4 = "attention_mask" in dummy_inputs 666 | if (cond1 and cond2 and cond3 and cond4): 667 | # Obtain the past sequence length from the value instead of the key (Bloom). 668 | past_length = dummy_inputs["past_key_values"][0][1].shape[1] 669 | 670 | dummy_inputs["attention_mask"] = DummyInputGenerator.pad_input_on_dim( 671 | dummy_inputs["attention_mask"], 672 | desired_length=past_length + 1, 673 | dim=1, 674 | dtype=dummy_inputs["attention_mask"].dtype, 675 | ) 676 | 677 | return dummy_inputs 678 | 679 | def add_past_key_values(self, inputs_or_outputs: Dict[str, Dict[int, str]], direction: str): 680 | """ 681 | Fills `input_or_outputs` mapping with past_key_values dynamic axes considering the direction. 682 | 683 | Args: 684 | inputs_or_outputs (`Dict[str, Dict[int, str]]`): The mapping to fill. 685 | direction (`str`): 686 | either "inputs" or "outputs", it specifies whether `input_or_outputs` is the input mapping or the 687 | output mapping, this is important for axes naming. 688 | """ 689 | if direction not in ["inputs", "outputs"]: 690 | raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given') 691 | 692 | if direction == "inputs": 693 | decoder_sequence_name = "past_sequence_length" 694 | name = "past_key_values" 695 | else: 696 | decoder_sequence_name = "past_sequence_length + 1" 697 | name = "present" 698 | 699 | for i in range(self._normalized_config.num_layers): 700 | inputs_or_outputs[f"{name}.{i}.key"] = {0: "batch_size", 1: decoder_sequence_name} 701 | inputs_or_outputs[f"{name}.{i}.value"] = {0: "batch_size", 1: decoder_sequence_name} 702 | 703 | model_type = model.config.model_type.replace("-", "_") 704 | export_config = QwenOpenVINOConfig 705 | TasksManager._SUPPORTED_MODEL_TYPE[model_type] = { 706 | 'onnx': { 707 | 'text-generation': make_backend_config_constructor_for_task(export_config, 'text-generation'), 708 | 'text-generation-with-past': make_backend_config_constructor_for_task(export_config, 'text-generation-with-past'), 709 | }, 710 | 'openvino': { 711 | 'text-generation': make_backend_config_constructor_for_task(export_config, 'text-generation'), 712 | 'text-generation-with-past': make_backend_config_constructor_for_task(export_config, 'text-generation-with-past'), 713 | }, 714 | } 715 | NormalizedConfigManager._conf[model_type] = normalized_config 716 | convert_optimum_causallm_base(model, args) 717 | if post_init is not None: 718 | unpatch_gptq(cuda, post_init) 719 | 720 | converters = { 721 | 'decoder': convert_causal_lm, 722 | 'chatglm2': convert_chatglm2, 723 | 'chatglm3': convert_chatglm2, 724 | 'qwen': convert_qwen, 725 | } 726 | 727 | 728 | def get_convert_model_type(model_id): 729 | default = 'decoder' 730 | for key in converters: 731 | if key in model_id: 732 | return key 733 | 734 | return default 735 | 736 | def main(): 737 | log.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.INFO, stream=sys.stdout) 738 | parser = ArgumentParser() 739 | parser.add_argument('--model_id', required=True) 740 | parser.add_argument('--output_dir', required=True) 741 | parser.add_argument('--save_orig', action='store_true') 742 | parser.add_argument('--precision', choices=['FP32', 'FP16'], default='FP32') 743 | compression_group = parser.add_argument_group('Weights compression parameters') 744 | compression_group.add_argument('--compress_weights', action='store_true') 745 | compression_group.add_argument( 746 | '--compress_weights_backends', 747 | help='Backend names used to compress the input model weights separated by space.', 748 | choices=[BackendType.PYTORCH.value, BackendType.OPENVINO.value], 749 | default=BackendType.OPENVINO.value, 750 | type=str.lower, 751 | nargs='+', 752 | ) 753 | 754 | args = parser.parse_args() 755 | model_type = get_convert_model_type(args.model_id.lower()) 756 | converter = converters[model_type] 757 | converter(args) 758 | 759 | if __name__ == "__main__": 760 | main() 761 | --------------------------------------------------------------------------------