Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion docsrc/user_guide/compilation/compilation_settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,21 @@ Precision and Typing
decomposed FP16 scaled dot product attention calculation runs in FP32 and only
its final output is cast back to FP16. This option has no effect on FP32 or
BF16 inputs and may increase memory use or reduce throughput.
* - ``pointwise_in_float32``
- ``False``
- Compute common FP16 and BF16 pointwise math inside each TensorRT engine in
FP32, such as residual adds, an RMSNorm built from pointwise ops and a
reduction, or a GELU. A value is rounded to 16 bits only where it leaves such
a region, not after each op, and a cast to 16 bits inside a region becomes a
cast to FP32. A matrix multiply, an attention, a softmax, a layer norm or any
other op ends a region and gets 16-bit inputs, as without this setting. Code
that runs in PyTorch is not changed, and values passed between an engine and
PyTorch keep their 16-bit dtype. Results are usually closer to an FP32 run
than those of a 16-bit PyTorch run, but measure it. TensorRT may not fuse the
added casts, and a cast between a matrix multiply and the add after it can
stop TensorRT from fusing the two, mostly for long inputs, so run time and
memory can grow. Weights read by region math are also stored in FP32 in the
engine.

----

Expand Down Expand Up @@ -576,7 +591,8 @@ rebuilt from scratch:
``disabled_constant_fold_exclusions``, ``attn_bias_is_causal``,
``fold_shared_kv_attention``, ``deduplicate_weights``, ``build_route``,
``fallback_pytorch_plugin_ops``, ``collapse_high_rank_permutes``,
``convert_antialiased_resize``, ``replace_interleave_stack_with_cat``.
``convert_antialiased_resize``, ``replace_interleave_stack_with_cat``,
``pointwise_in_float32``.
On TensorRT older than 10.14, ``strip_engine_weights`` also invalidates cached engines.

Settings not in this list (e.g., ``dryrun`` and ``pass_through_build_failures``)
Expand Down
9 changes: 9 additions & 0 deletions py/torch_tensorrt/dynamo/_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ def cross_compile_for_windows(
collapse_high_rank_permutes: bool = _defaults.COLLAPSE_HIGH_RANK_PERMUTES,
convert_antialiased_resize: bool = _defaults.CONVERT_ANTIALIASED_RESIZE,
replace_interleave_stack_with_cat: bool = _defaults.REPLACE_INTERLEAVE_STACK_WITH_CAT,
pointwise_in_float32: bool = _defaults.POINTWISE_IN_FLOAT32,
**kwargs: Any,
) -> torch.fx.GraphModule:
"""Compile an ExportedProgram module using TensorRT in Linux for Inference in Windows
Expand Down Expand Up @@ -278,6 +279,7 @@ def cross_compile_for_windows(
collapse_high_rank_permutes (bool): Rewrite a reshape, permute, reshape chain over more than 8 dimensions, TensorRT's limit, as reshapes and permutes of at most 8 dimensions that give the same values. Window and patch layouts, such as neighborhood attention and the Qwen2-VL image patches, build such chains. Left in PyTorch, each one splits the graph, and the partitioner can then hand many large tensors across one engine boundary. Only static shapes are rewritten. Fewer, larger engines can need much more time and memory to build and to run, so measure it. Default is False.
convert_antialiased_resize (bool): Run antialiased bilinear and bicubic resize (F.interpolate with antialias=True) in TensorRT instead of PyTorch, so it does not split the graph. Only static input and output heights and widths and floating-point inputs are converted. Some sizes run slower than in PyTorch, so measure it. Default is False.
replace_interleave_stack_with_cat (bool): Write a stack whose only user is a reshape that merges the new axis into a neighbor axis, as in torch.stack([even, odd], dim=3).flatten(2, 3) for a 2x upsample, as a concatenation of unsqueezed inputs. This can make large, image-sized interleaves faster on GPUs where TensorRT fuses the region around them, but slower where TensorRT runs them as separate layers and adds copies, so measure it. Only programs from torch.export are rewritten, not torch.compile graphs. Default is False.
pointwise_in_float32 (bool): Compute chains of common 16-bit pointwise ops and reductions inside each TensorRT engine in float32, and round a value to 16 bits only where it leaves such a chain. This can make results more accurate than a 16-bit PyTorch run, but can cost run time and memory; see the CompilationSettings Reference in the user guide. Default is False.
**kwargs: Any,
Returns:
torch.fx.GraphModule: Compiled FX Module, when run it will execute via TensorRT
Expand Down Expand Up @@ -390,6 +392,7 @@ def cross_compile_for_windows(
"collapse_high_rank_permutes": collapse_high_rank_permutes,
"convert_antialiased_resize": convert_antialiased_resize,
"replace_interleave_stack_with_cat": replace_interleave_stack_with_cat,
"pointwise_in_float32": pointwise_in_float32,
}

# disable the following settings is not supported for cross compilation for windows feature
Expand Down Expand Up @@ -544,6 +547,7 @@ def compile(
collapse_high_rank_permutes: bool = _defaults.COLLAPSE_HIGH_RANK_PERMUTES,
convert_antialiased_resize: bool = _defaults.CONVERT_ANTIALIASED_RESIZE,
replace_interleave_stack_with_cat: bool = _defaults.REPLACE_INTERLEAVE_STACK_WITH_CAT,
pointwise_in_float32: bool = _defaults.POINTWISE_IN_FLOAT32,
build_route: Optional[str] = _defaults.BUILD_ROUTE,
tune_build_routes: Optional[str] = _defaults.TUNE_BUILD_ROUTES,
tune_build_route_file: Optional[str] = _defaults.TUNE_BUILD_ROUTE_FILE,
Expand Down Expand Up @@ -674,6 +678,7 @@ def compile(
collapse_high_rank_permutes (bool): Rewrite a reshape, permute, reshape chain over more than 8 dimensions, TensorRT's limit, as reshapes and permutes of at most 8 dimensions that give the same values. Window and patch layouts, such as neighborhood attention and the Qwen2-VL image patches, build such chains. Left in PyTorch, each one splits the graph, and the partitioner can then hand many large tensors across one engine boundary. Only static shapes are rewritten. Fewer, larger engines can need much more time and memory to build and to run, so measure it. Default is False.
convert_antialiased_resize (bool): Run antialiased bilinear and bicubic resize (F.interpolate with antialias=True) in TensorRT instead of PyTorch, so it does not split the graph. Only static input and output heights and widths and floating-point inputs are converted. Some sizes run slower than in PyTorch, so measure it. Default is False.
replace_interleave_stack_with_cat (bool): Write a stack whose only user is a reshape that merges the new axis into a neighbor axis, as in torch.stack([even, odd], dim=3).flatten(2, 3) for a 2x upsample, as a concatenation of unsqueezed inputs. This can make large, image-sized interleaves faster on GPUs where TensorRT fuses the region around them, but slower where TensorRT runs them as separate layers and adds copies, so measure it. Only programs from torch.export are rewritten, not torch.compile graphs. Default is False.
pointwise_in_float32 (bool): Compute chains of common 16-bit pointwise ops and reductions inside each TensorRT engine in float32, and round a value to 16 bits only where it leaves such a chain. This can make results more accurate than a 16-bit PyTorch run, but can cost run time and memory; see the CompilationSettings Reference in the user guide. Default is False.
build_route (Optional[str]): TensorRT Global Performance Tuning build route string (space-separated "-knob=value" tokens). None uses the default route. This feature requires TensorRT with Global Performance Tuning enabled; currently unavailable on TensorRT-RTX / Windows.
tune_build_routes (Optional[str]): Build-route expression for an autotuning sweep that runs each candidate in a spawned child process (e.g. "-slice_fusion=[on|off] -kgen:codegen:cuda_tile=[0|1|2|3]"). None disables tuning.
tune_build_route_file (Optional[str]): Path to a file with one route token per line (same as "tune_build_routes"). Mutually exclusive with "tune_build_routes".
Expand Down Expand Up @@ -827,6 +832,7 @@ def compile(
"collapse_high_rank_permutes": collapse_high_rank_permutes,
"convert_antialiased_resize": convert_antialiased_resize,
"replace_interleave_stack_with_cat": replace_interleave_stack_with_cat,
"pointwise_in_float32": pointwise_in_float32,
"build_route": build_route,
"tune_build_routes": tune_build_routes,
"tune_build_route_file": tune_build_route_file,
Expand Down Expand Up @@ -2147,6 +2153,7 @@ def convert_exported_program_to_serialized_trt_engine(
collapse_high_rank_permutes: bool = _defaults.COLLAPSE_HIGH_RANK_PERMUTES,
convert_antialiased_resize: bool = _defaults.CONVERT_ANTIALIASED_RESIZE,
replace_interleave_stack_with_cat: bool = _defaults.REPLACE_INTERLEAVE_STACK_WITH_CAT,
pointwise_in_float32: bool = _defaults.POINTWISE_IN_FLOAT32,
lift_mutable_buffers: bool = False,
arg_input_binding_names: Any = None,
kwarg_input_binding_names: Any = None,
Expand Down Expand Up @@ -2265,6 +2272,7 @@ def convert_exported_program_to_serialized_trt_engine(
collapse_high_rank_permutes (bool): Rewrite a reshape, permute, reshape chain over more than 8 dimensions, TensorRT's limit, as reshapes and permutes of at most 8 dimensions that give the same values. Window and patch layouts, such as neighborhood attention and the Qwen2-VL image patches, build such chains. This function builds one engine, so without the rewrite such a chain makes the conversion fail. Only static shapes are rewritten. A large engine can need much more time and memory to build and to run, so measure it. Default is False.
convert_antialiased_resize (bool): Convert antialiased bilinear and bicubic resize (F.interpolate with antialias=True) to TensorRT. This function builds one engine, so without this setting such a resize makes the conversion fail. Only static input and output heights and widths and floating-point inputs are converted. Some sizes run slower than in PyTorch, so measure it. Default is False.
replace_interleave_stack_with_cat (bool): Write a stack whose only user is a reshape that merges the new axis into a neighbor axis, as in torch.stack([even, odd], dim=3).flatten(2, 3) for a 2x upsample, as a concatenation of unsqueezed inputs. This can make large, image-sized interleaves faster on GPUs where TensorRT fuses the region around them, but slower where TensorRT runs them as separate layers and adds copies, so measure it. Only programs from torch.export are rewritten, not torch.compile graphs. Default is False.
pointwise_in_float32 (bool): Compute chains of common 16-bit pointwise ops and reductions inside each TensorRT engine in float32, and round a value to 16 bits only where it leaves such a chain. This can make results more accurate than a 16-bit PyTorch run, but can cost run time and memory; see the CompilationSettings Reference in the user guide. Default is False.
**kwargs: Any,
Returns:
bytes: Serialized TensorRT engine, can either be saved to a file or deserialized via TensorRT APIs
Expand Down Expand Up @@ -2383,6 +2391,7 @@ def convert_exported_program_to_serialized_trt_engine(
"collapse_high_rank_permutes": collapse_high_rank_permutes,
"convert_antialiased_resize": convert_antialiased_resize,
"replace_interleave_stack_with_cat": replace_interleave_stack_with_cat,
"pointwise_in_float32": pointwise_in_float32,
}

settings = CompilationSettings(**compilation_options)
Expand Down
1 change: 1 addition & 0 deletions py/torch_tensorrt/dynamo/_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
COLLAPSE_HIGH_RANK_PERMUTES = False
CONVERT_ANTIALIASED_RESIZE = False
REPLACE_INTERLEAVE_STACK_WITH_CAT = False
POINTWISE_IN_FLOAT32 = False

# Global Performance Tuning (TensorRT build-route knobs)
BUILD_ROUTE = None
Expand Down
5 changes: 5 additions & 0 deletions py/torch_tensorrt/dynamo/_refit.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
pre_export_lowering,
remove_alias_from_exported_program,
)
from torch_tensorrt.dynamo.lowering.passes.pointwise_in_float32 import (
pointwise_in_float32,
)
from torch_tensorrt.dynamo.runtime._serialized_engine_layout import (
ENGINE_IDX,
SERIALIZED_METADATA_IDX,
Expand Down Expand Up @@ -430,6 +433,8 @@ def refit_module_weights(
to_torch_device(settings.device),
name,
)
# The engine was built from the rewritten graph, so its layers come from it too.
new_submodule = pointwise_in_float32(new_submodule, settings)
_refit_single_trt_engine_with_gm(
new_gm=new_submodule,
old_engine=engine,
Expand Down
5 changes: 5 additions & 0 deletions py/torch_tensorrt/dynamo/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
OFFLOAD_MODULE_TO_CPU,
OPTIMIZATION_LEVEL,
PASS_THROUGH_BUILD_FAILURES,
POINTWISE_IN_FLOAT32,
REFIT_IDENTICAL_ENGINE_WEIGHTS,
RELEASE_WEIGHTS_AFTER_BUILD,
REPLACE_INTERLEAVE_STACK_WITH_CAT,
Expand Down Expand Up @@ -211,6 +212,7 @@ class CompilationSettings:
collapse_high_rank_permutes (bool): Rewrite a reshape, permute, reshape chain over more than 8 dimensions, TensorRT's limit, as reshapes and permutes of at most 8 dimensions that give the same values. Window and patch layouts, such as neighborhood attention and the Qwen2-VL image patches, build such chains. Left in PyTorch, each one splits the graph, and the partitioner can then hand many large tensors across one engine boundary. Only static shapes are rewritten. Fewer, larger engines can need much more time and memory to build and to run, so measure it. Default is False.
convert_antialiased_resize (bool): Run antialiased bilinear and bicubic resize (F.interpolate with antialias=True) in TensorRT instead of PyTorch, so it does not split the graph. Only static input and output heights and widths and floating-point inputs are converted. Some sizes run slower than in PyTorch, so measure it. Default is False.
replace_interleave_stack_with_cat (bool): Write a stack whose only user is a reshape that merges the new axis into a neighbor axis, as in torch.stack([even, odd], dim=3).flatten(2, 3) for a 2x upsample, as a concatenation of unsqueezed inputs. This can make large, image-sized interleaves faster on GPUs where TensorRT fuses the region around them, but slower where TensorRT runs them as separate layers and adds copies, so measure it. Only programs from torch.export are rewritten, not torch.compile graphs. Default is False.
pointwise_in_float32 (bool): Compute chains of common 16-bit pointwise ops and reductions inside each TensorRT engine in float32, and round a value to 16 bits only where it leaves such a chain. This can make results more accurate than a 16-bit PyTorch run, but can cost run time and memory; see the CompilationSettings Reference in the user guide. Default is False.
build_route (Optional[str]): TensorRT Global Performance Tuning build route string (space-separated "-knob=value" tokens). None uses the default route. This feature requires TensorRT with Global Performance Tuning enabled; currently unavailable on TensorRT-RTX / Windows.
tune_build_routes (Optional[str]): Build-route expression for an autotuning sweep that runs each candidate in a spawned child process (e.g. "-slice_fusion=[on|off] -kgen:codegen:cuda_tile=[0|1|2|3]"). None disables tuning.
tune_build_route_file (Optional[str]): Path to a file with one route token per line (same as "tune_build_routes"). Mutually exclusive with "tune_build_routes".
Expand Down Expand Up @@ -307,6 +309,7 @@ class CompilationSettings:
collapse_high_rank_permutes: bool = COLLAPSE_HIGH_RANK_PERMUTES
convert_antialiased_resize: bool = CONVERT_ANTIALIASED_RESIZE
replace_interleave_stack_with_cat: bool = REPLACE_INTERLEAVE_STACK_WITH_CAT
pointwise_in_float32: bool = POINTWISE_IN_FLOAT32
build_route: Optional[str] = BUILD_ROUTE
tune_build_routes: Optional[str] = TUNE_BUILD_ROUTES
tune_build_route_file: Optional[str] = TUNE_BUILD_ROUTE_FILE
Expand Down Expand Up @@ -397,6 +400,7 @@ def __setstate__(self, state: dict[str, Any]) -> None:
state.setdefault(
"replace_interleave_stack_with_cat", REPLACE_INTERLEAVE_STACK_WITH_CAT
)
state.setdefault("pointwise_in_float32", POINTWISE_IN_FLOAT32)
state.setdefault("fold_shared_kv_attention", FOLD_SHARED_KV_ATTENTION)
state.setdefault("release_weights_after_build", RELEASE_WEIGHTS_AFTER_BUILD)
state.setdefault("deduplicate_weights", DEDUPLICATE_WEIGHTS)
Expand Down Expand Up @@ -452,6 +456,7 @@ def __setstate__(self, state: dict[str, Any]) -> None:
"collapse_high_rank_permutes",
"convert_antialiased_resize",
"replace_interleave_stack_with_cat",
"pointwise_in_float32",
}


Expand Down
9 changes: 8 additions & 1 deletion py/torch_tensorrt/dynamo/conversion/_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,13 +240,16 @@ def interpret_module_to_result(
) -> SerializedInterpreterResult:
"""Interpret an FX module to a TRTInterpreterResult
Args:
module: FX GraphModule to interpret
module: FX GraphModule to interpret. With pointwise_in_float32 set, it is rewritten in place.
inputs: It requires a sequence of FLATTENED Inputs representing inputs to the module. It should include both arg_inputs and kwarg_inputs, if applicable.
settings: Compilation settings
engine_cache: Engine cache instance
Returns:
SerializedInterpreterResult
"""
from torch_tensorrt.dynamo.lowering.passes.pointwise_in_float32 import (
pointwise_in_float32,
)
from torch_tensorrt.dynamo.tuning import (
gpt_settings_requested,
require_global_perf_tuning,
Expand All @@ -255,6 +258,10 @@ def interpret_module_to_result(
validate_tuning_options,
)

# Here rather than in lowering, so that code left to PyTorch keeps its dtype and
# every cast the pass adds lands in an engine.
module = pointwise_in_float32(module, settings)

if gpt_settings_requested(settings) or should_run_tuning(settings):
require_global_perf_tuning("Requested Global Performance Tuning settings")
validate_tuning_options(settings)
Expand Down
Loading
Loading