Transformers documentation
Kolibri 1.1
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 oflayer_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
< source >( 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 )
Parameters
- vocab_size (
int, optional, defaults to128000) — Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - hidden_size (
int, optional, defaults to2560) — Dimension of the hidden representations. - num_hidden_layers (
int, optional, defaults to50) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to48) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to4) — This is the number of key_value heads that should be used to implement Grouped Query Attention. Ifnum_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), ifnum_key_value_heads=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - hidden_act (
str, optional, defaults tosilu) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - max_position_embeddings (
int, optional, defaults to262144) — The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to1e-06) — The epsilon used by the rms normalization layers. - use_cache (
bool, optional, defaults toTrue) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - tie_word_embeddings (
bool, optional, defaults toFalse) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - sliding_window (
int, optional, defaults to513) — Sliding window attention window size. IfNone, no sliding window is applied. - attention_dropout (
Union[float, int], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - moe_intermediate_size (
int, optional, defaults to512) — Intermediate size of the routed expert MLPs. - num_experts_per_tok (
int, optional, defaults to6) — Number of experts to route each token to. This is the top-k value for the token-choice routing. - num_experts (
int, optional, defaults to384) — Number of routed experts in MoE layers. - norm_topk_prob (
bool, optional, defaults toFalse) — Whether to normalize the weights of the routed experts. - output_router_logits (
bool, optional, defaults toFalse) — Whether or not the router logits should be returned by the model. Enabling this will also allow the model to output the auxiliary loss, including load balancing loss and router z-loss. - pad_token_id (
int, optional) — Token id used for padding in the vocabulary. - bos_token_id (
int, optional) — Token id used for beginning-of-stream in the vocabulary. - eos_token_id (
Union[int, list[int]], optional) — Token id used for end-of-stream in the vocabulary. - head_dim (
int, optional, defaults to128) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads - shared_expert_intermediate_size (
int, optional, defaults to512) — Intermediate size of the shared expert MLPs. - layer_types (
list[str], optional) — A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically generated based on config values. - 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 ofmlp_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
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Kolibri1_1Model
class transformers.Kolibri1_1Model
< source >( config: Kolibri1_1Config )
Parameters
- 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.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( 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)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache).
Returns
MoeModelOutputWithPast or tuple(torch.Tensor)
A MoeModelOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Kolibri1_1Model forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
last_hidden_state (
torch.Tensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
config.is_encoder_decoder=Truein the cross-attention blocks) that can be used (seecacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.Tensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.Tensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.Tensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
router_logits (
tuple(torch.Tensor), optional, returned whenoutput_router_probs=Trueandconfig.add_router_probs=Trueis passed or whenconfig.output_router_probs=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, sequence_length, num_experts).Raw router logits (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliary loss for Mixture of Experts models.
Kolibri1_1ForCausalLM
class transformers.Kolibri1_1ForCausalLM
< source >( config: Kolibri1_1Config )
Parameters
- 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.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( 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)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
torch.Tensorof shape(batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- position_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.n_positions - 1]. - cache (
~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in thecachereturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
cacheare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
cacheare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - inputs_embeds (
torch.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for computing the causal language modeling loss. Indices should be in[-100, 0, ..., config.vocab_size](seeinput_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size].The labels are shifted internally so that
labels[..., 1:]are used to predictlogits[..., :-1, :]. Pass unshifted labels matchinginput_ids(i.e.labels = input_ids). Do not shift the labels yourself before passing them.If the labels are already shifted (for example with sequence parallelism), pass them as the
shift_labelskeyword argument and they are used as is.labelsmust still be passed for the loss to be computed. - use_cache (
bool, optional) — If set toTrue,cachekey value states are returned and can be used to speed up decoding (seecache). - logits_to_keep (
Union[int, torch.Tensor], optional, defaults to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_ids(special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If atorch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).
Returns
MoeCausalLMOutputWithPast or tuple(torch.Tensor)
A MoeCausalLMOutputWithPast or a tuple of
torch.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (None) and inputs.
The Kolibri1_1ForCausalLM forward method, overrides the __call__ special method.
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.
loss (
torch.Tensorof shape(1,), optional, returned whenlabelsis provided) — Language modeling loss (for next-token prediction).logits (
torch.Tensorof shape(batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).aux_loss (
torch.Tensor, optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True, and the model trains its router with a load-balancing loss) — Load-balancing auxiliary loss for the sparse modules. Models that balance their experts with a router bias instead (DeepSeek-V3 and the architectures derived from it) returnNonehere while still returningrouter_logits.router_logits (
tuple(torch.Tensor), optional, returned whenoutput_router_logits=Trueis passed or whenconfig.output_router_logits=True) — Tuple oftorch.Tensor(one for each sparse layer) of shape(batch_size * sequence_length, num_experts).Raw router logits computed by the MoE routers. They can be used to compute a load-balancing loss or to inspect how tokens are dispatched to experts.
cache (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) — It is a Cache instance. For more details, see our kv cache guide.Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
cacheinput) to speed up sequential decoding.hidden_states (
tuple(torch.Tensor), optional, returned whenoutput_hidden_states=Trueis passed or whenconfig.output_hidden_states=True) — Tuple oftorch.Tensor(one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size).Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (
tuple(torch.Tensor), optional, returned whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.Tensor(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length).Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Example:
>>> 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]