Skip to content

fix(autocast): keep copies that in-place writes need; add opt-in settings for model casts and the 2-norm - #5058

Open
shoumikhin wants to merge 3 commits into
pytorch:mainfrom
shoumikhin:autocast-model-casts
Open

shoumikhin wants to merge 3 commits into
pytorch:mainfrom
shoumikhin:autocast-model-casts

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

In-place writes after a cast give wrong values with the default settings. After autocast, z = h.half() can return h itself, since h is already float16:

h = self.lin(x)   # autocast runs it in float16
z = h.half()
z.mul_(2.0)       # must not change h

type_as and to.other do the same.

A model's own casts to FP32, such as x.float(), stay. Between 2 float16 ops, such a cast is a round trip.

The 2-norm (L2 norm). PyTorch computes a float16 2-norm, as in F.normalize, in float32, with casts around it.

What this change does

  1. A fix that changes the default path. Before autocast, every to() cast that changed the dtype when traced gets copy=True, and such a type_as or to.other becomes to.other(..., copy=True). It does not search for the writing op, so writes through dropout in eval mode, atleast_1d, a torch.autocast block or a split piece are covered, as is a type_as inside a torch.no_grad() block. autocast_excluded_ops still matches such a type_as as type_as. TensorRT adds no layer for a cast to the same dtype, while a segment that runs in PyTorch makes one copy. It shares this code with the region inliner.

  2. autocast_model_casts="reclassify", off by default. It removes round trips through the model's own casts to FP32. Values stay the same, except that an in-place write into x.float() of an FP32 model now matches eager.

  3. autocast_l2_norm_in_low_precision=True, off by default. It writes such a 2-norm as m * sqrt(sum((x / m) ** 2)) in the low precision type, where m is the largest magnitude of x, so a float16 sum does not overflow.

torch_tensorrt.dynamo.compile(
    ep, arg_inputs=[x], enable_autocast=True,
    autocast_low_precision_type=torch.float16,
    autocast_model_casts="reclassify", autocast_l2_norm_in_low_precision=True,
)

Neither is known to make a model faster: the first did not change latency in my tests, and the second adds a reduction.

Still open, also on main: a cast that returned its input when traced but copies after autocast, and a to() cast inside a torch.no_grad() block whose input autocast gives another dtype (export's dtype check fails).

What was tested

On an A100 with a PyTorch 2.16 nightly and TensorRT 11.4:

  • test_autocast.py and the lowering tests at each commit: all pass except tests that also fail on main. Each new test fails without its fix.
  • Default settings: the graphs of the existing autocast tests match main except for the added copy=True.

@meta-cla meta-cla Bot added the cla signed label Nov 16, 2026
@github-actions github-actions Bot added documentation Improvements or additions to documentation component: tests Issues re: Tests component: lowering Issues re: The lowering / preprocessing passes component: core Issues re: The core compiler component: api [Python] Issues re: Python API component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths labels Nov 16, 2026
@github-actions
github-actions Bot requested a review from narendasan November 16, 2026 14:59
@shoumikhin shoumikhin changed the title feat(autocast): opt-in settings to let autocast choose the precision of a model's own FP32 casts and 2-norms feat(autocast): autocast_model_casts="reclassify" lets autocast choose the precision of a model's own casts to FP32 Nov 17, 2026
@shoumikhin shoumikhin changed the title feat(autocast): autocast_model_casts="reclassify" lets autocast choose the precision of a model's own casts to FP32 feat(autocast): autocast_model_casts="reclassify" removes round trips through a model's own casts to FP32 Nov 18, 2026
@shoumikhin shoumikhin changed the title feat(autocast): autocast_model_casts="reclassify" removes round trips through a model's own casts to FP32 feat(autocast): opt-in settings for a model's own FP32 casts and for vector norm Nov 18, 2026
@shoumikhin

shoumikhin commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@narendasan could you take a look when you have a moment? It adds opt-in settings that remove extra FP32 casts that autocast keeps around ops it already runs in low precision. It also fixes wrong values from in-place writes after a cast with the default autocast settings. The red jobs are not from this PR. The same tests fail on main and on the other open PRs, and #5059 fixes them.

@zewenli98 zewenli98 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @shoumikhin for the great contribution. Since autocast_model_casts="reclassify" reduces the dtype conversions back and forth, I was wondering if you observed latency drop with the flag on? I thought TRT would do this for us while building engines. But anyways, this makes the FX graph clearer

@shoumikhin

Copy link
Copy Markdown
Contributor Author

Thanks @zewenli98. No, I did not see a latency drop, and you are right that TensorRT already takes care of these round trips. I built engines with autocast_model_casts set to "keep" and to "reclassify" (float16 autocast) on an A100 with TensorRT 11.4 and timed them interleaved: a 6-layer transformer with FP32 layer norm and softmax ran in 1.287 ms vs 1.282 ms, and a Llama model in the SmolLM2-135M shape ran in 3.290 ms vs 3.291 ms. Both engines had the same number of layers and the same error against eager FP32. The gain is the clearer FX graph you mention (429 graph casts down to 2 for the Llama model) and a smaller network for TensorRT, so I updated the description so it does not suggest a speedup.

@shoumikhin
shoumikhin force-pushed the autocast-model-casts branch 2 times, most recently from 0587093 to 13d8c3f Compare November 23, 2026 10:42
@shoumikhin shoumikhin changed the title feat(autocast): opt-in settings for a model's own FP32 casts and for vector norm feat(autocast): opt-in settings for a model's own FP32 casts and for the 2-norm Nov 23, 2026
@shoumikhin
shoumikhin force-pushed the autocast-model-casts branch 5 times, most recently from d95c61a to 929fafd Compare November 24, 2026 23:21
@shoumikhin shoumikhin changed the title feat(autocast): opt-in settings for a model's own FP32 casts and for the 2-norm fix(autocast): keep copies that in-place writes need; add opt-in settings for model casts and the 2-norm Nov 24, 2026
@shoumikhin
shoumikhin force-pushed the autocast-model-casts branch 2 times, most recently from bd9dfc3 to 73ba328 Compare November 25, 2026 19:11
@shoumikhin
shoumikhin force-pushed the autocast-model-casts branch 3 times, most recently from 17f531f to 30180d9 Compare November 26, 2026 03:21
…aced

A cast such as h.half() makes a copy when it changes the dtype. Autocast
can change the dtype of its input, so after autocast h can already be
float16, and then h.half() returns h itself. An op that writes in place
into the result then also changes h. x.type_as(y) and to.other(x, y)
behave the same way. For example, in a float32 model whose linear
autocast runs in float16:

    h = self.lin(x)
    z = h.half()
    z.mul_(2.0)  # must not change h

This gave wrong values with the default settings.

The region inliner already keeps such copies for the casts of the
regions it inlines. Now, before autocast, the same rule runs on the
whole program: every cast written with to() that changed the dtype when
traced gets copy=True, and such a type_as or to.other becomes
to.other(x, y, copy=True). autocast_excluded_ops matches such a type_as
as type_as too, as it does for an inlined one. The rule does not look
for the op that writes, so it also covers a write that reaches the cast
through an op that returns its input, such as dropout in eval mode,
atleast_1d or a torch.autocast block. Export keeps the ops of a
torch.autocast or torch.no_grad block in a graph of its own, so the rule
edits those graphs too, and recompiles each graph it changes, since the
region inliner can run their code before the whole graph is recompiled. This
covers the casts of a torch.autocast block and a type_as in a
torch.no_grad block. A to() cast in a torch.no_grad block still fails
when autocast gives its input another dtype, as before, since export
checks that dtype. A cast that still changes the dtype copies anyway, so
its values do not change. TensorRT adds no layer for a cast to the same
dtype, though in a segment that runs in PyTorch it is still a copy.

Autocast now also treats a to() with copy=True as a new tensor, not as
a view of its input, although its schema says it may return its input.
Otherwise, when view(dtype) reads such a type_as and something writes
into it in place, autocast left the cast as it was. The cast then made
the float16 that autocast gave y instead of the traced dtype, and
view(torch.int32) returned half as many values in the last dim. For
the same reason, an h.half() that view(dtype) reads no longer keeps the
op that makes h in float32.

The copies are decided before regions are inlined, since inlining
traces their ops again in other dtypes, so the casts that inlining adds
at the boundary of a region do not get copy=True.

The rule and the meta key that autocast_excluded_ops reads move from the
region inliner to pass_utils, which the inliner and pre_export_lowering
share, with the code that sets a schema argument, positionally or as a
keyword.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
… through a model's own casts to FP32

Autocast always keeps the casts to float32 that a model writes, such as
x.float() before F.normalize. An op that autocast runs in the low precision
type still casts its inputs to that type, so such a cast between two of
those ops only adds a round trip, for example float16 to float32 and back.

The new opt-in value autocast_model_casts="reclassify" removes these round
trips. A cast that autocast runs in the low precision type, and whose users
all cast their input to that type too, keeps the dtype of its input. The
values do not change, since a cast from float16 or bfloat16 to float32 is
exact. One case can differ: in a float32 model, x.float() returns x, so an
in-place write into it also changes x. "keep" makes that cast copy once
autocast makes x float16, while "reclassify" can keep it returning x, as
the model does.

Other casts still cast to float32: an excluded cast, one that makes an
output of the model, and one with a user in float32 or a user that depends
on the dtype of its input. Such a user is an op given a dtype, such as
sum(dtype=torch.float32), whose input autocast does not cast, or an op that
makes only integer or complex values, such as view_as_complex.

A reclassified cast that changed the dtype when traced keeps copy=True
from the default rule, so it still makes the copy it made then. An
in-place write into it and a view that needs a contiguous tensor, as in
x[::2].float().view(-1), see what they saw when traced. TensorRT adds no
layer for this cast.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>
…ision 2-norm in that type

PyTorch's decomposition of torch.linalg.vector_norm squares and sums a float16
or bfloat16 input in float32, as eager does. So a 2-norm that autocast runs in
float16, such as the one in F.normalize, still adds casts to float32 and back
around it.

The new opt-in setting autocast_l2_norm_in_low_precision=True writes such a
norm out as m * sqrt(sum((x / m) ** 2)), where m is the largest magnitude of
x along the reduced dimensions, and TensorRT runs it in the low precision
type. Dividing by m keeps each square at most 1, so in float16 the sum does
not overflow for a large norm. A square much smaller than 1 can still round
to 0. This needs no calibration data. The sum can still reach the number of
values it adds, so a norm of more values than the largest number of the type
(65504 in float16), of 0 values, of a 0-d tensor, or of a count not known
when compiling, stays as it is. m is clamped to the finite positive range of
the type, so a zero vector still has a norm of 0, and a vector that holds an
inf, such as a value above 65504 cast to float16, a norm of inf, as with the
setting off. For example, F.normalize of a vector of 300s or of 1e-4s gives
the same values as eager.

Only the 2-norm of linalg_vector_norm changes, which F.normalize, torch.norm
and Tensor.norm also use. Other norms, such as the 1-norm, a norm given a
dtype, and torch.linalg.norm, which exports another op, stay as they are. A
norm can still be kept in FP32 by excluding it, by its node name or the op
linalg_vector_norm. The norm keeps its name, so a program that returns it
still matches its signature. A norm that autocast keeps in its traced
float16, because a view(dtype) writes into it, is written out only when
autocast chose the low precision type for it.

The norms are written out after autocast has chosen every precision, so a cast
of a norm, such as vector_norm(h).float(), is reclassified like any other.

Signed-off-by: Anthony Shoumikhin <anthony@shoumikh.in>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla signed component: api [Python] Issues re: Python API component: core Issues re: The core compiler component: dynamo Issues relating to the `torch.compile` or `torch._dynamo.export` paths component: lowering Issues re: The lowering / preprocessing passes component: tests Issues re: Tests documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants