Transformers documentation

Kolibri 1.1

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

This model was contributed to Hugging Face Transformers on 2026-11-23.

Kolibri 1.1

Kolibri 1.1 is Aleph Alpha’s successor to Kolibri 1. Comparison to Kolibri 1:

  • It keeps the mixture-of-experts layers and the sliding-window attention layers of Kolibri 1.
  • The first two layers have a dense MLP instead of a mixture of experts.
  • Every fifth layer attends to the whole context, but sparsely. These layers replace the full-attention layers of Kolibri 1. They are the "indexed_attention" entries of layer_types.
  • Indexed-attention layers can attend to the keys and values of an earlier indexed-attention layer. Only the 5th, 20th, 25th and 30th layers compute their own. The other indexed-attention layers attend to those of the closest preceding of these, except the 50th layer, which attends to those of the 5th.

The sparse attention is designed as follows:

  • Every query attends to the 8 first tokens, the 128 most recent tokens and the 2048 highest scoring other keys. Queries that see no more keys than that attend to all of them.
  • Keys are scored without learned weights: by the ReLU of the logits of the first 12 query heads against key head 0, averaged over these heads.
  • Indexer layers (the 5th, 15th, 20th and 30th) first pick a pool of 16384 candidate keys: all of them for short contexts, otherwise the 1024 blocks of 16 consecutive keys whose averaged key scores highest. The other indexed-attention layers rescore the pool of the closest preceding indexer.

The sparse attention keys and values, as well as the routing queries and keys, are rounded to NVFP4.

This is a reference implementation. Sparse layers apply their key selection as an explicit attention mask, so only the eager and SDPA attention implementations are supported, selecting keys costs time and memory quadratic in the prompt length, and every decoding step rescans the whole context. A prefill of about 50k tokens fits on two 180 GB GPUs; 128k tokens does not.

from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Aleph-Alpha/Kolibri-1.1")
model = AutoModelForCausalLM.from_pretrained("Aleph-Alpha/Kolibri-1.1", device_map="auto", attn_implementation="sdpa")

messages = [{"role": "user", "content": "Erkläre kurz, was ein Mixture-of-Experts-Modell ist."}]
inputs = tokenizer.apply_chat_template(
    messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))

Kolibri1_1Config

class transformers.Kolibri1_1Config

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 128000hidden_size: int = 2560num_hidden_layers: int = 50num_attention_heads: int = 48num_key_value_heads: int = 4hidden_act: str = 'silu'max_position_embeddings: int = 262144initializer_range: float = 0.02rms_norm_eps: float = 1e-06use_cache: bool = Truetie_word_embeddings: bool = Falserope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonesliding_window: int | None = 513attention_dropout: float | int = 0.0moe_intermediate_size: int = 512num_experts_per_tok: int = 6num_experts: int = 384norm_topk_prob: bool = Falseoutput_router_logits: bool = Falsepad_token_id: int | None = Nonebos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Nonehead_dim: int = 128shared_expert_intermediate_size: int = 512layer_types: list[str] | None = Noneindex_layers: list[int] | None = Nonekv_source_layers: list[int] | None = Noneindex_topk: int = 2048index_pool_size: int = 16384index_compression: int = 16index_num_heads: int = 12index_num_local_tokens: int = 128index_num_sink_tokens: int = 8mlp_only_layers: list[int] | None = Nonemlp_only_intermediate_size: int = 3584 )

参数

  • vocab_size (int,可选,默认为 128000) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 2560) — 隐藏表示的维度。
  • num_hidden_layers (int,可选,默认为 50) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 48) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选,默认为 4) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则将使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行 meanpooling 来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • hidden_act (str,可选,默认为 silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • max_position_embeddings (int,可选,默认为 262144) — 该模型可能使用的最大序列长度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • rms_norm_eps (float,可选,默认为 1e-06) — RMS 归一化层使用的 epsilon 值。
  • use_cache (bool,可选,默认为 True) — 模型是否应返回最后一次键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 或模型为仅解码器生成式模型时相关。
  • tie_word_embeddings (bool,可选,默认为 False) — 是否根据模型的 tied_weights_keys 映射来绑定权重嵌入。
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • sliding_window (int,可选,默认为 513) — 滑动窗口注意力的窗口大小。如果为 None,则不应用滑动窗口。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • moe_intermediate_size (int,可选,默认为 512) — 路由专家 MLP 的中间层大小。
  • num_experts_per_tok (int,可选,默认为 6) — 每个 token 路由到的专家数量。这是 token-choice 路由的 top-k 值。
  • num_experts (int, 可选, 默认为 384) — MoE 层中路由专家的数量。
  • norm_topk_prob (bool,可选,默认为 False) — 是否对路由专家的权重进行归一化。
  • output_router_logits (bool,可选,默认为 False) — 是否由模型返回路由器 logits。启用此选项后,模型还将输出辅助损失,包括负载均衡损失和路由器 z-loss。
  • pad_token_id (int, 可选) — 词表中用于填充的 token id。
  • bos_token_id (int, 可选) — 词汇表中用于表示流起始的 Token id。
  • eos_token_id (Union[int, list[int]], 可选) — 词汇表中用于表示流结束(end-of-stream)的 token id。
  • head_dim (int,可选,默认为 128) — 注意力头维度。如果为 None,则默认为 hidden_size // num_attention_heads
  • shared_expert_intermediate_size (int,可选,默认为 512) — 共享专家 MLP 的中间层大小。
  • layer_types (list[str], 可选) — 一个列表,用于显式地将每个层索引映射到其层类型。如果未提供,将根据 config 值自动生成。
  • index_layers (list[int], optional) — Indices of the indexed-attention layers that select a new pool of candidate keys (indexers). Every other indexed-attention layer rescores the pool of the closest preceding indexer (reindexer). Must contain the first indexed-attention layer. Defaults to Kolibri 1.1’s layout: the 1st, 3rd, 4th and 6th indexed-attention layers.
  • kv_source_layers (list[int], optional) — For each layer, the index of the layer whose keys and values it attends to. An indexed-attention layer that reads those of an earlier layer has no key/value projections of its own. Defaults to Kolibri 1.1’s layout: of its 10 indexed-attention layers, the 2nd and 3rd read the keys and values of the 1st, the 7th to 9th those of the 6th and the 10th those of the 1st, while the 1st, 4th, 5th and 6th produce their own. Configs with more indexed-attention layers must set it explicitly. The entries of sliding-attention layers must be their own index.
  • index_topk (int, optional, defaults to 2048) — Number of keys each query of a sparse layer selects from its pool, besides the sink and local tokens.
  • index_pool_size (int, optional, defaults to 16384) — Number of keys in an indexer’s pool. Queries that see no more keys than this select from all of them.
  • index_compression (int, optional, defaults to 16) — Number of consecutive keys an indexer averages into one summary when scoring blocks for its pool.
  • index_num_heads (int, optional, defaults to 12) — Number of leading query heads used to score keys, at most the number of query heads of key head 0.
  • index_num_local_tokens (int, optional, defaults to 128) — Number of most recent tokens, including the query itself, that every query of a sparse layer attends to.
  • index_num_sink_tokens (int, optional, defaults to 8) — Number of leading tokens that every query of a sparse layer attends to.
  • mlp_only_layers (list[int], optional) — Indices of the layers with a dense MLP instead of a mixture of experts. Defaults to Kolibri 1.1’s layout: the first two layers.
  • mlp_only_intermediate_size (int, optional, defaults to 3584) — Intermediate size of the dense MLPs of mlp_only_layers.

This is the configuration class to store the configuration of a Kolibri1_1Model. It is used to instantiate a Kolibri1 1 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the Aleph-Alpha/Kolibri-1.1

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

>>> from transformers import Kolibri1_1Model, Kolibri1_1Config

>>> configuration = Kolibri1_1Config()
>>> model = Kolibri1_1Model(configuration)
>>> configuration = model.config

Kolibri1_1Model

class transformers.Kolibri1_1Model

< >

( config: Kolibri1_1Config )

参数

  • config (Kolibri1_1Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The bare Kolibri1 1 Model outputting raw hidden-states without any specific head on top.

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeModelOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • cache (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 cache 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 cache,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用 cache,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的所有 input_ids。

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。

返回值

MoeModelOutputWithPast 或 tuple(torch.Tensor)

MoeModelOutputWithPast 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。

The Kolibri1_1Model forward method, overrides the __call__ special method.

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • last_hidden_state(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor)— 模型最后一层输出的隐藏状态序列。

  • cache(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值,以及如果 config.is_encoder_decoder=True 则还包括交叉注意力块中的键和值),可用于(参见 cache 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

  • router_logits (tuple(torch.Tensor),可选,当传入 output_router_probs=True 且 config.add_router_probs=True,或当 config.output_router_probs=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, sequence_length, num_experts)。

    由 MoE 路由器计算的原始路由器 logits(softmax 之后),这些术语用于计算混合专家模型的辅助损失。

Kolibri1_1ForCausalLM

class transformers.Kolibri1_1ForCausalLM

< >

( config: Kolibri1_1Config )

参数

  • config (Kolibri1_1Config) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The Kolibri1 1 Model for causal language modeling.

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonecache: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → MoeCausalLMOutputWithPast or tuple(torch.Tensor)

参数

  • input_ids (torch.LongTensor 形状为 (batch_size, sequence_length), ,可选) — 输入序列中各 token 在词汇表中的索引。默认情况下,填充(padding)将被忽略。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。

    什么是输入 ID?

  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • position_ids (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为 [0, config.n_positions - 1].

    什么是位置 ID?

  • cache (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由 cache 在解码的先前阶段返回,当 use_cache=True 或 config.use_cache=True.

    仅允许将 Cache 实例作为输入,请参阅我们的 kv cache 指南。 如果未传入 cache,则默认会初始化 DynamicCache。

    模型将输出与输入相同的缓存格式。

    如果使用 cache,用户应仅输入未处理的 input_ids(即未向该模型提供其过去键值状态的那些),其形状为 (batch_size, unprocessed_length),而不是形状为 (batch_size, sequence_length) 的所有 input_ids。

  • inputs_embeds(形状为 (batch_size, sequence_length, hidden_size) 的 torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。
  • labels (torch.LongTensor 形状为 (batch_size, sequence_length), 可选) — 用于计算因果语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] (参见 input_ids 文档字符串)。索引设置为 -100 的 token 将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size].

    标签在内部会进行移位,因此使用labels[..., 1:]来预测logits[..., :-1, :]。 请传入与input_ids匹配的未移位标签(即labels = input_ids)。在传入之前,请勿自行对标签进行移位。

    如果标签已经移位(例如在使用序列并行时),请将其作为 shift_labels 关键字参数传入,系统将直接使用该值。为了计算损失,仍然必须传入 labels。

  • use_cache (bool, 可选) — 如果设置为 True,则会返回 cache 键值状态,可用于加速解码(参见 cache)。
  • logits_to_keep (Union[int, torch.Tensor], 可选,默认为 0) — 如果为 int,则计算最后 logits_to_keep 个 token 的 logits。如果为 0,则计算所有 input_ids 的 logits(特殊情况)。生成过程只需要最后一个 token 的 logits,仅针对该 token 进行计算可以节省内存,对于长序列或大词汇量而言,这种节省相当显著。 如果为 torch.Tensor,则必须是一维张量,对应于序列长度维度中需要保留的索引。 这在使用打包张量格式(将批次和序列长度合并为单一维度)时非常有用。

返回值

MoeCausalLMOutputWithPast 或 tuple(torch.Tensor)

MoeCausalLMOutputWithPast 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。

The Kolibri1_1ForCausalLM forward method, overrides the __call__ special method.

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits(形状为 (batch_size, sequence_length, config.vocab_size) 的 torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。

  • aux_loss (torch.Tensor,可选,当传入 output_router_logits=True 或 config.output_router_logits=True,且模型使用负载均衡损失训练其路由器时返回) — 稀疏模块的负载均衡辅助损失。那些改用路由器偏差来平衡其专家(DeepSeek-V3 及由其衍生的架构)的模型,此处返回 None,但仍会返回 router_logits。

  • router_logits (tuple(torch.Tensor),可选,在传入 output_router_logits=True 或 config.output_router_logits=True 时返回) — 一个 torch.Tensor 元组(每个稀疏层对应一个),形状为 (batch_size * sequence_length, num_experts)。

    由 MoE 路由器计算的原始路由器 logits。可用于计算负载均衡损失,或检查 token 如何被分发到各个专家。

  • cache(Cache,可选,在传入 use_cache=True 或 config.use_cache=True 时返回)—— 它是一个 Cache 实例。更多详情,请参阅我们的 kv cache 指南。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 cache 输入)加速顺序解码。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

    模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoTokenizer, Kolibri1_1ForCausalLM

>>> model = Kolibri1_1ForCausalLM.from_pretrained("Aleph-Alpha/Kolibri-1.1")
>>> tokenizer = AutoTokenizer.from_pretrained("Aleph-Alpha/Kolibri-1.1")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
Update on GitHub