You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2020/05/18 19:25:31 UTC

[GitHub] [incubator-tvm] yzhliu opened a new pull request #5618: [Arith] Inequalities solver

yzhliu opened a new pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618


   
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443963311



##########
File path: python/tvm/testing.py
##########
@@ -188,5 +189,96 @@ def assert_prim_expr_equal(lhs, rhs):
         raise ValueError("{} and {} are not equal".format(lhs, rhs))
 
 
+def check_bool_expr_is_true(bool_expr, vranges, cond=None):
+    """ Check that bool_expr holds given the condition cond
+    for every value of free variables from vranges.
+
+    Parameters
+    ----------
+    bool_expr : tvm.ir.expr.PrimExpr
+        Boolean expression to check
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    cond: tvm.ir.expr.PrimExpr
+        extra conditions needs to be satisfied.
+    """
+    if cond is not None:
+        bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr)
+
+    def _run_expr(expr, vranges):
+        """ Evaluate expr for every value of free variables
+        given by vranges and return the tensor of results.
+        """
+        def _compute_body(*us):
+            vmap = {v: u + r.min for (v, r), u in zip(vranges.items(), us)}
+            return tvm.tir.stmt_functor.substitute(expr, vmap)
+
+        A = tvm.te.compute([r.extent.value for v, r in vranges.items()], _compute_body)
+        args = [tvm.nd.empty(A.shape, A.dtype)]
+        sch = tvm.te.create_schedule(A.op)
+        mod = tvm.build(sch, [A])
+        mod(*args)
+        return args[0].asnumpy()
+
+    res = _run_expr(bool_expr, vranges)
+    if not np.all(res):
+        indices = list(np.argwhere(res == 0)[0])
+        counterex = [(str(v), i + r.min) for (v, r), i in zip(vranges.items(), indices)]
+        counterex = sorted(counterex, key=lambda x: x[0])
+        counterex = ", ".join([v + " = " + str(i) for v, i in counterex])
+        ana = tvm.arith.Analyzer()
+        raise AssertionError("Expression {}\nis not true on {}\n"
+                             "Counterexample: {}"
+                             .format(ana.simplify(bool_expr), vranges, counterex))
+
+
+def check_int_constraints_trans_consistency(constraints_trans, vranges=None):
+    """ Check IntConstraintsTransform is a bijective transformation.
+
+    Parameters
+    ----------
+    constraints_trans : arith.IntConstraintsTransform
+        Integer constraints transformation
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    """
+    if vranges is None:
+        vranges = {}
+
+    def _check_forward(constraints1, constraints2, varmap, backvarmap):
+        ana = tvm.arith.Analyzer()
+        all_vranges = vranges.copy()
+        all_vranges.update({v: r for v, r in constraints1.ranges.items()})
+
+        # Check that the transformation is injective
+        cond_on_vars = tvm.tir.const(1, 'bool')
+        for v in constraints1.variables:
+            # variable mapping is consistent
+            v_back = ana.simplify(tvm.tir.stmt_functor.substitute(varmap[v], backvarmap))
+            cond_on_vars = tvm.te.all(cond_on_vars, v == v_back)
+        # Also we have to check that the new relations are true when old relations are true
+        cond_subst = tvm.tir.stmt_functor.substitute(
+            tvm.te.all(tvm.tir.const(1, 'bool'), *constraints2.relations), backvarmap)
+        # We have to include relations from vranges too
+        for v in constraints2.variables:
+            if v in constraints2.ranges:
+                r = constraints2.ranges[v]
+                range_cond = tvm.te.all(v >= r.min, v < r.min + r.extent)
+                range_cond = tvm.tir.stmt_functor.substitute(range_cond, backvarmap)
+                cond_subst = tvm.te.all(cond_subst, range_cond)
+        cond_subst = ana.simplify(cond_subst)
+        check_bool_expr_is_true(
+            tvm.te.all(cond_subst, cond_on_vars), all_vranges,
+            cond=tvm.te.all(tvm.tir.const(1, 'bool'), *constraints1.relations))
+
+    rels = constraints_trans.dst.relations
+    if len(rels) == 1 and tvm.ir.structural_equal(rels[0], False):
+        # not solvable, skip

Review comment:
       yes.. but how can I detect the contradiction in the original constraints without running the solver? 




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443266079



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       Nice! I reproduced the bug on my old branch and debugged it a little bit. I think the real cause is a bug in the canonical simplifier, because on my branch it rewrites
   `((x0 - floordiv((x1*-5), 2)) + -1)` into `((x0 - ((x1*-5)/2)) - 1)` given ranges
   ```{x0: range(min=-20, ext=41), x1: range(min=-20, ext=41)}```. I'm not familiar with the internals of the canonical simplifier, so I don't know how to fix it properly (seems like when an expr is converted to SplitExpr, its div_mode is always initialized as kTruncDiv, which is wrong). Could you take a look?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] tqchen commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
tqchen commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r427561396



##########
File path: src/arith/util.cc
##########
@@ -27,6 +27,16 @@
 namespace tvm {
 namespace arith {
 
+int gcd(int a, int b) {

Review comment:
       gcd -> GreatestCommonDivisor

##########
File path: src/arith/util.cc
##########
@@ -49,5 +59,9 @@ std::tuple<int64_t, int64_t, int64_t> xgcd(int64_t a, int64_t b) {
   return std::make_tuple(old_r, old_s, old_t);
 }
 
+int lcm(int a, int b) {

Review comment:
       lcm ->  LeastCommonMultiple

##########
File path: src/arith/util.cc
##########
@@ -27,6 +27,16 @@
 namespace tvm {
 namespace arith {

Review comment:
       util-> utils (as per our previous discussion)




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-654270244


   @tqchen kindly ping


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r448630687



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,648 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Array<Var>& variables, const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  // use variables to keep the order of iteration
+  // so as to get rid of any non-determinism.
+  CHECK_EQ(variables.size(), bounds.size());
+  for (const auto v : variables) {
+    CHECK(bounds.count(v));
+    const auto& bnds = bounds[v];
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQ(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GE(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LE(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQ>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LT>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LT>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LE>(op->b, op->a); }
+
+ private:
+  template <class T>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<T, LT>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LE(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return T(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {

Review comment:
       nice catch.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r444310282



##########
File path: python/tvm/testing.py
##########
@@ -188,5 +189,96 @@ def assert_prim_expr_equal(lhs, rhs):
         raise ValueError("{} and {} are not equal".format(lhs, rhs))
 
 
+def check_bool_expr_is_true(bool_expr, vranges, cond=None):
+    """ Check that bool_expr holds given the condition cond
+    for every value of free variables from vranges.
+
+    Parameters
+    ----------
+    bool_expr : tvm.ir.expr.PrimExpr
+        Boolean expression to check
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    cond: tvm.ir.expr.PrimExpr
+        extra conditions needs to be satisfied.
+    """
+    if cond is not None:
+        bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr)
+
+    def _run_expr(expr, vranges):
+        """ Evaluate expr for every value of free variables
+        given by vranges and return the tensor of results.
+        """
+        def _compute_body(*us):
+            vmap = {v: u + r.min for (v, r), u in zip(vranges.items(), us)}
+            return tvm.tir.stmt_functor.substitute(expr, vmap)
+
+        A = tvm.te.compute([r.extent.value for v, r in vranges.items()], _compute_body)
+        args = [tvm.nd.empty(A.shape, A.dtype)]
+        sch = tvm.te.create_schedule(A.op)
+        mod = tvm.build(sch, [A])
+        mod(*args)
+        return args[0].asnumpy()
+
+    res = _run_expr(bool_expr, vranges)
+    if not np.all(res):
+        indices = list(np.argwhere(res == 0)[0])
+        counterex = [(str(v), i + r.min) for (v, r), i in zip(vranges.items(), indices)]
+        counterex = sorted(counterex, key=lambda x: x[0])
+        counterex = ", ".join([v + " = " + str(i) for v, i in counterex])
+        ana = tvm.arith.Analyzer()
+        raise AssertionError("Expression {}\nis not true on {}\n"
+                             "Counterexample: {}"
+                             .format(ana.simplify(bool_expr), vranges, counterex))
+
+
+def check_int_constraints_trans_consistency(constraints_trans, vranges=None):
+    """ Check IntConstraintsTransform is a bijective transformation.
+
+    Parameters
+    ----------
+    constraints_trans : arith.IntConstraintsTransform
+        Integer constraints transformation
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    """
+    if vranges is None:
+        vranges = {}
+
+    def _check_forward(constraints1, constraints2, varmap, backvarmap):
+        ana = tvm.arith.Analyzer()
+        all_vranges = vranges.copy()
+        all_vranges.update({v: r for v, r in constraints1.ranges.items()})
+
+        # Check that the transformation is injective
+        cond_on_vars = tvm.tir.const(1, 'bool')
+        for v in constraints1.variables:
+            # variable mapping is consistent
+            v_back = ana.simplify(tvm.tir.stmt_functor.substitute(varmap[v], backvarmap))
+            cond_on_vars = tvm.te.all(cond_on_vars, v == v_back)
+        # Also we have to check that the new relations are true when old relations are true
+        cond_subst = tvm.tir.stmt_functor.substitute(
+            tvm.te.all(tvm.tir.const(1, 'bool'), *constraints2.relations), backvarmap)
+        # We have to include relations from vranges too
+        for v in constraints2.variables:
+            if v in constraints2.ranges:
+                r = constraints2.ranges[v]
+                range_cond = tvm.te.all(v >= r.min, v < r.min + r.extent)
+                range_cond = tvm.tir.stmt_functor.substitute(range_cond, backvarmap)
+                cond_subst = tvm.te.all(cond_subst, range_cond)
+        cond_subst = ana.simplify(cond_subst)
+        check_bool_expr_is_true(
+            tvm.te.all(cond_subst, cond_on_vars), all_vranges,
+            cond=tvm.te.all(tvm.tir.const(1, 'bool'), *constraints1.relations))
+
+    rels = constraints_trans.dst.relations
+    if len(rels) == 1 and tvm.ir.structural_equal(rels[0], False):
+        # not solvable, skip

Review comment:
       You can check that the original constraints are false for all values of the variables. I would remove this check completely, I think _check_forward should do what is needed automatically or with some minor changes.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443241037



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,641 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  for (const auto iter : bounds) {

Review comment:
       Seems like this may be a source of non-determinism, consider passing the original array of variables as an argument to `as_conditions` to fix the order of iteration.
   (I'm so worried about determinism because in my experience the result of differentiation turned out to be very sensitive to slight variations in the algorithms, like the order of variables or conditions, and also non-determinism makes debugging much harder)




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r441904864



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +275,30 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         Constrains that cannot be transformed to Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);

Review comment:
       I would add some note on how the relations will look like, similarly to this: https://github.com/sergei-grechanik/tvm/blob/8cad2d1e62272b3e192bfe08b896e07bc9550e94/src/pass/zero_elimination.h#L227




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443921815



##########
File path: python/tvm/testing.py
##########
@@ -188,5 +189,96 @@ def assert_prim_expr_equal(lhs, rhs):
         raise ValueError("{} and {} are not equal".format(lhs, rhs))
 
 
+def check_bool_expr_is_true(bool_expr, vranges, cond=None):
+    """ Check that bool_expr holds given the condition cond
+    for every value of free variables from vranges.
+
+    Parameters
+    ----------
+    bool_expr : tvm.ir.expr.PrimExpr
+        Boolean expression to check
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    cond: tvm.ir.expr.PrimExpr
+        extra conditions needs to be satisfied.
+    """
+    if cond is not None:
+        bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr)
+
+    def _run_expr(expr, vranges):
+        """ Evaluate expr for every value of free variables
+        given by vranges and return the tensor of results.
+        """
+        def _compute_body(*us):
+            vmap = {v: u + r.min for (v, r), u in zip(vranges.items(), us)}
+            return tvm.tir.stmt_functor.substitute(expr, vmap)
+
+        A = tvm.te.compute([r.extent.value for v, r in vranges.items()], _compute_body)
+        args = [tvm.nd.empty(A.shape, A.dtype)]
+        sch = tvm.te.create_schedule(A.op)
+        mod = tvm.build(sch, [A])
+        mod(*args)
+        return args[0].asnumpy()
+
+    res = _run_expr(bool_expr, vranges)
+    if not np.all(res):
+        indices = list(np.argwhere(res == 0)[0])
+        counterex = [(str(v), i + r.min) for (v, r), i in zip(vranges.items(), indices)]
+        counterex = sorted(counterex, key=lambda x: x[0])
+        counterex = ", ".join([v + " = " + str(i) for v, i in counterex])
+        ana = tvm.arith.Analyzer()
+        raise AssertionError("Expression {}\nis not true on {}\n"
+                             "Counterexample: {}"
+                             .format(ana.simplify(bool_expr), vranges, counterex))
+
+
+def check_int_constraints_trans_consistency(constraints_trans, vranges=None):
+    """ Check IntConstraintsTransform is a bijective transformation.
+
+    Parameters
+    ----------
+    constraints_trans : arith.IntConstraintsTransform
+        Integer constraints transformation
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    """
+    if vranges is None:
+        vranges = {}
+
+    def _check_forward(constraints1, constraints2, varmap, backvarmap):
+        ana = tvm.arith.Analyzer()
+        all_vranges = vranges.copy()
+        all_vranges.update({v: r for v, r in constraints1.ranges.items()})
+
+        # Check that the transformation is injective
+        cond_on_vars = tvm.tir.const(1, 'bool')
+        for v in constraints1.variables:
+            # variable mapping is consistent
+            v_back = ana.simplify(tvm.tir.stmt_functor.substitute(varmap[v], backvarmap))
+            cond_on_vars = tvm.te.all(cond_on_vars, v == v_back)
+        # Also we have to check that the new relations are true when old relations are true
+        cond_subst = tvm.tir.stmt_functor.substitute(
+            tvm.te.all(tvm.tir.const(1, 'bool'), *constraints2.relations), backvarmap)
+        # We have to include relations from vranges too
+        for v in constraints2.variables:
+            if v in constraints2.ranges:
+                r = constraints2.ranges[v]
+                range_cond = tvm.te.all(v >= r.min, v < r.min + r.extent)
+                range_cond = tvm.tir.stmt_functor.substitute(range_cond, backvarmap)
+                cond_subst = tvm.te.all(cond_subst, range_cond)
+        cond_subst = ana.simplify(cond_subst)
+        check_bool_expr_is_true(
+            tvm.te.all(cond_subst, cond_on_vars), all_vranges,
+            cond=tvm.te.all(tvm.tir.const(1, 'bool'), *constraints1.relations))
+
+    rels = constraints_trans.dst.relations
+    if len(rels) == 1 and tvm.ir.structural_equal(rels[0], False):
+        # not solvable, skip

Review comment:
       I think it should be checked here that the original constraints are also unsolvable.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446365570



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       The issue resolves after merging the canonical simplify fix. I also remove the workaround for equations.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443165640



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +275,30 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         Constrains that cannot be transformed to Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);

Review comment:
       added. and also explain the relations form in `SolveLinearInequalities`




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443276092



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       It does not simplified to truncdiv in my branch though. I think the problem is rather like, `2x > 1` can be rounded to be `x > 1`, yet `2x == 1` cannot be rounded as `x == 1` or `x == 0`. The equations need to be specially handled.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-640256194


   @tqchen @sergei-grechanik @MarisaKirisame @eric-haibin-lin @ArmageddonKnight It's ready for review.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r441906157



##########
File path: python/tvm/arith/int_solver.py
##########
@@ -97,3 +143,33 @@ def solve_linear_equations(equations, variables=None, ranges=None):
     if isinstance(equations, IntConstraints):
         return _ffi_api.SolveLinearEquations(equations)
     return _ffi_api.SolveLinearEquations(variables, ranges, equations)
+
+
+def solve_linear_inequalities(equations, variables=None, ranges=None, deskew_range=False):
+    """Solve linear inequalities.
+
+    Parameters
+    ----------
+    equations   : List[tvm.ir.PrimExpr] or IntConstraints
+        The inequalities of the variables
+    variables   : Optional[List[tvm.tir.Var]]
+        The variables in the system.
+    ranges      : Optional[Map[tvm.tir.Var, tvm.ir.Range]]
+        The ranges of the variables.
+    deskew_range: Optional[bool]
+        Whether deskew the result ranges to be started from zero.
+        Default false.
+
+    Returns
+    -------
+    ret_ranges: IntConstraints or IntConstraintsTransform

Review comment:
       Adding another function. Returning IntConstraintsTransform when deskew_range=False is also ok, but I'm not sure how it is going to be used.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] tqchen merged pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
tqchen merged pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618


   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446359570



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,187 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solution_consistency():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)
+
+        solution = arith.solve_linear_inequalities(fs, vs, vranges, deskew_range=True)
+        testing.check_int_constraints_trans_consistency(solution)
+
+    for i in range(3):
+        _check(1, 1)
+    for i in range(3):
+        _check(1, 2)
+
+    for i in range(3):
+        _check(2, 1)
+    for i in range(3):
+        _check(2, 2)
+    for i in range(3):
+        _check(2, 3)
+
+    # Somewhere here coefficients in the results become too large, leading to overflow,
+    # so we use smaller initial coefficients
+    for i in range(5):
+        _check(3, 3, coef=(-2, 2))
+    for i in range(5):
+        _check(3, 4, coef=(-2, 2))
+
+    for i in range(5):
+        _check(4, 3, coef=(-1, 1))
+
+    for i in range(5):
+        _check(10, 2, coef=(-1, 1), bounds=(0, 4))
+    for i in range(5):
+        _check(10, 3, coef=(0, 1), bounds=(0, 4))
+
+
+def test_dual_variable():
+    x, y = te.var("x"), te.var("y")
+
+    variables = [x, y]
+    ranges = {
+        x: tvm.ir.Range(-100, 100),
+        y: tvm.ir.Range(0, 10),
+    }
+    problem = [
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ]
+
+    # solution as conditions
+    solution = arith._ffi_api.SolveInequalitiesAsCondition(variables, ranges, problem)
+    assert ir.structural_equal(solution[0], x >= (y + 10))
+    assert ir.structural_equal(solution[1], x <= (20 - y))
+    assert ir.structural_equal(solution[2], y >= 0)
+    assert ir.structural_equal(solution[3], y <= 5)
+
+    # solve and get the ranges
+    solution = arith.solve_linear_inequalities([
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ], [x, y], ranges)
+    # 0 <= y <=5
+    assert solution.ranges[y].min == 0
+    assert solution.ranges[y].extent == 6
+    # y + 10 <= x <= 20 - y
+    assert ir.structural_equal(solution.ranges[x].min, y + 10)
+    assert solution.ranges[x].extent == 11  # max(10 - 2y)
+
+    # deskew the solved ranges to be starting from zero
+    solution = arith.solve_linear_inequalities(problem, variables, ranges, deskew_range=True)
+    [x_new, y_new] = solution.dst.variables
+    [rel] = solution.dst.relations
+    assert ir.structural_equal(rel, (y_new*2) + x_new <= 10)
+    assert ir.structural_equal(solution.dst.ranges[x_new].min, 0)
+    assert ir.structural_equal(solution.dst.ranges[x_new].extent, 11)
+    assert ir.structural_equal(solution.dst.ranges[y_new].min, 0)
+    assert ir.structural_equal(solution.dst.ranges[y_new].extent, 6)
+    assert ir.structural_equal(solution.src_to_dst[x], x_new + (y_new + 10))
+    assert ir.structural_equal(solution.src_to_dst[y], y_new)
+    assert ir.structural_equal(solution.dst_to_src[x_new], x - y - 10)
+    assert ir.structural_equal(solution.dst_to_src[y_new], y)
+
+
+def test_equal():
+    x, y = te.var("x"), te.var("y")
+    problem = [
+        tvm.tir.GE(x + y, 10),
+        tvm.tir.GE(x - y, 2),
+        tvm.tir.LE(x, 6),
+    ]
+
+    solution = arith.solve_linear_inequalities(problem, [x, y])
+    assert solution.ranges[x].min == 6
+    assert solution.ranges[x].extent == 1
+    assert solution.ranges[y].min == 4
+    assert solution.ranges[y].extent == 1
+
+    solution = arith.solve_linear_inequalities(problem, [x, y], deskew_range=True)
+    assert len(solution.dst.variables) == 0
+    assert len(solution.dst.ranges) == 0
+    assert len(solution.dst.relations) == 0
+    assert solution.src_to_dst[x] == 6
+    assert solution.src_to_dst[y] == 4
+
+
+def test_multi_equal():
+    x, y, z = te.var("x"), te.var("y"), te.var("z")
+    problem = [
+        tvm.tir.LE(x, 6),
+        tvm.tir.GE(x, 6),
+        tvm.tir.GE(x - z * y, 0),
+        tvm.tir.LE(x - z * y, 0),
+    ]
+
+    solution = arith.solve_linear_inequalities(problem, [x, y, z])
+    assert solution.ranges[x].min == 6
+    assert solution.ranges[x].extent == 1
+
+    solution = arith.solve_linear_inequalities(problem, [x, y, z], deskew_range=True)
+    assert solution.src_to_dst[y] == y
+    assert solution.src_to_dst[z] == z
+    assert solution.src_to_dst[x] == 6
+
+
+def test_no_solution():
+    x = te.var("x0")
+    vranges = {x: tvm.ir.Range.make_by_min_extent(-20, 41)}
+    problem = [-x - 4 <= -5*x + 2, x*4 + 5 <= x*5]

Review comment:
       more cases are covered in `test_solution_consistency`




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-647070058


   @sergei-grechanik @tqchen @MarisaKirisame Addressed a few comments. It's ready for review.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-650352627


   @sergei-grechanik @ANSHUMAN87 @tqchen @MarisaKirisame Please take a look again.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] ANSHUMAN87 commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
ANSHUMAN87 commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446652171



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +286,56 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ *        The inequalities are rewritten using Fourier-Motzkin elimination.
+ *        This function takes an array of (in)equalities and an array of variables, and essentially
+ *        rewrites the (in)equalities into an array of (in)equalities of the following form,
+ *
+ *        x0 >= f0(x1, x2, ..., xn)
+ *        x0 <= g0(x1, x2, ..., xn)
+ *        x1 >= f1(x2, ..., xn)
+ *        x1 <= g1(x2, ..., xn)
+ *        ...
+ *        xn >= fn()  // just a constant
+ *        xn <= gn()  // just a constant
+ *
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and infer the range of each variable.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         The returned IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and deskew the ranges towards zero.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A transform (src IntConstraints -> dst IntConstraints)
+ *         from original variables to a set of new variables.
+ *         The ranges of new variables always start from zero,
+ *         their extents are solved from \p system_to_solve.
+ *         src IntConstraints is the same as \p system_to_solve.
+ *         dst IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range (start from zero) of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ *         Variable mapping can be obtained from
+ *         IntConstraintsTransform.src_to_dst and IntConstraintsTransform.dst_to_src.
+ */
+IntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& system_to_solve);

Review comment:
       @yzhliu :  Thanks a lot for such detail explanation. I get it clearly now!
   




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] tqchen commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
tqchen commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446673708



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,110 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (inclusive), upper bounds (inclusive) and equalities.
+ *        It also contains coefficient as a multiplier for the bounds, i.e.,
+ *        coef * var >= lower
+ *        coef * var == equal
+ *        coef * var <= upper
+ * \sa IntGrpBounds
+ */
+class IntGrpBoundsNode : public Object {

Review comment:
       IntGroupBounds

##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,110 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (inclusive), upper bounds (inclusive) and equalities.
+ *        It also contains coefficient as a multiplier for the bounds, i.e.,
+ *        coef * var >= lower
+ *        coef * var == equal
+ *        coef * var <= upper
+ * \sa IntGrpBounds
+ */
+class IntGrpBoundsNode : public Object {
+ public:
+  PrimExpr coef;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> equal;
+  Array<PrimExpr> upper;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {
+    v->Visit("coef", &coef);
+    v->Visit("lower", &lower);
+    v->Visit("equal", &equal);
+    v->Visit("upper", &upper);
+  }
+
+  bool SEqualReduce(const IntGrpBoundsNode* other, SEqualReducer eq) const {
+    return eq(coef, other->coef) && eq(lower, other->lower) && eq(equal, other->equal) &&
+           eq(upper, other->upper);
+  }
+
+  void SHashReduce(SHashReducer hash_reduce) const {
+    hash_reduce(coef);
+    hash_reduce(lower);
+    hash_reduce(equal);
+    hash_reduce(upper);
+  }
+
+  static constexpr const bool _type_has_method_sequal_reduce = true;
+  static constexpr const char* _type_key = "arith.IntGrpBounds";
+  TVM_DECLARE_FINAL_OBJECT_INFO(IntGrpBoundsNode, Object);
+};
+
+/*!
+ * \brief Managed reference to IntGrpBoundsNode.
+ * \sa IntGrpBoundsNode
+ */
+class IntGrpBounds : public ObjectRef {
+ public:
+  /*!
+   * \brief Constructor by fields
+   * \param coef The coefficient. Must be integer.
+   *        coef * var >= lower
+   *        coef * var == equal
+   *        coef * var >= upper
+   * \param lower the lower bounds (include)
+   * \param equal equalities
+   * \param upper the upper bounds (include)
+   */
+  TVM_DLL IntGrpBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,
+                       Array<PrimExpr> upper);
+
+  /*!
+   * \brief Construct bounds from a range.
+   * \param r The range
+   * \return constructed bounds.
+   */
+  static IntGrpBounds range(const Range& r);

Review comment:
       How about FromRange

##########
File path: python/tvm/arith/int_solver.py
##########
@@ -20,6 +20,52 @@
 from . import _ffi_api
 
 
+@tvm._ffi.register_object("arith.IntGrpBounds")
+class IntGrpBounds(Object):
+    """Represent integer grouped bounds which are classified into
+       lower bounds (include), upper bounds (include) and equalities.
+
+    Parameters
+    ----------
+    coef : tvm.ir.PrimExpr
+        The coefficient. Must be integer type.
+        coef * var >= lower
+        coef * var == equal
+        coef * var >= upper
+    lower : List[tvm.ir.PrimExpr]
+        the lower bounds (include)
+    equal : List[tvm.ir.PrimExpr]
+        equalities
+    upper : List[tvm.ir.PrimExpr]
+        the upper bounds (include)
+    """
+    def __init__(self, coef, lower, equal, upper):
+        self.__init_handle_by_constructor__(
+            _ffi_api.IntGrpBounds, coef, lower, equal, upper)
+
+    @staticmethod
+    def make_by_range(rng):
+        """Construct a IntGroupedBounds by Range.

Review comment:
       from_range




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443945936



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       `2x == 1` should be transformed to `x >= ceildiv(1, 2) = 1` and `x <= floordiv(1, 2) = 0` which gives the empty set, so I don't think that equations should be problematic.
   
   I checked out your branch and the bug I mentioned does seem to be fixed indeed. However your example results in the following failure (when the workaround for equations is off):
   ```
   AssertionError: Expression ((((((x0: int32 + 1) - (x1: int32*3)) <= (((x1*2) + x0) + 3)) || ((((x0*3) + 1) - (x1*5)) < ((x0*2) - 5))) || ((((x1*4) + x0) + 1) < ((2 - x0) - x1))) || ((((1 <= ((x1*5) + (x0*2))) && (x0 <= 20)) && ((1 <= (x0 - ((x1*-5) / 2))) && ((x0 - ((x1*-5) / 2)) < 19))) && ((-7 <= x1) && (x1 < 0))))                                                                      
   is not true on {x1: range(min=-20, ext=41), x0: range(min=-20, ext=41)}
   Counterexample: x0: int32 = 18, x1: int32 = -7
   ```
   But the expression is true for the given values if I'm not mistaken. Could be a bug in the testing function or a miscompile.
   
   (BTW, I see that trunc division appeared during simplification which probably shouldn't happen. Although it might not be the cause of the bug, it still seems bad because truncated division is harder to deal with and may cause poor performance of some transformations)




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] MarisaKirisame commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
MarisaKirisame commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r440736456



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,99 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (include), upper bounds (include) and equalities.

Review comment:
       ```suggestion
    *        lower bounds (inclusive), upper bounds (inclusive) and equalities.
   ```

##########
File path: src/arith/int_constraints.cc
##########
@@ -21,18 +21,166 @@
  * \file int_constraints.cc
  * \brief The integer constraints data structures.
  */
+#include <tvm/arith/analyzer.h>
 #include <tvm/arith/int_solver.h>
 #include <tvm/runtime/registry.h>
 #include <tvm/tir/expr.h>
 #include <tvm/tir/expr_functor.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
 
 #include <algorithm>
 #include <unordered_map>
 #include <utility>
 
+#include "../tir/transforms/ir_util.h"
+
 namespace tvm {
 namespace arith {
 
+IntGrpBounds::IntGrpBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,
+                           Array<PrimExpr> upper) {
+  CHECK(coef.dtype().is_int() || coef.dtype().is_uint())
+      << "Coefficient in IntGrpBounds must be integers";
+  ObjectPtr<IntGrpBoundsNode> node = make_object<IntGrpBoundsNode>();
+  node->coef = std::move(coef);
+  node->lower = std::move(lower);
+  node->equal = std::move(equal);
+  node->upper = std::move(upper);
+  data_ = std::move(node);
+}
+
+IntGrpBounds IntGrpBounds::range(const Range& r) {
+  Analyzer analyzer;
+  PrimExpr coef = tir::make_const(r->min.dtype(), 1);
+  Array<PrimExpr> equal;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> upper;
+  if (tir::is_one(r->extent)) {
+    equal.push_back(r->min);
+  } else {
+    lower.push_back(r->min);
+    upper.push_back(analyzer.Simplify(r->min + r->extent - 1));
+  }
+  return IntGrpBounds(coef, lower, equal, upper);
+}
+
+IntGrpBounds IntGrpBounds::operator+(const Range& r) {
+  Analyzer analyzer;
+  Array<PrimExpr> equal;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> upper;
+  if (tir::is_one(r->extent)) {
+    equal.push_back(analyzer.Simplify(r->min * operator->()->coef));

Review comment:
       maybe getting a constref that result form operator->() is better code style. seeing operator->() flying around hurt my eyes imo.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443166920



##########
File path: python/tvm/arith/int_solver.py
##########
@@ -97,3 +143,33 @@ def solve_linear_equations(equations, variables=None, ranges=None):
     if isinstance(equations, IntConstraints):
         return _ffi_api.SolveLinearEquations(equations)
     return _ffi_api.SolveLinearEquations(variables, ranges, equations)
+
+
+def solve_linear_inequalities(equations, variables=None, ranges=None, deskew_range=False):
+    """Solve linear inequalities.
+
+    Parameters
+    ----------
+    equations   : List[tvm.ir.PrimExpr] or IntConstraints
+        The inequalities of the variables
+    variables   : Optional[List[tvm.tir.Var]]
+        The variables in the system.
+    ranges      : Optional[Map[tvm.tir.Var, tvm.ir.Range]]
+        The ranges of the variables.
+    deskew_range: Optional[bool]
+        Whether deskew the result ranges to be started from zero.
+        Default false.
+
+    Returns
+    -------
+    ret_ranges: IntConstraints or IntConstraintsTransform

Review comment:
       I feel it might be fine as it keeps python interface concise.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r445305976



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       https://github.com/apache/incubator-tvm/pull/5922




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-643049731


   Also cc @xqdan @junrushao1994 if you have time review.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446351576



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +286,56 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ *        The inequalities are rewritten using Fourier-Motzkin elimination.
+ *        This function takes an array of (in)equalities and an array of variables, and essentially
+ *        rewrites the (in)equalities into an array of (in)equalities of the following form,
+ *
+ *        x0 >= f0(x1, x2, ..., xn)
+ *        x0 <= g0(x1, x2, ..., xn)
+ *        x1 >= f1(x2, ..., xn)
+ *        x1 <= g1(x2, ..., xn)
+ *        ...
+ *        xn >= fn()  // just a constant
+ *        xn <= gn()  // just a constant
+ *
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and infer the range of each variable.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         The returned IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and deskew the ranges towards zero.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A transform (src IntConstraints -> dst IntConstraints)
+ *         from original variables to a set of new variables.
+ *         The ranges of new variables always start from zero,
+ *         their extents are solved from \p system_to_solve.
+ *         src IntConstraints is the same as \p system_to_solve.
+ *         dst IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range (start from zero) of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ *         Variable mapping can be obtained from
+ *         IntConstraintsTransform.src_to_dst and IntConstraintsTransform.dst_to_src.
+ */
+IntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& system_to_solve);

Review comment:
       `SolveInequalitiesToRange` finds the best range for the inequalities, and stores in `IntConstraints.ranges`. the reason we need `IntConstraints` instead of `Map<Var, Range>` is that, there might be some equations/inequalities that we can not deal, we don't silently drop but store them in `IntConstraints.relations`.
   
   `SolveInequalitiesDeskewRange` does one more step to create new variables which satisfy the original inequality constraints, but always starts from zero. This is very useful when we deal with iteration indices in tvm compute. And maintaining the transform between old&new variables is necessary for 1) transform the old expression (tvm compute) to the new. 2) `SolveInequalitiesDeskewRange` can be run multiple times (until they converge) to get better results, thus a chain of transform is needed.
   
   You might have question why can't user invoke `SolveInequalitiesToRange` first and deskew to zero themselves? It's because variable ranges are solved iteratively, one variable's range depends on the previous solved range. `FindBestRange of var a  -> Deskew a -> FindBestRange of var b (given deskewed a) -> Deskew b (given deskewed a)  -> ...` is much more precise than `FindBestRange of var a  -> FindBestRange of var b (given range a) -> Deskew a & b independently`.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] ANSHUMAN87 commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
ANSHUMAN87 commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446651549



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,110 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (inclusive), upper bounds (inclusive) and equalities.
+ *        It also contains coefficient as a multiplier for the bounds, i.e.,
+ *        coef * var >= lower
+ *        coef * var == equal
+ *        coef * var <= upper
+ * \sa IntGrpBounds
+ */
+class IntGrpBoundsNode : public Object {
+ public:
+  PrimExpr coef;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> equal;
+  Array<PrimExpr> upper;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {
+    v->Visit("coef", &coef);
+    v->Visit("lower", &lower);
+    v->Visit("equal", &equal);
+    v->Visit("upper", &upper);
+  }
+
+  bool SEqualReduce(const IntGrpBoundsNode* other, SEqualReducer eq) const {
+    return eq(coef, other->coef) && eq(lower, other->lower) && eq(equal, other->equal) &&
+           eq(upper, other->upper);
+  }
+
+  void SHashReduce(SHashReducer hash_reduce) const {
+    hash_reduce(coef);
+    hash_reduce(lower);
+    hash_reduce(equal);
+    hash_reduce(upper);
+  }
+
+  static constexpr const bool _type_has_method_sequal_reduce = true;
+  static constexpr const char* _type_key = "arith.IntGrpBounds";
+  TVM_DECLARE_FINAL_OBJECT_INFO(IntGrpBoundsNode, Object);
+};
+
+/*!
+ * \brief Managed reference to IntGrpBoundsNode.
+ * \sa IntGrpBoundsNode
+ */
+class IntGrpBounds : public ObjectRef {
+ public:
+  /*!
+   * \brief Constructor by fields
+   * \param coef The coefficient. Must be integer.
+   *        coef * var >= lower
+   *        coef * var == equal
+   *        coef * var >= upper
+   * \param lower the lower bounds (include)
+   * \param equal equalities
+   * \param upper the upper bounds (include)
+   */
+  TVM_DLL IntGrpBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,
+                       Array<PrimExpr> upper);
+
+  /*!
+   * \brief Construct bounds from a range.
+   * \param r The range
+   * \return constructed bounds.
+   */
+  static IntGrpBounds range(const Range& r);

Review comment:
       Thanks! I see now. I am also okay if it is general convention:)
   @tqchen : Do you have any thoughts on the comment ?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r448630150



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,648 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Array<Var>& variables, const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  // use variables to keep the order of iteration
+  // so as to get rid of any non-determinism.
+  CHECK_EQ(variables.size(), bounds.size());
+  for (const auto v : variables) {
+    CHECK(bounds.count(v));
+    const auto& bnds = bounds[v];
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQ(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GE(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LE(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQ>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LT>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LT>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LE>(op->b, op->a); }
+
+ private:
+  template <class T>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<T, LT>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LE(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return T(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {
+      const LENode* le = iter->as<LENode>();
+      if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
+        return;
+      } else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
+        iter = inequality_set->erase(iter);
+      } else {
+        ++iter;
+      }
+    } else {
+      ++iter;
+    }
+  }
+
+  inequality_set->insert(new_ineq);
+}
+
+void ClassifyByPolarity(
+    const Var& var,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* next_ineq_set,
+    std::vector<PrimExpr>* rest, std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
+    std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
+  // Take formulas from current_ineq_set and classify them according to polarity wrt var
+  // and store to coef_pos and coef_neg respectively.
+  for (const PrimExpr& ineq : current_ineq_set) {
+    if (const LENode* le = ineq.as<LENode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          coef_pos->push_back({coef0, coef[1]});
+        } else if (coef0 < 0) {
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    } else if (const EQNode* eq = ineq.as<EQNode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          // Equalities may be considered as pairs of two inequalities
+          coef_pos->push_back({coef0, coef[1]});
+          coef_neg->push_back({-coef0, -coef[1]});
+        } else if (coef0 < 0) {
+          coef_pos->push_back({-coef0, -coef[1]});
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    }
+
+    // if nothing worked, put it in rest
+    rest->push_back(ineq);
+  }
+}
+
+void MoveEquality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* upper_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* lower_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* equalities) {
+  // those exist in both upper & lower bounds will be moved to equalities
+  for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
+    auto lb = lower_bounds->find(*ub);
+    if (lb != lower_bounds->end()) {
+      equalities->insert(*lb);
+      lower_bounds->erase(lb);
+      ub = upper_bounds->erase(ub);
+    } else {
+      ++ub;
+    }
+  }
+}
+
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
+  arith::Analyzer analyzer;
+  analyzer.Bind(system_to_solve->ranges);
+
+  // The algorithm consists in doing the following things for each variable v
+  // - Take formulas from `current_ineq_set_to_solve` and
+  //   classify them according to polarity wrt v.
+  // - Combine each formula of positive polarity (wrt v)
+  //   with each formula of negative polarity.
+  // - Put the resulting combinations into `next_ineq_set_to_solve`
+  //   along with unclassifiable formulas.
+  // - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
+  //   and move to the next variable.
+
+  // normalized inequality
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> current_ineq_set_to_solve;
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> next_ineq_set_to_solve;
+  // A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
+  // A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
+
+  // formulas we don't know what to do with
+  std::vector<PrimExpr> rest;
+
+  // Simplify each inequality into the form `expr <= 0` and add to current formulas
+  for (const PrimExpr& ineq : system_to_solve->relations) {
+    AddInequality(&current_ineq_set_to_solve, NormalizeComparisons()(analyzer.Simplify(ineq, 3)),
+                  &analyzer);
+  }
+
+  Map<Var, IntGrpBounds> res_bounds;
+  for (const Var& v : system_to_solve->variables) {
+    CHECK(!res_bounds.count(v))
+        << "Variable " << v
+        << " appears more than one time in the `variables` which might be a bug";
+
+    next_ineq_set_to_solve.clear();
+    coef_pos.clear();
+    coef_neg.clear();
+
+    // Add bounds from vranges
+    if (system_to_solve->ranges.count(v)) {
+      const Range& range = system_to_solve->ranges[v];
+      PrimExpr range_lbound = analyzer.Simplify(range->min, 3);
+      PrimExpr range_ubound = analyzer.Simplify(range->min + range->extent - 1, 3);
+      coef_neg.push_back({-1, range_lbound});
+      coef_pos.push_back({1, -range_ubound});
+    }
+
+    ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
+                       &coef_neg, &analyzer);
+
+    // Combine each positive inequality with each negative one (by adding them together)
+    int64_t gcd_x, gcd_y;
+    for (const auto& pos : coef_pos) {
+      for (const auto& neg : coef_neg) {
+        auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
+        PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
+        PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
+        // eliminate the current variable
+        PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
+        PrimExpr new_ineq = LE(new_lhs, make_zero(pos.second.dtype()));
+        // we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
+        // to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
+        // with steps = 2 it's (y*2) - 10 <= 0
+        new_ineq = NormalizeComparisons()(analyzer.Simplify(new_ineq, 3));
+        AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
+      }
+    }
+
+    // Now we have to generate resulting (in)equalities for the variable v
+
+    // Find the common denominator in a sense
+    // We will generate formulas of the form coef_lcm*v <= bound
+    int64_t coef_lcm = 1;
+    for (const auto& pos : coef_pos) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
+    }
+    for (const auto& neg : coef_neg) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
+    }
+
+    // The resulting lower and upper bounds
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> upper_bounds;
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> lower_bounds;
+    upper_bounds.reserve(coef_pos.size());
+    lower_bounds.reserve(coef_neg.size());
+
+    for (const auto& pos : coef_pos) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / pos.first) * pos.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound <= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = upper_bounds.begin(); iter != upper_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound >= 0)) {
+          iter = upper_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the upper bound
+      upper_bounds.insert(bound);
+    }
+    for (const auto& neg : coef_neg) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / neg.first) * neg.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound >= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = lower_bounds.begin(); iter != lower_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound <= 0)) {
+          iter = lower_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the lower bound
+      lower_bounds.insert(bound);
+    }
+
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> equal;
+    equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
+    MoveEquality(&upper_bounds, &lower_bounds, &equal);
+    std::vector<PrimExpr> equal_list(equal.begin(), equal.end());
+    std::sort(equal_list.begin(), equal_list.end(), ExprLess());
+
+    // Write it to the result.
+    IntGrpBounds bnds(make_const(v.dtype(), coef_lcm),
+                      Array<PrimExpr>(lower_bounds.begin(), lower_bounds.end()),
+                      Array<PrimExpr>(equal_list.begin(), equal_list.end()),
+                      Array<PrimExpr>(upper_bounds.begin(), upper_bounds.end()));
+    res_bounds.Set(v, bnds);
+
+    std::swap(current_ineq_set_to_solve, next_ineq_set_to_solve);
+  }
+
+  // Everything that is left goes to res.relations
+  Array<PrimExpr> other_conditions;
+  for (const PrimExpr& e : current_ineq_set_to_solve) {
+    PrimExpr e_simp = analyzer.Simplify(e, 3);
+    if (is_const_int(e_simp, 0)) {
+      // contradiction detected
+      other_conditions = {const_false()};
+      break;
+    } else if (is_const_int(e_simp, 1)) {
+      continue;
+    } else {
+      other_conditions.push_back(e_simp);
+    }
+  }
+
+  for (const PrimExpr& e : rest) {
+    other_conditions.push_back(e);
+  }
+
+  return {res_bounds, other_conditions};
+}
+
+IntConstraints SolveInequalitiesToRange(const IntConstraints& inequalities) {
+  // Resulting ranges will contain ranges for the new variables and for the variables that are
+  // not in the inequalities->variables but are in inequalities->ranges
+  // It will be useful when solving Jacobian axes jac_xxx)
+  Map<Var, Range> res_ranges;
+  // we get a set of equality, lower, upper bound of each variable.
+  auto solved_system = SolveLinearInequalities(inequalities);
+
+  Map<Var, IntGrpBounds> solved_bounds = solved_system.first;
+  Array<PrimExpr> solved_other_relations = solved_system.second;
+
+  Array<PrimExpr> res_relations;
+
+  // this keeps being updated during determining the range of each variable.
+  Map<Var, Range> vranges;
+  for (std::pair<Var, Range> vr : inequalities->ranges) {
+    vranges.Set(vr.first, vr.second);
+  }
+
+  // We process variables in the reverse direction to start with the most independent one.
+  // This order is needed to compute new ranges.
+  for (auto it = inequalities->variables.rbegin(); it != inequalities->variables.rend(); ++it) {
+    arith::Analyzer analyzer;
+    analyzer.Bind(vranges);
+
+    const Var& var = *it;
+    CHECK(solved_bounds.count(var));
+    auto bnd = solved_bounds[var];
+    if (is_one(bnd->coef) && !bnd->equal.empty()) {
+      // There is an equation of the form `v == expr`, so this variable can be completely removed.
+      // Note that we use the 0-th expression because they are ordered by complexity,
+      // so it must be the simplest one.
+      Range best_range(bnd->equal[0], analyzer.Simplify(bnd->equal[0] + 1, 3));
+      res_ranges.Set(var, best_range);

Review comment:
       in the else branch, they are not set unless `best_range` is defined.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] tqchen commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
tqchen commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-654358427


   Thanks @yzhliu  @sergei-grechanik @ANSHUMAN87  @MarisaKirisame 


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#issuecomment-652720020


   @tqchen @ANSHUMAN87 Please take a look again.


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446343013



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,110 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (inclusive), upper bounds (inclusive) and equalities.
+ *        It also contains coefficient as a multiplier for the bounds, i.e.,
+ *        coef * var >= lower
+ *        coef * var == equal
+ *        coef * var <= upper
+ * \sa IntGrpBounds
+ */
+class IntGrpBoundsNode : public Object {
+ public:
+  PrimExpr coef;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> equal;
+  Array<PrimExpr> upper;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {
+    v->Visit("coef", &coef);
+    v->Visit("lower", &lower);
+    v->Visit("equal", &equal);
+    v->Visit("upper", &upper);
+  }
+
+  bool SEqualReduce(const IntGrpBoundsNode* other, SEqualReducer eq) const {
+    return eq(coef, other->coef) && eq(lower, other->lower) && eq(equal, other->equal) &&
+           eq(upper, other->upper);
+  }
+
+  void SHashReduce(SHashReducer hash_reduce) const {
+    hash_reduce(coef);
+    hash_reduce(lower);
+    hash_reduce(equal);
+    hash_reduce(upper);
+  }
+
+  static constexpr const bool _type_has_method_sequal_reduce = true;
+  static constexpr const char* _type_key = "arith.IntGrpBounds";
+  TVM_DECLARE_FINAL_OBJECT_INFO(IntGrpBoundsNode, Object);
+};
+
+/*!
+ * \brief Managed reference to IntGrpBoundsNode.
+ * \sa IntGrpBoundsNode
+ */
+class IntGrpBounds : public ObjectRef {
+ public:
+  /*!
+   * \brief Constructor by fields
+   * \param coef The coefficient. Must be integer.
+   *        coef * var >= lower
+   *        coef * var == equal
+   *        coef * var >= upper
+   * \param lower the lower bounds (include)
+   * \param equal equalities
+   * \param upper the upper bounds (include)
+   */
+  TVM_DLL IntGrpBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,
+                       Array<PrimExpr> upper);
+
+  /*!
+   * \brief Construct bounds from a range.
+   * \param r The range
+   * \return constructed bounds.
+   */
+  static IntGrpBounds range(const Range& r);

Review comment:
       I'm ok with either way. This is following https://github.com/apache/incubator-tvm/blob/master/src/arith/int_set.cc#L600




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446351576



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +286,56 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ *        The inequalities are rewritten using Fourier-Motzkin elimination.
+ *        This function takes an array of (in)equalities and an array of variables, and essentially
+ *        rewrites the (in)equalities into an array of (in)equalities of the following form,
+ *
+ *        x0 >= f0(x1, x2, ..., xn)
+ *        x0 <= g0(x1, x2, ..., xn)
+ *        x1 >= f1(x2, ..., xn)
+ *        x1 <= g1(x2, ..., xn)
+ *        ...
+ *        xn >= fn()  // just a constant
+ *        xn <= gn()  // just a constant
+ *
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and infer the range of each variable.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         The returned IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and deskew the ranges towards zero.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A transform (src IntConstraints -> dst IntConstraints)
+ *         from original variables to a set of new variables.
+ *         The ranges of new variables always start from zero,
+ *         their extents are solved from \p system_to_solve.
+ *         src IntConstraints is the same as \p system_to_solve.
+ *         dst IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range (start from zero) of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ *         Variable mapping can be obtained from
+ *         IntConstraintsTransform.src_to_dst and IntConstraintsTransform.dst_to_src.
+ */
+IntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& system_to_solve);

Review comment:
       `SolveInequalitiesToRange` finds the best range for the inequalities, and stores in `IntConstraints.ranges`. the reason we need `IntConstraints` instead of `Map<Var, Range>` is that, there might be some equations/inequalities that we can not deal, we don't silently drop but store them in `IntConstraints.relations`.
   
   `SolveInequalitiesDeskewRange` does one more step to create new variables which satisfy the original inequality constraints, yet always starts from zero. This is very useful when we deal with iteration indices in tvm compute. And maintaining the transform between old&new variables is necessary for 1) transform the old expression (tvm compute) to the new. 2) `SolveInequalitiesDeskewRange` can be run multiple times (until they converge) to get better results, thus a chain of transform is needed.
   
   You might have question why can't user invoke `SolveInequalitiesToRange` first and deskew to zero themselves? It's because variable ranges are solved iteratively, one variable's range depends on the previous solved range. `FindBestRange of var a  -> Deskew a -> FindBestRange of var b (given deskewed a) -> Deskew b (given deskewed a)  -> ...` is much more precise than `FindBestRange of var a  -> FindBestRange of var b (given range a) -> Deskew a & b independently`.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443276163



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,641 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  for (const auto iter : bounds) {

Review comment:
       thx for pointing out. modified.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r441203304



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);

Review comment:
       I use unordered_set instead. The only place I use `ExprLess` is to get the simplest equation form (`std::sort(equal_list.begin(), equal_list.end(), ExprLess());`). I guess it is ok to keep it as simple.

##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  for (const auto iter : bounds) {
+    const Var& v = iter.first;
+    const auto& bnds = iter.second;
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQNode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GENode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LENode::make(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LTNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LTNode>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LENode>(op->b, op->a); }
+
+ private:
+  template <class TNode>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<TNode, LTNode>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LENode::make(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return TNode::make(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {
+      const LENode* le = iter->as<LENode>();
+      if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
+        return;
+      } else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
+        iter = inequality_set->erase(iter);
+      } else {
+        ++iter;
+      }
+    } else {
+      ++iter;
+    }
+  }
+
+  inequality_set->insert(new_ineq);
+}
+
+void ClassifyByPolarity(
+    const Var& var,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* next_ineq_set,
+    std::vector<PrimExpr>* rest, std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
+    std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
+  // Take formulas from current_ineq_set and classify them according to polarity wrt var
+  // and store to coef_pos and coef_neg respectively.
+  for (const PrimExpr& ineq : current_ineq_set) {
+    if (const LENode* le = ineq.as<LENode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          coef_pos->push_back({coef0, coef[1]});
+        } else if (coef0 < 0) {
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    } else if (const EQNode* eq = ineq.as<EQNode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          // Equalities may be considered as pairs of two inequalities
+          coef_pos->push_back({coef0, coef[1]});
+          coef_neg->push_back({-coef0, -coef[1]});
+        } else if (coef0 < 0) {
+          coef_pos->push_back({-coef0, -coef[1]});
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    }
+
+    // if nothing worked, put it in rest
+    rest->push_back(ineq);
+  }
+}
+
+void MoveEquality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* upper_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* lower_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* equalities) {
+  // those exist in both upper & lower bounds will be moved to equalities
+  for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
+    auto lb = lower_bounds->find(*ub);
+    if (lb != lower_bounds->end()) {
+      equalities->insert(*lb);
+      lower_bounds->erase(lb);
+      ub = upper_bounds->erase(ub);
+    } else {
+      ++ub;
+    }
+  }
+}
+
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
+  arith::Analyzer analyzer;
+  analyzer.Bind(system_to_solve->ranges);
+
+  // The algorithm consists in doing the following things for each variable v
+  // - Take formulas from `current_ineq_set_to_solve` and
+  //   classify them according to polarity wrt v.
+  // - Combine each formula of positive polarity (wrt v)
+  //   with each formula of negative polarity.
+  // - Put the resulting combinations into `next_ineq_set_to_solve`
+  //   along with unclassifiable formulas.
+  // - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
+  //   and move to the next variable.
+
+  // normalized inequality
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> current_ineq_set_to_solve;
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> next_ineq_set_to_solve;
+  // A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
+  // A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
+
+  // formulas we don't know what to do with
+  std::vector<PrimExpr> rest;
+
+  // Simplify each inequality into the form `expr <= 0` and add to current formulas
+  for (const PrimExpr& ineq : system_to_solve->relations) {
+    AddInequality(&current_ineq_set_to_solve, NormalizeComparisons()(analyzer.Simplify(ineq, 3)),
+                  &analyzer);
+  }
+
+  Map<Var, IntGrpBounds> res_bounds;
+  for (const Var& v : system_to_solve->variables) {
+    CHECK(!res_bounds.count(v))
+        << "Variable " << v
+        << " appears more than one time in the `variables` which might be a bug";
+
+    next_ineq_set_to_solve.clear();
+    coef_pos.clear();
+    coef_neg.clear();
+
+    // Add bounds from vranges
+    if (system_to_solve->ranges.count(v)) {
+      const Range& range = system_to_solve->ranges[v];
+      PrimExpr range_lbound = analyzer.Simplify(range->min, 3);
+      PrimExpr range_ubound = analyzer.Simplify(range->min + range->extent - 1, 3);
+      coef_neg.push_back({-1, range_lbound});
+      coef_pos.push_back({1, -range_ubound});
+    }
+
+    ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
+                       &coef_neg, &analyzer);
+
+    // Combine each positive inequality with each negative one (by adding them together)
+    int64_t gcd_x, gcd_y;
+    for (const auto& pos : coef_pos) {
+      for (const auto& neg : coef_neg) {
+        auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
+        PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
+        PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
+        // eliminate the current variable
+        PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
+        PrimExpr new_ineq = LENode::make(new_lhs, make_zero(pos.second.dtype()));
+        // we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
+        // to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
+        // with steps = 2 it's (y*2) - 10 <= 0
+        new_ineq = NormalizeComparisons()(analyzer.Simplify(new_ineq, 3));
+        AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
+      }
+    }
+
+    // Now we have to generate resulting (in)equalities for the variable v
+
+    // Find the common denominator in a sense
+    // We will generate formulas of the form coef_lcm*v <= bound
+    int64_t coef_lcm = 1;
+    for (const auto& pos : coef_pos) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
+    }
+    for (const auto& neg : coef_neg) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
+    }
+
+    // The resulting lower and upper bounds stored in sorted vectors
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> upper_bounds;
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> lower_bounds;
+    upper_bounds.reserve(coef_pos.size());
+    lower_bounds.reserve(coef_neg.size());
+
+    for (const auto& pos : coef_pos) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / pos.first) * pos.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound <= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = upper_bounds.begin(); iter != upper_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound >= 0)) {
+          iter = upper_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the upper bound
+      upper_bounds.insert(bound);
+    }
+    for (const auto& neg : coef_neg) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / neg.first) * neg.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound >= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = lower_bounds.begin(); iter != lower_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound <= 0)) {
+          iter = lower_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the lower bound
+      lower_bounds.insert(bound);
+    }
+
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> equal;
+    equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
+    MoveEquality(&upper_bounds, &lower_bounds, &equal);
+    std::vector<PrimExpr> equal_list(equal.begin(), equal.end());
+    std::sort(equal_list.begin(), equal_list.end(), ExprLess());
+
+    // Write it to the result.
+    IntGrpBounds bnds(make_const(v.dtype(), coef_lcm),
+                      Array<PrimExpr>(lower_bounds.begin(), lower_bounds.end()),
+                      Array<PrimExpr>(equal_list.begin(), equal_list.end()),
+                      Array<PrimExpr>(upper_bounds.begin(), upper_bounds.end()));

Review comment:
       I think as long as I'm using unordered_set to do the set operations this will be fine. 
   And `FindBestBound` enumerates all the pairs thus order should not matter.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r443165573



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       Thanks for the suggestion. It does find some bugs in the implementation, most related to round division, which might also exist in your branch, here's one example, 
   ```python
   [(((x0 + (x1*2)) + 3) < ((x0 + (x1*-3)) + 1)),
   ((((x0*3) + (x1*-5)) + 1) >= ((x0*2) + -5)),
   ((((x0*-1) + (x1*-1)) + 2) <= ((x0 + (x1*4)) + 1))]
   ```
   if we allow non-divisible results, it is solved to be
   ```
   IntConstraintsTransform(
   	IntConstraints([x0, x1], {x2: range(min=-20, ext=41), x1: range(min=-20, ext=41), x3: range(min=-20, ext=41), x0: range(min=-20, ext=41)}, [(((x0 + (x1*2)) + 3) < ((x0 + (x1*-3)) + 1)), ((((x0*3) + (x1*-5)) + 1) >= ((x0*2) + -5)), ((((x0*-1) + (x1*-1)) + 2) <= ((x0 + (x1*4)) + 1))])
   	IntConstraints([x0.shifted, x1.shifted], {x0.shifted: range(min=0, ext=18), x1.shifted: range(min=0, ext=7)}, [(36 <= (((x1.shifted*5) + (floordiv((37 - (x1.shifted*5)), 2)*2)) + (x0.shifted*2))), ((floordiv((37 - (x1.shifted*5)), 2) + x0.shifted) <= 20)])
   	{x0: (x0.shifted + floordiv((37 + (x1.shifted*-5)), 2)), x1: (x1.shifted + -7)}
   	{x0.shifted: ((x0 - floordiv((0 - (x1*5)), 2)) - 1), x1.shifted: (x1 + 7)}
   )
   ```
   I modified the `FindBestRange` to skip non-divisible cases,
   ```cpp
   if (analyzer.CanProve(floormod(low, coef) == 0)) {
         // we need to be very careful with rounding
         // as it could be wrong when we have equations.
         // equations can come from
         // 1. when it is a single point, i.e., extent == 1.
         // 2. when var is substituted by another var in deskew range.
         best_lower = low_divided;
         best_diff_over = diff_over;
   }
   ```




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r441316107



##########
File path: python/tvm/arith/int_solver.py
##########
@@ -97,3 +143,33 @@ def solve_linear_equations(equations, variables=None, ranges=None):
     if isinstance(equations, IntConstraints):
         return _ffi_api.SolveLinearEquations(equations)
     return _ffi_api.SolveLinearEquations(variables, ranges, equations)
+
+
+def solve_linear_inequalities(equations, variables=None, ranges=None, deskew_range=False):
+    """Solve linear inequalities.
+
+    Parameters
+    ----------
+    equations   : List[tvm.ir.PrimExpr] or IntConstraints
+        The inequalities of the variables
+    variables   : Optional[List[tvm.tir.Var]]
+        The variables in the system.
+    ranges      : Optional[Map[tvm.tir.Var, tvm.ir.Range]]
+        The ranges of the variables.
+    deskew_range: Optional[bool]
+        Whether deskew the result ranges to be started from zero.
+        Default false.
+
+    Returns
+    -------
+    ret_ranges: IntConstraints or IntConstraintsTransform

Review comment:
       do you mean adding another function for `deskew_range=False`, or making `deskew_range=False` also return IntConstraintsTransform?

##########
File path: python/tvm/arith/int_solver.py
##########
@@ -20,6 +20,52 @@
 from . import _ffi_api
 
 
+@tvm._ffi.register_object("arith.IntGrpBounds")
+class IntGrpBounds(Object):
+    """Represent integer grouped bounds which are classified into
+       lower bounds (include), upper bounds (include) and equalities.
+
+    Parameters
+    ----------
+    coef : tvm.ir.PrimExpr
+        The coefficient. Must be integer.

Review comment:
       yes. change to "integer type"




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] ANSHUMAN87 commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
ANSHUMAN87 commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r445020887



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +286,56 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ *        The inequalities are rewritten using Fourier-Motzkin elimination.
+ *        This function takes an array of (in)equalities and an array of variables, and essentially
+ *        rewrites the (in)equalities into an array of (in)equalities of the following form,
+ *
+ *        x0 >= f0(x1, x2, ..., xn)
+ *        x0 <= g0(x1, x2, ..., xn)
+ *        x1 >= f1(x2, ..., xn)
+ *        x1 <= g1(x2, ..., xn)
+ *        ...
+ *        xn >= fn()  // just a constant
+ *        xn <= gn()  // just a constant
+ *
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and infer the range of each variable.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         The returned IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);

Review comment:
       As the API does not produce Range type, may be we change the name SolveInequalitiesToRange() --> SolveInequalities()

##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,187 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solution_consistency():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)
+
+        solution = arith.solve_linear_inequalities(fs, vs, vranges, deskew_range=True)
+        testing.check_int_constraints_trans_consistency(solution)
+
+    for i in range(3):
+        _check(1, 1)
+    for i in range(3):
+        _check(1, 2)
+
+    for i in range(3):
+        _check(2, 1)
+    for i in range(3):
+        _check(2, 2)
+    for i in range(3):
+        _check(2, 3)
+
+    # Somewhere here coefficients in the results become too large, leading to overflow,
+    # so we use smaller initial coefficients
+    for i in range(5):
+        _check(3, 3, coef=(-2, 2))
+    for i in range(5):
+        _check(3, 4, coef=(-2, 2))
+
+    for i in range(5):
+        _check(4, 3, coef=(-1, 1))
+
+    for i in range(5):
+        _check(10, 2, coef=(-1, 1), bounds=(0, 4))
+    for i in range(5):
+        _check(10, 3, coef=(0, 1), bounds=(0, 4))
+
+
+def test_dual_variable():
+    x, y = te.var("x"), te.var("y")
+
+    variables = [x, y]
+    ranges = {
+        x: tvm.ir.Range(-100, 100),
+        y: tvm.ir.Range(0, 10),
+    }
+    problem = [
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ]
+
+    # solution as conditions
+    solution = arith._ffi_api.SolveInequalitiesAsCondition(variables, ranges, problem)
+    assert ir.structural_equal(solution[0], x >= (y + 10))
+    assert ir.structural_equal(solution[1], x <= (20 - y))
+    assert ir.structural_equal(solution[2], y >= 0)
+    assert ir.structural_equal(solution[3], y <= 5)
+
+    # solve and get the ranges
+    solution = arith.solve_linear_inequalities([
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ], [x, y], ranges)
+    # 0 <= y <=5
+    assert solution.ranges[y].min == 0
+    assert solution.ranges[y].extent == 6
+    # y + 10 <= x <= 20 - y
+    assert ir.structural_equal(solution.ranges[x].min, y + 10)
+    assert solution.ranges[x].extent == 11  # max(10 - 2y)
+
+    # deskew the solved ranges to be starting from zero
+    solution = arith.solve_linear_inequalities(problem, variables, ranges, deskew_range=True)
+    [x_new, y_new] = solution.dst.variables
+    [rel] = solution.dst.relations
+    assert ir.structural_equal(rel, (y_new*2) + x_new <= 10)
+    assert ir.structural_equal(solution.dst.ranges[x_new].min, 0)
+    assert ir.structural_equal(solution.dst.ranges[x_new].extent, 11)
+    assert ir.structural_equal(solution.dst.ranges[y_new].min, 0)
+    assert ir.structural_equal(solution.dst.ranges[y_new].extent, 6)
+    assert ir.structural_equal(solution.src_to_dst[x], x_new + (y_new + 10))
+    assert ir.structural_equal(solution.src_to_dst[y], y_new)
+    assert ir.structural_equal(solution.dst_to_src[x_new], x - y - 10)
+    assert ir.structural_equal(solution.dst_to_src[y_new], y)
+
+
+def test_equal():
+    x, y = te.var("x"), te.var("y")
+    problem = [
+        tvm.tir.GE(x + y, 10),
+        tvm.tir.GE(x - y, 2),
+        tvm.tir.LE(x, 6),
+    ]
+
+    solution = arith.solve_linear_inequalities(problem, [x, y])
+    assert solution.ranges[x].min == 6
+    assert solution.ranges[x].extent == 1
+    assert solution.ranges[y].min == 4
+    assert solution.ranges[y].extent == 1
+
+    solution = arith.solve_linear_inequalities(problem, [x, y], deskew_range=True)
+    assert len(solution.dst.variables) == 0
+    assert len(solution.dst.ranges) == 0
+    assert len(solution.dst.relations) == 0
+    assert solution.src_to_dst[x] == 6
+    assert solution.src_to_dst[y] == 4
+
+
+def test_multi_equal():
+    x, y, z = te.var("x"), te.var("y"), te.var("z")
+    problem = [
+        tvm.tir.LE(x, 6),
+        tvm.tir.GE(x, 6),
+        tvm.tir.GE(x - z * y, 0),
+        tvm.tir.LE(x - z * y, 0),
+    ]
+
+    solution = arith.solve_linear_inequalities(problem, [x, y, z])
+    assert solution.ranges[x].min == 6
+    assert solution.ranges[x].extent == 1
+
+    solution = arith.solve_linear_inequalities(problem, [x, y, z], deskew_range=True)
+    assert solution.src_to_dst[y] == y
+    assert solution.src_to_dst[z] == z
+    assert solution.src_to_dst[x] == 6
+
+
+def test_no_solution():
+    x = te.var("x0")
+    vranges = {x: tvm.ir.Range.make_by_min_extent(-20, 41)}
+    problem = [-x - 4 <= -5*x + 2, x*4 + 5 <= x*5]

Review comment:
       No solution with more variables can be added.

##########
File path: src/arith/analyzer.cc
##########
@@ -115,11 +115,15 @@ bool Analyzer::CanProve(const PrimExpr& expr) {
   return false;
 }
 
-PrimExpr Analyzer::Simplify(const PrimExpr& expr) {
+PrimExpr Analyzer::Simplify(const PrimExpr& expr, size_t steps) {

Review comment:
       steps is not exposed to user controlled now in packed func. May be we need to handle that?

##########
File path: python/tvm/testing.py
##########
@@ -188,5 +189,96 @@ def assert_prim_expr_equal(lhs, rhs):
         raise ValueError("{} and {} are not equal".format(lhs, rhs))
 
 
+def check_bool_expr_is_true(bool_expr, vranges, cond=None):
+    """ Check that bool_expr holds given the condition cond
+    for every value of free variables from vranges.
+
+    Parameters
+    ----------
+    bool_expr : tvm.ir.expr.PrimExpr
+        Boolean expression to check
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    cond: tvm.ir.expr.PrimExpr
+        extra conditions needs to be satisfied.
+    """
+    if cond is not None:
+        bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr)

Review comment:
       Why Not(cond) ? The description contradicts i think. Please check once.

##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,187 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solution_consistency():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)
+
+        solution = arith.solve_linear_inequalities(fs, vs, vranges, deskew_range=True)
+        testing.check_int_constraints_trans_consistency(solution)
+
+    for i in range(3):
+        _check(1, 1)
+    for i in range(3):
+        _check(1, 2)
+
+    for i in range(3):
+        _check(2, 1)
+    for i in range(3):
+        _check(2, 2)
+    for i in range(3):
+        _check(2, 3)
+
+    # Somewhere here coefficients in the results become too large, leading to overflow,
+    # so we use smaller initial coefficients
+    for i in range(5):
+        _check(3, 3, coef=(-2, 2))
+    for i in range(5):
+        _check(3, 4, coef=(-2, 2))
+
+    for i in range(5):
+        _check(4, 3, coef=(-1, 1))
+
+    for i in range(5):
+        _check(10, 2, coef=(-1, 1), bounds=(0, 4))
+    for i in range(5):
+        _check(10, 3, coef=(0, 1), bounds=(0, 4))
+
+
+def test_dual_variable():
+    x, y = te.var("x"), te.var("y")
+
+    variables = [x, y]
+    ranges = {
+        x: tvm.ir.Range(-100, 100),
+        y: tvm.ir.Range(0, 10),
+    }
+    problem = [
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ]
+
+    # solution as conditions
+    solution = arith._ffi_api.SolveInequalitiesAsCondition(variables, ranges, problem)
+    assert ir.structural_equal(solution[0], x >= (y + 10))
+    assert ir.structural_equal(solution[1], x <= (20 - y))
+    assert ir.structural_equal(solution[2], y >= 0)
+    assert ir.structural_equal(solution[3], y <= 5)
+
+    # solve and get the ranges
+    solution = arith.solve_linear_inequalities([
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ], [x, y], ranges)
+    # 0 <= y <=5
+    assert solution.ranges[y].min == 0
+    assert solution.ranges[y].extent == 6
+    # y + 10 <= x <= 20 - y
+    assert ir.structural_equal(solution.ranges[x].min, y + 10)
+    assert solution.ranges[x].extent == 11  # max(10 - 2y)
+
+    # deskew the solved ranges to be starting from zero
+    solution = arith.solve_linear_inequalities(problem, variables, ranges, deskew_range=True)
+    [x_new, y_new] = solution.dst.variables
+    [rel] = solution.dst.relations
+    assert ir.structural_equal(rel, (y_new*2) + x_new <= 10)
+    assert ir.structural_equal(solution.dst.ranges[x_new].min, 0)
+    assert ir.structural_equal(solution.dst.ranges[x_new].extent, 11)
+    assert ir.structural_equal(solution.dst.ranges[y_new].min, 0)
+    assert ir.structural_equal(solution.dst.ranges[y_new].extent, 6)
+    assert ir.structural_equal(solution.src_to_dst[x], x_new + (y_new + 10))
+    assert ir.structural_equal(solution.src_to_dst[y], y_new)
+    assert ir.structural_equal(solution.dst_to_src[x_new], x - y - 10)
+    assert ir.structural_equal(solution.dst_to_src[y_new], y)
+
+
+def test_equal():
+    x, y = te.var("x"), te.var("y")
+    problem = [
+        tvm.tir.GE(x + y, 10),
+        tvm.tir.GE(x - y, 2),
+        tvm.tir.LE(x, 6),
+    ]
+
+    solution = arith.solve_linear_inequalities(problem, [x, y])
+    assert solution.ranges[x].min == 6
+    assert solution.ranges[x].extent == 1
+    assert solution.ranges[y].min == 4
+    assert solution.ranges[y].extent == 1
+
+    solution = arith.solve_linear_inequalities(problem, [x, y], deskew_range=True)
+    assert len(solution.dst.variables) == 0
+    assert len(solution.dst.ranges) == 0
+    assert len(solution.dst.relations) == 0
+    assert solution.src_to_dst[x] == 6
+    assert solution.src_to_dst[y] == 4
+
+
+def test_multi_equal():
+    x, y, z = te.var("x"), te.var("y"), te.var("z")
+    problem = [
+        tvm.tir.LE(x, 6),
+        tvm.tir.GE(x, 6),
+        tvm.tir.GE(x - z * y, 0),
+        tvm.tir.LE(x - z * y, 0),
+    ]
+
+    solution = arith.solve_linear_inequalities(problem, [x, y, z])

Review comment:
       Can we add validation for relation as well?

##########
File path: include/tvm/arith/analyzer.h
##########
@@ -464,11 +464,16 @@ class TVM_DLL Analyzer {
    * \brief Simplify expr.
    *
    * \param expr The expression to be simplified.
+   * \param steps The simplification runs in the order of
+   *        rewrite_simplify (step 1) -> canonical_simplify (step 2) ->
+   *        rewrite_simplify (step 3) -> canonical_simplify (step 4) -> ...
+   *        param steps controls how many steps to run.
+   *        Default is 2, i.e., rewrite_simplify + canonical_simplify.
    * \return The result.
    *
    * \note Analyzer will call into sub-analyzers to get the result.
    */
-  PrimExpr Simplify(const PrimExpr& expr);
+  PrimExpr Simplify(const PrimExpr& expr, size_t steps = 2);

Review comment:
       May be size_t -> int ? (I think integer would be sufficient in this case).

##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,187 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solution_consistency():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)
+
+        solution = arith.solve_linear_inequalities(fs, vs, vranges, deskew_range=True)
+        testing.check_int_constraints_trans_consistency(solution)
+
+    for i in range(3):
+        _check(1, 1)
+    for i in range(3):
+        _check(1, 2)
+
+    for i in range(3):
+        _check(2, 1)
+    for i in range(3):
+        _check(2, 2)
+    for i in range(3):
+        _check(2, 3)
+
+    # Somewhere here coefficients in the results become too large, leading to overflow,
+    # so we use smaller initial coefficients
+    for i in range(5):
+        _check(3, 3, coef=(-2, 2))
+    for i in range(5):
+        _check(3, 4, coef=(-2, 2))
+
+    for i in range(5):
+        _check(4, 3, coef=(-1, 1))
+
+    for i in range(5):
+        _check(10, 2, coef=(-1, 1), bounds=(0, 4))
+    for i in range(5):
+        _check(10, 3, coef=(0, 1), bounds=(0, 4))
+
+
+def test_dual_variable():
+    x, y = te.var("x"), te.var("y")
+
+    variables = [x, y]
+    ranges = {
+        x: tvm.ir.Range(-100, 100),
+        y: tvm.ir.Range(0, 10),
+    }
+    problem = [
+        tvm.tir.LE(x + y, 20),
+        tvm.tir.GE(x - y, 10),
+    ]
+
+    # solution as conditions
+    solution = arith._ffi_api.SolveInequalitiesAsCondition(variables, ranges, problem)
+    assert ir.structural_equal(solution[0], x >= (y + 10))
+    assert ir.structural_equal(solution[1], x <= (20 - y))
+    assert ir.structural_equal(solution[2], y >= 0)
+    assert ir.structural_equal(solution[3], y <= 5)
+
+    # solve and get the ranges
+    solution = arith.solve_linear_inequalities([

Review comment:
       maybe use problem ?

##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +286,56 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ *        The inequalities are rewritten using Fourier-Motzkin elimination.
+ *        This function takes an array of (in)equalities and an array of variables, and essentially
+ *        rewrites the (in)equalities into an array of (in)equalities of the following form,
+ *
+ *        x0 >= f0(x1, x2, ..., xn)
+ *        x0 <= g0(x1, x2, ..., xn)
+ *        x1 >= f1(x2, ..., xn)
+ *        x1 <= g1(x2, ..., xn)
+ *        ...
+ *        xn >= fn()  // just a constant
+ *        xn <= gn()  // just a constant
+ *
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and infer the range of each variable.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         The returned IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and deskew the ranges towards zero.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A transform (src IntConstraints -> dst IntConstraints)
+ *         from original variables to a set of new variables.
+ *         The ranges of new variables always start from zero,
+ *         their extents are solved from \p system_to_solve.
+ *         src IntConstraints is the same as \p system_to_solve.
+ *         dst IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range (start from zero) of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ *         Variable mapping can be obtained from
+ *         IntConstraintsTransform.src_to_dst and IntConstraintsTransform.dst_to_src.
+ */
+IntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& system_to_solve);

Review comment:
       Same as above comment.
   
   I have one small query here. Why do we actually need IntConstraintsTransform ?
   Is there any case, we need to retain the previous mapping?

##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,110 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (inclusive), upper bounds (inclusive) and equalities.
+ *        It also contains coefficient as a multiplier for the bounds, i.e.,
+ *        coef * var >= lower
+ *        coef * var == equal
+ *        coef * var <= upper
+ * \sa IntGrpBounds
+ */
+class IntGrpBoundsNode : public Object {
+ public:
+  PrimExpr coef;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> equal;
+  Array<PrimExpr> upper;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {
+    v->Visit("coef", &coef);
+    v->Visit("lower", &lower);
+    v->Visit("equal", &equal);
+    v->Visit("upper", &upper);
+  }
+
+  bool SEqualReduce(const IntGrpBoundsNode* other, SEqualReducer eq) const {
+    return eq(coef, other->coef) && eq(lower, other->lower) && eq(equal, other->equal) &&
+           eq(upper, other->upper);
+  }
+
+  void SHashReduce(SHashReducer hash_reduce) const {
+    hash_reduce(coef);
+    hash_reduce(lower);
+    hash_reduce(equal);
+    hash_reduce(upper);
+  }
+
+  static constexpr const bool _type_has_method_sequal_reduce = true;
+  static constexpr const char* _type_key = "arith.IntGrpBounds";
+  TVM_DECLARE_FINAL_OBJECT_INFO(IntGrpBoundsNode, Object);
+};
+
+/*!
+ * \brief Managed reference to IntGrpBoundsNode.
+ * \sa IntGrpBoundsNode
+ */
+class IntGrpBounds : public ObjectRef {
+ public:
+  /*!
+   * \brief Constructor by fields
+   * \param coef The coefficient. Must be integer.
+   *        coef * var >= lower
+   *        coef * var == equal
+   *        coef * var >= upper
+   * \param lower the lower bounds (include)
+   * \param equal equalities
+   * \param upper the upper bounds (include)
+   */
+  TVM_DLL IntGrpBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,
+                       Array<PrimExpr> upper);
+
+  /*!
+   * \brief Construct bounds from a range.
+   * \param r The range
+   * \return constructed bounds.
+   */
+  static IntGrpBounds range(const Range& r);

Review comment:
       Maybe range --> CreateIntGrpBounds (Or something like that, as we are creating Bounds from Range)?

##########
File path: python/tvm/testing.py
##########
@@ -188,5 +189,96 @@ def assert_prim_expr_equal(lhs, rhs):
         raise ValueError("{} and {} are not equal".format(lhs, rhs))
 
 
+def check_bool_expr_is_true(bool_expr, vranges, cond=None):
+    """ Check that bool_expr holds given the condition cond
+    for every value of free variables from vranges.
+
+    Parameters
+    ----------
+    bool_expr : tvm.ir.expr.PrimExpr

Review comment:
       nit: tvm.ir.expr.PrimExpr -> tvm.ir.PrimExpr
   
   Please handle for other similar cases too :)




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r445181151



##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       I think you're right. It is something wrong with the testing function and compilation flow.
   during the testing & compilation, simplification is applied and seems to mistakenly transform floordiv to truncdiv, here is one example,
   
   ```python
   >>> import tvm
   >>> from tvm import te
   >>> from tvm.tir import floordiv
   >>> ana = tvm.arith.Analyzer()
   >>> x0, x1 = te.var("x0"), te.var("x1")
   >>> expr = (((x0 - floordiv((0 - (x1*5)), 2)) - 1) + floordiv((37 + ((x1 + 7)*-5)), 2))
   >>> expr_sim = ana.simplify(expr)
   >>> expr_sim
   ((floordiv((0 - (x1*5)), 2) + x0) - ((x1*-5)/2))
   >>> ana.simplify(tvm.tir.stmt_functor.substitute(expr, {x0: 1, x1: 3}))
   1
   >>> ana.simplify(tvm.tir.stmt_functor.substitute(expr_sim, {x0: 1, x1: 3}))
   0  # <- showing inconsistent results between expr and expr_sim
   ```
   
   I can confirm this is the part of logic in canonical simplification https://github.com/apache/incubator-tvm/blob/master/src/arith/canonical_simplify.cc#L757
   
   @tqchen do you have any idea about it?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] ANSHUMAN87 commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
ANSHUMAN87 commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446658531



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,648 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Array<Var>& variables, const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  // use variables to keep the order of iteration
+  // so as to get rid of any non-determinism.
+  CHECK_EQ(variables.size(), bounds.size());
+  for (const auto v : variables) {
+    CHECK(bounds.count(v));
+    const auto& bnds = bounds[v];
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQ(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GE(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LE(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQ>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LT>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LT>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LE>(op->b, op->a); }
+
+ private:
+  template <class T>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<T, LT>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LE(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return T(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {

Review comment:
       If new_ineq is not LENode, then may be we dont need this loop to enter, right? Please correct if i am wrong!




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446351576



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +286,56 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ *        The inequalities are rewritten using Fourier-Motzkin elimination.
+ *        This function takes an array of (in)equalities and an array of variables, and essentially
+ *        rewrites the (in)equalities into an array of (in)equalities of the following form,
+ *
+ *        x0 >= f0(x1, x2, ..., xn)
+ *        x0 <= g0(x1, x2, ..., xn)
+ *        x1 >= f1(x2, ..., xn)
+ *        x1 <= g1(x2, ..., xn)
+ *        ...
+ *        xn >= fn()  // just a constant
+ *        xn <= gn()  // just a constant
+ *
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and infer the range of each variable.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         The returned IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities and deskew the ranges towards zero.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A transform (src IntConstraints -> dst IntConstraints)
+ *         from original variables to a set of new variables.
+ *         The ranges of new variables always start from zero,
+ *         their extents are solved from \p system_to_solve.
+ *         src IntConstraints is the same as \p system_to_solve.
+ *         dst IntConstraints(variables, ranges, relations) contains,
+ *         1. variables  - the variables that have been solved.
+ *         2. ranges     - the best range (start from zero) of each variable.
+ *         3. relations  - constraints that cannot be transformed to
+ *                         Range will be stored in relations.
+ *         Variable mapping can be obtained from
+ *         IntConstraintsTransform.src_to_dst and IntConstraintsTransform.dst_to_src.
+ */
+IntConstraintsTransform SolveInequalitiesDeskewRange(const IntConstraints& system_to_solve);

Review comment:
       `SolveInequalitiesToRange` finds the best range for the inequalities, and stores in `IntConstraints.ranges`. the reason we need `IntConstraints` instead of `Map<Var, Range>` is that, there might be some equations/inequalities that we can not deal, we don't silently drop but store them in `IntConstraints.relations`.
   
   `SolveInequalitiesDeskewRange` does one more step to create new variables which satisfy the original inequality constraints, yet always starts from zero. This is very useful when we deal with iteration indices in tvm compute. And maintaining the mapping between old&new variables is necessary for 1) transform the old expression (tvm compute) to the new. 2) `SolveInequalitiesDeskewRange` can be run multiple times (until they converge) to get better results, thus a chain of mapping is needed.
   
   You might have question why can't user invoke `SolveInequalitiesToRange` first and deskew to zero themselves? It's because variable ranges are solved iteratively, one variable's range depends on the previous solved range. `FindBestRange of var a  -> Deskew a -> FindBestRange of var b (given deskewed a) -> Deskew b (given deskewed a)  -> ...` is much more precise than `FindBestRange of var a  -> FindBestRange of var b (given range a) -> Deskew a & b independently`.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] ANSHUMAN87 commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
ANSHUMAN87 commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446658619



##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,648 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Array<Var>& variables, const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  // use variables to keep the order of iteration
+  // so as to get rid of any non-determinism.
+  CHECK_EQ(variables.size(), bounds.size());
+  for (const auto v : variables) {
+    CHECK(bounds.count(v));
+    const auto& bnds = bounds[v];
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQ(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GE(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LE(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQ>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LT>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LT>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LE>(op->b, op->a); }
+
+ private:
+  template <class T>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<T, LT>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LE(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return T(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {

Review comment:
       If new_ineq is not LENode, then may be we dont need this loop to enter, right? Please correct if i am wrong!

##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,648 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Array<Var>& variables, const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  // use variables to keep the order of iteration
+  // so as to get rid of any non-determinism.
+  CHECK_EQ(variables.size(), bounds.size());
+  for (const auto v : variables) {
+    CHECK(bounds.count(v));
+    const auto& bnds = bounds[v];
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQ(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GE(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LE(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQ>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LT>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LE>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LT>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LE>(op->b, op->a); }
+
+ private:
+  template <class T>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<T, LT>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LE(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return T(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {
+      const LENode* le = iter->as<LENode>();
+      if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
+        return;
+      } else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
+        iter = inequality_set->erase(iter);
+      } else {
+        ++iter;
+      }
+    } else {
+      ++iter;
+    }
+  }
+
+  inequality_set->insert(new_ineq);
+}
+
+void ClassifyByPolarity(
+    const Var& var,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* next_ineq_set,
+    std::vector<PrimExpr>* rest, std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
+    std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
+  // Take formulas from current_ineq_set and classify them according to polarity wrt var
+  // and store to coef_pos and coef_neg respectively.
+  for (const PrimExpr& ineq : current_ineq_set) {
+    if (const LENode* le = ineq.as<LENode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          coef_pos->push_back({coef0, coef[1]});
+        } else if (coef0 < 0) {
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    } else if (const EQNode* eq = ineq.as<EQNode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          // Equalities may be considered as pairs of two inequalities
+          coef_pos->push_back({coef0, coef[1]});
+          coef_neg->push_back({-coef0, -coef[1]});
+        } else if (coef0 < 0) {
+          coef_pos->push_back({-coef0, -coef[1]});
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    }
+
+    // if nothing worked, put it in rest
+    rest->push_back(ineq);
+  }
+}
+
+void MoveEquality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* upper_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* lower_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* equalities) {
+  // those exist in both upper & lower bounds will be moved to equalities
+  for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
+    auto lb = lower_bounds->find(*ub);
+    if (lb != lower_bounds->end()) {
+      equalities->insert(*lb);
+      lower_bounds->erase(lb);
+      ub = upper_bounds->erase(ub);
+    } else {
+      ++ub;
+    }
+  }
+}
+
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
+  arith::Analyzer analyzer;
+  analyzer.Bind(system_to_solve->ranges);
+
+  // The algorithm consists in doing the following things for each variable v
+  // - Take formulas from `current_ineq_set_to_solve` and
+  //   classify them according to polarity wrt v.
+  // - Combine each formula of positive polarity (wrt v)
+  //   with each formula of negative polarity.
+  // - Put the resulting combinations into `next_ineq_set_to_solve`
+  //   along with unclassifiable formulas.
+  // - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
+  //   and move to the next variable.
+
+  // normalized inequality
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> current_ineq_set_to_solve;
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> next_ineq_set_to_solve;
+  // A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
+  // A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
+
+  // formulas we don't know what to do with
+  std::vector<PrimExpr> rest;
+
+  // Simplify each inequality into the form `expr <= 0` and add to current formulas
+  for (const PrimExpr& ineq : system_to_solve->relations) {
+    AddInequality(&current_ineq_set_to_solve, NormalizeComparisons()(analyzer.Simplify(ineq, 3)),
+                  &analyzer);
+  }
+
+  Map<Var, IntGrpBounds> res_bounds;
+  for (const Var& v : system_to_solve->variables) {
+    CHECK(!res_bounds.count(v))
+        << "Variable " << v
+        << " appears more than one time in the `variables` which might be a bug";
+
+    next_ineq_set_to_solve.clear();
+    coef_pos.clear();
+    coef_neg.clear();
+
+    // Add bounds from vranges
+    if (system_to_solve->ranges.count(v)) {
+      const Range& range = system_to_solve->ranges[v];
+      PrimExpr range_lbound = analyzer.Simplify(range->min, 3);
+      PrimExpr range_ubound = analyzer.Simplify(range->min + range->extent - 1, 3);
+      coef_neg.push_back({-1, range_lbound});
+      coef_pos.push_back({1, -range_ubound});
+    }
+
+    ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
+                       &coef_neg, &analyzer);
+
+    // Combine each positive inequality with each negative one (by adding them together)
+    int64_t gcd_x, gcd_y;
+    for (const auto& pos : coef_pos) {
+      for (const auto& neg : coef_neg) {
+        auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
+        PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
+        PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
+        // eliminate the current variable
+        PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
+        PrimExpr new_ineq = LE(new_lhs, make_zero(pos.second.dtype()));
+        // we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
+        // to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
+        // with steps = 2 it's (y*2) - 10 <= 0
+        new_ineq = NormalizeComparisons()(analyzer.Simplify(new_ineq, 3));
+        AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
+      }
+    }
+
+    // Now we have to generate resulting (in)equalities for the variable v
+
+    // Find the common denominator in a sense
+    // We will generate formulas of the form coef_lcm*v <= bound
+    int64_t coef_lcm = 1;
+    for (const auto& pos : coef_pos) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
+    }
+    for (const auto& neg : coef_neg) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
+    }
+
+    // The resulting lower and upper bounds
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> upper_bounds;
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> lower_bounds;
+    upper_bounds.reserve(coef_pos.size());
+    lower_bounds.reserve(coef_neg.size());
+
+    for (const auto& pos : coef_pos) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / pos.first) * pos.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound <= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = upper_bounds.begin(); iter != upper_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound >= 0)) {
+          iter = upper_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the upper bound
+      upper_bounds.insert(bound);
+    }
+    for (const auto& neg : coef_neg) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / neg.first) * neg.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound >= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = lower_bounds.begin(); iter != lower_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound <= 0)) {
+          iter = lower_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the lower bound
+      lower_bounds.insert(bound);
+    }
+
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> equal;
+    equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
+    MoveEquality(&upper_bounds, &lower_bounds, &equal);
+    std::vector<PrimExpr> equal_list(equal.begin(), equal.end());
+    std::sort(equal_list.begin(), equal_list.end(), ExprLess());
+
+    // Write it to the result.
+    IntGrpBounds bnds(make_const(v.dtype(), coef_lcm),
+                      Array<PrimExpr>(lower_bounds.begin(), lower_bounds.end()),
+                      Array<PrimExpr>(equal_list.begin(), equal_list.end()),
+                      Array<PrimExpr>(upper_bounds.begin(), upper_bounds.end()));
+    res_bounds.Set(v, bnds);
+
+    std::swap(current_ineq_set_to_solve, next_ineq_set_to_solve);
+  }
+
+  // Everything that is left goes to res.relations
+  Array<PrimExpr> other_conditions;
+  for (const PrimExpr& e : current_ineq_set_to_solve) {
+    PrimExpr e_simp = analyzer.Simplify(e, 3);
+    if (is_const_int(e_simp, 0)) {
+      // contradiction detected
+      other_conditions = {const_false()};
+      break;
+    } else if (is_const_int(e_simp, 1)) {
+      continue;
+    } else {
+      other_conditions.push_back(e_simp);
+    }
+  }
+
+  for (const PrimExpr& e : rest) {
+    other_conditions.push_back(e);
+  }
+
+  return {res_bounds, other_conditions};
+}
+
+IntConstraints SolveInequalitiesToRange(const IntConstraints& inequalities) {
+  // Resulting ranges will contain ranges for the new variables and for the variables that are
+  // not in the inequalities->variables but are in inequalities->ranges
+  // It will be useful when solving Jacobian axes jac_xxx)
+  Map<Var, Range> res_ranges;
+  // we get a set of equality, lower, upper bound of each variable.
+  auto solved_system = SolveLinearInequalities(inequalities);
+
+  Map<Var, IntGrpBounds> solved_bounds = solved_system.first;
+  Array<PrimExpr> solved_other_relations = solved_system.second;
+
+  Array<PrimExpr> res_relations;
+
+  // this keeps being updated during determining the range of each variable.
+  Map<Var, Range> vranges;
+  for (std::pair<Var, Range> vr : inequalities->ranges) {
+    vranges.Set(vr.first, vr.second);
+  }
+
+  // We process variables in the reverse direction to start with the most independent one.
+  // This order is needed to compute new ranges.
+  for (auto it = inequalities->variables.rbegin(); it != inequalities->variables.rend(); ++it) {
+    arith::Analyzer analyzer;
+    analyzer.Bind(vranges);
+
+    const Var& var = *it;
+    CHECK(solved_bounds.count(var));
+    auto bnd = solved_bounds[var];
+    if (is_one(bnd->coef) && !bnd->equal.empty()) {
+      // There is an equation of the form `v == expr`, so this variable can be completely removed.
+      // Note that we use the 0-th expression because they are ordered by complexity,
+      // so it must be the simplest one.
+      Range best_range(bnd->equal[0], analyzer.Simplify(bnd->equal[0] + 1, 3));
+      res_ranges.Set(var, best_range);

Review comment:
       nit: res_ranges.Set & vranges.Set can be taken to common place below if...else... block.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] sergei-grechanik commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
sergei-grechanik commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r436795027



##########
File path: include/tvm/arith/int_solver.h
##########
@@ -26,17 +26,99 @@
 
 #include <tvm/ir/expr.h>
 #include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
 
 #include <unordered_map>
+#include <utility>
 #include <vector>
 
+#include "analyzer.h"
+
 namespace tvm {
 namespace arith {
 
 using tir::IterVar;
 using tir::Var;
 using tir::VarNode;
 
+/*!
+ * \brief Represent integer grouped bounds which are classified into
+ *        lower bounds (include), upper bounds (include) and equalities.
+ *        It also contains coefficient as a multiplier for the bounds, i.e.,
+ *        coef * var >= lower
+ *        coef * var == equal
+ *        coef * var <= upper
+ * \sa IntGrpBounds
+ */
+class IntGrpBoundsNode : public Object {
+ public:
+  PrimExpr coef;
+  Array<PrimExpr> lower;
+  Array<PrimExpr> equal;
+  Array<PrimExpr> upper;
+
+  void VisitAttrs(tvm::AttrVisitor* v) {
+    v->Visit("coef", &coef);
+    v->Visit("lower", &lower);
+    v->Visit("equal", &equal);
+    v->Visit("upper", &upper);
+  }
+
+  bool SEqualReduce(const IntGrpBoundsNode* other, SEqualReducer eq) const {
+    return eq(coef, other->coef) && eq(lower, other->lower) && eq(equal, other->equal) &&
+           eq(upper, other->upper);
+  }
+
+  void SHashReduce(SHashReducer hash_reduce) const {
+    hash_reduce(coef);
+    hash_reduce(lower);
+    hash_reduce(equal);
+    hash_reduce(upper);
+  }
+
+  static constexpr const bool _type_has_method_sequal_reduce = true;
+  static constexpr const char* _type_key = "arith.IntGrpBounds";
+  TVM_DECLARE_FINAL_OBJECT_INFO(IntGrpBoundsNode, Object);
+};
+
+/*!
+ * \brief Managed reference to IntGrpBoundsNode.
+ * \sa IntGrpBoundsNode
+ */
+class IntGrpBounds : public ObjectRef {
+ public:
+  /*!
+   * \brief Constructor by fields
+   * \param coef The coefficient. Must be integer.
+   *        coef * var >= lower
+   *        coef * var == equal
+   *        coef * var >= upper
+   * \param lower the lower bounds (include)
+   * \param equal equalities
+   * \param upper the upper bounds (include)
+   */
+  TVM_DLL IntGrpBounds(PrimExpr coef, Array<PrimExpr> lower, Array<PrimExpr> equal,
+                       Array<PrimExpr> upper);
+
+  /*!
+   * \brief Construct bounds from a range.
+   * \param r The range
+   * \return constructed bounds.
+   */
+  static IntGrpBounds range(const Range& r);
+
+  /*!
+   * \brief Perform substitution on all components of the struct.
+   */
+  IntGrpBounds Substitute(const Map<Var, PrimExpr>& subst) const;
+
+  Range FindBestRange(const Map<Var, Range>& vranges_addl = {}) const;
+
+  IntGrpBounds operator+(const Range& r);

Review comment:
       Add descriptions for FindBestRange and operator+.

##########
File path: tests/python/unittest/test_arith_solve_linear_inequality.py
##########
@@ -0,0 +1,166 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import random
+import sys
+import pytest
+import tvm
+from tvm import te, arith, ir, tir, testing
+
+
+def test_solve_system_of_inequalities():
+    seed = random.randrange(sys.maxsize)
+    print("\nThis test is intentionally non-deterministic, "
+          "if it fails please report it in github issue together with this seed {}\n".format(seed))
+    random.seed(seed)
+
+    def _check(variables, formulas, coef=(-5, 5), bounds=(-20, 20)):
+        vs = [te.var("x" + str(i)) for i in range(variables)]
+
+        fs = []
+        for i in range(formulas):
+            s1 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s1 += random.randint(coef[0], coef[1])
+            s2 = sum([v*random.randint(coef[0], coef[1]) for v in vs])
+            s2 += random.randint(coef[0], coef[1])
+            op = random.choice([tir.expr.EQ, tir.expr.LE, tir.expr.LT, tir.expr.GE, tir.expr.GT])
+            fs.append(op(s1, s2))
+
+        vranges = {v: tvm.ir.expr.Range(bounds[0], bounds[1] + 1) for v in vs}
+        before = te.all(tir.const(1, 'bool'), *fs)
+        after = arith._ffi_api.SolveInequalitiesAsCondition(vs, vranges, fs)
+        after = te.all(tir.const(1, 'bool'), *after)
+        testing.check_bool_expr_is_true(before == after, vranges)

Review comment:
       I would also add some random testing for the deskewing transformation (probably using the check_solution function)

##########
File path: include/tvm/arith/int_solver.h
##########
@@ -191,6 +275,30 @@ void SmithNormalFormDiag(std::vector<std::vector<int64_t>>* S, std::vector<std::
  */
 IntConstraintsTransform SolveLinearEquations(const IntConstraints& system_to_solve);
 
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return A map of variables and their solved bounds,
+ *         and constrains that cannot be solved to bounds.
+ */
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve);
+
+/*!
+ * \brief Solve linear inequalities.
+ * \param system_to_solve the variables to solve, their ranges, and a list of inequalities.
+ * \return The result ranges for each variables.
+ *         Constrains that cannot be transformed to Range will be stored in relations.
+ */
+IntConstraints SolveInequalitiesToRange(const IntConstraints& system_to_solve);

Review comment:
       Probably add some description of the structure of the resulting constraints for these functions.

##########
File path: python/tvm/arith/int_solver.py
##########
@@ -97,3 +143,33 @@ def solve_linear_equations(equations, variables=None, ranges=None):
     if isinstance(equations, IntConstraints):
         return _ffi_api.SolveLinearEquations(equations)
     return _ffi_api.SolveLinearEquations(variables, ranges, equations)
+
+
+def solve_linear_inequalities(equations, variables=None, ranges=None, deskew_range=False):
+    """Solve linear inequalities.
+
+    Parameters
+    ----------
+    equations   : List[tvm.ir.PrimExpr] or IntConstraints
+        The inequalities of the variables
+    variables   : Optional[List[tvm.tir.Var]]
+        The variables in the system.
+    ranges      : Optional[Map[tvm.tir.Var, tvm.ir.Range]]
+        The ranges of the variables.
+    deskew_range: Optional[bool]
+        Whether deskew the result ranges to be started from zero.
+        Default false.
+
+    Returns
+    -------
+    ret_ranges: IntConstraints or IntConstraintsTransform
+        The result ranges for each variables.
+        Constrains that cannot be transformed to Range will be stored in IntConstraints.relations.
+        If deskew_range is set (=True), the result ranges will be deskewed to be started from zero.
+        New variables are created accordingly therefore IntConstraintsTransform is returned.
+    """
+    solver = _ffi_api.SolveInequalitiesDeskewRange \
+        if deskew_range else _ffi_api.SolveInequalitiesToRange
+    if isinstance(equations, IntConstraints):

Review comment:
       assert that variables and ranges are None in this case

##########
File path: python/tvm/arith/int_solver.py
##########
@@ -20,6 +20,52 @@
 from . import _ffi_api
 
 
+@tvm._ffi.register_object("arith.IntGrpBounds")
+class IntGrpBounds(Object):
+    """Represent integer grouped bounds which are classified into
+       lower bounds (include), upper bounds (include) and equalities.
+
+    Parameters
+    ----------
+    coef : tvm.ir.PrimExpr
+        The coefficient. Must be integer.

Review comment:
       Can `coef` be a non-const expression?

##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  for (const auto iter : bounds) {
+    const Var& v = iter.first;
+    const auto& bnds = iter.second;
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQNode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GENode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LENode::make(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LTNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LTNode>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LENode>(op->b, op->a); }
+
+ private:
+  template <class TNode>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<TNode, LTNode>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LENode::make(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return TNode::make(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {
+      const LENode* le = iter->as<LENode>();
+      if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
+        return;
+      } else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
+        iter = inequality_set->erase(iter);
+      } else {
+        ++iter;
+      }
+    } else {
+      ++iter;
+    }
+  }
+
+  inequality_set->insert(new_ineq);
+}
+
+void ClassifyByPolarity(
+    const Var& var,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* next_ineq_set,
+    std::vector<PrimExpr>* rest, std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
+    std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
+  // Take formulas from current_ineq_set and classify them according to polarity wrt var
+  // and store to coef_pos and coef_neg respectively.
+  for (const PrimExpr& ineq : current_ineq_set) {
+    if (const LENode* le = ineq.as<LENode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          coef_pos->push_back({coef0, coef[1]});
+        } else if (coef0 < 0) {
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    } else if (const EQNode* eq = ineq.as<EQNode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          // Equalities may be considered as pairs of two inequalities
+          coef_pos->push_back({coef0, coef[1]});
+          coef_neg->push_back({-coef0, -coef[1]});
+        } else if (coef0 < 0) {
+          coef_pos->push_back({-coef0, -coef[1]});
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    }
+
+    // if nothing worked, put it in rest
+    rest->push_back(ineq);
+  }
+}
+
+void MoveEquality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* upper_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* lower_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* equalities) {
+  // those exist in both upper & lower bounds will be moved to equalities
+  for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
+    auto lb = lower_bounds->find(*ub);
+    if (lb != lower_bounds->end()) {
+      equalities->insert(*lb);
+      lower_bounds->erase(lb);
+      ub = upper_bounds->erase(ub);
+    } else {
+      ++ub;
+    }
+  }
+}
+
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
+  arith::Analyzer analyzer;
+  analyzer.Bind(system_to_solve->ranges);
+
+  // The algorithm consists in doing the following things for each variable v
+  // - Take formulas from `current_ineq_set_to_solve` and
+  //   classify them according to polarity wrt v.
+  // - Combine each formula of positive polarity (wrt v)
+  //   with each formula of negative polarity.
+  // - Put the resulting combinations into `next_ineq_set_to_solve`
+  //   along with unclassifiable formulas.
+  // - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
+  //   and move to the next variable.
+
+  // normalized inequality
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> current_ineq_set_to_solve;
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> next_ineq_set_to_solve;
+  // A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
+  // A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
+
+  // formulas we don't know what to do with
+  std::vector<PrimExpr> rest;
+
+  // Simplify each inequality into the form `expr <= 0` and add to current formulas
+  for (const PrimExpr& ineq : system_to_solve->relations) {
+    AddInequality(&current_ineq_set_to_solve, NormalizeComparisons()(analyzer.Simplify(ineq, 3)),
+                  &analyzer);
+  }
+
+  Map<Var, IntGrpBounds> res_bounds;
+  for (const Var& v : system_to_solve->variables) {
+    CHECK(!res_bounds.count(v))
+        << "Variable " << v
+        << " appears more than one time in the `variables` which might be a bug";
+
+    next_ineq_set_to_solve.clear();
+    coef_pos.clear();
+    coef_neg.clear();
+
+    // Add bounds from vranges
+    if (system_to_solve->ranges.count(v)) {
+      const Range& range = system_to_solve->ranges[v];
+      PrimExpr range_lbound = analyzer.Simplify(range->min, 3);
+      PrimExpr range_ubound = analyzer.Simplify(range->min + range->extent - 1, 3);
+      coef_neg.push_back({-1, range_lbound});
+      coef_pos.push_back({1, -range_ubound});
+    }
+
+    ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
+                       &coef_neg, &analyzer);
+
+    // Combine each positive inequality with each negative one (by adding them together)
+    int64_t gcd_x, gcd_y;
+    for (const auto& pos : coef_pos) {
+      for (const auto& neg : coef_neg) {
+        auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
+        PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
+        PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
+        // eliminate the current variable
+        PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
+        PrimExpr new_ineq = LENode::make(new_lhs, make_zero(pos.second.dtype()));
+        // we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
+        // to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
+        // with steps = 2 it's (y*2) - 10 <= 0
+        new_ineq = NormalizeComparisons()(analyzer.Simplify(new_ineq, 3));
+        AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
+      }
+    }
+
+    // Now we have to generate resulting (in)equalities for the variable v
+
+    // Find the common denominator in a sense
+    // We will generate formulas of the form coef_lcm*v <= bound
+    int64_t coef_lcm = 1;
+    for (const auto& pos : coef_pos) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
+    }
+    for (const auto& neg : coef_neg) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
+    }
+
+    // The resulting lower and upper bounds stored in sorted vectors

Review comment:
       Remove the "stored in sorted vectors" part of the comment since this is not true anymore

##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  for (const auto iter : bounds) {
+    const Var& v = iter.first;
+    const auto& bnds = iter.second;
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQNode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GENode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LENode::make(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LTNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LTNode>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LENode>(op->b, op->a); }
+
+ private:
+  template <class TNode>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<TNode, LTNode>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LENode::make(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return TNode::make(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {
+      const LENode* le = iter->as<LENode>();
+      if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
+        return;
+      } else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
+        iter = inequality_set->erase(iter);
+      } else {
+        ++iter;
+      }
+    } else {
+      ++iter;
+    }
+  }
+
+  inequality_set->insert(new_ineq);
+}
+
+void ClassifyByPolarity(
+    const Var& var,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* next_ineq_set,
+    std::vector<PrimExpr>* rest, std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
+    std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
+  // Take formulas from current_ineq_set and classify them according to polarity wrt var
+  // and store to coef_pos and coef_neg respectively.
+  for (const PrimExpr& ineq : current_ineq_set) {
+    if (const LENode* le = ineq.as<LENode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          coef_pos->push_back({coef0, coef[1]});
+        } else if (coef0 < 0) {
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    } else if (const EQNode* eq = ineq.as<EQNode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          // Equalities may be considered as pairs of two inequalities
+          coef_pos->push_back({coef0, coef[1]});
+          coef_neg->push_back({-coef0, -coef[1]});
+        } else if (coef0 < 0) {
+          coef_pos->push_back({-coef0, -coef[1]});
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    }
+
+    // if nothing worked, put it in rest
+    rest->push_back(ineq);
+  }
+}
+
+void MoveEquality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* upper_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* lower_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* equalities) {
+  // those exist in both upper & lower bounds will be moved to equalities
+  for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
+    auto lb = lower_bounds->find(*ub);
+    if (lb != lower_bounds->end()) {
+      equalities->insert(*lb);
+      lower_bounds->erase(lb);
+      ub = upper_bounds->erase(ub);
+    } else {
+      ++ub;
+    }
+  }
+}
+
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
+  arith::Analyzer analyzer;
+  analyzer.Bind(system_to_solve->ranges);
+
+  // The algorithm consists in doing the following things for each variable v
+  // - Take formulas from `current_ineq_set_to_solve` and
+  //   classify them according to polarity wrt v.
+  // - Combine each formula of positive polarity (wrt v)
+  //   with each formula of negative polarity.
+  // - Put the resulting combinations into `next_ineq_set_to_solve`
+  //   along with unclassifiable formulas.
+  // - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
+  //   and move to the next variable.
+
+  // normalized inequality
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> current_ineq_set_to_solve;
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> next_ineq_set_to_solve;
+  // A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
+  // A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
+
+  // formulas we don't know what to do with
+  std::vector<PrimExpr> rest;
+
+  // Simplify each inequality into the form `expr <= 0` and add to current formulas
+  for (const PrimExpr& ineq : system_to_solve->relations) {
+    AddInequality(&current_ineq_set_to_solve, NormalizeComparisons()(analyzer.Simplify(ineq, 3)),
+                  &analyzer);
+  }
+
+  Map<Var, IntGrpBounds> res_bounds;
+  for (const Var& v : system_to_solve->variables) {
+    CHECK(!res_bounds.count(v))
+        << "Variable " << v
+        << " appears more than one time in the `variables` which might be a bug";
+
+    next_ineq_set_to_solve.clear();
+    coef_pos.clear();
+    coef_neg.clear();
+
+    // Add bounds from vranges
+    if (system_to_solve->ranges.count(v)) {
+      const Range& range = system_to_solve->ranges[v];
+      PrimExpr range_lbound = analyzer.Simplify(range->min, 3);
+      PrimExpr range_ubound = analyzer.Simplify(range->min + range->extent - 1, 3);
+      coef_neg.push_back({-1, range_lbound});
+      coef_pos.push_back({1, -range_ubound});
+    }
+
+    ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
+                       &coef_neg, &analyzer);
+
+    // Combine each positive inequality with each negative one (by adding them together)
+    int64_t gcd_x, gcd_y;
+    for (const auto& pos : coef_pos) {
+      for (const auto& neg : coef_neg) {
+        auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
+        PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
+        PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
+        // eliminate the current variable
+        PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
+        PrimExpr new_ineq = LENode::make(new_lhs, make_zero(pos.second.dtype()));
+        // we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
+        // to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
+        // with steps = 2 it's (y*2) - 10 <= 0
+        new_ineq = NormalizeComparisons()(analyzer.Simplify(new_ineq, 3));
+        AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
+      }
+    }
+
+    // Now we have to generate resulting (in)equalities for the variable v
+
+    // Find the common denominator in a sense
+    // We will generate formulas of the form coef_lcm*v <= bound
+    int64_t coef_lcm = 1;
+    for (const auto& pos : coef_pos) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
+    }
+    for (const auto& neg : coef_neg) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
+    }
+
+    // The resulting lower and upper bounds stored in sorted vectors
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> upper_bounds;
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> lower_bounds;
+    upper_bounds.reserve(coef_pos.size());
+    lower_bounds.reserve(coef_neg.size());
+
+    for (const auto& pos : coef_pos) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / pos.first) * pos.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound <= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = upper_bounds.begin(); iter != upper_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound >= 0)) {
+          iter = upper_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the upper bound
+      upper_bounds.insert(bound);
+    }
+    for (const auto& neg : coef_neg) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / neg.first) * neg.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound >= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = lower_bounds.begin(); iter != lower_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound <= 0)) {
+          iter = lower_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the lower bound
+      lower_bounds.insert(bound);
+    }
+
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> equal;
+    equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
+    MoveEquality(&upper_bounds, &lower_bounds, &equal);
+    std::vector<PrimExpr> equal_list(equal.begin(), equal.end());
+    std::sort(equal_list.begin(), equal_list.end(), ExprLess());
+
+    // Write it to the result.
+    IntGrpBounds bnds(make_const(v.dtype(), coef_lcm),
+                      Array<PrimExpr>(lower_bounds.begin(), lower_bounds.end()),
+                      Array<PrimExpr>(equal_list.begin(), equal_list.end()),
+                      Array<PrimExpr>(upper_bounds.begin(), upper_bounds.end()));

Review comment:
       lower_bounds and upper_bounds seem to be unsorted here. Doesn't it cause any problems?

##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);
+  }
+};
+
+/*!
+ * \brief Combine the information into an array of (in)equalities.
+ */
+Array<PrimExpr> as_conditions(const Map<Var, IntGrpBounds>& bounds,
+                              const Array<PrimExpr>& relations) {
+  Array<PrimExpr> res;
+  for (const auto iter : bounds) {
+    const Var& v = iter.first;
+    const auto& bnds = iter.second;
+    PrimExpr lhs = bnds->coef * v;
+    for (const PrimExpr& rhs : bnds->equal) {
+      res.push_back(tir::EQNode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->lower) {
+      res.push_back(tir::GENode::make(lhs, rhs));
+    }
+    for (const PrimExpr& rhs : bnds->upper) {
+      res.push_back(tir::LENode::make(lhs, rhs));
+    }
+  }
+  for (const PrimExpr& e : relations) {
+    res.push_back(e);
+  }
+  return res;
+}
+
+void DebugPrint(
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& next_ineq_set,
+    const std::vector<PrimExpr>& rest, const std::vector<std::pair<int64_t, PrimExpr>>& coef_pos,
+    const std::vector<std::pair<int64_t, PrimExpr>>& coef_neg) {
+  std::cout << "Current ineq set:\n[";
+  for (auto& ineq : current_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "Next ineq set:\n[";
+  for (auto& ineq : next_ineq_set) {
+    std::cout << ineq << ", ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_pos:\n[";
+  for (auto& coef : coef_pos) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+
+  std::cout << "coef_neg:\n[";
+  for (auto& coef : coef_neg) {
+    std::cout << "(" << coef.first << ", " << coef.second << "), ";
+  }
+  std::cout << "]\n";
+}
+
+/*!
+ * \brief normalize to the form `expr <= 0`
+ */
+class NormalizeComparisons : public ExprMutator {
+ public:
+  PrimExpr VisitExpr_(const EQNode* op) override { return Make<EQNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const NENode* op) override { return Make<NENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LTNode* op) override { return Make<LTNode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const LENode* op) override { return Make<LENode>(op->a, op->b); }
+  PrimExpr VisitExpr_(const GTNode* op) override { return Make<LTNode>(op->b, op->a); }
+  PrimExpr VisitExpr_(const GENode* op) override { return Make<LENode>(op->b, op->a); }
+
+ private:
+  template <class TNode>
+  PrimExpr Make(const PrimExpr& a, const PrimExpr& b) {
+    // rewrite LT to LE for ints
+    if (std::is_same<TNode, LTNode>::value && (a.dtype().is_int() || a.dtype().is_uint())) {
+      return LENode::make(analyzer_.Simplify(a - b + 1), make_zero(a.dtype()));
+    }
+    return TNode::make(analyzer_.Simplify(a - b), make_zero(a.dtype()));
+  }
+  arith::Analyzer analyzer_;
+};
+
+void AddInequality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* inequality_set,
+                   const PrimExpr& new_ineq, Analyzer* analyzer) {
+  if (analyzer->CanProve(new_ineq) || inequality_set->find(new_ineq) != inequality_set->end()) {
+    // redundant: follows from the vranges
+    // or has already been added
+    return;
+  }
+  for (auto iter = inequality_set->begin(); iter != inequality_set->end();) {
+    if (const LENode* new_le = new_ineq.as<LENode>()) {
+      const LENode* le = iter->as<LENode>();
+      if (le && analyzer->CanProve(new_le->a - le->a <= 0)) {
+        return;
+      } else if (le && analyzer->CanProve(le->a - new_le->a <= 0)) {
+        iter = inequality_set->erase(iter);
+      } else {
+        ++iter;
+      }
+    } else {
+      ++iter;
+    }
+  }
+
+  inequality_set->insert(new_ineq);
+}
+
+void ClassifyByPolarity(
+    const Var& var,
+    const std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>& current_ineq_set,
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* next_ineq_set,
+    std::vector<PrimExpr>* rest, std::vector<std::pair<int64_t, PrimExpr>>* coef_pos,
+    std::vector<std::pair<int64_t, PrimExpr>>* coef_neg, Analyzer* analyzer) {
+  // Take formulas from current_ineq_set and classify them according to polarity wrt var
+  // and store to coef_pos and coef_neg respectively.
+  for (const PrimExpr& ineq : current_ineq_set) {
+    if (const LENode* le = ineq.as<LENode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(le->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          coef_pos->push_back({coef0, coef[1]});
+        } else if (coef0 < 0) {
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    } else if (const EQNode* eq = ineq.as<EQNode>()) {
+      Array<PrimExpr> coef = arith::DetectLinearEquation(eq->a, {var});
+      if (!coef.empty() && is_const(coef[0])) {
+        int64_t coef0 = *as_const_int(coef[0]);
+        if (coef0 == 0) {
+          // zero polarity, straight to next_ineq_set
+          AddInequality(next_ineq_set, ineq, analyzer);
+        } else if (coef0 > 0) {
+          // Equalities may be considered as pairs of two inequalities
+          coef_pos->push_back({coef0, coef[1]});
+          coef_neg->push_back({-coef0, -coef[1]});
+        } else if (coef0 < 0) {
+          coef_pos->push_back({-coef0, -coef[1]});
+          coef_neg->push_back({coef0, coef[1]});
+        }
+        continue;
+      }
+    }
+
+    // if nothing worked, put it in rest
+    rest->push_back(ineq);
+  }
+}
+
+void MoveEquality(std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* upper_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* lower_bounds,
+                  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual>* equalities) {
+  // those exist in both upper & lower bounds will be moved to equalities
+  for (auto ub = upper_bounds->begin(); ub != upper_bounds->end();) {
+    auto lb = lower_bounds->find(*ub);
+    if (lb != lower_bounds->end()) {
+      equalities->insert(*lb);
+      lower_bounds->erase(lb);
+      ub = upper_bounds->erase(ub);
+    } else {
+      ++ub;
+    }
+  }
+}
+
+PartialSolvedInequalities SolveLinearInequalities(const IntConstraints& system_to_solve) {
+  arith::Analyzer analyzer;
+  analyzer.Bind(system_to_solve->ranges);
+
+  // The algorithm consists in doing the following things for each variable v
+  // - Take formulas from `current_ineq_set_to_solve` and
+  //   classify them according to polarity wrt v.
+  // - Combine each formula of positive polarity (wrt v)
+  //   with each formula of negative polarity.
+  // - Put the resulting combinations into `next_ineq_set_to_solve`
+  //   along with unclassifiable formulas.
+  // - Replace `current_ineq_set_to_solve` with `next_ineq_set_to_solve`
+  //   and move to the next variable.
+
+  // normalized inequality
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> current_ineq_set_to_solve;
+  std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> next_ineq_set_to_solve;
+  // A vector of pairs (c, e), c > 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_pos;
+  // A vector of pairs (c, e), c < 0, representing formulas of the form c*v + e <= 0
+  std::vector<std::pair<int64_t, PrimExpr>> coef_neg;
+
+  // formulas we don't know what to do with
+  std::vector<PrimExpr> rest;
+
+  // Simplify each inequality into the form `expr <= 0` and add to current formulas
+  for (const PrimExpr& ineq : system_to_solve->relations) {
+    AddInequality(&current_ineq_set_to_solve, NormalizeComparisons()(analyzer.Simplify(ineq, 3)),
+                  &analyzer);
+  }
+
+  Map<Var, IntGrpBounds> res_bounds;
+  for (const Var& v : system_to_solve->variables) {
+    CHECK(!res_bounds.count(v))
+        << "Variable " << v
+        << " appears more than one time in the `variables` which might be a bug";
+
+    next_ineq_set_to_solve.clear();
+    coef_pos.clear();
+    coef_neg.clear();
+
+    // Add bounds from vranges
+    if (system_to_solve->ranges.count(v)) {
+      const Range& range = system_to_solve->ranges[v];
+      PrimExpr range_lbound = analyzer.Simplify(range->min, 3);
+      PrimExpr range_ubound = analyzer.Simplify(range->min + range->extent - 1, 3);
+      coef_neg.push_back({-1, range_lbound});
+      coef_pos.push_back({1, -range_ubound});
+    }
+
+    ClassifyByPolarity(v, current_ineq_set_to_solve, &next_ineq_set_to_solve, &rest, &coef_pos,
+                       &coef_neg, &analyzer);
+
+    // Combine each positive inequality with each negative one (by adding them together)
+    int64_t gcd_x, gcd_y;
+    for (const auto& pos : coef_pos) {
+      for (const auto& neg : coef_neg) {
+        auto first_gcd = ExtendedEuclidean(pos.first, -neg.first, &gcd_x, &gcd_y);
+        PrimExpr c_pos = make_const(v.dtype(), neg.first / first_gcd);
+        PrimExpr c_neg = make_const(v.dtype(), pos.first / first_gcd);
+        // eliminate the current variable
+        PrimExpr new_lhs = c_neg * neg.second - c_pos * pos.second;
+        PrimExpr new_ineq = LENode::make(new_lhs, make_zero(pos.second.dtype()));
+        // we need rewrite_simplify -> canonical_simplify -> rewrite_simplify
+        // to help simplify things like (((y + 10) - (-1*(y - 20))) <= 0) => y - 5 <= 0
+        // with steps = 2 it's (y*2) - 10 <= 0
+        new_ineq = NormalizeComparisons()(analyzer.Simplify(new_ineq, 3));
+        AddInequality(&next_ineq_set_to_solve, new_ineq, &analyzer);
+      }
+    }
+
+    // Now we have to generate resulting (in)equalities for the variable v
+
+    // Find the common denominator in a sense
+    // We will generate formulas of the form coef_lcm*v <= bound
+    int64_t coef_lcm = 1;
+    for (const auto& pos : coef_pos) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, pos.first);
+    }
+    for (const auto& neg : coef_neg) {
+      coef_lcm = LeastCommonMultiple(coef_lcm, -neg.first);
+    }
+
+    // The resulting lower and upper bounds stored in sorted vectors
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> upper_bounds;
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> lower_bounds;
+    upper_bounds.reserve(coef_pos.size());
+    lower_bounds.reserve(coef_neg.size());
+
+    for (const auto& pos : coef_pos) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / pos.first) * pos.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(upper_bounds.begin(), upper_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound <= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = upper_bounds.begin(); iter != upper_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound >= 0)) {
+          iter = upper_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the upper bound
+      upper_bounds.insert(bound);
+    }
+    for (const auto& neg : coef_neg) {
+      PrimExpr bound = make_const(v.dtype(), -coef_lcm / neg.first) * neg.second;
+      bound = analyzer.Simplify(bound, 3);
+      // Don't add if any of the existing bounds is better
+      if (std::any_of(lower_bounds.begin(), lower_bounds.end(),
+                      [&bound, &analyzer](const PrimExpr& o) {
+                        return analyzer.CanProve(o - bound >= 0);
+                      })) {
+        continue;
+      }
+      // Erase all worse bounds
+      for (auto iter = lower_bounds.begin(); iter != lower_bounds.end();) {
+        if (analyzer.CanProve(*iter - bound <= 0)) {
+          iter = lower_bounds.erase(iter);
+        } else {
+          ++iter;
+        }
+      }
+      // Add the lower bound
+      lower_bounds.insert(bound);
+    }
+
+    std::unordered_set<PrimExpr, StructuralHash, StructuralEqual> equal;
+    equal.reserve(std::min(upper_bounds.size(), lower_bounds.size()));
+    MoveEquality(&upper_bounds, &lower_bounds, &equal);
+    std::vector<PrimExpr> equal_list(equal.begin(), equal.end());
+    std::sort(equal_list.begin(), equal_list.end(), ExprLess());
+
+    // Write it to the result.
+    IntGrpBounds bnds(make_const(v.dtype(), coef_lcm),
+                      Array<PrimExpr>(lower_bounds.begin(), lower_bounds.end()),
+                      Array<PrimExpr>(equal_list.begin(), equal_list.end()),
+                      Array<PrimExpr>(upper_bounds.begin(), upper_bounds.end()));
+    res_bounds.Set(v, bnds);
+
+    std::swap(current_ineq_set_to_solve, next_ineq_set_to_solve);
+  }
+
+  // Everything that is left goes to res.relations
+  Array<PrimExpr> other_conditions;
+  for (const PrimExpr& e : current_ineq_set_to_solve) {
+    PrimExpr e_simp = analyzer.Simplify(e, 3);
+    if (is_const_int(e_simp, 0)) {
+      // contradiction detected
+      other_conditions = {const_false()};
+      break;
+    } else if (is_const_int(e_simp, 1)) {
+      continue;
+    } else {
+      other_conditions.push_back(e_simp);
+    }
+  }
+
+  for (const PrimExpr& e : rest) {
+    other_conditions.push_back(e);
+  }
+
+  return {res_bounds, other_conditions};
+}
+
+IntConstraints SolveInequalitiesToRange(const IntConstraints& inequalities) {
+  // Resulting ranges will contain ranges for the new variables and for the variables that are
+  // not in the inequalities->variables but are in inequalities->ranges
+  // It will be useful when solving Jacobian axes jac_xxx)
+  Map<Var, Range> res_ranges;
+  // we get a set of equality, lower, upper bound of each variable.
+  auto solved_system = SolveLinearInequalities(inequalities);
+
+  Map<Var, IntGrpBounds> solved_bounds = solved_system.first;
+  Array<PrimExpr> solved_other_relations = solved_system.second;
+
+  Array<Var> res_variables;
+  Array<PrimExpr> res_relations;
+
+  // this keeps being updated during determining the range of each variable.
+  Map<Var, Range> vranges;
+  for (std::pair<Var, Range> vr : inequalities->ranges) {
+    vranges.Set(vr.first, vr.second);
+  }
+
+  // We process variables in the reverse direction to start with the most independent one.
+  // This order is needed to compute new ranges.
+  for (auto it = inequalities->variables.rbegin(); it != inequalities->variables.rend(); ++it) {
+    arith::Analyzer analyzer;
+    analyzer.Bind(vranges);
+
+    const Var& var = *it;
+    CHECK(solved_bounds.count(var));
+    auto bnd = solved_bounds[var];
+    if (is_one(bnd->coef) && !bnd->equal.empty()) {
+      // There is an equation of the form `v == expr`, so this variable can be completely removed.
+      // Note that we use the 0-th expression because they are ordered by complexity,
+      // so it must be the simplest one.
+      Range best_range(bnd->equal[0], analyzer.Simplify(bnd->equal[0] + 1, 3));
+      res_ranges.Set(var, best_range);
+      vranges.Set(var, best_range);
+    } else {
+      if (vranges.count(var) > 0) {
+        bnd = bnd + vranges[var];
+      }
+
+      auto best_range = bnd.FindBestRange(vranges);
+
+      if (best_range.defined()) {
+        res_ranges.Set(var, best_range);
+        vranges.Set(var, best_range);
+      }
+    }
+  }
+
+  // Add the original conditions (with variables substituted) to the resulting conditions

Review comment:
       As far as I understand there is no variable substitution here.

##########
File path: python/tvm/arith/int_solver.py
##########
@@ -97,3 +143,33 @@ def solve_linear_equations(equations, variables=None, ranges=None):
     if isinstance(equations, IntConstraints):
         return _ffi_api.SolveLinearEquations(equations)
     return _ffi_api.SolveLinearEquations(variables, ranges, equations)
+
+
+def solve_linear_inequalities(equations, variables=None, ranges=None, deskew_range=False):
+    """Solve linear inequalities.
+
+    Parameters
+    ----------
+    equations   : List[tvm.ir.PrimExpr] or IntConstraints
+        The inequalities of the variables
+    variables   : Optional[List[tvm.tir.Var]]
+        The variables in the system.
+    ranges      : Optional[Map[tvm.tir.Var, tvm.ir.Range]]
+        The ranges of the variables.
+    deskew_range: Optional[bool]
+        Whether deskew the result ranges to be started from zero.
+        Default false.
+
+    Returns
+    -------
+    ret_ranges: IntConstraints or IntConstraintsTransform

Review comment:
       Probably it would be better to modify this functions so that it always returns IntConstraintsTransform, not sure.

##########
File path: src/arith/solve_linear_inequality.cc
##########
@@ -0,0 +1,629 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*!
+ * \file tvm/arith/solve_linear_inequality.cc
+ * \brief Solve linear inequalities.
+ */
+#include <tvm/arith/analyzer.h>
+#include <tvm/arith/int_solver.h>
+#include <tvm/arith/pattern.h>
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/registry.h>
+#include <tvm/tir/analysis.h>
+#include <tvm/tir/expr.h>
+#include <tvm/tir/op.h>
+#include <tvm/tir/stmt_functor.h>
+
+#include "int_operator.h"
+
+namespace tvm {
+namespace arith {
+
+using namespace tvm::runtime;
+using namespace tvm::tir;
+
+#define PLUS_ONE(OP) \
+  void VisitExpr_(const OP* op) final { num_symbols_++; }
+
+#define PLUS_ONE_BINARY(OP)             \
+  void VisitExpr_(const OP* op) final { \
+    num_symbols_++;                     \
+    VisitExpr(op->a);                   \
+    VisitExpr(op->b);                   \
+  }
+
+/*!
+ * \brief Calculate the expresion complexity based on number of symbols it contains.
+ */
+class ExprComplexity : public ExprVisitor {
+ public:
+  size_t Eval(const PrimExpr& expr) {
+    VisitExpr(expr);
+    return num_symbols_;
+  }
+
+  PLUS_ONE_BINARY(AddNode)
+  PLUS_ONE_BINARY(SubNode)
+  PLUS_ONE_BINARY(MulNode)
+  PLUS_ONE_BINARY(DivNode)
+  PLUS_ONE_BINARY(ModNode)
+  PLUS_ONE_BINARY(FloorDivNode)
+  PLUS_ONE_BINARY(FloorModNode)
+  PLUS_ONE_BINARY(MinNode)
+  PLUS_ONE_BINARY(MaxNode)
+  PLUS_ONE_BINARY(EQNode)
+  PLUS_ONE_BINARY(NENode)
+  PLUS_ONE_BINARY(LTNode)
+  PLUS_ONE_BINARY(LENode)
+  PLUS_ONE_BINARY(GTNode)
+  PLUS_ONE_BINARY(GENode)
+  PLUS_ONE_BINARY(AndNode)
+  PLUS_ONE_BINARY(OrNode)
+  PLUS_ONE(VarNode)
+  PLUS_ONE(FloatImmNode)
+  PLUS_ONE(IntImmNode)
+  void VisitExpr_(const NotNode* op) final {
+    num_symbols_++;
+    VisitExpr(op->a);
+  }
+
+ private:
+  size_t num_symbols_{0};
+};
+
+struct ExprLess {
+  bool operator()(const PrimExpr& l, const PrimExpr& r) const {
+    return ExprComplexity().Eval(l) < ExprComplexity().Eval(r);

Review comment:
       This order is not total, so there may be problems with determinism. I would use some total order in the case when `ExprComplexity().Eval(l) == ExprComplexity().Eval(r)` for disambiguation.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [incubator-tvm] yzhliu commented on a change in pull request #5618: [Arith] Inequalities solver

Posted by GitBox <gi...@apache.org>.
yzhliu commented on a change in pull request #5618:
URL: https://github.com/apache/incubator-tvm/pull/5618#discussion_r446359262



##########
File path: python/tvm/testing.py
##########
@@ -188,5 +189,96 @@ def assert_prim_expr_equal(lhs, rhs):
         raise ValueError("{} and {} are not equal".format(lhs, rhs))
 
 
+def check_bool_expr_is_true(bool_expr, vranges, cond=None):
+    """ Check that bool_expr holds given the condition cond
+    for every value of free variables from vranges.
+
+    Parameters
+    ----------
+    bool_expr : tvm.ir.expr.PrimExpr
+        Boolean expression to check
+    vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range]
+        Free variables and their ranges
+    cond: tvm.ir.expr.PrimExpr
+        extra conditions needs to be satisfied.
+    """
+    if cond is not None:
+        bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr)

Review comment:
       for example, `2x > 4y` solves to `x > 2y` given x \in (0, 10), y \in (0, 10)
   It essentially creates iterations 
   ```python
   for x in range(10):
     for y in range(10):
       assert !(2x > 4y) || (x > 2y)
   ```
   I'll add the above to the comments




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org