快捷方式

torch_tensorrt

函式

torch_tensorrt.compile(module: Any, ir: str = 'default', inputs: Optional[Sequence[Input | torch.Tensor | InputTensorSpec]] = None, arg_inputs: Optional[Sequence[Sequence[Any]]] = None, kwarg_inputs: Optional[dict[Any, Any]] = None, enabled_precisions: Optional[Set[Union[dtype, dtype]]] = None, **kwargs: Any) Union[Module, ScriptModule, GraphModule, Callable[[...], Any]][source]

使用 TensorRT 為 NVIDIA GPU 編譯 PyTorch 模組

取得現有的 PyTorch 模組和一組設定來配置編譯器,並使用 ir 中指定的路徑來降低並將模組編譯為 TensorRT,然後返回一個 PyTorch 模組

專門轉換 Module 的 forward 方法

參數

module (Union(torch.nn.Module,torch.jit.ScriptModule) – 來源模組

關鍵字參數
  • inputs (List[Union(Input, torch.Tensor)]) –

    必要 模組輸入的輸入形狀、dtype 和記憶體佈局的規格清單。 此引數為必要引數。 輸入大小可以指定為 torch 大小、元組或清單。 可以使用 torch 資料類型或 torch_tensorrt 資料類型來指定 dtype,並且可以使用 torch 裝置或 torch_tensorrt 裝置類型列舉來選擇裝置類型。

    inputs=[
        torch_tensorrt.Input((1, 3, 224, 224)), # Static NCHW input shape for input #1
        torch_tensorrt.Input(
            min_shape=(1, 224, 224, 3),
            opt_shape=(1, 512, 512, 3),
            max_shape=(1, 1024, 1024, 3),
            dtype=torch.int32
            format=torch.channel_last
        ), # Dynamic input shape for input #2
        torch.randn((1, 3, 224, 244)) # Use an example tensor and let torch_tensorrt infer settings
    ]
    

  • arg_inputs (Tuple[Any, ...]) – 與 inputs 相同。 用於更好地理解 kwarg_inputs 的別名。

  • kwarg_inputs (dict[Any, ...]) – 可選,模組 forward 函數的 kwarg 輸入。

  • enabled_precision (Set(Union(torch.dpython:type, torch_tensorrt.dpython:type))) – TensorRT 在選擇核心時可以使用的資料類型集合

  • ir (str) – 請求的編譯策略。 (選項:default - 讓 Torch-TensorRT 決定,ts - 具有腳本路徑的 TorchScript)

  • **kwargs – 針對特定請求策略的其他設定(有關更多資訊,請參閱子模組)

回傳

編譯後的模組,執行時將透過 TensorRT 執行

回傳類型

torch.nn.Module

torch_tensorrt.convert_method_to_trt_engine(module: Any, method_name: str = 'forward', inputs: Optional[Sequence[Input | torch.Tensor | InputTensorSpec]] = None, arg_inputs: Optional[Sequence[Sequence[Any]]] = None, kwarg_inputs: Optional[dict[Any, Any]] = None, ir: str = 'default', enabled_precisions: Optional[Set[Union[dtype, dtype]]] = None, **kwargs: Any) bytes[source]

將 TorchScript 模組方法轉換為序列化的 TensorRT 引擎

給定轉換設定的字典,將模組的指定方法轉換為序列化的 TensorRT 引擎

參數

module (Union(torch.nn.Module,torch.jit.ScriptModule) – 來源模組

關鍵字參數
  • inputs (List[Union(Input, torch.Tensor)]) –

    必要 模組輸入的輸入形狀、dtype 和記憶體佈局的規格清單。 此引數為必要引數。 輸入大小可以指定為 torch 大小、元組或清單。 可以使用 torch 資料類型或 torch_tensorrt 資料類型來指定 dtype,並且可以使用 torch 裝置或 torch_tensorrt 裝置類型列舉來選擇裝置類型。

    input=[
        torch_tensorrt.Input((1, 3, 224, 224)), # Static NCHW input shape for input #1
        torch_tensorrt.Input(
            min_shape=(1, 224, 224, 3),
            opt_shape=(1, 512, 512, 3),
            max_shape=(1, 1024, 1024, 3),
            dtype=torch.int32
            format=torch.channel_last
        ), # Dynamic input shape for input #2
        torch.randn((1, 3, 224, 244)) # Use an example tensor and let torch_tensorrt infer settings
    ]
    

  • arg_inputs (Tuple[Any, ...]) – 與 inputs 相同。 用於更好地理解 kwarg_inputs 的別名。

  • kwarg_inputs (dict[Any, ...]) – 可選,模組 forward 函數的 kwarg 輸入。

  • enabled_precision (Set(Union(torch.dpython:type, torch_tensorrt.dpython:type))) – TensorRT 在選擇核心時可以使用的資料類型集合

  • ir (str) – 請求的編譯策略。 (選項:default - 讓 Torch-TensorRT 決定,ts - 具有腳本路徑的 TorchScript)

  • **kwargs – 針對特定請求策略的其他設定(有關更多資訊,請參閱子模組)

回傳

序列化的 TensorRT 引擎,可以儲存到檔案或透過 TensorRT API 反序列化

回傳類型

bytes

torch_tensorrt.save(module: Any, file_path: str = '', *, output_format: str = 'exported_program', inputs: Optional[Sequence[Tensor]] = None, arg_inputs: Optional[Sequence[Tensor]] = None, kwarg_inputs: Optional[dict[str, Any]] = None, retrace: bool = False) None[source]

以指定的輸出格式將模型儲存到磁碟。

參數
  • module (Optional(torch.jit.ScriptModule | torch.export.ExportedProgram | torch.fx.GraphModule | CudaGraphsTorchTensorRTModule)) – 編譯過的 Torch-TensorRT 模組

  • inputs (torch.Tensor) – Torch 輸入張量

  • arg_inputs (Tuple[Any, ...]) – 與 inputs 相同。 用於更好地理解 kwarg_inputs 的別名。

  • kwarg_inputs (dict[Any, ...]) – 可選,模組 forward 函數的 kwarg 輸入。

  • output_format (str) – 儲存模型的格式。選項包含 exported_program | torchscript.

  • retrace (bool) – 當模組類型為 fx.GraphModule 時,此選項會使用 torch.export.export(strict=False) 重新匯出圖形以儲存它。這個標誌目前是實驗性的。

torch_tensorrt.load(file_path: str = '') Any[原始碼]

載入 Torchscript 模型或 ExportedProgram。

從磁碟載入 TorchScript 或 ExportedProgram 檔案。檔案類型將使用 try, except 來檢測類型。

參數

file_path (str) – 磁碟上檔案的路徑

引發

ValueError – 如果沒有檔案,或檔案既不是 TorchScript 檔案也不是 ExportedProgram 檔案

類別

class torch_tensorrt.MutableTorchTensorRTModule(pytorch_model: Module, *, device: Optional[Union[Device, device, str]] = None, disable_tf32: bool = False, assume_dynamic_shape_support: bool = False, sparse_weights: bool = False, enabled_precisions: Set[Union[dtype, dtype]] = {dtype.f32}, engine_capability: EngineCapability = EngineCapability.STANDARD, immutable_weights: bool = True, debug: bool = False, num_avg_timing_iters: int = 1, workspace_size: int = 0, dla_sram_size: int = 1048576, dla_local_dram_size: int = 1073741824, dla_global_dram_size: int = 536870912, truncate_double: bool = False, require_full_compilation: bool = False, min_block_size: int = 5, torch_executed_ops: Optional[Collection[Union[Callable[[...], Any], str]]] = None, torch_executed_modules: Optional[List[str]] = None, pass_through_build_failures: bool = False, max_aux_streams: Optional[int] = None, version_compatible: bool = False, optimization_level: Optional[int] = None, use_python_runtime: bool = False, use_fast_partitioner: bool = True, enable_experimental_decompositions: bool = False, dryrun: bool = False, hardware_compatible: bool = False, timing_cache_path: str = '/tmp/torch_tensorrt_engine_cache/timing_cache.bin', **kwargs: Any)[source]

初始化一個 MutableTorchTensorRTModule,以便無縫地像操作常規 PyTorch 模組一樣操作它。所有 TensorRT 編譯和重新調整過程都會在您使用該模組時自動處理。對其屬性的任何更改或載入不同的 state_dict 都將觸發重新調整或重新編譯,這些操作將在下一次前向傳遞期間進行管理。

MutableTorchTensorRTModule 接受一個 PyTorch 模組和一組編譯器的配置設定。編譯完成後,該模組會保持 TensorRT 圖模組和原始 PyTorch 模組之間的連接。對 MutableTorchTensorRTModule 所做的任何修改都將反映在 TensorRT 圖模組和原始 PyTorch 模組中。

__init__(pytorch_model: Module, *, device: Optional[Union[Device, device, str]] = None, disable_tf32: bool = False, assume_dynamic_shape_support: bool = False, sparse_weights: bool = False, enabled_precisions: Set[Union[dtype, dtype]] = {dtype.f32}, engine_capability: EngineCapability = EngineCapability.STANDARD, immutable_weights: bool = True, debug: bool = False, num_avg_timing_iters: int = 1, workspace_size: int = 0, dla_sram_size: int = 1048576, dla_local_dram_size: int = 1073741824, dla_global_dram_size: int = 536870912, truncate_double: bool = False, require_full_compilation: bool = False, min_block_size: int = 5, torch_executed_ops: Optional[Collection[Union[Callable[[...], Any], str]]] = None, torch_executed_modules: Optional[List[str]] = None, pass_through_build_failures: bool = False, max_aux_streams: Optional[int] = None, version_compatible: bool = False, optimization_level: Optional[int] = None, use_python_runtime: bool = False, use_fast_partitioner: bool = True, enable_experimental_decompositions: bool = False, dryrun: bool = False, hardware_compatible: bool = False, timing_cache_path: str = '/tmp/torch_tensorrt_engine_cache/timing_cache.bin', **kwargs: Any) None[source]
參數

pytorch_model (torch.nn.module) – 需要加速的來源模組

關鍵字參數
  • device (Union(Device, torch.device, dict)) –

    TensorRT 引擎運行的目標裝置

    device=torch_tensorrt.Device("dla:1", allow_gpu_fallback=True)
    

  • disable_tf32 (bool) – 強制 FP32 層使用傳統的 FP32 格式,而不是預設行為(將輸入四捨五入到 10 位尾數,然後再進行乘法運算,但使用 23 位尾數累加總和)

  • assume_dynamic_shape_support (bool) – 將此設定為 true 可啟用轉換器以同時處理動態和靜態形狀。預設值:False

  • sparse_weights (bool) – 為卷積和全連接層啟用稀疏性。

  • enabled_precision (Set(Union(torch.dpython:type, torch_tensorrt.dpython:type))) – TensorRT 在選擇核心時可以使用的資料類型集合

  • immutable_weights (bool) – 構建不可重新調整的引擎。這對於某些不可重新調整的層很有用。

  • debug (bool) – 啟用可偵錯引擎

  • capability (EngineCapability) – 將核心選擇限制為安全 GPU 核心或安全 DLA 核心

  • num_avg_timing_iters (python:int) – 用於選擇核心的平均計時迭代次數

  • workspace_size (python:int) – 給予 TensorRT 的最大工作空間大小

  • dla_sram_size (python:int) – DLA 使用的快速軟體管理 RAM,用於在層內進行通訊。

  • dla_local_dram_size (python:int) – DLA 使用的主機 RAM,用於跨操作共享中間張量資料

  • dla_global_dram_size (python:int) – DLA 使用的主機 RAM,用於儲存權重和執行元資料

  • truncate_double (bool) – 將以 double (float64) 提供的權重截斷為 float32

  • calibrator (Union(torch_tensorrt._C.IInt8Calibrator, tensorrt.IInt8Calibrator)) – 校準器物件,將為 INT8 校準的 PTQ 系統提供資料

  • require_full_compilation (bool) – 要求模組進行端到端編譯,或返回錯誤,而不是返回混合圖,其中無法在 TensorRT 中執行的操作在 PyTorch 中執行

  • min_block_size (python:int) – 為了在 TensorRT 中運行一組操作,所需的連續 TensorRT 可轉換操作的最小數量

  • torch_executed_ops (Collection[Target]) – 必須在 PyTorch 中運行的 aten 運算符集合。如果此集合不為空,但 require_full_compilation 為 True,則會拋出錯誤

  • torch_executed_modules (List[str]) – 必須在 PyTorch 中運行的模組清單。如果此清單不為空,但 require_full_compilation 為 True,則會拋出錯誤

  • pass_through_build_failures (bool) – 如果編譯期間出現問題(僅適用於 torch.compile 工作流程),則會發生錯誤

  • max_aux_stream (Optional[python:int]) – 引擎中的最大串流數量

  • version_compatible (bool) – 構建與未來 TensorRT 版本相容的 TensorRT 引擎(限制為精簡運行時運算符,以便為引擎提供版本向前相容性)

  • optimization_level – (Optional[int]): 設定更高的最佳化層級可讓 TensorRT 花費更長的引擎構建時間來搜尋更多最佳化選項。與使用較低最佳化層級構建的引擎相比,產生的引擎可能具有更好的效能。預設最佳化層級為 3。有效值包括從 0 到最大最佳化層級的整數,目前為 5。將其設定為大於最大層級會導致與最大層級相同的行為。

  • use_python_runtime – (bool): 返回使用純 Python 運行時的圖,減少了序列化的選項

  • use_fast_partitioner – (bool): 使用基於鄰接的分割方案,而不是全域分割器。鄰接分割更快,但可能不是最佳的。如果尋找最佳效能,請使用全域分割器 (False)

  • enable_experimental_decompositions (bool) – 使用完整的運算符分解集。這些分解可能未經過測試,但有助於使圖更容易轉換為 TensorRT,從而可能增加在 TensorRT 中運行的圖的數量。

  • dryrun (bool) – 切換到「Dryrun」模式,運行除轉換為 TRT 之外的所有內容並記錄輸出

  • hardware_compatible (bool) – 構建與 GPU 架構(而不是構建引擎的 GPU 的架構)相容的 TensorRT 引擎(目前適用於 NVIDIA Ampere 及更新版本)

  • timing_cache_path (str) – 計時快取的路徑(如果存在),或編譯後將儲存的路徑

  • lazy_engine_init (bool) – 延遲設定引擎,直到所有引擎的編譯完成。可以允許編譯具有多個圖中斷的較大型模型,但可能導致運行時過度使用 GPU 記憶體。

  • **kwargs – Any,

回傳

MutableTorchTensorRTModule

compile() None[原始碼]

使用 PyTorch 模組 (重新)編譯 TRT 圖形模組。每當權重結構發生變更時(形狀、更多層…),都應呼叫此函式。 MutableTorchTensorRTModule 會自動捕獲權重值的更新,並呼叫此函式以重新編譯。如果無法捕獲變更,請手動呼叫此函式以重新編譯 TRT 圖形模組。

refit_gm() None[原始碼]

使用任何更新來重新調整 TRT 圖形模組。每當權重值發生變更但權重結構保持不變時,都應呼叫此函式。 MutableTorchTensorRTModule 會自動捕獲權重值的更新,並呼叫此函式以重新調整模組。如果無法捕獲變更,請手動呼叫此函式以更新 TRT 圖形模組。

class torch_tensorrt.Input(*args: Any, **kwargs: Any)[原始碼]

定義模組的輸入,根據預期的形狀、資料類型和張量格式。

變數
  • shape_mode (torch_tensorrt.Input._ShapeMode) – 輸入是靜態或動態形狀

  • shape (TupleDict) –

    單個 Tuple 或定義輸入形狀的 tuples 字典。靜態形狀的輸入將具有單個 tuple。動態輸入將具有以下形式的字典

    {"min_shape": Tuple, "opt_shape": Tuple, "max_shape": Tuple}
    

  • dtype (torch_tensorrt.dpython:type) – 輸入張量的預期資料類型(預設:torch_tensorrt.dtype.float32)

  • format (torch_tensorrt.TensorFormat) – 輸入張量的預期格式(預設:torch_tensorrt.TensorFormat.NCHW)

__init__(*args: Any, **kwargs: Any) None[原始碼]

torch_tensorrt.Input 的 __init__ 方法

Input 接受幾種建構模式之一

參數

shape (TupleList, optional) – 輸入張量的靜態形狀

關鍵字參數
  • shape (TupleList, optional) – 輸入張量的靜態形狀

  • min_shape (TupleList, optional) – 輸入張量形狀範圍的最小大小 注意:必須提供 min_shape、opt_shape、max_shape 這三個參數,不能有位置引數,必須未定義 shape,並且隱式地將 Input 的 shape_mode 設定為 DYNAMIC

  • opt_shape (TupleList, optional) – 輸入張量形狀範圍的最佳大小 注意:必須提供 min_shape、opt_shape、max_shape 這三個參數,不能有位置引數,必須未定義 shape,並且隱式地將 Input 的 shape_mode 設定為 DYNAMIC

  • max_shape (TupleList, optional) – 輸入張量形狀範圍的最大大小 注意:必須提供 min_shape、opt_shape、max_shape 這三個參數,不能有位置引數,必須未定義 shape,並且隱式地將 Input 的 shape_mode 設定為 DYNAMIC

  • dtype (torch.dpython:typetorch_tensorrt.dpython:type) – 輸入張量的預期資料類型(預設:torch_tensorrt.dtype.float32)

  • format (torch.memory_formattorch_tensorrt.TensorFormat) – 輸入張量的預期格式(預設:torch_tensorrt.TensorFormat.NCHW)

  • tensor_domain (Tuple(python:float, python:float), optional) – 張量允許值的域,以區間符號表示:[tensor_domain[0], tensor_domain[1])。注意:輸入 “None”(或不指定)將把界限設定為 [0, 2)

  • torch_tensor (torch.Tensor) – 持有與此 Input 對應的 torch 張量。

  • name (str, optional) – 輸入 nn.Module 的 forward 函式中此輸入的名稱。用於指定 dynamo tracer 中對應輸入的動態形狀。

範例

  • Input([1,3,32,32], dtype=torch.float32, format=torch.channel_last)

  • Input(shape=(1,3,32,32), dtype=torch_tensorrt.dtype.int32, format=torch_tensorrt.TensorFormat.NCHW)

  • Input(min_shape=(1,3,32,32), opt_shape=[2,3,32,32], max_shape=(3,3,32,32)) #隱式地 dtype=torch_tensorrt.dtype.float32, format=torch_tensorrt.TensorFormat.NCHW

example_tensor(optimization_profile_field: Optional[str] = None) Tensor[原始碼]

取得由 Input 物件指定的形狀的範例張量

參數

optimization_profile_field (Optional(str)) – 如果 Input 是動態形狀,則用於形狀的欄位名稱

回傳

一個 PyTorch Tensor

classmethod from_tensor(t: Tensor, disable_memory_format_check: bool = False) Input[source]

產生一個 Input 物件,其中包含給定 PyTorch 張量的資訊。

參數
  • tensor (torch.Tensor) – 一個 PyTorch 張量。

  • disable_memory_format_check (bool) – 是否驗證輸入張量的記憶體格式

回傳

一個 Input 物件。

classmethod from_tensors(ts: Sequence[Tensor], disable_memory_format_check: bool = False) List[Input][source]

產生一個 Inputs 列表,其中包含所有給定 PyTorch 張量的資訊。

參數
  • tensors (Iterable[torch.Tensor]) – 一個 PyTorch 張量的列表。

  • disable_memory_format_check (bool) – 是否驗證輸入張量的記憶體格式

回傳

一個 Inputs 列表。

dtype: dtype = 1

torch_tensorrt.dtype.float32)

型別

輸入張量的預期資料型別 (預設

format: memory_format = 1

torch_tensorrt.memory_format.linear)

型別

輸入張量的預期格式 (預設

class torch_tensorrt.Device(*args: Any, **kwargs: Any)[source]

定義一個裝置,可用於指定引擎的目標裝置

變數
  • device_type (DeviceType) – 目標裝置類型 (GPU 或 DLA)。根據是否指定 dla_core 隱式設定。

  • gpu_id (python:int) – 目標 GPU 的裝置 ID

  • dla_core (python:int) – 目標 DLA 核心的核心 ID

  • allow_gpu_fallback (bool) – 如果 DLA 無法支援操作,是否允許回復到 GPU

__init__(*args: Any, **kwargs: Any)[source]

torch_tensorrt.Device 的 __init__ 方法

Device 接受幾種建構模式之一

參數

spec (str) – 具有裝置規格的字串,例如 dla 的 “dla:0”,核心 ID 為 0

關鍵字參數
  • gpu_id (python:int) – 目標 GPU 的 ID (如果指定了 dla_core 給管理 DLA 的 GPU,則會被覆寫)。如果指定,則不應提供位置引數

  • dla_core (python:int) – 目標 DLA 核心的 ID。如果指定,則不應提供位置引數。

  • allow_gpu_fallback (bool) – 如果 DLA 不支援 TensorRT 操作,則允許 TensorRT 在 GPU 上排程它們 (如果裝置類型不是 DLA,則忽略)

範例

  • Device(“gpu:1”)

  • Device(“cuda:1”)

  • Device(“dla:0”, allow_gpu_fallback=True)

  • Device(gpu_id=0, dla_core=0, allow_gpu_fallback=True)

  • Device(dla_core=0, allow_gpu_fallback=True)

  • Device(gpu_id=1)

device_type: DeviceType = 1

目標裝置類型 (GPU 或 DLA)。根據是否指定了 dla_core 隱式設定。

dla_core: int = -1

目標 DLA 核心的核心 ID

gpu_id: int = -1

目標 GPU 的裝置 ID

列舉 (Enums)

class torch_tensorrt.dtype(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[原始碼]

列舉 (Enum) 用於描述 Torch-TensorRT 的資料類型,與 torch、tensorrt 和 numpy 的 dtype 具有相容性

to(t: Union[Type[dtype], Type[DataType], Type[dtype], Type[dtype]], use_default: bool = False) Union[dtype, DataType, dtype, dtype][原始碼]

將 dtype 轉換為 [torch, numpy, tensorrt] 中等效的類型

self 轉換為 numpy、torch 和 tensorrt 等效的 dtypes 之一。如果目標函式庫不支援 self,則會引發例外。 因此,不建議直接使用此方法。

或者使用 torch_tensorrt.dtype.try_to()

參數
  • t (Union(Type(torch.dpython:type), Type(tensorrt.DataType), Type(numpy.dpython:type), Type(dpython:type))) – 要轉換的另一個函式庫的資料類型列舉 (enum)

  • use_default (bool) – 在某些情況下,可以使用通用類型(例如 torch.float),因此不用引發例外,而是傳回預設值。

回傳

來自函式庫列舉 t 的 dtype 等效 torch_tensorrt.dtype

回傳類型

Union(torch.dtype, tensorrt.DataType, numpy.dtype, dtype)

引發

TypeError – 不支援的資料類型或未知的目標

範例

# Succeeds
float_dtype = torch_tensorrt.dtype.f32.to(torch.dtype) # Returns torch.float

# Failure
float_dtype = torch_tensorrt.dtype.bf16.to(numpy.dtype) # Throws exception
classmethod try_from(t: Union[dtype, DataType, dtype, dtype], use_default: bool = False) Optional[dtype][原始碼]

從另一個函式庫的 dtype 系統建立 Torch-TensorRT dtype。

採用來自 numpy、torch 和 tensorrt 的 dtype 列舉,並建立 torch_tensorrt.dtype。 如果來源 dtype 系統不受支援,或者在 Torch-TensorRT 中不支援該類型,則傳回 None

參數
  • t (Union(torch.dpython:type, tensorrt.DataType, numpy.dpython:type, dpython:type)) – 來自另一個函式庫的資料類型列舉 (enum)

  • use_default (bool) – 在某些情況下,可以使用通用類型(例如 torch_tensorrt.dtype.f32),因此不用引發例外,而是傳回預設值。

回傳

等效於 ttorch_tensorrt.dtypeNone

回傳類型

Optional(dtype)

範例

# Succeeds
float_dtype = torch_tensorrt.dtype.try_from(torch.float) # Returns torch_tensorrt.dtype.f32

# Unsupported type
float_dtype = torch_tensorrt.dtype.try_from(torch.complex128) # Returns None
try_to(t: Union[Type[dtype], Type[DataType], Type[dtype], Type[dtype]], use_default: bool) Optional[Union[dtype, DataType, dtype, dtype]][原始碼]

將 dtype 轉換為 [torch, numpy, tensorrt] 中等效的類型

self 轉換為 numpy、torch 和 tensorrt 的等效 dtype 之一。如果目標函式庫不支援 self,則傳回 None

參數
  • t (Union(Type(torch.dpython:type), Type(tensorrt.DataType), Type(numpy.dpython:type), Type(dpython:type))) – 要轉換的另一個函式庫的資料類型列舉 (enum)

  • use_default (bool) – 在某些情況下,可以使用通用類型(例如 torch.float),因此不用引發例外,而是傳回預設值。

回傳

來自函式庫列舉 t 的 dtype 等效 torch_tensorrt.dtype

回傳類型

Optional(Union(torch.dtype, tensorrt.DataType, numpy.dtype, dtype))

範例

# Succeeds
float_dtype = torch_tensorrt.dtype.f32.to(torch.dtype) # Returns torch.float

# Failure
float_dtype = torch_tensorrt.dtype.bf16.to(numpy.dtype) # Returns None
b

布林值,相當於 dtype.bool

bf16

16 位元 "Brain" 浮點數,相當於 dtype.bfloat16

f16

16 位元浮點數,相當於 dtype.halfdtype.fp16dtype.float16

f32

32 位元浮點數,相當於 dtype.floatdtype.fp32dtype.float32

f64

64 位元浮點數,相當於 dtype.doubledtype.fp64dtype.float64

f8

8 位元浮點數,相當於 dtype.fp8dtype.float8

i32

有符號 32 位元整數,相當於 dtype.int32dtype.int

i64

有符號 64 位元整數,相當於 dtype.int64dtype.long

i8

有符號 8 位元整數,相當於 dtype.int8,當啟用為核心精確度時,通常需要模型支援量化

u8

無符號 8 位元整數,相當於 dtype.uint8

unknown

哨兵值

class torch_tensorrt.DeviceType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[原始碼]

TensorRT 將定位的裝置類型

to(t: Union[Type[DeviceType], Type[DeviceType]], use_default: bool = False) Union[DeviceType, DeviceType][原始碼]

DeviceType 轉換為 tensorrt 中的等效類型。

self 轉換為 torch 或 tensorrt 等效的裝置類型之一。 如果目標函式庫不支援 self,則會引發例外。 因此,不建議直接使用此方法。

或者,使用 torch_tensorrt.DeviceType.try_to()

參數

t (Union(Type(tensorrt.DeviceType), Type(DeviceType))) – 要轉換為的另一個函式庫的裝置類型列舉

回傳

列舉 t 中等效的裝置類型 torch_tensorrt.DeviceType

回傳類型

Union(tensorrt.DeviceType, DeviceType)

引發

TypeError – 未知的目標類型或不支援的裝置類型

範例

# Succeeds
trt_dla = torch_tensorrt.DeviceType.DLA.to(tensorrt.DeviceType) # Returns tensorrt.DeviceType.DLA
classmethod try_from(d: Union[DeviceType, DeviceType]) Optional[DeviceType][原始碼]

從 TensorRT 裝置類型列舉建立 Torch-TensorRT 裝置類型列舉。

採用來自 tensorrt 的裝置類型列舉,並建立 torch_tensorrt.DeviceType。 如果來源不受支援,或者 Torch-TensorRT 不支援裝置類型,則會引發例外。 因此,不建議直接使用此方法。

或者,使用 torch_tensorrt.DeviceType.try_from()

參數

d (Union(tensorrt.DeviceType, DeviceType)) – 來自另一個函式庫的裝置類型列舉

回傳

d 等效的 torch_tensorrt.DeviceType

回傳類型

DeviceType

範例

torchtrt_dla = torch_tensorrt.DeviceType._from(tensorrt.DeviceType.DLA)
try_to(t: Union[Type[DeviceType], Type[DeviceType]], use_default: bool = False) Optional[Union[DeviceType, DeviceType]][原始碼]

DeviceType 轉換為 tensorrt 中的等效類型。

self 轉換為 torch 或 tensorrt 等效的記憶體格式之一。 如果目標函式庫不支援 self,則將傳回 None

參數

t (Union(Type(tensorrt.DeviceType), Type(DeviceType))) – 要轉換為的另一個函式庫的裝置類型列舉

回傳

列舉 t 中等效的裝置類型 torch_tensorrt.DeviceType

回傳類型

Optional(Union(tensorrt.DeviceType, DeviceType))

範例

# Succeeds
trt_dla = torch_tensorrt.DeviceType.DLA.to(tensorrt.DeviceType) # Returns tensorrt.DeviceType.DLA
DLA

目標是 DLA 核心

GPU

目標是 GPU

UNKNOWN

哨兵值

class torch_tensorrt.EngineCapability(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

EngineCapability 決定了建構時期網路的限制以及其目標的執行階段。

to(t: Union[Type[EngineCapability], Type[EngineCapability]]) Union[EngineCapability, EngineCapability][source]

EngineCapability 轉換為 tensorrt 中等效的類型

self 轉換為 torch 或 tensorrt 中等效的引擎能力。如果目標庫不支援 self,則會引發例外。 因此,不建議直接使用此方法。

或者,使用 torch_tensorrt.EngineCapability.try_to()

參數

t (Union(Type(tensorrt.EngineCapability), Type(EngineCapability))) – 要轉換為的另一個庫中的引擎能力枚舉

回傳

枚舉 ttorch_tensorrt.EngineCapability 的等效引擎能力

回傳類型

Union(tensorrt.EngineCapability, EngineCapability)

引發

TypeError – 未知的目標類型或不支援的引擎能力

範例

# Succeeds
torchtrt_dla_ec = torch_tensorrt.EngineCapability.DLA_STANDALONE.to(tensorrt.EngineCapability) # Returns tensorrt.EngineCapability.DLA
classmethod try_from() Optional[EngineCapability][source]

從 TensorRT 引擎能力枚舉建立 Torch-TensorRT 引擎能力枚舉。

從 tensorrt 取得裝置類型枚舉,並建立 torch_tensorrt.EngineCapability。如果 Torch-TensorRT 不支援來源或引擎能力等級,則會引發例外。 因此,不建議直接使用此方法。

或者,使用 torch_tensorrt.EngineCapability.try_from()

參數

c (Union(tensorrt.EngineCapability, EngineCapability)) – 來自另一個函式庫的引擎能力枚舉

回傳

c 等效的 torch_tensorrt.EngineCapability

回傳類型

EngineCapability

範例

torchtrt_safety_ec = torch_tensorrt.EngineCapability._from(tensorrt.EngineCapability.SAEFTY)
try_to(t: Union[Type[EngineCapability], Type[EngineCapability]]) Optional[Union[EngineCapability, EngineCapability]][source]

EngineCapability 轉換為 tensorrt 中等效的類型

self 轉換為 torch 或 tensorrt 中等效的引擎能力。如果目標庫不支援 self,則會傳回 None

參數

t (Union(Type(tensorrt.EngineCapability), Type(EngineCapability))) – 要轉換為的另一個庫中的引擎能力枚舉

回傳

枚舉 ttorch_tensorrt.EngineCapability 的等效引擎能力

回傳類型

Optional(Union(tensorrt.EngineCapability, EngineCapability))

範例

# Succeeds
trt_dla_ec = torch_tensorrt.EngineCapability.DLA.to(tensorrt.EngineCapability) # Returns tensorrt.EngineCapability.DLA_STANDALONE
DLA_STANDALONE

EngineCapability.DLA_STANDALONE 提供 DLA 相容的網路操作的限制子集,並且可以使用獨立的 DLA 執行階段 API 執行產生的序列化引擎。

SAFETY

EngineCapability.SAFETY 提供一個受限制的網路操作子集,這些操作經過安全認證,並且產生的序列化引擎可以使用 TensorRT 的安全執行階段 API 在 tensorrt.safe 命名空間中執行。

STANDARD

EngineCapability.STANDARD 不提供任何功能上的限制,並且產生的序列化引擎可以使用 TensorRT 的標準執行階段 API 執行。

class torch_tensorrt.memory_format(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[原始碼]
to(t: Union[Type[memory_format], Type[TensorFormat], Type[memory_format]]) Union[memory_format, TensorFormat, memory_format][原始碼]

memory_format 轉換為 torch 或 tensorrt 中的等效類型

self 轉換為 torch 或 tensorrt 等效的記憶體格式之一。如果目標函式庫不支援 self,則會引發例外。 因此,不建議直接使用此方法。

或者使用 torch_tensorrt.memory_format.try_to()

參數

t (Union(Type(torch.memory_format), Type(tensorrt.TensorFormat), Type(memory_format))) – 要轉換到的另一個函式庫的記憶體格式類型枚舉

回傳

枚舉 t 中的等效記憶體格式 torch_tensorrt.memory_format

回傳類型

Union(torch.memory_format, tensorrt.TensorFormat, memory_format)

引發

TypeError – 未知的目標類型或不支援的記憶體格式

範例

# Succeeds
tf = torch_tensorrt.memory_format.linear.to(torch.dtype) # Returns torch.contiguous
classmethod try_from(f: Union[memory_format, TensorFormat, memory_format]) Optional[memory_format][原始碼]

從另一個函式庫記憶體格式列舉建立一個 Torch-TensorRT 記憶體格式列舉。

採用來自 torch 和 tensorrt 其中一個的記憶體格式列舉,並建立一個 torch_tensorrt.memory_format。 如果不支援來源或 Torch-TensorRT 不支援記憶體格式,則會傳回 None

參數

f (Union(torch.memory_format, tensorrt.TensorFormat, memory_format)) – 來自另一個函式庫的記憶體格式列舉

回傳

f 等效的 torch_tensorrt.memory_format

回傳類型

Optional(memory_format)

範例

torchtrt_linear = torch_tensorrt.memory_format.try_from(torch.contiguous)
try_to(t: Union[Type[memory_format], Type[TensorFormat], Type[memory_format]]) Optional[Union[memory_format, TensorFormat, memory_format]][原始碼]

memory_format 轉換為 torch 或 tensorrt 中的等效類型

self 轉換為 torch 或 tensorrt 等效的記憶體格式之一。 如果目標函式庫不支援 self,則會傳回 None

參數

t (Union(Type(torch.memory_format), Type(tensorrt.TensorFormat), Type(memory_format))) – 要轉換到的另一個函式庫的記憶體格式類型枚舉

回傳

枚舉 t 中的等效記憶體格式 torch_tensorrt.memory_format

回傳類型

可選(Union(torch.memory_format, tensorrt.TensorFormat, memory_format))

範例

# Succeeds
tf = torch_tensorrt.memory_format.linear.to(torch.dtype) # Returns torch.contiguous
cdhw32

具備三個空間維度的 32 寬通道向量化行主序格式。

此格式與 FP16 和 INT8 綁定。僅適用於維度 >= 4 的情況。

對於具有維度 {N, C, D, H, W} 的張量,記憶體佈局等效於一個 C 陣列,其維度為 [N][(C+31)/32][D][H][W][32],張量座標 (n, d, c, h, w) 映射到陣列下標 [n][c/32][d][h][w][c%32]。

chw16

16 寬通道向量化行主序格式。

此格式與 FP16 綁定。僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個 C 陣列,其維度為 [N][(C+15)/16][H][W][16],張量座標 (n, c, h, w) 映射到陣列下標 [n][c/16][h][w][c%16]。

chw2

2 寬通道向量化行主序格式。

此格式在 TensorRT 中與 FP16 綁定。僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個 C 陣列,其維度為 [N][(C+1)/2][H][W][2],張量座標 (n, c, h, w) 映射到陣列下標 [n][c/2][h][w][c%2]。

chw32

32 寬通道向量化行主序格式。

此格式僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個 C 陣列,其維度為 [N][(C+31)/32][H][W][32],張量座標 (n, c, h, w) 映射到陣列下標 [n][c/32][h][w][c%32]。

chw4

4 寬通道向量化行主序格式。此格式與 INT8 綁定。僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個 C 陣列,其維度為 [N][(C+3)/4][H][W][4],張量座標 (n, c, h, w) 映射到陣列下標 [n][c/4][h][w][c%4]。

dhwc

非向量化通道最後格式。此格式與 FP32 綁定。僅適用於維度 >= 4 的情況。

等效於 memory_format.channels_last_3d

dhwc8

8 通道格式,其中 C 填充至 8 的倍數。

此格式與 FP16 綁定,且僅適用於維度 >= 4 的情況。

對於具有維度 {N, C, D, H, W} 的張量,記憶體佈局等效於一個陣列,其維度為 [N][D][H][W][(C+7)/8*8],張量座標 (n, c, d, h, w) 映射到陣列下標 [n][d][h][w][c]。

dla_hwc4

DLA 影像格式。通道最後格式。C 只能是 1、3、4。如果 C == 3,則會四捨五入為 4。沿 H 軸步進的跨距會四捨五入為 32 個位元組。

此格式與 FP16/Int8 綁定,且僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,其中當 C 分別為 1、3、4 時,C' 為 1、4、4,記憶體佈局等效於一個 C 陣列,其維度為 [N][H][roundUp(W, 32/C'/elementSize)][C'],其中 elementSize 對於 FP16 為 2,對於 Int8 為 1,C' 是四捨五入後的 C。張量座標 (n, c, h, w) 映射到陣列下標 [n][h][w][c]。

dla_linear

DLA 平面格式。行主序格式。沿 H 軸步進的跨距會四捨五入為 64 個位元組。

此格式與 FP16/Int8 綁定,且僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個 C 陣列,其維度為 [N][C][H][roundUp(W, 64/elementSize)],其中 elementSize 對於 FP16 為 2,對於 Int8 為 1,張量座標 (n, c, h, w) 映射到陣列下標 [n][c][h][w]。

hwc

非向量化通道最後格式。此格式與 FP32 綁定,且僅適用於維度 >= 3 的情況。

等效於 memory_format.channels_last

hwc16

16 通道格式,其中 C 填充至 16 的倍數。此格式與 FP16 綁定。僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個陣列,其維度為 [N][H][W][(C+15)/16*16],張量座標 (n, c, h, w) 映射到陣列下標 [n][h][w][c]。

hwc8

8 通道格式,其中 C 填充至 8 的倍數。

此格式與 FP16 綁定。僅適用於維度 >= 3 的情況。

對於具有維度 {N, C, H, W} 的張量,記憶體佈局等效於一個陣列,其維度為 [N][H][W][(C+7)/8*8],張量座標 (n, c, h, w) 映射到陣列下標 [n][h][w][c]。

linear

行主序線性格式。

對於具有維度 {N, C, H, W} 的張量,W 軸始終具有單位跨距,且每個其他軸的跨距至少是下一個維度乘以跨距的乘積。跨距與具有維度 [N][C][H][W] 的 C 陣列相同。

等效於 memory_format.contiguous

子模組

文件

取得 PyTorch 的完整開發者文件

檢視文件

教學

取得針對初學者和進階開發者的深入教學課程

查看教學

資源

尋找開發資源並獲得您的問題解答

查看資源