Movatterモバイル変換


[0]ホーム

URL:


Hugging Face's logoHugging Face

Transformers documentation

OLMoE

Transformers

You are viewingmain version, which requiresinstallation from source. If you'd likeregular pip install, checkout the latest stable version (v4.57.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

Collaborate on models, datasets and Spaces
Faster examples with accelerated inference
Switch between documentation themes

to get started

This model was released on 2024-09-03 and added to Hugging Face Transformers on 2024-09-03.

PyTorchFlashAttentionSDPA

OLMoE

OLMoE is a sparse Mixture-of-Experts (MoE) language model with 7B parameters but only 1B parameters are used per input token. It has similar inference costs as dense models but trains ~3x faster. OLMoE uses fine-grained routing with 64 small experts in each layer and uses a dropless token-based routing algorithm.

You can find all the original OLMoE checkpoints under theOLMoE collection.

This model was contributed byMuennighoff.

Click on the OLMoE models in the right sidebar for more examples of how to apply OLMoE to different language tasks.

The example below demonstrates how to generate text withPipeline or theAutoModel class.

<hfoptions id="usage"><hfoption id="Pipeline">
import torchfrom transformersimport pipelinepipe = pipeline(    task="text-generation",    model="allenai/OLMoE-1B-7B-0125",    dtype=torch.float16,    device=0,)result = pipe("Dionysus is the god of")print(result)
</hfoption><hfoption id="AutoModel">
import torchfrom transformersimport AutoModelForCausalLM, AutoTokenizerfrom accelerateimport Acceleratordevice = Accelerator().devicemodel = AutoModelForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924", attn_implementation="sdpa", dtype="auto", device_map="auto").to(device)tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")inputs = tokenizer("Bitcoin is", return_tensors="pt")inputs = {k: v.to(device)for k, vin inputs.items()}output = model.generate(**inputs, max_length=64)print(tokenizer.decode(output[0]))

Quantization

Quantization reduces the memory burden of large models by representing the weights in a lower precision. Refer to theQuantization overview for more available quantization backends.The example below usesbitsandbytes to only quantize the weights to 4-bits.

import torchfrom transformersimport AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfigfrom accelerateimport Acceleratordevice = Accelerator().devicequantization_config = BitsAndBytesConfig(   load_in_4bit=True,   bnb_4bit_compute_dtype=torch.float16,   bnb_4bit_use_double_quant=True,   bnb_4bit_quant_type="nf4")model = AutoModelForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924", attn_implementation="sdpa", dtype="auto", device_map="auto", quantization_config=quantization_config).to(device)tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")inputs = tokenizer("Bitcoin is", return_tensors="pt")inputs = {k: v.to(device)for k, vin inputs.items()}output = model.generate(**inputs, max_length=64)print(tokenizer.decode(output[0]))

OlmoeConfig

classtransformers.OlmoeConfig

<source>

(vocab_size: typing.Optional[int] = 50304hidden_size: typing.Optional[int] = 2048intermediate_size: typing.Optional[int] = 2048num_hidden_layers: typing.Optional[int] = 16num_attention_heads: typing.Optional[int] = 16num_key_value_heads: typing.Optional[int] = Nonehidden_act: typing.Optional[str] = 'silu'max_position_embeddings: typing.Optional[int] = 4096initializer_range: typing.Optional[float] = 0.02rms_norm_eps: typing.Optional[int] = 1e-05use_cache: typing.Optional[bool] = Truepad_token_id: typing.Optional[int] = 1bos_token_id: typing.Optional[int] = Noneeos_token_id: typing.Optional[int] = 50279tie_word_embeddings: typing.Optional[int] = Falserope_parameters: typing.Union[transformers.modeling_rope_utils.RopeParameters, dict[str, transformers.modeling_rope_utils.RopeParameters], NoneType] = Noneattention_bias: typing.Optional[bool] = Falseattention_dropout: typing.Optional[float] = 0.0clip_qkv: typing.Optional[bool] = Nonenum_experts_per_tok: typing.Optional[int] = 8num_experts: typing.Optional[int] = 64output_router_logits: typing.Optional[bool] = Falserouter_aux_loss_coef: typing.Optional[float] = 0.01norm_topk_prob: typing.Optional[bool] = False**kwargs)

Parameters

  • vocab_size (int,optional, defaults to 50304) —Vocabulary size of the OLMoE model. Defines the number of different tokens that can be represented by theinputs_ids passed when callingOlmoeModel
  • hidden_size (int,optional, defaults to 2048) —Dimension of the hidden representations.
  • intermediate_size (int,optional, defaults to 2048) —Dimension of the MLP representations.
  • num_hidden_layers (int,optional, defaults to 16) —Number of hidden layers in the Transformer decoder.
  • num_attention_heads (int,optional, defaults to 16) —Number of attention heads for each attention layer in the Transformer decoder.
  • num_key_value_heads (int,optional) —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=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. Whenconverting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructedby meanpooling all the original heads within that group. For more details, check outthispaper. If it is not specified, will default tonum_attention_heads.
  • hidden_act (str orfunction,optional, defaults to"silu") —The non-linear activation function (function or string) in the decoder.
  • max_position_embeddings (int,optional, defaults to 4096) —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-05) —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). Onlyrelevant ifconfig.is_decoder=True.
  • pad_token_id (int,optional, defaults to 1) —Padding token id.
  • bos_token_id (int,optional) —Beginning of stream token id.
  • eos_token_id (int,optional, defaults to 50279) —End of stream token id.
  • tie_word_embeddings (bool,optional, defaults toFalse) —Whether to tie weight embeddings
  • rope_parameters (RopeParameters,optional) —Dictionary containing the configuration parameters for the RoPE embeddings. The dictionaty should containa value forrope_theta and optionally parameters used for scaling in case you want to use RoPEwith longermax_position_embeddings.
  • attention_bias (bool, defaults toFalse,optional, defaults toFalse) —Whether to use a bias in the query, key, value and output projection layers during self-attention.
  • attention_dropout (float,optional, defaults to 0.0) —The dropout ratio for the attention probabilities.
  • clip_qkv (float,optional) —If notNone, elements of query, key and value attention states are clipped so that theirabsolute value does not exceed this value.
  • num_experts_per_tok (int,optional, defaults to 8) —Number of selected experts.
  • num_experts (int,optional, defaults to 64) —Number of routed experts.
  • output_router_logits (bool,optional, defaults toFalse) —Whether or not the router logits should be returned by the model. Enabling this will alsoallow the model to output the auxiliary loss, including load balancing loss and router z-loss.
  • router_aux_loss_coef (float,optional, defaults to 0.01) —The aux loss factor for the total loss.
  • norm_topk_prob (bool,optional, defaults toFalse) —Whether to normalize the topk probabilities.

This is the configuration class to store the configuration of aOlmoeModel. It is used to instantiate an OLMoEmodel according to the specified arguments, defining the model architecture. Instantiating a configuration with thedefaults will yield a similar configuration to that of theallenai/OLMoE-1B-7B-0924.

Configuration objects inherit fromPreTrainedConfig and can be used to control the model outputs. Read thedocumentation fromPreTrainedConfig for more information.

>>>from transformersimport OlmoeModel, OlmoeConfig>>># Initializing a OLMoE 7B A1B style configuration>>>configuration = OlmoeConfig()>>># Initializing a model from the OLMoE 7B A1B style configuration>>>model = OlmoeModel(configuration)>>># Accessing the model configuration>>>configuration = model.config

OlmoeModel

classtransformers.OlmoeModel

<source>

(config: OlmoeConfig)

Parameters

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

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

This model inherits fromPreTrainedModel. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)

This model is also a PyTorchtorch.nn.Module subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.

forward

<source>

(input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[transformers.cache_utils.Cache] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = None**kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs])transformers.modeling_outputs.MoeModelOutputWithPast ortuple(torch.FloatTensor)

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 usingAutoTokenizer. SeePreTrainedTokenizer.encode() andPreTrainedTokenizer.call() for details.

    What are 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 arenot masked,
    • 0 for tokens that aremasked.

    What are attention masks?

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

  • past_key_values (~cache_utils.Cache,optional) —Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=True orconfig.use_cache=True.

    OnlyCache instance is allowed as input, see ourkv cache guide.If nopast_key_values are passed,DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    Ifpast_key_values are used, the user is expected to input only unprocessedinput_ids (those that don’thave 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.FloatTensor of shape(batch_size, sequence_length, hidden_size),optional) —Optionally, instead of passinginput_ids you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convertinput_ids indices into associated vectors than themodel’s internal embedding lookup matrix.
  • use_cache (bool,optional) —If set toTrue,past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).
  • cache_position (torch.LongTensor of shape(sequence_length),optional) —Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids,this tensor is not affected by padding. It is used to update the cache in the correct position and to inferthe complete sequence length.

Returns

transformers.modeling_outputs.MoeModelOutputWithPast ortuple(torch.FloatTensor)

Atransformers.modeling_outputs.MoeModelOutputWithPast or a tuple oftorch.FloatTensor (ifreturn_dict=False is passed or whenconfig.return_dict=False) comprising variouselements depending on the configuration (OlmoeConfig) and inputs.

  • last_hidden_state (torch.FloatTensor of shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.

  • past_key_values (Cache,optional, returned whenuse_cache=True is passed or whenconfig.use_cache=True) — It is aCache instance. For more details, see ourkv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally ifconfig.is_encoder_decoder=True in the cross-attention blocks) that can be used (seepast_key_valuesinput) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor),optional, returned whenoutput_hidden_states=True is passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor (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.FloatTensor),optional, returned whenoutput_attentions=True is passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor (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-attentionheads.

  • router_logits (tuple(torch.FloatTensor),optional, returned whenoutput_router_probs=True andconfig.add_router_probs=True is passed or whenconfig.output_router_probs=True) — Tuple oftorch.FloatTensor (one for each layer) of shape(batch_size, sequence_length, num_experts).

    Raw router logtis (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliaryloss for Mixture of Experts models.

TheOlmoeModel forward method, overrides the__call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call theModuleinstance afterwards instead of this since the former takes care of running the pre and post processing steps whilethe latter silently ignores them.

OlmoeForCausalLM

classtransformers.OlmoeForCausalLM

<source>

(config)

Parameters

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

The Olmoe Model for causal language modeling.

This model inherits fromPreTrainedModel. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)

This model is also a PyTorchtorch.nn.Module subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.

forward

<source>

(input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: typing.Optional[transformers.cache_utils.Cache] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_router_logits: typing.Optional[bool] = Nonecache_position: typing.Optional[torch.LongTensor] = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs])transformers.modeling_outputs.MoeCausalLMOutputWithPast ortuple(torch.FloatTensor)

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 usingAutoTokenizer. SeePreTrainedTokenizer.encode() andPreTrainedTokenizer.call() for details.

    What are 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 arenot masked,
    • 0 for tokens that aremasked.

    What are attention masks?

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

  • past_key_values (~cache_utils.Cache,optional) —Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=True orconfig.use_cache=True.

    OnlyCache instance is allowed as input, see ourkv cache guide.If nopast_key_values are passed,DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    Ifpast_key_values are used, the user is expected to input only unprocessedinput_ids (those that don’thave 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.FloatTensor of shape(batch_size, sequence_length, hidden_size),optional) —Optionally, instead of passinginput_ids you can choose to directly pass an embedded representation. Thisis useful if you want more control over how to convertinput_ids indices into associated vectors than themodel’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape(batch_size, sequence_length),optional) —Labels for computing the masked language modeling loss. Indices should either be in[0, ..., config.vocab_size] or -100 (seeinput_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].
  • use_cache (bool,optional) —If set toTrue,past_key_values key value states are returned and can be used to speed up decoding (seepast_key_values).
  • output_router_logits (bool,optional) —Whether or not to return the logits of all the routers. They are useful for computing the router loss, andshould not be returned during inference.
  • cache_position (torch.LongTensor of shape(sequence_length),optional) —Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_ids,this tensor is not affected by padding. It is used to update the cache in the correct position and to inferthe complete sequence length.
  • logits_to_keep (Union[int, torch.Tensor], defaults to0) —If anint, compute logits for the lastlogits_to_keep tokens. If0, calculate logits for allinput_ids (special case). Only last token logits are needed for generation, and calculating them only for thattoken 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

transformers.modeling_outputs.MoeCausalLMOutputWithPast ortuple(torch.FloatTensor)

Atransformers.modeling_outputs.MoeCausalLMOutputWithPast or a tuple oftorch.FloatTensor (ifreturn_dict=False is passed or whenconfig.return_dict=False) comprising variouselements depending on the configuration (OlmoeConfig) and inputs.

  • loss (torch.FloatTensor of shape(1,),optional, returned whenlabels is provided) — Language modeling loss (for next-token prediction).

  • logits (torch.FloatTensor 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.FloatTensor,optional, returned whenlabels is provided) — aux_loss for the sparse modules.

  • router_logits (tuple(torch.FloatTensor),optional, returned whenoutput_router_probs=True andconfig.add_router_probs=True is passed or whenconfig.output_router_probs=True) — Tuple oftorch.FloatTensor (one for each layer) of shape(batch_size, sequence_length, num_experts).

    Raw router logtis (post-softmax) that are computed by MoE routers, these terms are used to compute the auxiliaryloss for Mixture of Experts models.

  • past_key_values (Cache,optional, returned whenuse_cache=True is passed or whenconfig.use_cache=True) — It is aCache instance. For more details, see ourkv cache guide.

    Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (seepast_key_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor),optional, returned whenoutput_hidden_states=True is passed or whenconfig.output_hidden_states=True) — Tuple oftorch.FloatTensor (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.FloatTensor),optional, returned whenoutput_attentions=True is passed or whenconfig.output_attentions=True) — Tuple oftorch.FloatTensor (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-attentionheads.

TheOlmoeForCausalLM forward method, overrides the__call__ special method.

Although the recipe for forward pass needs to be defined within this function, one should call theModuleinstance afterwards instead of this since the former takes care of running the pre and post processing steps whilethe latter silently ignores them.

Example:

>>>from transformersimport AutoTokenizer, OlmoeForCausalLM>>>model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924")>>>tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")>>>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 sure if you’re conscious of this, but I’m'
Update on GitHub


[8]ページ先頭

©2009-2025 Movatter.jp