From 65a934936439076085779892ef6658da6d6b85cc Mon Sep 17 00:00:00 2001 From: Andrew Adams Date: Tue, 3 Nov 2026 12:11:33 -0800 Subject: [PATCH 1/5] Add inductive Funcs: pure definitions that refer to themselves A Func may now be defined in terms of itself at earlier values of some of its pure Vars, with the recursion guarded by a select that names the base case, e.g. Func f(Int(32), "f"); f(x) = select(x <= 0, in(0), in(x) + f(x - 1)); Unlike the equivalent RDom scan, such a Func can be computed at its consumer, slid, and folded down to the few values the recurrence still reads. A Func that refers to itself must be declared with an explicit type. - Function classifies the Func and each of its Vars as inductive, and gives inductive Vars a new DimType, InductiveVar, which can't be parallelized, vectorized, or reordered against another loop derived from the same Var. - Bounds inference expands the region required of an inductive Func to reach its base case (Inductive.cpp). - Inductive Funcs can't be inlined or be pipeline outputs. An inductive update's RVars must be nested inside its inductive Vars. - Ring buffering rewrites a Func's calls to itself inside its own stores. Extracted from abadams/inductive_benchmarks, which builds on PR #8878. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- Makefile | 2 + src/AsyncProducers.cpp | 11 +- src/Bounds.cpp | 2 +- src/BoundsInference.cpp | 22 + src/CMakeLists.txt | 2 + src/Deserialization.cpp | 2 + src/Func.cpp | 83 +++- src/Func.h | 9 + src/Function.cpp | 218 ++++++++- src/Function.h | 6 + src/IR.cpp | 6 +- src/IRPrinter.cpp | 3 + src/Inductive.cpp | 207 +++++++++ src/Inductive.h | 62 +++ src/ParallelRVar.cpp | 15 +- src/ParallelRVar.h | 9 +- src/Schedule.h | 9 + src/ScheduleFunctions.cpp | 42 +- src/Serialization.cpp | 2 + src/halide_ir.fbs | 1 + test/correctness/CMakeLists.txt | 7 + .../correctness/fold_inductive_keeps_step.cpp | 125 +++++ test/correctness/inductive.cpp | 430 ++++++++++++++++++ .../inductive_base_case_bounds.cpp | 122 +++++ test/correctness/inductive_errors.cpp | 249 ++++++++++ test/correctness/inductive_folding.cpp | 129 ++++++ test/correctness/inductive_ring_buffer.cpp | 38 ++ test/correctness/inductive_var_race.cpp | 49 ++ 28 files changed, 1827 insertions(+), 35 deletions(-) create mode 100644 src/Inductive.cpp create mode 100644 src/Inductive.h create mode 100644 test/correctness/fold_inductive_keeps_step.cpp create mode 100644 test/correctness/inductive.cpp create mode 100644 test/correctness/inductive_base_case_bounds.cpp create mode 100644 test/correctness/inductive_errors.cpp create mode 100644 test/correctness/inductive_folding.cpp create mode 100644 test/correctness/inductive_ring_buffer.cpp create mode 100644 test/correctness/inductive_var_race.cpp diff --git a/Makefile b/Makefile index bfdea79938de..b10c3e02a21c 100644 --- a/Makefile +++ b/Makefile @@ -525,6 +525,7 @@ SOURCE_FILES = \ HexagonOffload.cpp \ HexagonOptimize.cpp \ ImageParam.cpp \ + Inductive.cpp \ InferArguments.cpp \ InjectHostDevBufferCopies.cpp \ Inline.cpp \ @@ -735,6 +736,7 @@ HEADER_FILES = \ HexagonOffload.h \ HexagonOptimize.h \ ImageParam.h \ + Inductive.h \ InferArguments.h \ InjectHostDevBufferCopies.h \ Inline.h \ diff --git a/src/AsyncProducers.cpp b/src/AsyncProducers.cpp index 3dd42a8a54d5..6a90478796f5 100644 --- a/src/AsyncProducers.cpp +++ b/src/AsyncProducers.cpp @@ -690,16 +690,21 @@ class UpdateIndices : public IRMutator { Stmt visit(const Provide *op) override { if (op->name == func_name) { - std::vector args = op->args; + // A Func defined in terms of itself calls itself in the values it + // stores, and those calls need the ring index as much as the store + // does, so mutate them rather than passing them through. + std::vector values = mutate(op->values); + std::vector args = mutate(op->args); + Expr predicate = mutate(op->predicate); args.push_back(ring_buffer_index); - return op->with(op->values, args, op->predicate); + return op->with(values, args, predicate); } return IRMutator::visit(op); } Expr visit(const Call *op) override { if (op->call_type == Call::Halide && op->name == func_name) { - std::vector args = op->args; + std::vector args = mutate(op->args); args.push_back(ring_buffer_index); return op->with(args); } diff --git a/src/Bounds.cpp b/src/Bounds.cpp index 738652696b81..64c4c5a0e5b0 100644 --- a/src/Bounds.cpp +++ b/src/Bounds.cpp @@ -3512,7 +3512,7 @@ FuncValueBounds compute_function_value_bounds(const vector &order, Interval result; - if (f.is_pure()) { + if (f.is_pure() && !f.is_inductive()) { // Make a scope that says the args could be anything. Scope arg_scope; diff --git a/src/BoundsInference.cpp b/src/BoundsInference.cpp index 3a0d3d2b76a1..0d31278ded71 100644 --- a/src/BoundsInference.cpp +++ b/src/BoundsInference.cpp @@ -7,6 +7,7 @@ #include "IREquality.h" #include "IRMutator.h" #include "IROperator.h" +#include "Inductive.h" #include "Inline.h" #include "Qualify.h" #include "Scope.h" @@ -384,6 +385,7 @@ class BoundsInference : public IRMutator { // don't care what sites are loaded, just what sites need // to have the correct value in them. So remap all selects // to if_then_elses to get tighter bounds. + // The implementation of expand_to_base_case relies on this conversion. class SelectToIfThenElse : public IRMutator { using IRMutator::visit; Expr visit(const Select *op) override { @@ -1013,6 +1015,26 @@ class BoundsInference : public IRMutator { } } + // For any inductively defined functions, make sure their + // bounds include the base case. + for (Stage &s : stages) { + bool eligible = s.func.is_pure() || s.func.updates().size() == 1; + if (!eligible || !s.func.is_inductive()) { + continue; + } + debug(4) << "Expanding bounds for inductively defined function " << s.func.name() << "\n"; + vector is_inductive_var; + is_inductive_var.reserve(s.func.args().size()); + for (const auto &arg : s.func.args()) { + is_inductive_var.push_back(s.func.is_inductive(arg)); + } + for (const auto &b1 : s.bounds) { + for (const auto &cval : s.exprs) { + s.bounds[b1.first] = expand_to_include_base_case(s.func.args(), is_inductive_var, cval.value, s.func.name(), s.bounds[b1.first], s.stage != 0); + } + } + } + // The region required of the each output is expanded to include the size of the output buffer. for (const Function &output : outputs) { Box output_box; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 114c53edfc84..aa89eb0832f6 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -137,6 +137,7 @@ target_sources( HexagonOffload.h HexagonOptimize.h ImageParam.h + Inductive.h InferArguments.h InjectHostDevBufferCopies.h Inline.h @@ -324,6 +325,7 @@ target_sources( HexagonOffload.cpp HexagonOptimize.cpp ImageParam.cpp + Inductive.cpp InferArguments.cpp InjectHostDevBufferCopies.cpp Inline.cpp diff --git a/src/Deserialization.cpp b/src/Deserialization.cpp index 3f4913740f41..c8253fb14f31 100644 --- a/src/Deserialization.cpp +++ b/src/Deserialization.cpp @@ -388,6 +388,8 @@ DimType Deserializer::deserialize_dim_type(Serialize::DimType dim_type) { return DimType::PureRVar; case Serialize::DimType::ImpureRVar: return DimType::ImpureRVar; + case Serialize::DimType::InductiveVar: + return DimType::InductiveVar; default: user_error << "unknown dim type " << (int)dim_type << "\n"; return DimType::PureVar; diff --git a/src/Func.cpp b/src/Func.cpp index 183c787dfa76..b4261a6a0a44 100644 --- a/src/Func.cpp +++ b/src/Func.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -77,10 +78,18 @@ Func::Func(const string &name) : func(unique_name(name)) { } +Func::Func(const Type &required_type, const string &name) + : func({required_type}, AnyDims, unique_name(name)) { +} + Func::Func(const Type &required_type, int required_dims, const string &name) : func({required_type}, required_dims, unique_name(name)) { } +Func::Func(const std::vector &required_types, const string &name) + : func(required_types, AnyDims, unique_name(name)) { +} + Func::Func(const std::vector &required_types, int required_dims, const string &name) : func(required_types, required_dims, unique_name(name)) { } @@ -516,7 +525,7 @@ void Stage::set_dim_type(const VarOrRVar &var, ForType t) { // If it's an rvar and the for type is parallel, we need to // validate that this doesn't introduce a race condition, // unless it is flagged explicitly or is a associative atomic operation. - if (!dim.is_pure() && var.is_rvar && is_parallel(t)) { + if (!dim.is_pure() && (var.is_rvar || dim.is_inductive()) && is_parallel(t)) { if (!definition.schedule().allow_race_conditions() && definition.schedule().atomic()) { if (!definition.schedule().override_atomic_associativity_test()) { @@ -1746,6 +1755,8 @@ Stage &Stage::fuse(const VarOrRVar &inner, const VarOrRVar &outer, const VarOrRV dims[inner_pos].dim_type = DimType::ImpureRVar; } else if (dims[inner_pos].dim_type == DimType::PureRVar || outer_type == DimType::PureRVar) { dims[inner_pos].dim_type = DimType::PureRVar; + } else if (dims[inner_pos].dim_type == DimType::InductiveVar || outer_type == DimType::InductiveVar) { + dims[inner_pos].dim_type = DimType::InductiveVar; } else { dims[inner_pos].dim_type = DimType::PureVar; } @@ -2237,6 +2248,35 @@ Stage &Stage::tile(const std::vector &previous, return tile(previous, previous, inners, factors, tail); } +namespace { +// Trace a dim name back through the splits list to the set of original +// dims it derives from. +std::set root_vars(const std::string &var, const std::vector &splits) { + std::set roots{var}; + for (auto it = splits.rbegin(); it != splits.rend(); ++it) { + switch (it->split_type) { + case Split::SplitVar: + if (roots.erase(it->outer) + roots.erase(it->inner)) { + roots.insert(it->old_var); + } + break; + case Split::FuseVars: + if (roots.erase(it->old_var)) { + roots.insert(it->outer); + roots.insert(it->inner); + } + break; + case Split::RenameVar: + if (roots.erase(it->outer)) { + roots.insert(it->old_var); + } + break; + } + } + return roots; +} +} // namespace + Stage &Stage::reorder(const std::vector &vars) { definition.schedule().touched() = true; const string &func_name = function.name(); @@ -2277,6 +2317,33 @@ Stage &Stage::reorder(const std::vector &vars) { if (!dims[idx[i]].is_pure()) { for (size_t j = i + 1; !safe_to_reorder && j < idx.size(); j++) { if (!dims[idx[j]].is_pure() && (idx[i] > idx[j])) { + if (dims[idx[i]].dim_type == DimType::InductiveVar && + dims[idx[j]].dim_type == DimType::InductiveVar) { + // Two inductive dims may swap if they derive from + // distinct original vars: every self-reference is + // non-increasing in each inductive var, so each + // recurrence chain sees its var increase under any + // nesting of the two. Loops deriving from a single + // inductive var must keep their order - swapping + // them makes the composed traversal of that var + // non-monotonic. + const vector &splits = definition.schedule().splits(); + std::set roots_i = root_vars(dims[idx[i]].var, splits); + std::set roots_j = root_vars(dims[idx[j]].var, splits); + bool disjoint = + std::none_of(roots_i.begin(), roots_i.end(), + [&](const string &r) { return roots_j.count(r); }); + if (disjoint) { + continue; + } + user_error + << "In schedule for " << name() + << ", can't reorder the loops " << vars[i].name() + << " and " << vars[j].name() + << " because they both derive from the same original " + << "inductive variable, whose loops must keep their " + << "nesting order.\n"; + } // Generate an error if the operator is not both associative and commutative. const auto &prover_result = prove_associativity(func_name, args, values); safe_to_reorder = prover_result.associative() && @@ -4664,8 +4731,11 @@ Stage FuncRef::operator/=(const FuncRef &e) { } FuncRef::operator Expr() const { - user_assert(func.has_pure_definition() || func.has_extern_definition()) - << "Can't call Func \"" << func.name() << "\" because it has not yet been defined.\n"; + user_assert(func.has_pure_definition() || func.has_extern_definition() || + !func.required_types().empty()) + << "Can't call Func \"" << func.name() << "\" because it has not yet been defined. " + << "A Func that refers to itself in its own definition must be declared " + << "with an explicit type.\n"; user_assert(func.outputs() == 1) << "Can't convert a reference Func \"" << func.name() @@ -4675,8 +4745,11 @@ FuncRef::operator Expr() const { } FuncTupleElementRef FuncRef::operator[](int i) const { - user_assert(func.has_pure_definition() || func.has_extern_definition()) - << "Can't call Func \"" << func.name() << "\" because it has not yet been defined.\n"; + user_assert(func.has_pure_definition() || func.has_extern_definition() || + !func.required_types().empty()) + << "Can't call Func \"" << func.name() << "\" because it has not yet been defined. " + << "A Func that refers to itself in its own definition must be declared " + << "with an explicit type.\n"; user_assert(func.outputs() != 1) << "Can't index into a reference to Func \"" << func.name() diff --git a/src/Func.h b/src/Func.h index def7e89fb1bd..c9a62cf6ce75 100644 --- a/src/Func.h +++ b/src/Func.h @@ -857,6 +857,10 @@ class Func { * that many dimensions. */ explicit Func(const Type &required_type, int required_dims, const std::string &name); + /** Declare a new undefined function with the given name. + * The function will be constrained to represent Exprs of required_type. */ + explicit Func(const Type &required_type, const std::string &name); + /** Declare a new undefined function with the given name. * If required_types is not empty, the function will be constrained to represent * Tuples of the same arity and types. (If required_types is empty, there is no constraint.) @@ -864,6 +868,11 @@ class Func { * that many dimensions. */ explicit Func(const std::vector &required_types, int required_dims, const std::string &name); + /** Declare a new undefined function with the given name. + * If required_types is not empty, the function will be constrained to represent + * Tuples of the same arity and types. (If required_types is empty, there is no constraint.) */ + explicit Func(const std::vector &required_types, const std::string &name); + /** Declare a new undefined function with an * automatically-generated unique name */ Func(); diff --git a/src/Function.cpp b/src/Function.cpp index 08968972fb67..5f2cb3f1214c 100644 --- a/src/Function.cpp +++ b/src/Function.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include "CSE.h" @@ -18,6 +19,10 @@ namespace Halide { namespace Internal { +namespace { +bool inductive_in(const std::vector &defs, const std::string &var, const std::string &fname); +} // namespace + using std::map; using std::pair; using std::string; @@ -234,9 +239,11 @@ struct CheckVars : public IRGraphVisitor { Scope<> defined_internally; const std::string name; bool unbound_reduction_vars_ok = false; + bool allow_inductive_self_reference = false; + bool pure; - CheckVars(const std::string &n) - : name(n) { + CheckVars(const std::string &n, bool pure) + : name(n), pure(pure) { } using IRVisitor::visit; @@ -249,15 +256,35 @@ struct CheckVars : public IRGraphVisitor { void visit(const Call *op) override { IRGraphVisitor::visit(op); - if (op->name == name && op->call_type == Call::Halide) { - for (size_t i = 0; i < op->args.size(); i++) { - const Variable *var = op->args[i].as(); - if (!pure_args[i].empty()) { - user_assert(var && var->name == pure_args[i]) - << "In definition of Func \"" << name << "\":\n" - << "All of a function's recursive references to itself" - << " must contain the same pure variables in the same" - << " places as on the left-hand-side.\n"; + bool proper_func = (name == op->name || op->call_type != Call::Halide); + if (op->call_type == Call::Halide && + op->func.defined() && + op->name != name) { + Function func = Function(op->func); + proper_func = (name == op->name || func.has_pure_definition() || func.has_extern_definition()); + } + if (pure) { + user_assert(proper_func) + << "In pure definition of Func \"" << name << "\":\n" + << "Can't call Func \"" << op->name + << "\" because it has not yet been defined," + << " and it is not a recursive call.\n"; + } else { + user_assert(proper_func) + << "In update definition of Func \"" << name << "\":\n" + << "Can't call Func \"" << op->name + << "\" because it has not yet been defined.\n"; + if (op->name == name && op->call_type == Call::Halide) { + for (size_t i = 0; i < op->args.size(); i++) { + const Variable *var = op->args[i].as(); + if (!pure_args[i].empty()) { + bool matches = var && var->name == pure_args[i]; + user_assert(matches || allow_inductive_self_reference) + << "In update definition of Func \"" << name << "\":\n" + << "All of a function's recursive references to itself" + << " in update definitions must contain the same pure" + << " variables in the same places as on the left-hand-side.\n"; + } } } } @@ -609,7 +636,7 @@ void Function::define(const vector &args, vector values) { // Make sure all the vars in the value are either args or are // attached to some parameter - CheckVars check(name()); + CheckVars check(name(), true); check.pure_args = args; for (const auto &value : values) { value.accept(&check); @@ -676,11 +703,27 @@ void Function::define(const vector &args, vector values) { init_def_args[i] = Var(args[i]); } + // If the function is inductive, + // the value and args might refer back to the + // function itself, introducing circular references and hence + // memory leaks. We need to break these cycles. + WeakenFunctionPtrs weakener(contents.get()); + for (auto &arg : init_def_args) { + arg = weakener(arg); + } + for (auto &value : values) { + value = weakener(value); + } + ReductionDomain rdom; contents->init_def = Definition(init_def_args, values, rdom, true); for (const auto &arg : args) { - Dim d = {arg, ForType::Serial, DeviceAPI::None, DimType::PureVar}; + DimType dtype = DimType::PureVar; + if (is_inductive(arg)) { + dtype = DimType::InductiveVar; + } + Dim d = {arg, ForType::Serial, DeviceAPI::None, dtype}; contents->init_def.schedule().dims().push_back(d); StorageDim sd = {arg}; contents->func_schedule.storage_dims().push_back(sd); @@ -753,6 +796,13 @@ void Function::define_update(const vector &_args, vector values, con << "because it has already been realized, used in the definition of " << "another Func, or been the target of a wrapper via in()/clone_in().\n"; + // Inductive functions cannot have updates on top of them + user_assert(!is_inductive()) + << "An update definition was added to Func " << name() << " after an inductive definition.\n"; + + // An update can be inductive only if it is the function's sole update + bool allow_inductive_self_reference = contents->updates.empty(); + for (auto &value : values) { user_assert(value.defined()) << "In update definition " << update_idx << " of Func \"" << name() << "\":\n" @@ -822,8 +872,9 @@ void Function::define_update(const vector &_args, vector values, con // pure args, in the reduction domain, or a parameter. Also checks // that recursive references to the function contain all the pure // vars in the LHS in the correct places. - CheckVars check(name()); + CheckVars check(name(), false); check.pure_args = pure_args; + check.allow_inductive_self_reference = allow_inductive_self_reference; for (const auto &arg : args) { arg.accept(&check); } @@ -913,6 +964,23 @@ void Function::define_update(const vector &_args, vector values, con Definition r(args, values, check.reduction_domain, false); internal_assert(!r.is_init()) << "Should have been an update definition\n"; + // The update's inductive pure variables. Their loops are serial by + // construction (they may be split but not parallelized), so two + // parallel iterations of an RVar see the same value of them: the race analysis + // below treats them as shared, which lets a read of an earlier step + // pass, as it should, since that step is complete. + std::set serial_vars; + { + std::vector defs = {definition()}; + defs.insert(defs.end(), updates().begin(), updates().end()); + defs.push_back(r); + for (const string &pure_arg : pure_args) { + if (!pure_arg.empty() && inductive_in(defs, pure_arg, name())) { + serial_vars.insert(pure_arg); + } + } + } + // First add any reduction domain if (check.reduction_domain.defined()) { for (const auto &rvar : check.reduction_domain.domain()) { @@ -922,7 +990,7 @@ void Function::define_update(const vector &_args, vector values, con // writing to. const string &v = rvar.var; - bool pure = can_parallelize_rvar(v, name(), r); + bool pure = can_parallelize_rvar(v, name(), r, serial_vars); Dim d = {v, ForType::Serial, DeviceAPI::None, pure ? DimType::PureRVar : DimType::ImpureRVar}; r.schedule().dims().push_back(d); @@ -1058,7 +1126,9 @@ int Function::dimensions() const { } int Function::outputs() const { - return (int)output_types().size(); + return (has_pure_definition() || has_extern_definition()) ? + (int)output_types().size() : + (int)required_types().size(); } const std::vector &Function::output_types() const { @@ -1129,8 +1199,122 @@ bool Function::has_pure_definition() const { return contents->init_def.defined(); } +bool Function::is_inductive() const { + if (!has_pure_definition()) { + return false; + } + + auto has_self_call = [&](const std::vector &values) { + bool found = false; + for (const Expr &e : values) { + visit_with(e, [&](auto *self, const Call *op) { + if (op->name == name() && op->call_type == Call::Halide) { + found = true; + } + self->visit_base(op); + }); + } + return found; + }; + + const std::vector &pure_args = args(); + auto has_shifted_self_call = [&](const std::vector &def_args, const std::vector &values) { + bool found = false; + for (const Expr &e : values) { + visit_with(e, [&](auto *self, const Call *op) { + if (op->name == name() && op->call_type == Call::Halide) { + for (size_t i = 0; i < op->args.size() && i < def_args.size() && i < pure_args.size(); i++) { + const Variable *lhs_var = def_args[i].as(); + if (lhs_var && !lhs_var->reduction_domain.defined() && lhs_var->name == pure_args[i]) { + const Variable *call_var = op->args[i].as(); + bool matches = call_var && call_var->name == lhs_var->name; + if (!matches) { + found = true; + } + } + } + } + self->visit_base(op); + }); + } + return found; + }; + + bool recursive = has_self_call(definition().values()); + for (const Definition &update : updates()) { + if (recursive) { + break; + } + recursive = has_shifted_self_call(update.args(), update.values()); + } + + return recursive; +} + +namespace { + +// Whether var, a pure variable of the Func named fname, is inductive +// across the given definitions: some definition writes at var and reads +// the Func at some other position along it. +bool inductive_in(const std::vector &defs, const string &var, const string &fname) { + // Only pure vars can be inductive + for (const Definition &def : defs) { + for (const ReductionVariable &rv : def.schedule().rvars()) { + if (rv.var == var) { + return false; + } + } + } + + bool inductive_in_var = false; + for (const Definition &def : defs) { + std::vector positions; + for (size_t i = 0; i < def.args().size(); i++) { + if (const auto &v = def.args()[i].as()) { + if (v->name == var) { + positions.push_back((int)i); + } + } + } + if (positions.empty()) { + continue; + } + + for (const Expr &e : def.values()) { + visit_with(e, [&](auto *self, const Call *op) { + if (op->call_type == Call::Halide && op->name == fname) { + for (int pos : positions) { + if (const auto &v = op->args[pos].as()) { + if (v->name != var) { + inductive_in_var = true; + } + } else { + inductive_in_var = true; + } + } + } + self->visit_base(op); + }); + } + } + + return inductive_in_var; +} + +} // namespace + +bool Function::is_inductive(const string &var) const { + if (!has_pure_definition()) { + return false; + } + + std::vector defs = {definition()}; + defs.insert(defs.end(), updates().begin(), updates().end()); + return inductive_in(defs, var, name()); +} + bool Function::can_be_inlined() const { - return is_pure() && definition().specializations().empty(); + return is_pure() && definition().specializations().empty() && !is_inductive(); } bool Function::has_update_definition() const { diff --git a/src/Function.h b/src/Function.h index 2a8dcbcca556..faf1d5cba908 100644 --- a/src/Function.h +++ b/src/Function.h @@ -197,6 +197,12 @@ class Function { !has_extern_definition()); } + /** Does this function have an inductive pure definition? */ + bool is_inductive() const; + + /** Is this function inductive in the given variable? */ + bool is_inductive(const std::string &var) const; + /** Is it legal to inline this function? */ bool can_be_inlined() const; diff --git a/src/IR.cpp b/src/IR.cpp index 3a91b4610cd9..2faf25684f9a 100644 --- a/src/IR.cpp +++ b/src/IR.cpp @@ -835,11 +835,13 @@ Expr Call::make(const Function &func, const std::vector &args, int idx, internal_assert(idx >= 0 && idx < func.outputs()) << "Value index out of range in call to halide function\n"; - internal_assert(func.has_pure_definition() || func.has_extern_definition()) + const bool defined = func.has_pure_definition() || func.has_extern_definition(); + internal_assert(defined || !func.required_types().empty()) << "Call to undefined halide function\n"; FunctionPtr fp = func.get_contents(); fp.follow_global_wrappers = follow_global_wrappers; - return make(func.output_types()[(size_t)idx], func.name(), args, Halide, + const Type &t = defined ? func.output_types()[(size_t)idx] : func.required_types()[(size_t)idx]; + return make(t, func.name(), args, Halide, fp, idx, Buffer<>(), Parameter()); } diff --git a/src/IRPrinter.cpp b/src/IRPrinter.cpp index 939b18d8494b..6018fb0d2025 100644 --- a/src/IRPrinter.cpp +++ b/src/IRPrinter.cpp @@ -471,6 +471,9 @@ std::ostream &operator<<(std::ostream &out, const DimType &t) { case DimType::PureRVar: out << "PureRVar"; break; + case DimType::InductiveVar: + out << "InductiveVar"; + break; case DimType::ImpureRVar: out << "ImpureRVar"; break; diff --git a/src/Inductive.cpp b/src/Inductive.cpp new file mode 100644 index 000000000000..e558f81db5aa --- /dev/null +++ b/src/Inductive.cpp @@ -0,0 +1,207 @@ +#include "Inductive.h" + +#include "Bounds.h" +#include "Error.h" +#include "ExprUsesVar.h" +#include "Function.h" +#include "IR.h" +#include "IREquality.h" +#include "IROperator.h" +#include "IRVisitor.h" +#include "Simplify.h" +#include "Substitute.h" + +namespace Halide { +namespace Internal { + +using std::string; +using std::vector; + +namespace { + +class BaseCaseSolver : public IRVisitor { + using IRVisitor::visit; + const vector &vars; + const string &func; + + const vector &start_box; + const vector &is_inductive_var; + const bool is_update; + + vector condition_intervals; + + Scope bounds; + + Scope<> inductive_vars; + + int nested_select = 0; + + void visit(const Call *op) override { + if (op->is_intrinsic(Call::if_then_else)) { + + // A select whose condition doesn't depend on any inductive var + // can be traversed normally. So can one whose condition reads + // the function itself: that is a data-dependent step of the + // recurrence, not a base-case guard, and both of its branches + // may recurse (each self-reference in them is still checked). + bool cond_is_inductive = expr_uses_vars(op->args[0], inductive_vars); + bool cond_recurses = false; + visit_with(op->args[0], [&](auto *self, const Call *inner_op) { + if (inner_op->name == func) { + cond_recurses = true; + } + self->visit_base(inner_op); + }); + if (!cond_is_inductive || cond_recurses) { + IRVisitor::visit(op); + return; + } + + // Theoretically there is no need to check op->args[0]. + // Select nodes are only converted to if_then_else when the condition is pure, + // which means the condition cannot have any recursive calls. + op->args[0].accept(this); + + bool left_recurse = false, right_recurse = false; + visit_with(op->args[1], [&](auto *self, const Call *inner_op) { + if (inner_op->name == func) { + left_recurse = true; + } + self->visit_base(inner_op); + }); + visit_with(op->args[2], [&](auto *self, const Call *inner_op) { + if (inner_op->name == func) { + right_recurse = true; + } + self->visit_base(inner_op); + }); + // Again, this check is theoretically unnecessary + user_assert(!(left_recurse && right_recurse)) << "Select node in inductive function " << func << " does not have a base case"; + + nested_select += 1; + vector old_intervals = condition_intervals; + if (left_recurse) { + for (size_t i = 0; i < vars.size(); i++) { + Interval inter = Interval::make_intersection(old_intervals[i], solve_for_outer_interval(simplify(op->args[0]), vars[i])); + condition_intervals[i] = Interval(inter.min, Interval::pos_inf()); + bounds.push(vars[i], condition_intervals[i]); + } + op->args[1].accept(this); + for (const auto &var : vars) { + bounds.pop(var); + } + } + if (right_recurse) { + for (size_t i = 0; i < vars.size(); i++) { + Interval inter = Interval::make_intersection(old_intervals[i], solve_for_outer_interval(simplify(!op->args[0]), vars[i])); + condition_intervals[i] = Interval(inter.min, Interval::pos_inf()); + bounds.push(vars[i], condition_intervals[i]); + } + op->args[2].accept(this); + for (const auto &var : vars) { + bounds.pop(var); + } + } + condition_intervals = old_intervals; + nested_select -= 1; + } else if (op->name == func) { + // An update definition's self-reference whose inductive args match the + // pure vars exactly is acceptable. + if (is_update) { + bool exact_pure_self_reference = true; + for (size_t position = 0; position < vars.size() && exact_pure_self_reference; position++) { + if (is_inductive_var[position] && + (position >= op->args.size() || !equal(op->args[position], Variable::make(op->args[position].type(), vars[position])))) { + exact_pure_self_reference = false; + } + } + if (exact_pure_self_reference) { + IRVisitor::visit(op); + return; + } + } + + user_assert(nested_select > 0) << "Function " << func << " contains an inductive function reference outside of a select operation value.\n"; + user_assert(nested_select == 1) << "Function " << func << " contains an inductive function reference inside a nested select operation.\n"; + bool found_inductive = false; + for (size_t position = 0; position < vars.size(); position++) { + const Expr inductive_expr = op->args[position]; + if (!is_inductive_var[position]) { + continue; + } + const Expr new_v = Variable::make(inductive_expr.type(), vars[position]); + const Expr gets_lower = simplify(new_v - inductive_expr > 0, bounds); + const Interval i_lower = solve_for_inner_interval(gets_lower, vars[position]); + + Interval new_interval; + if (equal(new_v, inductive_expr)) { + new_interval = start_box[position]; + } else if (i_lower.is_everything()) { + found_inductive = true; + new_interval = Interval(Interval::neg_inf(), start_box[position].max); + } else { + std::ostringstream err; + err << "Inductive variable " << vars[position] << " in inductive function " << func << " is not provably monotonically decreasing outside of the base case."; + user_error << err.str() << "\n"; + } + new_interval = Interval::make_intersection(new_interval, condition_intervals[position]); + Scope i_scope; + i_scope.push(vars[position], new_interval); + result_intervals[position] = Interval::make_union(result_intervals[position], Interval::make_union(new_interval, bounds_of_expr_in_scope(inductive_expr, i_scope))); + } + user_assert(found_inductive) << "Unable to prove in inductive function " << func << " that the inductive step is monotonically decreasing.\n"; + + IRVisitor::visit(op); + + } else { + IRVisitor::visit(op); + } + } + +public: + vector result_intervals; + + BaseCaseSolver(const vector &v, const vector &is_inductive_var, const string &func, const vector &con, bool is_update) + : vars(v), func(func), start_box(con), is_inductive_var(is_inductive_var), is_update(is_update) { + condition_intervals = vector(start_box.size()); + result_intervals = vector(start_box.size(), Interval::nothing()); + for (size_t i = 0; i < vars.size(); i++) { + if (is_inductive_var[i]) { + inductive_vars.push(vars[i]); + } + } + } +}; + +} // anonymous namespace + +Box expand_to_include_base_case(const vector &vars, const vector &is_inductive_var, + const Expr &RHS, const string &func, const Box &box_required, + bool is_update) { + Expr substed = substitute_in_all_lets(RHS); + Box box2 = box_required; + BaseCaseSolver b(vars, is_inductive_var, func, box_required.bounds, is_update); + substed.accept(&b); + + Scope non_inductive_scope; + for (size_t i = 0; i < vars.size(); i++) { + if (!is_inductive_var[i]) { + non_inductive_scope.push(vars[i], box_required[i]); + } + } + + for (size_t i = 0; i < vars.size(); i++) { + user_assert(b.result_intervals[i].is_bounded() || b.result_intervals[i].is_empty()) << "Unable to prove that the inductive function " << func << " uses a bounded interval"; + if (!b.result_intervals[i].is_empty()) { + Interval new_interval(min(b.result_intervals[i].min, box_required[i].min), box_required[i].max); + + new_interval.min = bounds_of_expr_in_scope(new_interval.min, non_inductive_scope).min; + box2[i] = new_interval; + } + } + + return box2; +} + +} // namespace Internal +} // namespace Halide diff --git a/src/Inductive.h b/src/Inductive.h new file mode 100644 index 000000000000..73afdf257550 --- /dev/null +++ b/src/Inductive.h @@ -0,0 +1,62 @@ +#ifndef INDUCTIVE_H +#define INDUCTIVE_H + +/** \file + * + * Utilities for processing inductively defined functions. + * + * A simple example of an inductively defined function is + * f(x) = select(x <= 0, input(0), input(x) + f(x - 1)); + * The purpose of inductive functions is to allow execution patterns that are + * impossible with reduction domains. For example, in the following code: + * + * f(x) = select(x <= 0, input(0), input(x) + f(x - 1)); + * g(x) = f(x) / 4; + * f.compute_at(g, x).store_root(); + * + * The resulting program computes a single value of f(x) at each value of g(x), + * thanks to Halide's sliding window optimization. As a result of storage folding, + * only the two most recent values of f(x) are stored at any given time. This is + * impossible if f(x) is defined using a reduction domain, since every value of f(x) + * must be computed and stored before g(x) is computed. + * + * If Halide is unable to perform the sliding window optimization, computing the + * inductive function is generally inefficient. + * + * In inductive functions, any recursive references must be inside a select statement, + * and cannot be inside nested select statements. The inductive arguments in the + * recursive reference must be monotonically decreasing. Currently, only single-valued + * functions are supported. Inductive functions cannot be inlined. + * + * An inductive function is usually expressed as a single pure definition (as in the + * examples above), but this is not required. It is also possible to define an inductive + * function with a non-inductive pure definition plus exactly one update definition, where + * the update definition is the inductive one. In that case, all RVars appearing in the + * update definition must be nested inside all of the inductive variables. + * + * An inductive function must be declared with an explicit type, because its + * definition refers to it before it is defined: + * Func f = Func(Int(32), "f"); + */ + +#include "Bounds.h" +#include "Expr.h" +#include "Interval.h" +#include "Scope.h" +#include "Solve.h" + +namespace Halide { +namespace Internal { + +/** Given an initial box for an inductively defined function, + returns an expanded box that includes the function's non-inductive base case. + is_inductive_var[i] should be true iff vars[i] is a dimension in which the + function actually recurses. */ +Box expand_to_include_base_case(const std::vector &vars, const std::vector &is_inductive_var, + const Expr &RHS, const std::string &func, const Box &box_required, + bool is_update = false); + +} // namespace Internal +} // namespace Halide + +#endif diff --git a/src/ParallelRVar.cpp b/src/ParallelRVar.cpp index 538cd144f449..826201dcc6bd 100644 --- a/src/ParallelRVar.cpp +++ b/src/ParallelRVar.cpp @@ -1,4 +1,5 @@ #include "ParallelRVar.h" + #include "CSE.h" #include "Debug.h" #include "Definition.h" @@ -9,6 +10,7 @@ #include "IRVisitor.h" #include "Simplify.h" #include "Substitute.h" +#include namespace Halide { namespace Internal { @@ -54,9 +56,11 @@ class RenameFreeVars : public IRMutator { using IRMutator::visit; map new_names; + // Variables the other thread shares with this one. + const std::set &serial_vars; Expr visit(const Variable *op) override { - if (!op->param.defined() && !op->image.defined()) { + if (!op->param.defined() && !op->image.defined() && !serial_vars.count(op->name)) { return Variable::make(op->type, get_new_name(op->name)); } else { return op; @@ -64,6 +68,10 @@ class RenameFreeVars : public IRMutator { } public: + explicit RenameFreeVars(const std::set &serial_vars) + : serial_vars(serial_vars) { + } + string get_new_name(const string &s) { map::iterator iter = new_names.find(s); if (iter != new_names.end()) { @@ -92,7 +100,8 @@ class SubstituteInBooleanLets : public IRMutator { bool can_parallelize_rvar(const string &v, const string &f, - const Definition &r) { + const Definition &r, + const std::set &serial_vars) { const vector &values = r.values(); const vector &args = r.args(); const vector &rvars = r.schedule().rvars(); @@ -109,7 +118,7 @@ bool can_parallelize_rvar(const string &v, } // Make an expr representing the store done by a different thread. - RenameFreeVars renamer; + RenameFreeVars renamer(serial_vars); auto other_store = renamer(args); // Construct an expression which is true when the two threads are diff --git a/src/ParallelRVar.h b/src/ParallelRVar.h index b06b3636b3e4..f010cc7e8540 100644 --- a/src/ParallelRVar.h +++ b/src/ParallelRVar.h @@ -7,6 +7,7 @@ * definition across a reduction variable. */ +#include #include namespace Halide { @@ -17,11 +18,15 @@ class Definition; /** Returns whether or not Halide can prove that it is safe to * parallelize an update definition across a specific variable. If * this returns true, it's definitely safe. If this returns false, it - * may still be safe, but Halide couldn't prove it. + * may still be safe, but Halide couldn't prove it. serial_vars names + * the definition's variables whose loops can never run two iterations + * at once, such as the Func's inductive Vars, so two parallel + * iterations of rvar see the same value of them. */ bool can_parallelize_rvar(const std::string &rvar, const std::string &func, - const Definition &r); + const Definition &r, + const std::set &serial_vars = {}); } // namespace Internal } // namespace Halide diff --git a/src/Schedule.h b/src/Schedule.h index c87073bf9ae9..85d9e2a3203f 100644 --- a/src/Schedule.h +++ b/src/Schedule.h @@ -362,6 +362,11 @@ enum class DimType { * definitions you can even redundantly re-evaluate points. */ PureVar = 0, + /** The dim originated from a Var in an inductively defined pure + * definition. InductiveVars cannot be reordered, parallelized, + * or vectorized. */ + InductiveVar, + /** The dim originated from an RVar. You can evaluate a Func at * distinct values of this RVar in any order (including in * parallel) over exactly the interval specified in the @@ -472,6 +477,10 @@ struct Dim { return (dim_type == DimType::PureRVar) || (dim_type == DimType::ImpureRVar); } + bool is_inductive() const { + return dim_type == DimType::InductiveVar; + } + /** Could multiple iterations of this loop happen at the same * time, with reads and writes interleaved in arbitrary ways * according to the memory model of the underlying compiler and diff --git a/src/ScheduleFunctions.cpp b/src/ScheduleFunctions.cpp index 43eb4f2f4977..3bbc9f315c7a 100644 --- a/src/ScheduleFunctions.cpp +++ b/src/ScheduleFunctions.cpp @@ -1468,7 +1468,7 @@ class InjectFunctionRealization : public IRMutator { // none of the functions in a fused group can be inlined, so this will only // happen when we're lowering a single func. if (provide_name != funcs[0].name() && - !funcs[0].is_pure() && + (!funcs[0].is_pure() || funcs[0].is_inductive()) && funcs[0].schedule().compute_level().is_inlined() && function_is_used_in_stmt(funcs[0], provide_op)) { @@ -2406,6 +2406,41 @@ bool validate_schedule(Function f, const Stmt &s, const Target &target, bool is_ } } + if (f.is_inductive()) { + // Check that any RDom used in an inductive Func's update + // has its loop nested inside every inductive dimension. + for (const Definition &upd : f.updates()) { + const vector &dims = upd.schedule().dims(); + int innermost_rvar_pos = -1; + for (size_t i = 0; i < dims.size(); i++) { + if (dims[i].is_rvar()) { + innermost_rvar_pos = std::max(innermost_rvar_pos, (int)i); + } + } + if (innermost_rvar_pos == -1) { + continue; + } + for (size_t i = 0; i < upd.args().size() && i < f.args().size(); i++) { + if (!f.is_inductive(f.args()[i])) { + continue; + } + const Variable *v = upd.args()[i].as(); + if (!v) { + continue; + } + for (size_t d = 0; d < dims.size(); d++) { + if (dims[d].var == v->name) { + user_assert(innermost_rvar_pos < (int)d) + << "In the update definition of inductive Func " << f.name() + << ", all RVar iterations must be nested inside all inductive " + << "variable loops, but inductive variable " << v->name + << " is nested inside an RVar's loop.\n"; + } + } + } + } + } + // Emit a warning if only some of the steps have been scheduled. bool any_scheduled = f.has_pure_definition() && f.definition().schedule().touched(); for (const Definition &r : f.updates()) { @@ -2573,7 +2608,7 @@ bool validate_schedule(Function f, const Stmt &s, const Target &target, bool is_ // will get lowered into compute_at innermost and thus can be treated // similarly as a non-inlined Func. if (store_at.is_inlined() && compute_at.is_inlined() && hoist_storage_at.is_inlined()) { - if (f.is_pure()) { + if (f.is_pure() && !f.is_inductive()) { validate_schedule_inlined_function(f); } return true; @@ -2900,6 +2935,9 @@ Stmt schedule_functions(const vector &outputs, const map &env, const Target &target, bool &any_memoized) { + for (const Function &o : outputs) { + user_assert(!o.is_inductive()) << "Function " << o.name() << " is an inductively defined output buffer, which is unsupported.\n"; + } string root_var = LoopLevel::root().lock().to_string(); Stmt s = For::make(root_var, 0, 0, ForType::Serial, Partition::Never, DeviceAPI::Host, Evaluate::make(0)); diff --git a/src/Serialization.cpp b/src/Serialization.cpp index b7c0e8522262..89207c51473e 100644 --- a/src/Serialization.cpp +++ b/src/Serialization.cpp @@ -354,6 +354,8 @@ Serialize::DimType Serializer::serialize_dim_type(const DimType &dim_type) { return Serialize::DimType::PureRVar; case DimType::ImpureRVar: return Serialize::DimType::ImpureRVar; + case DimType::InductiveVar: + return Serialize::DimType::InductiveVar; default: user_error << "Unsupported dim type\n"; return Serialize::DimType::PureVar; diff --git a/src/halide_ir.fbs b/src/halide_ir.fbs index a453b7a170d5..38f4affa5a2e 100644 --- a/src/halide_ir.fbs +++ b/src/halide_ir.fbs @@ -594,6 +594,7 @@ enum DimType: ubyte { PureVar, PureRVar, ImpureRVar, + InductiveVar, } table Dim { diff --git a/test/correctness/CMakeLists.txt b/test/correctness/CMakeLists.txt index b35f2e437078..ca7f6436ccd6 100644 --- a/test/correctness/CMakeLists.txt +++ b/test/correctness/CMakeLists.txt @@ -213,6 +213,7 @@ tests( float16_t_image_type.cpp float16_t_neon_op_check.cpp float_arg.cpp + fold_inductive_keeps_step.cpp fold_storage_not_applied.cpp for_each_element.cpp force_onto_stack.cpp @@ -319,6 +320,12 @@ tests( in_place.cpp incomplete_target.cpp indexing_access_undef.cpp + inductive.cpp + inductive_base_case_bounds.cpp + inductive_errors.cpp + inductive_folding.cpp + inductive_ring_buffer.cpp + inductive_var_race.cpp infer_arguments.cpp init_def_should_be_all_vars.cpp inline_reduction.cpp diff --git a/test/correctness/fold_inductive_keeps_step.cpp b/test/correctness/fold_inductive_keeps_step.cpp new file mode 100644 index 000000000000..eb130ef13419 --- /dev/null +++ b/test/correctness/fold_inductive_keeps_step.cpp @@ -0,0 +1,125 @@ +// A Func defined in terms of its own previous value reads that value while +// computing the next one, and never again, so one slot would do if every +// point were computed exactly once. A redundant split or a ShiftInwards tail +// computes points twice, and then the point's own store would overwrite the +// step it reads. Nothing checks for that, so the window always keeps the +// step: two slots for a reach of one, whether the coordinate the producer +// writes is plain or tiled (a tiled coordinate, yo*4 + yi, is what a real +// schedule looks like, and is where the arithmetic tends to go wrong). +// +// The values come out right either way - only the size of the allocation is at +// stake - so this asserts on the allocation rather than on the answer. + +#include "Halide.h" +#include + +using namespace Halide; +using namespace Halide::Internal; + +namespace { + +// Records the extent of the allocation for one Func. +class RecordAllocationExtent : public IRMutator { + using IRMutator::visit; + Stmt visit(const Allocate *op) override { + if (op->name == func) { + int64_t e = 1; + for (const Expr &s : op->extents) { + if (auto c = as_const_int(s)) { + e *= *c; + } else { + e = -1; + break; + } + } + *extent = e; + } + return IRMutator::visit(op); + } + +public: + std::string func; + int64_t *extent; + RecordAllocationExtent(std::string f, int64_t *e) + : func(std::move(f)), extent(e) { + } +}; + +// The width of one value of the slid dimension, so the extent can be read as a +// number of slots. +const int W = 8, N = 16; + +// consume_previous chooses whether the consumer also asks for the older value. +int64_t allocation_slots(bool tiled) { + Var y("y"), t("t"), yo("yo"), yi("yi"), to("to"), ti("ti"); + Func step("step"); + step(y, t) = cast(y + t); + + std::string mname = tiled ? "m_tiled" : "m_plain"; + Func m = Func(Float(32), mname); + m(y, t) = select(t <= 0, + step(y, t), + likely(m(y, t - 1) + step(y, t))); + + Func out("out"); + out(y, t) = m(y, t); + + out.bound(y, 0, W).bound(t, 0, N); + // Split the consumer's loop by one, so that the loop the producer is + // computed in runs once and there is nothing for the loop-based sliding to + // do with it. + out.split(t, to, ti, 1); + m.compute_at(out, ti).store_root().slide(out, t); + if (tiled) { + // The coordinate the producer writes becomes yo*4 + yi. + m.split(y, yo, yi, 4); + } + + int64_t extent = -1; + out.add_custom_lowering_pass(new RecordAllocationExtent(mname, &extent)); + out.compile_jit(get_host_target()); + + // The answers have to be right whatever the allocation is. + Buffer result = out.realize({W, N}); + for (int t = 0; t < N; t++) { + for (int y = 0; y < W; y++) { + float want = 0; + for (int i = 0; i <= t; i++) { + want += (float)(y + i); + } + if (result(y, t) != want) { + printf("out(%d, %d) = %f instead of %f\n", y, t, result(y, t), want); + return -2; + } + } + } + return extent < 0 ? extent : extent / W; +} + +} // namespace + +int main(int argc, char **argv) { + int64_t plain = allocation_slots(false); + int64_t tiled = allocation_slots(true); + printf("slots when the producer writes a plain coordinate: %d\n", (int)plain); + printf("slots when it writes a tiled one: %d\n", (int)tiled); + + int failures = 0; + if (plain != 2) { + printf("FAIL: the window should keep the step the recurrence reads, two " + "slots, but %d were allocated\n", + (int)plain); + failures++; + } + if (tiled != 2) { + printf("FAIL: tiling the coordinate the producer writes should not change " + "the window, two slots, but %d were allocated\n", + (int)tiled); + failures++; + } + if (failures) { + return 1; + } + printf("Success!\n"); + return 0; +} diff --git a/test/correctness/inductive.cpp b/test/correctness/inductive.cpp new file mode 100644 index 000000000000..36daf7ffc520 --- /dev/null +++ b/test/correctness/inductive.cpp @@ -0,0 +1,430 @@ +#include "Halide.h" +#include "check_call_graphs.h" +#include "test_sharding.h" + +#include +#include +#include +#include +#include + +namespace { + +using std::map; +using std::string; + +using namespace Halide; +using namespace Halide::Internal; + +int simple_inductive_test() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + + g(x, y) = select(x <= 0, 0, likely(g(max(0, x - 1), y) + x + y)); + + h(x, y) = g(x + 5, y) / 4; + + g.compute_at(h, x).store_at(h, y); + + h.bound(x, 0, 600).bound(y, 0, 5); + + Buffer im = h.realize({600, 5}); + auto func = [](int x, int y) { + return (y * (x + 5) + (x + 5) * (x + 6) / 2) / 4; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int reorder_test() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + + Var xi("xi"), xii("xii"), xo("xo"); + + g(x, y) = select(x <= 0, 0, g(max(0, x - 1), y) + x + y); + + h(x, y) = g(x + 5, y) / 4; + h.split(x, xo, xi, 24).reorder(xi, y, xo); + + g.compute_at(h, xo).store_root(); + + g.split(x, xi, xii, 5).reorder(xii, y, xi).vectorize(y, 8); + + Buffer im = h.realize({80, 80}); + auto func = [](int x, int y) { + return (y * (x + 5) + (x + 5) * (x + 6) / 2) / 4; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int summed_area_table() { + Func f("f"), g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + f(x, y) = x + y; + g(x, y) = f(x, y) + select(x <= 0, 0, g(x - 1, y)) + select(y <= 0, 0, g(x, y - 1)) - select(x <= 0 || y <= 0, 0, g(x - 1, y - 1)); + h(x, y) = g(x, y) / 8; + g.compute_at(h, x).store_root(); + + Buffer im = h.realize({80, 80}); + auto func = [](int x, int y) { + return (x * (x + 1) / 2 * (y + 1) + y * (y + 1) / 2 * (x + 1)) / 8; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int large_baseline() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + + g(x, y) = select(x <= 8, (y * x + x * (x + 1) / 2) - 1, g(x - 1, y) + x + y); + h(x, y) = g(x + 5, y) / 4; + + g.compute_at(h, x).store_at(h, y); + + Buffer im = h.realize({80, 80}); + auto func = [](int x, int y) { + return (y * (x + 5) + (x + 5) * (x + 6) / 2 - 1) / 4; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int fibonacci() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + + g(x, y) = select(x <= 1, 1, g(x - 1, y) + g(x - 2, y)); + h(x, y) = g(x, y); + + h.bound(x, 0, 80); + Buffer im = h.realize({80, 80}); + auto func = [](int x, int y) { + int a = 1; + int b = 1; + for (int i = 2; i <= x; i++) { + int c = a + b; + b = a; + a = c; + } + return a; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int sum_2d_test() { + Func f(Int(32), "f"), g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + f(x, y) = select(x <= 0, 0, x + f(x - 1, y)); + g(x, y) = select(y <= 0, f(x, 0), f(x, y) + g(x, y - 1)); + h(x, y) = g(x, y); + h.bound(x, 0, 80).bound(y, 0, 80).vectorize(x, 8); + g.compute_at(h, x).store_root().vectorize(x, 8); + f.compute_at(h, x).store_root(); + Buffer im = h.realize({80, 80}); + auto func = [](int x, int y) { + int result = 0; + for (int a = 0; a <= x; a++) { + for (int b = 0; b <= y; b++) { + result += a; + } + } + return result; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int sum_1d_test() { + Func f("f"), g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + f(x, y) = x + y; + f(x, y) += x; + g(x, y) = select(y <= 0, f(x, 0), f(x, y) + g(x, y - 1)); + h(x, y) = g(x, y); + h.bound(x, 0, 80).bound(y, 0, 80); + f.compute_at(h, x); + Buffer im = h.realize({80, 80}); + auto func = [](int x, int y) { + int result = 0; + for (int a = 0; a <= y; a++) { + result += 2 * x + a; + } + return result; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int multi_baseline_test() { + Func f("f"), g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + f(x, y) = x + y; + f(x, y) += x; + g(x, y) = select(y <= 0, f(x, 0), f(x, y) + g(x, y - 1)) + select(y <= 3, f(x, 0), f(x, y) + g(x, y - 1)); + h(x, y) = g(x, y); + h.bound(x, 0, 80).bound(y, 0, 20); + f.compute_at(h, x); + Buffer im = h.realize({80, 20}); + auto func = [](int x, int y) { + std::vector result; + + for (int a = 0; a <= y; a++) { + if (a <= 0) { + result.emplace_back(4 * x); + } else if (a <= 3) { + result.emplace_back(2 * x + (2 * x + a) + result[a - 1]); + } else { + result.emplace_back(2 * x + a + result[a - 1] + (2 * x + a) + result[a - 1]); + } + } + return result[y]; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int type_declare_test() { + Func g = Func(Int(32), "g"); + Func h("h"); + Var x("x"), y("y"); + + g(x, y) = select(x <= 0, 0, 1 + g(max(0, x - 1), y) + x + 2); + + h(x, y) = g(x + 5, y) / 4; + + g.compute_at(h, x).store_at(h, y); + + Buffer im = h.realize({600, 5}); + auto func = [](int x, int y) { + return (3 * (x + 5) + (x + 5) * (x + 6) / 2) / 4; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int inductive_update_rdom_test() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + + const int Y = 10; + RDom r(0, Y, 0, Y, "r"); + + g(x, y) = Expr(std::numeric_limits::min()); + g(x, r.x) = select(x <= 0, r.x, likely(max(g(x, r.x), g(x - 1, r.y) + x + r.y))); + + h(x, y) = g(x, y); + + h.bound(x, 0, 20).bound(y, 0, Y); + g.compute_at(h, x).store_root(); + + Buffer im = h.realize({20, Y}); + + std::vector> rows(20, std::vector(Y)); + for (int yy = 0; yy < Y; yy++) { + rows[0][yy] = yy; + } + for (int xx = 1; xx < 20; xx++) { + int best = rows[xx - 1][0] + xx + 0; + for (int ry = 1; ry < Y; ry++) { + best = std::max(best, rows[xx - 1][ry] + xx + ry); + } + for (int yy = 0; yy < Y; yy++) { + rows[xx][yy] = best; + } + } + auto func = [&](int x, int y) { + return rows[x][y]; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int tuple_test() { + Func g = Func(std::vector{Int(32), Int(32)}, "g"); + Func h("h"); + Var x("x"), y("y"); + + g(x, y) = Tuple(select(x <= 0, 0, g(max(0, x - 1), y)[0] + x + y), x - y); + h(x, y) = g(10, y)[0] / 4 + g(10, y)[1] + x; + + g.compute_root(); + + Buffer im = h.realize({10, 10}); + auto func = [](int x, int y) { + return (y * (5 + 5) + (5 + 5) * (5 + 6) / 2) / 4 + 10 - y + x; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int tuple_test_2() { + Func g = Func(std::vector{Int(32), Int(32)}, "g"); + Func h("h"); + Var x("x"), y("y"); + + g(x, y) = Tuple(select(x <= 0, 0, g(max(0, x - 1), y)[0] + x + y), select(y <= 0, 0, g(x, max(0, y - 1))[1] + x + y)); + h(x, y) = g(x, y)[0] + g(x, y)[1]; + + g.compute_root(); + + Buffer im = h.realize({10, 10}); + auto func = [](int x, int y) { + return y * x + x * (x + 1) / 2 + x * y + y * (y + 1) / 2; + }; + if (check_image(im, func)) { + return 1; + } + return 0; +} + +int distinct_inductive_reorder_test() { + // A Func inductive in two vars: every self-reference is non-increasing + // in each inductive var, so each recurrence chain sees its var increase + // under any nesting of the two inductive loops. Reordering loops that + // derive from DISTINCT original inductive vars is therefore legal; + // only loops deriving from the same one must keep their order. + auto make = [](Func &f, Var x, Var y) { + f(x, y) = select(x <= 0 || y <= 0, cast(x + y), + likely(f(x - 1, y) + f(x, y - 1))); + }; + auto reference = [](Buffer &im) { + for (int y = 0; y < im.height(); y++) { + for (int x = 0; x < im.width(); x++) { + uint32_t correct = (x == 0 || y == 0) ? (uint32_t)(x + y) : im(x - 1, y) + im(x, y - 1); + if (im(x, y) != correct) { + printf("im(%d, %d) = %u instead of %u\n", x, y, im(x, y), correct); + return 1; + } + } + } + return 0; + }; + + { + // Swap the two inductive dims outright. + Func f(UInt(32), 2, "f"), g("g"); + Var x("x"), y("y"); + make(f, x, y); + g(x, y) = f(x, y); + f.compute_root().reorder(y, x); + Buffer im = g.realize({16, 16}); + if (reference(im)) { + return 1; + } + } + + { + // Split both and interleave the pieces across the two vars. Pieces + // of the same var keep their relative order; pieces of distinct + // vars swap freely. + Func f(UInt(32), 2, "f"), g("g"); + Var x("x"), y("y"), xo("xo"), xi("xi"), yo("yo"), yi("yi"); + make(f, x, y); + g(x, y) = f(x, y); + f.compute_root().split(x, xo, xi, 4).split(y, yo, yi, 4).reorder(xi, yi, xo, yo); + Buffer im = g.realize({16, 16}); + if (reference(im)) { + return 1; + } + } + + return 0; +} + +int data_dependent_select_test() { + // A select whose condition reads the previous value is a step of the + // recurrence, not a base-case guard: both branches may recurse. The + // classifier must not demand a base case of it. A bounded Collatz-ish + // walk with state carried in a Tuple. + Func f(std::vector{Int(32), Int(32)}, 1, "f"), g("g"); + Var t("t"); + Expr prev = f(t - 1)[0], count = f(t - 1)[1]; + Expr even = prev % 2 == 0; + Expr next = select(even, prev / 2, select(prev > 1000, prev - 1000, 3 * prev + 1)); + Tuple base = {7, 0}; + Tuple step = {likely(next), count + select(even, 1, 2)}; + f(t) = select(t <= 0, base, step); + g(t) = f(t)[0] + f(t)[1]; + f.compute_at(g, t).store_root().fold_storage(t, 2); + Buffer im = g.realize({200}); + int v = 7, c = 0; + for (int t = 0; t < 200; t++) { + if (t > 0) { + bool ev = v % 2 == 0; + int nv = ev ? v / 2 : (v > 1000 ? v - 1000 : 3 * v + 1); + c += ev ? 1 : 2; + v = nv; + } + if (im(t) != v + c) { + printf("im(%d) = %d instead of %d\n", t, im(t), v + c); + return 1; + } + } + return 0; +} + +} // namespace + +int main(int argc, char **argv) { + struct Task { + std::string desc; + std::function fn; + }; + + std::vector tasks = { + {"simple inductive test", simple_inductive_test}, + {"reordering test", reorder_test}, + {"distinct inductive reorder test", distinct_inductive_reorder_test}, + {"data-dependent select test", data_dependent_select_test}, + {"summed area table test", summed_area_table}, + {"large baseline test", large_baseline}, + {"fibonacci test", fibonacci}, + {"2d sum test", sum_2d_test}, + {"1d sum test", sum_1d_test}, + {"multi-baseline test", multi_baseline_test}, + {"inductive update rdom test", inductive_update_rdom_test}, + {"type declaration test", type_declare_test}, + {"tuple test", tuple_test}, + {"tuple test 2", tuple_test_2}, + }; + + using Sharder = Halide::Internal::Test::Sharder; + Sharder sharder; + for (size_t t = 0; t < tasks.size(); t++) { + if (!sharder.should_run(t)) continue; + const auto &task = tasks.at(t); + std::cout << task.desc << "\n"; + if (task.fn() != 0) { + return 1; + } + } + + printf("Success!\n"); + return 0; +} diff --git a/test/correctness/inductive_base_case_bounds.cpp b/test/correctness/inductive_base_case_bounds.cpp new file mode 100644 index 000000000000..1dcbca65fe5f --- /dev/null +++ b/test/correctness/inductive_base_case_bounds.cpp @@ -0,0 +1,122 @@ +#include "Halide.h" +#include + +using namespace Halide; +using namespace Halide::Internal; + +namespace { + +// Finds the allocation for the inductive Func f and records whether its +// storage extents are constant, and whether any of them depend on a loop +// variable the allocation is nested inside. +class InspectFAllocation : public IRVisitor { + using IRVisitor::visit; + + std::vector enclosing_loops; + + void visit(const For *op) override { + enclosing_loops.push_back(op->name); + IRVisitor::visit(op); + enclosing_loops.pop_back(); + } + + void visit(const Allocate *op) override { + if (op->name == "f" || starts_with(op->name, "f$") || starts_with(op->name, "f.")) { + found = true; + all_extents_const = true; + depends_on_enclosing_loop = false; + for (const Expr &e : op->extents) { + if (!is_const(e)) { + all_extents_const = false; + } + for (const std::string &v : enclosing_loops) { + if (expr_uses_var(e, v)) { + depends_on_enclosing_loop = true; + } + } + } + } + IRVisitor::visit(op); + } + +public: + bool found = false; + bool all_extents_const = false; + bool depends_on_enclosing_loop = false; +}; + +InspectFAllocation inspect(bool compute_root) { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + // Inductive in x; the base case fires at x <= y - 100, so how far the + // recursion reaches back in x depends on the non-inductive var y. + f(x, y) = select(x > y - 100, f(x - 1, y) + 1, 0); + g(x, y) = f(x, y); + g.bound(x, 0, 200).bound(y, 0, 200); + if (compute_root) { + f.compute_root(); + } else { + f.compute_at(g, y); + } + Module m = g.compile_to_module({}, compute_root ? "g_root" : "g_at"); + InspectFAllocation v; + for (const auto &fn : m.functions()) { + fn.body.accept(&v); + } + return v; +} + +} // namespace + +int main(int argc, char **argv) { + // compute_at(g, y): f is realized inside the y loop, so the amount of f + // materialized depends on y - the base-case reach x = y - 100 appears in + // its storage extents. + InspectFAllocation at = inspect(false); + if (!at.found) { + printf("Failed to find an allocation for f in the compute_at schedule\n"); + return 1; + } + if (at.all_extents_const || !at.depends_on_enclosing_loop) { + printf("Expected the amount of f materialized to depend on y under " + "compute_at(g, y), but its allocation extents were " + "loop-invariant\n"); + return 1; + } + + // compute_root: f is realized once over the whole domain, so the base-case + // reach is bounded over all of y and its storage extents are constant. + InspectFAllocation root = inspect(true); + if (!root.found) { + printf("Failed to find an allocation for f in the compute_root schedule\n"); + return 1; + } + if (!root.all_extents_const || root.depends_on_enclosing_loop) { + printf("Expected the amount of f materialized to be independent of y " + "under compute_root, but its allocation extents still depended " + "on a loop variable\n"); + return 1; + } + + // The result is the same either way: f(x, y) counts up from the base case + // at x = y - 100, i.e. max(0, x - y + 100). + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x > y - 100, f(x - 1, y) + 1, 0); + g(x, y) = f(x, y); + g.bound(x, 0, 200).bound(y, 0, 200); + f.compute_at(g, y); + Buffer out = g.realize({200, 200}); + for (int yy = 0; yy < 200; yy++) { + for (int xx = 0; xx < 200; xx++) { + int expected = std::max(0, xx - yy + 100); + if (out(xx, yy) != expected) { + printf("out(%d, %d) = %d instead of %d\n", xx, yy, out(xx, yy), expected); + return 1; + } + } + } + + printf("Success!\n"); + return 0; +} diff --git a/test/correctness/inductive_errors.cpp b/test/correctness/inductive_errors.cpp new file mode 100644 index 000000000000..8f50e8bbcf73 --- /dev/null +++ b/test/correctness/inductive_errors.cpp @@ -0,0 +1,249 @@ +#include "Halide.h" +#include "expect_user_error.h" + +#include + +using namespace Halide; + +int main(int argc, char **argv) { +#ifndef HALIDE_WITH_EXCEPTIONS + printf("[SKIP] the error cases need exceptions.\n"); + return 0; +#else + int failures = 0; + + failures += !expect_user_error("untyped", "must be declared with an explicit type", []() { + Func f("f"), g("g"); + Var x("x"); + f(x) = select(x < 1, 0, x + f(x - 1)); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("2d_arbitrary", "not provably monotonically decreasing", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x < 2 || y < 2 || y > 6, 0, f(x - 1, y + 1)) + select(x < 2 || x > 6 || y < 2, 0, f(x + 1, y - 1)); + g(x, y) = f(x, y) * 2; + g.realize({10, 10}); + }); + + failures += !expect_user_error("cond_nested", "outside of a select", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < max(2, abs(select(x < 0, f(x - 1), 5))), 0, f(x - 1) + x); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("cond_nested_select", "not provably monotonically decreasing", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 0, 0, f(x - 1) + select(x < f(x + 1), 0, 1)); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("cond_self_reference", "outside of a select", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < f(x - 1), 0, f(x - 1) + x); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("diagonal_fold", "fold factor", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x <= 0 || y <= 0, x + y, likely(f(x - 1, y - 1) + 1)); + g(x, y) = f(x, y); + f.compute_at(g, x).store_root().fold_storage(y, 1); + g.bound(x, 0, 64).bound(y, 0, 8); + g.realize({64, 8}); + }); + + failures += !expect_user_error("external_lag_fold", "fold factor", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x <= 0, y, likely(f(x - 1, y) + 1)); + g(x, y) = f(x, y) + f(max(x - 1, 0), y); + f.compute_at(g, x).store_root().fold_storage(x, 1); + g.bound(x, 0, 64).bound(y, 0, 8); + g.realize({64, 8}); + }); + + failures += !expect_user_error("loop_1", "outside of a select", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 1, 0, f(x)); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("loop_2", "inductive step is monotonically decreasing", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 2, 0, f(x - 1) + f(x) + f(x - 2)); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("loop_3", "not provably monotonically decreasing", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 2, 0, f(x - 1) + f(min(2, x)) + f(x - 2)); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("nested_select", "nested select", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 1, 0, select(x < 3, 1, f(x - 1))); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("no_select", "outside of a select", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = x + f(x - 1); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("redundant_z_fold", "fold factor", []() { + Func f(Int(32), "f"), h("h"); + Var x("x"), y("y"), z("z"); + f(x, y) = select(x <= 0, y, likely(f(x - 1, y) + 1)); + h(x, y, z) = f(x, y); + h.reorder(z, y, x); + f.compute_at(h, z).store_root().fold_storage(x, 1); + h.bound(x, 0, 64).bound(y, 0, 8).bound(z, 0, 4); + h.realize({64, 8, 4}); + }); + + failures += !expect_user_error("reorder", "same original inductive variable", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"), xi("xi"), xo("xo"); + f(x) = select(x < 1, 0, x + f(x - 1)); + f.split(x, xo, xi, 8); + f.reorder(xo, xi); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("reorder_split", "same original inductive variable", []() { + Func f(Float(32), 1, "f"), g("g"); + Var t("t"), to("to"), ti("ti"); + f(t) = select(t <= 0, 0.f, likely(f(t - 1) + 1.f)); + g(t) = f(t); + f.compute_root().split(t, to, ti, 4).reorder(to, ti); + g.realize({16}); + }); + + failures += !expect_user_error("rvar_rhs", "not provably monotonically decreasing", []() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + const int Y = 10; + RDom ry(0, Y, "ry"); + g(x, y) = 0; + g(x, y) = select(x <= 0, y, likely(max(g(x, y), g(x - 1, ry) + x + ry))); + h(x, y) = g(x, y); + h.bound(x, 0, 20).bound(y, 0, Y); + g.compute_at(h, x).store_root(); + h.realize({20, Y}); + }); + + failures += !expect_user_error("small_fold", "fold factor", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x <= 0, 0, f(x - 1) + f(x - 2) + x); + g(x) = f(x) * 2; + f.compute_at(g, x).store_root().fold_storage(x, 1); + g.realize({10}); + }); + + failures += !expect_user_error("tuple_fold", "fold factor", []() { + Func f(std::vector{Int(32), Int(32)}, "f"), g("g"); + Var x("x"); + f(x) = select(x <= 0, Tuple(0, 0), Tuple(f(x - 1)[0] + 1, f(x - 1)[1] + f(x - 1)[0])); + g(x) = f(x)[1] * 2; + f.compute_at(g, x).store_root().fold_storage(x, 1); + g.realize({10}); + }); + + failures += !expect_user_error("tuple_to_expr", "returns a Tuple", []() { + Func g(std::vector{Int(32), Int(32)}, "g"), h("h"); + Var x("x"), y("y"); + g(x, y) = Tuple(select(x <= 0, 0, g(max(0, x - 1), y) + x + y), select(y <= 0, 0, g(x, max(0, y - 1)) + x + y)); + h(x, y) = g(x, y)[0] / 2; + h.realize({10, 10}); + }); + + failures += !expect_user_error("two_defs", "after an inductive definition", []() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + g(x, y) = select(x <= 0, y, likely(g(x - 1, y) + x)); + g(x, y) = select(y <= 0, g(x, y), likely(g(x, y - 1) + y)); + h(x, y) = g(x, y); + h.bound(x, 0, 20).bound(y, 0, 20); + g.compute_at(h, x).store_root(); + h.realize({20, 20}); + }); + + failures += !expect_user_error("update", "after an inductive definition", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 1, 0, x + f(x - 1)); + f(x) += 1; + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("update_reorder", "nested inside all inductive", []() { + Func g(Int(32), "g"), h("h"); + Var x("x"), y("y"); + const int Y = 10; + RDom ry(0, Y, "ry"); + g(x, y) = 0; + g(x, y) = select(x <= 0, y, likely(max(g(x, y), g(x - 1, ry) + x + ry))); + g.update().reorder(x, ry); + h(x, y) = g(x, y); + h.bound(x, 0, 20).bound(y, 0, Y); + g.compute_at(h, x).store_root(); + h.realize({20, Y}); + }); + + failures += !expect_user_error("var_swap", "not provably monotonically decreasing", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x < 1, 0, x + f(y - 1, x - 1)); + g(x, y) = f(x, y) * 2; + g.realize({10, 10}); + }); + + failures += !expect_user_error("vectorize", "race condition", []() { + Func f(Int(32), "f"), g("g"); + Var x("x"); + f(x) = select(x < 1, 0, x + f(x - 1)); + f.vectorize(x, 8); + g(x) = f(x) * 2; + g.realize({10}); + }); + + failures += !expect_user_error("output", "inductively defined output", []() { + Func f(Int(32), "f"); + Var x("x"); + f(x) = select(x < 1, 0, x + f(x - 1)); + f.realize({10}); + }); + + if (failures) { + printf("%d error cases failed\n", failures); + return 1; + } + printf("Success!\n"); + return 0; +#endif +} diff --git a/test/correctness/inductive_folding.cpp b/test/correctness/inductive_folding.cpp new file mode 100644 index 000000000000..16712e4b7935 --- /dev/null +++ b/test/correctness/inductive_folding.cpp @@ -0,0 +1,129 @@ +#include "Halide.h" +#include "check_call_graphs.h" +#include "test_sharding.h" + +#include +#include +#include +#include + +namespace { + +using namespace Halide; + +int fib_fold3() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x <= 1, x + y, likely(f(x - 1, y) + f(x - 2, y))); + g(x, y) = f(x, y); + // Reaches back two steps, so the window keeps t-1, t-2, and t. + f.compute_at(g, x).store_root().fold_storage(x, 3); + g.bound(x, 0, 30).bound(y, 0, 8); + + Buffer im = g.realize({30, 8}); + return check_image(im, [](int x, int y) { + if (x <= 1) return x + y; + int a = y, b = 1 + y; + for (int i = 2; i <= x; i++) { + int c = b + a; + a = b; + b = c; + } + return b; + }); +} + +int multi_inner_injective_fold1() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"), z("z"); + f(x, y, z) = select(x <= 0, y + z, likely(f(x - 1, y, z) + 1)); + g(x, y, z) = f(x, y, z); + g.reorder(z, y, x); + f.compute_at(g, x).store_root().fold_storage(x, 2); + g.bound(x, 0, 16).bound(y, 0, 4).bound(z, 0, 4); + + Buffer im = g.realize({16, 4, 4}); + return check_image(im, [](int x, int y, int z) { return x + y + z; }); +} + +int consumer_strided_nonfold_fold1() { + Func f(Int(32), "f"), g("g"); + Var x("x"), y("y"); + f(x, y) = select(x <= 0, y, likely(f(x - 1, y) + 1)); // f(x, y) = x + y + g(x, y) = f(x, 2 * y); + f.compute_at(g, x).store_root().fold_storage(x, 2); + g.bound(x, 0, 64).bound(y, 0, 8); + + Buffer im = g.realize({64, 8}); + return check_image(im, [](int x, int y) { return x + 2 * y; }); +} + +int box_filter_chained_inductive_fold() { + const int W = 10, H = 10, R = 4; + Var x("x"), y("y"); + + Func input("input"); + input(x, y) = x + y; + + Func rowsum(Int(32), "rowsum"); + rowsum(x, y) = select(x <= 0, input(0, y), + likely(rowsum(x - 1, y) + input(x, y))); + + Func sat(Int(32), "sat"); + sat(x, y) = select(y < 0, 0, + likely(sat(x, y - 1) + rowsum(x, y))); + + Func sat_clamped("sat_clamped"); + sat_clamped(x, y) = select(x < 0 || y < 0, 0, + sat(clamp(x, 0, W - 1), clamp(y, 0, H - 1))); + + Func box("box"); + box(x, y) = sat_clamped(x + R, y + R) - sat_clamped(x - R - 1, y + R) - sat_clamped(x + R, y - R - 1) + sat_clamped(x - R - 1, y - R - 1); + + box.bound(x, 0, W).bound(y, 0, H); + + sat.store_root().compute_at(box, y).fold_storage(y, 2 * R + 2); + rowsum.store_at(box, y).compute_at(sat, x).fold_storage(x, 2); + + Buffer result = box.realize({W, H}); + + return check_image(result, [&](int x, int y) { + int expected = 0; + for (int j = std::max(0, y - R); j <= std::min(H - 1, y + R); j++) { + for (int i = std::max(0, x - R); i <= std::min(W - 1, x + R); i++) { + expected += i + j; + } + } + return expected; + }); +} + +} // namespace + +int main(int argc, char **argv) { + struct Task { + std::string desc; + std::function fn; + }; + + std::vector tasks = { + {"fibonacci, fold_storage 3", fib_fold3}, + {"loop-reordered recurrence, fold_storage 2", multi_inner_injective_fold1}, + {"strided non-fold consumer access, fold_storage 2", consumer_strided_nonfold_fold1}, + {"box filter, fold_storage 2", box_filter_chained_inductive_fold}, + }; + + using Sharder = Halide::Internal::Test::Sharder; + Sharder sharder; + for (size_t t = 0; t < tasks.size(); t++) { + if (!sharder.should_run(t)) continue; + const auto &task = tasks.at(t); + std::cout << task.desc << "\n"; + if (task.fn() != 0) { + return 1; + } + } + + printf("Success!\n"); + return 0; +} diff --git a/test/correctness/inductive_ring_buffer.cpp b/test/correctness/inductive_ring_buffer.cpp new file mode 100644 index 000000000000..8be4dc6e85a9 --- /dev/null +++ b/test/correctness/inductive_ring_buffer.cpp @@ -0,0 +1,38 @@ +// A Func that is defined in terms of itself, holds a Tuple, and is ring +// buffered. Each of those three with any one of the others works; all three +// together used to fail an internal assertion in SplitTuples, comparing the +// arguments of a call against those of a store. +// +// Ring buffering gives the store an extra dimension for the ring index. The +// values being stored were passed through untouched, so a call the Func makes +// to itself - which only happens when it is defined in terms of itself - kept +// the arity it had before, and the two no longer agreed. +#include "Halide.h" +#include +using namespace Halide; +int main() { + Var x("x"), y("y"); + Func f({Int(32), Int(32)}, "f"), g("g"); + // component 0 counts up from y; component 1 sums component 0 so far. + f(x, y) = select(x <= 0, Tuple(y, 0), + Tuple(f(x - 1, y)[0] + 1, f(x - 1, y)[1] + f(x - 1, y)[0])); + g(x, y) = f(x, y)[1]; + f.hoist_storage_root().compute_at(g, x).ring_buffer(2); + g.bound(x, 0, 12).bound(y, 0, 4); + Buffer im = g.realize({12, 4}); + for (int j = 0; j < 4; j++) { + int c = j, s = 0; + for (int i = 0; i < 12; i++) { + if (i > 0) { + s += c; + c += 1; + } + if (im(i, j) != s) { + printf("bad %d %d: %d != %d\n", i, j, im(i, j), s); + return 1; + } + } + } + printf("Success!\n"); + return 0; +} diff --git a/test/correctness/inductive_var_race.cpp b/test/correctness/inductive_var_race.cpp new file mode 100644 index 000000000000..63663f1b6de2 --- /dev/null +++ b/test/correctness/inductive_var_race.cpp @@ -0,0 +1,49 @@ +#include "Halide.h" + +using namespace Halide; + +// An update definition that is inductive in t (it reads the step before) +// and reduces over an RDom in x may vectorize and parallelize x without +// allow_race_conditions(): t's loop is serial by construction, so the +// race analysis treats it as shared between iterations of x, and the +// reads of step t-1 are of a finished step. +int main(int argc, char **argv) { + const int W = 64, T = 8; + Func f("f"); + Var x("x"), t("t"); + RDom r(0, W, "r"); + f(x, t) = 0.f; + f(r, t) = select(t <= 0, cast(r), + likely(f(r, t - 1) + f((r + 1) % W, t - 1) + 1.0f)); + + RVar ro("ro"), ri("ri"); + f.update(0).split(r, ro, ri, 16).vectorize(ri).parallel(ro); + + // An inductive Func cannot be the output; a consumer reads it. + Func g("g"); + g(x, t) = f(x, t); + f.compute_root(); + Buffer out = g.realize({W, T}); + + std::vector ref(W), next(W); + for (int i = 0; i < W; i++) { + ref[i] = (float)i; + } + for (int tt = 0; tt < T; tt++) { + if (tt > 0) { + for (int i = 0; i < W; i++) { + next[i] = ref[i] + ref[(i + 1) % W] + 1.0f; + } + ref = next; + } + for (int i = 0; i < W; i++) { + if (out(i, tt) != ref[i]) { + printf("f(%d, %d) = %f instead of %f\n", i, tt, out(i, tt), ref[i]); + return 1; + } + } + } + + printf("Success!\n"); + return 0; +} From 8d7ccaef7b957281602f3d1c74e2c2f5cef1a6a5 Mon Sep 17 00:00:00 2001 From: Andrew Adams Date: Fri, 6 Nov 2026 12:31:34 -0800 Subject: [PATCH 2/5] Measure the footprint of a window warming up on the first iteration at the loop min A window that warms up on the first iteration of a loop computes a larger region on that iteration only, so storage folding measures that region's extent at the loop min rather than over the whole loop. Otherwise a cascade of inductive Funcs sliding over a split dimension needs a fold factor larger than the window it keeps. Add tests of cascades of second-order inductive Funcs, folded, and sliding over a split dimension. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/StorageFolding.cpp | 4 +- test/correctness/inductive_folding.cpp | 88 ++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) diff --git a/src/StorageFolding.cpp b/src/StorageFolding.cpp index 7a1ee3f4ada8..0ca348ad26ce 100644 --- a/src/StorageFolding.cpp +++ b/src/StorageFolding.cpp @@ -643,8 +643,10 @@ class AttemptStorageFoldingOfFunction : public IRMutator { // Take the difference before CSE, so that the terms the two ends // have in common cancel rather than being hidden behind lets. Expr diff = max - min; + Expr initial_diff = substitute(name, var_bounds.min, + substitute(steady_state, const_false(), diff)); Expr extent_expr = (Max::make(substitute(steady_state, const_true(), diff), - substitute(steady_state, const_false(), diff)) + + initial_diff) + 1); Expr extent = simplify(common_subexpression_elimination(extent_expr), bounds); diff --git a/test/correctness/inductive_folding.cpp b/test/correctness/inductive_folding.cpp index 16712e4b7935..b3a839a90029 100644 --- a/test/correctness/inductive_folding.cpp +++ b/test/correctness/inductive_folding.cpp @@ -98,6 +98,92 @@ int box_filter_chained_inductive_fold() { }); } +int cascaded_second_order_fold4() { + // Clamping the reads of the previous section keeps each section's + // region pinned to the base case, so each one warms up on the first + // iteration rather than by rewinding the loop. + Var c("c"), n("n"), co("co"), ci("ci"); + Func in("in"); + in(c, n) = (c * 7 + n * 13) % 17; + Func prev = in; + std::vector sections; + for (int k = 0; k < 2; k++) { + Func s(Int(32), "s" + std::to_string(k)); + s(c, n) = prev(c, max(n, 0)) + + select(n < 1, 0, likely(prev(c, max(n - 1, 0)) - s(c, n - 1))) + + select(n < 2, 0, likely(prev(c, max(n - 2, 0)) + s(c, n - 2))); + sections.push_back(s); + prev = s; + } + Func g("g"); + g(c, n) = prev(c, n); + g.split(c, co, ci, 4).reorder(ci, co, n); + for (Func s : sections) { + s.store_root().compute_at(g, co).fold_storage(n, 4); + } + g.bound(c, 0, 8).bound(n, 0, 32); + + Buffer im = g.realize({8, 32}); + return check_image(im, [](int c, int n) { + std::vector u(n + 1), v(n + 1); + for (int i = 0; i <= n; i++) { + u[i] = (c * 7 + i * 13) % 17; + } + for (int k = 0; k < 2; k++) { + for (int i = 0; i <= n; i++) { + v[i] = u[i] + + (i >= 1 ? u[i - 1] - v[i - 1] : 0) + + (i >= 2 ? u[i - 2] + v[i - 2] : 0); + } + std::swap(u, v); + } + return u[n]; + }); +} + +int cascaded_second_order_split_slide() { + // Sliding over a split dimension rewinds the outer loop, and each section + // must warm up a little earlier than the one it feeds. Each section only + // needs its own last two values, so all of them fold to 4. + Var c("c"), n("n"), no("no"), ni("ni"); + Func in("in"); + in(c, n) = (c * 7 + n * 13) % 17; + Func prev = BoundaryConditions::constant_exterior(in, 0, {{0, 8}, {0, 32}}); + std::vector sections; + for (int k = 0; k < 6; k++) { + Func s(Int(32), "s" + std::to_string(k)); + s(c, n) = prev(c, n) + + select(n < 1, 0, prev(c, n - 1) - s(c, n - 1)) + + select(n < 2, 0, prev(c, n - 2) + s(c, n - 2)); + sections.push_back(s); + prev = s; + } + Func g("g"); + g(c, n) = prev(c, n); + g.reorder(n, c).split(n, no, ni, 4, TailStrategy::RoundUp).unroll(ni); + for (Func s : sections) { + s.store_at(g, c).compute_at(g, ni).slide(g, n).fold_storage(n, 4); + } + g.bound(c, 0, 8); + + Buffer im = g.realize({8, 32}); + return check_image(im, [](int c, int n) { + std::vector u(n + 1), v(n + 1); + for (int i = 0; i <= n; i++) { + u[i] = (c * 7 + i * 13) % 17; + } + for (int k = 0; k < 6; k++) { + for (int i = 0; i <= n; i++) { + v[i] = u[i] + + (i >= 1 ? u[i - 1] - v[i - 1] : 0) + + (i >= 2 ? u[i - 2] + v[i - 2] : 0); + } + std::swap(u, v); + } + return u[n]; + }); +} + } // namespace int main(int argc, char **argv) { @@ -111,6 +197,8 @@ int main(int argc, char **argv) { {"loop-reordered recurrence, fold_storage 2", multi_inner_injective_fold1}, {"strided non-fold consumer access, fold_storage 2", consumer_strided_nonfold_fold1}, {"box filter, fold_storage 2", box_filter_chained_inductive_fold}, + {"cascaded second-order recurrences, fold_storage 4", cascaded_second_order_fold4}, + {"cascade sliding over a split dimension, fold_storage 4", cascaded_second_order_split_slide}, }; using Sharder = Halide::Internal::Test::Sharder; From 53e121ccd091feee09c7ff1aa7b304389d9c2e83 Mon Sep 17 00:00:00 2001 From: Andrew Adams Date: Fri, 6 Nov 2026 12:31:34 -0800 Subject: [PATCH 3/5] Add an iir_cascade app: a cascade of IIR filters as inductive Funcs Each section is a second-order recurrence over the samples, written as an inductive Func. The sections slide over the samples, and the last three values of each are kept in registers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- apps/CMakeLists.txt | 1 + apps/iir_cascade/CMakeLists.txt | 32 ++++++ apps/iir_cascade/Makefile | 23 +++++ apps/iir_cascade/iir_cascade_generator.cpp | 109 +++++++++++++++++++++ apps/iir_cascade/test.cpp | 93 ++++++++++++++++++ 5 files changed, 258 insertions(+) create mode 100644 apps/iir_cascade/CMakeLists.txt create mode 100644 apps/iir_cascade/Makefile create mode 100644 apps/iir_cascade/iir_cascade_generator.cpp create mode 100644 apps/iir_cascade/test.cpp diff --git a/apps/CMakeLists.txt b/apps/CMakeLists.txt index afc90b173081..33a2046cfa78 100644 --- a/apps/CMakeLists.txt +++ b/apps/CMakeLists.txt @@ -64,6 +64,7 @@ add_app(hexagon_benchmarks) add_app(hexagon_dma) add_app(hist) add_app(iir_blur) +add_app(iir_cascade) add_app(interpolate) add_app(lens_blur) add_app(linear_algebra) diff --git a/apps/iir_cascade/CMakeLists.txt b/apps/iir_cascade/CMakeLists.txt new file mode 100644 index 000000000000..a95b8b6ff0db --- /dev/null +++ b/apps/iir_cascade/CMakeLists.txt @@ -0,0 +1,32 @@ +cmake_minimum_required(VERSION 3.28) +project(iir_cascade) + +enable_testing() + +# Set up language settings +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED YES) +set(CMAKE_CXX_EXTENSIONS NO) + +# Find Halide +find_package(Halide REQUIRED) + +# Generator +add_halide_generator(iir_cascade.generator SOURCES iir_cascade_generator.cpp) + +# Filters +add_halide_library(iir_cascade FROM iir_cascade.generator) + +# Main executable +add_executable(iir_cascade_test test.cpp) +target_link_libraries(iir_cascade_test PRIVATE Halide::Tools iir_cascade) + +# Test that the app actually works! +add_test(NAME iir_cascade_test COMMAND iir_cascade_test) +set_tests_properties( + iir_cascade_test + PROPERTIES + LABELS iir_cascade + PASS_REGULAR_EXPRESSION "Success!" + SKIP_REGULAR_EXPRESSION "\\[SKIP\\]" +) diff --git a/apps/iir_cascade/Makefile b/apps/iir_cascade/Makefile new file mode 100644 index 000000000000..352c4d53c763 --- /dev/null +++ b/apps/iir_cascade/Makefile @@ -0,0 +1,23 @@ +include ../support/Makefile.inc + +.PHONY: build clean test + +build: $(BIN)/$(HL_TARGET)/test + +$(GENERATOR_BIN)/iir_cascade.generator: iir_cascade_generator.cpp $(GENERATOR_DEPS) + @mkdir -p $(@D) + $(CXX) $(CXXFLAGS) $(filter %.cpp,$^) -o $@ $(LIBHALIDE_LDFLAGS) + +$(BIN)/%/iir_cascade.a: $(GENERATOR_BIN)/iir_cascade.generator + @mkdir -p $(@D) + $^ -g iir_cascade -e $(GENERATOR_OUTPUTS) -o $(@D) target=$* + +$(BIN)/%/test: test.cpp $(BIN)/%/iir_cascade.a + @mkdir -p $(@D) + $(CXX-$*) $(CXXFLAGS-$*) -Wall -O2 -I$(BIN)/$* $^ -o $@ $(LDFLAGS-$*) + +clean: + rm -rf $(BIN) + +test: $(BIN)/$(HL_TARGET)/test + $< diff --git a/apps/iir_cascade/iir_cascade_generator.cpp b/apps/iir_cascade/iir_cascade_generator.cpp new file mode 100644 index 000000000000..36210d1e24fa --- /dev/null +++ b/apps/iir_cascade/iir_cascade_generator.cpp @@ -0,0 +1,109 @@ +// This file defines a generator for a cascade of second-order IIR filters +// (biquads) applied to many channels of audio. It computes the same thing as +// scipy.signal.sosfilt. +// +// Each section is an inductive Func: a Func defined in terms of its own +// previous outputs. This lets the entire cascade be computed in a single pass +// over the samples, keeping only the last few outputs of each section in +// registers. + +#include "Halide.h" + +using namespace Halide; + +class IIRCascade : public Generator { +public: + GeneratorParam sections{"sections", 8}; + + // The signal, indexed by channel then sample. + Input> input{"input"}; + // The filter coefficients, indexed by coefficient then section. The + // coefficients of each section are b0, b1, b2, a0, a1, a2, normalized so + // that a0 is one. + Input> sos{"sos"}; + Output> output{"output"}; + + void generate() { + Var c("c"), n("n"); + + std::vector cascade; + Func prev = BoundaryConditions::constant_exterior(input, + 0.f, + {{Expr{}, Expr{}}, + {0, input.dim(1).extent()}}); + for (int k = 0; k < sections; k++) { + Expr b0 = sos(0, k), b1 = sos(1, k), b2 = sos(2, k); + Expr a1 = sos(4, k), a2 = sos(5, k); + + // Inductive Funcs must have their type declared up front. + Func f(Float(32), "section_" + std::to_string(k)); + /* + // The clamps keep the reads of prev in bounds near the start of + // the signal, where the selects discard them. + f(c, n) = (b0 * prev(c, max(n, 0)) + + select(n < 1, 0.f, + likely(b1 * prev(c, max(n - 1, 0)) - a1 * f(c, n - 1))) + + select(n < 2, 0.f, + likely(b2 * prev(c, max(n - 2, 0)) - a2 * f(c, n - 2)))); + */ + + f(c, n) = (b0 * prev(c, n) + + b1 * prev(c, n - 1) + + b2 * prev(c, n - 2) - + select(n < 1, 0.f, a1 * f(c, n - 1)) - + select(n < 2, 0.f, likely(a2 * f(c, n - 2)))); + cascade.push_back(f); + prev = f; + } + output(c, n) = prev(c, n); + + // Schedule + // Each thread walks along the samples once for a vector of channels, + // computing every section at each sample. Each section slides over + // the samples, and the three values of it in use at once stay in + // registers. + const int vec = natural_vector_size(); + output.vectorize(c, vec, TailStrategy::RoundUp) + .reorder(n, c) + .parallel(c); + + for (Func f : cascade) { + f.store_at(output, c) + .compute_at(output, n) + .vectorize(c) + .store_in(MemoryType::Register); + } + + if (0) { + Buffer input(256, 1024), output(256, 1024), sos(6, sections); + input.fill([](int c, int n) { return sin(2 * M_PI * 440 * n / 48000) * (1.0f - 2.0f * c / 256); }); + sos.fill([&](int i, int k) -> float { + const double fs = 48000, q = 0.8; + double f0 = 120 * std::pow(8000.0 / 120, (double)k / ((int)sections - 1)); + double gain = std::pow(10.0, ((k % 2) ? 3.0 : -3.0) / 40); + double w0 = 2 * M_PI * f0 / fs; + double alpha = std::sin(w0) / (2 * q); + double a0 = 1 + alpha / gain; + switch (i) { + case 0: + return (1 + alpha * gain) / a0; + case 1: + return -2 * std::cos(w0) / a0; + case 2: + return (1 - alpha * gain) / a0; + case 3: + return 1; + case 4: + return -2 * std::cos(w0) / a0; + case 5: + return (1 - alpha / gain) / a0; + default: + return 0.0f; + } + }); + halidoscope(input, sos, output); + } + } +}; + +HALIDE_REGISTER_GENERATOR(IIRCascade, iir_cascade) diff --git a/apps/iir_cascade/test.cpp b/apps/iir_cascade/test.cpp new file mode 100644 index 000000000000..1c858672e0b6 --- /dev/null +++ b/apps/iir_cascade/test.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include + +#include "HalideBuffer.h" +#include "halide_benchmark.h" + +#include "iir_cascade.h" + +using namespace Halide::Runtime; +using namespace Halide::Tools; + +#ifndef M_PI +#define M_PI 3.14159265358979310000 +#endif + +// Must match the generator's sections parameter. +const int sections = 8; + +// Coefficients for a cascade of peaking equalizers, with center frequencies +// spread across the audible range, alternating between boost and cut. +Buffer make_sos() { + Buffer sos(6, sections); + const double fs = 48000, q = 0.8; + for (int k = 0; k < sections; k++) { + double f0 = 120 * std::pow(8000.0 / 120, (double)k / (sections - 1)); + double gain = std::pow(10.0, ((k % 2) ? 3.0 : -3.0) / 40); + double w0 = 2 * M_PI * f0 / fs; + double alpha = std::sin(w0) / (2 * q); + double a0 = 1 + alpha / gain; + sos(0, k) = (1 + alpha * gain) / a0; + sos(1, k) = -2 * std::cos(w0) / a0; + sos(2, k) = (1 - alpha * gain) / a0; + sos(3, k) = 1; + sos(4, k) = -2 * std::cos(w0) / a0; + sos(5, k) = (1 - alpha / gain) / a0; + } + return sos; +} + +// Run the cascade on one channel in double precision. +std::vector reference(const Buffer &input, const Buffer &sos, int c) { + std::vector x(input.dim(1).extent()), y(x.size()); + for (size_t n = 0; n < x.size(); n++) { + x[n] = input(c, n); + } + for (int k = 0; k < sections; k++) { + double x1 = 0, x2 = 0, y1 = 0, y2 = 0; + for (size_t n = 0; n < x.size(); n++) { + y[n] = sos(0, k) * x[n] + sos(1, k) * x1 + sos(2, k) * x2 - sos(4, k) * y1 - sos(5, k) * y2; + x2 = x1; + x1 = x[n]; + y2 = y1; + y1 = y[n]; + } + std::swap(x, y); + } + return x; +} + +int main(int argc, char **argv) { + const int channels = 1024; + const int samples = 65536; + + Buffer input(channels, samples); + Buffer output(channels, samples); + Buffer sos = make_sos(); + + uint32_t seed = 0; + input.for_each_value([&](float &v) { + seed = seed * 1664525 + 1013904223; + v = (int32_t)seed * (1.0f / 2147483648.0f); + }); + + double t = benchmark([&]() { + iir_cascade(input, sos, output); + }); + printf("Time: %gms\n", t * 1e3); + + for (int c = 0; c < channels; c += 37) { + std::vector expected = reference(input, sos, c); + for (int n = 0; n < samples; n++) { + if (std::abs(output(c, n) - expected[n]) > 1e-4) { + printf("output(%d, %d) = %f instead of %f\n", c, n, output(c, n), expected[n]); + return 1; + } + } + } + + printf("Success!\n"); + return 0; +} From f0dcf2a07325723a4cd6ea804d9f344be714ea6a Mon Sep 17 00:00:00 2001 From: Andrew Adams Date: Thu, 12 Nov 2026 11:52:28 -0800 Subject: [PATCH 4/5] Don't inline lets when finding an inductive Func's base case expand_to_include_base_case ran BaseCaseSolver, a tree visitor, over the result of substitute_in_all_lets, which is exponential in the depth of a let chain whose values reuse earlier lets. Have the solver track the enclosing lets instead, rewrapping the ones each condition or recursive argument uses. Lets whose values refer to the Func are checked where they are used, once per select arm. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Inductive.cpp | 94 +++++++++++++++++++++++----------- test/correctness/inductive.cpp | 37 +++++++++++++ 2 files changed, 101 insertions(+), 30 deletions(-) diff --git a/src/Inductive.cpp b/src/Inductive.cpp index e558f81db5aa..bc888d6ee144 100644 --- a/src/Inductive.cpp +++ b/src/Inductive.cpp @@ -9,7 +9,8 @@ #include "IROperator.h" #include "IRVisitor.h" #include "Simplify.h" -#include "Substitute.h" + +#include namespace Halide { namespace Internal { @@ -32,10 +33,61 @@ class BaseCaseSolver : public IRVisitor { Scope bounds; + // The inductive vars, and the enclosing lets that depend on them. Scope<> inductive_vars; + // The enclosing lets whose values refer to the function. These are + // checked where they are used, once per select arm. + Scope recursive_lets; + int arm = 0, arms = 0; + std::set> checked_lets; + + // The enclosing lets, outermost first. + vector> lets; + int nested_select = 0; + bool recurses(const Expr &e) const { + bool result = false; + visit_with( + e, + [&](auto *self, const Call *op) { + result |= op->name == func; + self->visit_base(op); + }, + [&](auto *, const Variable *op) { + result |= recursive_lets.contains(op->name); + }); + return result; + } + + Expr in_context(const Expr &e) const { + return rewrap_used_lets(e, lets); + } + + void visit_arm(const Expr &e) { + ScopedValue old_arm(arm, ++arms); + e.accept(this); + } + + void visit(const Variable *op) override { + if (recursive_lets.contains(op->name) && checked_lets.emplace(op->name, arm).second) { + recursive_lets.get(op->name).accept(this); + } + } + + void visit(const Let *op) override { + bool recursive = recurses(op->value); + if (!recursive) { + op->value.accept(this); + } + ScopedBinding<> bind_inductive(expr_uses_vars(op->value, inductive_vars), inductive_vars, op->name); + ScopedBinding bind_recursive(recursive, recursive_lets, op->name, op->value); + lets.emplace_back(op->name, op->value); + op->body.accept(this); + lets.pop_back(); + } + void visit(const Call *op) override { if (op->is_intrinsic(Call::if_then_else)) { @@ -45,14 +97,7 @@ class BaseCaseSolver : public IRVisitor { // recurrence, not a base-case guard, and both of its branches // may recurse (each self-reference in them is still checked). bool cond_is_inductive = expr_uses_vars(op->args[0], inductive_vars); - bool cond_recurses = false; - visit_with(op->args[0], [&](auto *self, const Call *inner_op) { - if (inner_op->name == func) { - cond_recurses = true; - } - self->visit_base(inner_op); - }); - if (!cond_is_inductive || cond_recurses) { + if (!cond_is_inductive || recurses(op->args[0])) { IRVisitor::visit(op); return; } @@ -62,19 +107,9 @@ class BaseCaseSolver : public IRVisitor { // which means the condition cannot have any recursive calls. op->args[0].accept(this); - bool left_recurse = false, right_recurse = false; - visit_with(op->args[1], [&](auto *self, const Call *inner_op) { - if (inner_op->name == func) { - left_recurse = true; - } - self->visit_base(inner_op); - }); - visit_with(op->args[2], [&](auto *self, const Call *inner_op) { - if (inner_op->name == func) { - right_recurse = true; - } - self->visit_base(inner_op); - }); + bool left_recurse = recurses(op->args[1]); + bool right_recurse = recurses(op->args[2]); + Expr cond = simplify(in_context(op->args[0])); // Again, this check is theoretically unnecessary user_assert(!(left_recurse && right_recurse)) << "Select node in inductive function " << func << " does not have a base case"; @@ -82,22 +117,22 @@ class BaseCaseSolver : public IRVisitor { vector old_intervals = condition_intervals; if (left_recurse) { for (size_t i = 0; i < vars.size(); i++) { - Interval inter = Interval::make_intersection(old_intervals[i], solve_for_outer_interval(simplify(op->args[0]), vars[i])); + Interval inter = Interval::make_intersection(old_intervals[i], solve_for_outer_interval(cond, vars[i])); condition_intervals[i] = Interval(inter.min, Interval::pos_inf()); bounds.push(vars[i], condition_intervals[i]); } - op->args[1].accept(this); + visit_arm(op->args[1]); for (const auto &var : vars) { bounds.pop(var); } } if (right_recurse) { for (size_t i = 0; i < vars.size(); i++) { - Interval inter = Interval::make_intersection(old_intervals[i], solve_for_outer_interval(simplify(!op->args[0]), vars[i])); + Interval inter = Interval::make_intersection(old_intervals[i], solve_for_outer_interval(simplify(!cond), vars[i])); condition_intervals[i] = Interval(inter.min, Interval::pos_inf()); bounds.push(vars[i], condition_intervals[i]); } - op->args[2].accept(this); + visit_arm(op->args[2]); for (const auto &var : vars) { bounds.pop(var); } @@ -111,7 +146,7 @@ class BaseCaseSolver : public IRVisitor { bool exact_pure_self_reference = true; for (size_t position = 0; position < vars.size() && exact_pure_self_reference; position++) { if (is_inductive_var[position] && - (position >= op->args.size() || !equal(op->args[position], Variable::make(op->args[position].type(), vars[position])))) { + (position >= op->args.size() || !equal(simplify(in_context(op->args[position])), Variable::make(op->args[position].type(), vars[position])))) { exact_pure_self_reference = false; } } @@ -125,7 +160,7 @@ class BaseCaseSolver : public IRVisitor { user_assert(nested_select == 1) << "Function " << func << " contains an inductive function reference inside a nested select operation.\n"; bool found_inductive = false; for (size_t position = 0; position < vars.size(); position++) { - const Expr inductive_expr = op->args[position]; + const Expr inductive_expr = simplify(in_context(op->args[position])); if (!is_inductive_var[position]) { continue; } @@ -178,10 +213,9 @@ class BaseCaseSolver : public IRVisitor { Box expand_to_include_base_case(const vector &vars, const vector &is_inductive_var, const Expr &RHS, const string &func, const Box &box_required, bool is_update) { - Expr substed = substitute_in_all_lets(RHS); Box box2 = box_required; BaseCaseSolver b(vars, is_inductive_var, func, box_required.bounds, is_update); - substed.accept(&b); + RHS.accept(&b); Scope non_inductive_scope; for (size_t i = 0; i < vars.size(); i++) { diff --git a/test/correctness/inductive.cpp b/test/correctness/inductive.cpp index 36daf7ffc520..2bc49efe07f6 100644 --- a/test/correctness/inductive.cpp +++ b/test/correctness/inductive.cpp @@ -389,6 +389,42 @@ int data_dependent_select_test() { return 0; } +int let_test() { + // Lets in the definition, around the base-case guard and inside the + // recursive step. The step contains a deep chain of lets, each of which + // uses the previous one twice, so they must not be inlined. + const int depth = 40; + Func f(Int(32), 1, "f"), g("g"); + Var x("x"); + Expr chain = x; + for (int k = 0; k < depth; k++) { + std::string n = unique_name('t'); + Expr v = Variable::make(Int(32), n); + chain = Let::make(n, chain, (v + v / 3) % 1000); + } + std::string xm_name = unique_name('t'); + Expr xm = Variable::make(Int(32), xm_name); + f(x) = Let::make(xm_name, x - 1, select(xm >= 0, f(xm) + chain, 0)); + g(x) = f(x); + f.compute_root(); + Buffer im = g.realize({50}); + int correct = 0; + for (int i = 0; i < 50; i++) { + if (i > 0) { + int c = i; + for (int k = 0; k < depth; k++) { + c = (c + c / 3) % 1000; + } + correct += c; + } + if (im(i) != correct) { + printf("im(%d) = %d instead of %d\n", i, im(i), correct); + return 1; + } + } + return 0; +} + } // namespace int main(int argc, char **argv) { @@ -402,6 +438,7 @@ int main(int argc, char **argv) { {"reordering test", reorder_test}, {"distinct inductive reorder test", distinct_inductive_reorder_test}, {"data-dependent select test", data_dependent_select_test}, + {"let test", let_test}, {"summed area table test", summed_area_table}, {"large baseline test", large_baseline}, {"fibonacci test", fibonacci}, From 9f4db38fa1aa62876c763ab6d643945c4a87f669 Mon Sep 17 00:00:00 2001 From: Andrew Adams Date: Tue, 24 Nov 2026 09:57:11 -0800 Subject: [PATCH 5/5] Credit Steven Raphael for inductive Funcs Much of the inductive Funcs implementation comes from #8878. Co-authored-by: Steven Raphael Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>