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로 표현할 수 있는 서로 다른 토큰의 수를 정의합니다.
  • hidden_size (int, 선택 사항, 기본값 2560) — 숨겨진 표현의 차원입니다.
  • num_hidden_layers (int, 선택 사항, 기본값 50) — Transformer decoder의 숨겨진 레이어 수.
  • num_attention_heads (int, 선택 사항, 기본값 48) — Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.
  • 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) — 모델이 마지막 key/values attention을 반환할지 여부입니다(모든 모델에서 사용되지 않음). config.is_decoder=True인 경우 또는 모델이 decoder-only 생성 모델인 경우에만 관련이 있습니다.
  • tie_word_embeddings (bool, 선택, 기본값 False) — 모델의 tied_weights_keys 매핑에 따라 가중치 임베딩을 묶을지 여부.
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], 선택) — RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 rope_theta 값이 포함되어야 하며, 더 긴 max_position_embeddings로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.
  • sliding_window (int, 선택 사항, 기본값 513) — 슬라이딩 윈도우 어텐션의 윈도우 크기입니다. None인 경우 슬라이딩 윈도우가 적용되지 않습니다.
  • attention_dropout (Union[float, int], 선택 사항, 기본값 0.0) — Attention 확률에 적용할 dropout 비율입니다.
  • moe_intermediate_size (int, 선택 사항, 기본값 512) — 라우팅된 expert MLP의 intermediate size입니다.
  • num_experts_per_tok (int, 선택 사항, 기본값 6) — 각 토큰을 라우팅할 전문가의 수입니다. 이는 토큰 선택 라우팅의 top-k 값입니다.
  • num_experts (int, 선택 사항, 기본값 384) — MoE 레이어의 라우팅 전문가 수입니다.
  • norm_topk_prob (bool, 선택 사항, 기본값 False) — 라우팅된 전문가의 가중치를 정규화할지 여부입니다.
  • output_router_logits (bool, 선택 사항, 기본값 False) — 모델이 router logits를 반환할지 여부입니다. 이 옵션을 활성화하면 load balancing loss와 router z-loss를 포함한 auxiliary loss도 출력할 수 있습니다.
  • pad_token_id (int, 선택 사항) — 어휘에서 패딩에 사용되는 토큰 ID입니다.
  • bos_token_id (int, 선택 사항) — 어휘에서 스트림 시작에 사용되는 토큰 ID입니다.
  • eos_token_id (Union[int, list[int]], 선택) — 어휘에서 스트림 종료에 사용되는 토큰 ID입니다.
  • head_dim (int, 선택 사항, 기본값 128) — Attention head의 차원입니다. None인 경우 hidden_size // num_attention_heads 값이 기본값으로 사용됩니다.
  • shared_expert_intermediate_size (int, 선택 사항, 기본값 512) — 공유 expert MLP의 intermediate size입니다.
  • 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

Configuration 객체는 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), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • cache (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key와 value)입니다. 이는 일반적으로 cache 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

    입력으로 Cache 인스턴스만 허용되며, kv cache guide를 참고하세요. cache가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.

    모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.

    cache가 사용되는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만, 즉 (batch_size, sequence_length) 모양의 모든 input_ids 대신 (batch_size, unprocessed_length) 모양의 처리되지 않은 input_ids를 입력해야 합니다.

  • inputs_embeds (torch.FloatTensor, shape (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.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • last_hidden_state (torch.Tensor, shape (batch_size, sequence_length, hidden_size)) — 모델의 마지막 레이어 출력에서 생성된 hidden-state 시퀀스입니다.

  • cache (Cache, 선택 사항, use_cache=True가 전달되거나 config.use_cache=True인 경우 반환됨) — Cache 인스턴스입니다. 자세한 내용은 kv cache 가이드를 참고하세요.

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프-어텐션 블록의 key와 value, 그리고 config.is_encoder_decoder=True인 경우 크로스-어텐션 블록의 key와 value)를 포함합니다(사용 방법은 cache 입력을 참조).

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

  • router_logits (tuple(torch.Tensor), 선택 사항, output_router_probs=True와 config.add_router_probs=True가 전달되었거나 config.output_router_probs=True인 경우 반환됨) — 각 레이어마다 하나씩, 모양이 (batch_size, sequence_length, num_experts)인 torch.Tensor의 튜플.

    MoE 라우터가 계산하는 softmax 적용 후의 원시 라우터 로짓(raw router logits)입니다. 이 값들은 Mixture of Experts 모델의 보조 손실(auxiliary loss)을 계산하는 데 사용됩니다.

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), 선택 사항) — 어휘(input vocabulary)에서 입력 시퀀스 토큰의 인덱스입니다. 기본적으로 패딩은 무시됩니다.

    AutoTokenizer를 사용하여 인덱스를 얻을 수 있습니다. 자세한 내용은 PreTrainedTokenizer.encode() 및 PreTrainedTokenizer.call()를 참조하세요.

    입력 ID란 무엇인가요?

  • attention_mask (torch.Tensor 형상이 (batch_size, sequence_length), 선택 사항) — 패딩 토큰 인덱스에 대한 attention을 수행하지 않도록 방지하는 마스크. [0, 1]에서 선택된 마스크 값: 마스크되지 않은 토큰은 1, 마스크된 토큰은 0. attention mask란 무엇인가요? [0, 1]:
    • 마스크되지 않은 토큰에 대해 1
    • 마스크된 토큰에 대해 0

    어텐션 마스크란 무엇인가요?

  • position_ids (torch.LongTensor 의 shape (batch_size, sequence_length), , 선택 사항) — 위치 임베딩에서 각 입력 시퀀스 토큰의 위치 인덱스. 범위 [0, config.n_positions - 1].

    포지션 ID란 무엇인가요?

  • cache (~cache_utils.Cache, 선택 사항) — 순차적 디코딩을 가속화할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록과 크로스 어텐션 블록의 key와 value)입니다. 이는 일반적으로 cache 디코딩의 이전 단계에서 모델이 반환한 use_cache=True 또는 config.use_cache=True.

    입력으로 Cache 인스턴스만 허용되며, kv cache guide를 참고하세요. cache가 전달되지 않으면 기본적으로 DynamicCache가 초기화됩니다.

    모델은 입력으로 제공된 것과 동일한 캐시 형식을 출력합니다.

    cache가 사용되는 경우, 이 모델에 과거 키 값 상태가 제공되지 않은 input_ids만, 즉 (batch_size, sequence_length) 모양의 모든 input_ids 대신 (batch_size, unprocessed_length) 모양의 처리되지 않은 input_ids를 입력해야 합니다.

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), 선택) — input_ids를 전달하는 대신 임베딩 표현을 직접 전달할 수 있습니다. 이는 모델 내부의 임베딩 조회 행렬보다 input_ids 인덱스를 관련 벡터로 변환하는 방식에 대해 더 세밀한 제어가 필요한 경우에 유용합니다.
  • labels (torch.LongTensor 형태가 (batch_size, sequence_length), 선택 사항) — causal language modeling loss를 계산하기 위한 라벨. 인덱스는 [-100, 0, ..., config.vocab_size] (참조 input_ids 문서 문자열). 인덱스가 -100 으로 설정된 토큰은 무시(마스크)되며, loss는 라벨이 [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 토큰에 대한 logits를 계산합니다. 0인 경우, 모든 input_ids에 대한 logits를 계산합니다(특수한 경우). 생성에는 마지막 토큰의 logits만 필요하며, 해당 토큰에 대해서만 계산하면 메모리를 절약할 수 있습니다. 이는 긴 시퀀스나 큰 어휘 크기의 경우 상당한 이점을 제공합니다. torch.Tensor인 경우, 시퀀스 길이 차원에서 유지할 인덱스에 해당하는 1차원 텐서여야 합니다. 이는 패킹된 텐서 형식(배치와 시퀀스 길이를 단일 차원으로 사용하는 경우)을 사용할 때 유용합니다.

반환값

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.

이 함수 내에서 forward pass의 레시피를 정의해야 하지만, 이후에는 이 함수 대신 Module 인스턴스를 호출해야 합니다. 전자는 전처리 및 후처리 단계를 실행하는 것을 처리하는 반면, 후자는 이를 조용히 무시하기 때문입니다.

  • loss (torch.Tensor, shape (1,), 선택 사항, labels이 제공될 때 반환됨) — 언어 모델링 손실(다음 토큰 예측용).

  • logits (torch.Tensor, shape (batch_size, sequence_length, config.vocab_size)) — 언어 모델링 헤드에서 생성된 예측 점수(SoftMax 적용 전 각 어휘 토큰에 대한 점수).

  • aux_loss (torch.Tensor, 선택 사항, output_router_logits=True가 전달되거나 config.output_router_logits=True인 경우, 그리고 모델이 로드 밸런싱 손실로 라우터를 학습하는 경우 반환됨) — 희소 모듈에 대한 로드 밸런싱 보조 손실입니다. 대신 라우터 바이어스로 전문가를 균형 맞추는 모델(DeepSeek-V3 및 이를 기반으로 파생된 아키텍처)은 router_logits를 반환하되 여기서는 None을 반환합니다.

  • router_logits (tuple(torch.Tensor), 선택 사항, output_router_logits=True가 전달되거나 config.output_router_logits=True인 경우 반환됨) — torch.Tensor의 튜플(스파스 레이어마다 하나)로, 형태는 (batch_size * sequence_length, num_experts)입니다.

    MoE 라우터가 계산한 원시 라우터 로짓입니다. 로드 밸런싱 손실을 계산하거나 토큰이 전문가로 어떻게 분배되는지 확인하는 데 사용할 수 있습니다.

  • cache (Cache, 선택 사항, use_cache=True가 전달되거나 config.use_cache=True인 경우 반환됨) — Cache 인스턴스입니다. 자세한 내용은 kv cache 가이드를 참고하세요.

    순차적 디코딩을 가속화하는 데 사용할 수 있는 사전 계산된 hidden-states(셀프 어텐션 블록의 key와 value)를 포함합니다(입력 cache 참조).

  • hidden_states (tuple(torch.Tensor), 선택 사항, output_hidden_states=True가 전달되거나 config.output_hidden_states=True인 경우 반환됨) — torch.Tensor의 튜플(모델에 임베딩 레이어가 있는 경우 임베딩 출력 1개 + 각 레이어의 출력 1개)로, 모양은 (batch_size, sequence_length, hidden_size)입니다.

    각 레이어의 출력에서 모델의 Hidden-states와 선택적 초기 임베딩 출력을 포함합니다.

  • attentions (tuple(torch.Tensor), 선택 사항, output_attentions=True가 전달되었거나 config.output_attentions=True인 경우 반환됨) — 각 레이어마다 하나씩 포함된 torch.Tensor의 튜플로, 모양은 (batch_size, num_heads, sequence_length, sequence_length)입니다.

    self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치.

예:

>>> 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