Transformers documentation
Ergo
This model was contributed to Hugging Face Transformers on 2026-12-01.
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.
The example below demonstrates how to generate text with the AutoModelForCausalLM class.
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 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.
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 returns the same message for a chat.
from transformers import pipeline
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
message = generator(messages, max_new_tokens=512)[0]["generated_text"][-1]ErgoConfig
class transformers.ErgoConfig
< 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 = 262144hidden_size: int = 8192num_hidden_layers: int = 64num_attention_heads: int = 64num_key_value_heads: int = 8first_dense_intermediate_size: int = 32768num_dense_blocks: int = 1moe_intermediate_size: int = 4096shared_intermediate_size: int = 8192num_experts: int = 256num_experts_per_tok: int = 8moe_routed_scaling_factor: float = 2.8284271247461903max_position_embeddings: int = 524288initializer_range: float = 0.02rms_norm_eps: float = 1e-12use_cache: bool = Truerope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonesliding_window: int = 512global_attention_every_n_layers: int = 4global_attention_scale: float | None = Nonelayer_types: list[str] | None = Nonemlp_layer_types: list[str] | None = Nonepad_token_id: int | None = 0eos_token_id: int | list[int] | None = 1bos_token_id: int | None = 2 )
Parameters
- vocab_size (
int, optional, defaults to262144) — Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - hidden_size (
int, optional, defaults to8192) — Dimension of the hidden representations. - num_hidden_layers (
int, optional, defaults to64) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to64) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to8) — 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. - first_dense_intermediate_size (
int, optional, defaults to 32768) — Dimension of the MLP in the firstnum_dense_blockslayers, 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 to4096) — 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 to256) — Number of routed experts in MoE layers. - num_experts_per_tok (
int, optional, defaults to8) — 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 to8**0.5) — Factor the routed experts’ output is scaled by before the shared expert’s output is added. - max_position_embeddings (
int, optional, defaults to524288) — 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-12) — 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. - 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 to512) — Sliding window attention window size. IfNone, 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 lastsliding_windowtokens 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 firstnum_dense_blockslayers and"sparse"thereafter. - pad_token_id (
int, optional, defaults to0) — Token id used for padding in the vocabulary. - eos_token_id (
Union[int, list[int]], optional, defaults to1) — Token id used for end-of-stream in the vocabulary. - bos_token_id (
int, optional, defaults to2) — 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
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Example:
>>> 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.configErgoTokenizer
class transformers.ErgoTokenizer
< source >( vocab: str | dict[str, int] | None = Nonemerges: str | list[str] | None = Noneunk_token: str = '<unk>'bos_token: str = '<bos>'eos_token: str = '<ctrl100>'pad_token: str = '<pad>'add_bos_token: bool = Falseadd_eos_token: bool = False**kwargs )
Parameters
- vocab (
strordict[str, int], optional) — Custom vocabulary dict. If not provided, a minimal vocabulary is created from the special tokens. - merges (
strorlist[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 toFalse) — Whether or not to add abos_tokenat the start of sequences. - add_eos_token (
bool, optional, defaults toFalse) — Whether or not to add aneos_tokenat 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 ”▁“.
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
class transformers.ErgoModel
< source >( config: ErgoConfig )
Parameters
- config (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() 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. 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] = 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.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. - 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 (ErgoConfig) and inputs.
The 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
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.
ErgoForCausalLM
class transformers.ErgoForCausalLM
< source >( config: ErgoConfig )
Parameters
- config (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() method to load the model weights.
The Ergo 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 (ErgoConfig) and inputs.
The 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
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, 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."