人工智能大模型NLP深度学习预训练微调RLHF模型量化【免费下载链接】PaddleNLPEasy-to-use and powerful LLM and SLM library with awesome model zoo.项目地址https://gitcode.com/gh_mirrors/pa/PaddleNLP点击查看免费下载本篇技术指南以 PaddleNLP 官方模型库中的 BART 模型汇总文档docs/en/model_zoo/transformers/BART/contents.rst为主体结合仓库内 paddlenlp/transformers/bart/ 目录下的源码实现系统梳理 BART 在 PaddleNLP 中支持的预训练权重、模型架构细节、配置参数与调用方式。读完本文你将掌握如何在 PaddleNLP 中加载bart-base/bart-large权重并基于BartModel、BartForConditionalGeneration等类完成条件生成、序列分类、阅读理解等任务。BART 模型与 PaddleNLP 的预训练权重一览BARTBidirectional and Auto-Regressive Transformer是一种基于去噪自编码denoising autoencoder预训练的序列到序列Seq2SeqTransformer 模型其编码器采用双向注意力解码器采用自回归注意力天然适合文本生成、摘要、翻译等条件生成任务。PaddleNLP 当前官方支持两个英文 BART 预训练权重对应关系如下表源自contents.rst预训练权重语言模型说明bart-baseEnglish12 层6 层编码器 6 层解码器、hidden 维度 768、12 个注意力头、约 217M 参数即 BART base 模型英文bart-largeEnglishBART large 模型英文架构细节见下文contents.rst中同时对两种架构给出了补充说明模型语言架构细节BART base 模型英文English12 层、768-hidden、16 头、139M 参数BART large 模型英文English24 层、768-hidden、16 头、509M 参数注意文档中这两张表对 head 数、hidden 维度存在不一致的表述。以仓库源码为准configuration.py 中定义的精确超参数见下一节。实践时请以源码中的BartConfig实际取值为准。这两个权重的加载入口定义在 configuration.py 中BART_PRETRAINED_INIT_CONFIGURATION { bart-base: { vocab_size: 50265, bos_token_id: 0, pad_token_id: 1, eos_token_id: 2, forced_eos_token_id: 2, decoder_start_token_id: 2, d_model: 768, num_encoder_layers: 6, num_decoder_layers: 6, encoder_attention_heads: 12, decoder_attention_heads: 12, encoder_ffn_dim: 3072, decoder_ffn_dim: 3072, dropout: 0.1, activation_function: gelu, attention_dropout: 0.1, activation_dropout: 0.1, max_position_embeddings: 1024, init_std: 0.02, scale_embedding: False, }, bart-large: { ... }, }模型权重下载映射定义在BART_PRETRAINED_RESOURCE_FILES_MAP中bart-base与bart-large均对应独立的model_state资源文件加载时会按需自动下载。架构与配置从 BartConfig 理解模型规模BART 的配置类为BartConfig继承自PretrainedConfigmodel_type bart并通过attribute_map兼容了num_encoder_layers ↔ encoder_layers、num_decoder_layers ↔ decoder_layers、num_classes ↔ num_labels等命名差异。其关键参数及语义如下摘自 configuration.py 的 docstring参数默认值说明vocab_size50265词表大小决定input_ids可表示的 token 种类数d_model1024docstring/ 768bart-base 实际编码器、解码器各层及池化层的隐藏维度encoder_layers/decoder_layers6 / 6编码器、解码器层数encoder_attention_heads/decoder_attention_heads12 / 12编码器、解码器每层注意力头数encoder_ffn_dim/decoder_ffn_dim3072 / 3072编码器、解码器前馈网络中间层维度activation_functiongelu前馈网络激活函数支持gelu、relu及 Paddle 支持的其他激活dropout0.1embedding、编码器及池化层全连接层的 dropout 概率attention_dropout0.1注意力概率的 dropout 比例activation_dropout0.1全连接层内部激活的 dropout 比例max_position_embeddings1024模型可处理的最大序列长度init_std0.02权重矩阵初始化的截断正态分布标准差scale_embeddingFalse是否将 embedding 除以sqrt(d_model)进行缩放forced_eos_token_id2生成到达max_length时强制作为最后一个 token 的 id通常等于eos_token_id从源码可见bart-base与bart-large的核心差异在于bart-based_model768编码器 6 层 解码器 6 层共 12 层每层 12 个注意力头FFN 维度 3072bart-larged_model1024编码器 12 层 解码器 12 层共 24 层每层 16 个注意力头FFN 维度 4096。两者的max_position_embeddings均为 1024vocab_size均为 50265这也与 tokenizer.py 中PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES对两个权重的定义均为 1024保持一致。BartConfig构造函数还做了几项 BART 特有处理默认is_encoder_decoderTrue、decoder_start_token_id2、forced_eos_token_id2并保留了面向 BART CNN 摘要模型的向后兼容逻辑——当forced_bos_token_id为空且配置中显式指定了force_bos_token_to_be_generated时自动将其回填为bos_token_id并给出告警。模型实现BartModel 及其编码器-解码器结构BART 的核心模型实现位于 modeling.py公开导出的类包括BartModel裸 BART 模型输出原始隐状态register_base_model注册的基座模型BartPretrainedModel预训练模型抽象基类统一管理配置、预训练权重映射与下载BartEncoder/BartDecoder独立的编码器与解码器模块BartForSequenceClassification序列分类/回归任务BartForQuestionAnswering抽取式问答span 预测任务BartForConditionalGeneration带语言建模头的条件生成模型BartClassificationHead句子级分类头。编码器与解码器的组成BartEncoder与BartDecoder均以config与共享的embed_tokens构造见 modeling.pyself.embed_tokens nn.Embedding(config.vocab_size, config.d_model) self.embed_scale (config.d_model**0.5) if config.scale_embedding else 1.0 self.encoder_embed_positions BartLearnedPositionalEmbedding(config.max_position_embeddings, config.d_model) self.encoder_dropout nn.Dropout(config.dropout) self.encoder_layernorm_embedding nn.LayerNorm(config.d_model) self.encoder nn.TransformerEncoder( nn.TransformerEncoderLayer( d_modelconfig.d_model, nheadconfig.encoder_attention_heads, dim_feedforwardconfig.encoder_ffn_dim, dropoutconfig.dropout, activationconfig.activation_function, attn_dropoutconfig.attention_dropout, act_dropoutconfig.activation_dropout, ), config.encoder_layers, )实现要点共享词嵌入BartModel中创建了self.shared nn.Embedding(config.vocab_size, config.d_model)并同时传给BartEncoder与BartDecoder编码器与解码器共用同一份 token embedding与原始 BART 一致。学习式位置编码BartLearnedPositionalEmbedding继承了paddle.nn.EmbeddingBART 采用可学习的位置向量而非正弦位置编码且 BART 特有的 hack 是位置 id 偏移 2self.offset 2padding id 为 0/1 时实际取 2/3num_embeddings相应加上偏移量见 modeling.py。训练时自动构造 decoder 输入当未显式传入decoder_input_ids时BartModel.forward会调用shift_tokens_right将input_ids右移一位并把第一位填充为decoder_start_token_id值为 2从而直接复用 encoder 的输入完成教师强制训练见 modeling.py 与forward中的调用逻辑。mask 自动生成未提供attention_mask时模型内部会根据pad_token_id自动生成 padding mask并将 2D mask 扩展为可广播到[batch_size, num_heads, seq_len, seq_len]的形状解码器未提供decoder_attention_mask时会自动构建上三角因果 maskpaddle.tensor.triu(..., 1)保证自回归特性。增量解码 cacheBartDecoder的forward支持cache参数MultiHeadAttention.Cache/StaticCache推理时可通过use_cacheTrue复用历史 KV避免重复计算加速生成。权重初始化_init_weights对nn.Linear与nn.Embedding使用均值为 0、标准差为config.init_std默认 0.02的正态分布初始化。输出结构与状态管理BartModel.forward在return_dictTrue时返回Seq2SeqModelOutput包含解码器隐状态、past_key_values、解码器/交叉注意力、以及编码器的last_hidden_state、hidden_states与attentions等字段return_dictFalse时返回 tuple。在use_cacheTrue且cacheNone时会调用self.decoder.decoder.gen_cache(encoder_last_hidden_state)生成初始 cache并将memory_mask编码器侧 mask正确整形后传给解码器的交叉注意力。此外BartPretrainedModel._get_name_mappings定义了与 Fairseq / HuggingFace 权重的名称映射规则StateDictNameMapping覆盖 encoder/decoder 各层的 q/k/v/out 投影、FFN 的linear1/linear2、各 LayerNorm、lm_head与final_logits_bias等并对权重矩阵按transpose规则转换从而保证从预训练权重到 Paddle 参数布局的正确加载。实战使用加载预训练权重与调用各类模型1. 加载裸模型与分词器PaddleNLP 提供了统一风格的from_pretrained接口。以下示例来自BartModel的 docstring见 modeling.pyimport paddle from paddlenlp.transformers import BartModel, BartTokenizer tokenizer BartTokenizer.from_pretrained(bart-base) model BartModel.from_pretrained(bart-base) inputs tokenizer(Welcome to use PaddlePaddle and PaddleNLP!) inputs {k: paddle.to_tensor([v]) for (k, v) in inputs.items()} output model(**inputs)BartTokenizer基于 byte-level Byte-Pair-EncodingBPE内部复用了 GPT tokenizer 的分词机制通过vocab_file与merges_file完成子词切分并定义了 BART 特有的特殊 tokenbos_tokens、eos_token/s、cls_tokens、sep_token/s、unk_tokenunk、pad_tokenpad、mask_tokenmask见 tokenizer.py。2. 条件生成摘要、翻译等BartForConditionalGeneration在BartModel之上叠加了lm_head[vocab_size, d_model]的权重矩阵与final_logits_biasforward时通过lm_logits matmul(outputs[0], lm_head_weight, transpose_yTrue) final_logits_bias得到词表维 logits见 modeling.pyfrom paddlenlp.transformers import BartForConditionalGeneration, BartTokenizer tokenizer BartTokenizer.from_pretrained(bart-base) model BartForConditionalGeneration.from_pretrained(bart-base) inputs tokenizer(Welcome to use PaddlePaddle and PaddleNLP!) inputs {k: paddle.to_tensor([v]) for (k, v) in inputs.items()} outputs model(**inputs)该模型为生成任务实现了完整的接入prepare_inputs_for_generation当cache非空时将decoder_input_ids截取为最后一个 tokendecoder_input_ids[:, -1].unsqueeze(-1)以支持增量生成prepare_decoder_input_ids_from_labels由 labels 构造右移后的 decoder 输入prepare_fast_entry支持切换到FasterBARTpaddlenlp.ops中的高性能解码算子可通过decode_strategysampling/topk/topp、use_fp16_decoding、decoding_lib、enable_fast_encoder等参数启用快速解码路径需要注意的是快速版本目前不支持repetition_penalty ! 1、min_length ! 0、forced_bos_token_id ! None也不允许 topk 与 topp 同时生效见 modeling.py。3. 序列分类与回归BartForSequenceClassification通过BartClassificationHead在模型顶部增加句子级分类头先对 decoder 输出做 dropout经dense线性层与tanh激活后再做 dropout最后经out_proj输出num_labels维 logits。分类时默认取 eos token 位置的隐状态作为句向量若input_ids中的eos数量不一致会抛出异常提示见 modeling.py 与 modeling.py。传入labels后模型会根据problem_type自动选择损失函数num_labels 1时使用MSELoss回归单标签分类使用CrossEntropyLoss多标签分类使用BCEWithLogitsLoss。示例from paddlenlp.transformers import BartForSequenceClassification, BartTokenizer tokenizer BartTokenizer.from_pretrained(bart-base) model BartForSequenceClassification.from_pretrained(bart-base) inputs tokenizer(Welcome to use PaddlePaddle and PaddleNLP!) inputs {k: paddle.to_tensor([v]) for (k, v) in inputs.items()} logits model(**inputs)4. 抽取式问答BartForQuestionAnswering在模型顶部叠加nn.Linear(config.d_model, 2)输出经 transpose 后拆分为start_logits与end_logits用于 SQuAD 等 span 抽取任务。传入start_positions/end_positions时会用CrossEntropyLoss(ignore_indexignored_index)分别计算起止位置损失并取平均见 modeling.py。从文档到源码信息溯源速查为便于读者继续深入以下列出本文涉及的关键文件与定位关注点文件模型汇总表本文主体文档docs/en/model_zoo/transformers/BART/contents.rst配置类与预训练权重定义paddlenlp/transformers/bart/configuration.py全部模型类实现paddlenlp/transformers/bart/modeling.py分词器实现paddlenlp/transformers/bart/tokenizer.py模块导出声明paddlenlp/transformers/bart/init.py小结PaddleNLP 为 BART 提供了完整的官方支持bart-base与bart-large两套英文预训练权重、覆盖条件生成/分类/问答的四个任务模型类、基于 byte-level BPE 的专用分词器以及训练自动 shift decoder 输入、推理KV cache 增量解码、FasterBART 快速解码两端能力。实践中只需记住一条主线用BartTokenizer.from_pretrained得到分词器、用对应任务模型类的from_pretrained加载权重即可快速搭建基于 BART 的 Seq2Seq 应用需要微调或定制时再以BartConfig的参数为基准调整模型规模与超参。赞分享人工智能大模型NLP深度学习预训练微调RLHF模型量化【免费下载链接】PaddleNLPEasy-to-use and powerful LLM and SLM library with awesome model zoo.项目地址https://gitcode.com/gh_mirrors/pa/PaddleNLP点击查看免费下载相关推荐PaddleNLP 中 CTRL 模型预训练权重与使用指南PaddleNLP 中 CTRL 模型预训练权重与使用指南 本篇指南基于 PaddleNLP 仓库中 CTRL 模型汇总文档 https://link.gitc人工智能大模型NLP深度学习预训练微调RLHF模型量化模型推理服务本地部署模型压缩强化学习模型评测PaddleNLP 中 BART 模型预训练权重与源码实现全解析从模型汇总表到实战调用PaddleNLP 中 BART 模型预训练权重与源码实现全解析从模型汇总表到实战调用 BARTBidirectional and Auto Regress人工智能大模型NLP深度学习预训练微调RLHF模型量化模型推理服务本地部署模型压缩强化学习模型评测PaddleNLP ERNIE-GEN 预训练模型与权重使用指南PaddleNLP ERNIE GEN 预训练模型与权重使用指南 本篇指南聚焦 PaddleNLP 中 ERNIE GEN 生成式预训练模型及其官方预训练权重的人工智能大模型NLP深度学习预训练微调RLHF模型量化模型推理服务本地部署模型压缩强化学习模型评测上一篇DownmarkerWPF 项目下载及安装教程下一篇探索材料科学的利器密度泛函理论与第一性原理计算资源库创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
