amachine.am_transformers.am_control_model_exp
38class ControlGmhConfig(GraniteMoeHybridConfig): 39 40 model_type = my_model_type 41 42 def __init__( 43 self, 44 control_params = None, 45 **kwargs 46 ) : 47 super().__init__(**kwargs) 48 49 if control_params is None : 50 control_params = {} 51 52 control_params[ "add_control" ] = control_params.get( "add_control", True ) 53 control_params[ "override_control_residual" ] = control_params.get( "override_control_residual", True ) 54 control_params[ "bypass_control_output" ] = control_params.get( "bypass_control_output", False ) 55 control_params[ "add_control_loss" ] = control_params.get( "add_control_loss", True ) 56 control_params[ "control_loss_skip_tokens" ] = control_params.get( "control_loss_skip_tokens", 0 ) 57 control_params[ "control_loss_schedule_tokens" ] = control_params.get( "control_loss_schedule_tokens", 183_500_800 ) 58 control_params[ "alpha_c" ] = control_params.get( "alpha_c", 0.2 ) 59 control_params[ "alpha_w" ] = control_params.get( "alpha_w", 2.0 ) 60 control_params[ "beta_div" ] = control_params.get( "beta_div", 0.2 ) 61 control_params[ "covariance_weight" ] = control_params.get( "covariance_weight", 1.0 ) 62 63 assert isinstance( self.layer_types , list ) 64 65 cl = control_params.get( "control_layer", len( self.layer_types ) // 2 + 1 ) 66 control_params[ "control_layer" ] = cl 67 68 assert isinstance( cl, int ) 69 assert cl > 0 and cl < len( self.layer_types ) - 1 70 71 self.control_params = control_params
42 def __init__( 43 self, 44 control_params = None, 45 **kwargs 46 ) : 47 super().__init__(**kwargs) 48 49 if control_params is None : 50 control_params = {} 51 52 control_params[ "add_control" ] = control_params.get( "add_control", True ) 53 control_params[ "override_control_residual" ] = control_params.get( "override_control_residual", True ) 54 control_params[ "bypass_control_output" ] = control_params.get( "bypass_control_output", False ) 55 control_params[ "add_control_loss" ] = control_params.get( "add_control_loss", True ) 56 control_params[ "control_loss_skip_tokens" ] = control_params.get( "control_loss_skip_tokens", 0 ) 57 control_params[ "control_loss_schedule_tokens" ] = control_params.get( "control_loss_schedule_tokens", 183_500_800 ) 58 control_params[ "alpha_c" ] = control_params.get( "alpha_c", 0.2 ) 59 control_params[ "alpha_w" ] = control_params.get( "alpha_w", 2.0 ) 60 control_params[ "beta_div" ] = control_params.get( "beta_div", 0.2 ) 61 control_params[ "covariance_weight" ] = control_params.get( "covariance_weight", 1.0 ) 62 63 assert isinstance( self.layer_types , list ) 64 65 cl = control_params.get( "control_layer", len( self.layer_types ) // 2 + 1 ) 66 control_params[ "control_layer" ] = cl 67 68 assert isinstance( cl, int ) 69 assert cl > 0 and cl < len( self.layer_types ) - 1 70 71 self.control_params = control_params
Arguments:
- vocab_size (
int, optional, defaults to32000): Vocabulary size of the model. Defines the number of different tokens that can be represented by theinput_ids. - hidden_size (
int, optional, defaults to4096): Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to11008): Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to32): Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to32): 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=1the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default tonum_attention_heads. - hidden_act (
str, optional, defaults tosilu): The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - max_position_embeddings (
int, optional, defaults to2048): The maximum sequence length that this model might ever be used with. - initializer_range (
float, optional, defaults to0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - rms_norm_eps (
float, optional, defaults to1e-06): The epsilon used by the rms normalization layers. - use_cache (
bool, optional, defaults toTrue): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant ifconfig.is_decoder=Trueor when the model is a decoder-only generative model. - pad_token_id (
int, optional): Token id used for padding in the vocabulary. - bos_token_id (
int, optional, defaults to1): Token id used for beginning-of-stream in the vocabulary. - eos_token_id (
Union[int, list[int]], optional, defaults to2): Token id used for end-of-stream in the vocabulary. - tie_word_embeddings (
bool, optional, defaults toFalse): Whether to tie weight embeddings according to model'stied_weights_keysmapping. - rope_parameters (
Union[~modeling_rope_utils.RopeParameters, dict], optional): Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value forrope_thetaand optionally parameters used for scaling in case you want to use RoPE with longermax_position_embeddings. - attention_bias (
bool, optional, defaults toFalse): Whether to use a bias in the query, key, value and output projection layers during self-attention. - attention_dropout (
Union[float, int], optional, defaults to0.0): The dropout ratio for the attention probabilities. - embedding_multiplier (
float, optional, defaults to 1.0): embedding multiplier. - logits_scaling (
float, optional, defaults to 1.0): divisor for output logits. - residual_multiplier (
float, optional, defaults to 1.0): residual multiplier. - attention_multiplier (
float, optional, defaults to 1.0): attention multiplier. - num_local_experts (
int, optional, defaults to8): Number of local experts on each device.num_expertsshould be divisible bynum_local_experts. - num_experts_per_tok (
int, optional, defaults to2): Number of experts to route each token to. This is the top-k value for the token-choice routing. - output_router_logits (
bool, optional, defaults toFalse): Whether or not the router logits should be returned by the model. Enabling this will also allow the model to output the auxiliary loss, including load balancing loss and router z-loss. - router_aux_loss_coef (
float, optional, defaults to0.001): Auxiliary load balancing loss coefficient. Used to penalize uneven expert routing in MoE models. - shared_intermediate_size (
int, optional, defaults to 1024): intermediate size for shared experts. - position_embedding_type (
str, optional): Positional embedding type to be used; defaults to None. Allowed options:[None, "rope"] - 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. - mamba_n_heads (
int, optional, defaults to128): The number of mamba heads used in the v2 implementation. - mamba_n_groups (
int, optional, defaults to1): The number of the mamba groups used in the v2 implementation. - mamba_d_state (
int, optional, defaults to256): Size of the SSM state (latent state dimension) in the Mamba layers. - mamba_d_head (
Union[int, str], optional, defaults toauto): Head embedding dimension size - mamba_d_conv (
int, optional, defaults to4): The size of the mamba convolution kernel - mamba_expand (
int, optional, defaults to2): Expanding factor (relative to hidden_size) used to determine the mamba intermediate size - mamba_chunk_size (
int, optional, defaults to256): The chunks in which to break the sequence when doing prefill/training - mamba_conv_bias (
bool, optional, defaults toTrue): Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block. - mamba_proj_bias (
bool, optional, defaults toFalse): Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block - time_step_min (
float, optional, defaults to0.001): Minimumtime_stepused to bounddt_proj.bias. - time_step_max (
float, optional, defaults to0.1): Maximumtime_stepused to bounddt_proj.bias. - time_step_limit (
Union[list[float, float], tuple[float, float]], optional, defaults to(0.0, inf)): Accepted range of time step values for clamping.
Example:
>>> from transformers import GraniteMoeHybridModel, GraniteMoeHybridConfig
>>> # Initializing a GraniteMoeHybrid config
>>> configuration = GraniteMoeHybridConfig()
>>> # Accessing the model configuration
>>> configuration = model.config
303class ControlGmhForCausalLM(GraniteMoeHybridForCausalLM): 304 305 config_class = ControlGmhConfig 306 _no_split_modules = ["ControlGmhDecoderLayer"] 307 308 def __init__(self, config): 309 310 super().__init__(config) 311 312 self.model = ControlGmhModel(config) 313 self.register_buffer("global_token_counter", torch.tensor(0, dtype=torch.long)) 314 self.post_init() 315 316 @can_return_tuple 317 def forward( 318 self, 319 input_ids: torch.LongTensor | None = None, 320 attention_mask: torch.Tensor | None = None, 321 position_ids: torch.LongTensor | None = None, 322 past_key_values: Cache | None = None, 323 inputs_embeds: torch.FloatTensor | None = None, 324 labels: torch.LongTensor | None = None, 325 output_router_logits: bool | None = None, 326 logits_to_keep: int | torch.Tensor = 0, 327 **kwargs, 328 ) -> tuple | MoeCausalLMOutputWithPast: 329 330 output_router_logits = ( 331 output_router_logits if output_router_logits is not None else self.config.output_router_logits 332 ) 333 # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) 334 outputs = self.model( 335 input_ids=input_ids, 336 attention_mask=attention_mask, 337 position_ids=position_ids, 338 past_key_values=past_key_values, 339 inputs_embeds=inputs_embeds, 340 **kwargs, 341 ) 342 343 # Only compute necessary logits 344 hidden_states = outputs.last_hidden_state 345 slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep 346 logits = self.lm_head(hidden_states[:, slice_indices, :]) 347 logits = logits / self.config.logits_scaling 348 349 loss = None 350 if labels is not None: 351 # Flatten the tokens 352 loss = self.loss_function( 353 logits, 354 labels, 355 vocab_size=self.config.vocab_size, 356 **kwargs, 357 ) 358 359 aux_loss = None 360 if output_router_logits: 361 aux_loss = load_balancing_loss_func( 362 outputs.router_logits, 363 self.num_experts, 364 self.num_experts_per_tok, 365 attention_mask, 366 ) 367 if labels is not None: 368 loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device 369 370 ############################################################# 371 # Custom Information-Theoretic Synergy Loss 372 ############################################################# 373 374 main_loss = loss 375 metrics = {} 376 377 # Only execute if we have a valid main loss (training mode) and the required control outputs 378 if main_loss is not None and hasattr(outputs, "control_output") and hasattr(outputs, "without_control"): 379 380 entropy_chunk_size = kwargs.get( "entropy_chunk_size", 512 ) 381 382 X_c = outputs.control_output[:, slice_indices, :] 383 X_w = outputs.without_control[:, slice_indices, :] 384 385 tokens_seen = self.global_token_counter 386 self.global_token_counter += ( X_c.shape[ 0 ]*X_c.shape[ 1 ] ) 387 388 if X_c.ndim != 3 or X_w.ndim != 3: 389 raise ValueError("Expected X_c and X_w to have shape (B, S, D)") 390 if X_c.shape != X_w.shape: 391 raise ValueError(f"X_c and X_w must have matching shapes, got {X_c.shape} and {X_w.shape}") 392 393 X_c = X_c.reshape(-1, X_c.shape[-1]) 394 X_w = X_w.reshape(-1, X_w.shape[-1]) 395 396 if X_c.shape[0] > 0: 397 398 #----------------------------------------------------------------------- 399 400 add_control_loss = self.config.control_params.get( "add_control_loss" ) 401 control_loss_schedule_tokens = self.config.control_params.get( "control_loss_schedule_tokens" ) 402 control_loss_skip_tokens = self.config.control_params.get( "control_loss_skip_tokens" ) 403 404 assert isinstance( add_control_loss, bool ) 405 assert isinstance( control_loss_schedule_tokens, int ) 406 assert isinstance( control_loss_skip_tokens, int ) 407 408 alpha_c = self.config.control_params.get( "alpha_c" ) 409 alpha_w = self.config.control_params.get( "alpha_w" ) 410 beta_div = self.config.control_params.get( "beta_div" ) 411 412 assert isinstance( alpha_c, float ) 413 assert isinstance( alpha_w, float ) 414 assert isinstance( beta_div, float ) 415 416 covariance_weight = self.config.control_params.get( "covariance_weight" ) 417 418 assert isinstance( covariance_weight, float ) 419 420 #---------------------------------------------------------------------------- 421 422 logits_scaling = float(self.config.logits_scaling) 423 424 if logits_scaling <= 0: 425 raise ValueError("logits_scaling must be positive") 426 427 # ------------------------------------------------------------------ 428 # Predictive-information proxy 429 # ------------------------------------------------------------------ 430 431 loss_info_c = normalized_lm_head_entropy_deficit( 432 hidden=X_c, 433 lm_head=self.lm_head, 434 logits_scaling=logits_scaling, 435 use_checkpoint=True, 436 chunk_size=128, 437 include_bias=False, 438 non_uniformity_weight=1.0 439 ) 440 441 loss_info_w = normalized_lm_head_entropy_deficit( 442 hidden=X_w, 443 lm_head=self.lm_head, 444 logits_scaling=logits_scaling, 445 use_checkpoint=True, 446 chunk_size=128, 447 include_bias=False, 448 non_uniformity_weight=1.0 449 ) 450 451 # ------------------------------------------------------------------ 452 # VICReg-style non-collapse and feature decorrelation 453 # ------------------------------------------------------------------ 454 455 loss_covariance_c = covariance_loss(X_c) * ( X_c.shape[-1] / 4.0 ) 456 loss_div_c = covariance_weight * loss_covariance_c 457 458 # ------------------------------------------------------------------ 459 # Schedule and aggregation 460 # ------------------------------------------------------------------ 461 462 schedule_position = max( 0, tokens_seen - control_loss_skip_tokens ) / control_loss_schedule_tokens 463 464 schedule_c = get_sigmoid_weight( 465 r=schedule_position, 466 midpoint=0.5, 467 steepness=12.0, 468 ) 469 470 weighted_ctrl = alpha_c * loss_info_c + alpha_w * loss_info_w + beta_div * loss_div_c 471 loss_ctrl_scheduled = schedule_c * weighted_ctrl 472 473 if add_control_loss : 474 loss = main_loss + schedule_c * weighted_ctrl 475 476 metrics = { 477 "main_loss" : main_loss.detach(), 478 "loss_info_c": loss_info_c.detach(), 479 "loss_info_w": loss_info_w.detach(), 480 "loss_covariance_c": loss_covariance_c.detach(), 481 "loss_diversity_c": loss_div_c.detach(), 482 "loss_ctrl_weighted": weighted_ctrl.detach(), 483 "loss_ctrl_scheduled": loss_ctrl_scheduled.detach(), 484 "train_synergy_schedule": schedule_c, 485 } 486 487 ############################################################ 488 489 return ControlCausalLMOutput( 490 loss=loss, 491 aux_loss=aux_loss, 492 logits=logits, 493 past_key_values=outputs.past_key_values, 494 hidden_states=outputs.hidden_states, 495 attentions=outputs.attentions, 496 router_logits=outputs.router_logits, 497 **metrics 498 )
The Granitemoehybrid 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.
Arguments:
- config ([
GraniteMoeHybridConfig]): 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 [~PreTrainedModel.from_pretrained] method to load the model weights.
308 def __init__(self, config): 309 310 super().__init__(config) 311 312 self.model = ControlGmhModel(config) 313 self.register_buffer("global_token_counter", torch.tensor(0, dtype=torch.long)) 314 self.post_init()
Args:
config ([GraniteMoeHybridConfig]):
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
[~PreTrainedModel.from_pretrained] method to load the model weights.
316 @can_return_tuple 317 def forward( 318 self, 319 input_ids: torch.LongTensor | None = None, 320 attention_mask: torch.Tensor | None = None, 321 position_ids: torch.LongTensor | None = None, 322 past_key_values: Cache | None = None, 323 inputs_embeds: torch.FloatTensor | None = None, 324 labels: torch.LongTensor | None = None, 325 output_router_logits: bool | None = None, 326 logits_to_keep: int | torch.Tensor = 0, 327 **kwargs, 328 ) -> tuple | MoeCausalLMOutputWithPast: 329 330 output_router_logits = ( 331 output_router_logits if output_router_logits is not None else self.config.output_router_logits 332 ) 333 # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) 334 outputs = self.model( 335 input_ids=input_ids, 336 attention_mask=attention_mask, 337 position_ids=position_ids, 338 past_key_values=past_key_values, 339 inputs_embeds=inputs_embeds, 340 **kwargs, 341 ) 342 343 # Only compute necessary logits 344 hidden_states = outputs.last_hidden_state 345 slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep 346 logits = self.lm_head(hidden_states[:, slice_indices, :]) 347 logits = logits / self.config.logits_scaling 348 349 loss = None 350 if labels is not None: 351 # Flatten the tokens 352 loss = self.loss_function( 353 logits, 354 labels, 355 vocab_size=self.config.vocab_size, 356 **kwargs, 357 ) 358 359 aux_loss = None 360 if output_router_logits: 361 aux_loss = load_balancing_loss_func( 362 outputs.router_logits, 363 self.num_experts, 364 self.num_experts_per_tok, 365 attention_mask, 366 ) 367 if labels is not None: 368 loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device 369 370 ############################################################# 371 # Custom Information-Theoretic Synergy Loss 372 ############################################################# 373 374 main_loss = loss 375 metrics = {} 376 377 # Only execute if we have a valid main loss (training mode) and the required control outputs 378 if main_loss is not None and hasattr(outputs, "control_output") and hasattr(outputs, "without_control"): 379 380 entropy_chunk_size = kwargs.get( "entropy_chunk_size", 512 ) 381 382 X_c = outputs.control_output[:, slice_indices, :] 383 X_w = outputs.without_control[:, slice_indices, :] 384 385 tokens_seen = self.global_token_counter 386 self.global_token_counter += ( X_c.shape[ 0 ]*X_c.shape[ 1 ] ) 387 388 if X_c.ndim != 3 or X_w.ndim != 3: 389 raise ValueError("Expected X_c and X_w to have shape (B, S, D)") 390 if X_c.shape != X_w.shape: 391 raise ValueError(f"X_c and X_w must have matching shapes, got {X_c.shape} and {X_w.shape}") 392 393 X_c = X_c.reshape(-1, X_c.shape[-1]) 394 X_w = X_w.reshape(-1, X_w.shape[-1]) 395 396 if X_c.shape[0] > 0: 397 398 #----------------------------------------------------------------------- 399 400 add_control_loss = self.config.control_params.get( "add_control_loss" ) 401 control_loss_schedule_tokens = self.config.control_params.get( "control_loss_schedule_tokens" ) 402 control_loss_skip_tokens = self.config.control_params.get( "control_loss_skip_tokens" ) 403 404 assert isinstance( add_control_loss, bool ) 405 assert isinstance( control_loss_schedule_tokens, int ) 406 assert isinstance( control_loss_skip_tokens, int ) 407 408 alpha_c = self.config.control_params.get( "alpha_c" ) 409 alpha_w = self.config.control_params.get( "alpha_w" ) 410 beta_div = self.config.control_params.get( "beta_div" ) 411 412 assert isinstance( alpha_c, float ) 413 assert isinstance( alpha_w, float ) 414 assert isinstance( beta_div, float ) 415 416 covariance_weight = self.config.control_params.get( "covariance_weight" ) 417 418 assert isinstance( covariance_weight, float ) 419 420 #---------------------------------------------------------------------------- 421 422 logits_scaling = float(self.config.logits_scaling) 423 424 if logits_scaling <= 0: 425 raise ValueError("logits_scaling must be positive") 426 427 # ------------------------------------------------------------------ 428 # Predictive-information proxy 429 # ------------------------------------------------------------------ 430 431 loss_info_c = normalized_lm_head_entropy_deficit( 432 hidden=X_c, 433 lm_head=self.lm_head, 434 logits_scaling=logits_scaling, 435 use_checkpoint=True, 436 chunk_size=128, 437 include_bias=False, 438 non_uniformity_weight=1.0 439 ) 440 441 loss_info_w = normalized_lm_head_entropy_deficit( 442 hidden=X_w, 443 lm_head=self.lm_head, 444 logits_scaling=logits_scaling, 445 use_checkpoint=True, 446 chunk_size=128, 447 include_bias=False, 448 non_uniformity_weight=1.0 449 ) 450 451 # ------------------------------------------------------------------ 452 # VICReg-style non-collapse and feature decorrelation 453 # ------------------------------------------------------------------ 454 455 loss_covariance_c = covariance_loss(X_c) * ( X_c.shape[-1] / 4.0 ) 456 loss_div_c = covariance_weight * loss_covariance_c 457 458 # ------------------------------------------------------------------ 459 # Schedule and aggregation 460 # ------------------------------------------------------------------ 461 462 schedule_position = max( 0, tokens_seen - control_loss_skip_tokens ) / control_loss_schedule_tokens 463 464 schedule_c = get_sigmoid_weight( 465 r=schedule_position, 466 midpoint=0.5, 467 steepness=12.0, 468 ) 469 470 weighted_ctrl = alpha_c * loss_info_c + alpha_w * loss_info_w + beta_div * loss_div_c 471 loss_ctrl_scheduled = schedule_c * weighted_ctrl 472 473 if add_control_loss : 474 loss = main_loss + schedule_c * weighted_ctrl 475 476 metrics = { 477 "main_loss" : main_loss.detach(), 478 "loss_info_c": loss_info_c.detach(), 479 "loss_info_w": loss_info_w.detach(), 480 "loss_covariance_c": loss_covariance_c.detach(), 481 "loss_diversity_c": loss_div_c.detach(), 482 "loss_ctrl_weighted": weighted_ctrl.detach(), 483 "loss_ctrl_scheduled": loss_ctrl_scheduled.detach(), 484 "train_synergy_schedule": schedule_c, 485 } 486 487 ############################################################ 488 489 return ControlCausalLMOutput( 490 loss=loss, 491 aux_loss=aux_loss, 492 logits=logits, 493 past_key_values=outputs.past_key_values, 494 hidden_states=outputs.hidden_states, 495 attentions=outputs.attentions, 496 router_logits=outputs.router_logits, 497 **metrics 498 )
The [GraniteMoeHybridForCausalLM] 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.
Arguments:
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].past_key_values (
~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 thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only [
~cache_utils.Cache] instance is allowed as input, see our kv cache guide. If nopast_key_valuesare passed, [~cache_utils.DynamicCache] will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don't have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length).- inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional): Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model's internal embedding lookup matrix. - labels (
torch.LongTensorof 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_idsdocstring). Tokens with indices set to-100are ignored (masked), the loss is only computed for the tokens with labels in[0, ..., config.vocab_size]. - output_router_logits (
bool, optional): Whether or not to return the logits of all the routers. They are useful for computing the router loss, and should not be returned during inference. - 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:
[
~modeling_outputs.MoeCausalLMOutputWithPast] ortuple(torch.FloatTensor): A [~modeling_outputs.MoeCausalLMOutputWithPast] or a tuple oftorch.FloatTensor(ifreturn_dict=Falseis passed or whenconfig.return_dict=False) comprising various elements depending on the configuration ([None]) and inputs.
- loss (
torch.FloatTensorof shape(1,), optional, returned whenlabelsis provided) -- Language modeling loss (for next-token prediction). - logits (
torch.FloatTensorof 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 whenlabelsis provided) -- aux_loss for the sparse modules. router_logits (
tuple(torch.FloatTensor), optional, returned whenoutput_router_probs=Trueandconfig.add_router_probs=Trueis 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 auxiliary loss for Mixture of Experts models.
past_key_values (
Cache, optional, returned whenuse_cache=Trueis passed or whenconfig.use_cache=True) -- It is a [~cache_utils.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
past_key_valuesinput) to speed up sequential decoding.hidden_states (
tuple(torch.FloatTensor), optional, returned whenoutput_hidden_states=Trueis 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=Trueis 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-attention heads.
Example:
>>> from transformers import AutoTokenizer, GraniteMoeHybridForCausalLM
>>> model = GraniteMoeHybridForCausalLM.from_pretrained("ibm-granite/granite-4.0-h-tiny")
>>> tokenizer = AutoTokenizer.from_pretrained("ibm-granite/granite-4.0-h-tiny")
>>> 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."