Repository navigation
fix(autocast): keep copies that in-place writes need; add opt-in settings for model casts and the 2-norm - #5058
shoumikhin wants to merge 3 commits into
Conversation
f462d35 to
3663052
Compare
3663052 to
31b218b
Compare
31b218b to
32bdee4
Compare
|
@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
left a comment
There was a problem hiding this comment.
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
32bdee4 to
8cf8433
Compare
|
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 |
0587093 to
13d8c3f
Compare
d95c61a to
929fafd
Compare
bd9dfc3 to
73ba328
Compare
17f531f to
30180d9
Compare
…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>
30180d9 to
0cafc43
Compare
What is wrong today
In-place writes after a cast give wrong values with the default settings. After autocast,
z = h.half()can returnhitself, sincehis already float16:type_asandto.otherdo 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
A fix that changes the default path. Before autocast, every
to()cast that changed the dtype when traced getscopy=True, and such atype_asorto.otherbecomesto.other(..., copy=True). It does not search for the writing op, so writes through dropout in eval mode,atleast_1d, atorch.autocastblock or asplitpiece are covered, as is atype_asinside atorch.no_grad()block.autocast_excluded_opsstill matches such atype_asastype_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.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 intox.float()of an FP32 model now matches eager.autocast_l2_norm_in_low_precision=True, off by default. It writes such a 2-norm asm * sqrt(sum((x / m) ** 2))in the low precision type, wheremis the largest magnitude ofx, so a float16 sum does not overflow.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 atorch.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.pyand the lowering tests at each commit: all pass except tests that also fail on main. Each new test fails without its fix.copy=True.