# ONNX Runtime Models

## Models

### Generic model classes

The following ORT classes are available for instantiating a base model class without a specific head.

#### ORTModel

#### class optimum.onnxruntime.ORTModel

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L138)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

Base class for implementing models using ONNX Runtime.

The ORTModel implements generic methods for interacting with the BOINC AI Hub as well as exporting vanilla transformers models to ONNX using `optimum.exporters.onnx` toolchain.

Class attributes:

* model\_type (`str`, *optional*, defaults to `"onnx_model"`) — The name of the model type to use when registering the ORTModel classes.
* auto\_model\_class (`Type`, *optional*, defaults to `AutoModel`) — The “AutoModel” class to represented by the current ORTModel class.

Common attributes:

* model (`ort.InferenceSession`) — The ONNX Runtime InferenceSession that is running the model.
* config ([PretrainedConfig](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig) — The configuration of the model.
* use\_io\_binding (`bool`, *optional*, defaults to `True`) — Whether to use I/O bindings with **ONNX Runtime with the CUDAExecutionProvider**, this can significantly speedup inference depending on the task.
* model\_save\_dir (`Path`) — The directory where the model exported to ONNX is saved. By defaults, if the loaded model is local, the directory where the original model will be used. Otherwise, the cache directory is used.
* providers (\`List\[str]) — The list of execution providers available to ONNX Runtime.

**from\_pretrained**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L573)

( model\_id: typing.Union\[str, pathlib.Path]export: bool = Falseforce\_download: bool = Falseuse\_auth\_token: typing.Optional\[str] = Nonecache\_dir: typing.Optional\[str] = Nonesubfolder: str = ''config: typing.Optional\[ForwardRef('PretrainedConfig')] = Nonelocal\_files\_only: bool = Falseprovider: str = 'CPUExecutionProvider'session\_options: typing.Optional\[onnxruntime.capi.onnxruntime\_pybind11\_state.SessionOptions] = Noneprovider\_options: typing.Union\[typing.Dict\[str, typing.Any], NoneType] = Noneuse\_io\_binding: typing.Optional\[bool] = None\*\*kwargs ) → `ORTModel`

Parameters

* **model\_id** (`Union[str, Path]`) — Can be either:
  * A string, the *model id* of a pretrained model hosted inside a model repo on boincai.com. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
  * A path to a *directory* containing a model saved using `~OptimizedModel.save_pretrained`, e.g., `./my_model_directory/`.
* **from\_transformers** (`bool`, defaults to `False`) — Defines whether the provided `model_id` contains a vanilla Transformers checkpoint.
* **force\_download** (`bool`, defaults to `True`) — Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.
* **use\_auth\_token** (`Optional[str]`, defaults to `None`) — The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `transformers-cli login` (stored in `~/.boincai`).
* **cache\_dir** (`Optional[str]`, defaults to `None`) — Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
* **subfolder** (`str`, defaults to `""`) — In case the relevant files are located inside a subfolder of the model repo either locally or on boincai.com, you can specify the folder name here.
* **config** (`Optional[transformers.PretrainedConfig]`, defaults to `None`) — The model configuration.
* **local\_files\_only** (`Optional[bool]`, defaults to `False`) — Whether or not to only look at local files (i.e., do not try to download the model).
* **trust\_remote\_code** (`bool`, defaults to `False`) — Whether or not to allow for custom code defined on the Hub in their own modeling. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine.
* **provider** (`str`, defaults to `"CPUExecutionProvider"`) — ONNX Runtime provider to use for loading the model. See <https://onnxruntime.ai/docs/execution-providers/> for possible providers.
* **session\_options** (`Optional[onnxruntime.SessionOptions]`, defaults to `None`), — ONNX Runtime session options to use for loading the model.
* **provider\_options** (`Optional[Dict[str, Any]]`, defaults to `None`) — Provider option dictionaries corresponding to the provider used. See available options for each provider: <https://onnxruntime.ai/docs/api/c/group___global.html> .
* **use\_io\_binding** (`Optional[bool]`, defaults to `None`) — Whether to use IOBinding during inference to avoid memory copy between the host and device, or between numpy/torch tensors and ONNX Runtime ORTValue. Defaults to `True` if the execution provider is CUDAExecutionProvider. For \[\~onnxruntime.ORTModelForCausalLM], defaults to `True` on CPUExecutionProvider, in all other cases defaults to `False`.
* **kwargs** (`Dict[str, Any]`) — Will be passed to the underlying model loading methods.

Parameters for decoder models (ORTModelForCausalLM, ORTModelForSeq2SeqLM, ORTModelForSeq2SeqLM, ORTModelForSpeechSeq2Seq, ORTModelForVision2Seq)

* **use\_cache** (`Optional[bool]`, defaults to `True`) — Whether or not past key/values cache should be used. Defaults to `True`.

Parameters for ORTModelForCausalLM

* **use\_merged** (`Optional[bool]`, defaults to `None`) — whether or not to use a single ONNX that handles both the decoding without and with past key values reuse. This option defaults to `True` if loading from a local repository and a merged decoder is found. When exporting with `export=True`, defaults to `False`. This option should be set to `True` to minimize memory usage.

Returns

`ORTModel`

The loaded ORTModel model.

Instantiate a pretrained model from a pre-trained model configuration.

**load\_model**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L330)

( path: typing.Union\[str, pathlib.Path]provider: str = 'CPUExecutionProvider'session\_options: typing.Optional\[onnxruntime.capi.onnxruntime\_pybind11\_state.SessionOptions] = Noneprovider\_options: typing.Union\[typing.Dict\[str, typing.Any], NoneType] = None )

Parameters

* **path** (`Union[str, Path]`) — Path of the ONNX model.
* **provider** (`str`, defaults to `"CPUExecutionProvider"`) — ONNX Runtime provider to use for loading the model. See <https://onnxruntime.ai/docs/execution-providers/> for possible providers.
* **session\_options** (`Optional[onnxruntime.SessionOptions]`, defaults to `None`) — ONNX Runtime session options to use for loading the model.
* **provider\_options** (`Optional[Dict[str, Any]]`, defaults to `None`) — Provider option dictionary corresponding to the provider used. See available options for each provider: <https://onnxruntime.ai/docs/api/c/group___global.html> .

Loads an ONNX Inference session with a given provider. Default provider is `CPUExecutionProvider` to match the default behaviour in PyTorch/TensorFlow/JAX.

**raise\_on\_numpy\_input\_io\_binding**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L792)

( use\_torch: bool )

Parameters

* **use\_torch** (`bool`) — Whether the tensor used during inference are of type torch.Tensor or not.

Raises an error if IO Binding is requested although the tensor used are numpy arrays.

**shared\_attributes\_init**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L181)

( model: InferenceSessionuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

Initializes attributes that may be shared among several ONNX Runtime inference sesssions.

**to**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L294)

( device: typing.Union\[torch.device, str, int] ) → `ORTModel`

Parameters

* **device** (`torch.device` or `str` or `int`) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native `torch.device` or a `str` too.

Returns

`ORTModel`

the model placed on the requested device.

Changes the ONNX Runtime provider according to the device.

### Natural Language Processing

The following ORT classes are available for the following natural language processing tasks.

#### ORTModelForCausalLM

#### class optimum.onnxruntime.ORTModelForCausalLM

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_decoder.py#L115)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = Noneuse\_cache: typing.Optional\[bool] = None\*\*kwargs )

ONNX model with a causal language modeling head for ONNX Runtime inference. This class officially supports bloom, codegen, falcon, gpt2, gpt\_bigcode, gpt\_neo, gpt\_neox, gptj, llama.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_decoder.py#L179)

( input\_ids: LongTensorattention\_mask: typing.Optional\[torch.FloatTensor] = Noneposition\_ids: typing.Optional\[torch.LongTensor] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonelabels: typing.Optional\[torch.LongTensor] = Noneuse\_cache\_branch: bool = None\*\*kwargs )

Parameters

* **input\_ids** (`torch.LongTensor`) — Indices of decoder input sequence tokens in the vocabulary of shape `(batch_size, sequence_length)`.
* **attention\_mask** (`torch.LongTensor`) — Mask to avoid performing attention on padding token indices, of shape `(batch_size, sequence_length)`. Mask values selected in `[0, 1]`.
* **past\_key\_values** (`tuple(tuple(torch.FloatTensor), *optional*, defaults to` None`)` — Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding. The tuple is of length `config.n_layers` with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`.

The `ORTModelForCausalLM` 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.

Example of text generation:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForCausalLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/gpt2")
>>> model = ORTModelForCausalLM.from_pretrained("optimum/gpt2")

>>> inputs = tokenizer("My name is Arthur and I live in", return_tensors="pt")

>>> gen_tokens = model.generate(**inputs,do_sample=True,temperature=0.9, min_length=20,max_length=20)
>>> tokenizer.batch_decode(gen_tokens)
```

Example using `transformers.pipelines`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForCausalLM

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/gpt2")
>>> model = ORTModelForCausalLM.from_pretrained("optimum/gpt2")
>>> onnx_gen = pipeline("text-generation", model=model, tokenizer=tokenizer)

>>> text = "My name is Arthur and I live in"
>>> gen = onnx_gen(text)
```

#### ORTModelForMaskedLM

#### class optimum.onnxruntime.ORTModelForMaskedLM

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1000)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a MaskedLMOutput for masked language modeling tasks. This class officially supports albert, bert, camembert, convbert, data2vec\_text, deberta, deberta\_v2, distilbert, electra, flaubert, ibert, mobilebert, roberta, roformer, squeezebert, xlm, xlm\_roberta.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1007)

( input\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Noneattention\_mask: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Nonetoken\_type\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = None\*\*kwargs )

Parameters

* **input\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`](https://huggingface.co/docs/transformers/autoclass_tutorial#autotokenizer). See [`PreTrainedTokenizer.encode`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.encode) and [`PreTrainedTokenizer.__call__`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — 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?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **token\_type\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  * 1 for tokens that are **sentence A**,
  * 0 for tokens that are **sentence B**. [What are token type IDs?](https://huggingface.co/docs/transformers/glossary#token-type-ids)

The `ORTModelForMaskedLM` 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.

Example of feature extraction:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> model = ORTModelForMaskedLM.from_pretrained("optimum/bert-base-uncased-for-fill-mask")

>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="np")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 8, 28996]
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForMaskedLM

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> model = ORTModelForMaskedLM.from_pretrained("optimum/bert-base-uncased-for-fill-mask")
>>> fill_masker = pipeline("fill-mask", model=model, tokenizer=tokenizer)

>>> text = "The capital of France is [MASK]."
>>> pred = fill_masker(text)
```

#### ORTModelForSeq2SeqLM

#### class optimum.onnxruntime.ORTModelForSeq2SeqLM

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1119)

( encoder\_session: InferenceSessiondecoder\_session: InferenceSessionconfig: PretrainedConfigonnx\_paths: typing.List\[str]decoder\_with\_past\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Noneuse\_cache: bool = Trueuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = None\*\*kwargs )

Sequence-to-sequence model with a language modeling head for ONNX Runtime inference. This class officially supports bart, blenderbot, blenderbot\_small, longt5, m2m\_100, marian, mbart, mt5, pegasus, t5.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1173)

( input\_ids: LongTensor = Noneattention\_mask: typing.Optional\[torch.FloatTensor] = Nonedecoder\_input\_ids: typing.Optional\[torch.LongTensor] = Noneencoder\_outputs: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonelabels: typing.Optional\[torch.LongTensor] = None\*\*kwargs )

Parameters

* **input\_ids** (`torch.LongTensor`) — Indices of input sequence tokens in the vocabulary of shape `(batch_size, encoder_sequence_length)`.
* **attention\_mask** (`torch.LongTensor`) — Mask to avoid performing attention on padding token indices, of shape `(batch_size, encoder_sequence_length)`. Mask values selected in `[0, 1]`.
* **decoder\_input\_ids** (`torch.LongTensor`) — Indices of decoder input sequence tokens in the vocabulary of shape `(batch_size, decoder_sequence_length)`.
* **encoder\_outputs** (`torch.FloatTensor`) — The encoder `last_hidden_state` of shape `(batch_size, encoder_sequence_length, hidden_size)`.
* **past\_key\_values** (`tuple(tuple(torch.FloatTensor), *optional*, defaults to` None`)` — Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding. The tuple is of length `config.n_layers` with each tuple having 2 tensors of shape `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)` and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

The `ORTModelForSeq2SeqLM` 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.

Example of text generation:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForSeq2SeqLM

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/t5-small")
>>> model = ORTModelForSeq2SeqLM.from_pretrained("optimum/t5-small")

>>> inputs = tokenizer("My name is Eustache and I like to", return_tensors="pt")

>>> gen_tokens = model.generate(**inputs)
>>> outputs = tokenizer.batch_decode(gen_tokens)
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForSeq2SeqLM

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/t5-small")
>>> model = ORTModelForSeq2SeqLM.from_pretrained("optimum/t5-small")
>>> onnx_translation = pipeline("translation_en_to_de", model=model, tokenizer=tokenizer)

>>> text = "My name is Eustache."
>>> pred = onnx_translation(text)
```

#### ORTModelForSequenceClassification

#### class optimum.onnxruntime.ORTModelForSequenceClassification

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1225)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. This class officially supports albert, bart, bert, camembert, convbert, data2vec\_text, deberta, deberta\_v2, distilbert, electra, flaubert, ibert, mbart, mobilebert, nystromformer, roberta, roformer, squeezebert, xlm, xlm\_roberta.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1233)

( input\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Noneattention\_mask: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Nonetoken\_type\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = None\*\*kwargs )

Parameters

* **input\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`](https://huggingface.co/docs/transformers/autoclass_tutorial#autotokenizer). See [`PreTrainedTokenizer.encode`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.encode) and [`PreTrainedTokenizer.__call__`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — 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?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **token\_type\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  * 1 for tokens that are **sentence A**,
  * 0 for tokens that are **sentence B**. [What are token type IDs?](https://huggingface.co/docs/transformers/glossary#token-type-ids)

The `ORTModelForSequenceClassification` 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.

Example of single-label classification:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForSequenceClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> model = ORTModelForSequenceClassification.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="np")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 2]
```

Example using `transformers.pipelines`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> model = ORTModelForSequenceClassification.from_pretrained("optimum/distilbert-base-uncased-finetuned-sst-2-english")
>>> onnx_classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)

>>> text = "Hello, my dog is cute"
>>> pred = onnx_classifier(text)
```

Example using zero-shot-classification `transformers.pipelines`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/distilbert-base-uncased-mnli")
>>> model = ORTModelForSequenceClassification.from_pretrained("optimum/distilbert-base-uncased-mnli")
>>> onnx_z0 = pipeline("zero-shot-classification", model=model, tokenizer=tokenizer)

>>> sequence_to_classify = "Who are you voting for in 2020?"
>>> candidate_labels = ["Europe", "public health", "politics", "elections"]
>>> pred = onnx_z0(sequence_to_classify, candidate_labels, multi_label=True)
```

#### ORTModelForTokenClassification

#### class optimum.onnxruntime.ORTModelForTokenClassification

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1326)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. This class officially supports albert, bert, bloom, camembert, convbert, data2vec\_text, deberta, deberta\_v2, distilbert, electra, flaubert, gpt2, ibert, mobilebert, roberta, roformer, squeezebert, xlm, xlm\_roberta.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1335)

( input\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Noneattention\_mask: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Nonetoken\_type\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = None\*\*kwargs )

Parameters

* **input\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`](https://huggingface.co/docs/transformers/autoclass_tutorial#autotokenizer). See [`PreTrainedTokenizer.encode`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.encode) and [`PreTrainedTokenizer.__call__`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — 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?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **token\_type\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  * 1 for tokens that are **sentence A**,
  * 0 for tokens that are **sentence B**. [What are token type IDs?](https://huggingface.co/docs/transformers/glossary#token-type-ids)

The `ORTModelForTokenClassification` 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.

Example of token classification:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-NER")
>>> model = ORTModelForTokenClassification.from_pretrained("optimum/bert-base-NER")

>>> inputs = tokenizer("My name is Philipp and I live in Germany.", return_tensors="np")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 12, 9]
```

Example using `transformers.pipelines`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForTokenClassification

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/bert-base-NER")
>>> model = ORTModelForTokenClassification.from_pretrained("optimum/bert-base-NER")
>>> onnx_ner = pipeline("token-classification", model=model, tokenizer=tokenizer)

>>> text = "My name is Philipp and I live in Germany."
>>> pred = onnx_ner(text)
```

#### ORTModelForMultipleChoice

#### class optimum.onnxruntime.ORTModelForMultipleChoice

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1425)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. This class officially supports albert, bert, camembert, convbert, data2vec\_text, deberta\_v2, distilbert, electra, flaubert, ibert, mobilebert, nystromformer, roberta, roformer, squeezebert, xlm, xlm\_roberta.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1433)

( input\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Noneattention\_mask: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Nonetoken\_type\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = None\*\*kwargs )

Parameters

* **input\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`](https://huggingface.co/docs/transformers/autoclass_tutorial#autotokenizer). See [`PreTrainedTokenizer.encode`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.encode) and [`PreTrainedTokenizer.__call__`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — 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?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **token\_type\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  * 1 for tokens that are **sentence A**,
  * 0 for tokens that are **sentence B**. [What are token type IDs?](https://huggingface.co/docs/transformers/glossary#token-type-ids)

The `ORTModelForMultipleChoice` 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.

Example of mutliple choice:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForMultipleChoice

>>> tokenizer = AutoTokenizer.from_pretrained("ehdwns1516/bert-base-uncased_SWAG")
>>> model = ORTModelForMultipleChoice.from_pretrained("ehdwns1516/bert-base-uncased_SWAG", export=True)

>>> num_choices = 4
>>> first_sentence = ["Members of the procession walk down the street holding small horn brass instruments."] * num_choices
>>> second_sentence = [
...     "A drum line passes by walking down the street playing their instruments.",
...     "A drum line has heard approaching them.",
...     "A drum line arrives and they're outside dancing and asleep.",
...     "A drum line turns the lead singer watches the performance."
... ]
>>> inputs = tokenizer(first_sentence, second_sentence, truncation=True, padding=True)

# Unflatten the inputs values expanding it to the shape [batch_size, num_choices, seq_length]
>>> for k, v in inputs.items():
...     inputs[k] = [v[i: i + num_choices] for i in range(0, len(v), num_choices)]
>>> inputs = dict(inputs.convert_to_tensors(tensor_type="pt"))
>>> outputs = model(**inputs)
>>> logits = outputs.logits
```

#### ORTModelForQuestionAnswering

#### class optimum.onnxruntime.ORTModelForQuestionAnswering

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1103)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a QuestionAnsweringModelOutput for extractive question-answering tasks like SQuAD. This class officially supports albert, bart, bert, camembert, convbert, data2vec\_text, deberta, deberta\_v2, distilbert, electra, flaubert, gptj, ibert, mbart, mobilebert, nystromformer, roberta, roformer, squeezebert, xlm, xlm\_roberta.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1110)

( input\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Noneattention\_mask: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Nonetoken\_type\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = None\*\*kwargs )

Parameters

* **input\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`](https://huggingface.co/docs/transformers/autoclass_tutorial#autotokenizer). See [`PreTrainedTokenizer.encode`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.encode) and [`PreTrainedTokenizer.__call__`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — 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?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **token\_type\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  * 1 for tokens that are **sentence A**,
  * 0 for tokens that are **sentence B**. [What are token type IDs?](https://huggingface.co/docs/transformers/glossary#token-type-ids)

The `ORTModelForQuestionAnswering` 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.

Example of question answering:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/roberta-base-squad2")
>>> model = ORTModelForQuestionAnswering.from_pretrained("optimum/roberta-base-squad2")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="np")
>>> start_positions = torch.tensor([1])
>>> end_positions = torch.tensor([3])

>>> outputs = model(**inputs, start_positions=start_positions, end_positions=end_positions)
>>> start_scores = outputs.start_logits
>>> end_scores = outputs.end_logits
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForQuestionAnswering

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/roberta-base-squad2")
>>> model = ORTModelForQuestionAnswering.from_pretrained("optimum/roberta-base-squad2")
>>> onnx_qa = pipeline("question-answering", model=model, tokenizer=tokenizer)

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> pred = onnx_qa(question, text)
```

### Computer vision

The following ORT classes are available for the following computer vision tasks.

#### ORTModelForImageClassification

#### class optimum.onnxruntime.ORTModelForImageClassification

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1531)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model for image-classification tasks. This class officially supports beit, convnext, data2vec\_vision, deit, levit, mobilenet\_v1, mobilenet\_v2, mobilevit, poolformer, resnet, segformer, swin, vit.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1538)

( pixel\_values: typing.Union\[torch.Tensor, numpy.ndarray]\*\*kwargs )

Parameters

* **pixel\_values** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, num_channels, height, width)`, defaults to `None`) — Pixel values corresponding to the images in the current batch. Pixel values can be obtained from encoded images using [`AutoFeatureExtractor`](https://huggingface.co/docs/transformers/autoclass_tutorial#autofeatureextractor).

The `ORTModelForImageClassification` 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.

Example of image classification:

Copied

```
>>> import requests
>>> from PIL import Image
>>> from optimum.onnxruntime import ORTModelForImageClassification
>>> from transformers import AutoFeatureExtractor

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/vit-base-patch16-224")
>>> model = ORTModelForImageClassification.from_pretrained("optimum/vit-base-patch16-224")

>>> inputs = preprocessor(images=image, return_tensors="np")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
```

Example using `transformers.pipeline`:

Copied

```
>>> import requests
>>> from PIL import Image
>>> from transformers import AutoFeatureExtractor, pipeline
>>> from optimum.onnxruntime import ORTModelForImageClassification

>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/vit-base-patch16-224")
>>> model = ORTModelForImageClassification.from_pretrained("optimum/vit-base-patch16-224")
>>> onnx_image_classifier = pipeline("image-classification", model=model, feature_extractor=preprocessor)

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> pred = onnx_image_classifier(url)
```

#### ORTModelForSemanticSegmentation

#### class optimum.onnxruntime.ORTModelForSemanticSegmentation

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1625)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model for semantic-segmentation, with an all-MLP decode head on top e.g. for ADE20k, CityScapes. This class officially supports segformer.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1632)

( \*\*kwargs )

Parameters

* **pixel\_values** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, num_channels, height, width)`, defaults to `None`) — Pixel values corresponding to the images in the current batch. Pixel values can be obtained from encoded images using [`AutoFeatureExtractor`](https://huggingface.co/docs/transformers/autoclass_tutorial#autofeatureextractor).

The `ORTModelForSemanticSegmentation` 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.

Example of semantic segmentation:

Copied

```
>>> import requests
>>> from PIL import Image
>>> from optimum.onnxruntime import ORTModelForSemanticSegmentation
>>> from transformers import AutoFeatureExtractor

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> model = ORTModelForSemanticSegmentation.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")

>>> inputs = preprocessor(images=image, return_tensors="np")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
```

Example using `transformers.pipeline`:

Copied

```
>>> import requests
>>> from PIL import Image
>>> from transformers import AutoFeatureExtractor, pipeline
>>> from optimum.onnxruntime import ORTModelForSemanticSegmentation

>>> preprocessor = AutoFeatureExtractor.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> model = ORTModelForSemanticSegmentation.from_pretrained("optimum/segformer-b0-finetuned-ade-512-512")
>>> onnx_image_segmenter = pipeline("image-segmentation", model=model, feature_extractor=preprocessor)

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> pred = onnx_image_segmenter(url)
```

### Audio

The following ORT classes are available for the following audio tasks.

#### ORTModelForAudioClassification

#### class optimum.onnxruntime.ORTModelForAudioClassification

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1731)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model for audio-classification, with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. This class officially supports audio\_spectrogram\_transformer, data2vec\_audio, hubert, sew, sew\_d, unispeech, unispeech\_sat, wavlm, wav2vec2, wav2vec2-conformer.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1739)

( input\_values: typing.Optional\[torch.Tensor] = Noneattenton\_mask: typing.Optional\[torch.Tensor] = None\*\*kwargs )

Parameters

* **input\_values** (`torch.Tensor` of shape `(batch_size, sequence_length)`) — Float values of input raw speech waveform.. Input values can be obtained from audio file loaded into an array using [`AutoFeatureExtractor`](https://huggingface.co/docs/transformers/autoclass_tutorial#autofeatureextractor).

The `ORTModelForAudioClassification` 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.

Example of audio classification:

Copied

```
>>> from transformers import AutoFeatureExtractor
>>> from optimum.onnxruntime import ORTModelForAudioClassification
>>> from datasets import load_dataset
>>> import torch

>>> dataset = load_dataset("ba-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/hubert-base-superb-ks")
>>> model = ORTModelForAudioClassification.from_pretrained("optimum/hubert-base-superb-ks")

>>> # audio file is decoded on the fly
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_ids = torch.argmax(logits, dim=-1).item()
>>> predicted_label = model.config.id2label[predicted_class_ids]
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoFeatureExtractor, pipeline
>>> from optimum.onnxruntime import ORTModelForAudioClassification

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/hubert-base-superb-ks")
>>> dataset = load_dataset("ba-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")

>>> model = ORTModelForAudioClassification.from_pretrained("optimum/hubert-base-superb-ks")
>>> onnx_ac = pipeline("audio-classification", model=model, feature_extractor=feature_extractor)

>>> pred = onnx_ac(dataset[0]["audio"]["array"])
```

#### ORTModelForAudioFrameClassification

#### class optimum.onnxruntime.ORTModelForAudioFrameClassification

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1989)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a frame classification head on top for tasks like Speaker Diarization. This class officially supports data2vec\_audio, unispeech\_sat, wavlm, wav2vec2, wav2vec2-conformer.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1996)

( input\_values: typing.Optional\[torch.Tensor] = None\*\*kwargs )

Parameters

* **input\_values** (`torch.Tensor` of shape `(batch_size, sequence_length)`) — Float values of input raw speech waveform.. Input values can be obtained from audio file loaded into an array using [`AutoFeatureExtractor`](https://huggingface.co/docs/transformers/autoclass_tutorial#autofeatureextractor).

The `ORTModelForAudioFrameClassification` 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.

Example of audio frame classification:

Copied

```
>>> from transformers import AutoFeatureExtractor
>>> from optimum.onnxruntime import ORTModelForAudioFrameClassification
>>> from datasets import load_dataset
>>> import torch

>>> dataset = load_dataset("ba-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/wav2vec2-base-superb-sd")
>>> model =  ORTModelForAudioFrameClassification.from_pretrained("optimum/wav2vec2-base-superb-sd")

>>> inputs = feature_extractor(dataset[0]["audio"]["array"], return_tensors="pt", sampling_rate=sampling_rate)
>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> probabilities = torch.sigmoid(logits[0])
>>> labels = (probabilities > 0.5).long()
>>> labels[0].tolist()
```

#### ORTModelForCTC

#### class optimum.onnxruntime.ORTModelForCTC

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1817)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with a language modeling head on top for Connectionist Temporal Classification (CTC). This class officially supports data2vec\_audio, hubert, sew, sew\_d, unispeech, unispeech\_sat, wavlm, wav2vec2, wav2vec2-conformer.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1824)

( input\_values: typing.Optional\[torch.Tensor] = None\*\*kwargs )

Parameters

* **input\_values** (`torch.Tensor` of shape `(batch_size, sequence_length)`) — Float values of input raw speech waveform.. Input values can be obtained from audio file loaded into an array using [`AutoFeatureExtractor`](https://huggingface.co/docs/transformers/autoclass_tutorial#autofeatureextractor).

The `ORTModelForCTC` 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.

Example of CTC:

Copied

```
>>> from transformers import AutoProcessor, HubertForCTC
>>> from optimum.onnxruntime import ORTModelForCTC
>>> from datasets import load_dataset
>>> import torch

>>> dataset = load_dataset("ba-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate

>>> processor = AutoProcessor.from_pretrained("optimum/hubert-large-ls960-ft")
>>> model = ORTModelForCTC.from_pretrained("optimum/hubert-large-ls960-ft")

>>> # audio file is decoded on the fly
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
>>> with torch.no_grad():
...     logits = model(**inputs).logits
>>> predicted_ids = torch.argmax(logits, dim=-1)

>>> transcription = processor.batch_decode(predicted_ids)
```

#### ORTModelForSpeechSeq2Seq

#### class optimum.onnxruntime.ORTModelForSpeechSeq2Seq

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1270)

( encoder\_session: InferenceSessiondecoder\_session: InferenceSessionconfig: PretrainedConfigonnx\_paths: typing.List\[str]decoder\_with\_past\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Noneuse\_cache: bool = Trueuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = None\*\*kwargs )

Speech Sequence-to-sequence model with a language modeling head for ONNX Runtime inference. This class officially supports whisper, speech\_to\_text.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1312)

( input\_features: typing.Optional\[torch.FloatTensor] = Noneattention\_mask: typing.Optional\[torch.LongTensor] = Nonedecoder\_input\_ids: typing.Optional\[torch.LongTensor] = Noneencoder\_outputs: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonelabels: typing.Optional\[torch.LongTensor] = None\*\*kwargs )

Parameters

* **input\_features** (`torch.FloatTensor`) — Mel features extracted from the raw speech waveform. `(batch_size, feature_size, encoder_sequence_length)`.
* **decoder\_input\_ids** (`torch.LongTensor`) — Indices of decoder input sequence tokens in the vocabulary of shape `(batch_size, decoder_sequence_length)`.
* **encoder\_outputs** (`torch.FloatTensor`) — The encoder `last_hidden_state` of shape `(batch_size, encoder_sequence_length, hidden_size)`.
* **past\_key\_values** (`tuple(tuple(torch.FloatTensor), *optional*, defaults to` None`)` — Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding. The tuple is of length `config.n_layers` with each tuple having 2 tensors of shape `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)` and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

The `ORTModelForSpeechSeq2Seq` 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.

Example of text generation:

Copied

```
>>> from transformers import AutoProcessor
>>> from optimum.onnxruntime import ORTModelForSpeechSeq2Seq
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("optimum/whisper-tiny.en")
>>> model = ORTModelForSpeechSeq2Seq.from_pretrained("optimum/whisper-tiny.en")

>>> ds = load_dataset("ba-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> inputs = processor.feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")

>>> gen_tokens = model.generate(inputs=inputs.input_features)
>>> outputs = processor.tokenizer.batch_decode(gen_tokens)
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoProcessor, pipeline
>>> from optimum.onnxruntime import ORTModelForSpeechSeq2Seq
>>> from datasets import load_dataset

>>> processor = AutoProcessor.from_pretrained("optimum/whisper-tiny.en")
>>> model = ORTModelForSpeechSeq2Seq.from_pretrained("optimum/whisper-tiny.en")
>>> speech_recognition = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor)

>>> ds = load_dataset("ba-internal-testing/librispeech_asr_dummy", "clean", split="validation")
>>> pred = speech_recognition(ds[0]["audio"]["array"])
```

#### ORTModelForAudioXVector

#### class optimum.onnxruntime.ORTModelForAudioXVector

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1900)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model with an XVector feature extraction head on top for tasks like Speaker Verification. This class officially supports data2vec\_audio, unispeech\_sat, wavlm, wav2vec2, wav2vec2-conformer.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L1907)

( input\_values: typing.Optional\[torch.Tensor] = None\*\*kwargs )

Parameters

* **input\_values** (`torch.Tensor` of shape `(batch_size, sequence_length)`) — Float values of input raw speech waveform.. Input values can be obtained from audio file loaded into an array using [`AutoFeatureExtractor`](https://huggingface.co/docs/transformers/autoclass_tutorial#autofeatureextractor).

The `ORTModelForAudioXVector` 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.

Example of Audio XVector:

Copied

```
>>> from transformers import AutoFeatureExtractor
>>> from optimum.onnxruntime import ORTModelForAudioXVector
>>> from datasets import load_dataset
>>> import torch

>>> dataset = load_dataset("ba-internal-testing/librispeech_asr_demo", "clean", split="validation")
>>> dataset = dataset.sort("id")
>>> sampling_rate = dataset.features["audio"].sampling_rate

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("optimum/wav2vec2-base-superb-sv")
>>> model = ORTModelForAudioXVector.from_pretrained("optimum/wav2vec2-base-superb-sv")

>>> # audio file is decoded on the fly
>>> inputs = feature_extractor(
...     [d["array"] for d in dataset[:2]["audio"]], sampling_rate=sampling_rate, return_tensors="pt", padding=True
... )
>>> with torch.no_grad():
...     embeddings = model(**inputs).embeddings

>>> embeddings = torch.nn.functional.normalize(embeddings, dim=-1).cpu()

>>> cosine_sim = torch.nn.CosineSimilarity(dim=-1)
>>> similarity = cosine_sim(embeddings[0], embeddings[1])
>>> threshold = 0.7
>>> if similarity < threshold:
...     print("Speakers are not the same!")
>>> round(similarity.item(), 2)
```

### Multimodal

The following ORT classes are available for the following multimodal tasks.

#### ORTModelForVision2Seq

#### class optimum.onnxruntime.ORTModelForVision2Seq

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1449)

( encoder\_session: InferenceSessiondecoder\_session: InferenceSessionconfig: PretrainedConfigonnx\_paths: typing.List\[str]decoder\_with\_past\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Noneuse\_cache: bool = Trueuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = None\*\*kwargs )

VisionEncoderDecoder Sequence-to-sequence model with a language modeling head for ONNX Runtime inference. This class officially supports trocr and vision-encoder-decoder.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1507)

( pixel\_values: typing.Optional\[torch.FloatTensor] = Nonedecoder\_input\_ids: typing.Optional\[torch.LongTensor] = Noneencoder\_outputs: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonelabels: typing.Optional\[torch.LongTensor] = None\*\*kwargs )

Parameters

* **pixel\_values** (`torch.FloatTensor`) — Features extracted from an Image. This tensor should be of shape `(batch_size, num_channels, height, width)`.
* **decoder\_input\_ids** (`torch.LongTensor`) — Indices of decoder input sequence tokens in the vocabulary of shape `(batch_size, decoder_sequence_length)`.
* **encoder\_outputs** (`torch.FloatTensor`) — The encoder `last_hidden_state` of shape `(batch_size, encoder_sequence_length, hidden_size)`.
* **past\_key\_values** (`tuple(tuple(torch.FloatTensor), *optional*, defaults to` None`)` — Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding. The tuple is of length `config.n_layers` with each tuple having 2 tensors of shape `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)` and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

The `ORTModelForVision2Seq` 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.

Example of text generation:

Copied

```
>>> from transformers import AutoImageProcessor, AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForVision2Seq
>>> from PIL import Image
>>> import requests


>>> processor = AutoImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> model = ORTModelForVision2Seq.from_pretrained("nlpconnect/vit-gpt2-image-captioning", export=True)

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(image, return_tensors="pt")

>>> gen_tokens = model.generate(**inputs)
>>> outputs = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoImageProcessor, AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForVision2Seq
>>> from PIL import Image
>>> import requests


>>> processor = AutoImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
>>> model = ORTModelForVision2Seq.from_pretrained("nlpconnect/vit-gpt2-image-captioning", export=True)

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_to_text = pipeline("image-to-text", model=model, tokenizer=tokenizer, feature_extractor=processor, image_processor=processor)
>>> pred = image_to_text(image)
```

#### ORTModelForPix2Struct

#### class optimum.onnxruntime.ORTModelForPix2Struct

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1598)

( encoder\_session: InferenceSessiondecoder\_session: InferenceSessionconfig: PretrainedConfigonnx\_paths: typing.List\[str]decoder\_with\_past\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Noneuse\_cache: bool = Trueuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = Nonegeneration\_config: typing.Optional\[transformers.generation.configuration\_utils.GenerationConfig] = None\*\*kwargs )

Pix2struct model with a language modeling head for ONNX Runtime inference. This class officially supports pix2struct.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_seq2seq.py#L1610)

( flattened\_patches: typing.Optional\[torch.FloatTensor] = Noneattention\_mask: typing.Optional\[torch.LongTensor] = Nonedecoder\_input\_ids: typing.Optional\[torch.LongTensor] = Nonedecoder\_attention\_mask: typing.Optional\[torch.BoolTensor] = Noneencoder\_outputs: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonepast\_key\_values: typing.Optional\[typing.Tuple\[typing.Tuple\[torch.Tensor]]] = Nonelabels: typing.Optional\[torch.LongTensor] = None\*\*kwargs )

Parameters

* **flattened\_patches** (`torch.FloatTensor` of shape `(batch_size, seq_length, hidden_size)`) — Flattened pixel patches. the `hidden_size` is obtained by the following formula: `hidden_size` = `num_channels` *`patch_size`* `patch_size` The process of flattening the pixel patches is done by `Pix2StructProcessor`.
* **attention\_mask** (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*) — Mask to avoid performing attention on padding token indices.
* **decoder\_input\_ids** (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*) — Indices of decoder input sequence tokens in the vocabulary. Pix2StructText uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
* **decoder\_attention\_mask** (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*) — Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default.
* **encoder\_outputs** (`tuple(tuple(torch.FloatTensor)`, *optional*) — Tuple consists of (`last_hidden_state`, `optional`: *hidden\_states*, `optional`: *attentions*) `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
* **past\_key\_values** (`tuple(tuple(torch.FloatTensor), *optional*, defaults to` None`)` — Contains the precomputed key and value hidden states of the attention blocks used to speed up decoding. The tuple is of length `config.n_layers` with each tuple having 2 tensors of shape `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)` and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

The `ORTModelForPix2Struct` 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.

Example of pix2struct:

Copied

```
>>> from transformers import AutoProcessor
>>> from optimum.onnxruntime import ORTModelForPix2Struct
>>> from PIL import Image
>>> import requests

>>> processor = AutoProcessor.from_pretrained("google/pix2struct-ai2d-base")
>>> model = ORTModelForPix2Struct.from_pretrained("google/pix2struct-ai2d-base", export=True, use_io_binding=True)

>>> url = "https://boincai.com/datasets/boincai/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> question = "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"
>>> inputs = processor(images=image, text=question, return_tensors="pt")

>>> gen_tokens = model.generate(**inputs)
>>> outputs = processor.batch_decode(gen_tokens, skip_special_tokens=True)
```

### Custom Tasks

The following ORT classes are available for the following custom tasks.

**ORTModelForCustomTasks**

#### class optimum.onnxruntime.ORTModelForCustomTasks

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L2069)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model for any custom tasks. It can be used to leverage the inference acceleration for any single-file ONNX model, that may use custom inputs and outputs.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L2074)

( \*\*kwargs )

The `ORTModelForCustomTasks` 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.

Example of custom tasks(e.g. a sentence transformers taking `pooler_output` as output):

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForCustomTasks

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> model = ORTModelForCustomTasks.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")

>>> inputs = tokenizer("I love burritos!", return_tensors="np")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooler_output = outputs.pooler_output
```

Example using `transformers.pipelines`(only if the task is supported):

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForCustomTasks

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> model = ORTModelForCustomTasks.from_pretrained("optimum/sbert-all-MiniLM-L6-with-pooler")
>>> onnx_extractor = pipeline("feature-extraction", model=model, tokenizer=tokenizer)

>>> text = "I love burritos!"
>>> pred = onnx_extractor(text)
```

**ORTModelForFeatureExtraction**

#### class optimum.onnxruntime.ORTModelForFeatureExtraction

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L892)

( model: InferenceSessionconfig: PretrainedConfiguse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Nonepreprocessors: typing.Optional\[typing.List] = None\*\*kwargs )

ONNX Model for feature-extraction task.

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**forward**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_ort.py#L899)

( input\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Noneattention\_mask: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = Nonetoken\_type\_ids: typing.Union\[torch.Tensor, numpy.ndarray, NoneType] = None\*\*kwargs )

Parameters

* **input\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`](https://huggingface.co/docs/transformers/autoclass_tutorial#autotokenizer). See [`PreTrainedTokenizer.encode`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.encode) and [`PreTrainedTokenizer.__call__`](https://huggingface.co/docs/transformers/main_classes/tokenizer#transformers.PreTrainedTokenizerBase.__call__) for details. [What are input IDs?](https://huggingface.co/docs/transformers/glossary#input-ids)
* **attention\_mask** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — 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?](https://huggingface.co/docs/transformers/glossary#attention-mask)
* **token\_type\_ids** (`Union[torch.Tensor, np.ndarray, None]` of shape `(batch_size, sequence_length)`, defaults to `None`) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:
  * 1 for tokens that are **sentence A**,
  * 0 for tokens that are **sentence B**. [What are token type IDs?](https://huggingface.co/docs/transformers/glossary#token-type-ids)

The `ORTModelForFeatureExtraction` 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.

Example of feature extraction:

Copied

```
>>> from transformers import AutoTokenizer
>>> from optimum.onnxruntime import ORTModelForFeatureExtraction
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> model = ORTModelForFeatureExtraction.from_pretrained("optimum/all-MiniLM-L6-v2")

>>> inputs = tokenizer("My name is Philipp and I live in Germany.", return_tensors="np")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> list(last_hidden_state.shape)
[1, 12, 384]
```

Example using `transformers.pipeline`:

Copied

```
>>> from transformers import AutoTokenizer, pipeline
>>> from optimum.onnxruntime import ORTModelForFeatureExtraction

>>> tokenizer = AutoTokenizer.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> model = ORTModelForFeatureExtraction.from_pretrained("optimum/all-MiniLM-L6-v2")
>>> onnx_extractor = pipeline("feature-extraction", model=model, tokenizer=tokenizer)

>>> text = "My name is Philipp and I live in Germany."
>>> pred = onnx_extractor(text)
```

### Stable Diffusion

**ORTStableDiffusionPipeline**

#### class optimum.onnxruntime.ORTStableDiffusionPipeline

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_diffusion.py#L542)

( vae\_decoder\_session: InferenceSessiontext\_encoder\_session: InferenceSessionunet\_session: InferenceSessionconfig: typing.Dict\[str, typing.Any]tokenizer: CLIPTokenizerscheduler: typing.Union\[diffusers.schedulers.scheduling\_ddim.DDIMScheduler, diffusers.schedulers.scheduling\_pndm.PNDMScheduler, diffusers.schedulers.scheduling\_lms\_discrete.LMSDiscreteScheduler]feature\_extractor: typing.Optional\[transformers.models.clip.feature\_extraction\_clip.CLIPFeatureExtractor] = Nonevae\_encoder\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetext\_encoder\_2\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetokenizer\_2: typing.Optional\[transformers.models.clip.tokenization\_clip.CLIPTokenizer] = Noneuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = None )

ONNX Runtime-powered stable diffusion pipeline corresponding to [diffusers.StableDiffusionPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline).

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/pipelines/diffusers/pipeline_stable_diffusion.py#L202)

( prompt: typing.Union\[str, typing.List\[str], NoneType] = Noneheight: typing.Optional\[int] = Nonewidth: typing.Optional\[int] = Nonenum\_inference\_steps: int = 50guidance\_scale: float = 7.5negative\_prompt: typing.Union\[str, typing.List\[str], NoneType] = Nonenum\_images\_per\_prompt: int = 1eta: float = 0.0generator: typing.Optional\[numpy.random.mtrand.RandomState] = Nonelatents: typing.Optional\[numpy.ndarray] = Noneprompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Noneoutput\_type: str = 'pil'return\_dict: bool = Truecallback: typing.Union\[typing.Callable\[\[int, int, numpy.ndarray], NoneType], NoneType] = Nonecallback\_steps: int = 1guidance\_rescale: float = 0.0 ) → `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

Parameters

* **prompt** (`Optional[Union[str, List[str]]]`, defaults to None) — The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead.
* **height** (`Optional[int]`, defaults to None) — The height in pixels of the generated image.
* **width** (`Optional[int]`, defaults to None) — The width in pixels of the generated image.
* **num\_inference\_steps** (`int`, defaults to 50) — The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
* **guidance\_scale** (`float`, defaults to 7.5) — Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.
* **negative\_prompt** (`Optional[Union[str, list]]`) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **num\_images\_per\_prompt** (`int`, defaults to 1) — The number of images to generate per prompt.
* **eta** (`float`, defaults to 0.0) — Corresponds to parameter eta (η) in the DDIM paper: <https://arxiv.org/abs/2010.02502>. Only applies to `schedulers.DDIMScheduler`, will be ignored for others.
* **generator** (`Optional[np.random.RandomState]`, defaults to `None`) —: A np.random.RandomState to make generation deterministic.
* **latents** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`.
* **prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument.
* **negative\_prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative\_prompt\_embeds will be generated from `negative_prompt` input argument.
* **output\_type** (`str`, defaults to `"pil"`) — The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
* **return\_dict** (`bool`, defaults to `True`) — Whether or not to return a `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` instead of a plain tuple.
* **callback** (Optional\[Callable], defaults to `None`) — A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
* **callback\_steps** (`int`, defaults to 1) — The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step.
* **guidance\_rescale** (`float`, defaults to 0.0) — Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when using zero terminal SNR.

Returns

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of` bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the` safety\_checker\`.

Function invoked when calling the pipeline for generation.

**ORTStableDiffusionImg2ImgPipeline**

#### class optimum.onnxruntime.ORTStableDiffusionImg2ImgPipeline

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_diffusion.py#L551)

( vae\_decoder\_session: InferenceSessiontext\_encoder\_session: InferenceSessionunet\_session: InferenceSessionconfig: typing.Dict\[str, typing.Any]tokenizer: CLIPTokenizerscheduler: typing.Union\[diffusers.schedulers.scheduling\_ddim.DDIMScheduler, diffusers.schedulers.scheduling\_pndm.PNDMScheduler, diffusers.schedulers.scheduling\_lms\_discrete.LMSDiscreteScheduler]feature\_extractor: typing.Optional\[transformers.models.clip.feature\_extraction\_clip.CLIPFeatureExtractor] = Nonevae\_encoder\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetext\_encoder\_2\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetokenizer\_2: typing.Optional\[transformers.models.clip.tokenization\_clip.CLIPTokenizer] = Noneuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = None )

ONNX Runtime-powered stable diffusion pipeline corresponding to [diffusers.StableDiffusionImg2ImgPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/img2img#diffusers.StableDiffusionImg2ImgPipeline).

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/pipelines/diffusers/pipeline_stable_diffusion_img2img.py#L76)

( prompt: typing.Union\[str, typing.List\[str], NoneType] = Noneimage: typing.Union\[numpy.ndarray, PIL.Image.Image] = Nonestrength: float = 0.8num\_inference\_steps: int = 50guidance\_scale: float = 7.5negative\_prompt: typing.Union\[str, typing.List\[str], NoneType] = Nonenum\_images\_per\_prompt: int = 1eta: float = 0.0generator: typing.Optional\[numpy.random.mtrand.RandomState] = Noneprompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Noneoutput\_type: str = 'pil'return\_dict: bool = Truecallback: typing.Union\[typing.Callable\[\[int, int, numpy.ndarray], NoneType], NoneType] = Nonecallback\_steps: int = 1 ) → `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

Parameters

* **prompt** (`Optional[Union[str, List[str]]]`, defaults to None) — The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead.
* **image** (`Union[np.ndarray, PIL.Image.Image]`) — `Image`, or tensor representing an image batch which will be upscaled.
* **strength** (`float`, defaults to 0.8) — Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the `strength`. The number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will be maximum and the denoising process will run for the full number of iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
* **num\_inference\_steps** (`int`, defaults to 50) — The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
* **guidance\_scale** (`float`, defaults to 7.5) — Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.
* **negative\_prompt** (`Optional[Union[str, list]]`) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **num\_images\_per\_prompt** (`int`, defaults to 1) — The number of images to generate per prompt.
* **eta** (`float`, defaults to 0.0) — Corresponds to parameter eta (η) in the DDIM paper: <https://arxiv.org/abs/2010.02502>. Only applies to `schedulers.DDIMScheduler`, will be ignored for others.
* **generator** (`Optional[np.random.RandomState]`, defaults to `None`) —: A np.random.RandomState to make generation deterministic.
* **prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument.
* **negative\_prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative\_prompt\_embeds will be generated from `negative_prompt` input argument.
* **output\_type** (`str`, defaults to `"pil"`) — The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
* **return\_dict** (`bool`, defaults to `True`) — Whether or not to return a `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` instead of a plain tuple.
* **callback** (Optional\[Callable], defaults to `None`) — A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
* **callback\_steps** (`int`, defaults to 1) — The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step.

Returns

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of` bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the` safety\_checker\`.

Function invoked when calling the pipeline for generation.

**ORTStableDiffusionInpaintPipeline**

#### class optimum.onnxruntime.ORTStableDiffusionInpaintPipeline

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_diffusion.py#L560)

( vae\_decoder\_session: InferenceSessiontext\_encoder\_session: InferenceSessionunet\_session: InferenceSessionconfig: typing.Dict\[str, typing.Any]tokenizer: CLIPTokenizerscheduler: typing.Union\[diffusers.schedulers.scheduling\_ddim.DDIMScheduler, diffusers.schedulers.scheduling\_pndm.PNDMScheduler, diffusers.schedulers.scheduling\_lms\_discrete.LMSDiscreteScheduler]feature\_extractor: typing.Optional\[transformers.models.clip.feature\_extraction\_clip.CLIPFeatureExtractor] = Nonevae\_encoder\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetext\_encoder\_2\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetokenizer\_2: typing.Optional\[transformers.models.clip.tokenization\_clip.CLIPTokenizer] = Noneuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = None )

ONNX Runtime-powered stable diffusion pipeline corresponding to [diffusers.StableDiffusionInpaintPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/inpaint#diffusers.StableDiffusionInpaintPipeline).

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/pipelines/diffusers/pipeline_stable_diffusion_inpaint.py#L98)

( prompt: typing.Union\[str, typing.List\[str]]image: Imagemask\_image: Imageheight: typing.Optional\[int] = Nonewidth: typing.Optional\[int] = Nonenum\_inference\_steps: int = 50guidance\_scale: float = 7.5negative\_prompt: typing.Union\[str, typing.List\[str], NoneType] = Nonenum\_images\_per\_prompt: int = 1eta: float = 0.0generator: typing.Optional\[numpy.random.mtrand.RandomState] = Nonelatents: typing.Optional\[numpy.ndarray] = Noneprompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Noneoutput\_type: str = 'pil'return\_dict: bool = Truecallback: typing.Union\[typing.Callable\[\[int, int, numpy.ndarray], NoneType], NoneType] = Nonecallback\_steps: int = 1 ) → `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

Parameters

* **prompt** (`Union[str, List[str]]`) — The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead.
* **image** (`PIL.Image.Image`) — `Image`, or tensor representing an image batch which will be upscaled.
* **mask\_image** (`PIL.Image.Image`) — `Image`, or tensor representing a masked image batch which will be upscaled.
* **height** (`Optional[int]`, defaults to None) — The height in pixels of the generated image.
* **width** (`Optional[int]`, defaults to None) — The width in pixels of the generated image.
* **num\_inference\_steps** (`int`, defaults to 50) — The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
* **guidance\_scale** (`float`, defaults to 7.5) — Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.
* **negative\_prompt** (`Optional[Union[str, list]]`) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **num\_images\_per\_prompt** (`int`, defaults to 1) — The number of images to generate per prompt.
* **eta** (`float`, defaults to 0.0) — Corresponds to parameter eta (η) in the DDIM paper: <https://arxiv.org/abs/2010.02502>. Only applies to `schedulers.DDIMScheduler`, will be ignored for others.
* **generator** (`Optional[np.random.RandomState]`, defaults to `None`) —: A np.random.RandomState to make generation deterministic.
* **latents** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`.
* **prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument.
* **negative\_prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative\_prompt\_embeds will be generated from `negative_prompt` input argument.
* **output\_type** (`str`, defaults to `"pil"`) — The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
* **return\_dict** (`bool`, defaults to `True`) — Whether or not to return a `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` instead of a plain tuple.
* **callback** (Optional\[Callable], defaults to `None`) — A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
* **callback\_steps** (`int`, defaults to 1) — The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step.

Returns

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of` bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the` safety\_checker\`.

Function invoked when calling the pipeline for generation.

**ORTStableDiffusionXLPipeline**

#### class optimum.onnxruntime.ORTStableDiffusionXLPipeline

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_diffusion.py#L627)

( vae\_decoder\_session: InferenceSessiontext\_encoder\_session: InferenceSessionunet\_session: InferenceSessionconfig: typing.Dict\[str, typing.Any]tokenizer: CLIPTokenizerscheduler: typing.Union\[diffusers.schedulers.scheduling\_ddim.DDIMScheduler, diffusers.schedulers.scheduling\_pndm.PNDMScheduler, diffusers.schedulers.scheduling\_lms\_discrete.LMSDiscreteScheduler]feature\_extractor: typing.Optional\[transformers.models.clip.feature\_extraction\_clip.CLIPFeatureExtractor] = Nonevae\_encoder\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetext\_encoder\_2\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetokenizer\_2: typing.Optional\[transformers.models.clip.tokenization\_clip.CLIPTokenizer] = Noneuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Noneadd\_watermarker: typing.Optional\[bool] = None )

ONNX Runtime-powered stable diffusion pipeline corresponding to [diffusers.StableDiffusionXLPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline).

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/pipelines/diffusers/pipeline_stable_diffusion_xl.py#L263)

( prompt: typing.Union\[str, typing.List\[str], NoneType] = Noneheight: typing.Optional\[int] = Nonewidth: typing.Optional\[int] = Nonenum\_inference\_steps: int = 50guidance\_scale: float = 5.0negative\_prompt: typing.Union\[str, typing.List\[str], NoneType] = Nonenum\_images\_per\_prompt: int = 1eta: float = 0.0generator: typing.Optional\[numpy.random.mtrand.RandomState] = Nonelatents: typing.Optional\[numpy.ndarray] = Noneprompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Nonepooled\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_pooled\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Noneoutput\_type: str = 'pil'return\_dict: bool = Truecallback: typing.Union\[typing.Callable\[\[int, int, numpy.ndarray], NoneType], NoneType] = Nonecallback\_steps: int = 1cross\_attention\_kwargs: typing.Union\[typing.Dict\[str, typing.Any], NoneType] = Noneguidance\_rescale: float = 0.0original\_size: typing.Union\[typing.Tuple\[int, int], NoneType] = Nonecrops\_coords\_top\_left: typing.Tuple\[int, int] = (0, 0)target\_size: typing.Union\[typing.Tuple\[int, int], NoneType] = None ) → `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` or `tuple`

Parameters

* **prompt** (`Optional[Union[str, List[str]]]`, defaults to None) — The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead.
* **height** (`Optional[int]`, defaults to None) — The height in pixels of the generated image.
* **width** (`Optional[int]`, defaults to None) — The width in pixels of the generated image.
* **num\_inference\_steps** (`int`, defaults to 50) — The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
* **guidance\_scale** (`float`, defaults to 5) — Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.
* **negative\_prompt** (`Optional[Union[str, list]]`) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **num\_images\_per\_prompt** (`int`, defaults to 1) — The number of images to generate per prompt.
* **eta** (`float`, defaults to 0.0) — Corresponds to parameter eta (η) in the DDIM paper: <https://arxiv.org/abs/2010.02502>. Only applies to `schedulers.DDIMScheduler`, will be ignored for others.
* **generator** (`Optional[np.random.RandomState]`, defaults to `None`) —: A np.random.RandomState to make generation deterministic.
* **latents** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`.
* **prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument.
* **negative\_prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative\_prompt\_embeds will be generated from `negative_prompt` input argument.
* **output\_type** (`str`, defaults to `"pil"`) — The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
* **return\_dict** (`bool`, defaults to `True`) — Whether or not to return a `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` instead of a plain tuple.
* **callback** (Optional\[Callable], defaults to `None`) — A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
* **callback\_steps** (`int`, defaults to 1) — The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step.
* **guidance\_rescale** (`float`, defaults to 0.7) — Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when using zero terminal SNR.

Returns

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` or `tuple`

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of` bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the` safety\_checker\`.

Function invoked when calling the pipeline for generation.

**ORTStableDiffusionXLImg2ImgPipeline**

#### class optimum.onnxruntime.ORTStableDiffusionXLImg2ImgPipeline

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_diffusion.py#L636)

( vae\_decoder\_session: InferenceSessiontext\_encoder\_session: InferenceSessionunet\_session: InferenceSessionconfig: typing.Dict\[str, typing.Any]tokenizer: CLIPTokenizerscheduler: typing.Union\[diffusers.schedulers.scheduling\_ddim.DDIMScheduler, diffusers.schedulers.scheduling\_pndm.PNDMScheduler, diffusers.schedulers.scheduling\_lms\_discrete.LMSDiscreteScheduler]feature\_extractor: typing.Optional\[transformers.models.clip.feature\_extraction\_clip.CLIPFeatureExtractor] = Nonevae\_encoder\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetext\_encoder\_2\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetokenizer\_2: typing.Optional\[transformers.models.clip.tokenization\_clip.CLIPTokenizer] = Noneuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = Noneadd\_watermarker: typing.Optional\[bool] = None )

ONNX Runtime-powered stable diffusion pipeline corresponding to [diffusers.StableDiffusionXLImg2ImgPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLImg2ImgPipeline).

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/pipelines/diffusers/pipeline_stable_diffusion_xl_img2img.py#L267)

( prompt: typing.Union\[str, typing.List\[str], NoneType] = Noneimage: typing.Union\[numpy.ndarray, PIL.Image.Image] = Nonestrength: float = 0.3num\_inference\_steps: int = 50guidance\_scale: float = 5.0negative\_prompt: typing.Union\[str, typing.List\[str], NoneType] = Nonenum\_images\_per\_prompt: int = 1eta: float = 0.0generator: typing.Optional\[numpy.random.mtrand.RandomState] = Nonelatents: typing.Optional\[numpy.ndarray] = Noneprompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Nonepooled\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Nonenegative\_pooled\_prompt\_embeds: typing.Optional\[numpy.ndarray] = Noneoutput\_type: str = 'pil'return\_dict: bool = Truecallback: typing.Union\[typing.Callable\[\[int, int, numpy.ndarray], NoneType], NoneType] = Nonecallback\_steps: int = 1cross\_attention\_kwargs: typing.Union\[typing.Dict\[str, typing.Any], NoneType] = Noneguidance\_rescale: float = 0.0original\_size: typing.Union\[typing.Tuple\[int, int], NoneType] = Nonecrops\_coords\_top\_left: typing.Tuple\[int, int] = (0, 0)target\_size: typing.Union\[typing.Tuple\[int, int], NoneType] = Noneaesthetic\_score: float = 6.0negative\_aesthetic\_score: float = 2.5 ) → `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` or `tuple`

Parameters

* **prompt** (`Optional[Union[str, List[str]]]`, defaults to None) — The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead.
* **image** (`Union[np.ndarray, PIL.Image.Image]`) — `Image`, or tensor representing an image batch which will be upscaled.
* **strength** (`float`, defaults to 0.8) — Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the `strength`. The number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will be maximum and the denoising process will run for the full number of iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
* **num\_inference\_steps** (`int`, defaults to 50) — The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
* **guidance\_scale** (`float`, defaults to 5) — Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.
* **negative\_prompt** (`Optional[Union[str, list]]`) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **num\_images\_per\_prompt** (`int`, defaults to 1) — The number of images to generate per prompt.
* **eta** (`float`, defaults to 0.0) — Corresponds to parameter eta (η) in the DDIM paper: <https://arxiv.org/abs/2010.02502>. Only applies to `schedulers.DDIMScheduler`, will be ignored for others.
* **generator** (`Optional[np.random.RandomState]`, defaults to `None`) —: A np.random.RandomState to make generation deterministic.
* **latents** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`.
* **prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument.
* **negative\_prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative\_prompt\_embeds will be generated from `negative_prompt` input argument.
* **output\_type** (`str`, defaults to `"pil"`) — The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
* **return\_dict** (`bool`, defaults to `True`) — Whether or not to return a `~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` instead of a plain tuple.
* **callback** (Optional\[Callable], defaults to `None`) — A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
* **callback\_steps** (`int`, defaults to 1) — The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step.
* **guidance\_rescale** (`float`, defaults to 0.7) — Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when using zero terminal SNR.

Returns

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` or `tuple`

`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of` bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the` safety\_checker\`.

Function invoked when calling the pipeline for generation.

**ORTLatentConsistencyModelPipeline**

#### class optimum.onnxruntime.ORTLatentConsistencyModelPipeline

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/onnxruntime/modeling_diffusion.py#L569)

( vae\_decoder\_session: InferenceSessiontext\_encoder\_session: InferenceSessionunet\_session: InferenceSessionconfig: typing.Dict\[str, typing.Any]tokenizer: CLIPTokenizerscheduler: typing.Union\[diffusers.schedulers.scheduling\_ddim.DDIMScheduler, diffusers.schedulers.scheduling\_pndm.PNDMScheduler, diffusers.schedulers.scheduling\_lms\_discrete.LMSDiscreteScheduler]feature\_extractor: typing.Optional\[transformers.models.clip.feature\_extraction\_clip.CLIPFeatureExtractor] = Nonevae\_encoder\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetext\_encoder\_2\_session: typing.Optional\[onnxruntime.capi.onnxruntime\_inference\_collection.InferenceSession] = Nonetokenizer\_2: typing.Optional\[transformers.models.clip.tokenization\_clip.CLIPTokenizer] = Noneuse\_io\_binding: typing.Optional\[bool] = Nonemodel\_save\_dir: typing.Union\[str, pathlib.Path, tempfile.TemporaryDirectory, NoneType] = None )

ONNX Runtime-powered stable diffusion pipeline corresponding to [diffusers.LatentConsistencyModelPipeline](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/latent_consistency#diffusers.LatentConsistencyModelPipeline).

This model inherits from [ORTModel](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel), check its documentation for the generic methods the library implements for all its model (such as downloading or saving).

This class should be initialized using the [onnxruntime.modeling\_ort.ORTModel.from\_pretrained()](https://huggingface.co/docs/optimum/main/en/onnxruntime/package_reference/modeling_ort#optimum.onnxruntime.ORTModel.from_pretrained) method.

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/optimum/blob/main/optimum/pipelines/diffusers/pipeline_latent_consistency.py#L30)

( prompt: typing.Union\[str, typing.List\[str], NoneType] = Noneheight: typing.Optional\[int] = Nonewidth: typing.Optional\[int] = Nonenum\_inference\_steps: int = 4original\_inference\_steps: int = Noneguidance\_scale: float = 8.5num\_images\_per\_prompt: int = 1generator: typing.Optional\[numpy.random.mtrand.RandomState] = Nonelatents: typing.Optional\[numpy.ndarray] = Noneprompt\_embeds: typing.Optional\[numpy.ndarray] = Noneoutput\_type: str = 'pil'return\_dict: bool = Truecallback: typing.Union\[typing.Callable\[\[int, int, numpy.ndarray], NoneType], NoneType] = Nonecallback\_steps: int = 1 ) → `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

Parameters

* **prompt** (`Optional[Union[str, List[str]]]`, defaults to None) — The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead.
* **height** (`Optional[int]`, defaults to None) — The height in pixels of the generated image.
* **width** (`Optional[int]`, defaults to None) — The width in pixels of the generated image.
* **num\_inference\_steps** (`int`, defaults to 50) — The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.
* **guidance\_scale** (`float`, defaults to 7.5) — Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.
* **num\_images\_per\_prompt** (`int`, defaults to 1) — The number of images to generate per prompt.
* **generator** (`Optional[np.random.RandomState]`, defaults to `None`) —: A np.random.RandomState to make generation deterministic.
* **latents** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`.
* **prompt\_embeds** (`Optional[np.ndarray]`, defaults to `None`) — Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument.
* **output\_type** (`str`, defaults to `"pil"`) — The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
* **return\_dict** (`bool`, defaults to `True`) — Whether or not to return a `~pipelines.stable_diffusion.StableDiffusionPipelineOutput` instead of a plain tuple.
* **callback** (Optional\[Callable], defaults to `None`) — A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
* **callback\_steps** (`int`, defaults to 1) — The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step.
* **guidance\_rescale** (`float`, defaults to 0.0) — Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when using zero terminal SNR.

Returns

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` or `tuple`

`~pipelines.stable_diffusion.StableDiffusionPipelineOutput` if `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of` bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the` safety\_checker\`.

Function invoked when calling the pipeline for generation.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://boinc-ai.gitbook.io/optimum/onnx-runtime/reference/onnx-runtime-models.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
