LLM 大模型学习必知必会系列(十一):大模型自动评估理论和实战以及大模型评估框架详解0.前言大语言模型(LLM)评测是LLM开发和应用中的关键环节。目前评测方法可以分为人工评测和自动评测,其中,自动评测技术相比人工评测来讲,具有效率高、一致性好、可复现、鲁棒性好等特点,逐渐成为业界研究的重点。模型的自动评测技术可以分为rule-based和model-based两大类:rule-based方法:benchmark以客观题为主,例如多选题,被测的LLM通过理解context/question,来指定最佳答案解析LLM的response,与标准答案做对比计算metric(accuracy、rouge、bleu等)model-based方法:裁判员模型(e.g. GPT-4、Claude、Expert Models/Reward models)LLM Peer-examination如何评估一个LLM哪些维度?语义理解(Understanding)知识推理(Reasoning)专业能力(e.g. coding、math)应用能力(MedicalApps、AgentApps、AI-FOR-SCI ...)指令跟随(Instruction Following)鲁棒性(Robustness)偏见(Bias)幻觉(Hallucinations)安全性(Safety)例:GPT-4 vs LLaMA2-7B能力维度对比评测1. 自动评估方法模型效果评估基准和指标(Benchmarks & Metrics)数据集描述评价指标样例MMLUMassiveMultitaskLanguageUnderstanding 一个多任务数据集,由各种学科的多项选择题组成。涵盖STEM、人文、社科等领域。包括57个子任务,包括初等数学、美国历史、计算机科学、法律等等。AccuracyQuestion: In 2016, about how many people in the United States were homeless? A. 55,000 B. 550,000 C. 5,500,000 D. 55,000,000 Answer: BTriviaQA阅读理解数据集,包含超过65万个问题-答案-证据三元组。其包括95K个问答对,由冷知识爱好者提供 + 独立收集的事实性文档撰写EM(ExactMatch) F1 (word-level)(问题-答案-证据文档)MATH 12500道数学题,每道包含step-by-step solutionAccuracyHumanEvalHumanEval (Hand-Written Evaluation Set) 一个手写的问题解决数据集,要求根据给定的问题和代码模板,生成正确的代码片段。包含164个高质量的问题,涵盖五种编程语言:Python, C++, Java, Go, 和 JavaScript。pass@k{ "task_id": "test/0", "prompt": "def return1():\n", "canonical_solution": " return 1", "test": "def check(candidate):\n assert candidate() == 1", "entry_point": "return1" }Rule-based自动评测基本流程根据数据集原始question来构建prompt示例(few-shot)示例:few-shot with CoT # Examples in BBH Evaluate the result of a random Boolean expression. Q: not ( ( not not True ) ) is A: Let's think step by step. Remember that (i) expressions inside brackets are always evaluated first and that (ii) the order of operations from highest priority to lowest priority is "not", "and", "or", respectively. We first simplify this expression "Z" as follows: "Z = not ( ( not not True ) ) = not ( ( A ) )" where "A = not not True". Let's evaluate A: A = not not True = not (not True) = not False = True. Plugging in A, we get: Z = not ( ( A ) ) = not ( ( True ) ) = not True = False. So the answer is False. Q: True and False and not True and True is A: Let's think step by step. Remember that (i) expressions inside brackets are always evaluated first and that (ii) the order of operations from highest priority to lowest priority is "not", "and", "or", respectively. We first simplify this expression "Z" as follows: "Z = True and False and not True and True = A and B" where "A = True and False" and "B = not True and True". Let's evaluate A: A = True and False = False. Let's evaluate B: B = not True and True = not (True and True) = not (True) = False. Plugging in A and B, we get: Z = A and B = False and False = False. So the answer is False.模型预测Generate # Demo -- model_genereate 直接生成response def model_generate(query: str, infer_cfg: dict) -> str: inputs = tokenizer.encode(query) input_ids = inputs['input_ids'] ... # Process infer cfg (do_sample, top_k, top_p, temperature, special_tokens ...) generation_config = process_cfg(args) ... # Run inference output_ids = model.generate( input_ids=input_ids, attention_mask=attention_mask, generation_config=generation_config, ) response = tokenizer.decode(output_ids, **decode_kwargs) return responseLikelihood#Demo -- model_call方式计算loglikelihood # context + continuation 拼接,示例: # Question: 法国的首都是哪里? # Choices: A.北京 B.巴黎 C.汉堡 D.纽约 # pair-1: (ctx, cont) = (法国的首都是哪里?,A.北京) # pair-2: (ctx, cont) = (法国的首都是哪里?,B.巴黎) # pair-3: (ctx, cont) = (法国的首都是哪里?,C.汉堡) # pair-4: (ctx, cont) = (法国的首都是哪里?,D.纽约) # Logits --> def loglikelihood(self, inputs: list, infer_cfg: dict = None) -> list: # To predict one doc doc_ele_pred = [] for ctx, continuation in inputs: # ctx_enc shape: [context_tok_len] cont_enc shape: [continuation_tok_len] ctx_enc, cont_enc = self._encode_pair(ctx, continuation) inputs_tokens = torch.tensor( (ctx_enc.tolist() + cont_enc.tolist())[-(self.max_length + 1):][:-1], dtype=torch.long, device=self.model.device).unsqueeze(0) logits = self.model(inputs_tokens)[0] logits = torch.nn.functional.log_softmax(logits.float(), dim=-1) logits = logits[:, -len(cont_enc):, :] cont_enc = cont_enc.unsqueeze(0).unsqueeze(-1) logits = torch.gather(logits.cpu(), 2, cont_enc.cpu()).squeeze(-1) choice_score = float(logits.sum()) doc_ele_pred.append(choice_score) # e.g. [-2.3, 1.1, -12.9, -9.2], length=len(choices) return doc_ele_pred2.评价指标(Metrics)WeightedAverageAccuracy 加权平均准确率Perplexity 困惑度Rouge (Recall-Oriented Understudy for Gisting Evaluation)Bleu (Bilingual evaluation understudy)ELO Rating SystemPASS@K2.1 Model-based自动评测中心化评测中心化评测模式下,裁判员模型只有一个,可靠性高,但容易收到裁判员模型的bias影响去中心化评测去中心化评测方式,要求模型之间做peer-examination特点是公平性好,但计算量大,且鲁棒性不高裁判员模型GPT-4、Claude、Qwen-Max等 (产品APIs)PandLM、Auto-J (tuned from LLM, like LLaMA)Reward models (Ranking learning)Chatbot Arena -竞技场模式(Battle count of each combination of models, from LMSYS)(Fraction of Model A wins for all non-tied A vs. B battles, from LMSYS)LLM指令攻防指令诱导 (诱导模型输出目标答案,from SuperCLUE)有害指令注入 (将真实有害意图注入到prompt中, from SuperCLUE)2.2 模型性能评估model serving performance evaluation指标名称说明Time测试总时间(时间单位均为秒)Expected number of requests期望发送的请求数,和prompt文件以及期望number有关concurrency并发数completed完成的请求数succeed成功请求数failed失败请求数qps平均qpslatency平均latencytime to first token平均首包延迟throughputoutput tokens / seconds 平均每秒输出token数time per output token平均生成一个token需要的时间 总output_tokens/总时间package per request平均每个请求的包数time per package平均每包时间input tokens per request平均每个请求的输入token数output tokens per request平均每个请求输出token数2.3 问题和挑战基准失效&数据泄露静态数据集与快速演进的LLM能力形成GAP,导致基准失效公开的benchmark被泄露到LLM的开发PT、CPT、SFT等开发环节解决思路: 动态数据集裁判员模型的能力上限裁判员模型的存在明显的能力边界,很难胜任更多场景、更强模型的评测工作泛化性问题LLM幻觉的诊断问题3.LLM评估实战LLMuses框架--轻量化、端到端的大模型自动评估框架GitHub: https://github.com/modelscope/llmuses框架特性预置常用的测试基准,包括:MMLU、C-Eval、GSM8K、ARC、HellaSwag、TruthfulQA、MATH、HumanEval、BBH、GeneralQA等常用评估指标(metrics)的实现统一model接入,兼容多个系列模型的generate、chat接口客观题自动评估使用专家模型实现复杂任务的自动评估竞技场模式(Arena)评估报告生成与可视化LLM性能评测(Performance Evaluation)环境安装 # 1. 代码下载 git clone **********:modelscope/llmuses.git # 2. 安装依赖 cd llmuses/ pip install -r requirements/requirements.txt pip install -e .简单评测 python llmuses/run.py --model ZhipuAI/chatglm3-6b --datasets ceval --outputs ./outputs/test --limit 10--model: ModelScope模型id, (https://modelscope.cn/models/ZhipuAI/chatglm3-6b/summary) ,也可以是模型的本地路径--datasets: 数据集的id--limit: (每个sub-task)最大评测样本数带参数评测 python llmuses/run.py --model ZhipuAI/chatglm3-6b --outputs ./outputs/test2 --model-args revision=v1.0.2,precision=torch.float16,device_map=auto --datasets arc --limit 10 --model-args: 模型参数,以逗号分隔,key=value形式 --datasets: 数据集名称,参考下文`数据集列表`章节--mem-cache: 是否使用内存缓存,若开启,则已经跑过的数据会自动缓存,并持久化到本地磁盘--limit: 每个subset最大评估数据量竞技场模式--Single modeSingle mode,使用专家模型(GPT-4)对待测LLM进行打分 # Example python llmuses/run_arena.py --c registry/config/cfg_single.yaml --dry-run竞技场模式--Baseline modeBaseline mode,选定baseline模型,其它待测LLM与该模型进行对比 # Example python llmuses/run_arena.py --dry-run --c registry/config/cfg_pairwise_baseline.yaml竞技场模式--Pairwise modePairwise mode,待测LLM两两组合进行对弈 python llmuses/run_arena.py -c registry/config/cfg_arena.yaml --dry-run效果评测报告按照预定格式存放数据,使用streamlit启动可视化服务 # Usage: streamlit run viz.py -- --review-file llmuses/registry/data/qa_browser/battle.jsonl --category-file llmuses/registry/data/qa_browser/category_mapping.yaml报告可视化Leaderboard: https://modelscope.cn/leaderboard/58/ranking?type=free模型性能评测(Perf Eval)性能评测报告示例4.大模型评估框架-llmuses链接:https://github.com/modelscope/eval-scope大型语言模型评估(LLMs evaluation)已成为评价和改进大模型的重要流程和手段,为了更好地支持大模型的评测,我们提出了llmuses框架,该框架主要包括以下几个部分:预置了多个常用的测试基准数据集,包括:MMLU、CMMLU、C-Eval、GSM8K、ARC、HellaSwag、TruthfulQA、MATH、HumanEval等常用评估指标(metrics)的实现统一model接入,兼容多个系列模型的generate、chat接口自动评估(evaluator):客观题自动评估使用专家模型实现复杂任务的自动评估评估报告生成竞技场模式(Arena)可视化工具模型性能评估特点轻量化,尽量减少不必要的抽象和配置易于定制仅需实现一个类即可接入新的数据集模型可托管在ModelScope上,仅需model id即可一键发起评测支持本地模型可部署在本地评估报告可视化展现丰富的评估指标model-based自动评估流程,支持多种评估模式Single mode: 专家模型对单个模型打分Pairwise-baseline mode: 与 baseline 模型对比Pairwise (all) mode: 全部模型两两对比4.1 环境准备我们推荐使用conda来管理环境,并使用pip安装依赖:创建conda环境conda create -n eval-scope python=3.10conda activate eval-scope安装依赖pip install llmuses使用源码安装下载源码git clone https://github.com/modelscope/eval-scope.git安装依赖cd eval-scope/pip install -e .4.2快速开始简单评估在指定的若干数据集上评估某个模型,流程如下:如果使用git安装,可在任意路径下执行:python -m llmuses.run --model ZhipuAI/chatglm3-6b --template-type chatglm3 --datasets arc --limit 100如果使用源码安装,在eval-scope路径下执行:python llmuses/run.py --model ZhipuAI/chatglm3-6b --template-type chatglm3 --datasets mmlu ceval --limit 10其中,--model参数指定了模型的ModelScope model id,模型链接:ZhipuAI/chatglm3-6b带参数评估python llmuses/run.py --model ZhipuAI/chatglm3-6b --template-type chatglm3 --model-args revision=v1.0.2,precision=torch.float16,device_map=auto --datasets mmlu ceval --use-cache true --limit 10python llmuses/run.py --model qwen/Qwen-1_8B --generation-config do_sample=false,temperature=0.0 --datasets ceval --dataset-args '{"ceval": {"few_shot_num": 0, "few_shot_random": false}}' --limit 10参数说明:--model-args: 模型参数,以逗号分隔,key=value形式--datasets: 数据集名称,支持输入多个数据集,使用空格分开,参考下文数据集列表章节--use-cache: 是否使用本地缓存,默认为false;如果为true,则已经评估过的模型和数据集组合将不会再次评估,直接从本地缓存读取--dataset-args: 数据集的evaluation settings,以json格式传入,key为数据集名称,value为参数,注意需要跟--datasets参数中的值一一对应--few_shot_num: few-shot的数量--few_shot_random: 是否随机采样few-shot数据,如果不设置,则默认为true--limit: 每个subset最大评估数据量--template-type: 需要手动指定该参数,使得eval-scope能够正确识别模型的类型,用来设置model generation config。关于--template-type,具体可参考:模型类型列表可以使用以下方式,来查看模型的template type list:from llmuses.models.template import TemplateTypeprint(TemplateType.get_template_name_list())4.3 使用本地数据集数据集默认托管在ModelScope上,加载需要联网。如果是无网络环境,可以使用本地数据集,流程如下:下载数据集到本地#假如当前本地工作路径为 /path/to/workdirwget https://modelscope.oss-cn-beijing.aliyuncs.com/open_data/benchmark/data.zipunzip data.zip则解压后的数据集路径为:/path/to/workdir/data 目录下,该目录在后续步骤将会作为--dataset-dir参数的值传入使用本地数据集创建评估任务python llmuses/run.py --model ZhipuAI/chatglm3-6b --template-type chatglm3 --datasets arc --dataset-hub Local --dataset-dir /path/to/workdir/data --limit 10#参数说明#--dataset-hub: 数据集来源,枚举值: `ModelScope`, `Local`, `HuggingFace` (TO-DO) 默认为`ModelScope`#-dataset-dir: 当--dataset-hub为`Local`时,该参数指本地数据集路径; 如果--dataset-hub 设置为`ModelScope` or `HuggingFace`,则该参数的含义是数据集缓存路径。(可选)在离线环境加载模型和评测模型文件托管在ModelScope Hub端,需要联网加载,当需要在离线环境创建评估任务时,可参考以下步骤:#1. 准备模型本地文件夹,文件夹结构参考chatglm3-6b,链接:https://modelscope.cn/models/ZhipuAI/chatglm3-6b/files#例如,将模型文件夹整体下载到本地路径 /path/to/ZhipuAI/chatglm3-6b#2. 执行离线评估任务python llmuses/run.py --model /path/to/ZhipuAI/chatglm3-6b --template-type chatglm3 --datasets arc --dataset-hub Local --dataset-dir /path/to/workdir/data --limit 104.4 使用run_task函数提交评估任务配置任务import torchfrom llmuses.constants import DEFAULT_ROOT_CACHE_DIR#示例your_task_cfg = { 'model_args': {'revision': None, 'precision': torch.float16, 'device_map': 'auto'}, 'generation_config': {'do_sample': False, 'repetition_penalty': 1.0, 'max_new_tokens': 512}, 'dataset_args': {}, 'dry_run': False, 'model': 'ZhipuAI/chatglm3-6b', 'datasets': ['arc', 'hellaswag'], 'work_dir': DEFAULT_ROOT_CACHE_DIR, 'outputs': DEFAULT_ROOT_CACHE_DIR, 'mem_cache': False, 'dataset_hub': 'ModelScope', 'dataset_dir': DEFAULT_ROOT_CACHE_DIR, 'stage': 'all', 'limit': 10, 'debug': False }执行任务from llmuses.run import run_taskrun_task(task_cfg=your_task_cfg)4.4.1 竞技场模式(Arena)竞技场模式允许多个候选模型通过两两对比(pairwise battle)的方式进行评估,并可以选择借助AI Enhanced Auto-Reviewer(AAR)自动评估流程或者人工评估的方式,最终得到评估报告,流程示例如下:环境准备a. 数据准备,questions data格式参考:llmuses/registry/data/question.jsonlb. 如果需要使用自动评估流程(AAR),则需要配置相关环境变量,我们以GPT-4 based auto-reviewer流程为例,需要配置以下环境变量:> export OPENAI_API_KEY=YOUR_OPENAI_API_KEY配置文件arena评估流程的配置文件参考: llmuses/registry/config/cfg_arena.yaml字段说明: questions_file: question data的路径 answers_gen: 候选模型预测结果生成,支持多个模型,可通过enable参数控制是否开启该模型 reviews_gen: 评估结果生成,目前默认使用GPT-4作为Auto-reviewer,可通过enable参数控制是否开启该步骤 elo_rating: ELO rating 算法,可通过enable参数控制是否开启该步骤,注意该步骤依赖review_file必须存在执行脚本#Usage:cd llmuses#dry-run模式 (模型answer正常生成,但专家模型不会被触发,评估结果会随机生成)python llmuses/run_arena.py -c registry/config/cfg_arena.yaml --dry-run#执行评估流程python llmuses/run_arena.py --c registry/config/cfg_arena.yaml结果可视化#Usage:streamlit run viz.py -- --review-file llmuses/registry/data/qa_browser/battle.jsonl --category-file llmuses/registry/data/qa_browser/category_mapping.yaml4.4.2 单模型打分模式(Single mode)这个模式下,我们只对单个模型输出做打分,不做两两对比。配置文件评估流程的配置文件参考: llmuses/registry/config/cfg_single.yaml字段说明: questions_file: question data的路径 answers_gen: 候选模型预测结果生成,支持多个模型,可通过enable参数控制是否开启该模型 reviews_gen: 评估结果生成,目前默认使用GPT-4作为Auto-reviewer,可通过enable参数控制是否开启该步骤 rating_gen: rating 算法,可通过enable参数控制是否开启该步骤,注意该步骤依赖review_file必须存在执行脚本#Example:python llmuses/run_arena.py --c registry/config/cfg_single.yaml4.4.3 Baseline模型对比模式(Pairwise-baseline mode)这个模式下,我们选定 baseline 模型,其他模型与 baseline 模型做对比评分。这个模式可以方便的把新模型加入到 Leaderboard 中(只需要对新模型跟 baseline 模型跑一遍打分即可)配置文件评估流程的配置文件参考: llmuses/registry/config/cfg_pairwise_baseline.yaml字段说明: questions_file: question data的路径 answers_gen: 候选模型预测结果生成,支持多个模型,可通过enable参数控制是否开启该模型 reviews_gen: 评估结果生成,目前默认使用GPT-4作为Auto-reviewer,可通过enable参数控制是否开启该步骤 rating_gen: rating 算法,可通过enable参数控制是否开启该步骤,注意该步骤依赖review_file必须存在执行脚本#Example:python llmuses/run_arena.py --c llmuses/registry/config/cfg_pairwise_baseline.yaml4.5 数据集列表DatasetNameLinkStatusNotemmlummluActivecevalcevalActivegsm8kgsm8kActivearcarcActivehellaswaghellaswagActivetruthful_qatruthful_qaActivecompetition_mathcompetition_mathActivehumanevalhumanevalActivebbhbbhActiveraceraceActivetrivia_qatrivia_qaTo be intergrated4.6 Leaderboard 榜单ModelScope LLM Leaderboard大模型评测榜单旨在提供一个客观、全面的评估标准和平台,帮助研究人员和开发者了解和比较ModelScope上的模型在各种任务上的性能表现。Leaderboard4.7 实验和报告ModelRevisionPrecisionHumanitiesSTEMSocialScienceOtherWeightedAvgTargetDeltaBaichuan2-7B-Basev1.0.2fp160.41110.38070.52330.5040.4506-Baichuan2-7B-Chatv1.0.4fp160.44390.3740.55240.54580.4762-chatglm2-6bv1.0.12fp160.38340.34130.47080.44450.40770.4546(CoT)-4.69%chatglm3-6b-basev1.0.1fp160.54350.50870.72270.64710.59920.614-1.48%internlm-chat-7bv1.0.1fp160.40050.35470.49530.47960.4297-Llama-2-13b-msv1.0.2fp160.43710.38870.55790.54370.4778-Llama-2-7b-msv1.0.2fp160.31460.30370.41340.38850.3509-Qwen-14B-Chatv1.0.6bf160.53260.53970.71840.68590.6102-Qwen-7Bv1.1.6bf160.3870.40.54030.51390.4527-Qwen-7B-Chat-Int8v1.1.6int80.43220.42770.60880.57780.5035-Target -- The official claimed score of the model on the datasetDelta -- The difference between the WeightedAvg score and the Target scoreSettings: (Split: test, Total num: 13985, 5-shot)ModelRevisionPrecisionHumanitiesSTEMSocialScienceOtherWeightedAvgAvgTargetDeltaBaichuan2-7B-Basev1.0.2fp160.42950.3980.57360.53250.47810.49180.5416 (official)-4.98%Baichuan2-7B-Chatv1.0.4fp160.43440.39370.58140.54620.48370.50290.5293 (official)-2.64%chatglm2-6bv1.0.12fp160.39410.3760.48970.47060.42880.4442--chatglm3-6b-basev1.0.1fp160.53560.48470.71750.62730.58570.5995--internlm-chat-7bv1.0.1fp160.41710.39030.57720.54930.47690.4876--Llama-2-13b-msv1.0.2fp160.4840.41330.61570.58090.52010.53270.548 (official)-1.53%Llama-2-7b-msv1.0.2fp160.37470.33630.43720.45140.39790.40890.453 (official)-4.41%Qwen-14B-Chatv1.0.6bf160.5740.5530.74030.6840.63130.64140.646 (official)-0.46%Qwen-7Bv1.1.6bf160.45870.4260.60780.56290.50840.51510.567 (official)-5.2%Qwen-7B-Chat-Int8v1.1.6int80.46970.43830.62840.59670.52710.53470.554 (official)-1.93%4.8 性能评测工具专注于大语言模型的压测工具,可定制化支持各种不通的数据集格式,以及不同的API协议格式。