# Ergo

Ergo is a Mixture of Experts (MoE) language model developed by Amazon FMR.

Key architectural features:

- **Local and global attention**: every fourth layer attends to the whole context and uses no position embeddings. The other layers attend to the last 512 tokens and use rotary position embeddings. Attention is grouped-query attention with QK normalization.
- **Sparse Mixture of Experts**: 256 routed experts with 8 active per token, plus 1 shared expert. Experts are MLPs with a squared ReLU activation, each followed by its own RMSNorm. The first layer uses a dense MLP.
- **Sigmoid routing** with a bias that only affects which experts are selected, and a routed scaling factor.
- **Gated residual connections**: attention and the MLP are normalized on both their input and their output, and added to the residual stream through a learned gate per hidden dimension.

The residual stream is kept in `float32`. Embeddings, normalization layers, residual gates and language modeling head are also in `float32`.

The weights are released under the [Amazon Ergo Open Weight License](https://huggingface.co/Amazon-FMR/Ergo/blob/main/LICENSE.md).

The example below demonstrates how to generate text with the [AutoModelForCausalLM](/docs/transformers/v5.25.0/en/model_doc/auto#transformers.AutoModelForCausalLM) class.

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Amazon-FMR/Ergo")
model = AutoModelForCausalLM.from_pretrained("Amazon-FMR/Ergo", dtype=torch.bfloat16, device_map="auto")

inputs = tokenizer("The capital of France is", return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=32)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

Support for loading Ergo with `from_pretrained(..., distributed_config=...)` is still in development.
In the meantime, the [FSDP2 and expert parallelism example](https://gist.github.com/jfc4050/5b2a48692323560130a389bd86a431f1) shows a temporary workaround for loading Ergo for distributed training.

## Chat format

The chat format of Ergo is built from control tokens, such as `<ctrl0>` and `<ctrl100>`, that mark the start and end of a turn, of a reasoning block and of a tool call. The checkpoint ships a chat template that builds the prompt and a response template that parses the generated message.

```python
messages = [{"role": "user", "content": "What is the capital of France?"}]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)

output = model.generate(**inputs, max_new_tokens=512)
response_ids = output[0, inputs["input_ids"].shape[1] :]
message = tokenizer.parse_response(response_ids, prefix=inputs["input_ids"][0])
print(message.get("reasoning_content"), message.get("content"), message.get("tool_calls"))
```

Pass `enable_thinking=False` to make the model answer without a reasoning block, and `tools=[...]` to offer tools.

A control token written in a message is encoded as a control token. Pass `sanitize_control_tokens=True` to encode it as text when the messages come from an untrusted source.

The [TextGenerationPipeline](/docs/transformers/v5.25.0/en/main_classes/pipelines#transformers.TextGenerationPipeline) returns the same message for a chat.

```python
from transformers import pipeline

generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
message = generator(messages, max_new_tokens=512)[0]["generated_text"][-1]
```

## ErgoConfig[[transformers.ErgoConfig]]

#### transformers.ErgoConfig[[transformers.ErgoConfig]]

```python
transformers.ErgoConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vocab_size: int = 262144, hidden_size: int = 8192, num_hidden_layers: int = 64, num_attention_heads: int = 64, num_key_value_heads: int = 8, first_dense_intermediate_size: int = 32768, num_dense_blocks: int = 1, moe_intermediate_size: int = 4096, shared_intermediate_size: int = 8192, num_experts: int = 256, num_experts_per_tok: int = 8, moe_routed_scaling_factor: float = 2.8284271247461903, max_position_embeddings: int = 524288, initializer_range: float = 0.02, rms_norm_eps: float = 1e-12, use_cache: bool = True, rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = None, sliding_window: int = 512, global_attention_every_n_layers: int = 4, global_attention_scale: float | None = None, layer_types: list[str] | None = None, mlp_layer_types: list[str] | None = None, pad_token_id: int | None = 0, eos_token_id: int | list[int] | None = 1, bos_token_id: int | None = 2)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/configuration_ergo.py#L29)

**Parameters:**

vocab_size (`int`, *optional*, defaults to `262144`) : Vocabulary size of the model. Defines the number of different tokens that can be represented by the `input_ids`.

hidden_size (`int`, *optional*, defaults to `8192`) : Dimension of the hidden representations.

num_hidden_layers (`int`, *optional*, defaults to `64`) : Number of hidden layers in the Transformer decoder.

num_attention_heads (`int`, *optional*, defaults to `64`) : Number of attention heads for each attention layer in the Transformer decoder.

num_key_value_heads (`int`, *optional*, defaults to `8`) : This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the 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](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`.

first_dense_intermediate_size (`int`, *optional*, defaults to 32768) : Dimension of the MLP in the first `num_dense_blocks` layers, which have no experts.

num_dense_blocks (`int`, *optional*, defaults to 1) : Number of leading layers with a dense MLP instead of a mixture of experts.

moe_intermediate_size (`int`, *optional*, defaults to `4096`) : Intermediate size of the routed expert MLPs.

shared_intermediate_size (`int`, *optional*, defaults to 8192) : Dimension of the shared expert, which every token goes through on top of its routed experts.

num_experts (`int`, *optional*, defaults to `256`) : Number of routed experts in MoE layers. 

num_experts_per_tok (`int`, *optional*, defaults to `8`) : Number of experts to route each token to. This is the top-k value for the token-choice routing.

moe_routed_scaling_factor (`float`, *optional*, defaults to `8**0.5`) : Factor the routed experts' output is scaled by before the shared expert's output is added.

max_position_embeddings (`int`, *optional*, defaults to `524288`) : The maximum sequence length that this model might ever be used with.

initializer_range (`float`, *optional*, defaults to `0.02`) : The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

rms_norm_eps (`float`, *optional*, defaults to `1e-12`) : The epsilon used by the rms normalization layers.

use_cache (`bool`, *optional*, defaults to `True`) : Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True` or when the model is a decoder-only generative model.

rope_parameters (`Union[~modeling_rope_utils.RopeParameters, dict]`, *optional*) : Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`.

sliding_window (`int`, *optional*, defaults to `512`) : Sliding window attention window size. If `None`, no sliding window is applied.

global_attention_every_n_layers (`int`, *optional*, defaults to 4) : Every n-th layer attends to the whole context and uses no position embeddings. The other layers attend to the last `sliding_window` tokens and use rotary position embeddings.

global_attention_scale (`float`, *optional*) : Factor the attention logits of the layers that attend to the whole context are multiplied by. Checkpoints whose context was extended after pretraining set it.

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.

mlp_layer_types (`list[str]`, *optional*) : MLP type for each layer. Defaults to `"dense"` for the first `num_dense_blocks` layers and `"sparse"` thereafter.

pad_token_id (`int`, *optional*, defaults to `0`) : Token id used for padding in the vocabulary.

eos_token_id (`Union[int, list[int]]`, *optional*, defaults to `1`) : Token id used for end-of-stream in the vocabulary.

bos_token_id (`int`, *optional*, defaults to `2`) : Token id used for beginning-of-stream in the vocabulary.

This is the configuration class to store the configuration of a ErgoModel. It is used to instantiate a Ergo
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 [Amazon-FMR/Ergo](https://huggingface.co/Amazon-FMR/Ergo)

Configuration objects inherit from [PreTrainedConfig](/docs/transformers/v5.25.0/en/main_classes/configuration#transformers.PreTrainedConfig) and can be used to control the model outputs. Read the
documentation from [PreTrainedConfig](/docs/transformers/v5.25.0/en/main_classes/configuration#transformers.PreTrainedConfig) for more information.

Example:

```python
>>> from transformers import ErgoModel, ErgoConfig

>>> # Initializing an Ergo style configuration
>>> configuration = ErgoConfig()

>>> # Initializing a model from the Ergo style configuration
>>> model = ErgoModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

## ErgoTokenizer[[transformers.ErgoTokenizer]]

#### transformers.ErgoTokenizer[[transformers.ErgoTokenizer]]

```python
transformers.ErgoTokenizer(vocab: str | dict[str, int] | None = None, merges: str | list[str] | None = None, unk_token: str = '<unk>', bos_token: str = '<bos>', eos_token: str = '<ctrl100>', pad_token: str = '<pad>', add_bos_token: bool = False, add_eos_token: bool = False, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/tokenization_ergo.py#L28)

**Parameters:**

vocab (`str` or `dict[str, int]`, *optional*) : Custom vocabulary dict. If not provided, a minimal vocabulary is created from the special tokens.

merges (`str` or `list[str]`, *optional*) : Custom merges list.

unk_token (`str`, *optional*, defaults to `"<unk>"`) : The unknown token.

bos_token (`str`, *optional*, defaults to `"<bos>"`) : The beginning of sequence token. It is not added to chat prompts.

eos_token (`str`, *optional*, defaults to `"<ctrl100>"`) : The end of sequence token. It closes every turn of a chat, so generation stops on it.

pad_token (`str`, *optional*, defaults to `"<pad>"`) : The padding token.

add_bos_token (`bool`, *optional*, defaults to `False`) : Whether or not to add a `bos_token` at the start of sequences.

add_eos_token (`bool`, *optional*, defaults to `False`) : Whether or not to add an `eos_token` at the end of sequences.

Construct an Ergo tokenizer (backed by HuggingFace's tokenizers library).

This tokenizer uses a BPE model with byte fallback, no prefix space, and a normalizer that replaces spaces
with "▁".

#### convert_from_spm_model[[transformers.ErgoTokenizer.convert_from_spm_model]]

```python
convert_from_spm_model(vocab, **kwargs)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/tokenization_ergo.py#L101)

Builds the merges and the added tokens from a SentencePiece `tokenizer.model`, so that a checkpoint without
`tokenizer.json` encodes like SentencePiece.

A merge is every split of a piece into two pieces, ranked by the score of the merged piece. SentencePiece
never merges into control, unknown or byte pieces. Control and unknown pieces become special tokens.
User-defined pieces, which are runs of whitespace, become ordinary added tokens that are matched on the
normalized text.

## ErgoModel[[transformers.ErgoModel]]

#### transformers.ErgoModel[[transformers.ErgoModel]]

```python
transformers.ErgoModel(config: ErgoConfig)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/modeling_ergo.py#L546)

**Parameters:**

config ([ErgoConfig](/docs/transformers/v5.25.0/en/model_doc/ergo#transformers.ErgoConfig)) : 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()](/docs/transformers/v5.25.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

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

This model inherits from [PreTrainedModel](/docs/transformers/v5.25.0/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.ErgoModel.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, use_cache: bool | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/modeling_ergo.py#L562)

**Parameters:**

input_ids (`torch.LongTensor` of 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](/docs/transformers/v5.25.0/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.  [What are input IDs?](../glossary#input-ids)

attention_mask (`torch.Tensor` of 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**.  [What are attention masks?](../glossary#attention-mask)

position_ids (`torch.LongTensor` of 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]`.  [What are position IDs?](../glossary#position-ids)

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 the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/en/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/en/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

use_cache (`bool`, *optional*) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

**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 ([ErgoConfig](/docs/transformers/v5.25.0/en/model_doc/ergo#transformers.ErgoConfig)) and inputs.

The [ErgoModel](/docs/transformers/v5.25.0/en/model_doc/ergo#transformers.ErgoModel) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance 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.Tensor` of 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 when `use_cache=True` is passed or when `config.use_cache=True`) -- It is a [Cache](/docs/transformers/v5.25.0/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

  Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
  `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `cache`
  input) to speed up sequential decoding.
- **hidden_states** (`tuple(torch.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.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 when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.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 when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`) -- Tuple of `torch.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.

## ErgoForCausalLM[[transformers.ErgoForCausalLM]]

#### transformers.ErgoForCausalLM[[transformers.ErgoForCausalLM]]

```python
transformers.ErgoForCausalLM(config: ErgoConfig)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/modeling_ergo.py#L626)

**Parameters:**

config ([ErgoConfig](/docs/transformers/v5.25.0/en/model_doc/ergo#transformers.ErgoConfig)) : 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()](/docs/transformers/v5.25.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The Ergo Model for causal language modeling.

This model inherits from [PreTrainedModel](/docs/transformers/v5.25.0/en/main_classes/model#transformers.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](https://pytorch.org/docs/stable/nn.html#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[[transformers.ErgoForCausalLM.forward]]

```python
forward(input_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, position_ids: typing.Optional[torch.LongTensor] = None, cache: transformers.cache_utils.Cache | None = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: typing.Optional[torch.LongTensor] = None, use_cache: bool | None = None, logits_to_keep: typing.Union[int, torch.Tensor] = 0, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[Source](https://github.com/huggingface/transformers/blob/v5.25.0/src/transformers/models/ergo/modeling_ergo.py#L640)

**Parameters:**

input_ids (`torch.LongTensor` of 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](/docs/transformers/v5.25.0/en/model_doc/auto#transformers.AutoTokenizer). See [PreTrainedTokenizer.encode()](/docs/transformers/v5.25.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.encode) and [PreTrainedTokenizer.__call__()](/docs/transformers/v5.25.0/en/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__) for details.  [What are input IDs?](../glossary#input-ids)

attention_mask (`torch.Tensor` of 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**.  [What are attention masks?](../glossary#attention-mask)

position_ids (`torch.LongTensor` of 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]`.  [What are position IDs?](../glossary#position-ids)

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 the `cache` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.  Only [Cache](/docs/transformers/v5.25.0/en/internal/generation_utils#transformers.Cache) instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache). If no `cache` are passed, [DynamicCache](/docs/transformers/v5.25.0/en/internal/generation_utils#transformers.DynamicCache) will be initialized by default.  The model will output the same cache format that is fed as input.  If `cache` are used, the user is expected to input only unprocessed `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids` of shape `(batch_size, sequence_length)`.

inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) : Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.

labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*) : Labels for computing the causal language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring). Tokens with indices set to `-100` are 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 predict `logits[..., :-1, :]`. Pass unshifted labels matching `input_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_labels` keyword argument and they are used as is. `labels` must still be passed for the loss to be computed.

use_cache (`bool`, *optional*) : If set to `True`, `cache` key value states are returned and can be used to speed up decoding (see `cache`).

logits_to_keep (`Union[int, torch.Tensor]`, *optional*, defaults to `0`) : If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all `input_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 a `torch.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 ([ErgoConfig](/docs/transformers/v5.25.0/en/model_doc/ergo#transformers.ErgoConfig)) and inputs.

The [ErgoForCausalLM](/docs/transformers/v5.25.0/en/model_doc/ergo#transformers.ErgoForCausalLM) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance 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.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss (for next-token prediction).
- **logits** (`torch.Tensor` of 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 when `output_router_logits=True` is passed or when `config.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) return `None` here while still returning
  `router_logits`.
- **router_logits** (`tuple(torch.Tensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.output_router_logits=True`) -- Tuple of `torch.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 when `use_cache=True` is passed or when `config.use_cache=True`) -- It is a [Cache](/docs/transformers/v5.25.0/en/internal/generation_utils#transformers.Cache) instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

  Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
  `cache` input) to speed up sequential decoding.
- **hidden_states** (`tuple(torch.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.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 when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.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:

```python
>>> from transformers import AutoTokenizer, ErgoForCausalLM

>>> model = ErgoForCausalLM.from_pretrained("meta-ergo/Ergo-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-ergo/Ergo-2-7b-hf")

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

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```

