
Transformers 中的 Cohere Command-RRAG 与工具调用场景下的因果语言模型使用指南【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformersCohere Command-R 是由 Cohere 训练并贡献进 Transformers 的一个 35B 参数多语言大语言模型针对检索增强生成RAG与外部 API / 工具调用做了专门训练原生支持单步与多步工具使用上下文长度可达 128K tokens。本文以 Cohere 模型文档 为主线结合仓库中 configuration_cohere.py、modeling_cohere.py 与 tokenization_cohere.py 的实现细节系统讲解如何在当前 Transformers 仓库中加载、推理、量化并诊断 Command-R 系列模型读完你即可在本地用 Pipeline、AutoModel 与 CLI 三种方式跑通 Command-R并掌握 RAG / 工具调用专用提示模板与内存优化要点。Command-R 是什么面向 grounded generation 与工具调用的 35B 模型Command-R见原文档对 Command-R 博客 的引用是一个 35B 参数的多语言 LLM其设计目标并非通用闲聊而是长上下文工作负载检索增强生成RAG能够依据检索到的文档片段生成带引用的答案即文档所述的grounded generation调用外部 API 与工具支持单步single-step与多步multi-step工具调用128K tokens 上下文窗口可一次性纳入长文档或长对话历史。在 Transformers 中Command-R 的 checkpoint 可直接通过自动模型类加载cohere已注册进 modeling_auto.pyCohereModel、CohereForCausalLM对应的映射表。除 Command-R 本体外同一系列的其他 checkpoint 可参见 Command Models 集合。注意本页只覆盖第一代 Command-RCohereForAI/c4ai-command-r-v01仓库中另有独立的 cohere2 文档 介绍采用滑动窗口注意力的 7B 开源版本 Command R7B两者实现分属cohere与cohere2两个模块。三种方式快速上手 Command-R 生成原文档用同一段以问答为例的代码展示了三种入口下面逐一给出可完整运行的形态。方式一Pipeline一行完成任务from transformers import pipeline pipeline pipeline( tasktext-generation, modelCohereForAI/c4ai-command-r-v01, device0 # 指定 GPU 设备 ) pipeline(Plants create energy through a process known as)Pipeline 内部会自动组装 tokenizer 与模型适合快速验证与脚本化推理。方式二AutoModelForCausalLM chat template推荐这是最贴近生产实践的写法——它通过apply_chat_template走 Command-R 专属聊天模板而不是把用户句子裸塞给模型from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer AutoTokenizer.from_pretrained(CohereForAI/c4ai-command-r-v01) model AutoModelForCausalLM.from_pretrained( CohereForAI/c4ai-command-r-v01, device_mapauto, attn_implementationsdpa, ) # 用 Command-R 的 chat template 格式化消息 messages [{role: user, content: How do plants make energy?}] input_ids tokenizer.apply_chat_template( messages, tokenizeTrue, add_generation_promptTrue, return_tensorspt ).to(model.device) output model.generate( input_ids, max_new_tokens100, do_sampleTrue, temperature0.3, cache_implementationstatic, ) print(tokenizer.decode(output[0], skip_special_tokensTrue))几点参数解释均可替换为其他采样参数attn_implementationsdpa启用 PyTorch 原生 SDPA 内核见下文注意力后端temperature0.3偏低适合事实性问答do_sampleTrue开启随机采样cache_implementationstatic使用静态 KV cache 以提升长序列解码吞吐add_generation_promptTrue保证输入末尾带上开始生成助手回复的控制 token。方式三transformers CLI无需写 Python# pip install -U flash-attn --no-build-isolation transformers chat CohereForAI/c4ai-command-r-v01 --dtype auto --attn_implementation flash_attention_2命令行中的--dtype auto让框架按设备自动选择权重精度若本地已安装 FlashAttention可用flash_attention_2后端获得高性能解码。CLI 需要较新版本仓库配套的 transformers 命令可通过仓库 cli 目录了解 chat 子命令的其他开关。从源码看 Command-R 的架构细节原文档对本模型的代码说明非常克制正文仅提示它基于 EleutherAI 的 GPT-NeoX 代码改写但翻开 modeling_cohere.py 可以发现它与 Llama 的同源关系与四处关键差异理解这些差异有助于你调参和做二次开发logit_scale输出缩放与 Llama 最显眼的区别。配置中logit_scale默认为0.0625。在 modeling_cohere.py 中CohereForCausalLM.forward计算完lm_head后执行logits logits * self.logit_scale这是训练时就引入的固定缩放推理与微调时不应移除否则 logits 量纲错位会破坏采样分布。QK Normquery-key 归一化。use_qk_norm默认False开启后注意力会先对 Q、K 在每个 head_dim 上做一次 CohereLayerNorm 归一化再进 RoPE 与注意力。代码注释将其标注为main diff from Llama。Rotary Embedding 的 interleave 拼接。RoPE 频率以interleave方式交织而非 Llama 式的cat见CohereRotaryEmbedding.forward中torch.repeat_interleave(freqs, 2, dim-1)的注释。pre-LayerNorm 并行分支的 decoder layer。每个CohereDecoderLayer内部是residual attention mlp先对残差做一次 LayerNormattention 与 MLPSwiGLU 结构gate/up/down三个线性层读取同一份归一化结果后并行计算再相加这与 Llama 顺序式先 attn 后 mlp 各自带残差不同减少了 LayerNorm 次数。此外配置类 CohereConfig 本身是strict数据类默认超参数直接对应 Command-R 的官方规模rope_theta默认500000.0支撑 128K 长上下文的外推。模型类还声明了base_model_tp_plan/base_model_pp_plan表明支持张量并行与流水线并行的分层切分计划。注意力后端支持从 modeling_cohere.py 中CoherePreTrainedModel的能力标记看cohere模型类支持_supports_flash_attn、_supports_sdpa、_supports_flex_attn因此可以传入flash_attention_2需自行安装 flash-attn速度最快仅支持 fp16/bf16见下文注意事项sdpaPyTorch 内置无需额外依赖是文档示例中的默认推荐eager走纯 PyTorch 算子便于调试flex_attn与分页注意力等能力在仓库 generation 与 tests/generation/test_flash_attention_parity.py 中有更完整的覆盖测试。用 bitsandbytes 把 Command-R 压到 4-bitCommand-R 有 35B 参数fp16 权重即需约 70GB 显存单卡难以直接加载。文档给出的做法是用 bitsandbytes 量化到 4-bitfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig bnb_config BitsAndBytesConfig(load_in_4bitTrue) tokenizer AutoTokenizer.from_pretrained(CohereForAI/c4ai-command-r-v01) model AutoModelForCausalLM.from_pretrained( CohereForAI/c4ai-command-r-v01, device_mapauto, quantization_configbnb_config, attn_implementationsdpa, ) # 用 Command-R 的 chat template 格式化消息 messages [{role: user, content: How do plants make energy?}] input_ids tokenizer.apply_chat_template( messages, tokenizeTrue, add_generation_promptTrue, return_tensorspt ).to(model.device) output model.generate( input_ids, max_new_tokens100, do_sampleTrue, temperature0.3, cache_implementationstatic, ) print(tokenizer.decode(output[0], skip_special_tokensTrue))要点BitsAndBytesConfig(load_in_4bitTrue)也可按需追加bnb_4bit_compute_dtype、bnb_4bit_quant_type等字段细化精度与计算 dtypequantization_config与device_mapauto配合使各层在加载时就被分片到可用设备关于量化后如何微调QLoRA以及更多量化后端AWQ、GPTQ、HQQ 等参见仓库 bitsandbytes 指南 与 量化总览。用 AttentionMaskVisualizer 理解注意力掩码Command-R 面向长上下文、支持左填充批处理理解哪些 token 能 attend 到哪些 token对排查生成质量很有价值。文档给出的诊断工具是注意力掩码可视化器代码位于仓库 attention_visualizer.py该文件中的AttentionMaskVisualizer类会基于模型的因果掩码把每个 token 的可 attend 关系渲染成矩阵图from transformers.utils.attention_visualizer import AttentionMaskVisualizer visualizer AttentionMaskVisualizer(CohereForAI/c4ai-command-r-v01) visualizer(Plants create energy through a process known as)输出会以逐 token 的网格展示当前 prompt 下哪些位置相互可见。由于本仓库不含该输出图的副本原文档中的示意图托管在文档仓库运行时请以终端打印结果为准。使用注意事项原文档Notes一节专门提醒了一类易错点此处完整保留并补充解释使用 FlashAttention-2 时不要在AutoModel.from_pretrained中传dtype参数。FlashAttention-2 只支持 fp16 或 bf16直接指定dtypetorch.float32会报错或静默失效。正确姿势是训练场景在Trainer中开启fp16True或bf16True自动混合精度AMP推理脚本用torch.autocast上下文包裹前向传播让算子以半精度执行或用--dtype autoCLI让框架按设备能力自动选择。这一限制同样适用于所有依赖 flash-attn 的模型属于使用 Transformers 的通用经验。API 速查配置、Tokenizer 与模型类原文档以 autodoc 形式给出了四个公开类本文将其整理为便于检索的速查表。CohereConfig定义在 configuration_cohere.py继承PreTrainedConfigmodel_type cohere。默认值即 Command-R 官方超参参数默认值说明vocab_size256000词表大小hidden_size8192隐藏层维度intermediate_size22528SwiGLU 中间层维度num_hidden_layers40解码器层数num_attention_heads64注意力头数num_key_value_headsNone attention headsGQA 的 KV 头数缺省时与 Q 头相同hidden_actsiluMLP 激活函数max_position_embeddings8192训练最大序列长度initializer_range0.02参数初始化范围layer_norm_eps1e-5LayerNorm 的 epsilonlogit_scale0.0625输出 logits 的固定缩放系数use_cacheTrue是否缓存 past_key_valuespad_token_id/bos_token_id/eos_token_id0 / 5 / 255001特殊 token idtie_word_embeddingsTrue是否捆绑输入/输出词嵌入rope_parameters.rope_theta500000.0RoPE 基数支撑长上下文attention_bias/attention_dropoutFalse / 0.0注意力线性层偏置与 dropoutuse_qk_normFalse是否启用 QK 归一化__post_init__中会在num_key_value_headsNone时自动补齐为num_attention_heads因此你不需要手动设置 KV 头数也能得到与 Command-R 一致的配置。CohereTokenizer定义在 tokenization_cohere.py底层是 byte-level BPE并启用了ByteFallback未登录 UTF-8 字节回退与NFC 归一化预处理阶段即执行见其 normalizer 配置其padding_side固定为left左侧填充适合 decoder-only 长上下文批处理。特殊 token 约定BOS_TOKENbos、|END_OF_TURN_TOKEN|eos、PADpad。注意如果自定义了bos_token/eos_token必须同步调用tokenizer.update_post_processor()重新生成 post-processor否则编码结果的首/尾 token 值不准确而add_prefix_spaceTrue虽可绕过部分行为但模型预训练并未采用该设置可能造成精度下降。当配合is_split_into_wordsTrue做逐词标注时则必须设置add_prefix_spaceTrue。除常规聊天模板外该 tokenizer 还暴露两个 Command-R 特性方法是 RAG / Agent 场景的杀手锏apply_grounded_generation_template(conversation, documents, citation_modeaccurate)把对话历史与检索文档形如{title: ..., text: ...}的字典列表渲染为带引用指令的 RAG prompt。citation_mode取accurate先答后补引用引用质量更高或fast直接生成带引用答案所需生成 token 更少apply_tool_use_template(conversation, tools)把工具清单name/description/parameter_definitions与对话渲染为工具调用 prompt模型会输出类似[{tool_name: internet_search, parameters: {...}}]的结构化动作多轮循环即可实现多步工具调用。二者在实现上都会委托给apply_chat_template分别对应chat_templaterag与tool_use具体调用示例见 tokenization_cohere.py 中两个方法的 doctest可按其中给出的internet_search/directly_answer等工具 schema 直接改写复用。CohereModel 与 CohereForCausalLMCohereModel裸主干词嵌入 → 40 层CohereDecoderLayer→ 末层 LayerNorm输出BaseModelOutputWithPast前向仅暴露forward方法。加载原始 checkpoint 权重时直接对应仓库中的 model 权重键。CohereForCausalLM在主干之上叠加lm_head默认与embed_tokens权重捆绑见_tied_weights_keys并在forward中执行logits * logit_scale它混入GenerationMixin可直接调用generate()。该类的 doctest 演示了最基本的续写流程model.generate(...)后tokenizer.batch_decode。两者的完整参数签名与返回值均可在 modeling_cohere.py 中查阅常见入参包括input_ids、attention_mask、position_ids、past_key_valuesKV cache类型为 cache_utils.py 中的Cache、inputs_embeds、use_cache等。相关阅读同类后一代模型见 Cohere2 模型文档Command R7B滑动窗口注意力量化总览 与 bitsandbytes 提供更多低比特加载后端模型与 tokenizer 的官方测试分别在 test_modeling_cohere.py 与 test_tokenization_cohere.py其中包含与参考实现一致性校验、长上下文与注意力掩码等用例可作为自建适配的回归基线。【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考