Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ SOURCE_FILES = \
HexagonOffload.cpp \
HexagonOptimize.cpp \
ImageParam.cpp \
Inductive.cpp \
InferArguments.cpp \
InjectHostDevBufferCopies.cpp \
Inline.cpp \
Expand Down Expand Up @@ -736,6 +737,7 @@ HEADER_FILES = \
HexagonOffload.h \
HexagonOptimize.h \
ImageParam.h \
Inductive.h \
InferArguments.h \
InjectHostDevBufferCopies.h \
Inline.h \
Expand Down
1 change: 1 addition & 0 deletions apps/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
32 changes: 32 additions & 0 deletions apps/iir_cascade/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -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\\]"
)
23 changes: 23 additions & 0 deletions apps/iir_cascade/Makefile
Original file line number Diff line number Diff line change
@@ -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
$<
109 changes: 109 additions & 0 deletions apps/iir_cascade/iir_cascade_generator.cpp
Original file line number Diff line number Diff line change
@@ -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<IIRCascade> {
public:
GeneratorParam<int> sections{"sections", 8};

// The signal, indexed by channel then sample.
Input<Buffer<float, 2>> 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<Buffer<float, 2>> sos{"sos"};
Output<Buffer<float, 2>> output{"output"};

void generate() {
Var c("c"), n("n");

std::vector<Func> 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<float>();
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<float> 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)
93 changes: 93 additions & 0 deletions apps/iir_cascade/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>

#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<float, 2> make_sos() {
Buffer<float, 2> 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<double> reference(const Buffer<float, 2> &input, const Buffer<float, 2> &sos, int c) {
std::vector<double> 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<float, 2> input(channels, samples);
Buffer<float, 2> output(channels, samples);
Buffer<float, 2> 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<double> 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;
}
11 changes: 8 additions & 3 deletions src/AsyncProducers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -690,16 +690,21 @@ class UpdateIndices : public IRMutator {

Stmt visit(const Provide *op) override {
if (op->name == func_name) {
std::vector<Expr> 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<Expr> values = mutate(op->values);
std::vector<Expr> 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<Expr> args = op->args;
std::vector<Expr> args = mutate(op->args);
args.push_back(ring_buffer_index);
return op->with(args);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Bounds.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3512,7 +3512,7 @@ FuncValueBounds compute_function_value_bounds(const vector<string> &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<Interval> arg_scope;
Expand Down
22 changes: 22 additions & 0 deletions src/BoundsInference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<bool> 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;
Expand Down
2 changes: 2 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ target_sources(
HexagonOffload.h
HexagonOptimize.h
ImageParam.h
Inductive.h
InferArguments.h
InjectHostDevBufferCopies.h
Inline.h
Expand Down Expand Up @@ -325,6 +326,7 @@ target_sources(
HexagonOffload.cpp
HexagonOptimize.cpp
ImageParam.cpp
Inductive.cpp
InferArguments.cpp
InjectHostDevBufferCopies.cpp
Inline.cpp
Expand Down
2 changes: 2 additions & 0 deletions src/Deserialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading