Halide  12.0.1
Halide compiler and libraries
simd_op_check.h
Go to the documentation of this file.
1 #ifndef SIMD_OP_CHECK_H
2 #define SIMD_OP_CHECK_H
3 
4 #include "Halide.h"
5 #include "halide_test_dirs.h"
6 
7 #include <fstream>
8 
9 namespace Halide {
10 struct TestResult {
11  std::string op;
12  std::string error_msg;
13 };
14 
15 struct Task {
16  std::string op;
17  std::string name;
20 };
21 
23 public:
24  std::string filter{"*"};
26  std::vector<Task> tasks;
27  std::mt19937 rng;
28 
30 
31  ImageParam in_f32{Float(32), 1, "in_f32"};
32  ImageParam in_f64{Float(64), 1, "in_f64"};
33  ImageParam in_bf16{BFloat(16), 1, "in_bf16"};
34  ImageParam in_i8{Int(8), 1, "in_i8"};
35  ImageParam in_u8{UInt(8), 1, "in_u8"};
36  ImageParam in_i16{Int(16), 1, "in_i16"};
37  ImageParam in_u16{UInt(16), 1, "in_u16"};
38  ImageParam in_i32{Int(32), 1, "in_i32"};
39  ImageParam in_u32{UInt(32), 1, "in_u32"};
40  ImageParam in_i64{Int(64), 1, "in_i64"};
41  ImageParam in_u64{UInt(64), 1, "in_u64"};
42 
43  const std::vector<ImageParam> image_params{in_f32, in_f64, in_bf16, in_i8, in_u8, in_i16, in_u16, in_i32, in_u32, in_i64, in_u64};
44  const std::vector<Argument> arg_types{in_f32, in_f64, in_bf16, in_i8, in_u8, in_i16, in_u16, in_i32, in_u32, in_i64, in_u64};
45  int W;
46  int H;
47 
48  SimdOpCheckTest(const Target t, int w, int h)
49  : target(t), W(w), H(h) {
50  target = target
56  }
57  virtual ~SimdOpCheckTest() = default;
58 
59  void set_seed(int seed) {
60  rng.seed(seed);
61  }
62 
63  size_t get_num_threads() const {
64  return num_threads;
65  }
66 
67  void set_num_threads(size_t n) {
68  num_threads = n;
69  }
70 
71  virtual bool can_run_code() const {
72  // Assume we are configured to run wasm if requested
73  // (we'll fail further downstream if not)
75  return true;
76  }
77  // If we can (target matches host), run the error checking Halide::Func.
78  Target host_target = get_host_target();
79  bool can_run_the_code =
80  (target.arch == host_target.arch &&
81  target.bits == host_target.bits &&
82  target.os == host_target.os);
83  // A bunch of feature flags also need to match between the
84  // compiled code and the host in order to run the code.
91  if (target.has_feature(f) != host_target.has_feature(f)) {
92  can_run_the_code = false;
93  }
94  }
95  return can_run_the_code;
96  }
97 
98  virtual void compile_and_check(Func error, const std::string &op, const std::string &name, int vector_width, std::ostringstream &error_msg) {
99  std::string fn_name = "test_" + name;
100  std::string file_name = output_directory + fn_name;
101 
102  auto ext = Internal::get_output_info(target);
103  std::map<Output, std::string> outputs = {
104  {Output::c_header, file_name + ext.at(Output::c_header).extension},
105  {Output::object, file_name + ext.at(Output::object).extension},
106  {Output::assembly, file_name + ".s"},
107  };
108  error.compile_to(outputs, arg_types, fn_name, target);
109 
110  std::ifstream asm_file;
111  asm_file.open(file_name + ".s");
112 
113  bool found_it = false;
114 
115  std::ostringstream msg;
116  msg << op << " did not generate for target=" << target.to_string() << " vector_width=" << vector_width << ". Instead we got:\n";
117 
118  std::string line;
119  while (getline(asm_file, line)) {
120  msg << line << "\n";
121 
122  // Check for the op in question
123  found_it |= wildcard_search(op, line) && !wildcard_search("_" + op, line);
124  }
125 
126  if (!found_it) {
127  error_msg << "Failed: " << msg.str() << "\n";
128  }
129 
130  asm_file.close();
131  }
132 
133  // Check if pattern p matches str, allowing for wildcards (*).
134  bool wildcard_match(const char *p, const char *str) const {
135  // Match all non-wildcard characters.
136  while (*p && *str && *p == *str && *p != '*') {
137  str++;
138  p++;
139  }
140 
141  if (!*p) {
142  return *str == 0;
143  } else if (*p == '*') {
144  p++;
145  do {
146  if (wildcard_match(p, str)) {
147  return true;
148  }
149  } while (*str++);
150  } else if (*p == ' ') { // ignore whitespace in pattern
151  p++;
152  if (wildcard_match(p, str)) {
153  return true;
154  }
155  } else if (*str == ' ') { // ignore whitespace in string
156  str++;
157  if (wildcard_match(p, str)) {
158  return true;
159  }
160  }
161  return !*p;
162  }
163 
164  bool wildcard_match(const std::string &p, const std::string &str) const {
165  return wildcard_match(p.c_str(), str.c_str());
166  }
167 
168  // Check if a substring of str matches a pattern p.
169  bool wildcard_search(const std::string &p, const std::string &str) const {
170  return wildcard_match("*" + p + "*", str);
171  }
172 
173  TestResult check_one(const std::string &op, const std::string &name, int vector_width, Expr e) {
174  std::ostringstream error_msg;
175 
176  class HasInlineReduction : public Internal::IRVisitor {
178  void visit(const Internal::Call *op) override {
179  if (op->call_type == Internal::Call::Halide) {
180  Internal::Function f(op->func);
181  if (f.has_update_definition()) {
182  inline_reduction = f;
183  result = true;
184  }
185  }
186  IRVisitor::visit(op);
187  }
188 
189  public:
190  Internal::Function inline_reduction;
191  bool result = false;
192  } has_inline_reduction;
193  e.accept(&has_inline_reduction);
194 
195  // Define a vectorized Halide::Func that uses the pattern.
196  Halide::Func f(name);
197  f(x, y) = e;
198  f.bound(x, 0, W).vectorize(x, vector_width);
199  f.compute_root();
200 
201  // Include a scalar version
202  Halide::Func f_scalar("scalar_" + name);
203  f_scalar(x, y) = e;
204 
205  if (has_inline_reduction.result) {
206  // If there's an inline reduction, we want to vectorize it
207  // over the RVar.
208  Var xo, xi;
209  RVar rxi;
210  Func g{has_inline_reduction.inline_reduction};
211 
212  // Do the reduction separately in f_scalar
213  g.clone_in(f_scalar);
214 
215  g.compute_at(f, x)
216  .update()
217  .split(x, xo, xi, vector_width)
218  .atomic(true)
219  .vectorize(g.rvars()[0])
220  .vectorize(xi);
221  }
222 
223  // The output to the pipeline is the maximum absolute difference as a double.
224  RDom r_check(0, W, 0, H);
225  Halide::Func error("error_" + name);
226  error() = Halide::cast<double>(maximum(absd(f(r_check.x, r_check.y), f_scalar(r_check.x, r_check.y))));
227 
228  setup_images();
229  compile_and_check(error, op, name, vector_width, error_msg);
230 
231  bool can_run_the_code = can_run_code();
232  if (can_run_the_code) {
233  Target run_target = target
237 
238  error.infer_input_bounds({}, run_target);
239  // Fill the inputs with noise
240  for (auto p : image_params) {
241  Halide::Buffer<> buf = p.get();
242  if (!buf.defined()) continue;
243  assert(buf.data());
244  Type t = buf.type();
245  // For floats/doubles, we only use values that aren't
246  // subject to rounding error that may differ between
247  // vectorized and non-vectorized versions
248  if (t == Float(32)) {
249  buf.as<float>().for_each_value([&](float &f) { f = (rng() & 0xfff) / 8.0f - 0xff; });
250  } else if (t == Float(64)) {
251  buf.as<double>().for_each_value([&](double &f) { f = (rng() & 0xfff) / 8.0 - 0xff; });
252  } else {
253  // Random bits is fine
254  for (uint32_t *ptr = (uint32_t *)buf.data();
255  ptr != (uint32_t *)buf.data() + buf.size_in_bytes() / 4;
256  ptr++) {
257  // Never use the top four bits, to avoid
258  // signed integer overflow.
259  *ptr = ((uint32_t)rng()) & 0x0fffffff;
260  }
261  }
262  }
263  Realization r = error.realize();
264  double e = Buffer<double>(r[0])();
265  // Use a very loose tolerance for floating point tests. The
266  // kinds of bugs we're looking for are codegen bugs that
267  // return the wrong value entirely, not floating point
268  // accuracy differences between vectors and scalars.
269  if (e > 0.001) {
270  error_msg << "The vector and scalar versions of " << name << " disagree. Maximum error: " << e << "\n";
271 
272  std::string error_filename = output_directory + "error_" + name + ".s";
273  error.compile_to_assembly(error_filename, arg_types, target);
274 
275  std::ifstream error_file;
276  error_file.open(error_filename);
277 
278  error_msg << "Error assembly: \n";
279  std::string line;
280  while (getline(error_file, line)) {
281  error_msg << line << "\n";
282  }
283 
284  error_file.close();
285  }
286  }
287 
288  return {op, error_msg.str()};
289  }
290 
291  void check(std::string op, int vector_width, Expr e) {
292  // Make a name for the test by uniquing then sanitizing the op name
293  std::string name = "op_" + op;
294  for (size_t i = 0; i < name.size(); i++) {
295  if (!isalnum(name[i])) name[i] = '_';
296  }
297 
298  name += "_" + std::to_string(tasks.size());
299 
300  // Bail out after generating the unique_name, so that names are
301  // unique across different processes and don't depend on filter
302  // settings.
303  if (!wildcard_match(filter, op)) return;
304 
305  tasks.emplace_back(Task{op, name, vector_width, e});
306  }
307  virtual void add_tests() = 0;
308  virtual void setup_images() {
309  for (auto p : image_params) {
310  p.reset();
311 
312  const int alignment_bytes = 16;
313  p.set_host_alignment(alignment_bytes);
314  const int alignment = alignment_bytes / p.type().bytes();
315  p.dim(0).set_min((p.dim(0).min() / alignment) * alignment);
316  }
317  }
318  virtual bool test_all() {
319  /* First add some tests based on the target */
320  add_tests();
321  Internal::ThreadPool<TestResult> pool(num_threads);
322  std::vector<std::future<TestResult>> futures;
323  for (const Task &task : tasks) {
324  futures.push_back(pool.async([this, task]() {
325  return check_one(task.op, task.name, task.vector_width, task.expr);
326  }));
327  }
328 
329  bool success = true;
330  for (auto &f : futures) {
331  const TestResult &result = f.get();
332  std::cout << result.op << "\n";
333  if (!result.error_msg.empty()) {
334  std::cerr << result.error_msg;
335  success = false;
336  }
337  }
338 
339  return success;
340  }
341 
342 private:
343  size_t num_threads;
344  const Halide::Var x{"x"}, y{"y"};
345 };
346 } // namespace Halide
347 #endif // SIMD_OP_CHECK_H
A Halide::Buffer is a named shared reference to a Halide::Runtime::Buffer.
Definition: Buffer.h:115
A halide function.
Definition: Func.h:681
void compile_to_assembly(const std::string &filename, const std::vector< Argument > &, const std::string &fn_name, const Target &target=get_target_from_environment())
Statically compile this function to text assembly equivalent to the object file generated by compile_...
Func & compute_root()
Compute all of this function once ahead of time.
Stage update(int idx=0)
Get a handle on an update step for the purposes of scheduling it.
void infer_input_bounds(const std::vector< int32_t > &sizes, const Target &target=get_jit_target_from_environment(), const ParamMap &param_map=ParamMap::empty_map())
For a given size of output, or a given output buffer, determine the bounds required of all unbound Im...
Func & vectorize(const VarOrRVar &var)
Mark a dimension to be computed all-at-once as a single vector.
Func & compute_at(const Func &f, const Var &var)
Compute this function as needed for each unique value of the given var for the given calling function...
Realization realize(std::vector< int32_t > sizes={}, const Target &target=Target(), const ParamMap &param_map=ParamMap::empty_map())
Evaluate this function over some rectangular domain and return the resulting buffer or buffers.
Func & bound(const Var &var, Expr min, Expr extent)
Statically declare that the range over which a function should be evaluated is given by the second an...
void compile_to(const std::map< Output, std::string > &output_files, const std::vector< Argument > &args, const std::string &fn_name, const Target &target=get_target_from_environment())
Compile and generate multiple target files with single call.
Func clone_in(const Func &f)
Similar to Func::in; however, instead of replacing the call to this Func with an identity Func that r...
An Image parameter to a halide pipeline.
Definition: ImageParam.h:23
A reference-counted handle to Halide's internal representation of a function.
Definition: Function.h:38
bool has_update_definition() const
Does this function have an update definition?
A base class for algorithms that need to recursively walk over the IR.
Definition: IRVisitor.h:19
virtual void visit(const IntImm *)
std::future< T > async(Func func, Args... args)
Definition: ThreadPool.h:117
static size_t num_processors_online()
Definition: ThreadPool.h:79
A multi-dimensional domain over which to iterate.
Definition: RDom.h:193
RVar x
Direct access to the first four dimensions of the reduction domain.
Definition: RDom.h:337
RVar y
Definition: RDom.h:337
A reduction variable represents a single dimension of a reduction domain (RDom).
Definition: RDom.h:29
A Realization is a vector of references to existing Buffer objects.
Definition: Realization.h:21
size_t get_num_threads() const
Definition: simd_op_check.h:63
virtual void compile_and_check(Func error, const std::string &op, const std::string &name, int vector_width, std::ostringstream &error_msg)
Definition: simd_op_check.h:98
const std::vector< Argument > arg_types
Definition: simd_op_check.h:44
std::string output_directory
Definition: simd_op_check.h:25
virtual void setup_images()
void set_seed(int seed)
Definition: simd_op_check.h:59
virtual void add_tests()=0
bool wildcard_match(const std::string &p, const std::string &str) const
virtual bool test_all()
bool wildcard_search(const std::string &p, const std::string &str) const
bool wildcard_match(const char *p, const char *str) const
virtual ~SimdOpCheckTest()=default
SimdOpCheckTest(const Target t, int w, int h)
Definition: simd_op_check.h:48
void check(std::string op, int vector_width, Expr e)
const std::vector< ImageParam > image_params
Definition: simd_op_check.h:43
TestResult check_one(const std::string &op, const std::string &name, int vector_width, Expr e)
void set_num_threads(size_t n)
Definition: simd_op_check.h:67
virtual bool can_run_code() const
Definition: simd_op_check.h:71
std::vector< Task > tasks
Definition: simd_op_check.h:26
A Halide variable, to be used when defining functions.
Definition: Var.h:19
std::map< Output, const OutputInfo > get_output_info(const Target &target)
std::string get_test_tmp_dir()
Return the path to a directory that can be safely written to when running tests; the contents directo...
This file defines the class FunctionDAG, which is our representation of a Halide pipeline,...
Target get_host_target()
Return the target corresponding to the host machine.
Type BFloat(int bits, int lanes=1)
Construct a floating-point type in the bfloat format.
Definition: Type.h:513
Type UInt(int bits, int lanes=1)
Constructing an unsigned integer type.
Definition: Type.h:503
Type Float(int bits, int lanes=1)
Construct a floating-point type.
Definition: Type.h:508
Expr maximum(Expr, const std::string &s="maximum")
Type Int(int bits, int lanes=1)
Constructing a signed integer type.
Definition: Type.h:498
Expr absd(Expr a, Expr b)
Return the absolute difference between two values.
char * buf
Definition: printer.h:32
unsigned __INT32_TYPE__ uint32_t
A fragment of Halide syntax.
Definition: Expr.h:256
A function call.
Definition: IR.h:464
@ Halide
A call to a Func.
Definition: IR.h:471
FunctionPtr func
Definition: IR.h:598
CallType call_type
Definition: IR.h:475
void accept(IRVisitor *v) const
Dispatch to the correct visitor method for this node.
Definition: Expr.h:190
A struct representing a target machine and os to generate code for.
Definition: Target.h:19
enum Halide::Target::Arch arch
bool has_feature(Feature f) const
int bits
The bit-width of the target machine.
Definition: Target.h:51
enum Halide::Target::OS os
std::string to_string() const
Convert the Target into a string form that can be reconstituted by merge_string(),...
Target without_feature(Feature f) const
Return a copy of the target with the given feature cleared.
Feature
Optional features a target can have.
Definition: Target.h:57
@ NoBoundsQuery
Definition: Target.h:61
@ DisableLLVMLoopOpt
Definition: Target.h:120
@ POWER_ARCH_2_07
Definition: Target.h:71
Target with_feature(Feature f) const
Return a copy of the target with the given feature set.
std::string op
Definition: simd_op_check.h:16
std::string name
Definition: simd_op_check.h:17
std::string error_msg
Definition: simd_op_check.h:12
Types in the halide type system.
Definition: Type.h:269