Transformers documentation

Step3p7 (Step-3.7-Flash)

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.14.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

This model was contributed to Hugging Face Transformers on 2026-08-16.

Step3p7 (Step-3.7-Flash)

Overview

Step-3.7-Flash was proposed in Step 3.7 Flash by StepFun. It is a 198B-parameter sparse Mixture-of-Experts vision-language model, pairing a 196B-parameter MoE language backbone with a 1.8B-parameter vision encoder for native image understanding.

Architecture

StepFun hasn’t published a technical report for Step-3.7-Flash, so the details below are drawn from the released checkpoint’s configuration rather than a paper.

  • Sparse MoE decoder: all but the first 3 decoder layers route through a MoE block of 288 routed experts (top-8 per token) plus a single shared expert. The router scores experts with a sigmoid and a learned per-expert bias instead of an auxiliary load-balancing loss, the same strategy as DeepSeek-V3.
  • Gated attention: each attention layer adds an extra projection whose sigmoid output gates the attention output per head, before the output projection — the same Gated Attention mechanism used in Qwen3-Next. A subset of layers use fewer heads and a sliding window instead of full attention.
  • Multi-token prediction: some checkpoints ship extra decoder layers trained for multi-token prediction, which generate() can use for speculative decoding via use_mtp=True.
  • Vision encoder: a SigLIP-style ViT with 2-D rotary position embeddings and a learned per-layer scale on the attention and MLP branches. Its output is downsampled 4x by two stride-2 convolutions before a linear projector maps it into the text model’s hidden size.
  • Dynamic image tiling: instead of a fixed tile grid, the image processor picks its tiling window from each image’s own aspect ratio, producing one downscaled global view plus zero or more local high-resolution crops per image.

Usage example

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor


model = AutoModelForImageTextToText.from_pretrained(
    "stepfun-ai/Step-3.7-Flash", dtype=torch.bfloat16, device_map="auto",
)
processor = AutoProcessor.from_pretrained("stepfun-ai/Step-3.7-Flash")

messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"},
            {"type": "text", "text": "Describe this image briefly."},
        ],
    }
]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)

generated_ids = model.generate(**inputs, max_new_tokens=32, do_sample=False)
print(processor.batch_decode(generated_ids, skip_special_tokens=True)[0])

Step3p7Config

class transformers.Step3p7Config

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprojector_bias: bool = Falseimage_token_id: int = 151679 )

Parameters

  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the vision backbone.
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig], optional) — The config object or dictionary of the text backbone.
  • projector_bias (bool, optional, defaults to False) — Whether to use bias in the multimodal projector.
  • image_token_id (int, optional, defaults to 151679) — The image token index used as a placeholder for input images.

This is the configuration class to store the configuration of a Step3p7Model. It is used to instantiate a Step3P7 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 stepfun-ai/Step-3.7-Flash

Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.

Step3p7VisionConfig

class transformers.Step3p7VisionConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Nonehidden_size: int = 1536intermediate_size: int = 3072num_hidden_layers: int = 47num_attention_heads: int = 16num_channels: int = 3image_size: int = 728patch_size: int = 14hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0mlp_ratio: float = 5.833333333333333layer_scale_init_value: float = 0.1rope_parameters: dict | None = Nonemax_position_embeddings: int = 2704 )

Parameters

  • hidden_size (int, optional, defaults to 1536) — Dimension of the hidden representations.
  • intermediate_size (int, optional, defaults to 3072) — Dimension of the MLP representations.
  • num_hidden_layers (int, optional, defaults to 47) — 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_channels (int, optional, defaults to 3) — The number of input channels.
  • image_size (int, optional, defaults to 728) — The size (resolution) of each image.
  • patch_size (int, optional, defaults to 14) — The size (resolution) of each patch.
  • hidden_act (str, optional, defaults to quick_gelu) — The non-linear activation function (function or string) in the decoder. For example, "gelu", "relu", "silu", etc.
  • layer_norm_eps (float, optional, defaults to 1e-05) — The epsilon used by the layer normalization layers.
  • attention_dropout (Union[float, int], optional, defaults to 0.0) — The dropout ratio for the attention probabilities.
  • mlp_ratio (float, optional, defaults to 5.833333333333333) — Ratio of the MLP hidden dim to the embedding dim.
  • layer_scale_init_value (float, optional, defaults to 0.1) — Scale to use in the self-attention layers. 0.1 for base, 1e-6 for large. Set 0 to disable layer scale.
  • rope_parameters (dict, optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for rope_theta and optionally parameters used for scaling in case you want to use RoPE with longer max_position_embeddings.
  • max_position_embeddings (int, optional, defaults to 2704) — The maximum sequence length that this model might ever be used with.

This is the configuration class to store the configuration of a Step3p7Model. It is used to instantiate a Step3P7 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 stepfun-ai/Step-3.7-Flash

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 Step3p7VisionConfig, Step3p7VisionModel

>>> # Initializing a Step3p7VisionConfig with google/step3p7-base-patch16-224 style configuration
>>> configuration = Step3p7VisionConfig()

>>> # Initializing a Step3p7VisionModel (with random weights) from the google/step3p7-base-patch16-224 style configuration
>>> model = Step3p7VisionModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

Step3p7TextConfig

class transformers.Step3p7TextConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Nonevocab_size: int = 128815hidden_size: int = 4096intermediate_size: int = 11264num_hidden_layers: int = 45num_attention_heads: int = 64num_key_value_heads: int = 8head_dim: int = 128hidden_act: str = 'silu'max_position_embeddings: int = 128000initializer_range: float = 0.02rms_norm_eps: float = 1e-05use_cache: bool = Truepad_token_id: int = 1bos_token_id: int | None = Noneeos_token_id: int | list[int] | None = Nonetie_word_embeddings: bool = Falseattention_dropout: float | int = 0.0num_experts_per_tok: int = 8num_local_experts: int = 128rope_parameters: transformers.modeling_rope_utils.RopeParameters | dict | None = Nonemlp_layer_types: list[str] | None = Nonelayer_types: list[str] | None = Nonemoe_intermediate_size: int = 1280n_routed_experts: int = 288share_expert_dim: int = 1280sliding_window: int | None = Nonenum_sliding_attention_heads: int | None = Noneattention_bias: bool = Falsequery_pre_attn_scalar: int | float | None = Nonemoe_router_scaling_factor: float = 1.0mlp_bias: bool = Falseswiglu_limits: list[float | int | None] | None = Noneswiglu_limits_shared: list[float | int | None] | None = Nonemtp_layer_types: list[str] | None = Nonemtp_mlp_layer_types: list[str] | None = None )

Parameters

  • vocab_size (int, optional, defaults to 128815) — Vocabulary size of the model. Defines the number of different tokens that can be represented by the input_ids.
  • hidden_size (int, optional, defaults to 4096) — Dimension of the hidden representations.
  • intermediate_size (int, optional, defaults to 11264) — Dimension of the MLP representations.
  • num_hidden_layers (int, optional, defaults to 45) — Number of hidden layers in the Transformer decoder.
  • num_attention_heads (int, optional, defaults to 64) — Number of attention heads for each attention layer in the Transformer decoder.
  • num_key_value_heads (int, optional, defaults to 8) — This is the number of key_value heads that should be used to implement Grouped Query Attention. If num_key_value_heads=num_attention_heads, the model will use Multi Head Attention (MHA), if num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out this paper. If it is not specified, will default to num_attention_heads.
  • head_dim (int, optional, defaults to 128) — The attention head dimension. If None, it will default to hidden_size // num_attention_heads
  • hidden_act (str, optional, defaults to silu) — The non-linear activation function (function or string) in the decoder. For example, "gelu", "relu", "silu", etc.
  • max_position_embeddings (int, optional, defaults to 128000) — 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 to True) — Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if config.is_decoder=True or when the model is a decoder-only generative model.
  • pad_token_id (int, optional, defaults to 1) — Token id used for padding in the vocabulary.
  • bos_token_id (int, optional) — Token id used for beginning-of-stream in the vocabulary.
  • eos_token_id (Union[int, list[int]], optional) — Token id used for end-of-stream in the vocabulary.
  • tie_word_embeddings (bool, optional, defaults to False) — Whether to tie weight embeddings according to model’s tied_weights_keys mapping.
  • attention_dropout (Union[float, int], optional, defaults to 0.0) — The dropout ratio for the attention probabilities.
  • num_experts_per_tok (int, optional, defaults to 8) — Number of experts to route each token to. This is the top-k value for the token-choice routing.
  • num_local_experts (int, optional, defaults to 128) — Number of local experts on each device. num_experts should be divisible by num_local_experts.
  • rope_parameters (Union[~modeling_rope_utils.RopeParameters, dict], optional) — Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for rope_theta and optionally parameters used for scaling in case you want to use RoPE with longer max_position_embeddings.
  • mlp_layer_types (list[str], optional) — Per-layer MLP type: "sparse" (MoE) or "dense". If not provided, derived from the legacy moe_layers_enum hub-config kwarg (comma-separated string or list of MoE layer indices), defaulting to all layers from index 3 onward being MoE.
  • 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.
  • moe_intermediate_size (int, optional, defaults to 1280) — Intermediate size of the routed expert MLPs.
  • n_routed_experts (int, optional, defaults to 288) — Total number of routed experts. Accessible as num_local_experts via attribute_map.
  • share_expert_dim (int, optional, defaults to 1280) — Intermediate size of the always-active shared expert.
  • sliding_window (int, optional) — Sliding window attention window size. If None, no sliding window is applied.
  • num_sliding_attention_heads (int, optional) — Attention head count for "sliding_attention" layers, if different from num_attention_heads. Defaults to the legacy attention_other_setting hub-config kwarg’s num_attention_heads entry. Applied via a per_layer_config override (see PreTrainedConfig), not a per-layer list field.
  • attention_bias (bool, optional, defaults to False) — Whether to use a bias in the query, key, value and output projection layers during self-attention.
  • query_pre_attn_scalar (int or float, optional) — Step3p7Attention.__init__ hook point: defaults to head_dim, giving standard head_dim ** -0.5 scaling; overridable per released checkpoint variant.
  • moe_router_scaling_factor (float, optional, defaults to 1.0) — Scaling factor applied to the MoE block’s routed-expert output (routed_scaling_factor in Step3p7SparseMoeBlock).
  • mlp_bias (bool, optional, defaults to False) — Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
  • swiglu_limits (list[float | None], optional) — Per-layer gate/up clamping bound; None means no clamping.
  • swiglu_limits_shared (list[float | int | None], optional) — Per-layer gate/up clamping bound for the always-active shared expert; None means no clamping.
  • mtp_layer_types (list[str], optional) — Per-MTP-layer attention type; split off layer_types’s legacy trailing pad instead of being discarded, so Step3p7Config.get_mtp_config() can build the MTP layers for generate(use_mtp=True).
  • mtp_mlp_layer_types (list[str], optional) — Per-MTP-layer MLP type, analogous to mtp_layer_types for mlp_layer_types.

This is the configuration class to store the configuration of a Step3p7Model. It is used to instantiate a Step3P7 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 stepfun-ai/Step-3.7-Flash

Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.

Step3p7ImageProcessor

class transformers.Step3p7ImageProcessor

< >

( **kwargs: Unpack )

Parameters

  • do_convert_rgb (bool, kwargs, optional, defaults to True) — Whether to convert the image to RGB.
  • do_resize (bool, kwargs, optional) — Whether to resize the image.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs, defaults to {'height' -- 728, 'width': 728}): Describes the maximum input dimensions to the model.
  • default_to_square (bool, kwargs, optional, defaults to True) — Whether to default to a square image when resizing, if size is an int.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applying center_crop.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, defaults to Resampling.BILINEAR) — Resampling filter to use if resizing the image. This can be one of the enum PILImageResampling. Only has an effect if do_resize is set to True.
  • do_rescale (bool, kwargs, optional, defaults to True) — Whether to rescale the image.
  • rescale_factor (float, kwargs, optional, defaults to 0.00392156862745098) — Rescale factor to rescale the image by if do_rescale is set to True.
  • do_normalize (bool, kwargs, optional, defaults to True) — Whether to normalize the image.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to [0.48145466, 0.4578275, 0.40821073]) — Image mean to use for normalization. Only has an effect if do_normalize is set to True.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional, defaults to [0.26862954, 0.26130258, 0.27577711]) — Image standard deviation to use for normalization. Only has an effect if do_normalize is set to True.
  • do_pad (bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in {"height": int, "width" int} to pad the images to. Must be larger than any image size provided for preprocessing. If pad_size is not provided, images will be padded to the largest height and width in the batch. Applied only when do_pad=True.
  • do_center_crop (bool, kwargs, optional) — Whether to center crop the image.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, optional) — Only ChannelDimension.FIRST is supported. Added for compatibility with slow processors.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
    • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
    • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
    • "none" or ChannelDimension.NONE: image in (height, width) format.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models. Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models.
  • Returns stacked tensors if set to 'pt', otherwise returns a list of tensors. —

Constructs a Step3p7ImageProcessor image processor.

disable_grouping (bool, kwargs, optional): Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157 image_seq_length (int, kwargs, optional): The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models.

get_number_of_image_patches

< >

( height: intwidth: intimages_kwargs = None )

Return the number of local patches for an image of the given size.

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: Unpack ) ~image_processing_base.BatchFeature

Parameters

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False.
  • do_convert_rgb (bool, kwargs, optional) — Whether to convert the image to RGB.
  • do_resize (bool, kwargs, optional) — Whether to resize the image.
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Describes the maximum input dimensions to the model.
  • default_to_square (bool, kwargs, optional) — Whether to default to a square image when resizing, if size is an int.
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — Size of the output image after applying center_crop.
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — Resampling filter to use if resizing the image. This can be one of the enum PILImageResampling. Only has an effect if do_resize is set to True.
  • do_rescale (bool, kwargs, optional) — Whether to rescale the image.
  • rescale_factor (float, kwargs, optional) — Rescale factor to rescale the image by if do_rescale is set to True.
  • do_normalize (bool, kwargs, optional) — Whether to normalize the image.
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image mean to use for normalization. Only has an effect if do_normalize is set to True.
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional) — Image standard deviation to use for normalization. Only has an effect if do_normalize is set to True.
  • do_pad (bool, kwargs, optional) — Whether to pad the image. Padding is done either to the largest size in the batch or to a fixed square size per image. The exact padding strategy depends on the model.
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — The size in {"height": int, "width" int} to pad the images to. Must be larger than any image size provided for preprocessing. If pad_size is not provided, images will be padded to the largest height and width in the batch. Applied only when do_pad=True.
  • do_center_crop (bool, kwargs, optional) — Whether to center crop the image.
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, optional) — Only ChannelDimension.FIRST is supported. Added for compatibility with slow processors.
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
    • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
    • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
    • "none" or ChannelDimension.NONE: image in (height, width) format.
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — The device to process the videos on. If unset, the device is inferred from the input videos.
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — Returns stacked tensors if set to 'pt', otherwise returns a list of tensors.
  • disable_grouping (bool, kwargs, optional) — Whether to disable grouping of images by size to process them individually and not in batches. If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int, kwargs, optional) — The number of image tokens to be used for each image in the input. Added for backward compatibility but this should be set as a processor attribute in future models.
  • patch_size (int, kwargs, optional, defaults to 504) — Target size (height = width) for each local patch crop.
  • max_image_size (int, kwargs, optional, defaults to 3024) — Images larger than this (on their longest side) are scaled down uniformly before patch planning.

Returns

~image_processing_base.BatchFeature

  • data (dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.).
  • tensor_type (Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.

Step3p7Processor

class transformers.Step3p7Processor

< >

( image_processortokenizer = Nonechat_template = None**kwargs )

Processor for Step-3.7-Flash.

Uses ProcessorMixin.call() for the standard image-token expansion flow: the image processor splits each image into global + local patch crops, then replace_image_token builds the per-image replacement string that get_text_with_replacements substitutes into the text.

replace_image_token

< >

( image_inputs: dictimage_idx: int**kwargs )

Return the expanded token string for image image_idx (patches + global view).

Step3p7VisionModel

class transformers.Step3p7VisionModel

< >

( config: Step3p7VisionConfig )

Vision encoder: patch embeddings → 2-D RoPE transformer layers → conv downsampler.

The rotary embedding (self.rotary_emb) and layer stack (self.layers) are held directly on this module, following the Gemma4 convention of not wrapping them in a separate Encoder submodule.

forward

< >

( pixel_values: Tensor**kwargs: Unpack ) BaseModelOutput or tuple(torch.FloatTensor)

Parameters

  • pixel_values (torch.Tensor of shape (batch_size, num_channels, image_size, image_size)) — The tensors corresponding to the input images. Pixel values can be obtained using Step3p7ImageProcessor. See Step3p7ImageProcessor.__call__() for details (Step3p7Processor uses Step3p7ImageProcessor for processing images).

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 (Step3p7Config) and inputs.

The Step3p7VisionModel forward method, overrides the __call__ special method.

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

  • last_hidden_state (torch.FloatTensor of 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 when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.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.

Step3p7TextModel

class transformers.Step3p7TextModel

< >

( config: Step3p7TextConfig )

Parameters

  • config (Step3p7TextConfig) — 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 Step3P7 Text 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

< >

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: Unpack ) BaseModelOutputWithPast or tuple(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 using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.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 are not masked,
    • 0 for tokens that are masked.

    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-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

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

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

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 (Step3p7Config) and inputs.

The Step3p7TextModel forward method, overrides the __call__ special method.

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

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

    If past_key_values is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output.

  • past_key_values (Cache, optional, returned when use_cache=True is passed or when config.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=True in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.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.

Step3p7Model

class transformers.Step3p7Model

< >

( config: Step3p7Config )

Parameters

  • config (Step3p7Config) — 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 Llava-Next model which consists of a vision backbone and a language model without language modeling head.

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

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Nonepixel_values_local: typing.Optional[torch.FloatTensor] = Nonenum_local_patches: typing.Union[list[int], torch.Tensor, NoneType] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Noneuse_cache: bool | None = None**kwargs: Unpack ) Step3p7ModelOutputWithPast or tuple(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 using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using Step3p7ImageProcessor. See Step3p7ImageProcessor.__call__() for details (Step3p7Processor uses Step3p7ImageProcessor for processing images).
  • pixel_values_local (torch.FloatTensor, optional) — Local patch pixel values of shape (total_patches, 3, H, W).
  • num_local_patches (list[int] or torch.Tensor, optional) — Number of local patches per image in the batch.
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • 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-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

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

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

Returns

Step3p7ModelOutputWithPast or tuple(torch.FloatTensor)

A Step3p7ModelOutputWithPast 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 (Step3p7Config) and inputs.

The Step3p7Model forward method, overrides the __call__ special method.

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

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

    If past_key_values is used only the last hidden-state of the sequences of shape (batch_size, 1, hidden_size) is output.

  • past_key_values (Cache, optional, returned when use_cache=True is passed or when config.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_values input) to speed up sequential decoding.

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.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.

  • image_hidden_states (torch.FloatTensor, optional) — A torch.FloatTensor of size (batch_size, num_images, sequence_length, hidden_size). image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.

Step3p7ForConditionalGeneration

class transformers.Step3p7ForConditionalGeneration

< >

( config: Step3p7Config )

Parameters

  • config (Step3p7Config) — 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 Step3P7 Model for token generation conditioned on other modalities (e.g. image-text-to-text generation).

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

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.FloatTensor] = Nonepixel_values_local: typing.Optional[torch.FloatTensor] = Nonenum_local_patches: typing.Union[list[int], torch.Tensor, NoneType] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.LongTensor] = Nonepast_key_values: transformers.cache_utils.Cache | None = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneuse_cache: bool | None = Nonelogits_to_keep: typing.Union[int, torch.Tensor] = 0**kwargs: Unpack ) Step3p7CausalLMOutputWithPast or tuple(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 using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    What are input IDs?

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) — The tensors corresponding to the input images. Pixel values can be obtained using Step3p7ImageProcessor. See Step3p7ImageProcessor.__call__() for details (Step3p7Processor uses Step3p7ImageProcessor for processing images).
  • pixel_values_local (torch.FloatTensor, optional) — Local patch pixel values of shape (total_patches, 3, H, W).
  • num_local_patches (list[int] or torch.Tensor, optional) — Number of local patches per image in the batch.
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    What are attention masks?

  • 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-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

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

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
  • logits_to_keep (Union[int, torch.Tensor], optional, defaults to 0) — If an int, compute logits for the last logits_to_keep tokens. If 0, calculate logits for all input_ids (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If a torch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).

Returns

Step3p7CausalLMOutputWithPast or tuple(torch.FloatTensor)

A Step3p7CausalLMOutputWithPast 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 (Step3p7Config) and inputs.

The Step3p7ForConditionalGeneration forward method, overrides the __call__ special method.

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

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels 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).

  • past_key_values (Cache, optional, returned when use_cache=True is passed or when config.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_values input) to speed up sequential decoding.

  • hidden_states (tuple[torch.FloatTensor], optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.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 when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.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.

  • image_hidden_states (torch.FloatTensor, optional) — A torch.FloatTensor of size (batch_size * num_patches, num_images, sequence_length, hidden_size)`. image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.

Example:

>>> from PIL import Image
>>> from transformers import AutoProcessor, Step3p7ForConditionalGeneration

>>> model = Step3p7ForConditionalGeneration.from_pretrained("stepfun-ai/Step-3.7-Flash")
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/Step-3.7-Flash")

>>> 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]
Update on GitHub