Halide 22.0.0
Halide compiler and libraries
Loading...
Searching...
No Matches
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#include "halide_thread_pool.h"
7#include "test_sharding.h"
8
9#include <fstream>
10#include <iostream>
11
12namespace {
13
14using namespace Halide;
15
16// Some exprs of each type to use in checked expressions. These will turn
17// into loads to thread-local image params.
18Expr input(const Type &t, const Expr &arg) {
19 return Internal::Call::make(t, "input", {arg}, Internal::Call::Extern);
20}
21Expr in_f16(const Expr &arg) {
22 return input(Float(16), arg);
23}
24Expr in_bf16(const Expr &arg) {
25 return input(BFloat(16), arg);
26}
27Expr in_f32(const Expr &arg) {
28 return input(Float(32), arg);
29}
30Expr in_f64(const Expr &arg) {
31 return input(Float(64), arg);
32}
33Expr in_i8(const Expr &arg) {
34 return input(Int(8), arg);
35}
36Expr in_i16(const Expr &arg) {
37 return input(Int(16), arg);
38}
39Expr in_i32(const Expr &arg) {
40 return input(Int(32), arg);
41}
42Expr in_i64(const Expr &arg) {
43 return input(Int(64), arg);
44}
45Expr in_u8(const Expr &arg) {
46 return input(UInt(8), arg);
47}
48Expr in_u16(const Expr &arg) {
49 return input(UInt(16), arg);
50}
51Expr in_u32(const Expr &arg) {
52 return input(UInt(32), arg);
53}
54Expr in_u64(const Expr &arg) {
55 return input(UInt(64), arg);
56}
57} // namespace
58
59namespace Halide {
60struct TestResult {
61 std::string op;
62 std::string error_msg;
63};
64
65struct Task {
66 std::string op;
67 std::string name;
70};
71
73public:
74 static constexpr int max_i8 = 127;
75 static constexpr int max_i16 = 32767;
76 static constexpr int max_i32 = 0x7fffffff;
77 static constexpr int max_u8 = 255;
78 static constexpr int max_u16 = 65535;
79 const Expr max_u32 = UInt(32).max();
80
81 std::string filter{"*"};
83 std::vector<Task> tasks;
84
86
87 int W;
88 int H;
89
91
93
101 virtual ~SimdOpCheckTest() = default;
102
103 void set_seed(int seed) {
104 rng_seed = seed;
105 }
106
107 virtual bool can_run_code() const {
110 }
111 // If we can (target matches host), run the error checking Halide::Func.
113 bool can_run_the_code =
114 (target.arch == host_target.arch &&
115 target.bits == host_target.bits &&
116 target.os == host_target.os);
117 // A bunch of feature flags also need to match between the
118 // compiled code and the host in order to run the code.
119 for (Target::Feature f : {
153 }) {
154 if (target.has_feature(f) != host_target.has_feature(f)) {
155 can_run_the_code = false;
156 }
157 }
158 return can_run_the_code;
159 }
160
161 virtual void compile_and_check(Func error,
162 const std::string &op,
163 const std::string &name,
164 int vector_width,
165 const std::vector<Argument> &arg_types,
166 std::ostringstream &error_msg) {
167 std::string fn_name = "test_" + name;
168 std::string file_name = output_directory + fn_name;
169
171 std::map<OutputFileType, std::string> outputs = {
175 };
176 error.compile_to(outputs, arg_types, fn_name, target);
177
178 std::ifstream asm_file;
179 asm_file.open(file_name + ".s");
180
181 bool found_it = false;
182
183 std::ostringstream msg;
184 msg << op << " did not generate for target=" << get_run_target().to_string() << " vector_width=" << vector_width << ". Instead we got:\n";
185
186 std::string line;
187 while (getline(asm_file, line)) {
188 msg << line << "\n";
189
190 // Check for the op in question
191 found_it |= wildcard_search(op, line) && !wildcard_search("_" + op, line);
192 }
193
194 if (!found_it) {
195 error_msg << "Failed: " << msg.str() << "\n";
196 }
197
198 asm_file.close();
199 }
200
201 // Check if pattern p matches str, allowing for wildcards (*).
202 bool wildcard_match(const char *p, const char *str) const {
203 // Match all non-wildcard characters.
204 while (*p && *str && *p == *str && *p != '*') {
205 str++;
206 p++;
207 }
208
209 if (!*p) {
210 return *str == 0;
211 } else if (*p == '*') {
212 p++;
213 do {
214 if (wildcard_match(p, str)) {
215 return true;
216 }
217 } while (*str++);
218 } else if (*p == ' ') { // ignore whitespace in pattern
219 p++;
220 if (wildcard_match(p, str)) {
221 return true;
222 }
223 } else if (*str == ' ') { // ignore whitespace in string
224 str++;
225 if (wildcard_match(p, str)) {
226 return true;
227 }
228 }
229 return !*p;
230 }
231
232 bool wildcard_match(const std::string &p, const std::string &str) const {
233 return wildcard_match(p.c_str(), str.c_str());
234 }
235
236 // Check if a substring of str matches a pattern p.
237 bool wildcard_search(const std::string &p, const std::string &str) const {
238 return wildcard_match("*" + p + "*", str);
239 }
240
247
248 TestResult check_one(const std::string &op, const std::string &name, int vector_width, Expr e) {
249 std::ostringstream error_msg;
250
251 // Map the input calls in the Expr to loads to local
252 // imageparams, so that we're not sharing state across threads.
253 std::vector<ImageParam> image_params{
254 ImageParam{Float(32), 1, "in_f32"},
255 ImageParam{Float(64), 1, "in_f64"},
256 ImageParam{Float(16), 1, "in_f16"},
257 ImageParam{BFloat(16), 1, "in_bf16"},
258 ImageParam{Int(8), 1, "in_i8"},
259 ImageParam{UInt(8), 1, "in_u8"},
260 ImageParam{Int(16), 1, "in_i16"},
261 ImageParam{UInt(16), 1, "in_u16"},
262 ImageParam{Int(32), 1, "in_i32"},
263 ImageParam{UInt(32), 1, "in_u32"},
264 ImageParam{Int(64), 1, "in_i64"},
265 ImageParam{UInt(64), 1, "in_u64"}};
266
267 for (auto &p : image_params) {
269 p.set_host_alignment(alignment_bytes);
270 const int alignment = alignment_bytes / p.type().bytes();
271 p.dim(0).set_min((p.dim(0).min() / alignment) * alignment);
272 }
273
274 std::vector<Argument> arg_types(image_params.begin(), image_params.end());
275
278
279 Expr visit(const Internal::Call *op) override {
280 if (op->name == "input") {
281 for (auto &p : image_params) {
282 if (p.type() == op->type) {
283 return p(mutate(op->args[0]));
284 }
285 }
286 } else if (op->call_type == Internal::Call::Halide && !op->func.weak) {
288 f.mutate(this);
289 }
291 }
292 const std::vector<ImageParam> &image_params;
293
294 public:
295 HookUpImageParams(const std::vector<ImageParam> &image_params)
297 }
299 e = hook_up_image_params.mutate(e);
300
303 void visit(const Internal::Call *op) override {
306 if (f.has_update_definition() &&
307 f.update(0).schedule().rvars().size() > 0) {
309 result = true;
310 }
311 }
312 IRVisitor::visit(op);
313 }
314
315 public:
317 bool result = false;
320
321 // Define a vectorized Halide::Func that uses the pattern.
322 Halide::Func f(name);
323 f(x, y) = e;
324 f.bound(x, 0, W).vectorize(x, vector_width);
325 f.compute_root();
326
327 // Include a scalar version
328 Halide::Func f_scalar("scalar_" + name);
329 f_scalar(x, y) = e;
330
331 if (has_inline_reduction.result) {
332 // If there's an inline reduction, we want to vectorize it
333 // over the RVar.
334 Var xo, xi;
335 RVar rxi;
336 Func g{has_inline_reduction.inline_reduction};
337
338 // Do the reduction separately in f_scalar
339 g.clone_in(f_scalar);
340
341 g.compute_at(f, x)
342 .update()
343 .split(x, xo, xi, vector_width)
344 .atomic(true)
345 .vectorize(g.rvars()[0])
346 .vectorize(xi);
347 }
348
349 // We'll check over H rows, but we won't let the pipeline know H
350 // statically, as that can trigger some simplifications that change
351 // instruction selection.
352 Param<int> rows;
353 rows.set(H);
354 arg_types.push_back(rows);
355
356 // The output to the pipeline is the maximum absolute difference as a double.
357 RDom r_check(0, W, 0, rows);
358 Halide::Func error("error_" + name);
360
361 compile_and_check(error, op, name, vector_width, arg_types, error_msg);
362
364 if (can_run_the_code) {
366
367 // Make some unallocated input buffers
368 std::vector<Runtime::Buffer<>> inputs(image_params.size());
369
370 std::vector<Argument> args(image_params.size() + 1);
371 for (size_t i = 0; i < image_params.size(); i++) {
372 args[i] = image_params[i];
373 inputs[i] = Runtime::Buffer<>(args[i].type, nullptr, 0);
374 }
375 args.back() = rows;
376
377 auto callable = error.compile_to_callable(args, run_target);
378
380 output(0) = 1; // To ensure we'll fail if it's never written to
381
382 // Do the bounds query call
383 assert(inputs.size() == 12);
384 (void)callable(inputs[0], inputs[1], inputs[2], inputs[3],
385 inputs[4], inputs[5], inputs[6], inputs[7],
386 inputs[8], inputs[9], inputs[10], inputs[11],
387 H, output);
388
389 std::mt19937 rng;
390 rng.seed(rng_seed);
391
392 // Allocate the input buffers and fill them with noise
393 for (size_t i = 0; i < inputs.size(); i++) {
394 if (inputs[i].size_in_bytes()) {
395 inputs[i].allocate();
396
397 Type t = inputs[i].type();
398 // For floats/doubles, we only use values that aren't
399 // subject to rounding error that may differ between
400 // vectorized and non-vectorized versions
401 if (t == Float(32)) {
402 inputs[i].as<float>().for_each_value([&](float &f) { f = (rng() & 0xfff) / 8.0f - 0xff; });
403 } else if (t == Float(64)) {
404 inputs[i].as<double>().for_each_value([&](double &f) { f = (rng() & 0xfff) / 8.0 - 0xff; });
405 } else if (t == Float(16)) {
406 inputs[i].as<float16_t>().for_each_value([&](float16_t &f) { f = float16_t((rng() & 0xff) / 8.0f - 0xf); });
407 } else if (t == BFloat(16)) {
408 inputs[i].as<bfloat16_t>().for_each_value([&](bfloat16_t &f) { f = bfloat16_t((rng() & 0xff) / 8.0f - 0xf); });
409 } else {
411 // Random bits is fine, but in the 32-bit int case we
412 // never use the top four bits, to avoid signed integer
413 // overflow.
414 const uint32_t mask = (t == Int(32)) ? 0x0fffffffU : 0xffffffffU;
415 for (uint32_t *ptr = (uint32_t *)inputs[i].data();
416 ptr != (uint32_t *)inputs[i].data() + inputs[i].size_in_bytes() / 4;
417 ptr++) {
418 *ptr = ((uint32_t)rng()) & mask;
419 }
420 }
421 }
422 }
423
424 // Do the real call
425 (void)callable(inputs[0], inputs[1], inputs[2], inputs[3],
426 inputs[4], inputs[5], inputs[6], inputs[7],
427 inputs[8], inputs[9], inputs[10], inputs[11],
428 H, output);
429
430 double e = output(0);
431 // Use a very loose tolerance for floating point tests. The
432 // kinds of bugs we're looking for are codegen bugs that
433 // return the wrong value entirely, not floating point
434 // accuracy differences between vectors and scalars.
435 if (e > 0.001) {
436 error_msg << "The vector and scalar versions of " << name << " disagree. Maximum error: " << e << "\n";
437
438 std::string error_filename = output_directory + "error_" + name + ".s";
439 error.compile_to_assembly(error_filename, arg_types, target);
440
441 std::ifstream error_file;
443
444 error_msg << "Error assembly: \n";
445 std::string line;
446 while (getline(error_file, line)) {
447 error_msg << line << "\n";
448 }
449
450 error_file.close();
451 }
452 }
453
454 return {op, error_msg.str()};
455 }
456
457 void check(std::string op, int vector_width, Expr e) {
458 // Make a name for the test by uniquing then sanitizing the op name
459 std::string name = "op_" + op;
460 for (size_t i = 0; i < name.size(); i++) {
461 if (!isalnum(name[i])) name[i] = '_';
462 }
463
464 name += "_" + std::to_string(tasks.size());
465
466 // Bail out after generating the unique_name, so that names are
467 // unique across different processes and don't depend on filter
468 // settings.
469 if (!wildcard_match(filter, op)) return;
470
471 tasks.emplace_back(Task{op, name, vector_width, e});
472 }
473 virtual void add_tests() = 0;
474 virtual int image_param_alignment() {
475 return 16;
476 }
477
478 virtual bool use_multiple_threads() const {
479 return true;
480 }
481
482 virtual bool test_all() {
483 /* First add some tests based on the target */
484 add_tests();
485
486 // Remove irrelevant noise from output
488 const std::string run_target_str = run_target.to_string();
489
491
492 Halide::Tools::ThreadPool<TestResult> pool(
494 Halide::Tools::ThreadPool<TestResult>::num_processors_online() :
495 1);
496 std::vector<std::future<TestResult>> futures;
497
498 for (size_t t = 0; t < tasks.size(); t++) {
499 if (!sharder.should_run(t)) continue;
500 const auto &task = tasks.at(t);
501 futures.push_back(pool.async([&]() {
502 return check_one(task.op, task.name, task.vector_width, task.expr);
503 }));
504 }
505
506 for (auto &f : futures) {
507 auto result = f.get();
508 constexpr int tabstop = 32;
509 const int spaces = std::max(1, tabstop - (int)result.op.size());
510 std::cout << result.op << std::string(spaces, ' ') << "(" << run_target_str << ")\n";
511 if (!result.error_msg.empty()) {
512 std::cerr << result.error_msg;
513 // The thread-pool destructor will block until in-progress tasks
514 // are done, and then will discard any tasks that haven't been
515 // launched yet.
516 return false;
517 }
518 }
519
520 return true;
521 }
522
523 template<typename SIMDOpCheckT>
524 static int main(int argc, char **argv, const std::vector<Target> &targets_to_test) {
525 Target host = get_host_target();
526 std::cout << "host is: " << host << "\n";
527
528 const int seed = argc > 2 ? atoi(argv[2]) : time(nullptr);
529 std::cout << "simd_op_check test seed: " << seed << "\n";
530
531 for (const auto &t : targets_to_test) {
532 if (!t.supported()) {
533 std::cout << "[SKIP] Unsupported target: " << t << "\n";
534 return 0;
535 }
536 SIMDOpCheckT test(t);
537
538 if (!t.supported()) {
539 std::cout << "Halide was compiled without support for " << t.to_string() << ". Skipping.\n";
540 continue;
541 }
542
543 if (argc > 1) {
544 test.filter = argv[1];
545 }
546
547 if (getenv("HL_SIMD_OP_CHECK_FILTER")) {
548 test.filter = getenv("HL_SIMD_OP_CHECK_FILTER");
549 }
550
551 test.set_seed(seed);
552
553 if (argc > 2) {
554 // Don't forget: if you want to run the standard tests to a specific output
555 // directory, you'll need to invoke with the first arg enclosed
556 // in quotes (to avoid it being wildcard-expanded by the shell):
557 //
558 // correctness_simd_op_check "*" /path/to/output
559 //
560 test.output_directory = argv[2];
561 }
562
563 bool success = test.test_all();
564
565 // Compile a runtime for this target, for use in the static test.
566 compile_standalone_runtime(test.output_directory + "simd_op_check_runtime.o", test.target);
567
568 if (!success) {
569 return 1;
570 }
571 }
572
573 std::cout << "Success!\n";
574 return 0;
575 }
576
577private:
578 const Halide::Var x{"x"}, y{"y"};
579};
580
581} // namespace Halide
582
583#endif // SIMD_OP_CHECK_H
A halide function.
Definition Func.h:706
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.
Callable compile_to_callable(const std::vector< Argument > &args, const Target &target=get_jit_target_from_environment())
Eagerly jit compile the function to machine code and return a callable struct that behaves like a fun...
void compile_to(const std::map< OutputFileType, 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 & vectorize(const VarOrRVar &var)
Mark a dimension to be computed all-at-once as a single vector.
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...
An Image parameter to a halide pipeline.
Definition ImageParam.h:23
const StageSchedule & schedule() const
Get the default (no-specialization) stage-specific schedule associated with this definition.
A reference-counted handle to Halide's internal representation of a function.
Definition Function.h:39
bool has_update_definition() const
Does this function have an update definition?
void mutate(IRMutator *mutator)
Accept a mutator to mutator all of the definitions and arguments of this function.
Definition & update(int idx=0)
Get a mutable handle to this function's update definition at index 'idx'.
A base class for passes over the IR which modify it (e.g.
Definition IRMutator.h:26
virtual Expr visit(const IntImm *)
A base class for algorithms that need to recursively walk over the IR.
Definition IRVisitor.h:19
virtual void visit(const IntImm *)
const std::vector< ReductionVariable > & rvars() const
RVars of reduction domain associated with this schedule if there is any.
A scalar parameter to a halide pipeline.
Definition Param.h:22
HALIDE_NO_USER_CODE_INLINE void set(const SOME_TYPE &val)
Set the current value of this parameter.
Definition Param.h:174
A multi-dimensional domain over which to iterate.
Definition RDom.h:193
A reduction variable represents a single dimension of a reduction domain (RDom).
Definition RDom.h:29
A templated Buffer class that wraps halide_buffer_t and adds functionality.
static Buffer< T, Dims, InClassDimStorage > make_scalar()
Make a zero-dimensional Buffer.
static constexpr int max_u8
static constexpr int max_i32
virtual bool use_multiple_threads() const
virtual void add_tests()=0
virtual int image_param_alignment()
bool wildcard_match(const std::string &p, const std::string &str) const
static constexpr int max_i8
static constexpr int max_u16
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)
void check(std::string op, int vector_width, Expr e)
Target get_run_target() const
static int main(int argc, char **argv, const std::vector< Target > &targets_to_test)
static constexpr int max_i16
TestResult check_one(const std::string &op, const std::string &name, int vector_width, Expr e)
virtual bool can_run_code() const
std::vector< Task > tasks
virtual void compile_and_check(Func error, const std::string &op, const std::string &name, int vector_width, const std::vector< Argument > &arg_types, std::ostringstream &error_msg)
A Halide variable, to be used when defining functions.
Definition Var.h:19
std::map< OutputFileType, 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:556
Type UInt(int bits, int lanes=1)
Constructing an unsigned integer type.
Definition Type.h:546
Type Float(int bits, int lanes=1)
Construct a floating-point type.
Definition Type.h:551
Expr maximum(Expr, const std::string &s="maximum")
Type Int(int bits, int lanes=1)
Constructing a signed integer type.
Definition Type.h:541
Expr absd(Expr a, Expr b)
Return the absolute difference between two values.
void compile_standalone_runtime(const std::string &object_filename, const Target &t)
Create an object file containing the Halide runtime for a given target.
Internal::ConstantInterval cast(Type t, const Internal::ConstantInterval &a)
Cast operators for ConstantIntervals.
int atoi(const char *)
unsigned __INT32_TYPE__ uint32_t
char * getenv(const char *)
A fragment of Halide syntax.
Definition Expr.h:258
A function call.
Definition IR.h:490
@ Extern
A call to an external C-ABI function, possibly with side-effects.
Definition IR.h:494
@ Halide
A call to a Func.
Definition IR.h:497
std::string name
Definition IR.h:491
FunctionPtr func
Definition IR.h:690
CallType call_type
Definition IR.h:501
std::vector< Expr > args
Definition IR.h:492
static Expr make(Type type, IntrinsicOp op, const std::vector< Expr > &args, CallType call_type, FunctionPtr func=FunctionPtr(), int value_index=0, const Buffer<> &image=Buffer<>(), Parameter param=Parameter())
int64_t min
The lower and upper bound of the interval.
void accept(IRVisitor *v) const
Dispatch to the correct visitor method for this node.
Definition Expr.h:192
static bool can_jit_target(const Target &target)
If the given target can be executed via the wasm executor, return true.
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:50
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:84
@ AVX512_Cannonlake
Definition Target.h:135
@ AVX512_SapphireRapids
Definition Target.h:136
Target with_feature(Feature f) const
Return a copy of the target with the given feature set.
std::string op
std::string name
std::string error_msg
Types in the halide type system.
Definition Type.h:283
HALIDE_ALWAYS_INLINE bool is_int_or_uint() const
Is this type an integer type of any sort?
Definition Type.h:447
Expr max() const
Return an expression which is the maximum value of this type.
Class that provides a type that implements half precision floating point (IEEE754 2008 binary16) in s...
Definition Float16.h:17