Skip to content

Commit

Permalink
Complete revamp of float/promotion sympy handling (#126905)
Browse files Browse the repository at this point in the history
Summary:
At a high level, the idea behind this PR is:

* Make it clearer what the promotion and int/float rules for various Sympy operations are. Operators that previously were polymorphic over int/float are now split into separate operators for clarity. We never do mixed int/float addition/multiplication etc in sympy, instead, we always promote to the appropriate operator. (However, equality is currently not done correctly.)
* Enforce strict typing on ValueRanges: if you have a ValueRange for a float, the lower and upper MUST be floats, and so forth for integers.

The story begins in **torch/utils/_sympy/functions.py**. Here, I make some changes to how we represent certain operations in sympy expressions:

* FloorDiv now only supports integer inputs; to do float floor division, do a truediv and then a trunc. Additionally, we remove the divide out addition by gcd optimization, because sympy gcd is over fields and is willing to generate rationals (but rationals are bad for ValueRange strict typing).
* ModularIndexing, LShift, RShift now assert they are given integer inputs.
* Mod only supports integer inputs; eventually we will support FloatMod (left for later work, when we build out Sympy support for floating operations). Unfortunately, I couldn't assert integer inputs here, because of a bad interaction with sympy's inequality solver that is used by the offline solver
* TrueDiv is split into FloatTrueDiv and IntTrueDiv. This allows for us to eventually generate accurate code for Python semantics IntTrueDiv, which is written in a special way to preserve precision when the inputs are >= 2**53 beyond what first coercing the integer to floats and then doing true division.
* Trunc is split to TruncToFloat and TruncToInt.
* Round is updated to return a float, not an int, making it consistent with the round op handler in Inductor. To get Python-style conversion to int, we call TruncToInt on the result.
* RoundDecimal updated to consistently only ever return a float
* Add ToFloat for explicit coercion to float (required so we can enforce strict ValueRanges typing)

In **torch/__init__.py**, we modify SymInt and SymFloat to appropriately call into new bindings that route to these refined sympy operations.  Also, we modify `torch.sym_min` and `torch.sym_max` to have promotion semantics (if one argument is a float, the return result is always a float), making them inconsistent with builtins.min/max, but possible to do type analysis without runtime information.

We also need to introduce some new op handlers in **torch/_inductor/ops_handler.py**:

* `to_int` for truncation to int64, directly corresponding to TruncToInt; this can be implemented by trunc and dtype, but with a dedicated handler it is more convenient for roundtripping in Sympy
* `int_truediv` for Python-style integer true division, which has higher precision than casting to floats and then running `truediv`

These changes have consequences. First, we need to make some administrative changes:

* Actually wire up these Sympy functions from SymInt/SymFloat in **torch/fx/experimental/sym_node.py**, including the new promotion rules (promote2)
* Add support for new Sympy functions in **torch/utils/_sympy/interp.py**, **torch/utils/_sympy/reference.py**
  * In particular, in torch.utils._sympy.reference, we have a strong preference to NOT do nontrivial compute, instead, everything in ops handler should map to a singular sympy function
  * TODO: I chose to roundtrip mod back to our Mod function, but I think I'm going to have to deal with the C/Python inconsistency this to fix tests here
* Add printer support for the Sympy functions in **torch/_inductor/codegen/common.py**, **torch/_inductor/codegen/cpp_utils.py**, **torch/_inductor/codegen/triton.py**. `int_truediv` and mixed precision equality is currently not implemented soundly, so we will lose precision in codegen for large values. TODO: The additions here are not exhaustive yet
* Update ValueRanges logic to use new sympy functions in **torch/utils/_sympy/value_ranges.py**. In general, we prefer to use the new Sympy function rather than try to roll things by hand, which is what was done previously for many VR analysis functions.

In **torch/fx/experimental/symbolic_shapes.py** we need to make some symbolic reasoning adjustments:

* Avoid generation of rational subexpressions by removing simplification of `x // y` into `floor(x / y)`. This simplification then triggers an addition simplification rule `(x + y) / c --> x / c + y / c` which is bad because x / c is a rational number now
* `_assert_bound_is_rational` is no more, we no longer generate rational bounds
* Don't intersect non-int value ranges with the `int_range`
* Support more sympy Functions for guard SYMPY_INTERP
* Assert the type of value range is consistent with the variable type

The new asserts uncovered necessary bug fixes:

* **torch/_inductor/codegen/cpp.py**, **torch/_inductor/select_algorithm.py**, **torch/_inductor/sizevars.py** - Ensure Wild/Symbol manually allocated in Inductor is marked `is_integer` so it's accepted to build expressions
* **torch/_inductor/utils.py** - make sure you actually pass in sympy.Expr to these functions
* **torch/_inductor/ir.py** - make_contiguous_strides_for takes int/SymInt, not sympy.Expr!
* **torch/export/dynamic_shapes.py** - don't use infinity to represent int ranges, instead use sys.maxsize - 1

Because of the removal of some symbolic reasoning that produced rationals, some of our symbolic reasoning has gotten worse and we are unable to simplify some guards. Check the TODO at **test/test_proxy_tensor.py**

**Reland notes.** This requires this internal fbcode diff https://www.internalfb.com/phabricator/paste/view/P1403322587 but I cannot prepare the diff codev due to https://fb.workplace.com/groups/osssupport/posts/26343544518600814/

It also requires this Executorch PR pytorch#3911 but the ET PR can be landed prior to this landing.

Signed-off-by: Edward Z. Yang <[email protected]>

X-link: pytorch/pytorch#126905
Approved by: https://github.com/xadupre, https://github.com/lezcano

bypass-github-export-checks

Reviewed By: atalman

Differential Revision: D58333817

Pulled By: ezyang

fbshipit-source-id: 7b6c6f8184db7ca4ac55fc938ac97183f6969ce4
  • Loading branch information
ezyang authored and facebook-github-bot committed Jun 10, 2024
1 parent bd3acf2 commit 27d5329
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 4 deletions.
8 changes: 4 additions & 4 deletions examples/selective_build/test_selective_build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ test_buck2_select_ops_in_list() {
${PYTHON_EXECUTABLE} -m examples.portable.scripts.export --model_name="add_mul"

echo "Running selective build test"
# set max_kernel_num=18: 16 primops, add, mul
# set max_kernel_num=19: 17 primops, add, mul
$BUCK run //examples/selective_build:selective_build_test \
--config=executorch.max_kernel_num=18 \
--config=executorch.max_kernel_num=19 \
--config=executorch.select_ops=list \
-- --model_path=./add_mul.pte

Expand Down Expand Up @@ -100,11 +100,11 @@ test_cmake_select_ops_in_list() {

local example_dir=examples/selective_build
local build_dir=cmake-out/${example_dir}
# set MAX_KERNEL_NUM=18: 16 primops, add, mul
# set MAX_KERNEL_NUM=19: 17 primops, add, mul
rm -rf ${build_dir}
retry cmake -DBUCK2="$BUCK" \
-DCMAKE_BUILD_TYPE=Release \
-DMAX_KERNEL_NUM=18 \
-DMAX_KERNEL_NUM=19 \
-DEXECUTORCH_SELECT_OPS_LIST="aten::convolution.out,\
aten::_native_batch_norm_legit_no_training.out,aten::hardtanh.out,aten::add.out,\
aten::mean.out,aten::view_copy.out,aten::permute_copy.out,aten::addmm.out,\
Expand Down
1 change: 1 addition & 0 deletions exir/pass_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@

_TORCH_SYM_OPS: Set[Any] = { # pyre-ignore
torch.sym_int,
torch.sym_float,
torch.sym_ite,
torch.sym_max,
torch.sym_min,
Expand Down
6 changes: 6 additions & 0 deletions exir/passes/executorch_prim_ops_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ def truediv(a: _SymScalar, b: _SymScalar) -> _SymScalar:
return a / b # pyre-ignore


@bind_pattern_to_op(executorch_prims_lib, "sym_float.Scalar(Scalar a) -> Scalar")
def sym_float(a: _SymScalar) -> _SymScalar:
return float(a) # pyre-ignore


# TODO: ideally we should return SymBool in the schema, but it seems
# the schema parser does not recognize SymBool yet: P629748075
@bind_pattern_to_op(executorch_prims_lib, "gt.Scalar(Scalar a, Scalar b) -> bool")
Expand Down Expand Up @@ -87,6 +92,7 @@ def eq(a: _SymScalar, b: _SymScalar) -> bool:
operator.lt: ops.backend.executorch_prim.lt.Scalar,
operator.ge: ops.backend.executorch_prim.ge.Scalar,
operator.le: ops.backend.executorch_prim.le.Scalar,
torch.sym_float: ops.backend.executorch_prim.sym_float.Scalar,
}


Expand Down
1 change: 1 addition & 0 deletions exir/serde/export_serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ def _reverse_map(d: Dict[Any, Enum]):
operator.mod,
torch.sym_sqrt,
torch.sym_int,
torch.sym_float,
torch.sym_ite,
torch.sym_max,
torch.sym_min,
Expand Down
21 changes: 21 additions & 0 deletions kernels/prim_ops/register_prim_ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,27 @@ static Kernel prim_ops[] = {
}
}),

// executorch_prim::sym_float.Scalar(Scalar) -> Scalar
Kernel(
"executorch_prim::sym_float.Scalar",
[](RuntimeContext& context, EValue** stack) {
// can't use macro because of custom casting behavior
// TODO: Now that we are reliably generating conversion operators,
// we can remove the mixed type handling for other operators
(void)context;
EValue& a = *stack[0];
EValue& out = *stack[1];
if (a.isInt()) {
out = EValue(static_cast<double>(a.toInt()));
} else if (a.isDouble()) {
// TODO: This should be impossible
out = EValue(a.toDouble());
} else {
// TODO Fail using runtime context
ET_CHECK_MSG(false, "%zu", (size_t)a.tag);
}
}),

// executorch_prim::eq.Scalar(Scalar, Scalar) -> bool
Kernel(
"executorch_prim::eq.Scalar",
Expand Down
3 changes: 3 additions & 0 deletions kernels/prim_ops/test/prim_ops_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ TEST_F(RegisterPrimOpsTest, TestAlgebraOps) {

getOpsFn("executorch_prim::truediv.Scalar")(context, stack);
EXPECT_FLOAT_EQ(stack[2]->toDouble(), 0.75);

getOpsFn("executorch_prim::sym_float.Scalar")(context, stack);
EXPECT_FLOAT_EQ(stack[1]->toDouble(), 3.0);
}

TEST_F(RegisterPrimOpsTest, TestETCopyIndex) {
Expand Down

0 comments on commit 27d5329

Please sign in to comment.