microsoft / TransformerCompression

For releasing code related to compression methods for transformers, accompanying our publications
MIT License
356 stars 31 forks source link

why the generation speed of the pruned model by SliceGPT is slower than the original model? #115

Closed joyce0105-ops closed 5 months ago

joyce0105-ops commented 5 months ago

model:Llama2-Chinese-7b-Chat GPU:RTX4090 the generation speed of the original model:47.36 token/s the generation speed of the pruned model:30.49 token/s with all the generate parameters is same

nailimixaM commented 5 months ago

Hi, could I ask what slicing level this is for? Do you have a minimal script you could share which does the generation speed test on Llama-2-7b-hf? Thanks

joyce0105-ops commented 5 months ago

@nailimixaM

my slice:

python ./experiments/run_slicegpt.py \
       --model meta-llama/Llama-2-7b-hf \
       --model-path ./Llama2-Chinese-7b-Chat\
       --save-dir sliceGPT_save_model \
       --sparsity 0.25 \
       --device cuda:0 \
       --cal-dataset alpaca_data_zh_51k_my_small \
       --cal-nsamples 50 \
       --no-wandb

the script for the generation speed :

from slicegpt import gpu_utils, hf_utils, utils
import os

import torch
import numpy as np
from tqdm import tqdm
from datetime import datetime

model = 'meta-llama/Llama-2-7b-hf'
sliced_model_path = 'sliceGPT_save_model/Llama-2-7b-hf_0.25.pt'
sparsity = 0.25
hf_token = os.getenv('HF_TOKEN', None)

model_adapter, tokenizer = hf_utils.load_sliced_model(
            model,
            sliced_model_path,
            sparsity=sparsity,
            token=hf_token
        )

model = model_adapter.model

if torch.cuda.is_available():
    device = torch.device(0)
model = model.to(device)

DEFAULT_SYSTEM_PROMPT = '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n{0} [/INST] '

inputs = [
    "为什么要减少污染,保护环境", 
    "哈哈哈,你是什么名字呀",
    "ubuntu怎么安装git lfs",
    "你是什么模型?",
    "如果我是DJ你会爱我吗?",
    "请列出最近一个月内涨幅前五的美国科技股票",
    "如何通过技术分析预测股票价格走势?",
    "给出一支最近表现良好的科技股票,并简要介绍其业务领域和未来发展前景。",
    "给出一家在过去6个月里股价上涨超过20%的公司,该公司的市值是多少?",
    "什么是“蓝筹股”?可以给我列举几个例子吗?",
    "请问目前苹果公司(AAPL)的股价是多少?",
    "预测下一月华尔街投资银行的收盘价",
    "请问目前苹果公司(AAPL)的股价是多少?",
    "现在值得投资的股票有哪些?",
    "请列出前五名市值最大的科技公司。",
    "针对某支股票,预测未来一周的走势如何?",
]

inputs_prompt = [DEFAULT_SYSTEM_PROMPT.format(_input) for _input in inputs]
results_ip = []

for _ip in tqdm(inputs_prompt):
    st_time = datetime.now()
    inputs = tokenizer(_ip, return_tensors='pt')
    input_ids = inputs['input_ids'].to(device)

    generate_params = {
        'input_ids': input_ids,
        'temperature': 0.2,
        'top_k': 40,
        'top_p': 0.9,
        'max_new_tokens': 512,
        'do_sample': True,
        'repetition_penalty': 1.1,
        'eos_token_id': tokenizer.eos_token_id
    }

    with torch.no_grad():
        outputs = model.generate(**generate_params)
        outputs_res = tokenizer.decode(outputs[0], skip_special_tokens=True)
    ed_time = datetime.now()

    _total_input_tokens = input_ids.shape[1]
    _total_output_tokens = outputs.shape[1]
    _total_time = (ed_time - st_time).total_seconds()
    _tokens_per_sec = _total_output_tokens / _total_time

    _res = {
        "total_input_tokens": _total_input_tokens,
        "total_output_tokens": _total_output_tokens,
        "total_time": _total_time,
        "tokens_per_sec": _tokens_per_sec
    }
    results_ip.append(_res)

avg_process_tokens = np.sum([r['total_output_tokens']-r['total_input_tokens'] for r in results_ip])/np.sum([r['total_time'] for r in results_ip])
print("token/s: {0:.2f}".format(avg_process_tokens))

thanks for your help

wangzhenyu32 commented 5 months ago

Hello, Can you generate normal content use this script?

zhaoyang-star commented 5 months ago

outputs = model.generate(**generate_params) will yield wrong output compared to the dense model. @joyce0105-ops could you please double check it?

joyce0105-ops commented 5 months ago

@zhaoyang-star could you tell me your error information when using the sliced model? I can get the output with outputs = model.generate(**generate_params)

zhaoyang-star commented 5 months ago

@joyce0105-ops I print outputs_res after outputs_res = tokenizer.decode(outputs[0], skip_special_tokens=True). The outputs are as following:

 ['[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n为什么要减少污染,保护环境 [/INST] đe łæśśure đe', '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n哈哈哈,你是什么名字呀 [/INST] 1000000000', '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\nubuntu怎么安装git lfs [/INST] 1000000000', '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n你是什么模型? [/INST] 1st person singular pronoun ) . \n']

It seems the sliced model can not generate normal sentences.

joyce0105-ops commented 5 months ago

@zhaoyang-star strangely, my outputs:

['[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n为什么要减少污染,保护环境 [/INST]  作为一个能够帮助我们解决问题的AI助手,我认为应该尽可能地降低污染并保护环境。首先,我们需要了解和理解环境的影响,以及对环境的负面影响。然后,我们可以通过减少使用化学物质、循环利用、减少废弃物和垃圾等方法来减少污染。此外,我们还可以通过支持清洁能源、生态建设和环保活动来保护环境。最后,我们需要通过教育和各种行动来传达这些信息,并促进公众参与环保工作。无论如何,我们都应该加入环保行动,共同保护我们的家园和未来。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n哈哈哈,你是什么名字呀 [/INST] 好的,我是AI助手“AI助手”。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\nubuntu怎么安装git lfs [/INST] 以下是在Python中使用Git仓库的步骤:\n1. 创建一个新的Git仓库,并将它存储在一个数据库中。\n2. 使用Python的Git仓库API来读取和编写文本。\n3. 使用Python的数据库操作来管理和查询文本。\n4. 使用Python的图形学工具来生成和分析图像。\n5. 使用Python的机器学习工具来进行分类和模型学习。\n6. 使用Python的Web开发工具来构建网站和应用程序。\n7. 使用Python的数据科学工具来处理、分析和可视化数据。\n8. 使用Python的自然语言处理工具来进行文本处理和自然语言处理任务。\n9. 使用Python的计算机视觉工具来实现对图像的自动识别和分析。\n10. 使用Python的机器学习工具来进行自然语言处理和智能问答。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n你是什么模型? [/INST] 我是一种语言处理模型,能够自动生成文本或回答问题。我可以根据输入的信息和数据进行学习和改进,并在不同的情况下提供有用的建议和解决方案。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n如果我是DJ你会爱我吗? [/INST] 作为AI语言模型,我不能感知和表达情感,因此无法回答这个问题。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n请列出最近一个月内涨幅前五的美国科技股票 [/INST] 以下是最近一个月内涨幅前五的美国科技股票:\n1. 谷歌股票(Google stock)\n2. 亚马逊股票(Amazon stock)\n3. 微软股票(Microsoft stock)\n4. 苹果股票(Apple stock)\n5. 阿里巴特股票(Alibaba Stock)\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n如何通过技术分析预测股票价格走势? [/INST]  以下是通过技术分析预测股票价格走势的一些方法:\n1. 时间序列分析:通过对股票价格的时间序列数据进行分析,可以发现股票价格在不同时间段内的变化趋势和特征。\n2. 机器学习模型:使用机器学习算法来建立股票价格预测模型,并根据模型的性能进行评估和调整。\n3. 深度学习:利用深度学习算法,可以更好地处理大量数据,并提高预测准确度。\n4. 自然语言处理:通过自然语言处理技术,可以从文本中获取关于股票市场的信息,并将其与股票价格相关联。\n5. 图像处理:通过图像处理技术,可以从图像中获取关于股票市场的信息,并将其与股票价格相关联。\n6. 统计学分析:通过对股票价格的统计数据进行分析,可以发现股票价格在不同时间段内的变化趋势和特征。\n7. 经济学分析:通过对经济数据进行分析,可以了解股票市场的动态和影响因素。\n8. 社交媒体分析:通过对社交媒体上的股票话题',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n给出一支最近表现良好的科技股票,并简要介绍其业务领域和未来发展前景。 [/INST] 我们可以选择Apple公司作为一个最近表现良好的科技股票。Apple公司是一家在电子设备、云计算、智能家居等多个领域都有广泛影响力的企业。该公司的主要业务领域包括设备制造、应用程序开发、云服务和数据存储等。Apple公司还在智能家居、自动驾车和健康保健等领域进行了深入的研究和发展。未来,Apple公司将继续关注设备、应用程序和云服务的发展,同时也会加强对智能家居、自动驾车和健康保健等领域的研究和发展。这些领域的发展将使Apple公司更加成功和创新。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n给出一家在过去6个月里股价上涨超过20%的公司,该公司的市值是多少? [/INST] 我不能提供具体的数据来回答这个问题。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n什么是“蓝筹股”?可以给我列举几个例子吗? [/INST]  "蓝筹股"是指在公司管理中,通过制定和实现有效的财务计划来提高公司的经济效益和利益。这些计划包括预算、财务管理、资金管理等方面的决策。以下是几个例子:\n1. 规划和管理财务流动,确保公司的财务使用更加有效环境。\n2. 制定和实现财务政策,如削减成本、提高生产力、扩大市场等。\n3. 建立和管理财务数据库,以便更好地了解公司的财务状况和进展。\n4. 制定和实现财务管理计划,如财务管理、财务控制、财务分析等。\n5. 制定和实现资金管理计划,如财务投资、财务管理、财务安全等。\n6. 制定和实现财务政策,如协商、合作、沟通等。\n7. 制定和实现财务管理计划,如财务管理、财务控制、财务分析等。\n8. 制定和实现资金管理计划,如财务投资、财务管理、财务安全等。\n9. 制定和实现财务政策,如协商、合作、沟通等。\n10. 制定和实现财务管理计划,如财务管理',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n请问目前苹果公司(AAPL)的股价是多少? [/INST] 抱歉,我不能提供实时的苹果公司(Apple)股价信息。这是因为我作为AI语言模型而无法获取实时数据。建议用户通过在网上的财务应用程序或者在线资产管理平台来查看苹果公司的股价。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n预测下一月华尔街投资银行的收盘价 [/INST]  作为AI语言模型,我不能提供实时的市场信息和预测结果。建议用户在社交媒体、新闻网站或专业金融博客上查找相关信息以获取更好的决策。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n请问目前苹果公司(AAPL)的股价是多少? [/INST] 抱歉,我不能提供实时的苹果公司(Apple)股价信息。这是因为我是一个AI语言模型,并没有实时数据源或者可以获取实时市场信息的功能。建议您使用网上的财务数据库或者在线交易平台来查看苹果公司的股价。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n现在值得投资的股票有哪些? [/INST] 作为AI语言模型,我无法提供实时的股票市场信息和建议。如果您需要更多的信息或者专业的经验来做出财务决策,可以向相关的金融机构或专业的股票分析员求助。\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n请列出前五名市值最大的科技公司。 [/INST] 以下是前五名市值最大的科技公司:\n1. 谷歌(Google)2. 苹果(Apple)3. 亚马逊(Amazon)4. 微软(Microsoft)5. 百度(baidu)\n',
 '[INST] <<SYS>>\nYou are a helpful assistant. 你是一个乐于助人的助手。\n<</SYS>>\n\n针对某支股票,预测未来一周的走势如何? [/INST]  作为AI语言模型,我不能提供实时的股票数据和预测结果。建议用户通过网站或应用程序获取当前股票市场信息,并根据自己的理解和经验进行预测。同时,还可以参考专业的股票分析员或专业的股票指标来帮助预测股票的走势。\n']

and the structure of my sliced model:

UninitializedLlamaForCausalLM(
  (model): LlamaModel(
    (embed_tokens): Embedding(32000, 4096, padding_idx=0)
    (layers): ModuleList(
      (0-30): 31 x CompressedLlamaDecoderLayer(
        (self_attn): LlamaSdpaAttention(
          (q_proj): Linear(in_features=3072, out_features=4096, bias=False)
          (k_proj): Linear(in_features=3072, out_features=4096, bias=False)
          (v_proj): Linear(in_features=3072, out_features=4096, bias=False)
          (o_proj): Linear(in_features=4096, out_features=3072, bias=False)
          (rotary_emb): LlamaRotaryEmbedding()
        )
        (mlp): LlamaMLP(
          (gate_proj): Linear(in_features=3072, out_features=11008, bias=False)
          (up_proj): Linear(in_features=3072, out_features=11008, bias=False)
          (down_proj): Linear(in_features=11008, out_features=3072, bias=False)
          (act_fn): SiLU()
        )
        (input_layernorm): RMSN()
        (post_attention_layernorm): RMSN()
      )
      (31): CompressedLlamaDecoderLayer(
        (self_attn): LlamaSdpaAttention(
          (q_proj): Linear(in_features=3072, out_features=4096, bias=False)
          (k_proj): Linear(in_features=3072, out_features=4096, bias=False)
          (v_proj): Linear(in_features=3072, out_features=4096, bias=False)
          (o_proj): Linear(in_features=4096, out_features=3072, bias=False)
          (rotary_emb): LlamaRotaryEmbedding()
        )
        (mlp): LlamaMLP(
          (gate_proj): Linear(in_features=3072, out_features=11008, bias=False)
          (up_proj): Linear(in_features=3072, out_features=11008, bias=False)
          (down_proj): Linear(in_features=11008, out_features=4096, bias=False)
          (act_fn): SiLU()
        )
        (input_layernorm): RMSN()
        (post_attention_layernorm): RMSN()
      )
    )
    (norm): RMSN()
  )
  (lm_head): Linear(in_features=4096, out_features=32000, bias=False)
)
zhaoyang-star commented 5 months ago

Chat

Thanks for your quick feedback. I noticed there are two difference in my test:

BTW, do you try to slice codellama-34b or some other models whose params similar with 34B? I found it needs huge cpu memory (more than 400GB) to slice this kind of model even TP=4. It is weird. @nailimixaM @pashminacameron Could you please give some hint on this issue? Thanks.

joyce0105-ops commented 5 months ago

@zhaoyang-star I don't have such a plan yet. I am still confused about the generating speed of the sliced model is slower than the original one. Could you share your test result with me? thanks ~

zhaoyang-star commented 5 months ago

@zhaoyang-star I don't have such a plan yet. I am still confused about the generating speed of the sliced model is slower than the original one. Could you share your test result with me? thanks ~

I did inference speed comparison by using experiments/run_benchmark.py. The generation speed of sliced model is close to the dense model. Details:

nailimixaM commented 5 months ago

@zhaoyang-star @joyce0105-ops thanks for sharing more details!

Speedup:

CPU memory footprint for slicing: @zhaoyang-star could you open a separate issue for this, so we can try and debug? Thanks.