Transformers documentation
DiffusionGemma
This model was contributed to Hugging Face Transformers on 2026-06-10.
DiffusionGemma
Overview
DiffusionGemma is engineered to reduce the sequential bottlenecks of standard causal language models. It employs an encoder-decoder architecture specifically optimized for inference speed.
The encoder operates in a prefill capacity, processing the initial prompt and generating the KV cache. The decoder then utilizes bidirectional attention to process an input block (a ‘canvas’) of tokens, accessing the cached context via cross-attention.
During inference, DiffusionGemma leverages multi-canvas sampling. Rather than generating one token at a time, the model iteratively denoises a full block of tokens using a diffusion sampler. Once a canvas is fully denoised, it is processed by the encoder and appended to the KV cache, after which the model generates the next canvas. This block-autoregressive approach facilitates text generation at higher speeds.
You can find the model card and checkpoint here.
Usage examples
Despite it being a text diffusion model and having a custom generation loop, most of the interface is shared with other model that can generate text with .generate(). If you’re using another transformers model in your app, you should be able to directly replace it with this model.
Common caveats:
- DiffusionGemma doesn’t accept
use_cache. It always uses a KV cache; - Support for common flags like
top_kwon’t be available at release day, but will be added over time if they are compatible with text diffusion.
from transformers import DiffusionGemmaForBlockDiffusion, AutoProcessor
model = DiffusionGemmaForBlockDiffusion.from_pretrained(
"google/diffusiongemma-26B-A4B-it", device_map="auto",
)
processor = AutoProcessor.from_pretrained("google/diffusiongemma-26B-A4B-it")
messages = [
{
"role": "user", "content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
{"type": "text", "text": "What is shown in this image?"},
]
},
]
inputs = processor.apply_chat_template(
messages,
tokenize=True,
return_dict=True,
return_tensors="pt",
add_generation_prompt=True,
).to(model.device)
input_len = inputs["input_ids"].shape[-1]
# Set `cache_implementation="static"` in `generate` to trigger `torch.compile`.
# Compilation is much faster, after warming up!
output = model.generate(**inputs, max_new_tokens=256)
print(processor.decode(output.sequences[0][input_len:], skip_special_tokens=True))Like other models that can generate text, you can set a streamer class to stream text. Unlike other models, DiffusionGemma generates intermediate drafts before the final text. You can visualize them with TextDiffusionStreamer
from transformers import TextDiffusionStreamer
# (... copy from the example above, up to the `generate` call)
streamer = TextDiffusionStreamer(tokenizer=processor.tokenizer)
model.generate(**inputs, max_new_tokens=256, streamer=streamer)DiffusionGemmaTextConfig
class transformers.DiffusionGemmaTextConfig
< source >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 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: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None vocab_size: int = 262144 hidden_size: int = 2304 intermediate_size: int = 9216 num_hidden_layers: int = 30 num_attention_heads: int = 8 num_key_value_heads: int = 4 head_dim: int = 256 hidden_activation: str = 'gelu_pytorch_tanh' max_position_embeddings: int = 131072 initializer_range: float = 0.02 rms_norm_eps: float = 1e-06 pad_token_id: int | None = 0 eos_token_id: int | list[int] | None = 1 bos_token_id: int | None = 2 tie_word_embeddings: bool = True rope_parameters: dict | None = None attention_bias: bool = False attention_dropout: int | float | None = 0.0 sliding_window: int = 512 layer_types: list[str] | None = None use_bidirectional_attention: typing.Optional[typing.Literal['all', 'vision']] = None num_global_key_value_heads: int | None = None global_head_dim: int = 512 num_experts: int | None = None top_k_experts: int | None = None moe_intermediate_size: int | None = None )
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 to2304) — Dimension of the hidden representations. - intermediate_size (
int, optional, defaults to9216) — Dimension of the MLP representations. - num_hidden_layers (
int, optional, defaults to30) — Number of hidden layers in the Transformer decoder. - num_attention_heads (
int, optional, defaults to8) — Number of attention heads for each attention layer in the Transformer decoder. - num_key_value_heads (
int, optional, defaults to4) — 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. - head_dim (
int, optional, defaults to256) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads - hidden_activation (
str, optional, defaults togelu_pytorch_tanh) — The non-linear activation function (function or string) in the decoder. For example,"gelu","relu","silu", etc. - max_position_embeddings (
int, optional, defaults to131072) — 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. - 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. - tie_word_embeddings (
bool, optional, defaults toTrue) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - rope_parameters (
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[int, float], optional, defaults to0.0) — The dropout ratio for the attention probabilities. - sliding_window (
int, optional, defaults to512) — Sliding window attention window size. IfNone, no sliding window is applied. - 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. - use_bidirectional_attention (
str, optional) — Controls bidirectional attention behavior. When set to"vision", vision tokens attend bidirectionally while text tokens use causal attention. When set to"all", all tokens use bidirectional attention. - num_global_key_value_heads (
int, optional) — Number of key-value heads for global (full) attention layers. IfNone, defaults tonum_key_value_heads. - global_head_dim (
int, defaults to 512) — Dimension of each attention head in global (full) attention layers. - num_experts (
int, optional) — Number of routed experts in MoE layers. - top_k_experts (
int, optional) — Number of experts activated per token in MoE layers. - moe_intermediate_size (
int, optional) — Intermediate (hidden) size of each expert’s feed-forward network in MoE layers.
This is the configuration class to store the configuration of a DiffusionGemmaModel. It is used to instantiate a Diffusion Gemma 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 google/diffusiongemma-26B-A4B-it
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
DiffusionGemmaConfig
class transformers.DiffusionGemmaConfig
< source >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 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: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None text_config: transformers.models.diffusion_gemma.configuration_diffusion_gemma.DiffusionGemmaTextConfig | dict[str, typing.Any] | None = None vision_config: transformers.configuration_utils.PreTrainedConfig | dict[str, typing.Any] | None = None boi_token_id: int | None = 255999 eoi_token_id: int | None = 258882 image_token_id: int | None = 258880 initializer_range: float | None = 0.02 tie_word_embeddings: bool = True canvas_length: int | None = 256 )
Parameters
- text_config (
Union[~models.diffusion_gemma.configuration_diffusion_gemma.DiffusionGemmaTextConfig, dict[str, Any]], optional) — The config object or dictionary of the text backbone. - vision_config (
Union[~configuration_utils.PreTrainedConfig, dict[str, Any]], optional) — The config object or dictionary of the vision backbone. - boi_token_id (
int, optional, defaults to 255999) — The begin-of-image token index to wrap the image prompt. - eoi_token_id (
int, optional, defaults to 258882) — The end-of-image token index to wrap the image prompt. - image_token_id (
int, optional, defaults to258880) — The image token index used as a placeholder for input images. - initializer_range (
float, optional, defaults to0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - tie_word_embeddings (
bool, optional, defaults toTrue) — Whether to tie weight embeddings according to model’stied_weights_keysmapping. - canvas_length (
int, optional, defaults to 256) — The size of the canvas or, in other words, the block length in block diffusion. Used to initialize an empty canvas.
This is the configuration class to store the configuration of a DiffusionGemmaModel. It is used to instantiate a Diffusion Gemma 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 google/diffusiongemma-26B-A4B-it
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 (
>>> DiffusionGemmaConfig,
>>> DiffusionGemmaModel,
>>> DiffusionGemmaTextConfig,
>>> Gemma4VisionConfig,
>>> )
>>> # Initializing a DiffusionGemma Text config.
>>> text_config = DiffusionGemmaTextConfig()
>>> # Initializing a Gemma 4 vision config (DiffusionGemma uses Gemma 4's vision block).
>>> vision_config = Gemma4VisionConfig()
>>> # Initializing a DiffusionGemma text config
>>> configuration = DiffusionGemmaConfig(text_config, vision_config)
>>> # Initializing a model from the configuration
>>> model = DiffusionGemmaModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configDiffusionGemmaGenerationOutput
class transformers.DiffusionGemmaGenerationOutput
< source >( sequences: LongTensor tokens_per_forward: int | None = None past_key_values: transformers.cache_utils.Cache | None = None logits: None = None scores: None = None hidden_states: None = None )
Parameters
- sequences (
torch.LongTensorof shape(batch_size, sequence_length)) — The generated sequences, including the prompt ifinput_idswas provided to thegeneratemethod. - tokens_per_forward (
torch.LongTensorof shape (batch_size)) — The number of tokens per forward in thisgeneratecall, for each member in the batch. This is often used as a secundary evaluation metric for text diffusion models. - past_key_values (
~cache_utils.Cache, optional) — The cache used for generation. It can be passed to subsequent calls togenerateto speed up generation, in multi-turn sessions. - logits (
None, optional) — Unused. Kept in the interface for BC. - scores (
None, optional) — Unused. Kept in the interface for BC. - hidden_states (
None, optional) — Unused. Kept in the interface for BC. - sequences (
torch.LongTensorof shape(batch_size, sequence_length)) — The generated sequences, including the prompt ifinput_idswas provided to thegeneratemethod. - tokens_per_forward (
torch.LongTensorof shape (batch_size)) — The number of tokens per forward in thisgeneratecall, for each member in the batch. This is often used as a secundary evaluation metric for text diffusion models. - past_key_values (
~cache_utils.Cache, optional, defaults toNone) — The cache used for generation. It can be passed to subsequent calls togenerateto speed up generation, in multi-turn sessions. - logits (
None, optional, defaults toNone) — Unused. Kept in the interface for BC. - scores (
None, optional, defaults toNone) — Unused. Kept in the interface for BC. - hidden_states (
None, optional, defaults toNone) — Unused. Kept in the interface for BC.
DiffusionGemmaGenerationMixin
Mixin class for DiffusionGemma generation. Contains all the model-level methods.
adjust_generation_fn
< source >( generation_config from_auto_class from_pipeline pretrained_model_name_or_path cache_dir force_download proxies local_files_only token revision subfolder trust_remote_code **kwargs )
Logic used at model_cls.from_pretrained() time, to set a model-level generation config.
(NOTE: Originally copied from GenerationMixin.adjust_generation_fn on 2026-05-04, and stripped down
for DiffusionGemma.)
generate
< source >( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None streamer: transformers.generation.streamers.BaseStreamer | None = None generation_config: transformers.models.diffusion_gemma.generation_diffusion_gemma.DiffusionGemmaGenerationConfig | None = None logits_processor: transformers.generation.logits_process.LogitsProcessorList | None = None stopping_criteria: transformers.generation.stopping_criteria.StoppingCriteriaList | None = None **kwargs ) → DiffusionGemmaGenerationOutput
Parameters
- input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — The sequence used as a prompt for the generation.
- past_key_values (Cache, optional) —
Cache object containing the past key values and past attention masks for the decoder. If it is set,
input_idsand/orpixel_valuesmust correspond to uncached data only. - streamer (
BaseStreamer, optional) — Streamer object that will be used to stream the generated sequences. Generated tokens are passed throughstreamer.put(token_ids)and the streamer is responsible for any further processing. If the streamer object has aput_draftmethod, tokens from the denoising steps will be sent there.
Additional arguments for power users
- generation_config (DiffusionGemmaGenerationConfig, optional) —
The generation configuration to be used as base parametrization for the generation call, overriding
the model defaults. If the model checkpoint has a
generation_config.jsonfile, the model default will be loaded from there. Otherwise, it will be an emptyDiffusionGemmaGenerationConfiginstance. As an additional shortcut,**kwargsmatching attributes in thegeneration_configwill override them. - logits_processor (LogitsProcessorList, optional) — Custom logits processors that complement the default logits processors built from arguments and generation config, to be applied on the diffusion logits. If provided, these processors will be first to be applied. This feature is intended for advanced users. You can, for instance, pass here the logits processors commonly used with AR LLMs.
- stopping_criteria (StoppingCriteriaList, optional) — Custom stopping criteria that complements the default block autoregressive stopping criteria built from arguments and a generation config. If provided, these criteria will be first to be applied. This feature is intended for advanced users. You can, for instance, pass here the stopping criteria commonly used with AR LLMs.
- kwargs (
dict[str, Any], optional) — Ad hoc parametrization ofgeneration_configand/or additional model-specific kwargs that will be forwarded to theforwardfunction of the model.
Returns
a ModelOutput instance containing the generated text (sequences),
as well as other optional outputs.
Generates text using the diffusion model.
It contains an outer loop doing autoregressive generation of canvases (blocks of tokens), and an inner loop doing diffusion on each canvas. The algorithm works roughly as follows:
- Autoregressive canvas generation loop: a. Encode all previous tokens using the encoder, to get the KV cache. b. Prepare data for the new denoising loop c. For each denoising (diffusion) step: i. Run the decoder, taking the current canvas, the encoder KV cache, and the self-conditioning logits (if available) as inputs. ii. Select new canvas tokens from the output logits. iii. Apply the sampler acceptance and renoising logic. iv. Update the diffusion stopping criteria. v. Use the output logits as self-conditioning logits for the next step. d. Append the new denoised canvas to the sequence of generated tokens. e. Check if any autoregressive stopping criteria are met, and break the outer loop if all sequences have met them. Replaces generated tokens in finished sequences by pad. f. Prepare tensors for the next block
Examples:
>>> from transformers import DiffusionGemmaForBlockDiffusion, AutoProcessor, TextDiffusionStreamer
>>> model = DiffusionGemmaForBlockDiffusion.from_pretrained(
... "CHECKPOINT", device_map="auto",
>>> )
>>> chat = [{"role": "user", "content": "Why is the sky blue?"},]
>>> processor = AutoProcessor.from_pretrained("CHECKPOINT")
>>> input_ids = processor.apply_chat_template(chat, tokenize=True, return_tensors="pt")
>>> streamer = TextDiffusionStreamer(tokenizer=processor.tokenizer)
>>> model.generate(input_ids.to(model.device), max_new_tokens=512, streamer=streamer)DiffusionGemmaGenerationConfig
class transformers.DiffusionGemmaGenerationConfig
< source >( **kwargs )
Parameters that control the length of the output
- max_new_tokens (
int, optional) — The maximum number of tokens to generate, ignoring the number of tokens in the prompt. - max_length (
int, optional) — The maximum length of the output sequence.max_new_tokensis recommended for controlling how many tokens the model generates.
Diffusion parameters
- max_denoising_steps (
int) — The maximum number of denoising steps to perform. - sampler_config (
EntropyBoundSamplerConfig) — The configuration for the sampler. See EntropyBoundSampler to learn how a sampler operates in a text diffusion model. - t_min (
float) — The final temperature in the schedule, i.e. at the last denoising step. See LinearTemperatureScheduleLogitsProcessor for more details. - t_max (
float) — The initial temperature in the schedule, i.e. at the first denoising step. See LinearTemperatureScheduleLogitsProcessor for more details. - stability_threshold (
int) — The number of steps for which the accepted canvas must be the same to trigger the stopping criteria. See StableAndConfidentStoppingCriteria for more details. - confidence_threshold (
float) — The threshold for the mean of the entropy of temperature-scaled logits to trigger the stopping criteria. See StableAndConfidentStoppingCriteria for more details.
Parameters that control the cache
- cache_implementation (
str, optional) — Name of the cache class that will be instantiated ingenerate, for faster decoding. Possible values are:"dynamic": DynamicCache"static": StaticCache"offloaded":DynamicCache(offloaded=True)"offloaded_static":StaticCache(offloaded=True)"quantized": QuantizedCache
If none is specified, we will use the default cache for the model (which is often DynamicCache). See our cache documentation for further information.
- cache_config (
dict, optional, default toNone) — Arguments used in the key-value cache class can be passed incache_config.
Special tokens that can be used at generation time
A GenerationConfig class with paremeterization custom to DiffusionGemma generate.
EntropyBoundSamplerConfig
class transformers.EntropyBoundSamplerConfig
< source >( entropy_bound: float )
Parameters
- entropy_bound (
float) — The entropy bound. The higher this value is, the more tokens will be accepted. See the docstring of EntropyBoundSampler.accept_canvas() for more details on how it is applied.
Configuration class for the entropy bound sampler.
EntropyBoundSampler
class transformers.EntropyBoundSampler
< source >( config: EntropyBoundSamplerConfig canvas_length: int vocab_size: int max_denoising_steps: int )
Sampler class that initializes a canvas with random tokens, accepts tokens based on token-level entropy, and renoises non-accepted tokens.
Here is a rough sketch of how the sampler loop works: +-----------------------+ | Canvas initialization | | xT ∈ U(V) | +-----------+-----------+ | v +----------+---------+ +---------------------+ +--------->| Current canvas x_t |------>| Denoiser canvas x_D | | +----------+---------+ +----------+----------+ | \ / | \ / | \ Acceptance logic / | v v | +-------------------------+ | Stop if max | Accepted canvas x{t-1} | | denosing steps +------------+------------+ +-------------------+ | reached or \ | New canvas ∈ U(V) | | adaptive stopping \ +---------+---------+ | triggers \ Renoising logic / | v v | +-------------------------+ +---------------------------------------| Next canvas x_{t-1} | +-------------------------+
accept_canvas
< source >( current_canvas: LongTensor denoiser_canvas: LongTensor logits: FloatTensor cur_step: int ) → torch.LongTensor
Accepts tokens from the denoiser based on an entropy bound. More concretely, sampling proceeds by accepting k tokens with lowest entropy, such that
sum_i^k entropy_i - max(entropy_1, …, entropy_k) <= entropy_bound,
where the LHS is the upper bound on the joint mutual information between these tokens, and thus the sampler chooses k tokens that they are approximately independent.
Originally proposed in https://arxiv.org/pdf/2505.24857
Initializes and returns a new canvas of canvas_length tokens with random values from the vocabulary.
renoise_canvas
< source >( accepted_canvas: LongTensor cur_step: int ) → torch.LongTensor
Renoises all non-accepted tokens.
StableAndConfidentStoppingCriteria
class transformers.StableAndConfidentStoppingCriteria
< source >( stability_threshold: int confidence_threshold: float )
Adaptive stopping strategy that stops when the diffusion process is confident and stable. To be more specific:
- The diffusion process is stable when the accepted canvas are the same across
stability_thresholdsteps. - The diffusion process is confident when the mean of the entropy of the processed logits is below
confidence_threshold.
LinearTemperatureScheduleLogitsProcessor
class transformers.LinearTemperatureScheduleLogitsProcessor
< source >( t_min: float t_max: float max_denoising_steps: int )
Logits processor that applies a linear temperature schedule to the logits. This is similar to
TemperatureLogitsWarper, except that the temperature is a function of the current step.
At step n out of N, the temperature t is given by t = t_min + ((t_max - t_min) * (n/N)).
DiffusionGemmaPreTrainedModel
class transformers.DiffusionGemmaPreTrainedModel
< source >( config: PreTrainedConfig *inputs **kwargs )
Define the computation performed at every call.
Should be overridden by all subclasses.
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 registered hooks while the latter silently ignores them.
DiffusionGemmaModel
class transformers.DiffusionGemmaModel
< source >( config: DiffusionGemmaConfig )
Parameters
- config (DiffusionGemmaConfig) — 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 Diffusion Gemma 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: torch.LongTensor | None = None attention_mask: torch.Tensor | dict | None = None past_key_values: transformers.cache_utils.Cache | None = None position_ids: torch.LongTensor | None = None decoder_input_ids: torch.LongTensor | None = None self_conditioning_logits: torch.FloatTensor | None = None decoder_attention_mask: torch.Tensor | dict | None = None decoder_position_ids: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → BaseModelOutputWithPast or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Uncached token IDs for the prompt to be encoded as context for the canvas. - attention_mask (
torch.Tensorof shape(batch_size, sequence_length)ordict, optional) — Mask for the input tokens. - 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 instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, 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). - 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]. - decoder_input_ids (
torch.LongTensorof shape(batch_size, canvas_length), optional) — Token IDs for the canvas to be refined. - self_conditioning_logits (
torch.FloatTensorof shape(batch_size, canvas_length, vocab_size), optional) — Self-conditioning logits from the previous denoising step, used to compute the self-conditioning embeddings. - decoder_attention_mask (
torch.Tensorof shape(batch_size, sequence_length+canvas_length)ordict, optional) — Attention mask for the decoder KV cache. Used to specify padded/unpopulated encoder KV cached entries. - decoder_position_ids (
torch.LongTensorof shape(batch_size, canvas_length), optional) — The position IDs for the tokens in the canvas.
Returns
BaseModelOutputWithPast or tuple(torch.FloatTensor)
A BaseModelOutputWithPast or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (DiffusionGemmaConfig) and inputs.
The DiffusionGemmaModel 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.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.If
past_key_valuesis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.past_key_values (
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 (seepast_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.
DiffusionGemmaEncoderModel
class transformers.DiffusionGemmaEncoderModel
< source >( config: DiffusionGemmaConfig )
Parameters
- config (DiffusionGemmaConfig) — 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 DiffusionGemma encoder model comprising a vision backbone and a language model, without a language modeling head. It is very similar to Gemma4Model, except that it doesn’t support audio or video inputs, and always assumes the MoE code path in the inner layers.
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: torch.LongTensor | None = None pixel_values: torch.FloatTensor | None = None attention_mask: torch.Tensor | dict | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None mm_token_type_ids: torch.LongTensor | None = None inputs_embeds: torch.FloatTensor | None = None image_position_ids: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → BaseModelOutputWithPast or tuple(torch.FloatTensor)
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.
- pixel_values (
torch.FloatTensorof shape(batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained usingimage_processor_class. Seeimage_processor_class.__call__for details (Gemma4Processor usesimage_processor_classfor processing images). - attention_mask (
Union[torch.Tensor, dict]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.
- 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 instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, 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). - mm_token_type_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2). Multimodal token type ids can be obtained using AutoProcessor. See ProcessorMixin.call() for details. - 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. - image_position_ids (
torch.LongTensorof shape(batch_size, max_patches, 2), optional) — 2D patch position coordinates from the image processor, with(-1, -1)indicating padding. Passed through to the vision encoder for positional embedding computation.
Returns
BaseModelOutputWithPast or tuple(torch.FloatTensor)
A BaseModelOutputWithPast or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (DiffusionGemmaConfig) and inputs.
The DiffusionGemmaEncoderModel 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.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.If
past_key_valuesis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.past_key_values (
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 (seepast_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.
DiffusionGemmaEncoderTextModel
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | dict | None = None position_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None inputs_embeds: torch.FloatTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → BaseModelOutputWithPast or tuple(torch.FloatTensor)
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 (
Union[torch.Tensor, dict]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.
- 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 instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, 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.
Returns
BaseModelOutputWithPast or tuple(torch.FloatTensor)
A BaseModelOutputWithPast or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (DiffusionGemmaConfig) and inputs.
The DiffusionGemmaEncoderTextModel 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.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.If
past_key_valuesis used only the last hidden-state of the sequences of shape(batch_size, 1, hidden_size)is output.past_key_values (
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 (seepast_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.
DiffusionGemmaDecoderModel
Decoder model for DiffusionGemma.
Processes canvas tokens with bidirectional self-attention and cross-attention to the encoder’s KV cache.
The decoder reads but does not update the KV cache. Excluding these differences, it is similar to
DiffusionGemmaEncoderTextModel, and they share all weights they have in common.
forward
< source >( decoder_input_ids: LongTensor past_key_values: transformers.cache_utils.Cache | None = None self_conditioning_logits: torch.FloatTensor | None = None decoder_attention_mask: torch.Tensor | dict | None = None decoder_position_ids: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → BaseModelOutput or tuple(torch.FloatTensor)
Parameters
- decoder_input_ids (
torch.LongTensorof shape(batch_size, canvas_length)) — Token IDs for the canvas to be refined. - 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 instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, 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). - self_conditioning_logits (
torch.FloatTensorof shape(batch_size, canvas_length, vocab_size), optional) — Self-conditioning logits from the previous denoising step, used to compute the self-conditioning embeddings. - decoder_attention_mask (
torch.Tensorof shape(batch_size, sequence_length+canvas_length)ordict, optional) — Attention mask for the decoder KV cache. Used to specify padded/unpopulated encoder KV cached entries. - decoder_position_ids (
torch.LongTensorof shape(batch_size, canvas_length), optional) — The position IDs for the tokens in the canvas.
Returns
BaseModelOutput or tuple(torch.FloatTensor)
A BaseModelOutput or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (DiffusionGemmaConfig) and inputs.
The DiffusionGemmaDecoderModel 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.FloatTensorof shape(batch_size, sequence_length, hidden_size)) — Sequence of hidden-states at the output of the last layer of the model.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.
DiffusionGemmaForBlockDiffusion
DiffusionGemma model for block diffusion. It calls DiffusionGemmaModel to obtains the hidden states for
the input canvas, conditioned by a prompt KV cache. Using its LM Head and self-conditioning blocks, it converts
those hidden states into logits to sample the next canvas, as well as the self-conditioning embeddings for the
next block diffusion step.
forward
< source >( input_ids: torch.LongTensor | None = None attention_mask: torch.Tensor | dict | None = None past_key_values: transformers.cache_utils.Cache | None = None position_ids: torch.LongTensor | None = None decoder_input_ids: torch.LongTensor | None = None self_conditioning_logits: torch.FloatTensor | None = None decoder_attention_mask: torch.Tensor | dict | None = None decoder_position_ids: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → CausalLMOutputWithPast or tuple(torch.FloatTensor)
Parameters
- input_ids (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Uncached token IDs for the prompt to be encoded as context for the canvas. - attention_mask (
torch.LongTensorof shape(batch_size, sequence_length)ordict, optional) — Mask for the input tokens. - 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 instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, 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). - 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]. - decoder_input_ids (
torch.LongTensorof shape(batch_size, canvas_length), optional) — Token IDs for the canvas to be refined. - self_conditioning_logits (
torch.FloatTensorof shape(batch_size, canvas_length, vocab_size), optional) — Self-conditioning logits from the previous denoising step, used to compute the self-conditioning embeddings. - decoder_attention_mask (
torch.Tensorof shape(batch_size, sequence_length+canvas_length)ordict, optional) — Attention mask for the decoder KV cache. Used to specify padded/unpopulated encoder KV cached entries. - decoder_position_ids (
torch.LongTensorof shape(batch_size, canvas_length), optional) — The position IDs for the tokens in the canvas.
Returns
CausalLMOutputWithPast or tuple(torch.FloatTensor)
A CausalLMOutputWithPast or a tuple of
torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various
elements depending on the configuration (DiffusionGemmaConfig) and inputs.
The DiffusionGemmaForBlockDiffusion 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.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).past_key_values (
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
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 PIL import Image
>>> from transformers import AutoProcessor, DiffusionGemmaForBlockDiffusion
>>> model = DiffusionGemmaForBlockDiffusion.from_pretrained("google/diffusiongemma-26B-A4B-it")
>>> processor = AutoProcessor.from_pretrained("google/diffusiongemma-26B-A4B-it")
>>> messages = [
... {
... "role": "user", "content": [
... {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
... {"type": "text", "text": "Where is the cat standing?"},
... ]
... },
... ]
>>> inputs = processor.apply_chat_template(
... messages,
... tokenize=True,
... return_dict=True,
... return_tensors="pt",
... add_generation_prompt=True
... )
>>> # Generate
>>> generate_ids = model.generate(**inputs)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]