code: def export_pytorch(
      model: Union["PreTrainedModel", "ModelMixin"],
      config: OnnxConfig,
      opset: int,
      output: Path,
      device: str = "cpu",
      dtype: Optional["torch.dtype"] = None,
      input_shapes: Optional[Dict] = None,
      model_kwargs: Optional[Dict[str, Any]] = None,
  ) -> Tuple[List[str], List[str]]:
      """
      Exports a PyTorch model to an ONNX Intermediate Representation.
  
      Args:
          model ([`PreTrainedModel`]):
              The model to export.
          config ([`~exporters.onnx.config.OnnxConfig`]):
              The ONNX configuration associated with the exported model.
          opset (`int`):
              The version of the ONNX operator set to use.
          output (`Path`):
              Path to save the exported ONNX file to.
          device (`str`, defaults to `"cpu"`):
              The device on which the ONNX model will be exported. Either `cpu` or `cuda`. Only PyTorch is supported for
              export on CUDA devices.
          dtype (`Optional[torch.dtype]`, defaults to `None`):
              Data type to remap the model inputs to. PyTorch-only. Only `torch.float16` is supported.
          input_shapes (`Optional[Dict]`, defaults to `None`):
              If specified, allows to use specific shapes for the example input provided to the ONNX exporter.
          model_kwargs (`Optional[Dict[str, Any]]`, defaults to `None`):
              Experimental usage: keyword arguments to pass to the model during
              the export. This argument should be used along the `custom_onnx_config` argument
              in case, for example, the model inputs/outputs are changed (for example, if
              `model_kwargs={"output_attentions": True}` is passed).
  
      Returns:
          `Tuple[List[str], List[str]]`: A tuple with an ordered list of the model's inputs, and the named outputs from
          the ONNX configuration.
      """
      from torch.onnx import export as onnx_export
      from torch.utils._pytree import tree_map
  
      logger.info(f"Using framework PyTorch: {torch.__version__}")
      FORCE_ONNX_EXTERNAL_DATA = (
          os.getenv("FORCE_ONNX_EXTERNAL_DATA", "0") == "1"
      )
  
      with torch.no_grad():
          model.config.return_dict = True
          model = model.eval()
  
          # Check if we need to override certain configuration item
          if config.values_override is not None:
              logger.info(
                  f"Overriding {len(config.values_override)} configuration item(s)"
              )
              for (
                  override_config_key,
                  override_config_value,
              ) in config.values_override.items():
                  logger.info(
                      f"\t- {override_config_key} -> {override_config_value}"
                  )
                  setattr(
                      model.config,
                      override_config_key,
                      override_config_value,
                  )
  
          if input_shapes is None:
              input_shapes = (
                  {}
              )  # will use the defaults from DEFAULT_DUMMY_SHAPES
  
          # Check that inputs match, and order them properly
          dummy_inputs = config.generate_dummy_inputs(
              framework="pt", **input_shapes
          )
  
          device = torch.device(device)
  
          def remap(value):
              if isinstance(value, torch.Tensor):
                  value = value.to(device)
  
              return value
  
          if device.type == "cuda" and torch.cuda.is_available():
              model.to(device)
              dummy_inputs = tree_map(remap, dummy_inputs)
  
          dummy_inputs = config.rename_ambiguous_inputs(dummy_inputs)
  
          with config.patch_model_for_export(
              model, model_kwargs=model_kwargs
          ):
              check_dummy_inputs_are_allowed(model, dummy_inputs)
  
              inputs = config.ordered_inputs(model)
              input_names = list(inputs.keys())
              output_names = list(config.outputs.keys())
  
              # Export can work with named args but the dict containing named args has to be the last element of the args
              # tuple.
              onnx_export(
                  model,
                  (dummy_inputs,),
                  f=output.as_posix(),
                  input_names=input_names,
                  output_names=output_names,
                  dynamic_axes=dict(
                      chain(inputs.items(), config.outputs.items())
                  ),
                  do_constant_folding=True,
                  opset_version=opset,
              )
  
          # check if external data was exported
          # TODO: this is quite inefficient as we load in memory if models are <2GB without external data
          onnx_model = onnx.load(str(output), load_external_data=False)
          model_uses_external_data = check_model_uses_external_data(
              onnx_model
          )
  
          if model_uses_external_data or FORCE_ONNX_EXTERNAL_DATA:
              tensors_paths = _get_onnx_external_data_tensors(
                  onnx_model
              )
              logger.info("Saving external data to one file...")
  
              # try free model memory
              del model
              del onnx_model
              gc.collect()
              if device.type == "cuda" and torch.cuda.is_available():
                  torch.cuda.empty_cache()
  
              onnx_model = onnx.load(
                  str(output), load_external_data=True
              )  # this will probably be too memory heavy for large models
              onnx.save(
                  onnx_model,
                  str(output),
                  save_as_external_data=True,
                  all_tensors_to_one_file=True,
                  location=output.name + "_data",
                  size_threshold=1024
                  if not FORCE_ONNX_EXTERNAL_DATA
                  else 0,
              )
  
              # delete previous external data
              for tensor in tensors_paths:
                  os.remove(output.parent / tensor)
  
      return input_names, output_names
  
imports: import copy
  import gc
  import multiprocessing
  import os
  import traceback
  from inspect import signature
  from itertools import chain
  from pathlib import Path
  from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
  import numpy
  import onnx
  from transformers.utils import is_tf_available, is_torch_available
  from ...onnx.utils import _get_onnx_external_data_tensors, check_model_uses_external_data
  from ...utils import TORCH_MINIMUM_VERSION, is_diffusers_available, is_torch_onnx_support_available, logging, require_numpy_strictly_lower
  from ..error_utils import AtolError, MinimumVersionError, OutputMatchError, ShapeError
  from .base import OnnxConfig
  from .model_configs import SpeechT5OnnxConfig
  from .utils import PickableInferenceSession, recursive_to_device
label_desc: Use image node_id 5 for calling a global function with example usage: export_pytorch(model, config, opset, output, device, dtype, input_shapes, model_kwargs) and returns: input_names,  output_names, value