人工智能大模型预训练微调LoRARLHF强化学习分布式训练【免费下载链接】PaddleNLPEasy-to-use and powerful LLM and SLM library with awesome model zoo.项目地址https://gitcode.com/gh_mirrors/pa/PaddleNLP点击查看免费下载RougeRecall-Oriented Understudy for Gisting Evaluation是自动文摘、机器翻译、文本生成等领域最经典的评测指标族本指南以 PaddleNLP 的 paddlenlp.metrics.rouge 模块为对象逐一拆解 RougeNRouge-1 / Rouge-2、RougeL基于最长公共子序列 LCS以及专为 DuReader 阅读理解竞赛设计的 RougeLForDuReader 的实现原理、API 用法与集成方式。读完本文你将能够理解每条 Rouge 公式在代码中的落点、正确调用各类 Rouge 评测器的接口并能把评测指标无缝挂接到 Paddle 训练循环与真实数据集的评测流程中。Rouge 指标家族与 PaddleNLP 中的定位Rouge 全称 Recall-Oriented Understudy for Gisting Evaluation最初用于评估自动文摘质量如今已被广泛用于机器翻译、文本生成、阅读理解等自然语言生成任务的自动评测。Rouge 族指标通过比较模型生成的候选文本candidate与人工标注的参考文本reference之间的 n-gram 或最长公共子序列重叠程度来衡量生成质量其命名中的Recall-Oriented表明该指标族本质上更强调召回参考文本中的内容是否被生成出来。在 PaddleNLP 的 paddlenlp/metrics/init.py 中Rouge 系列与 Perplexity、BLEU、AccuracyAndF1、PearsonAndSpearman、Mcc、ChunkEvaluator、Squad 等指标共同构成paddlenlp.metrics指标库其中 Rouge 相关 API 有paddlenlp.metrics.RougeL基于最长公共子序列的 Rouge-L适用于文摘、翻译、对话生成等任务paddlenlp.metrics.RougeLForDuReader带 YesNo / Entity 加分的 Rouge-L用于 DuReader 阅读理解竞赛评测paddlenlp.metrics.RougeN基类内部实现 n-gram 重叠统计、paddlenlp.metrics.Rouge1、paddlenlp.metrics.Rouge2经典的 n-gram 类 Rouge 指标。模块入口通过from .rouge import Rouge1, Rouge2, RougeL, RougeLForDuReader, RougeN见 paddlenlp/metrics/init.py对外导出用户既可直接从paddlenlp.metrics顶层导入也可通过paddlenlp.metrics.rouge子模块按需导入。RougeN基于 n-gram 重叠的经典实现n-gram 集合的构建RougeN类paddlenlp/metrics/rouge.py是 Rouge-1、Rouge-2 的公共基类其核心是_get_ngrams方法def _get_ngrams(self, words): Calculates word n-grams for multiple sentences. ngram_set set() max_index_ngram_start len(words) - self.n for i in range(max_index_ngram_start 1): ngram_set.add(tuple(words[i : i self.n])) return ngram_set该方法从 token 序列中按滑动窗口切出全部连续的 n-gram并以tuple形式存入set天然完成去重。n1时即单词集合n2时即相邻词二元组集合。窗口范围len(words) - self.n保证不会越界且当序列长度小于 n 时不会产生任何 n-gram。重叠计数与召回率计算compute方法完成核心统计paddlenlp/metrics/rouge.pydef compute(self, evaluated_sentences_ids, reference_sentences_ids): if len(evaluated_sentences_ids) 0 or len(reference_sentences_ids) 0: raise ValueError(Collections must contain at least 1 sentence.) reference_count 0 overlapping_count 0 for evaluated_sentence_ids, reference_sentence_ids in zip( evaluated_sentences_ids, reference_sentences_ids): evaluated_ngrams self._get_ngrams(evaluated_sentence_ids) reference_ngrams self._get_ngrams(reference_sentence_ids) reference_count len(reference_ngrams) # Gets the overlapping ngrams between evaluated and reference overlapping_ngrams evaluated_ngrams.intersection(reference_ngrams) overlapping_count len(overlapping_ngrams) return overlapping_count, reference_count这里按句子对逐一取 n-gram 集合的intersection计算重叠数同时累加参考文本的 n-gram 总数score方法则将二者相除得到 ROUGE-N 召回率def score(self, evaluated_sentences_ids, reference_sentences_ids): overlapping_count, reference_count self.compute( evaluated_sentences_ids, reference_sentences_ids) return overlapping_count / reference_count注意RougeN的输入是已经转成 id 的句子集合evaluated_sentences_ids/reference_sentences_ids即句子列表的列表这与下面RougeL直接接收词列表的接口不同。与训练循环对接的 accumulate / reset / updateRougeN还实现了面向 minibatch 累积评测的状态接口update(overlapping_count, reference_count)把单次计算得到的重叠数与参考数累加到成员变量self.overlapping_count、self.reference_countaccumulate()返回self.overlapping_count / self.reference_count即所有累积 batch 上的整体 ROUGE-Nreset()将两个计数清零用于开启新一轮评测name()返回Rouge-%s % self.n如Rouge-1、Rouge-2。Rouge1、Rouge2只是分别以n1、n2实例化基类paddlenlp/metrics/rouge.py无额外逻辑。从测试用例 tests/metrics/test_rouge.py 可以看到 Rouge-1 的完整用法from paddlenlp.metrics import Rouge1 rouge1 Rouge1() rouge1.reset() cand [The, cat, The, cat, on, the, mat] ref_list [[The, cat, is, on, the, mat], [There, is, a, cat, on, the, mat]] self.assertEqual(rouge1.score(cand, ref_list), 0.07692307692307693)该测试对应的 Rouge-1 召回率 1/13 ≈ 0.07692可在仓库中直接运行tests/metrics/test_rouge.py复现验证。RougeL基于最长公共子序列LCS的评测公式与数学定义RougeLpaddlenlp/metrics/rouge.py继承自paddle.metric.Metric其 docstring 给出了完整数学定义R_{LCS} LCS(C, S) / len(S) P_{LCS} LCS(C, S) / len(C) F_{LCS} (1 γ²) · R_{LCS} · P_{LCS} / (R_{LCS} γ² · P_{LCS})其中C为候选句子candidateS为参考句子referenceLCS(C, S)表示二者最长公共子序列的长度。与 n-gram 统计不同LCS 天然考虑了句子级的结构相似性能自动识别序列中连续共同出现的 n-gram且对词序的容忍度更高——只要子序列保持相对顺序即可命中。动态规划实现 LCSlcs方法paddlenlp/metrics/rouge.py用经典的二维动态规划求解def lcs(self, string, sub): if len(string) len(sub): sub, string string, sub lengths np.zeros((len(string) 1, len(sub) 1)) for j in range(1, len(sub) 1): for i in range(1, len(string) 1): if string[i - 1] sub[j - 1]: lengths[i][j] lengths[i - 1][j - 1] 1 else: lengths[i][j] max(lengths[i - 1][j], lengths[i][j - 1]) return lengths[len(string)][len(sub)]实现细节上先将较长序列放在外层维度以稳定矩阵形状lengths[i][j]记录string[:i]与sub[:j]的 LCS 长度字符相等时取对角值加一不等时取左、上两个方向的最大值。算法复杂度为 O(len(string) × len(sub))。注意此处的输入string/sub是词列表字符串列表逐元素比较的是 token 是否相等。add_inst多参考取最优的精度-召回融合add_instpaddlenlp/metrics/rouge.py接受一个候选和参考列表ref_list对每条参考分别计算 P、R然后取prec_max、rec_max再按 F 公式融合def add_inst(self, cand, ref_list): precs, recalls [], [] for ref in ref_list: basic_lcs self.lcs(cand, ref) prec basic_lcs / len(cand) if len(cand) 0.0 else 0.0 rec basic_lcs / len(ref) if len(ref) 0.0 else 0.0 precs.append(prec) recalls.append(rec) prec_max max(precs) rec_max max(recalls) if prec_max ! 0 and rec_max ! 0: score ((1 self.gamma**2) * prec_max * rec_max) / float( rec_max self.gamma**2 * prec_max) else: score 0.0 self.inst_scores.append(score)关键设计点多参考处理对同一候选的多个参考答案分别打分后取最大值符合 Rouge 评测惯例多参考场景下以最优参考为准分母保护len(cand) 0.0/len(ref) 0.0的判空避免除零P、R 全为 0 时 F 值直接置 0gamma 权重gamma默认 1.2用于调节召回在最终分数中的权重gamma越大越偏重召回。构造参数与 Metric 协议RougeL的构造函数签名paddlenlp/metrics/rouge.pydef __init__(self, trans_funcNone, vocabNone, gamma1.2, namerouge-l, *args, **kwargs):trans_funccallable把网络输出转换为字符串/词列表以便计分的转换函数可选vocabdict 或paddlenlp.data.vocab目标语言词表当trans_func为 None 时配合default_trans_func使用此时必须提供gammafloat召回权重超参默认 1.2namestrMetric 实例名称默认rouge-l。作为paddle.metric.Metric的子类它完整实现了四个协议方法update(output, label, seq_maskNone)将模型输出转为候选/参考对并逐条add_inst。若未提供trans_func则要求vocab非空否则抛出AttributeError同时校验len(cand_list) ! len(ref_list)时抛出ValueErroraccumulate()返回sum(self.inst_scores) / len(self.inst_scores)即全部实例分数的均值reset()清空inst_scoresname()返回构造时传入的name。update中默认的转换逻辑default_trans_funcpaddlenlp/metrics/utils.py实现为对网络输出按seq_mask扩展并掩码沿最后一维取argmax得到预测 token id再分别遍历候选与标签、按 mask 截断到有效长度最后用vocab将 id 映射回 token 列表标签侧包装为[token_list]形式以兼容多参考接口。文档示例与测试验证RougeLdocstring 自带可直接运行的示例from paddlenlp.metrics import RougeL rougel RougeL() cand [The,cat,The,cat,on,the,mat] ref_list [[The,cat,is,on,the,mat], [There,is,a,cat,on,the,mat]] rougel.add_inst(cand, ref_list) print(rougel.score()) # 0.7800511508951408该数值在 tests/metrics/test_rouge.py 中被断言验证读者可直接运行测试复现。相比RougeN.score(cand, ref_list)的传参即算风格RougeL需要先add_inst再score()/accumulate()这是二者接口设计上的重要差异。RougeLForDuReader阅读理解竞赛的加分评测设计动机与参数RougeLForDuReaderpaddlenlp/metrics/rouge.py针对 DuReader 阅读理解竞赛设计在标准 Rouge-L 基础上引入 YesNo 与 Entity 两种加分bonus机制def __init__(self, alpha1.0, beta1.0, gamma1.2): super(RougeLForDuReader, self).__init__(gamma) self.alpha alpha self.beta betaalphafloatYesNo 数据集加分的权重默认 1.0betafloatEntity 数据集加分的权重默认 1.0gammafloat召回权重默认 1.2透传给基类RougeL。加分公式其add_inst签名扩展为add_inst(cand, ref_list, yn_labelNone, yn_refNone, entity_refNone)核心计算为p_denom len(cand) self.alpha * yn_bonus self.beta * entity_bonus r_denom len(ref) self.alpha * yn_bonus self.beta * entity_bonus prec (basic_lcs self.alpha * yn_bonus self.beta * entity_bonus) / p_denom rec (basic_lcs self.alpha * yn_bonus self.beta * entity_bonus) / r_denom即把alpha * yn_bonus beta * entity_bonus同时加进分子重叠量与分母长度再按与RougeL相同的prec_max / rec_max / F流程融合若 P、R 均为 0 则得分为 0。yn_label/yn_ref与entity_ref二选一传入前者非空则走 YesNo 加分否则走 Entity 加分。两种加分函数的实现def add_yn_bonus(self, cand, ref, yn_label, yn_ref): if yn_label ! yn_ref: return 0.0 lcs_ self.lcs(cand, ref) return lcs_ def add_entity_bonus(self, cand, entity_ref): lcs_ 0.0 for ent in entity_ref: if ent in cand: lcs_ len(ent) return lcs_YesNo 加分仅当模型预测的 Yes/No 标签与参考答案一致时返回候选与参考的 LCS 长度作为加分——即答案类别判对直接奖励Entity 加分逐一检查实体参考列表中的实体是否出现在候选文本中命中则累加该实体的长度——即实体抽取全直接奖励。在 DuReader 评测中的实际应用paddlenlp/metrics/dureader.py 中的dureader_evaluate展示了标准 Rouge-L 与 BLEU-4 的组合评测流程def dureader_evaluate(examples, preds): bleu_eval BLEU(4) rouge_eval RougeL() for example in examples: qid example.qas_id if qid not in preds: print(Missing prediction for %s % qid) continue pred_answers preds[qid] pred_answers normalize([pred_answers])[0] ref_answers example.orig_answer_text if not ref_answers: continue ref_answers normalize(ref_answers) bleu_eval.add_inst(pred_answers, ref_answers) rouge_eval.add_inst(pred_answers, ref_answers) bleu4 bleu_eval.score() rouge_l rouge_eval.score() metrics {ROUGE-L: round(rouge_l * 100, 2), BLEU-4: round(bleu4 * 100, 2)}这段代码演示了三个工程要点归一化预处理答案先经normalize全角转半角、统一标点、去空白后再打分保证中英文标点差异不干扰 LCS 计算逐条累积对每个样本add_inst最后统一score()与RougeL的实例级接口配合缺失保护预测缺失的qid打印告警并跳过避免脏数据拖垮评测。在训练循环中集成 Rouge 指标的完整方案RougeL因继承paddle.metric.Metric可以直接通过paddle.metric.Metric的标准协议接入 Paddle 训练/评估循环。以无trans_func、走词表转换的典型用法为例import paddle from paddlenlp.metrics import RougeL rougel RougeL(vocabvocab) # vocab 为 id - token 的词表 ... for batch in eval_loader(): logits, labels, seq_mask model(batch) rougel.update(logits.numpy(), labels.numpy(), seq_mask.numpy()) rouge_l rougel.accumulate() # 或 rougel.score() print(ROUGE-L:, rouge_l) rougel.reset() # 开启下一轮评测若希望完全自定义网络输出 - 候选/参考文本的转换逻辑例如 beam search 产出的字符串而非 argmax id则传入自定义trans_funcdef my_trans_func(output, label, seq_mask): # output: 模型输出; label: 标签; seq_mask: 序列掩码 # 返回 cand_list, ref_list return cand_list, ref_list rougel RougeL(trans_funcmy_trans_func)若输出侧直接就是词列表字符串则可用最轻量的add_inst逐条打分如 tests/metrics/test_rouge.py 所示。三种模式对应三档接入成本纯实例打分最简→trans_func自定义转换灵活→vocab default_trans_func直接对接 Paddle 网络输出张量。小结与选型建议评测器计算单元核心接口典型任务关键参数RougeNRouge1/Rouge2n-gram 集合重叠score(cand_ids, ref_ids)、compute机器翻译、摘要的 n-gram 级召回n1 或 2RougeL最长公共子序列add_inst(cand, ref_list)、update/accumulate摘要、生成、阅读理解gamma1.2、trans_func、vocabRougeLForDuReaderLCS YesNo/Entity 加分add_inst(cand, ref_list, yn_label, entity_ref)DuReader 阅读理解竞赛alpha1.0、beta1.0、gamma1.2选型建议需要快速验证 n-gram 级重合度、且数据已是 id 形式用Rouge1/Rouge2生成式任务摘要、对话、翻译首选RougeL它兼顾词序结构且与paddle.metric.Metric无缝集成DuReader 类问答评测务必使用RougeLForDuReaderYesNo 与 Entity 加分能显著提升与官方榜单口径的一致性。以上全部实现细节、默认参数与示例数值均可直接对照仓库源码 paddlenlp/metrics/rouge.py、工具函数 paddlenlp/metrics/utils.py 以及测试用例 tests/metrics/test_rouge.py 进行验证DuReader 组合评测的完整代码见 paddlenlp/metrics/dureader.py。赞分享人工智能大模型预训练微调LoRARLHF强化学习分布式训练【免费下载链接】PaddleNLPEasy-to-use and powerful LLM and SLM library with awesome model zoo.项目地址https://gitcode.com/gh_mirrors/pa/PaddleNLP点击查看免费下载相关推荐PaddleNLP 模型评价指标Metrics全景指南从 Perplexity 到 SQuAD 的 API 解析与源码级实战PaddleNLP 模型评价指标Metrics全景指南从 Perplexity 到 SQuAD 的 API 解析与源码级实战 PaddleNLP 作为覆盖人工智能大模型预训练微调LoRARLHF强化学习分布式训练模型推理服务推理引擎模型量化模型压缩本地部署NLPPaddleNLP 中的 LayoutLMTokenizer从源码解析到文档理解实战PaddleNLP 中的 LayoutLMTokenizer从源码解析到文档理解实战 导读 LayoutLMTokenizer 是 PaddleNLP 为视觉人工智能大模型预训练微调LoRARLHF强化学习分布式训练模型推理服务推理引擎模型量化模型压缩本地部署NLPPaddleNLP 评估指标库 paddlenlp.metrics 完全指南从生成质量到序列标注的指标实现与实战PaddleNLP 评估指标库 paddlenlp.metrics 完全指南从生成质量到序列标注的指标实现与实战 导读 paddlenlp.metrics人工智能大模型预训练微调LoRARLHF强化学习分布式训练模型推理服务推理引擎模型量化模型压缩本地部署NLP创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
