Skip to content

Commit ed41a28

Browse files
Fix cast removal bug (#17953)
The `RemoveDuplicateCastTransformer` fairly naively removed Cast nodes from the graph without considering precision loss when using the same `TypeGroup`. For instance, F64 -> F32 -> F64 would be optimised out of the graph. I also noticed that signedness was not accounted for, which is not covered by any existing issue but is a problem. For example doing int -> unsigned int -> int produces very different values for negative inputs and so should not be optimised out One could argue that we shouldn't be performing such cast elimination at all (at least not in this transformer). The original scope might be well restricted to only eliminating unnecessary casts from the `InsertCastTransformer` and no others. ### Motivation and Context This should fix #17565, ttps://github.com//issues/9915 and #8787.
1 parent 20f2dd8 commit ed41a28

File tree

2 files changed

+133
-18
lines changed

2 files changed

+133
-18
lines changed

onnxruntime/core/optimizer/insert_cast_transformer.cc

+68-18
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ onnxruntime::NodeArg* AddCastNode(onnxruntime::Graph& graph,
3232
int64_t to_type,
3333
onnxruntime::ProviderType providerType) {
3434
// insert cast op to cast input
35-
std::string node_name = graph.GenerateNodeName("InsertedCast_" + old_arg->Name());
35+
std::string node_name = graph.GenerateNodeName("InsertedPrecisionFreeCast_" + old_arg->Name());
3636

3737
auto* new_arg = &graph.GetOrCreateNodeArg(node_name, new_type);
3838

@@ -235,33 +235,95 @@ enum TypeGroup {
235235
Unknown = -1,
236236
Bool = 0,
237237
Integer = 1,
238-
Float = 2,
238+
Unsigned = 2,
239+
Float = 3,
239240
};
240241

241242
TypeGroup GetTypeGroup(DataType type) {
242243
if (*type == "tensor(bool)") {
243244
return Bool;
244245
}
245246

246-
if (*type == "tensor(int16)" || *type == "tensor(int32)" || *type == "tensor(int64)" || *type == "tensor(int8)" ||
247-
*type == "tensor(uint16)" || *type == "tensor(uint32)" || *type == "tensor(uint64)" || *type == "tensor(uint8)") {
247+
if (*type == "tensor(int16)" || *type == "tensor(int32)" || *type == "tensor(int64)" || *type == "tensor(int8)") {
248248
return Integer;
249249
}
250250

251+
if (*type == "tensor(uint16)" || *type == "tensor(uint32)" || *type == "tensor(uint64)" || *type == "tensor(uint8)") {
252+
return Unsigned;
253+
}
254+
251255
if (*type == "tensor(bfloat16)" || *type == "tensor(double)" || *type == "tensor(float)" || *type == "tensor(float16)") {
252256
return Float;
253257
}
254258

255259
return Unknown;
256260
}
257261

262+
int BitLength(DataType type) {
263+
if (*type == "tensor(bool)") {
264+
return 1;
265+
} else if (*type == "tensor(uint8)" || *type == "tensor(int8)") {
266+
return 8;
267+
} else if (*type == "tensor(int16)" || *type == "tensor(uint16)" || *type == "tensor(bfloat16)" || *type == "tensor(float16)") {
268+
return 16;
269+
} else if (*type == "tensor(int32)" || *type == "tensor(uint32)" || *type == "tensor(float)") {
270+
return 32;
271+
} else if (*type == "tensor(int64)" || *type == "tensor(uint64)" || *type == "tensor(double)") {
272+
return 64;
273+
} else {
274+
return -1;
275+
}
276+
}
277+
258278
/** Transformer to remove duplicate Cast nodes. */
259279
class RemoveDuplicateCastTransformer : public GraphTransformer {
260280
public:
261281
RemoveDuplicateCastTransformer() : GraphTransformer("RemoveDuplicateCastTransformer") {
262282
}
263283

264284
private:
285+
static bool UnsafeCast(DataType src_type, DataType dst_type, const Node& node) {
286+
// This is not a complete cast optimisation pass, and is more conservative than it could be.
287+
// For instance, certain integral -> floating point casts could be optimised but this is left to an explicit cast optimisation pass.
288+
289+
// The comparison with "InsertedPrecisionFreeCast_" reflects cast nodes that are inserted by InsertCastTransformer.
290+
// Such casts should not be considered as loss of precision - the inserted upcasts (f16 -> f32) and downcasts (f32 -> f16) are inserted to support kernels when on a CPU EP without F16 support.
291+
auto src_type_group = GetTypeGroup(src_type);
292+
auto dst_type_group = GetTypeGroup(dst_type);
293+
if (Unknown == src_type_group || Unknown == dst_type_group) {
294+
return true;
295+
}
296+
297+
// Do not remove any signed -> unsigned cast.
298+
if ((src_type_group != Bool && src_type_group != Unsigned) && Unsigned == dst_type_group) {
299+
return true;
300+
}
301+
302+
// Do not remove any floating point -> non floating point cast.
303+
if (Float == src_type_group && Float != dst_type_group) {
304+
return true;
305+
}
306+
307+
auto src_bit_length = BitLength(src_type);
308+
auto dst_bit_length = BitLength(dst_type);
309+
310+
// unsigned integer -> integer cast may overflow if the destination integer is smaller or equal to the source integer.
311+
if (Unsigned == src_type_group && Integer == dst_type_group) {
312+
return dst_bit_length <= src_bit_length;
313+
}
314+
315+
// integral -> floating cast may overflow if integer cannot be encoded in the mantissa. This check could be more precise.
316+
if ((Integer == src_type_group || Unsigned == src_type_group) && Float == dst_type_group) {
317+
return dst_bit_length <= src_bit_length;
318+
}
319+
320+
if ((*src_type == "tensor(float16)" && *dst_type == "tensor(bfloat16)") || (*src_type == "tensor(bfloat16)" && *dst_type == "tensor(float16)")) {
321+
return true;
322+
}
323+
324+
return src_bit_length > dst_bit_length && (node.Name().compare(0, 26, "InsertedPrecisionFreeCast_"));
325+
}
326+
265327
Status ApplyImpl(Graph& graph, bool& modified, int graph_level, const logging::Logger& logger) const override {
266328
auto output_args = graph.GetOutputs();
267329
InlinedHashSet<const onnxruntime::NodeArg*> graph_outputs;
@@ -293,17 +355,8 @@ class RemoveDuplicateCastTransformer : public GraphTransformer {
293355
// - for each consumer cast node, it meets above condition for this optimization.
294356
auto src_type = node.InputDefs()[0]->Type();
295357
auto dst_type = node.OutputDefs()[0]->Type();
296-
TypeGroup src_type_group = GetTypeGroup(src_type);
297-
TypeGroup dst_type_group = GetTypeGroup(dst_type);
298-
if (src_type_group == Unknown || dst_type_group == Unknown) {
299-
continue;
300-
}
301-
302-
bool loss_precision_cast = false;
303-
if (src_type_group > dst_type_group) {
304-
loss_precision_cast = true;
305-
}
306358

359+
bool loss_precision_cast = UnsafeCast(src_type, dst_type, node);
307360
size_t num_children = node.GetOutputEdgesCount();
308361

309362
bool inconsistent_casts = false;
@@ -312,10 +365,7 @@ class RemoveDuplicateCastTransformer : public GraphTransformer {
312365
if (output_node.OpType() == "Cast") {
313366
auto src_type1 = output_node.InputDefs()[0]->Type();
314367
auto dst_type1 = output_node.OutputDefs()[0]->Type();
315-
TypeGroup src_type_group1 = GetTypeGroup(src_type1);
316-
TypeGroup dst_type_group1 = GetTypeGroup(dst_type1);
317-
if (src_type_group1 == Unknown || dst_type_group1 == Unknown ||
318-
(loss_precision_cast && dst_type_group1 > src_type_group1)) {
368+
if (loss_precision_cast && UnsafeCast(dst_type1, src_type1, output_node)) {
319369
inconsistent_casts = true;
320370
break;
321371
}

onnxruntime/test/framework/insert_cast_transformer_test.cc

+65
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include "core/framework/allocator.h"
55
#include "core/optimizer/insert_cast_transformer.h"
66
#include "core/graph/model.h"
7+
#include "core/graph/node_attr_utils.h"
78
#include "gtest/gtest.h"
89
#include "test_utils.h"
910
#include "test/test_environment.h"
@@ -110,6 +111,70 @@ TEST(TransformerTest, InsertCastAllCPUTest) {
110111
}
111112
}
112113

114+
TEST(TransformerTest, CastRemovalDoesNotLowerPrecisionTest) {
115+
auto model = std::make_shared<onnxruntime::Model>("test", false, DefaultLoggingManager().DefaultLogger());
116+
onnxruntime::Graph& graph = model->MainGraph();
117+
TypeProto tensor_float_32;
118+
tensor_float_32.mutable_tensor_type()->set_elem_type(TensorProto_DataType_FLOAT);
119+
TypeProto tensor_float_64;
120+
tensor_float_64.mutable_tensor_type()->set_elem_type(TensorProto_DataType_DOUBLE);
121+
onnxruntime::NodeArg n1_def("N1", &tensor_float_64),
122+
n2_def("N2", &tensor_float_32),
123+
n3_def("N3", &tensor_float_64);
124+
125+
NodeAttributes n1_attrs = {{"to", utils::MakeAttribute("to", static_cast<int64_t>(ONNX_NAMESPACE::TensorProto_DataType_FLOAT))}};
126+
NodeAttributes n2_attrs = {{"to", utils::MakeAttribute("to", static_cast<int64_t>(ONNX_NAMESPACE::TensorProto_DataType_DOUBLE))}};
127+
128+
graph.AddNode("node1", "Cast", "F64 to F32 cast", ArgMap{&n1_def}, ArgMap{&n2_def}, &n1_attrs);
129+
graph.AddNode("node2", "Cast", "F32 to F64 cast", ArgMap{&n2_def}, ArgMap{&n3_def}, &n2_attrs);
130+
131+
auto status = graph.Resolve();
132+
ASSERT_TRUE(status.IsOK()) << status.ErrorMessage();
133+
134+
InsertCastTransformer cast_inserter("Test", DefaultCpuExecutionProvider()->GetKernelRegistry().get());
135+
136+
bool modified = true;
137+
status = cast_inserter.Apply(graph, modified, DefaultLoggingManager().DefaultLogger());
138+
EXPECT_TRUE(status.IsOK()) << status.ErrorMessage();
139+
status = graph.Resolve();
140+
EXPECT_TRUE(status.IsOK()) << status.ErrorMessage();
141+
142+
// When casting f64 -> f32 -> f64 we should not be optimising away the cast since there is a loss of precision.
143+
EXPECT_EQ(graph.NumberOfNodes(), 2);
144+
}
145+
146+
TEST(TransformerTest, CastRemovalDoesNotRemoveSignednessTest) {
147+
auto model = std::make_shared<onnxruntime::Model>("test", false, DefaultLoggingManager().DefaultLogger());
148+
onnxruntime::Graph& graph = model->MainGraph();
149+
TypeProto tensor_uint32;
150+
tensor_uint32.mutable_tensor_type()->set_elem_type(TensorProto_DataType_UINT32);
151+
TypeProto tensor_int32;
152+
tensor_int32.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT32);
153+
onnxruntime::NodeArg n1_def("N1", &tensor_int32),
154+
n2_def("N2", &tensor_uint32),
155+
n3_def("N3", &tensor_int32);
156+
157+
NodeAttributes n1_attrs = {{"to", utils::MakeAttribute("to", static_cast<int64_t>(ONNX_NAMESPACE::TensorProto_DataType_UINT32))}};
158+
NodeAttributes n2_attrs = {{"to", utils::MakeAttribute("to", static_cast<int64_t>(ONNX_NAMESPACE::TensorProto_DataType_INT32))}};
159+
160+
graph.AddNode("node1", "Cast", "I32 to UI32 cast", ArgMap{&n1_def}, ArgMap{&n2_def}, &n1_attrs);
161+
graph.AddNode("node2", "Cast", "UI32 to I32 cast", ArgMap{&n2_def}, ArgMap{&n3_def}, &n2_attrs);
162+
163+
auto status = graph.Resolve();
164+
ASSERT_TRUE(status.IsOK()) << status.ErrorMessage();
165+
166+
InsertCastTransformer cast_inserter("Test", DefaultCpuExecutionProvider()->GetKernelRegistry().get());
167+
168+
bool modified = true;
169+
status = cast_inserter.Apply(graph, modified, DefaultLoggingManager().DefaultLogger());
170+
EXPECT_TRUE(status.IsOK()) << status.ErrorMessage();
171+
status = graph.Resolve();
172+
EXPECT_TRUE(status.IsOK()) << status.ErrorMessage();
173+
174+
// When casting i32 -> ui32 -> i32 we should not be optimising away the cast since applying the casts produces a very different result.
175+
EXPECT_EQ(graph.NumberOfNodes(), 2);
176+
}
177+
113178
// test that when there are 3 Cast ops in a row we remove the correct ones
114179
TEST(TransformerTest, ThreeInARowRemoval) {
115180
auto model_uri = MODEL_FOLDER ORT_TSTR("triple-cast.onnx");

0 commit comments

Comments
 (0)