Transformers documentation
Exporters
Exporters
New export backends can be added to Transformers by subclassing HfExporter.
Learn how to use the built-in exporters in the Exporters guide.
AutoHfExporter
The Auto-HF exporter class that takes care of automatically instantiating to the correct HfExporter given the ExportConfig.
Load an exporter instance from a pretrained model/checkpoint that ships an export config.
Not implemented yet — placeholder for a first-class “export recipe” workflow.
The idea: model owners publish an export_config.json (or an export_config field in config.json) alongside their weights on the Hub. That file captures the settings the
owner has already validated for their architecture — the target format (dynamo / onnx / executorch), exact dynamic-shape specs (e.g. text_ids dynamic to 4096,
image tiles fixed at 448, batch=1 for edge deployment), strict flag, ONNX opset,
prefill vs. decode layout, ExecuTorch backend choice, and any other knob that today lives
as tribal knowledge in a README or a private notebook.
Consumers then get the owner-validated export in one call:
exporter = AutoHfExporter.from_pretrained("org/model-name")
program = exporter.export(model, inputs)Composes with the [register_export_input_preparer] registry: the owner supplies the
shape spec via export_config.json, transformers supplies the data-dependent
precomputations (cu_seqlens, vision position ids, window indices, …) for that
architecture. Together they cover the two hard parts of exporting new models — knowing
the right shape contract and preparing the right inputs — so downstream users don’t
re-derive either from scratch (and don’t break in production when they get it wrong).
Return True if the provided dict describes an export_format that has both a
registered config class and a registered exporter class. Warns with an actionable message
when the format is missing entirely, unknown, or only half-registered.
AutoExportConfig
The Auto-HF export config class that takes care of automatically dispatching to the correct export config given an export config stored in a dictionary.
HfExporter
Abstract base class for all Transformers exporters.
Subclass and implement ~HfExporter.export to add a new export backend.
export
< source >( model: PreTrainedModelsample_inputs: MutableMapping[str, torch.Tensor | Cache]config: ExportConfigMixin )
Parameters
- model (PreTrainedModel) — The model to export.
- sample_inputs (
dict[str, torch.Tensor | Cache]) — Forward kwargs — what you’d pass tomodel(**sample_inputs). These are used directly as the example inputs during tracing. For an autoregressive decode-step export, this means you need to includepast_key_values,cache_position, etc. If you only have generation-style inputs, use~HfExporter.export_for_generationinstead — it runsmodel.generatefor you and exports each stage. - config (
ExportConfigMixin) — Backend-specific configuration.
Export the model and return the backend-specific program object.
export_for_generation
< source >( model: PreTrainedModelsample_inputs: MutableMapping[str, torch.Tensor | Cache]config: ExportConfigMixin | dict[str, ExportConfigMixin]generation_config: GenerationConfig | None = Nonemulti_token_decode: bool = False ) → dict[str, Any]
Parameters
- model (PreTrainedModel) —
The generative model to export. Must support
model.generate(**sample_inputs). - sample_inputs (
dict[str, torch.Tensor | Cache]) — Generate kwargs — what you’d pass tomodel.generate(**sample_inputs)(typicallyinput_ids+attention_mask, plus any modality inputs likepixel_values/input_featuresfor multi-modal models). Per-stage forward kwargs are captured internally. - config (
ExportConfigMixinordict[str, ExportConfigMixin]) — Backend-specific configuration. Pass a single config to apply to every component, or adictkeyed by component name (e.g."image_encoder","language_model","lm_head","decode") to override per-component — all component names must be present in the dict. - generation_config (GenerationConfig, optional) —
Forwarded to the
generate()capture (defaults to the model’s own). Pass one withcache_implementation="static"to export against a fixed-sizeStaticCache. - multi_token_decode (
bool, optional, defaults toFalse) — Whether thedecodecomponent processes multiple query tokens at once — a dynamic query axis (prefill on an empty cache, continuation-from-past otherwise) — vs the classic single-token step (see decompose_for_generation()). Only stays dynamic under a dynamic-shape export (config.dynamic=True).
Returns
dict[str, Any]
{component_name: backend_specific_artifact} — same keys as
decompose_for_generation(). Values are whatever
~HfExporter.export returns for the concrete backend (ExportedProgram,
ONNXProgram, ExecutorchProgramManager).
Decompose a generative model and export each component independently.
Thin wrapper around decompose_for_generation() that calls ~HfExporter.export on every returned (submodel, forward_inputs) pair. If you need
the intermediate (submodel, forward_inputs) pairs (for verification, custom inputs,
skipping a stage, …), call decompose_for_generation() directly.
Check required_packages are installed and warn on version drift from tested_versions.
DynamoExporter
Exporter that converts a PreTrainedModel to an ExportedProgram.
Example:
>>> from transformers.exporters.exporter_dynamo import DynamoExporter, DynamoConfig
>>> exporter = DynamoExporter()
>>> exported = exporter.export(model, inputs, config=DynamoConfig(dynamic=True))
>>> outputs = exported.module()(**inputs)export
< source >( model: PreTrainedModelsample_inputs: MutableMapping[str, Any]config: DynamoConfig | dict[str, Any] )
OnnxExporter
Exporter that converts a PreTrainedModel to an ONNX ONNXProgram.
Example:
>>> from transformers.exporters.exporter_onnx import OnnxExporter, OnnxConfig
>>> exporter = OnnxExporter()
>>> onnx_program = exporter.export(model, inputs, config=OnnxConfig(dynamic=True))
>>> outputs = onnx_program(**inputs) # run in-memory
>>> exporter.export(model, inputs, config=OnnxConfig(output_path="model.onnx")) # save to diskexport
< source >( model: PreTrainedModelsample_inputs: MutableMapping[str, Any]config: OnnxConfig | dict[str, Any] )
ExecutorchExporter
Exporter that converts a PreTrainedModel to an ExecuTorch ExecutorchProgramManager.
Example:
>>> from transformers.exporters.exporter_executorch import ExecutorchExporter, ExecutorchConfig
>>> exporter = ExecutorchExporter()
>>> et_program = exporter.export(model, inputs, config=ExecutorchConfig(backend="xnnpack"))
>>> et_program.write_to_file("model.pte")export
< source >( model: PreTrainedModelsample_inputs: MutableMapping[str, Any]config: ExecutorchConfig | dict[str, Any] )
Export a model to ExecuTorch, applying backend preparation and torch op patches.
DynamoConfig
class transformers.exporters.DynamoConfig
< source >( export_format: ExportFormat = <ExportFormat.DYNAMO: 'dynamo'>dynamic: bool = Falsestrict: bool = Falsedynamic_shapes: dict[str, Any] | None = Noneprefer_deferred_runtime_asserts_over_guards: bool = Falsequantizer: ExportQuantizer | None = None )
Parameters
- dynamic (bool, optional, defaults to False) — Whether to export with dynamic (symbolic) shapes. When True and dynamic_shapes is not set, all tensor dimensions are set to Dim.AUTO automatically.
- strict (bool, optional, defaults to False) — Whether to enable strict mode in torch.export. Runs the full symbolic trace and catches more errors, but is slower and more likely to fail on complex models.
- dynamic_shapes (dict[str, Any], optional) — Explicit per-input dynamic shape specifications passed to torch.export. Takes precedence over dynamic.
- prefer_deferred_runtime_asserts_over_guards (bool, optional, defaults to False) —
When True, data-dependent shape guards are emitted as runtime asserts in the exported
graph instead of failing the export at trace time when a guard wouldn’t hold across the
full symbolic shape range. Most transformer LLMs need this set to True when using
fine-grained
Dim(min=, max=)bounds. Not needed withdynamic=True/Dim.AUTO, wheretorch.exportinfers shape relations instead of verifying them against the user-stated bounds. - quantizer ([~exporters.quantizers.ExportQuantizer], optional) — Post-training quantization applied during the export: [~exporters.quantizers.PT2EQuantizer] or [~exporters.quantizers.NNCFTorchFXQuantizer] on the FX graph for every backend, [~exporters.quantizers.OnnxRuntimeQuantizer] on the converted ONNX model, or [~exporters.quantizers.NNCFOpenVINOQuantizer] / [~exporters.quantizers.NNCFOnnxQuantizer] on the converted OpenVINO / ONNX model.
Configuration class for exporting models via torch.export.
OnnxConfig
class transformers.exporters.OnnxConfig
< source >( export_format: ExportFormat = <ExportFormat.ONNX: 'onnx'>dynamic: bool = Falsestrict: bool = Falsedynamic_shapes: dict[str, Any] | None = Noneprefer_deferred_runtime_asserts_over_guards: bool = Falsequantizer: ExportQuantizer | None = Noneoutput_path: str | PathLike | None = Noneopset_version: int | None = Noneexternal_data: bool = Trueoptimize: bool = Trueexport_params: bool = Truekeep_initializers_as_inputs: bool = False )
Parameters
- output_path (
strorPathLike, optional) — Output path for the.onnxfile. WhenNone(default) the exported model is kept in memory as anONNXProgramand not written to disk. - opset_version (
int, optional) — ONNX opset version to target. Defaults to the latest opset supported by the installedonnxscriptversion. - external_data (
bool, optional, defaults toTrue) — Store large weight tensors in a separate.onnx_datasidecar file instead of embedding them in the protobuf. Required for models whose weights exceed the 2 GB protobuf limit. - optimize (
bool, optional, defaults toTrue) — Runonnxscriptoptimisation passes (constant folding, dead-code elimination, …) on the exported graph. Disable for models that hit upstreamonnxscriptoptimiser bugs. - export_params (
bool, optional, defaults toTrue) — Embed model weights in the ONNX graph. Set toFalseto export a weight-free graph (weights must be supplied at runtime). - keep_initializers_as_inputs (
bool, optional, defaults toFalse) — Expose weight initializers as explicit graph inputs. Required by some older ONNX runtimes (opset < 9).
Configuration class for exporting models to ONNX via torch.onnx.export.
Inherits all fields from DynamoConfig (dynamic, strict, dynamic_shapes, prefer_deferred_runtime_asserts_over_guards).
ExecutorchConfig
class transformers.exporters.ExecutorchConfig
< source >( export_format: ExportFormat = <ExportFormat.EXECUTORCH: 'executorch'>dynamic: bool = Falsestrict: bool = Falsedynamic_shapes: dict[str, Any] | None = Noneprefer_deferred_runtime_asserts_over_guards: bool = Falsequantizer: ExportQuantizer | None = Nonebackend: str = 'xnnpack'alloc_graph_input: bool = Truealloc_graph_output: bool = Truealloc_mutable_buffers: bool = True )
Parameters
- backend (
str, optional, defaults to"xnnpack") — Target ExecuTorch backend. Supported values:"xnnpack"— CPU inference via the XNNPACK library (default; runs anywhere)."cuda"— GPU inference via the ExecuTorch CUDA backend."mlx"— GPU inference via the ExecuTorch MLX backend on Apple Silicon.
- alloc_graph_input (
bool, optional, defaults toTrue) — Whether the memory-planning pass reserves arena memory for graph inputs. WhenFalse, the runtime uses the caller-provided input buffers directly instead of copying into the arena — so an in-placeUSER_INPUT_MUTATION(e.g. aStaticCachewrite) lands in the caller’s tensor rather than an arena copy. - alloc_graph_output (
bool, optional, defaults toTrue) — Whether the memory-planning pass reserves arena memory for graph outputs. WhenFalse, the caller must bind output buffers at runtime (Method::set_output_data_ptr); binding an output to its mutated input’s buffer avoids the copy-out roundtrip. - alloc_mutable_buffers (
bool, optional, defaults toTrue) — Whether the memory-planning pass reserves arena memory for mutable buffers (model-resident state). Passed through to theMemoryPlanningPass.
Configuration class for exporting models to ExecuTorch format.
Inherits all fields from DynamoConfig (dynamic, strict, dynamic_shapes, prefer_deferred_runtime_asserts_over_guards).
OpenVINOConfig
class transformers.exporters.OpenVINOConfig
< source >( export_format: ExportFormat = <ExportFormat.OPENVINO: 'openvino'>dynamic: bool = Falsestrict: bool = Falsedynamic_shapes: dict[str, Any] | None = Noneprefer_deferred_runtime_asserts_over_guards: bool = Falsequantizer: ExportQuantizer | None = Noneoutput_path: str | PathLike | None = Nonecompress_to_fp16: bool = Truestateful: bool = True )
Parameters
- output_path (str or PathLike, optional) —
Output path for the .xml file (the matching .bin is written alongside). When
None (default) the converted model is kept in memory as an
openvino.Model. - compress_to_fp16 (bool, optional, defaults to True) —
Compress floating-point weights to FP16 when saving — halves on-disk size with
negligible accuracy impact on most models. Only applied when
output_pathis set. - stateful (bool, optional, defaults to True) —
Fold round-tripped state tensors (KV cache, SSM states, …) into internal OV
variables (
ReadValue/Assign`). The runtime then carries state across `infer()` calls instead of marshalling cache tensors through inputs/outputs on every step, and a fused `beam_idxinput reorders state in-graph for beam search. No-op for models without round-tripped state (encoders, prefill-only exports). Set it to False for targets that take no stateful model, such as the NPU plugin.
Configuration class for exporting models to OpenVINO IR via openvino.convert_model.
Inherits all fields from [DynamoConfig] (dynamic, strict, dynamic_shapes, prefer_deferred_runtime_asserts_over_guards).
Quantizers
class transformers.exporters.ExportQuantizer
< source >( calibration_dataset: Iterable[dict[str, Any]] | None = None )
Parameters
- calibration_dataset (
Iterable[dict], optional) — Input dicts the quantizer calibrates on: a list, or aDataLoaderwhose batches collate to model inputs. For~HfExporter.export_for_generationthey are generate kwargs, captured into a calibration set per component. WhenNone, a quantizer that needs data calibrates on the export’s own sample inputs, with a warning.
Base class for post-training quantizers applied during export.
A quantizer declares the export formats it supports and the packages it needs (with the versions it is tested on,
like the exporters) and whether it quantizes the torch.export FX graph, before any conversion (so every backend
takes the result), or the model a backend converts it into (onnx_ir.Model, openvino.Model). The exporter
validates it against the export up front, then calls ~ExportQuantizer.quantize with that model and the export’s
sample inputs. Subclass it and implement quantize to add a new quantization method; a CalibrationSet maps the
calibration samples to the model’s own inputs.
Quantize model (the FX graph if quantizes_fx_graph, else the backend model) and return the result,
calibrated on calibration_dataset, or on the export’s sample_inputs when it has none.
Raise if this quantizer can’t run on an export_format export, or a package it needs is missing or too old;
warn when one differs from the version it is tested on.
A copy of this quantizer that calibrates on calibration_dataset.
class transformers.exporters.quantizers.CalibrationSet
< source >( calibration_dataset: Iterable[dict[str, Any]] | Nonesample_inputs: dict[str, Any]transform: Callable[[dict[str, Any]], Any] )
Re-iterable view of calibration samples as model inputs.
The samples are the quantizer’s calibration_dataset, or the export’s own sample_inputs (with a warning, once
they are read) when it has none. They can be any mapping, such as a tokenizer’s BatchEncoding. transform maps
each forward-kwarg sample to what the quantized model takes (traced kwargs, ONNX feeds, OpenVINO
port feeds), lazily, one sample at a time, on every pass.
class transformers.exporters.PT2EQuantizer
< source >( quantizer: Anycalibration_dataset: Iterable[dict[str, Any]] | None = None )
Parameters
- quantizer (
torchao.quantization.pt2e.quantizer.Quantizer) — The PT2E quantizer that annotates the graph. Its quantize/dequantize ops must be ones the target backend supports:X86InductorQuantizerfor inductor, ONNX (QDQ) or OpenVINO,XNNPACKQuantizerfor ExecuTorch. - calibration_dataset (
Iterable[dict], optional) — Input dicts the observers calibrate on (seeExportQuantizer), one forward each. To calibrate on batches, pass aDataLoaderthat collates the samples into batched input dicts instead of a list of single samples.
Quantize the FX graph with PyTorch 2 Export (PT2E) quantization: prepare_pt2e inserts observers, the calibration set drives them, and convert_pt2e replaces them with
quantize/dequantize ops. Works with every export backend.
Example:
>>> from torchao.quantization.pt2e.quantizer.x86_inductor_quantizer import (
... X86InductorQuantizer,
... get_default_x86_inductor_quantization_config,
... )
>>> from transformers.exporters import DynamoConfig, PT2EQuantizer
>>> x86 = X86InductorQuantizer().set_global(get_default_x86_inductor_quantization_config())
>>> DynamoConfig(quantizer=PT2EQuantizer(x86, calibration_dataset=samples))class transformers.exporters.OnnxRuntimeQuantizer
< source >( config: OnnxRuntimeStaticConfig | OnnxRuntimeDynamicConfig | None = Nonecalibration_dataset: Iterable[dict[str, Any]] | None = None )
Quantize the converted ONNX model with ONNX Runtime’s own tools (onnxruntime.quantization): quantize_static with an OnnxRuntimeStaticConfig (the default), or quantize_dynamic with an OnnxRuntimeDynamicConfig.
Example:
>>> from transformers.exporters import (
... OnnxConfig,
... OnnxRuntimeDynamicConfig,
... OnnxRuntimeQuantizer,
... OnnxRuntimeStaticConfig,
... )
>>> static = OnnxRuntimeStaticConfig(per_channel=True)
>>> OnnxConfig(quantizer=OnnxRuntimeQuantizer(static, calibration_dataset=samples))
>>> OnnxConfig(quantizer=OnnxRuntimeQuantizer(OnnxRuntimeDynamicConfig()))class transformers.exporters.OnnxRuntimeStaticConfig
< source >( quant_format: Any = Noneop_types_to_quantize: list[str] | None = Noneper_channel: bool | None = Nonereduce_range: bool | None = Noneactivation_type: Any = Noneweight_type: Any = Nonenodes_to_quantize: list[str] | None = Nonenodes_to_exclude: list[str] | None = Nonecalibrate_method: Any = Nonecalibration_providers: list[str] | None = Noneextra_options: dict[str, Any] | None = None )
Arguments of onnxruntime.quantization.quantize_static: int8 activations and weights (QDQ by default), calibrated
on the quantizer’s calibration_dataset. A field left to None keeps ONNX Runtime’s default. See quantize_static for each one.
class transformers.exporters.OnnxRuntimeDynamicConfig
< source >( op_types_to_quantize: list[str] | None = Noneper_channel: bool | None = Nonereduce_range: bool | None = Noneweight_type: Any = Nonenodes_to_quantize: list[str] | None = Nonenodes_to_exclude: list[str] | None = Noneextra_options: dict[str, Any] | None = None )
Arguments of onnxruntime.quantization.quantize_dynamic: int8 weights, activations quantized at runtime, no
calibration. A field left to None keeps ONNX Runtime’s default. See quantize_dynamic for each one.
class transformers.exporters.NNCFOpenVINOQuantizer
< source >( config: NNCFQuantizationConfig | NNCFWeightCompressionConfig | None = Nonecalibration_dataset: Iterable[dict[str, Any]] | None = None )
Quantize the converted OpenVINO model with NNCF: nncf.quantize with a NNCFQuantizationConfig (the default), or nncf.compress_weights with a NNCFWeightCompressionConfig.
Example:
>>> import nncf
>>> from transformers.exporters import NNCFOpenVINOQuantizer, NNCFWeightCompressionConfig, OpenVINOConfig
>>> OpenVINOConfig(quantizer=NNCFOpenVINOQuantizer(calibration_dataset=samples))
>>> OpenVINOConfig(
... quantizer=NNCFOpenVINOQuantizer(NNCFWeightCompressionConfig(mode=nncf.CompressWeightsMode.INT4_SYM))
... )class transformers.exporters.NNCFOnnxQuantizer
< source >( config: NNCFQuantizationConfig | NNCFWeightCompressionConfig | None = Nonecalibration_dataset: Iterable[dict[str, Any]] | None = None )
Quantize the converted ONNX model with NNCF through its ONNX backend: nncf.quantize with a NNCFQuantizationConfig (the default, int8 QDQ), or nncf.compress_weights with a NNCFWeightCompressionConfig (int4 as ONNX Runtime’s MatMulNBits).
Example:
>>> import nncf
>>> from transformers.exporters import NNCFOnnxQuantizer, NNCFWeightCompressionConfig, OnnxConfig
>>> OnnxConfig(quantizer=NNCFOnnxQuantizer(calibration_dataset=samples))
>>> OnnxConfig(quantizer=NNCFOnnxQuantizer(NNCFWeightCompressionConfig(mode=nncf.CompressWeightsMode.INT4_SYM)))class transformers.exporters.NNCFTorchFXQuantizer
< source >( config: NNCFQuantizationConfig | NNCFWeightCompressionConfig | None = Nonecalibration_dataset: Iterable[dict[str, Any]] | None = None )
Quantize the torch.export FX graph with NNCF through its TorchFX
backend: nncf.quantize with a NNCFQuantizationConfig (the default, quantize/dequantize ops), or nncf.compress_weights with a NNCFWeightCompressionConfig. Like PT2EQuantizer, it runs before any
conversion, so every backend takes its result. ExecuTorch lowers only the weight-only result: XNNPACK doesn’t
delegate the quantize/dequantize ops, and ExecuTorch has no kernels for them.
class transformers.exporters.NNCFQuantizationConfig
< source >( mode: Any = Nonepreset: Any = Nonetarget_device: Any = Nonesubset_size: int | None = Nonefast_bias_correction: bool | None = Nonemodel_type: Any = Noneignored_scope: Any = Noneadvanced_parameters: Any = None )
Arguments of nncf.quantize: int8 activations and weights, calibrated on the quantizer’s calibration_dataset.
A field left to None keeps NNCF’s default, except model_type, which defaults to nncf.ModelType.TRANSFORMER.
See nncf.quantize for each one.
class transformers.exporters.NNCFWeightCompressionConfig
< source >( mode: Any = Noneratio: float | None = Nonegroup_size: int | None = Noneignored_scope: Any = Noneall_layers: bool | None = Nonesensitivity_metric: Any = Nonesubset_size: int | None = Noneawq: bool | None = Nonescale_estimation: bool | None = Nonegptq: bool | None = Nonelora_correction: bool | None = Nonebackup_mode: Any = Nonecompression_format: Any = Noneadvanced_parameters: Any = None )
Arguments of nncf.compress_weights: weight-only int8 or int4, with data-aware methods (AWQ, scale estimation,
GPTQ) for the int4 modes. The int8 modes are data-free; the others calibrate on the quantizer’s calibration_dataset. gptq and lora_correction are OpenVINO-only. A field left to None keeps NNCF’s
default. See nncf.compress_weights for
each one.
Utilities
Lower-level functions that power export_for_generation, useful when you need to intervene
between decomposing a model and exporting each component.
transformers.exporters.utils.get_leaf_tensors
< source >( obj: Any ) → dict[str, torch.Tensor]
Recursively retrieve all leaf tensors from a potentially nested structure.
transformers.exporters.utils.prepare_for_export
< source >( model: PreTrainedModel | torch.nn.Moduleinputs: MutableMapping[str, Any] )
Configure model and inputs for export. Mutates both model and inputs in place,
returning (model, inputs, output_flags) where output_flags holds the values popped
from inputs for use_cache, return_dict, etc. (to be applied reversibly onto model.config by patch_model_config during the trace).
- Strips label inputs (
labels,future_values) — loss computation is unsupported. - Pops output flags (
use_cache,return_dict, …) frominputsso they don’t appear as traced kwargs; the values are returned for the trace block to apply ontomodel.config. - Pre-computes data-dependent vision/audio kwargs registered via
@register_export_input_preparerand writes them intoinputs. - Casts input tensors to match the model’s
dtype/device.
transformers.exporters.utils.decompose_prefill_decode
< source >( model: PreTrainedModelinputs: dict[str, Any]generation_config: Any = Nonemulti_token_decode: bool = False ) → dict[str, tuple[torch.nn.Module, dict]]
Returns
dict[str, tuple[torch.nn.Module, dict]]
{"prefill": (model, prefill_inputs), "decode": (model, decode_inputs)}.
Run model.generate() and capture prefill and decode inputs.
Reuses the full generation machinery so every architecture (decoder-only, SSM, encoder-decoder, multi-modal, …) gets correct inputs without reimplementing the loop.
generation_config is forwarded to generate() (defaulting to the model’s own), so the captured
inputs use whatever cache generate() would build. Pass one with cache_implementation="static" and max_cache_len=N to capture a statically sized cache in the decode inputs — the basis for
a static-cache export. max_cache_len sizes the cache independently of the capture, so the
exported decode takes a fixed [..., N, ...] cache rather than a growing one.
When multi_token_decode, the decode component is captured as a multi-token decode — two
consecutive decode steps merged (see _merge_decode_calls) so its query-sequence axis stays
symbolic (a single-token decode would specialize that axis to 1). It then handles both one token
(ordinary decoding) and many (continuation-from-past, or a plain prefill when the cache is empty). Otherwise decode is the
classic single-token decode.
transformers.exporters.utils.decompose_multimodal
< source >( model: PreTrainedModelinputs: dict[str, Any] ) → dict[str, tuple[torch.nn.Module, dict]]
Returns
dict[str, tuple[torch.nn.Module, dict]]
One name: (module, inputs)
entry per detected submodule (image/audio encoder, projector, language model, lm_head).
Raises
ValueError
ValueError— if no known multi-modal submodules are found on the model.
Capture inputs to each multi-modal submodule via a single forward pass.
Detects all known multi-modal submodules by attribute name (vision tower, projector,
language model, lm_head, …) and captures their forward kwargs during one model(**inputs) call.
Each submodule is returned as a separate name: (module, inputs) entry for
independent export. The token-merge step (e.g. masked_scatter for multi-modal models)
is intentionally left outside the exported graphs — it is the caller’s responsibility
to assemble inputs_embeds from the encoder outputs before running the decoder.
transformers.exporters.utils.decompose_for_generation
< source >( model: PreTrainedModelinputs: dict[str, Any]generation_config: Any = Nonemulti_token_decode: bool = False ) → `{component_name
Parameters
- model — Generative model. Must support
model.generate(**inputs). - inputs — Generate kwargs — what you’d pass to
model.generate(**inputs). - generation_config — Optional
GenerationConfigforwarded togenerate()during capture. Pass one withcache_implementation="static"+max_cache_len=Nto export against a statically sized cache (seedecompose_prefill_decode). - multi_token_decode — When
True, capture thedecodecomponent as a multi-token decode (dynamic query sequence axis: multiple tokens at once — continuation-from-past, or a plain prefill when the cache is empty); a single-token decode can’t stay dynamic (seedecompose_prefill_decode).
Returns
`{component_name
(submodel, forward_inputs)}. Keys are “prefill”/“decode”for plain generative models and”/“multi_modal_projector”/“language_model”/“lm_head”/“decode”` for multi-modal generative models.
Decompose a generative model into independently exportable (model, forward_inputs) pairs.
Runs decompose_prefill_decode to capture prefill and decode forward kwargs from a real model.generate(**inputs, max_new_tokens=2). If the prefill is multi-modal (per is_multimodal),
further splits it into one entry per submodule (vision/audio encoder, projector, language model, lm_head) via decompose_multimodal.
Returns True if the model is multi-modal with modal encoders and a language model.
A non-PreTrainedModel (e.g. a bare nn.Module) has no canonical get_encoder/get_decoder accessors and is trivially not multi-modal, so it short-circuits to False.