Skip to content

Commit

Permalink
core: Adding option to print full precision fp (#3381)
Browse files Browse the repository at this point in the history
`mlir-opt` attempts to print floats as 6dp scientific notation, but
round-trips to ensure there is no precision loss and the printed number
will bitwise reproduce exactly. If this fails, it will choose a
different printing method to ensure bit-reproducible printing for a
given precision of fp types.

This PR takes the approach of mlir-opt: attempt to print to scientific
6dp notation iff the resulting string is losslessly reproducible, or
else print to full precision using repr. This has the advantage of not
affecting a vast number of filechecks, mirroring upstream, and not
having a flag for either full or reduced precision.

---------

Co-authored-by: n-io <[email protected]>
  • Loading branch information
2 people authored and lfrenot committed Nov 4, 2024
1 parent 77505b5 commit 6460b2d
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions xdsl/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,10 +560,17 @@ def print_attribute(self, attribute: Attribute) -> None:
return

if isinstance(attribute, FloatAttr):
attr = cast(AnyFloatAttr, attribute)
self.print_float(attr)
self.print_string(" : ")
self.print_attribute(attr.type)
value = attribute.value
attr_type = cast(
FloatAttr[Float16Type | Float32Type | Float64Type], attribute
).type
# to mirror mlir-opt, attempt to print scientific notation iff the value parses losslessly
float_str = f"{value.data:.6e}"
if float(float_str) == value.data:
self.print_string(f"{float_str} : ")
else:
self.print_string(f"{repr(value.data)} : ")
self.print_attribute(attr_type)
return

# Complex types have MLIR shorthands but XDSL does not.
Expand Down Expand Up @@ -623,7 +630,11 @@ def print_one_elem(val: Attribute):
if isinstance(val, IntegerAttr):
self.print_string(f"{val.value.data}")
elif isinstance(val, FloatAttr):
self.print_float(cast(AnyFloatAttr, val))
float_str = f"{val.value.data:.6e}"
if float(float_str) == val.value.data:
self.print_string(float_str)
else:
self.print_string(f"{repr(val.value.data)}")
else:
raise Exception(
"unexpected attribute type "
Expand Down

0 comments on commit 6460b2d

Please sign in to comment.