Skip to content
Closed
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
9 changes: 9 additions & 0 deletions docsrc/user_guide/compilation/compilation_settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,14 @@ numerically sensitive. Enable it with ``enable_autocast=True``.
``torch.no_grad()``, the block leaves nothing in the graph.
``autocast_excluded_node_names`` also matches the names that ops have in the
regions.
* - ``autocast_vector_norm_in_low_precision``
- ``False``
- Whether a 2-norm, ``torch.linalg.vector_norm(x)`` as ``F.normalize`` uses it,
that autocast runs in the low precision type is written as ``sqrt(sum(x * x))``
in that type. By default PyTorch computes it in FP32 for a float16 or bfloat16
``x``, as eager does, which adds casts around it. TensorRT then chooses how to
square and sum in float16, and a float16 sum of squares overflows for a norm above
about 256, so check the accuracy, or keep such norms in FP32 with the exclusions.

----

Expand Down Expand Up @@ -546,6 +554,7 @@ rebuilt from scratch:
``autocast_excluded_nodes``, ``autocast_excluded_node_names``,
``autocast_excluded_ops``, ``autocast_max_output_threshold``,
``autocast_max_depth_of_reduction``, ``autocast_model_regions``,
``autocast_vector_norm_in_low_precision``,
``decompose_attention``,
``disabled_constant_fold_exclusions``, ``attn_bias_is_causal``,
``fold_shared_kv_attention``, ``deduplicate_weights``, ``build_route``,
Expand Down
3 changes: 3 additions & 0 deletions py/torch_tensorrt/dynamo/_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ def compile(
torch.utils.data.DataLoader
] = _defaults.AUTOCAST_CALIBRATION_DATALOADER,
autocast_model_regions: str = _defaults.AUTOCAST_MODEL_REGIONS,
autocast_vector_norm_in_low_precision: bool = _defaults.AUTOCAST_VECTOR_NORM_IN_LOW_PRECISION,
cpu_memory_budget: Optional[int] = _defaults.CPU_MEMORY_BUDGET,
max_partition_size: Optional[int] = _defaults.MAX_PARTITION_SIZE,
enable_resource_partitioning: bool = _defaults.ENABLE_RESOURCE_PARTITIONING,
Expand Down Expand Up @@ -691,6 +692,7 @@ def compile(
autocast_max_depth_of_reduction (Optional[int]): Maximum depth of reduction allowed in low precision. Nodes with higher reduction depths will remain in FP32. This helps prevent excessive accuracy loss in operations particularly sensitive to reduced precision, as higher-depth reductions may amplify computation errors in low precision formats. If not provided, infinity will be used. Needs autocast_calibration_dataloader. Default is None.
autocast_calibration_dataloader (Optional[torch.utils.data.DataLoader]): The dataloader to use for autocast calibration. Default is None.
autocast_model_regions (str): What autocast does with the regions the model itself runs under torch.autocast. "keep" builds them with the precisions that PyTorch autocast gives them. "reclassify" removes their autocast, so that the autocast rules, exclusions and calibration of Torch-TensorRT choose the precision of every op in them too. Regions with enabled=False, which a model uses to keep ops in FP32, keep their autocast. So do regions whose values inlining would change, such as one that writes into a buffer in place, and regions inside a torch.no_grad() block when the model is exported with grad mode on. autocast_excluded_node_names also matches the names that ops have in the regions. Default is "keep".
autocast_vector_norm_in_low_precision (bool): Whether a 2-norm, torch.linalg.vector_norm(x) as F.normalize uses it, that autocast runs in the low precision type is written as sqrt(sum(x * x)) in that type. By default PyTorch computes it in FP32 for a float16 or bfloat16 x, as eager does, which adds casts around it. TensorRT then chooses how to square and sum in float16, and a float16 sum of squares overflows for a norm above about 256, so check the accuracy, or keep such norms in FP32 with the exclusions. Default is False.
enable_resource_partitioning (bool): Enable resource-aware partitioning. This is useful when the model is large and the CPU memory is limited.
cpu_memory_budget (Optional[int]): With resource partitioning, the host memory in bytes the compilation may use: each TensorRT engine is sized to a quarter of what the process's resident memory leaves of it. Defaults to the available system memory.
max_partition_size (Optional[int]): The weight bytes per TensorRT engine the resource partitioner splits to: a finer control than ``cpu_memory_budget``, which it replaces, so the two can't both be set. The size is then not derived from the budget and the process's resident memory, so the same model and size always give the same split. Setting it turns resource partitioning on.
Expand Down Expand Up @@ -921,6 +923,7 @@ def compile(
"autocast_max_depth_of_reduction": autocast_max_depth_of_reduction,
"autocast_calibration_dataloader": autocast_calibration_dataloader,
"autocast_model_regions": autocast_model_regions,
"autocast_vector_norm_in_low_precision": autocast_vector_norm_in_low_precision,
"enable_resource_partitioning": enable_resource_partitioning,
"cpu_memory_budget": cpu_memory_budget,
"max_partition_size": max_partition_size,
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 @@ -78,6 +78,7 @@
AUTOCAST_MAX_DEPTH_OF_REDUCTION = None
AUTOCAST_CALIBRATION_DATALOADER = None
AUTOCAST_MODEL_REGIONS = "keep"
AUTOCAST_VECTOR_NORM_IN_LOW_PRECISION = False
ENABLE_RESOURCE_PARTITIONING = False
CPU_MEMORY_BUDGET = None
MAX_PARTITION_SIZE = None
Expand Down
8 changes: 8 additions & 0 deletions py/torch_tensorrt/dynamo/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
AUTOCAST_MAX_DEPTH_OF_REDUCTION,
AUTOCAST_MAX_OUTPUT_THRESHOLD,
AUTOCAST_MODEL_REGIONS,
AUTOCAST_VECTOR_NORM_IN_LOW_PRECISION,
BUILD_ROUTE,
CACHE_BUILT_ENGINES,
COLLAPSE_HIGH_RANK_PERMUTES,
Expand Down Expand Up @@ -175,6 +176,7 @@ class CompilationSettings:
autocast_max_depth_of_reduction (Optional[int]): Maximum depth of reduction allowed in low precision. Nodes with higher reduction depths will remain in FP32. This helps prevent excessive accuracy loss in operations particularly sensitive to reduced precision, as higher-depth reductions may amplify computation errors in low precision formats. If not provided, infinity will be used. Needs autocast_calibration_dataloader. Default is None.
autocast_calibration_dataloader (Optional[torch.utils.data.DataLoader]): The dataloader to use for autocast calibration. Default is None.
autocast_model_regions (str): What autocast does with the regions the model itself runs under torch.autocast. "keep" builds them with the precisions that PyTorch autocast gives them. "reclassify" removes their autocast, so that the autocast rules, exclusions and calibration of Torch-TensorRT choose the precision of every op in them too. Regions with enabled=False, which a model uses to keep ops in FP32, keep their autocast. So do regions whose values inlining would change, such as one that writes into a buffer in place, and regions inside a torch.no_grad() block when the model is exported with grad mode on. autocast_excluded_node_names also matches the names that ops have in the regions. Default is "keep".
autocast_vector_norm_in_low_precision (bool): Whether a 2-norm, torch.linalg.vector_norm(x) as F.normalize uses it, that autocast runs in the low precision type is written as sqrt(sum(x * x)) in that type. By default PyTorch computes it in FP32 for a float16 or bfloat16 x, as eager does, which adds casts around it. TensorRT then chooses how to square and sum in float16, and a float16 sum of squares overflows for a norm above about 256, so check the accuracy, or keep such norms in FP32 with the exclusions. Default is False.
max_partition_size (Optional[int]): The weight bytes per TensorRT engine the resource partitioner
splits to: a finer control than ``cpu_memory_budget``, which it replaces, so the two can't both be set. The
size is then not derived from the budget and the process's resident memory, so the same model and size always
Expand Down Expand Up @@ -285,6 +287,7 @@ class CompilationSettings:
AUTOCAST_CALIBRATION_DATALOADER
)
autocast_model_regions: str = AUTOCAST_MODEL_REGIONS
autocast_vector_norm_in_low_precision: bool = AUTOCAST_VECTOR_NORM_IN_LOW_PRECISION
# Set by autocast, not by users: the nodes it kept in high precision using the
# calibration data. Saved in place of the data so refit can reuse the choice.
_autocast_calibrated_high_precision_nodes: Optional[FrozenSet[str]] = field(
Expand Down Expand Up @@ -415,6 +418,10 @@ def __setstate__(self, state: dict[str, Any]) -> None:
state.setdefault("max_partition_size", MAX_PARTITION_SIZE)
state.setdefault("autocast_excluded_node_names", AUTOCAST_EXCLUDED_NODE_NAMES)
state.setdefault("autocast_model_regions", AUTOCAST_MODEL_REGIONS)
state.setdefault(
"autocast_vector_norm_in_low_precision",
AUTOCAST_VECTOR_NORM_IN_LOW_PRECISION,
)
state.setdefault("_autocast_calibrated_high_precision_nodes", None)
self.__dict__.update(state)

Expand Down Expand Up @@ -442,6 +449,7 @@ def __setstate__(self, state: dict[str, Any]) -> None:
"autocast_max_output_threshold",
"autocast_max_depth_of_reduction",
"autocast_model_regions",
"autocast_vector_norm_in_low_precision",
"decompose_attention",
"disabled_constant_fold_exclusions",
"attn_bias_is_causal",
Expand Down
28 changes: 28 additions & 0 deletions py/torch_tensorrt/dynamo/lowering/passes/rule_based_autocast.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,28 @@ def _is_given_a_dtype(n: torch.fx.Node) -> bool:
return False


def _write_out_vector_norm(gm: torch.fx.GraphModule, node: torch.fx.Node) -> None:
"""Replace a 2-norm, linalg_vector_norm(x, 2, dim, keepdim), with
sqrt(sum(x * x, dim, keepdim)) in the dtype of x. PyTorch's decomposition squares
and sums a float16 or bfloat16 x in float32, with casts around it."""
names = [a.name for a in node.target._schema.arguments]
args = {**dict(zip(names, node.args)), **node.kwargs}
x = args["self"]
if args.get("ord", 2) != 2:
return
with gm.graph.inserting_before(node):
square = gm.graph.call_function(torch.ops.aten.mul.Tensor, (x, x))
total = gm.graph.call_function(
torch.ops.aten.sum.dim_IntList,
(square, args.get("dim"), args.get("keepdim", False)),
)
root = gm.graph.call_function(torch.ops.aten.sqrt.default, (total,))
square.meta["val"] = x.meta["val"]
total.meta["val"] = root.meta["val"] = node.meta["val"]
node.replace_all_uses_with(root)
gm.graph.erase_node(node)


def _has_only_integer_outputs(n: torch.fx.Node) -> bool:
tensors = [
v for v in pytree.tree_leaves(n.meta.get("val")) if isinstance(v, torch.Tensor)
Expand Down Expand Up @@ -395,6 +417,12 @@ def _cast_args_to_traced_dtypes(node: torch.fx.Node) -> None:
):
# With only bool inputs, mask * 0.5 still makes float32.
node.meta["val"] = _retype_tensors(node.meta["val"], target_dtype)
if (
settings.autocast_vector_norm_in_low_precision
and target_dtype == autocast_low_precision_type
and node.target == torch.ops.aten.linalg_vector_norm.default
):
_write_out_vector_norm(gm, node)

gm = clean_up_graph_after_modifications(gm)
logger.debug("Graph after Autocast based on the rules:\n%s", gm.graph)
Expand Down
60 changes: 60 additions & 0 deletions tests/py/dynamo/models/test_autocast.py
Original file line number Diff line number Diff line change
Expand Up @@ -2233,6 +2233,66 @@ def test_autocast_model_regions_rejects_unknown_values():
CompilationSettings(autocast_model_regions="inline")


@pytest.mark.unit
@pytest.mark.parametrize("in_low_precision", [False, True])
def test_autocast_vector_norm_in_low_precision(in_low_precision):
class Model(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(4, 8, 3, padding=1)
self.conv2 = nn.Conv2d(8, 8, 3, padding=1)

def forward(self, x):
h = self.conv1(x)
# The 1-norm and the excluded 2-norm keep linalg_vector_norm.
scale = torch.linalg.vector_norm(h, 1, dim=1, keepdim=True)
kept = torch.linalg.vector_norm(h, dim=(2, 3), keepdim=True)
return self.conv2(nn.functional.normalize(h, dim=1)) * scale + kept

model = Model().cuda().eval()
x = torch.randn(1, 4, 16, 16, device="cuda")
ep = torch.export.export(model, (x,))
l1, normalize, excluded = [
n.name
for n in ep.graph.find_nodes(
op="call_function", target=torch.ops.aten.linalg_vector_norm.default
)
]
kwargs = dict(
enable_autocast=True,
autocast_low_precision_type=torch.float16,
autocast_excluded_node_names={f"{excluded}$"},
autocast_vector_norm_in_low_precision=in_low_precision,
)
graph = pre_export_lowering(ep, CompilationSettings(**kwargs)).graph
norms = {
n.name: n.meta["val"].dtype
for n in graph.find_nodes(
op="call_function", target=torch.ops.aten.linalg_vector_norm.default
)
}
sums = graph.find_nodes(op="call_function", target=torch.ops.aten.sum.dim_IntList)
if in_low_precision:
assert norms == {l1: torch.float16, excluded: torch.float32}
(total,) = sums
assert total.meta["val"].dtype == torch.float16
else:
assert norms == {
l1: torch.float16,
normalize: torch.float16,
excluded: torch.float32,
}
assert not sums

trt_model = torch_tensorrt.dynamo.compile(
torch.export.export(model, (x,)), arg_inputs=[x], min_block_size=1, **kwargs
)
ref = model(x)
torch.testing.assert_close(
trt_model(x).float(), ref, rtol=1e-2, atol=1e-2 * ref.abs().max().item()
)


@pytest.mark.unit
@pytest.mark.critical
@pytest.mark.parametrize(
Expand Down
Loading