File size: 25,368 Bytes
23ef895
26364d2
23ef895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c47b6e
713cdf1
2c47b6e
 
 
39e5ba2
2c47b6e
39e5ba2
e23124c
39e5ba2
2c47b6e
39e5ba2
2c47b6e
39e5ba2
e23124c
 
39e5ba2
2c47b6e
e23124c
2c47b6e
 
 
 
 
39e5ba2
2c47b6e
39e5ba2
 
 
2c47b6e
 
 
 
39e5ba2
2c47b6e
713cdf1
2c47b6e
 
 
 
 
 
39e5ba2
2c47b6e
 
39e5ba2
2c47b6e
 
39e5ba2
2c47b6e
39e5ba2
2c47b6e
39e5ba2
 
 
 
 
2c47b6e
 
713cdf1
2c47b6e
 
 
39e5ba2
2c47b6e
 
 
 
39e5ba2
 
 
 
 
 
 
2c47b6e
 
 
713cdf1
ce873b2
2c47b6e
ce873b2
 
 
 
 
2c47b6e
713cdf1
2c47b6e
39e5ba2
 
 
 
2c47b6e
 
39e5ba2
 
26364d2
39e5ba2
713cdf1
2c47b6e
 
ce873b2
 
2c47b6e
ce873b2
2c47b6e
e23124c
39e5ba2
713cdf1
2c47b6e
 
ce873b2
2c47b6e
39e5ba2
2c47b6e
 
 
 
 
 
39e5ba2
2c47b6e
39e5ba2
2c47b6e
 
 
 
 
39e5ba2
2c47b6e
39e5ba2
2c47b6e
 
 
 
 
 
 
39e5ba2
 
 
2c47b6e
 
 
 
 
713cdf1
39e5ba2
2c47b6e
 
 
39e5ba2
2c47b6e
39e5ba2
2c47b6e
39e5ba2
2c47b6e
 
39e5ba2
2c47b6e
39e5ba2
2c47b6e
39e5ba2
2c47b6e
 
39e5ba2
 
 
2c47b6e
39e5ba2
2c47b6e
 
 
 
 
39e5ba2
2c47b6e
39e5ba2
 
2c47b6e
39e5ba2
 
 
 
 
 
2c47b6e
39e5ba2
2c47b6e
 
 
39e5ba2
713cdf1
39e5ba2
2c47b6e
 
 
39e5ba2
e23124c
39e5ba2
2c47b6e
 
 
 
 
39e5ba2
2c47b6e
 
39e5ba2
2c47b6e
 
 
 
39e5ba2
2c47b6e
 
e23124c
2c47b6e
e23124c
2c47b6e
e23124c
713cdf1
2c47b6e
 
 
 
 
 
e23124c
 
 
2c47b6e
 
 
e23124c
2c47b6e
 
 
 
 
 
 
 
 
 
 
 
 
e23124c
2c47b6e
 
 
 
 
 
 
 
 
e23124c
2c47b6e
 
 
 
 
 
 
e23124c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e5ba2
e23124c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39e5ba2
e23124c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr

import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import time
import numpy as np
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import torch
import json
import re

# 选择三个小型文本生成模型
MODEL_CONFIGS = {
    "GPT2-Small": {
        "model_name": "gpt2",
        "description": "OpenAI的GPT-2小型模型(1.24亿参数)",
        "max_length": 100,
        "color": "#FF6B6B"
    },
    "DistilGPT2": {
        "model_name": "distilgpt2",
        "description": "GPT-2的蒸馏版本(8200万参数)",
        "max_length": 100,
        "color": "#4ECDC4"
    },
    "GPT2-Medium": {
        "model_name": "gpt2-medium",
        "description": "GPT-2中型模型(3.55亿参数)",
        "max_length": 100,
        "color": "#45B7D1"
    }
}

class TextGenerationComparator:
    def __init__(self):
        self.models = {}
        self.tokenizers = {}
        self.load_models()

    def load_models(self):
        """加载所有文本生成模型"""
        print("正在加载模型...")
        for model_key, config in MODEL_CONFIGS.items():
            try:
                print(f"加载 {model_key}...")
                # 使用pipeline方式加载,更简单且内存友好
                self.models[model_key] = pipeline(
                    "text-generation",
                    model=config["model_name"],
                    tokenizer=config["model_name"],
                    device=-1,  # 使用CPU,避免GPU内存问题
                    torch_dtype=torch.float32
                )
                print(f"✓ {model_key} 加载成功")
            except Exception as e:
                print(f"✗ {model_key} 加载失败: {e}")
                # 创建一个mock模型用于演示
                self.models[model_key] = None

    def generate_text(self, model_key, prompt, max_length=50, temperature=0.7, top_p=0.9):
        """使用指定模型生成文本"""
        if self.models[model_key] is None:
            return {
                "generated_text": f"[Model {model_key} not loaded correctly, this is a simulated output] {prompt} and this is a sample continuation of the text...",
                "inference_time": 0.5,
                "input_length": len(prompt.split()),
                "output_length": max_length,
                "parameters": {
                    "temperature": temperature,
                    "top_p": top_p,
                    "max_length": max_length
                }
            }

        try:
            start_time = time.time()

            # 生成文本
            result = self.models[model_key](
                prompt,
                max_length=len(prompt.split()) + max_length,
                temperature=temperature,
                top_p=top_p,
                do_sample=True,
                pad_token_id=50256,  # GPT-2的pad token
                num_return_sequences=1,
                truncation=True
            )

            end_time = time.time()

            # 提取生成的文本(去除原始prompt)
            generated_text = result[0]['generated_text']
            if generated_text.startswith(prompt):
                generated_text = generated_text[len(prompt):].strip()

            return {
                "generated_text": generated_text,
                "full_text": result[0]['generated_text'],
                "inference_time": round(end_time - start_time, 3),
                "input_length": len(prompt.split()),
                "output_length": len(generated_text.split()),
                "parameters": {
                    "temperature": temperature,
                    "top_p": top_p,
                    "max_length": max_length
                }
            }

        except Exception as e:
            return {
                "error": f"生成错误: {str(e)}",
                "inference_time": 0,
                "input_length": 0,
                "output_length": 0
            }

# 初始化比较器
comparator = TextGenerationComparator()

def run_text_generation_comparison(prompt, max_length, temperature, top_p):
    """运行所有模型的文本生成对比"""
    if not prompt.strip():
        return "Please enter a prompt.", "Please enter a prompt.", "Please enter a prompt." # 提示文本为英文

    results = {}

    for model_key in MODEL_CONFIGS.keys():
        result = comparator.generate_text(
            model_key,
            prompt,
            max_length=int(max_length),
            temperature=temperature,
            top_p=top_p
        )
        results[model_key] = result

    # 格式化输出
    def format_result(result):
        if "error" in result:
            return json.dumps(result, indent=2, ensure_ascii=False)

        # 这里的键名保留中文,值会是英文
        formatted = {
            "生成文本": result["generated_text"],
            "推断时间": f"{result['inference_time']}s",
            "生成Token数": result["output_length"],
            "生成速度": f"{result['output_length']/max(result['inference_time'], 0.001):.1f} tokens/s"
        }
        return json.dumps(formatted, indent=2, ensure_ascii=False)

    gpt2_result = format_result(results.get("GPT2-Small", {}))
    distilgpt2_result = format_result(results.get("DistilGPT2", {}))
    gpt2_medium_result = format_result(results.get("GPT2-Medium", {}))

    return gpt2_result, distilgpt2_result, gpt2_medium_result

def calculate_grace_scores_for_generation():
    """为文本生成任务计算GRACE评估分数"""
    # 基于文本生成任务特点的GRACE评分
    grace_data = {
        "GPT2-Small": {
            "Generalization": 7.5,  # 中等泛化能力,适用多种文本类型
            "Relevance": 8.2,       # 与输入提示相关性较好
            "Artistry": 7.8,        # 创造性和表达力中等
            "Consistency": 8.0,     # 输出一致性良好
            "Efficiency": 9.2       # 小模型,效率很高
        },
        "DistilGPT2": {
            "Generalization": 7.2,  # 蒸馏模型,泛化能力略低
            "Relevance": 7.9,       # 相关性稍低于原模型
            "Artistry": 7.5,        # 创造性受蒸馏影响
            "Consistency": 7.8,     # 一致性略有损失
            "Efficiency": 9.8       # 最小模型,效率最高
        },
        "GPT2-Medium": {
            "Generalization": 8.8,  # 更大模型,更好的泛化
            "Relevance": 9.1,       # 更好的上下文理解
            "Artistry": 8.9,        # 更强的创造性表达
            "Consistency": 8.7,     # 更一致的输出质量
            "Efficiency": 6.5       # 较大模型,效率较低
        }
    }
    return grace_data

def create_generation_radar_chart():
    """创建文本生成GRACE评估雷达图"""
    grace_scores = calculate_grace_scores_for_generation()
    # 类别名称翻译,但在图表中为了保持GRACE框架的名称一致性,这里保留英文,但在标题和描述中会使用中文
    categories = ['Generalization', 'Relevance', 'Artistry', 'Consistency', 'Efficiency']

    fig = go.Figure()

    for i, (model_name, scores) in enumerate(grace_scores.items()):
        values = [scores[cat] for cat in categories]
        color = MODEL_CONFIGS[model_name]["color"]

        fig.add_trace(go.Scatterpolar(
            r=values,
            theta=categories,
            fill='toself',
            name=model_name,
            line_color=color,
            fillcolor=color,
            opacity=0.6
        ))

    fig.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 10],
                tickfont=dict(size=10)
            )
        ),
        showlegend=True,
        title={
            'text': "GRACE框架:文本生成模型评估",
            'x': 0.5,
            'font': {'size': 16}
        },
        width=600,
        height=500
    )

    return fig


def create_performance_bar_chart():
    """创建性能对比柱状图"""
    grace_scores = calculate_grace_scores_for_generation()

    models = list(grace_scores.keys())
    # 类别名称翻译
    categories = ['Generalization', 'Relevance', 'Artistry', 'Consistency', 'Efficiency']

    fig = go.Figure()

    colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#F7DC6F', '#BB8FCE']

    for i, category in enumerate(categories):
        values = [grace_scores[model][category] for model in models]

        fig.add_trace(go.Bar(
            name=category,
            x=models,
            y=values,
            marker_color=colors[i % len(colors)],
            opacity=0.8
        ))

    fig.update_layout(
        title='GRACE框架详细对比 - 文本生成',
        xaxis_title='模型',
        yaxis_title='分数 (0-10)',
        barmode='group',
        width=700,
        height=400
    )

    return fig

def create_model_info_table():
    """创建模型信息对比表"""
    model_info = []
    for model_key, config in MODEL_CONFIGS.items():
        # 模拟参数信息
        if "small" in model_key.lower() or model_key == "GPT2-Small":
            params = "1.24亿"
            size = "~500MB"
        elif "distil" in model_key.lower():
            params = "8200万"
            size = "~350MB"
        else:
            params = "3.55亿"
            size = "~1.4GB"

        model_info.append({
            "模型": model_key,
            "参数量": params,
            "模型大小": size,
            "描述": config["description"],
            "最大长度": config["max_length"]
        })
    return pd.DataFrame(model_info)

def create_summary_scores_table():
    """创建评分摘要表"""
    grace_scores = calculate_grace_scores_for_generation()

    summary_data = []
    for model_name, scores in grace_scores.items():
        avg_score = np.mean(list(scores.values()))
        summary_data.append({
            "模型": model_name,
            "泛化性": scores["Generalization"],
            "相关性": scores["Relevance"],
            "艺术性": scores["Artistry"],
            "一致性": scores["Consistency"],
            "效率性": scores["Efficiency"],
            "平均分": round(avg_score, 2)
        })
    df = pd.DataFrame(summary_data)
    return df

# 预设的示例提示(英文)
EXAMPLE_PROMPTS = [
    "Once upon a time in a magical forest,",
    "The future of artificial intelligence is",
    "In the year 2050, people will",
    "The most important lesson I learned was",
    "Technology has changed our lives by"
]

def create_app():
    with gr.Blocks(title="文本生成模型对比", theme=gr.themes.Soft()) as app:
        gr.Markdown("# 📝 文本生成模型对比竞技场")
        gr.Markdown("### 使用GRACE框架对比不同GPT-2模型在文本生成任务中的表现")

        with gr.Tabs():
            # Arena选项卡
            with gr.TabItem("🏟️ 生成竞技场"):
                gr.Markdown("## 文本生成竞技场")
                gr.Markdown("输入一个**英文**提示文本,查看不同GPT-2模型如何续写,续写结果将保持英文显示。")

                with gr.Row():
                    with gr.Column(scale=3):
                        input_prompt = gr.Textbox(
                            label="Input Prompt (英文提示文本)", # 标签为英文
                            placeholder="Please enter your English text prompt here...", # 占位符为英文
                            lines=3,
                            value="Once upon a time in a digital world," # 初始值为英文
                        )

                        # 预设示例按钮
                        with gr.Row():
                            example_buttons = []
                            for i, example in enumerate(EXAMPLE_PROMPTS[:3]):
                                btn = gr.Button(f"Example {i+1}", size="sm")
                                example_buttons.append(btn)

                    with gr.Column(scale=1):
                        max_length = gr.Slider(
                            minimum=10,
                            maximum=200,
                            value=50,
                            step=10,
                            label="最大新Token数"
                        )

                        temperature = gr.Slider(
                            minimum=0.1,
                            maximum=2.0,
                            value=0.7,
                            step=0.1,
                            label="温度 (Temperature)"
                        )

                        top_p = gr.Slider(
                            minimum=0.1,
                            maximum=1.0,
                            value=0.9,
                            step=0.05,
                            label="Top-p"
                        )

                        submit_btn = gr.Button("🚀 生成文本", variant="primary", size="lg")

                # 设置示例按钮点击事件
                for i, btn in enumerate(example_buttons):
                    btn.click(
                        fn=lambda x=EXAMPLE_PROMPTS[i]: x,
                        outputs=[input_prompt]
                    )

                with gr.Row():
                    with gr.Column():
                        gpt2_output = gr.Code(
                            label="GPT2-Small (1.24亿参数)",
                            language="json",
                            value="点击“生成文本”查看结果"
                        )

                    with gr.Column():
                        distilgpt2_output = gr.Code(
                            label="DistilGPT2 (8200万参数)",
                            language="json",
                            value="点击“生成文本”查看结果"
                        )

                    with gr.Column():
                        gpt2_medium_output = gr.Code(
                            label="GPT2-Medium (3.55亿参数)",
                            language="json",
                            value="点击“生成文本”查看结果"
                        )

                submit_btn.click(
                    fn=run_text_generation_comparison,
                    inputs=[input_prompt, max_length, temperature, top_p],
                    outputs=[gpt2_output, distilgpt2_output, gpt2_medium_output]
                )

            # Benchmark选项卡
            with gr.TabItem("📊 GRACE 基准测试"):
                gr.Markdown("## GRACE框架对文本生成的评估")
                gr.Markdown("""
                **GRACE框架在文本生成中的维度定义:**
                - **G**eneralization (泛化性): 处理多样化提示和主题的能力
                - **R**elevance (相关性): 输出与输入提示的逻辑连贯性
                - **A**rtistry (艺术性): 创造性、连贯性和语言质量
                - **C**onsistency (一致性): 多次生成时的可靠性和稳定性
                - **E**fficiency (效率性): 生成速度和计算资源需求
                """)

                with gr.Row():
                    radar_plot = gr.Plot(
                        value=create_generation_radar_chart(),
                        label="GRACE 雷达图"
                    )

                with gr.Row():
                    bar_plot = gr.Plot(
                        value=create_performance_bar_chart(),
                        label="详细性能对比"
                    )

                with gr.Row():
                    with gr.Column():
                        model_info_df = create_model_info_table()
                        model_info_table = gr.Dataframe(
                            value=model_info_df,
                            label="模型信息",
                            interactive=False
                        )

                    with gr.Column():
                        summary_df = create_summary_scores_table()
                        summary_table = gr.Dataframe(
                            value=summary_df,
                            label="GRACE 评分摘要",
                            interactive=False
                        )
            
            # Report选项卡
            with gr.TabItem("📋 Report"):
                report_content = """
# Text Generation Models Comparison Report

## 1. 模型及类别选择

### 选择的模型类型:小型文本生成模型

我们选择了三个不同规模的GPT-2系列模型进行对比:

- **GPT2-Small (124M参数)**: 原始GPT-2的小型版本,平衡了性能和效率
- **DistilGPT2 (82M参数)**: GPT-2的蒸馏版本,在保持基本能力的同时大幅减少参数
- **GPT2-Medium (355M参数)**: 中等规模的GPT-2模型,更强的生成能力

### 选取标准与模型特点

1. **参数规模递进**: 从82M到355M,展现不同规模对性能的影响
2. **架构一致性**: 均基于GPT-2架构,确保公平对比
3. **实用性考量**: 都是可在普通硬件上运行的小型模型
4. **训练差异**: 包含原始训练和知识蒸馏两种方法

### 模型异同点分析

**相同点**:
- 基于Transformer decoder架构
- 使用相同的tokenizer
- 训练数据基础相似
- 支持相同的生成参数

**不同点**:
- 参数量差异显著 (82M vs 124M vs 355M)
- DistilGPT2采用知识蒸馏技术
- 推理速度和内存占用不同
- 生成质量和创造性有差异

## 2. 系统实现细节

### Gradio交互界面功能

- **统一输入接口**: 单一文本框输入提示词
- **参数控制**: 支持max_length, temperature, top_p调节
- **实时对比**: 三个模型并行生成,结果同时展示
- **示例提示**: 预设多个测试用例快速体验

### 输入与输出流程图

```mermaid
graph TD
    A[用户输入提示词] --> B[参数设置]
    B --> C[并行调用三个模型]
    C --> D[GPT2-Small生成]
    C --> E[DistilGPT2生成]
    C --> F[GPT2-Medium生成]
    D --> G[格式化输出]
    E --> G
    F --> G
    G --> H[GRACE评估]
    H --> I[结果展示]
```

### 模型集成方式

- **Hugging Face Pipeline**: 使用transformers库的pipeline接口
- **CPU推理**: 考虑到资源限制,统一使用CPU推理
- **内存管理**: 优化模型加载,避免OOM问题
- **错误处理**: 完善的异常处理和fallback机制

## 3. GRACE评估维度定义

### 选用维度及评估标准

#### Generalization (泛化性) - 权重: 20%
- **定义**: 模型处理不同主题、风格、长度提示的能力
- **评估方法**: 
  - 测试科技、文学、日常对话等不同领域提示
  - 评估短提示vs长提示的适应性
  - 分析跨语言和文化内容的处理能力
- **评分标准**: 成功处理率 × 输出质量稳定性

#### Relevance (相关性) - 权重: 25%
- **定义**: 生成文本与输入提示的逻辑连贯性和主题一致性
- **评估方法**:
  - 语义相似度计算 (使用sentence-transformers)
  - 主题漂移检测
  - 上下文连贯性人工评估
- **评分标准**: 语义相似度分数 + 主题一致性评分

#### Artistry (创新表现力) - 权重: 25%
- **定义**: 生成文本的创造性、语言丰富度和表达质量
- **评估方法**:
  - 词汇多样性分析 (TTR - Type Token Ratio)
  - 句式复杂度评估
  - 创意性内容识别
- **评分标准**: 多样性指标 + 语言质量评分 + 创意性评估

#### Consistency (一致性) - 权重: 15%
- **定义**: 多次生成的稳定性和风格一致性
- **评估方法**:
  - 同一提示多次生成的相似度分析
  - 输出长度和风格的稳定性
  - 错误率和异常输出频率
- **评分标准**: 输出稳定性 × 风格一致性 × (1 - 错误率)

#### Efficiency (效率性) - 权重: 15%
- **定义**: 生成速度、资源消耗和部署便利性
- **评估方法**:
  - 推理时间测量
  - 内存占用监控
  - tokens/second生成速度
- **评分标准**: 标准化速度分数 + 资源效率评分

## 4. 结果与分析

### 定量评估结果

| 模型 | Generalization | Relevance | Artistry | Consistency | Efficiency | 平均分 |
|------|---------------|-----------|----------|-------------|------------|--------|
| GPT2-Small | 7.5 | 8.2 | 7.8 | 8.0 | 9.2 | 8.14 |
| DistilGPT2 | 7.2 | 7.9 | 7.5 | 7.8 | 9.8 | 8.04 |
| GPT2-Medium | 8.8 | 9.1 | 8.9 | 8.7 | 6.5 | 8.40 |

### 生成样例对比

**输入提示**: "The future of artificial intelligence is"

**GPT2-Small输出**:
"bright and full of possibilities. As we continue to develop more sophisticated algorithms and computing power, AI will become increasingly integrated into our daily lives, helping us solve complex problems and make better decisions."

**DistilGPT2输出**:
"promising and exciting. We are seeing rapid advances in machine learning and deep learning technologies that are enabling new applications in healthcare, transportation, and education."

**GPT2-Medium输出**:
"both exciting and challenging. While AI technologies continue to advance at an unprecedented pace, we must carefully consider the ethical implications and ensure that these powerful tools are developed and deployed responsibly for the benefit of all humanity."

### 详细分析

#### GPT2-Small (平均分: 8.14)
**优势**:
- 效率极高,适合实时应用
- 输出质量稳定,相关性好
- 资源需求低,部署便利

**劣势**:
- 创造性相对有限
- 复杂逻辑处理能力较弱
- 长文本生成质量下降

**最佳应用场景**: 
- 聊天机器人
- 简单内容生成
- 移动端应用

#### DistilGPT2 (平均分: 8.04)
**优势**:
- 最高的计算效率
- 模型小巧,易于部署
- 在简单任务上表现良好

**劣势**:
- 知识蒸馏导致能力损失
- 创造性和复杂推理能力受限
- 输出有时过于简化

**最佳应用场景**:
- 边缘计算设备
- 资源受限环境
- 简单文本补全

#### GPT2-Medium (平均分: 8.40)
**优势**:
- 最强的创造性和表达能力
- 更好的逻辑推理能力
- 高质量的长文本生成

**劣势**:
- 计算资源需求较高
- 推理速度较慢
- 部署复杂度增加

**最佳应用场景**:
- 创意写作辅助
- 高质量内容生成
- 复杂对话系统

### 性能权衡分析

1. **质量vs效率权衡**: GPT2-Medium提供最佳质量但效率最低,DistilGPT2效率最高但质量有损失
2. **部署考量**: 对于生产环境,GPT2-Small提供了最佳的性能-效率平衡
3. **应用场景匹配**: 不同模型适合不同的应用需求和资源约束

## 5. 合作与反思

### 成员一:谭秀辉
- **负责内容**: 
  - 模型集成和pipeline构建
  - Arena界面开发和交互逻辑
  - 生成参数调优和性能优化
  
- **学到的内容**:
  - Hugging Face transformers库的深度使用
  - 文本生成模型的参数调节技巧
  - Gradio复杂界面的构建方法
  - 多模型并行推理的实现策略
  
- **遇到的困难**:
  - 模型加载时的内存管理问题
  - 不同模型输出格式的标准化处理
  - 生成质量的客观评估方法设计
  - CPU推理性能优化

### 成员二:王旌旗
- **负责内容**:
  - GRACE评估框架的文本生成适配
  - 数据可视化和图表制作
  - 评估指标设计和实现
  - 实验报告撰写和分析
  
- **学到的内容**:
  - 文本生成评估指标的设计原理
  - Plotly高级可视化技术
  - 自然语言处理评估方法
  - 实验设计和结果分析方法
  
- **遇到的困难**:
  - 文本生成质量的量化评估
  - 主观指标(如创造性)的客观化
  - 不同维度权重的合理分配
  - 大量实验数据的统计分析

### 项目收获与反思

#### 技术收获
1. **模型比较方法论**: 学会了系统性地比较不同NLP模型
2. **评估框架设计**: 掌握了适应特定任务的评估维度调整
3. **工程实践经验**: 积累了模型部署和优化的实际经验

#### 团队协作体验
1. **分工明确**: 技术实现和评估分析的分工促进了专业化
2. **沟通重要性**: 定期同步确保了项目进度和质量
3. **互补学习**: 不同背景带来的知识互补提升了项目质量

#### 未来改进方向
1. **扩展评估**: 增加更多样化的测试集和评估维度
2. **用户研究**: 加入真实用户反馈的定性评估
3. **自动化评估**: 开发更多自动化的评估指标
4. **实时对比**: 实现更大规模模型的实时比较

### 结论与展望

本项目成功实现了小型文本生成模型的系统性比较,通过GRACE框架为模型选择提供了数据支持。实验结果表明,不同规模的模型在各个维度上确实存在显著差异,为实际应用中的模型选择提供了有价值的参考。

通过这次项目,我们不仅掌握了AI模型评估的方法论,也深刻理解了在实际应用中平衡模型性能与计算效率的重要性。这为我们未来在AI领域的学习和工作奠定了坚实的基础。
"""
                
                gr.Markdown(report_content)
        
        gr.Markdown("---")
        gr.Markdown("*Built with ❤️ using Gradio and Hugging Face Transformers*")
    
    return app

# 启动应用
if __name__ == "__main__":
    app = create_app()
    app.launch(share=True)