Skip to content

[BUG] Improper hash calculation with deferred static evaluation #1211

@Kenny-Vilella

Description

@Kenny-Vilella

Bug Description

It comes from MjWarp, in some special edge case we launch the wrong kernel because the hash assigned to the kernel does not include critical information from deferred static evaluation.

Simple repro:

import warp as wp

wp.init()

_KERNEL_CACHE = {}

def cache_kernel(func):
    def wrapper(*args):
        # Hash lists by converting to tuple
        key = hash(tuple(tuple(a) if isinstance(a, list) else a for a in args))
        if key not in _KERNEL_CACHE:
            _KERNEL_CACHE[key] = func(*args)
        return _KERNEL_CACHE[key]
    return wrapper


@cache_kernel
def make_kernel(collision_types):
    """Kernel factory - the wp.static(collision_types[i]) references loop var 'i'."""

    def my_kernel(result: wp.array(dtype=int)):
        tid = wp.tid()
        if tid == 0:
            # Loop over collision types - 'i' is a loop variable
            for i in range(wp.static(len(collision_types))):
                # wp.static references 'i', so it's DEFERRED (not in initial hash)
                result[i] = wp.static(collision_types[i])

    return wp.kernel(module="unique", enable_backward=False)(my_kernel)

# Test 1: Create kernel with types [100, 200]
types_1 = [100, 200]
result_1 = wp.zeros(2, dtype=int)
wp.launch(make_kernel(types_1), dim=1, inputs=[], outputs=[result_1])
wp.synchronize()
print(f"  Result: {result_1.numpy().tolist()}")
print(f"  Expected: {types_1}")

# Test 2: Create kernel with types [999, 888] - DIFFERENT types, SAME length!
types_2 = [999, 888]
result_2 = wp.zeros(2, dtype=int)
wp.launch(make_kernel(types_2), dim=1, inputs=[], outputs=[result_2])
wp.synchronize()
print(f"  Result: {result_2.numpy().tolist()}")
print(f"  Expected: {types_2}")


# Test 3: Create kernel with types [999, 888, 100] - DIFFERENT length
types_3 = [999, 888, 100]
result_3 = wp.zeros(3, dtype=int)
wp.launch(make_kernel(types_3), dim=1, inputs=[], outputs=[result_3])
wp.synchronize()
print(f"  Result: {result_3.numpy().tolist()}")
print(f"  Expected: {types_3}")

System Information

No response

Metadata

Metadata

Labels

bugSomething isn't working

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions