首页
/ Transformers 中的 CohereCompass:Cohere 小型专用(视觉)语言模型的统一架构与实战指南

Transformers 中的 CohereCompass:Cohere 小型专用(视觉)语言模型的统一架构与实战指南

2026-09-06 19:14:09作者:明树来

导读

CohereCompass 是 Cohere 为训练小而专的(视觉)语言模型((Vision-)Language Models)设计的基座架构,已于 2026-08-10 由社区贡献合入 Hugging Face Transformers(官方模型文档)。它以“模块化复用”著称:文本解码器继承 Cohere2 的实现,视觉塔与多模态融合沿用 Qwen3VL/Qwen2VL 的成熟管线,并在此基础上加入 DeepStack 视觉残差注入与按层配置的 RoPE 等定制能力。读完本文,你将掌握 CohereCompass 的组件划分与配置项语义,能够用 Auto API 加载与运行其视觉-语言指令模型、纯文本模型与序列分类模型,并理解其源码级实现原理。

Overview:CohereCompass 是什么

依据文档与源码,CohereCompass 定位为 Cohere 训练“小规模、专门化”(vision-)language models 的基座架构(base architecture)。它在库中以一个统一的 model_type = "cohere_compass" 复合架构出现,同时附带 cohere_compass_textcohere_compass_vision 两个子模型类型,文档中的默认参考检查点为 CohereLabs/North-Micro-Vision-Instruct

从实现角度(modular_cohere_compass.py)可以清晰看到它的“拼装”性质:

  • CohereCompassTextConfig 继承自 Cohere2 的 Cohere2ConfigMLPLayerNormAttentionDecoderLayer 直接复用 cohere2 模块;
  • CohereCompassVisionConfigVisionModel 与顶层融合逻辑继承自 qwen3_vl,处理器体系复用 qwen3_vlqwen2_vl
  • 位置编码 CohereCompassRotaryEmbedding 是 Gemma3 旋转编码适配 Compass 多轴位置 ID 的产物(mrope 布局来自 Qwen3VL)。

因此,CohereCompass 文档所描述的“基础能力”,在代码里是一份基于模块化(modular)体系的子类化组合:所有架构文件均由 modular_cohere_compass.py 自动生成(生成物位于同目录下的 configuration_*.pymodeling_*.pyprocessing_*.py 等),修改需要作用于 modular 源文件。

架构解剖:文本解码器 + 视觉塔 + DeepStack 融合

统一的文本解码器

CohereCompassTextModel 在源码中被注释为 “Unified text decoder”(modular_cohere_compass.py):

  • 纯文本检查点:使用普通 2D 位置编码,即标准因果语言模型;
  • 视觉-语言检查点:切换为 3D mrope 多轴位置编码并配合 DeepStack 视觉特征注入。

其内部为标准的解码器栈:embed_tokens → N 层 CohereCompassDecoderLayer → 末尾 CohereCompassLayerNorm。注意力结构具备下列可配置特性(configuration_cohere_compass.py):

  • 逐层注意力类型 layer_types:每层可为 full_attention(全因果注意力)或 sliding_attention(滑窗注意力),默认全部为 full_attentionsliding_window 默认为 4096,用于构建对应的滑窗因果掩码;
  • 逐层 RoPE(rope_parameters:允许按层配置旋转编码参数,也可通过把某层对应 rope 参数置空实现 NoPE(无位置编码)层;convert_rope_params_to_dict 显式允许 “per layer rope with optional NoPE layers”。在文本前向中,位置编码按 layer_types 去重后逐类预计算,再按层分发(modular_cohere_compass.py);
  • 多轴位置 ID:位置张量形状为 (4, batch, seq),硬编码的 4 对应“文本、时间、高度、宽度”四个轴;第一维(纯文本轴)用于构造因果掩码,剩余三维进入 mrope 旋转编码(modular_cohere_compass.py);
  • logit 缩放与池化logit_scale 作用于 LM logits;poolingbos/eos/mean,None 时默认 eos)服务于分类头。

视觉塔与 DeepStack

视觉子配置继承自 Qwen3VLVisionConfig,默认参数体现了“小模型”取向:patch size 16、spatial_merge_size 2、temporal_patch_size 2,视觉输出经 out_hidden_size = 3584 对齐到解码器。其最具辨识度的机制是 DeepStack 视觉索引(deepstack_visual_indexes,默认 [8, 16, 24]:视觉编码器在第 8、16、24 层的中间特征被抽取为“DeepStack 嵌入”(对应论文 DeepStack, arXiv:2406.04334),并随图像嵌入一起送入文本解码器。

融合过程在 Qwen3VLModel.forward 中体现(modeling_qwen3_vl.py):

  1. 视觉塔输出被拆成 pooler_output(常规图像嵌入,通过 masked_scatter 写入 <image> 占位符)与 deepstack_features(各 DeepStack 层的特征列表);
  2. 顶层模型把它们整理为 visual_pos_masksdeepstack_visual_embeds(形状为 (num_layers, visual_seqlen, embed_dim));
  3. 文本解码器在每一层做完自注意力后,若当前层序号落在 DeepStack 范围内,就通过 _deepstack_process 将对应视觉特征逐位置残差相加到视觉 token 的 hidden states 上(modeling_qwen3_vl.py)。

这一设计使视觉信息能以“贯穿多个深度层”的方式融入解码,而非只在首层一次性注入,是 CohereCompass 视觉-语言能力的关键来源。从源码结构推断,这也是检查点名称中 “Vision-Instruct” 后缀所指的能力形态。

配置参考:三个 Config 类

CohereCompassConfig(复合配置)

CohereCompassConfig 是顶层配置,内部持有两个子配置(sub_configs),并定义视觉 token 相关的特殊 ID(configuration_cohere_compass.py):

参数 默认值 含义
model_type "cohere_compass" 复合模型类型,触发 AutoModelForImageTextToText 等自动加载
text_config CohereCompassTextConfig 文本解码器子配置,可为 dict 或对象
vision_config CohereCompassVisionConfig 视觉塔子配置,可为 dict 或对象
image_token_id 255031 图像占位符 token ID
video_token_id 255032 视频占位符 token ID
vision_start_token_id 255028 视觉内容起始 token ID
vision_end_token_id 255029 视觉内容结束 token ID

两个子配置在 __post_init__ 中被自动规范化:若以 dict 传入会被实例化为对应的 PreTrainedConfig 子类;若为 None 则使用默认值构造。兼容性细节:历史检查点里把视觉子配置误标成 "cohere_compass" 类型时,代码会手动改写为 "cohere_compass_vision"

CohereCompassTextConfig(文本子配置)

继承 Cohere2Config,以下默认值对应文档标注的 “North-Micro-Vision-Instruct 风格”配置:

参数 默认值 说明
vocab_size 256000 词表大小
hidden_size 8192 隐藏层维度
intermediate_size 22528 MLP 中间维度(SwiGLU,激活为 silu
num_hidden_layers 40 解码器层数
num_attention_heads 64 注意力头数
num_key_value_heads None 为 None 时取注意力头数(MHA)
head_dim 128 __post_init__ 中由 hidden_size / heads 计算
max_position_embeddings 8192 最大上下文长度
sliding_window 4096 滑窗注意力窗口
layer_types ["full_attention"] * 40 逐层注意力类型
layer_norm_eps 1e-5 LayerNorm epsilon
attention_bias False 注意力投影偏置
attention_dropout 0.0 注意力 dropout
tie_word_embeddings True 输入/输出嵌入是否共享
use_cache True 是否缓存 past_key_values(推理时被忽略的键列表见 keys_to_ignore_at_inference
pad_token_id / bos_token_id / eos_token_id 0 / 5 / 255001 特殊 token ID
logit_scale None LM logits 缩放,None 时在模型内取 1.0
pooling None 分类池化策略(None 等价于 eos
initializer_range 0.02 权重初始化范围

此外配置内置了张量并行(base_model_tp_plan,如 q_proj/k_proj/v_proj/gate_proj/up_projcolwiseo_proj/down_projrowwise 切分)与流水线并行(base_model_pp_plan)的分片计划,说明该架构对分布式推理有原生支持。

CohereCompassVisionConfig(视觉子配置)

参数 默认值 说明
depth 27 视觉塔层数
hidden_size 1152 视觉隐藏维度
intermediate_size 4304 视觉 MLP 中间维度(激活 gelu_pytorch_tanh
num_heads 16 注意力头数
in_channels 3 输入通道(RGB)
patch_size 16 图像 patch 尺寸
spatial_merge_size 2 空间 token 合并比例
temporal_patch_size 2 时间轴 patch 尺寸(视频)
out_hidden_size 3584 视觉输出维度(与解码器对齐)
num_position_embeddings 2304 最大视觉位置数
deepstack_visual_indexes [8, 16, 24] 用于提取 DeepStack 特征的层索引

模型族:从基座到各种任务头

CohereCompass 在库中注册了完整的模型族(auto 映射)。其中 cohere_compass 复合类型自动解析到多模态模型,cohere_compass_text 类型自动解析到纯文本模型:

类型 职责
CohereCompassModel cohere_compass VLM 基座:把视觉塔融合进解码器并应用 DeepStack 残差
CohereCompassForConditionalGeneration cohere_compass 图像-文本到文本生成头,含 forwardget_image_features
CohereCompassTextModel cohere_compass_text 纯文本解码器基座
CohereCompassForCausalLM cohere_compass_text 文本自回归 LM 头(logit_scale 默认 1.0)
CohereCompassTextForSequenceClassification cohere_compass_text 文本序列分类头
CohereCompassVisionModel cohere_compass_vision 独立视觉塔(input_modalities = ("image",)

几个值得注意的实现细节(modular_cohere_compass.py):

  • CohereCompassForConditionalGenerationforward 接受 input_ids / attention_mask / position_ids / past_key_values / inputs_embeds / labels / pixel_values / pixel_values_videos / image_grid_thw / video_grid_thw / mm_token_type_ids / use_cache / logits_to_keep 等入参;视觉-语言基础组件(如 get_placeholder_maskget_image_featuresget_video_features)由 Qwen3VL 管线提供;
  • 前向尾部使用 logits_to_keep 只对最后若干个位置计算 LM logits 以节约显存,随后按 logit_scale(来自 text_config)缩放 logits;
  • CohereCompassPreTrainedModel 声明了 input_modalities = ("image", "text"),并把 CohereCompassDecoderLayer 列入 _no_split_modules(影响 device_map 自动切分时的模块边界);
  • 分类模型 CohereCompassTextForSequenceClassification 支持三种池化:eos(取最右非 pad token,默认)、bos(取首 token,适合双向骨干)、mean(对非 pad token 做掩码平均);不支持的值会抛出 ValueErrormodular_cohere_compass.py)。

处理器体系:图像、视频与统一 Processor

CohereCompass 的预处理器全部是对现有实现的类型别名式封装(为保证内部 model_type 兼容性而改写,见 modular_cohere_compass.py):

Auto API 中的解析关系为:cohere_compass 类型 → CohereCompassProcessor / CohereCompassVideoProcessor,并可通过 processor_class 中的 pil 键指定 PIL 版图像处理器(见 auto_mappings.py)。

实战:图片理解推理(继承官方示例)

文档给出了最核心的使用方式:用 Auto APIAutoModelForImageTextToText + AutoProcessor)加载视觉指令模型,把图片与文本交错在同一个 message 中,经 apply_chat_template 完成 tokenize 后直接 generate

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor

model_id = "CohereLabs/North-Micro-Vision-Instruct"

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(
    model_id,
    device_map="auto",
)

image_url = "https://cdn-uploads.huggingface.co/production/uploads/66d732effe6684fc16b12c28/Io_5OCmftsmH-n158ZtPs.png"
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": image_url},
            {"type": "text", "text": "What do you see?"},
        ],
    }
]

inputs = processor.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_tensors="pt",
    return_dict=True,
).to(model.device)

outputs = model.generate(
    **inputs,
    max_new_tokens=128,
)

input_length = inputs["input_ids"].shape[-1]
response = processor.decode(
    outputs[0][input_length:],
    skip_special_tokens=True,
)
print(response)

代码要点:

  1. 消息内容可交错content 列表允许“一张或多张图片 + 文本”任意穿插;多轮对话沿用同一 messages 结构追加即可;
  2. 纯文本提示:直接省略 {"type": "image", ...} 条目即可,其余 API 不变;
  3. 截断生成结果:用 input_length = inputs["input_ids"].shape[-1] 定位提示长度,再对 outputs[0][input_length:] 解码,避免把提示词重新打印出来;
  4. 自动设备与精度管理device_map="auto" 让模型按 _no_split_modules 边界自动分片到可用设备;
  5. 该模型文档标有 FlashAttention 与 SDPA(PyTorch 的 scaled dot-product attention)徽标,说明两种注意力后端均受支持:在不额外传参时默认走 _attn_implementation 配置;如需显式启用可用 attn_implementation="flash_attention_2""sdpa"(需要对应硬件/环境满足 FlashAttention 的安装前提)。

同一推理流程的等价写法是使用显式类 CohereCompassProcessorCohereCompassForConditionalGeneration(模型自带 docstring 示例,见 modular_cohere_compass.py),当需要精确控制类而不依赖类型探测时推荐此写法。

从零构造配置与模型(示例代码)

文档在 CohereCompassConfig 中给出了纯 Python 构造“North-Micro-Vision-Instruct 风格”配置的方式,适合做架构冒烟测试或自定义小模型训练:

from transformers import CohereCompassForConditionalGeneration, CohereCompassConfig

# 初始化一个 "CohereLabs/North-Micro-Vision-Instruct" 风格的配置
configuration = CohereCompassConfig()

# 由该配置初始化一个模型(随机权重)
model = CohereCompassForConditionalGeneration(configuration)

# 读取模型实际生效的配置
configuration = model.config

纯文本模型与分类模型

  • 文本 LM:纯文本检查点的 model_typecohere_compass_text,用 AutoModelForCausalLM.from_pretrained 即可命中 CohereCompassForCausalLM
  • 序列分类CohereCompassTextForSequenceClassification 对每个位置先用 score 投影再按 config.text_config.pooling 池化。可通过对配置设置 pooling 来选择 bos/eos/mean 三种策略;在 eos 模式下复用父类前向,其他模式下自行实现掩码池化,mean 会借助 attention_mask(或 pad_token_id)排除填充位(modular_cohere_compass.py)。

源码地图:想深入还可以看哪里

仓库内与本文相关的关键实现与测试文件如下:

需要留意的是,本文列出的默认超参均来自当前仓库源码的架构默认值,真实检查点的配置以其 Hugging Face Hub 上的 config.json 为准;from_pretrained 会自动加载该配置并覆盖本地默认值。

登录后查看全文
热门项目推荐
相关项目推荐