计算语言模型计算每秒钟生成的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()
相关推荐
黑妹天下第一乖1 小时前
第09讲 · 多媒体与音频 SDK:硬件编解码与端侧语音
人工智能·嵌入式硬件·深度学习·机器人·音视频·iot
FII工业富联科技服务3 小时前
2026年AI技术发展趋势分析:从模型能力突破到工业AI的真实应用
大数据·人工智能·深度学习·机器学习·制造·ai智能体·agentic ai
菩提树下的凡夫3 小时前
多线程是加载一个复用推理模型还是用多个独立的推理模型
人工智能·深度学习
草上飞95275 小时前
把前沿能力装进便宜产物,本身是多数模型还不会的能力
人工智能·深度学习·llm
跟我学机器学习5 小时前
Qwen3 Reranking原理与使用:重排模型在 RAG 中的作用
人工智能·深度学习·transformer
江润舟5 小时前
万物|炼器:从零手搓工业级旋转目标检测网络·卷4 —— 模块化重构(一)
人工智能·深度学习
129Lab6 小时前
电池热管理仿真的AI加速:用Python+PINN物理信息神经网络替代传统CFD的可行性探索
pytorch·python·cfd·pinn·物理信息神经网络·仿真加速·电池热管理
Yolanda_20227 小时前
21.神经网络-线性层及其他层介绍
人工智能·深度学习·神经网络
答案是你7 小时前
YOLOE 开放词汇检测 + ONNX / TensorRT 推理,开源了!
python·深度学习·yolo·目标检测·计算机视觉·视觉检测
朝朝辞暮i7 小时前
VLA 系统学习第 7 课:loss.backward() 到底做了什么?——从计算图到反向传播
人工智能·python·深度学习·神经网络·vla