1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
|
import re
from contextlib import contextmanager
import halide as hl
@contextmanager
def assert_throws(exn, msg):
try:
yield
except Exception as e:
if not isinstance(e, exn):
raise
if not re.search(msg, str(e)):
raise AssertionError(
f"Expected {exn.__name__} with message matching /{msg}/, but got: {type(e).__name__} '{e}'"
)
else:
raise AssertionError(
f"Expected {exn.__name__} to be raised, but no exception occurred."
)
def test_compiletime_error():
x = hl.Var("x")
y = hl.Var("y")
f = hl.Func("f")
f[x, y] = hl.u16(x + y)
# Deliberate type-mismatch error
buf = hl.Buffer(hl.UInt(8), [2, 2])
with assert_throws(
hl.HalideError,
"Error: Output buffer f has type uint16 but type of the buffer passed in is uint8",
):
f.realize(buf)
def test_runtime_error():
x = hl.Var("x")
f = hl.Func("f")
f[x] = hl.u8(x)
f.bound(x, 0, 1)
# Deliberate runtime error
buf = hl.Buffer(hl.UInt(8), [10])
with assert_throws(
hl.HalideError,
r"Error: Bounds given for f(\$\d+)? in x \(from 0 to 0\) do not cover required region \(from 0 to 9\)",
):
f.realize(buf)
def test_misused_and():
x = hl.Var("x")
y = hl.Var("y")
f = hl.Func("f")
with assert_throws(ValueError, "cannot be converted to a bool"):
f[x, y] = hl.print_when(x == 0 and y == 0, 0, "x=", x, "y=", y)
f.realize([10, 10])
def test_misused_or():
x = hl.Var("x")
y = hl.Var("y")
f = hl.Func("f")
with assert_throws(ValueError, "cannot be converted to a bool"):
f[x, y] = hl.print_when(x == 0 or y == 0, 0, "x=", x, "y=", y)
f.realize([10, 10])
def test_basics():
input = hl.ImageParam(hl.UInt(16), 2, "input")
x, y = hl.Var("x"), hl.Var("y")
blur_x = hl.Func("blur_x")
blur_xx = hl.Func("blur_xx")
blur_y = hl.Func("blur_y")
yy = hl.i32(1)
assert yy.type() == hl.Int(32)
z = x + 1
input[x, y]
input[0, 0]
input[z, y]
input[x + 1, y]
input[x, y] + input[x + 1, y]
if False:
aa = blur_x[x, y]
bb = blur_x[x, y + 1]
aa + bb
blur_x[x, y] + blur_x[x, y + 1]
(input[x, y] + input[x + 1, y]) / 2
blur_x[x, y]
blur_xx[x, y] = input[x, y]
blur_x[x, y] = (input[x, y] + input[x + 1, y] + input[x + 2, y]) / 3
blur_y[x, y] = (blur_x[x, y] + blur_x[x, y + 1] + blur_x[x, y + 2]) / 3
xi, yi = hl.Var("xi"), hl.Var("yi")
blur_y.tile(x, y, xi, yi, 8, 4).parallel(y).vectorize(xi, 8)
blur_x.compute_at(blur_y, x).vectorize(x, 8)
blur_y.compile_jit()
def test_basics2():
input = hl.ImageParam(hl.Float(32), 3, "input")
hl.Param(hl.Float(32), "r_sigma", 0.1)
s_sigma = 8
x = hl.Var("x")
y = hl.Var("y")
hl.Var("z")
hl.Var("c")
# Add a boundary condition
clamped = hl.Func("clamped")
clamped[x, y] = input[
hl.clamp(x, 0, input.width() - 1), hl.clamp(y, 0, input.height() - 1), 0
]
# Construct the bilateral grid
r = hl.RDom([(0, s_sigma), (0, s_sigma)], "r")
clamped[x * s_sigma, y * s_sigma]
clamped[x * s_sigma * hl.i32(1), y * s_sigma * hl.i32(1)]
clamped[x * s_sigma - hl.i32(s_sigma // 2), y * s_sigma - hl.i32(s_sigma // 2)]
clamped[x * s_sigma - s_sigma // 2, y * s_sigma - s_sigma // 2]
clamped[x * s_sigma + r.x - s_sigma // 2, y * s_sigma + r.y - s_sigma // 2]
with assert_throws(hl.HalideError, "Implicit cast from float32 to int"):
clamped[x * s_sigma - s_sigma / 2, y * s_sigma - s_sigma / 2]
def test_basics3():
input = hl.ImageParam(hl.Float(32), 3, "input")
r_sigma = hl.Param(
hl.Float(32), "r_sigma", 0.1
) # Value needed if not generating an executable
s_sigma = 8 # This is passed during code generation in the C++ version
x = hl.Var("x")
y = hl.Var("y")
z = hl.Var("z")
c = hl.Var("c")
# Add a boundary condition
clamped = hl.Func("clamped")
clamped[x, y] = input[
hl.clamp(x, 0, input.width() - 1), hl.clamp(y, 0, input.height() - 1), 0
]
# Construct the bilateral grid
r = hl.RDom([(0, s_sigma), (0, s_sigma)], "r")
val = clamped[x * s_sigma + r.x - s_sigma // 2, y * s_sigma + r.y - s_sigma // 2]
val = hl.clamp(val, 0.0, 1.0)
zi = hl.i32((val / r_sigma) + 0.5)
histogram = hl.Func("histogram")
histogram[x, y, z, c] = 0.0
ss = hl.select(c == 0, val, 1.0)
left = histogram[x, y, zi, c]
left += 5
left += ss
def test_basics4():
# Test for f[g[r]] = ...
# See https://github.com/halide/Halide/issues/4285
x = hl.Var("x")
f = hl.Func("f")
g = hl.Func("g")
g[x] = 1
f[x] = 0.0
r = hl.RDom([(0, 100)])
f[g[r]] = 2.5
f.compute_root()
f.compile_jit()
def test_basics5():
# Test Func.in_()
x, y = hl.Var("x"), hl.Var("y")
f = hl.Func("f")
g = hl.Func("g")
h = hl.Func("h")
f[x, y] = y
r = hl.RDom([(0, 100)])
g[x] = 0
g[x] += f[x, r]
h[x] = 0
h[x] += f[x, r]
f.in_(g).compute_at(g, x)
f.in_(h).compute_at(h, x)
g.compute_root()
h.compute_root()
p = hl.Pipeline([g, h])
p.compile_jit()
def test_float_or_int():
x = hl.Var("x")
i32, f32 = hl.Int(32), hl.Float(32)
assert hl.Expr(x).type() == i32
assert (x * 2).type() == i32
assert (x / 2).type() == i32
assert ((x // 2) - 1 + 2 * (x % 2)).type() == i32
assert ((x / 2) - 1 + 2 * (x % 2)).type() == i32
assert (x / 2).type() == i32
assert (x / 2.0).type() == f32
assert (x // 2).type() == i32
assert ((x // 2) - 1).type() == i32
assert (x % 2).type() == i32
assert (2 * (x % 2)).type() == i32
assert ((x // 2) - 1 + 2 * (x % 2)).type() == i32
assert type(x) is hl.Var
assert (hl.Expr(x)).type() == i32
assert (hl.Expr(2.0)).type() == f32
assert (hl.Expr(2)).type() == i32
assert (x + 2).type() == i32
assert (2 + x).type() == i32
assert (hl.Expr(2) + hl.Expr(3)).type() == i32
assert (hl.Expr(2.0) + hl.Expr(3)).type() == f32
assert (hl.Expr(2) + 3.0).type() == f32
assert (hl.Expr(2) + 3).type() == i32
assert (hl.Expr(x) + 2).type() == i32
assert (2 + hl.Expr(x)).type() == i32
assert (2 * (x + 2)).type() == i32
assert (x + 0).type() == i32
assert (x % 2).type() == i32
assert (2 * x).type() == i32
assert (x * 2).type() == i32
assert (x * 2).type() == i32
assert (x % 2).type() == i32
assert ((x % 2) * 2).type() == i32
assert (2 * (x % 2)).type() == i32
assert ((x + 2) * 2).type() == i32
def test_operator_order():
x = hl.Var("x")
f = hl.Func("f")
x + 1
1 + x
f[x] = x**2
f[x] + 1
hl.Expr(1) + f[x]
1 + f[x]
def _check_is_u16(e):
assert e.type() == hl.UInt(16), e.type()
def test_int_promotion():
# Verify that (Exprlike op literal) correctly matches the type
# of the literal to the Exprlike (rather than promoting the result to int32).
# All types that use add_binary_operators() should be tested here.
x = hl.Var("x")
# All the binary ops are handled the same, so + is good enough
# Exprlike = FuncRef
f = hl.Func("f")
f[x] = hl.u16(x)
_check_is_u16(f[x] + 2)
_check_is_u16(2 + f[x])
# Exprlike = Expr
e = hl.Expr(f[x])
_check_is_u16(e + 2)
_check_is_u16(2 + e)
# Exprlike = Param
p = hl.Param(hl.UInt(16))
_check_is_u16(p + 2)
_check_is_u16(2 + p)
# Exprlike = RDom/RVar
# Exprlike = Var
# (skipped, since these can never have values of any type other than int32)
def test_vector_tile():
# Test Func.tile() and Stage.tile() with vector arguments
x, y, z = [hl.Var(c) for c in "xyz"]
xi, yi = hl.vars("xi yi")
xo, yo = hl.vars("xo yo")
f = hl.Func("f")
g = hl.Func("g")
hl.Func("h")
f[x, y] = y
f[x, y] += x
g[x, y, z] = x + y
g[x, y, z] += z
f.tile([x, y], [xo, yo], [x, y], [8, 8])
f.update(0).tile([x, y], [xo, yo], [xi, yi], [8, 8])
g.tile([x, y], [xo, yo], [x, y], [8, 8], hl.TailStrategy.RoundUp)
g.update(0).tile([x, y], [xo, yo], [xi, yi], [8, 8], hl.TailStrategy.GuardWithIf)
p = hl.Pipeline([f, g])
p.compile_jit()
def test_scalar_funcs():
input = hl.ImageParam(hl.UInt(16), 0, "input")
f = hl.Func("f")
g = hl.Func("g")
input[()]
(input[()] + input[()]) / 2
f[()]
g[()]
f[()] = (input[()] + input[()] + input[()]) / 3
g[()] = (f[()] + f[()] + f[()]) / 3
g.compile_jit()
def test_bool_conversion():
x = hl.Var("x")
f = hl.Func("f")
f[x] = x
# Verify that this doesn't fail with 'Argument passed to specialize must be of type bool'
f.compute_root().specialize(True)
def test_typed_funcs():
x = hl.Var("x")
y = hl.Var("y")
f = hl.Func("f")
assert not f.defined()
with assert_throws(hl.HalideError, "it is undefined"):
assert f.type() == hl.Int(32)
with assert_throws(hl.HalideError, "it is undefined"):
assert f.outputs() == 0
with assert_throws(hl.HalideError, "it is undefined"):
assert f.dimensions() == 0
f = hl.Func(hl.Int(32), 2, "f")
assert not f.defined()
assert f.type() == hl.Int(32)
assert f.types() == [hl.Int(32)]
assert f.outputs() == 1
assert f.dimensions() == 2
f = hl.Func([hl.Int(32), hl.Float(64)], 3, "f")
assert not f.defined()
with assert_throws(hl.HalideError, "it returns a Tuple"):
assert f.type() == hl.Int(32)
assert f.types() == [hl.Int(32), hl.Float(64)]
assert f.outputs() == 2
assert f.dimensions() == 3
f = hl.Func(hl.Int(32), 1, "f")
with assert_throws(
hl.HalideError,
"is constrained to have exactly 1 dimensions, but is defined with 2 dimensions",
):
f[x, y] = hl.i32(0)
f.realize([10, 10])
f = hl.Func(hl.Int(32), 2, "f")
with assert_throws(
hl.HalideError,
"is constrained to only hold values of type int32 but is defined with values of type int16",
):
f[x, y] = hl.i16(0)
f.realize([10, 10])
f = hl.Func((hl.Int(32), hl.Float(32)), 2, "f")
with assert_throws(
hl.HalideError,
r"is constrained to only hold values of type \(int32, float32\) "
r"but is defined with values of type \(int16, float64\)",
):
f[x, y] = (hl.i16(0), hl.f64(0))
def test_requirements():
delta = hl.Param(hl.Int(32), "delta")
x = hl.Var("x")
f = hl.Func("f_requirements")
f[x] = x + delta
# Add a requirement
p = hl.Pipeline([f])
p.add_requirement(delta != 0) # error_args omitted
p.add_requirement(delta > 0, "negative values are bad", delta)
delta.set(1)
p.realize([10])
with assert_throws(hl.HalideError, r"Requirement Failed: \(false\)"):
delta.set(0)
p.realize([10])
with assert_throws(
hl.HalideError, r"Requirement Failed: \(false\) negative values are bad -1"
):
delta.set(-1)
p.realize([10])
def test_implicit_convert_int64():
assert (hl.i32(0) + 0x7FFFFFFF).type() == hl.Int(32)
assert (hl.i32(0) + (0x7FFFFFFF + 1)).type() == hl.Int(64)
def test_pow_rpow():
two = hl.Expr(2.0)
x = hl.Var("x")
for three in (3, hl.Expr(3)):
f = hl.Func("f")
f[x] = 0.0
f[0] = two**three
f[1] = three**two
assert list(f.realize([2])) == [8.0, 9.0]
def test_unevaluated_funcref():
x = hl.Var("x")
f = hl.Func("f")
# `ref` is a FuncRef
ref = f[x]
# Because the func `f` did not have a pure definition, `ref` is set to an
# UnevaluatedFuncRefExpr with RHS `1` and operator `+`. In C++, this would
# immediately create a new update stage (and the associated pure definition).
ref += 1
with assert_throws(
TypeError,
r"unsupported operand type\(s\) for \+=: 'halide.halide_\._UnevaluatedFuncRefExpr' and 'int'",
):
# We've gone too far... UnevaluatedFuncRefExpr doesn't define any binary
# operators. This does not implicitly cast to Expr.
ref += 1
# Since `ref` is still an unevaluated FuncRef, this line will cause the creation
# of an update stage along with an implicit pure definition (because the operation
# is +, the initialization will be to 0).
f[x] = ref
with assert_throws(
hl.HalideError,
r"Cannot use an unevaluated reference to 'f(\$\d+)?' to define an update when a pure definition already exists.",
):
# Trying to do this twice is asking for problems, so we don't allow it.
f[x] = ref
# Check that defining the first update stage worked.
assert f.realize([1])[0] == 1
with assert_throws(
hl.HalideError,
r"Cannot use an unevaluated reference to 'f\$\d+' to define an update at a different location.",
):
# We also can't use the unevaluated ref to define an update in a
# different func (even if they look like they have the same name)
f = hl.Func("f")
f[x] = ref
# A few more tests that check the results of various equivalent-looking rewrites.
f = hl.Func("f")
ref = f[x]
ref += 1
f[x] = ref
assert f.realize([1])[0] == 1
f = hl.Func("f")
ref = f[x] + 1
f[x] = ref
assert f.realize([1])[0] == 1
f = hl.Func("f")
f[x] = f[x] + 1
assert f.realize([1])[0] == 1
f = hl.Func("f")
f[x] += 1
assert f.realize([1])[0] == 1
with assert_throws(
hl.HalideError,
r"Error: Can't call Func \"f(\$\d+)?\" because it has not yet been defined\.",
):
# This is invalid because we only allow unevaluated func refs on the LHS of a
# binary operator.
f = hl.Func("f")
f[x] = 1 + f[x]
with assert_throws(
hl.HalideError,
r"Cannot use an unevaluated reference to 'f(\$\d+)?' to define an update at a different location\.",
):
# This is OK
g = hl.Func("g")
g[0] += 1
assert list(g.realize([2])) == [1, 0]
# This is invalid because the list of arguments changed
f = hl.Func("f")
f[0] = f[x] + 1
# A test to make sure that indexing at a FuncRef is OK
g = hl.Func("g")
g[x] = 2
f = hl.Func("f")
f[g[0]] += 1
assert list(f.realize([3])) == [0, 0, 1]
# A test to make sure that placeholder args work
g = hl.Func("g")
g[x] = 2
f = hl.Func("f")
f[hl._] += g[hl._]
assert list(f.realize([1])) == [2]
def test_implicit_update_by_int():
x = hl.Var("x")
f = hl.Func("f")
f[x] += 1
assert f.realize([1])[0] == 1
f = hl.Func("f")
f[x] -= 1
assert f.realize([1])[0] == -1
f = hl.Func("f")
f[x] *= 2
assert f.realize([1])[0] == 2
f = hl.Func("f")
f[x] /= 1
assert f.realize([1])[0] == 1
f = hl.Func("f")
f[x] /= 2
assert f.realize([1])[0] == 0
def test_implicit_update_by_float():
# The floating-point equality comparisons in this test
# should be exact in any halfway sane floating point
# implementation. If these checks fail because of
# imprecision, we should be informed.
x = hl.Var("x")
f = hl.Func("f")
f[x] += 1.0
assert f.realize([1])[0] == 1.0
f = hl.Func("f")
f[x] -= 1.0
assert f.realize([1])[0] == -1.0
f = hl.Func("f")
f[x] *= 2.0
assert f.realize([1])[0] == 2.0
f = hl.Func("f")
f[x] /= 1.0
assert f.realize([1])[0] == 1.0
f = hl.Func("f")
f[x] /= 2.0
assert f.realize([1])[0] == 0.5
def test_print_ir():
im = hl.ImageParam()
assert str(im) == "<halide.ImageParam ImageParam()>"
im = hl.OutputImageParam()
assert str(im) == "<halide.OutputImageParam OutputImageParam()>"
im = hl.ImageParam(hl.UInt(16), 2, "input")
assert str(im) == "<halide.ImageParam 'input', dims: 2, type: uint16>"
r = hl.RDom()
assert str(r) == "<halide.RDom RDom()>"
p = hl.Pipeline()
assert str(p) == "<halide.Pipeline Pipeline()>"
if __name__ == "__main__":
test_compiletime_error()
test_runtime_error()
test_misused_and()
test_misused_or()
test_typed_funcs()
test_float_or_int()
test_operator_order()
test_int_promotion()
test_vector_tile()
test_basics()
test_basics2()
test_basics3()
test_basics4()
test_basics5()
test_scalar_funcs()
test_bool_conversion()
test_requirements()
test_implicit_convert_int64()
test_pow_rpow()
test_unevaluated_funcref()
test_implicit_update_by_int()
test_implicit_update_by_float()
test_print_ir()
|