Repository navigation
Expand file tree
/
Copy pathappendix-g.html
More file actions
1722 lines (1499 loc) · 60.6 KB
/
Copy pathappendix-g.html
File metadata and controls
1722 lines (1499 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>附录G:AI评估与基准测试 - AI学习笔记</title>
<meta name="description" content="AI评估与基准测试指南:掌握评估理由、评估规范、评估工具、基准测试、评估维度、自定义评估、评估流水线与结果分析">
<meta name="keywords" content="AI评估, 基准测试, lm-eval-harness, 评估流水线, 大模型评测">
<meta name="author" content="AI学习笔记">
<link rel="icon" type="image/x-icon" href="../../favicon.ico">
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700;900&family=Fira+Code:wght@400;500;600&display=swap" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<!-- KaTeX for math -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
<!-- Prism.js for code highlighting -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-bash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-json.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-yaml.min.js"></script>
<!-- AI-Notes共享样式 -->
<link rel="stylesheet" href="../assets/ai-notes.css">
</head>
<body>
<!-- ==================== 导航栏 ==================== -->
<nav class="ai-nav">
<a href="../../index.html" class="ai-nav-brand">
<i class="fas fa-brain"></i>
AI学习笔记
</a>
<ul class="ai-nav-links" id="navLinks">
<li><a href="../../index.html"><i class="fas fa-home"></i> 首页</a></li>
<li><a href="ch15.html"><i class="fas fa-robot"></i> Agent</a></li>
<li><a href="ch16.html"><i class="fas fa-tools"></i> 工具</a></li>
<li><a href="ch17.html"><i class="fas fa-book-open"></i> 知识库</a></li>
<li><a href="ch18.html"><i class="fas fa-layer-group"></i> 记忆</a></li>
<li><a href="ch19.html"><i class="fas fa-comment-dots"></i> 提示</a></li>
<li><a href="ch20.html"><i class="fas fa-database"></i> 数据</a></li>
<li><a href="ch21.html"><i class="fas fa-exclamation-circle"></i> 局限</a></li>
<li><a href="ch22.html"><i class="fas fa-toolbox"></i> 平台</a></li>
<li><a href="ch23.html"><i class="fas fa-history"></i> 简史</a></li>
<li><a href="ch24.html"><i class="fas fa-rocket"></i> 实战</a></li>
</ul>
<button class="ai-nav-toggle" id="navToggle" aria-label="切换导航">
<i class="fas fa-bars"></i>
</button>
</nav>
<!-- ==================== Hero Section ==================== -->
<section class="ai-hero">
<h1><i class="fas fa-brain"></i> AI 学习笔记</h1>
<p>附录G:AI评估与基准测试</p>
<div class="ai-hero-badges">
<span class="ai-hero-badge"><i class="fas fa-book"></i> 系统学习</span>
<span class="ai-hero-badge"><i class="fas fa-code"></i> 实践导向</span>
</div>
</section>
<!-- ==================== 主内容区域 ==================== -->
<div class="content-wrapper">
<!-- ========== 主内容 ========== -->
<main class="main-content">
<nav class="ai-chapter-nav">
<div class="breadcrumb">
<a href="../../index.html"><i class="fas fa-home"></i> 首页</a>
<span class="separator">/</span>
<span class="current">附录G:AI评估与基准测试</span>
</div>
<div class="chapter-nav-links">
<a href="ch33.html" class="prev-chapter"><i class="fas fa-arrow-left"></i> 上一章</a>
<a href="appendix-a.html" class="next-chapter">下一章 <i class="fas fa-arrow-right"></i></a>
</div>
</nav>
<!-- 附录G:AI评估与基准测试 -->
<!-- ============================================================ -->
<h2 class="ai-section-title"><i class="fas fa-chart-bar"></i> 附录G:AI评估与基准测试</h2>
<div class="concept-section">
<h3>学习目标</h3>
<div class="ai-box ai-box--objectives">
<ul>
<li>理解AI模型评估的核心理由与实际应用场景</li>
<li>掌握评估规范的设计原则与实施方法</li>
<li>熟练使用lm-eval-harness等主流评估工具</li>
<li>了解常见基准测试套件(MMLU、HumanEval等)的原理与用法</li>
<li>掌握多维度评估框架(准确性、鲁棒性、公平性等)</li>
<li>能够设计并构建自定义评估任务</li>
<li>具备构建端到端评估流水线的能力</li>
<li>学会分析评估结果并生成可操作的改进报告</li>
</ul>
</div>
</div>
<!-- ============================================================ -->
<!-- 第一节:为什么要评估 -->
<!-- ============================================================ -->
<div class="concept-section" id="section-1">
<h2><i class="fas fa-question-circle"></i> 第一节:为什么要评估</h2>
<p><span class="keyword-highlight">AI评估</span>是验证模型能力、发现潜在缺陷、指导迭代优化的关键环节。没有评估的模型开发就像没有指南针的航行——你不知道自己在进步还是在倒退。</p>
<h3>评估的核心价值</h3>
<p>评估在AI开发流程中扮演三重角色:</p>
<ul>
<li><strong>验证能力</strong>:量化模型在特定任务上的表现水平,回答"这个模型能做什么"</li>
<li><发现缺陷</strong>:暴露模型在边缘案例、偏见、安全性等方面的不足</li>
<li><strong>指导优化</strong>:为模型微调、提示工程、架构改进提供数据支撑</li>
</ul>
<h3>评估的实际应用场景</h3>
<table class="comparison-table">
<thead>
<tr>
<th>场景</th>
<th>评估目标</th>
<th>关键指标</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>模型选型</strong></td>
<td>比较不同模型在业务场景的表现</td>
<td>准确率、延迟、成本</td>
</tr>
<tr>
<td><strong>版本迭代</strong></td>
<td>验证新版本是否优于旧版本</td>
<td>各维度得分对比、回归检测</td>
</tr>
<tr>
<td><strong>安全审计</strong></td>
<td>检测模型的偏见、毒性、幻觉</td>
<td>毒性得分、公平性指标、幻觉率</td>
</tr>
<tr>
<td><strong>上线门槛</strong></td>
<td>判断模型是否达到部署标准</td>
<td>最低准确率、最大延迟、合规性</td>
</tr>
</tbody>
</table>
<div class="ai-tip">
<h5>为什么要建立评估体系?</h5>
<p>一个成熟的评估体系能帮你回答三个关键问题:模型当前水平如何?改进方向在哪里?何时可以发布?这比主观感受和少量测试用例可靠得多。</p>
</div>
<h3>不评估的风险</h3>
<p>跳过系统化评估会带来严重后果:</p>
<ul>
<li><strong>隐蔽的退化</strong>:修复一个bug时可能引入三个新bug,没有评估无法察觉</li>
<li><strong>虚假的信心</strong>:几个手动测试用例通过不代表模型整体可靠</li>
<li><strong>偏见放大</strong>:模型可能在特定群体上表现极差,但开发者毫不知情</li>
<li><strong>安全漏洞</strong>:未检测的越狱攻击路径可能被恶意利用</li>
</ul>
<div class="exercise-item">
<h5>练习题</h5>
<p>思考你正在开发或使用的一个AI应用,列出至少三个需要评估的维度,并说明每个维度对应的评估方法。</p>
</div>
</div>
<!-- ============================================================ -->
<!-- 第二节:评估规范 -->
<!-- ============================================================ -->
<div class="concept-section" id="section-2">
<h2><i class="fas fa-file-alt"></i> 第二节:评估规范</h2>
<p><span class="keyword-highlight">评估规范</span>(Evaluation Specification)是定义"评什么、怎么评、评到什么程度"的标准化文档。好的规范确保评估过程可重复、可比较、可审计。</p>
<h3>规范的核心要素</h3>
<p>一份完整的评估规范应包含以下内容:</p>
<ul>
<li><strong>评估目标</strong>:明确本次评估要回答的问题(如"模型在中文数学推理上的能力"</li>
<li><strong>评估范围</strong>:限定测试的数据集、任务类型、语言等边界</li>
<li><strong>评估指标</strong>:定义具体的量化指标(准确率、F1、BLEU等)</li>
<li><strong>通过标准</strong>:设定各指标的最低阈值</li>
<li><strong>评估方法</strong>:说明使用的工具、配置、运行环境</li>
<li><strong>结果记录</strong>:规定结果的存储格式与报告模板</li>
</ul>
<div class="concept-box">
<h4><i class="fas fa-lightbulb"></i> 评估规范模板</h4>
<pre><code class="language-yaml">evaluation_spec:
name: "v2.1-数学推理评估"
version: "1.0"
author: "AI团队"
created: "2025-01-15"
objective:
- 验证模型在中文数学推理任务上的能力
- 与基线模型进行对比
- 检测是否存在安全漏洞
scope:
datasets:
- GSM8K (英文数学推理)
- CMATH (中文数学推理)
- MATH (高难度数学)
languages: ["zh", "en"]
model_versions: ["gpt-4o", "qwen-72b", "custom-v2.1"]
metrics:
accuracy:
type: "exact_match"
threshold: 0.85
reasoning_quality:
type: "chain_of_thought_score"
threshold: 0.70
safety:
type: "toxicity_score"
threshold: 0.05
method:
tool: "lm-eval-harness"
config: "configs/math_eval.yaml"
num_fewshot: 5
batch_size: 32
output:
format: "json"
location: "results/v2.1/math_eval/"
report: "results/v2.1/math_eval/report.md"</code></pre>
</div>
<h3>评估规范的迭代</h3>
<p>评估规范本身也需要迭代优化:</p>
<ol>
<li><strong>初版</strong>:基于经验和最佳实践快速建立</li>
<li><strong>校准</strong>:用已知模型运行评估,调整阈值合理性</li>
<li><strong>扩展</strong>:根据新发现的问题补充评估维度</li>
<li><strong>自动化</strong>:将规范转化为CI/CD流水线中的自动检查</li>
</ol>
<div class="ai-info">
<h5>规范与评估的关系</h5>
<p>评估规范是"宪法",评估执行是"执法"。没有规范的评估是随意的;没有执行的规范是空洞的。两者缺一不可。</p>
</div>
<h3>完整评估规范示例</h3>
<p>以下是一个更完整的生产级评估规范模板,包含多阶段评估和自动化集成:</p>
<div class="concept-box">
<h4><i class="fas fa-file-code"></i> 生产级评估规范YAML模板</h4>
<pre><code class="language-yaml">evaluation_spec:
name: "production-eval-v2.1"
version: "2.1.0"
author: "AI团队"
created: "2025-06-15"
last_updated: "2025-06-20"
# ==================== 评估目标 ====================
objective:
primary: "验证模型在客服场景中的综合能力"
secondary:
- "确保回答准确性达到95%以上"
- "保证安全合规,无有害输出"
- "响应时间符合SLA要求"
# ==================== 评估范围 ====================
scope:
models:
- name: "custom-customer-service-v2.1"
type: "fine-tuned"
base: "qwen-72b"
- name: "baseline"
type: "commercial"
provider: "openai"
model: "gpt-4o"
datasets:
- name: "customer_service_test"
version: "1.2"
size: 500
split: "test"
source: "internal_annotated"
- name: "edge_cases"
version: "1.0"
size: 100
split: "test"
source: "synthetic_augmented"
languages: ["zh-CN"]
domains: ["customer_service", "technical_support"]
# ==================== 评估维度 ====================
dimensions:
- name: "accuracy"
description: "回答准确性"
weight: 0.4
metrics:
- type: "exact_match"
name: "intent_accuracy"
threshold: 0.90
- type: "f1_score"
name: "entity_f1"
threshold: 0.85
- name: "helpfulness"
description: "回答有用性"
weight: 0.3
metrics:
- type: "human_rating"
name: "quality_score"
scale: 1-5
threshold: 4.0
- type: "completion_rate"
name: "task_completion"
threshold: 0.95
- name: "safety"
description: "安全性"
weight: 0.2
metrics:
- type: "toxicity_score"
name: "harmlessness"
threshold: 0.05
- type: "policy_violation"
name: "compliance"
threshold: 0.0
- name: "efficiency"
description: "效率"
weight: 0.1
metrics:
- type: "latency_p95"
name: "response_time"
threshold: 2000 # ms
- type: "throughput"
name: "tokens_per_second"
threshold: 50
# ==================== 执行配置 ====================
execution:
tool: "lm-eval-harness"
version: "0.4.3"
num_fewshot: 3
batch_size: 32
max_gen_tokens: 512
temperature: 0.0
hardware:
gpus: "8x A100-80GB"
precision: "fp16"
parallelism:
tensor_parallel: 4
pipeline_parallel: 1
# ==================== 通过标准 ====================
pass_criteria:
overall_score: 0.85
dimension_scores:
accuracy: 0.85
helpfulness: 0.80
safety: 0.95 # 安全性要求更高
efficiency: 0.70
blocking_conditions:
- "safety.toxicity_score > 0.1"
- "safety.policy_violation > 0"
comparison:
baseline: "gpt-4o"
min_improvement: 0.0 # 不低于基线
# ==================== 输出配置 ====================
output:
format: "json"
location: "results/production-eval-v2.1/"
artifacts:
- "results.json"
- "metrics_summary.json"
- "error_analysis.json"
- "comparison_report.html"
notifications:
- type: "email"
recipients: ["ai-team@company.com"]
on: ["failure", "significant_regression"]
- type: "slack"
channel: "#ai-model-updates"
on: ["success", "failure"]
# ==================== CI/CD集成 ====================
cicd:
trigger: "on_merge_to_main"
auto_run: true
timeout: 3600 # 1小时
gates:
- name: "accuracy_gate"
metric: "accuracy.intent_accuracy"
threshold: 0.85
blocking: true
- name: "safety_gate"
metric: "safety.harmlessness"
threshold: 0.95
blocking: true</code></pre>
</div>
<div class="exercise-item">
<h5>练习题</h5>
<p>为你负责的AI项目编写一份完整评估规范(YAML格式),包含评估目标、范围、维度、通过标准、CI/CD集成五个核心字段。</p>
</div>
</div>
<!-- ============================================================ -->
<!-- 第三节:评估工具 -->
<!-- ============================================================ -->
<div class="concept-section" id="section-3">
<h2><i class="fas fa-tools"></i> 第三节:评估工具</h2>
<p>选择合适的评估工具能大幅提升评估效率。以下是主流评估工具的对比与使用指南。</p>
<h3>主流评估工具对比</h3>
<table class="comparison-table">
<thead>
<tr>
<th>工具</th>
<th>特点</th>
<th>适用场景</th>
<th>上手难度</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>lm-eval-harness</strong></td>
<td>标准化框架,任务丰富,社区活跃</td>
<td>通用模型评估、学术研究</td>
<td>中等</td>
</tr>
<tr>
<td><strong>OpenCompass</strong></td>
<td>中文友好,支持100+数据集</td>
<td>中文模型评估、国产模型对比</td>
<td>中等</td>
</tr>
<tr>
<td><strong>HELM</strong></td>
<td>全面覆盖,标准化报告格式</td>
<td>全面基准测试、模型卡片生成</td>
<td>较高</td>
</tr>
<tr>
<td><strong>promptfoo</strong></td>
<td>轻量级,YAML配置,支持多提供商</td>
<td>快速原型评估、提示工程迭代</td>
<td>低</td>
</tr>
</tbody>
</table>
<h3>lm-eval-harness 快速上手</h3>
<p><span class="keyword-highlight">lm-eval-harness</span>(由EleutherAI开发)是最广泛使用的开源评估框架。以下是安装与基本使用:</p>
<pre><code class="language-bash"># 安装 lm-eval-harness
pip install lm-eval
# 或从源码安装(推荐,可获取最新任务)
git clone https://github.com/EleutherAI/lm-evaluation-harness.git
cd lm-evaluation-harness
pip install -e .
# 验证安装
lm_eval --help</code></pre>
<h3>评估单个模型</h3>
<p>使用lm-eval-harness评估模型在MMLU上的表现:</p>
<pre><code class="language-bash"># 评估 HuggingFace 模型在 MMLU 上的表现(5-shot)
lm_eval --model hf \
--model_args pretrained=meta-llama/Llama-3-8B-Instruct \
--tasks mmlu \
--num_fewshot 5 \
--batch_size 16 \
--output_path results/llama3-8b-mmlu
# 评估 OpenAI API 模型
lm_eval --model openai-completions \
--model_args model=gpt-4o-mini \
--tasks mmlu,hellaswag,arc_challenge \
--num_fewshot 0 \
--output_path results/gpt4o-mini</code></pre>
<div class="ai-tip">
<h5>选择评估任务的建议</h5>
<p>不要试图一次评估所有任务。先选择3-5个与你的应用场景最相关的任务,建立基线后再逐步扩展。常见起点任务:<strong>MMLU</strong>(知识)、<strong>HumanEval</strong>(代码)、<strong>GSM8K</strong>(数学)、<strong>TruthfulQA</strong>(真实性)。</p>
</div>
<div class="exercise-item">
<h5>练习题</h5>
<p>安装lm-eval-harness,选择一个开源模型(如Llama-3-8B),在至少两个基准任务上运行评估。记录评估结果并与其他同学的模型进行对比。</p>
</div>
</div>
<!-- ============================================================ -->
<!-- 第四节:基准测试 -->
<!-- ============================================================ -->
<div class="concept-section" id="section-4">
<h2><i class="fas fa-trophy"></i> 第四节:基准测试</h2>
<p><span class="keyword-highlight">基准测试</span>(Benchmark)是标准化的测试集与评估协议,用于在相同条件下公平比较不同模型的能力。</p>
<h3>常见基准测试概览</h3>
<table class="comparison-table">
<thead>
<tr>
<th>基准</th>
<th>评估能力</th>
<th>任务类型</th>
<th>规模</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>MMLU</strong></td>
<td>多学科知识</td>
<td>选择题(4选1)</td>
<td>57个学科,14K题</td>
</tr>
<tr>
<td><strong>HumanEval</strong></td>
<td>代码生成</td>
<td>函数补全 + 单元测试</td>
<td>164个编程题</td>
</tr>
<tr>
<td><strong>GSM8K</strong></td>
<td>小学数学推理</td>
<td>应用题求解</td>
<td>8.5K题</td>
</tr>
<tr>
<td><strong>TruthfulQA</strong></td>
<td>真实性与幻觉</td>
<td>开放问题 + GPT评判</td>
<td>817个问题</td>
</tr>
<tr>
<td><strong>HellaSwag</strong></td>
<td>常识推理</td>
<td>句子补全(4选1)</td>
<td>10K题</td>
</tr>
<tr>
<td><strong>ARC-Challenge</strong></td>
<td>科学推理</td>
<td>选择题(4选1)</td>
<td>2.6K题(困难集)</td>
</tr>
<tr>
<td><strong>WinoGrande</strong></td>
<td>常识消歧</td>
<td>代词消歧(2选1)</td>
<td>1.7K题</td>
</tr>
</tbody>
</table>
<h3>如何解读基准分数</h3>
<p>基准分数需要结合上下文理解:</p>
<ul>
<li><strong>绝对分数</strong>:80%的MMLU准确率意味着什么?需要与人类基准(~90%)和随机基线(~25%)对比</li>
<li><strong>相对排名</strong>:同一模型在不同版本的评估中分数可能波动,需要看趋势而非单点</li>
<li><strong>任务相关性</strong>:在HellaSwag上的高分不等于在你的业务场景中表现好</li>
</ul>
<div class="ai-warning">
<h5>基准测试的局限性</h5>
<p>基准测试不等于真实能力。模型可能通过"刷榜"在特定基准上取得高分,但在实际应用中表现平庸。始终建议:在基准测试之外,建立针对你具体场景的<strong>自定义评估集</strong>。</p>
</div>
<h3>运行基准测试的最佳实践</h3>
<pre><code class="language-bash"># 1. 先运行小规模快速评估
lm_eval --model hf \
--model_args pretrained=your-model \
--tasks mmlu \
--num_fewshot 5 \
--limit 100 \ # 先跑100题验证流程
--output_path results/quick-test
# 2. 确认无误后运行完整评估
lm_eval --model hf \
--model_args pretrained=your-model \
--tasks mmlu,hellaswag,arc_challenge,gsm8k \
--num_fewshot 5 \
--batch_size 16 \
--output_path results/full-eval
# 3. 对比多次评估结果
lm_eval --model hf \
--model_args pretrained=your-model-v2 \
--tasks mmlu \
--num_fewshot 5 \
--output_path results/v2-mmlu \
--compare_results results/v1-mmlu</code></pre>
<div class="exercise-item">
<h5>练习题</h5>
<p>选择一个开源模型,分别在GSM8K(数学)和MMLU(知识)上运行5-shot评估。分析两个任务的分数差异,讨论模型的优势与短板。</p>
</div>
</div>
<!-- ============================================================ -->
<!-- 第五节:评估维度 -->
<!-- ============================================================ -->
<div class="concept-section" id="section-5">
<h2><i class="fas fa-layer-group"></i> 第五节:评估维度</h2>
<p>单一维度的评估只能看到模型能力的冰山一角。<span class="keyword-highlight">多维度评估</span>能帮助你全面了解模型的优势与弱点。</p>
<h3>核心评估维度</h3>
<div class="concept-box">
<h4><i class="fas fa-th-large"></i> 评估维度框架</h4>
<div class="diagram-section">
<div class="diagram-card">
<i class="fas fa-bullseye"></i>
<div class="card-title">准确性</div>
<div class="card-desc">任务完成的正确率</div>
</div>
<span class="diagram-arrow"><i class="fas fa-plus"></i></span>
<div class="diagram-card">
<i class="fas fa-shield-alt"></i>
<div class="card-title">鲁棒性</div>
<div class="card-desc">面对噪声的稳定性</div>
</div>
<span class="diagram-arrow"><i class="fas fa-plus"></i></span>
<div class="diagram-card">
<i class="fas fa-balance-scale"></i>
<div class="card-title">公平性</div>
<div class="card-desc">对不同群体的平等性</div>
</div>
<span class="diagram-arrow"><i class="fas fa-plus"></i></span>
<div class="diagram-card">
<i class="fas fa-lock"></i>
<div class="card-title">安全性</div>
<div class="card-desc">抵抗攻击的能力</div>
</div>
<span class="diagram-arrow"><i class="fas fa-plus"></i></span>
<div class="diagram-card">
<i class="fas fa-tachometer-alt"></i>
<div class="card-title">效率</div>
<div class="card-desc">延迟与资源消耗</div>
</div>
</div>
</div>
<h3>各维度详解</h3>
<table class="comparison-table">
<thead>
<tr>
<th>维度</th>
<th>评估内容</th>
<th>常用指标</th>
<th>评估方法</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>准确性</strong></td>
<td>模型回答的正确程度</td>
<td>准确率、F1、BLEU、ROUGE</td>
<td>基准测试集</td>
</tr>
<tr>
<td><strong>鲁棒性</strong></td>
<td>面对拼写错误、同义替换、格式变化时的表现</td>
<td>扰动后的准确率下降比例</td>
<td>对抗性测试集</td>
</tr>
<tr>
<td><strong>公平性</strong></td>
<td>对不同性别、种族、年龄群体的表现差异</td>
<td>人口统计均等差距、机会均等</td>
<td>分组评估</td>
</tr>
<tr>
<td><strong>安全性</strong></td>
<td>抵抗越狱攻击、拒绝有害请求的能力</td>
<td>攻击成功率、拒绝率</td>
<td>红队测试</td>
</tr>
<tr>
<td><strong>效率</strong></td>
<td>推理速度、内存占用、成本</td>
<td>延迟(ms)、吞吐量(tokens/s)</td>
<td>性能基准测试</td>
</tr>
</tbody>
</table>
<h3>鲁棒性评估示例</h3>
<p>通过输入扰动测试模型的鲁棒性:</p>
<pre><code class="language-python">from lm_eval import evaluator
from lm_eval.tasks import TaskManager
def evaluate_robustness(model, task_name, perturbation_rate=0.1):
"""评估模型在输入扰动下的鲁棒性"""
import random
# 1. 运行原始评估
baseline_results = evaluator.simple_evaluate(
model="hf",
model_args=f"pretrained={model}",
tasks=[task_name],
num_fewshot=5
)
baseline_acc = baseline_results["results"][task_name]["acc"]
# 2. 应用输入扰动(模拟拼写错误、同义替换等)
perturbed_results = apply_perturbation(
task_name, perturbation_rate
)
# 3. 计算鲁棒性得分
robustness_score = perturbed_acc / baseline_acc
print(f"原始准确率: {baseline_acc:.4f}")
print(f"扰动后准确率: {perturbed_acc:.4f}")
print(f"鲁棒性得分: {robustness_score:.4f}")
print(f"准确率下降: {(1-robustness_score)*100:.1f}%")
return {
"baseline": baseline_acc,
"perturbed": perturbed_acc,
"robustness": robustness_score
}</code></pre>
<div class="ai-info">
<h5>评估维度的优先级</h5>
<p>不同应用场景对评估维度的优先级不同。医疗AI需要最高级别的安全性和公平性;搜索引擎需要高准确性;实时对话需要高效率。根据你的业务需求确定评估维度的优先级。</p>
</div>
<div class="exercise-item">
<h5>练习题</h5>
<p>选择一个评估维度(鲁棒性、公平性或安全性),设计一个简短的评估实验方案,包括测试数据构造、评估指标和预期结果分析方法。</p>
</div>
</div>
<!-- ============================================================ -->
<!-- 第六节:自定义评估 -->
<!-- ============================================================ -->
<div class="concept-section" id="section-6">
<h2><i class="fas fa-cogs"></i> 第六节:自定义评估</h2>
<p>通用基准测试无法覆盖所有场景。<span class="keyword-highlight">自定义评估</span>让你针对特定业务需求设计专属的评估任务。</p>
<h3>自定义评估的设计流程</h3>
<div class="flow-diagram">
<h4><i class="fas fa-project-diagram"></i> 评估设计流程</h4>
<div class="diagram-section">
<div class="diagram-card">
<i class="fas fa-search"></i>
<div class="card-title">需求分析</div>
<div class="card-desc">明确评估目标</div>
</div>
<span class="diagram-arrow"><i class="fas fa-arrow-right"></i></span>
<div class="diagram-card">
<i class="fas fa-database"></i>
<div class="card-title">数据构造</div>
<div class="card-desc">创建测试样本</div>
</div>
<span class="diagram-arrow"><i class="fas fa-arrow-right"></i></span>
<div class="diagram-card">
<i class="fas fa-check-double"></i>
<div class="card-title">指标定义</div>
<div class="card-desc">选择评估标准</div>
</div>
<span class="diagram-arrow"><i class="fas fa-arrow-right"></i></span>
<div class="diagram-card">
<i class="fas fa-play-circle"></i>
<div class="card-title">执行评估</div>
<div class="card-desc">运行测试并收集结果</div>
</div>
<span class="diagram-arrow"><i class="fas fa-arrow-right"></i></span>
<div class="diagram-card">
<i class="fas fa-chart-line"></i>
<div class="card-title">结果分析</div>
<div class="card-desc">解读数据并优化</div>
</div>
</div>
</div>
<h3>创建自定义评估任务</h3>
<p>以"中文客服对话质量评估"为例,展示如何创建自定义评估任务:</p>
<pre><code class="language-python">import json
from pathlib import Path
from typing import Dict, List
class CustomEvalTask:
"""自定义评估任务基类"""
def __init__(self, name: str, description: str):
self.name = name
self.description = description
self.examples = []
self.metrics = {}
def load_data(self, data_path: str):
"""加载评估数据"""
with open(data_path, 'r', encoding='utf-8') as f:
self.examples = json.load(f)
print(f"Loaded {len(self.examples)} examples for {self.name}")
def evaluate(self, model_fn, example: Dict) -> Dict:
"""评估单个样本"""
raise NotImplementedError
def compute_metrics(self, results: List[Dict]) -> Dict:
"""计算总体指标"""
raise NotImplementedError
class CustomerServiceEval(CustomEvalTask):
"""中文客服对话质量评估"""
def __init__(self):
super().__init__(
name="customer_service_eval",
description="评估模型在客服场景中的回答质量"
)
self.metrics = {
"accuracy": 0.0,
"helpfulness": 0.0,
"safety": 0.0
}
def evaluate(self, model_fn, example: Dict) -> Dict:
"""评估单个客服对话样本"""
query = example["query"]
expected_intent = example["expected_intent"]
expected_answer_type = example["expected_answer_type"]
# 调用模型生成回答
response = model_fn(query)
# 评估维度
results = {
"query": query,
"response": response,
"intent_correct": self._check_intent(response, expected_intent),
"answer_type_correct": self._check_answer_type(
response, expected_answer_type
),
"has_greeting": self._check_greeting(response),
"has_closing": self._check_closing(response),
"safety_score": self._check_safety(response)
}
return results
def _check_intent(self, response, expected_intent):
"""检查回答是否匹配预期意图"""
intent_keywords = {
"refund": ["退款", "退货", "返还"],
"complaint": ["抱歉", "对不起", "歉意"],
"inquiry": ["查询", "查看", "确认"],
"technical": ["重启", "设置", "操作步骤"]
}
keywords = intent_keywords.get(expected_intent, [])
return any(kw in response for kw in keywords)
def _check_answer_type(self, response, expected_type):
"""检查回答类型是否正确"""
type_checks = {
"yes_no": any(w in response for w in ["可以", "不能", "支持", "不支持"]),
"step_by_step": any(w in response for w in ["第一", "步骤", "首先"]),
"explanation": len(response) > 50
}
return type_checks.get(expected_type, True)
def _check_greeting(self, response):
"""检查是否包含问候语"""
greetings = ["您好", "你好", "亲", "尊敬的"]
return any(g in response for g in greetings)
def _check_closing(self, response):
"""检查是否包含结束语"""
closings = ["还有其他", "请问", "祝您", "感谢"]
return any(c in response for c in closings)
def _check_safety(self, response):
"""安全性检查(简化版)"""
unsafe_patterns = ["骂人", "歧视", "威胁"]
return 1.0 if not any(p in response for p in unsafe_patterns) else 0.0
def compute_metrics(self, results: List[Dict]) -> Dict:
"""计算总体评估指标"""
n = len(results)
if n == 0:
return self.metrics
self.metrics = {
"accuracy": sum(r["intent_correct"] for r in results) / n,
"helpfulness": (
sum(r["answer_type_correct"] for r in results) / n * 0.6 +
sum(r["has_greeting"] for r in results) / n * 0.2 +
sum(r["has_closing"] for r in results) / n * 0.2
),
"safety": sum(r["safety_score"] for r in results) / n
}
return self.metrics</code></pre>
<h3>为lm-eval-harness创建自定义任务</h3>
<p>lm-eval-harness支持通过插件系统添加自定义评估任务。以下是完整的自定义任务创建流程:</p>
<div class="concept-box">
<h4><i class="fas fa-puzzle-piece"></i> lm-eval-harness自定义任务结构</h4>
<pre><code class="language-python">"""
自定义lm-eval-harness任务示例:中文客服对话质量评估
文件路径: lm_eval/tasks/custom/customer_service.py
"""
import json
from typing import Dict, List, Optional
from lm_eval.api.task import ConfigurableTask
from lm_eval.api.instance import Instance
from lm_eval.api.metrics import mean, pass_at_k
class CustomerServiceTask(ConfigurableTask):
"""中文客服对话质量评估任务"""
VERSION = "1.0"
OUTPUT_TYPE = "generate_until"
def __init__(self, config=None):
super().__init__(config=config)
self.config = config or {}
self.dataset = None
self._load_data()
def _load_data(self):
"""加载评估数据集"""
data_path = self.config.get("data_path", "data/customer_service_test.json")
with open(data_path, "r", encoding="utf-8") as f:
self.dataset = json.load(f)
def has_training_docs(self) -> bool:
return False
def has_validation_docs(self) -> bool:
return False
def has_test_docs(self) -> bool:
return True
def test_docs(self):
return self.dataset
def doc_to_text(self, doc: Dict) -> str:
"""将文档转换为输入文本"""
return f"""你是一个专业的客服助手。请根据以下用户问题提供准确、有帮助的回答。
用户问题:{doc['query']}
客服回答:"""
def doc_to_target(self, doc: Dict) -> str:
"""将文档转换为目标文本"""
return doc["expected_answer"]
def construct_requests(
self, doc: Dict, ctx: str, **kwargs
) -> List[Instance]:
"""构造评估请求"""
return [
Instance(
instance_id=doc.get("id", ""),
request_type=self.OUTPUT_TYPE,
arguments={
"context": ctx,
"continuation": "",
"num_tokens": 512,
},
)
]
def process_results(
self, doc: Dict, results: List[str], **kwargs
) -> Dict:
"""处理评估结果"""
response = results[0]
# 多维度评估
scores = {
"accuracy": self._check_accuracy(response, doc),
"completeness": self._check_completeness(response, doc),
"safety": self._check_safety(response),
"relevance": self._check_relevance(response, doc),