Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code generation for concatenate should be tree-of-ifs, not chain-of-ifs #495

Open
inducer opened this issue Apr 29, 2024 · 3 comments
Open

Comments

@inducer
Copy link
Owner

inducer commented Apr 29, 2024

def map_concatenate(self, expr: Concatenate) -> IndexLambda:
from pymbolic.primitives import If, Comparison, Subscript
def get_subscript(array_index: int, offset: ScalarExpression) -> Subscript:
aggregate = prim.Variable(f"_in{array_index}")
index = [prim.Variable(f"_{i}")
if i != expr.axis
else (prim.Variable(f"_{i}") - offset)
for i in range(len(expr.shape))]
return Subscript(aggregate, tuple(index))
lbounds: List[Any] = [0]
ubounds: List[Any] = [expr.arrays[0].shape[expr.axis]]
for i, array in enumerate(expr.arrays[1:], start=1):
ubounds.append(ubounds[i-1]+array.shape[expr.axis])
lbounds.append(ubounds[i-1])
# I = axis index
#
# => If(_I < arrays[0].shape[axis],
# _in0[_0, _1, ..., _I, ...],
# If(_I < (arrays[1].shape[axis]+arrays[0].shape[axis]),
# _in1[_0, _1, ..., _I-arrays[0].shape[axis], ...],
# ...
# _inNm1[_0, _1, ...] ...))
for i in range(len(expr.arrays) - 1, -1, -1):
lbound, ubound = lbounds[i], ubounds[i]
subarray_expr = get_subscript(i, lbound)
if i == len(expr.arrays) - 1:
concat_expr = subarray_expr
else:
concat_expr = If(Comparison(prim.Variable(f"_{expr.axis}"),
"<", ubound),
subarray_expr,
concat_expr)
bindings = {f"_in{i}": self.rec(array)
for i, array in enumerate(expr.arrays)}
return IndexLambda(expr=concat_expr,
shape=self._rec_shape(expr.shape),
dtype=expr.dtype,
bindings=immutabledict(bindings),
axes=expr.axes,
var_to_reduction_descr=immutabledict(),
tags=expr.tags)

cc @majosm

@kaushikcfd
Copy link
Collaborator

IIUC, you are proposing we have a switch-case node in the IR?

@inducer
Copy link
Owner Author

inducer commented Apr 30, 2024

No, not at all. I'm just proposing that we organize the generated If nodes...

image

@kaushikcfd
Copy link
Collaborator

Makes sense, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants