计算语言模型计算每秒钟生成的token数量it/s

main() 函数的stream循环中,我们可以计算每秒钟生成的token数量,然后输出 it/s。在流式生成过程中,我们可以使用Python的time模块来计算速度。在测试时,生成速度会受到多个因素的影响,包括设备性能、模型大小、输入文本长度等。

python 复制代码
import os
import torch
import platform
from colorama import Fore, Style
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation.utils import GenerationConfig
import time


def init_model():
    print("init model ...")
    model = AutoModelForCausalLM.from_pretrained(
        "baichuan-inc/Baichuan-13B-Chat",
        torch_dtype=torch.float16,
        device_map="cuda",
        trust_remote_code=True
    )

    model.generation_config = GenerationConfig.from_pretrained(
        "baichuan-inc/Baichuan-13B-Chat"
    )
    tokenizer = AutoTokenizer.from_pretrained(
        "baichuan-inc/Baichuan-13B-Chat",
        use_fast=False,
        trust_remote_code=True
    )
    return model, tokenizer


def clear_screen():
    if platform.system() == "Windows":
        os.system("cls")
    else:
        os.system("clear")
    print(Fore.YELLOW + Style.BRIGHT + "欢迎使用百川大模型,输入进行对话,clear 清空历史,CTRL+C 中断生成,stream 开关流式生成,exit 结束。")
    return []


def main(stream=True):
    model, tokenizer = init_model()

    messages = clear_screen()
    while True:
        prompt = input(Fore.GREEN + Style.BRIGHT + "\n用户:" + Style.NORMAL)
        if prompt.strip() == "exit":
            break
        if prompt.strip() == "clear":
            messages = clear_screen()
            continue
        print(Fore.CYAN + Style.BRIGHT + "\nBaichuan:" + Style.NORMAL, end='')
        if prompt.strip() == "stream":
            stream = not stream
            print(Fore.YELLOW + "({}流式生成)\n".format("开启" if stream else "关闭"), end='')
            continue
        messages.append({"role": "user", "content": prompt})
        if stream:
            position = 0
            try:
                start_time = time.time()
                total_tokens = 0
                for response in model.chat(tokenizer, messages, stream=True):
                    print(response[position:], end='', flush=True)
                    position = len(response)
                    total_tokens += len(tokenizer(response, return_tensors='pt')['input_ids'][0])
                    if torch.backends.mps.is_available():
                        torch.mps.empty_cache()
                end_time = time.time()
                elapsed_time = end_time - start_time
                tokens_per_second = total_tokens / elapsed_time
                print(f"\n\n生成速度:{tokens_per_second:.2f} tokens/s")
            except KeyboardInterrupt:
                pass
            print()

        else:
            response = model.chat(tokenizer, messages)
            print(response)
            if torch.backends.mps.is_available():
                torch.mps.empty_cache()
        messages.append({"role": "assistant", "content": response})

    print(Style.RESET_ALL)


if __name__ == "__main__":
    main()
相关推荐
zhengyawen66628 分钟前
深度学习之图像分类(一)
人工智能·深度学习·分类
不爱学英文的码字机器2 小时前
深度学习的力量:精准肿瘤检测从此不再遥远
人工智能·深度学习
tRNA做科研2 小时前
Pytorch深度学习教程_3_初识pytorch
人工智能·pytorch·深度学习
SylviaW082 小时前
神经网络八股(1)
人工智能·深度学习·神经网络
AAIshangyanxiu3 小时前
从CNN到 Transformer:基于PyTorch的遥感影像、无人机影像的地物分类、目标检测、语义分割和点云分类
pytorch·cnn·卷积神经网络·transformer·遥感影像目标检测
Black蜡笔小新4 小时前
AI大模型驱动的智能音视频通信:视频通话SDK工具EasyRTC在嵌入式设备中的应用探索
人工智能·语言模型·大模型·音视频·webrtc·rtc
Zhouqi_Hua4 小时前
LLM论文笔记 15: Transformers Can Achieve Length Generalization But Not Robustly
论文阅读·笔记·深度学习·语言模型·自然语言处理
冰淇淋百宝箱5 小时前
长文档处理痛点:GPT-4 Turbo引文提取优化策略与替代方案讨论
人工智能·深度学习·算法
HPC_fac130520678165 小时前
深度学习模型应用场景全解析:CNN、Transformer、BERT、RNN与GAN
rnn·深度学习·机器学习·数据挖掘·cnn·bert·transformer
时光旅人01号6 小时前
深度学习工厂的蓝图:拆解CUDA驱动、PyTorch与OpenCV的依赖关系
pytorch·深度学习·opencv