|
| 1 | +import functools |
| 2 | +import hashlib |
| 3 | +import logging |
| 4 | +import threading |
| 5 | +from typing import Any |
| 6 | +from collections.abc import Callable |
| 7 | + |
| 8 | +import cutlass.cute as cute |
| 9 | + |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +class CuteKernelCache: |
| 15 | + """Global cache for compiled CUTE kernels""" |
| 16 | + |
| 17 | + def __init__(self): |
| 18 | + self._cache: dict[str, Any] = {} |
| 19 | + self._stats = {"hits": 0, "misses": 0} |
| 20 | + self._lock = threading.Lock() |
| 21 | + |
| 22 | + def get(self, key: str) -> Any | None: |
| 23 | + with self._lock: |
| 24 | + if key in self._cache: |
| 25 | + self._stats["hits"] += 1 |
| 26 | + return self._cache[key] |
| 27 | + self._stats["misses"] += 1 |
| 28 | + return None |
| 29 | + |
| 30 | + def set(self, key: str, value: Any) -> None: |
| 31 | + with self._lock: |
| 32 | + self._cache[key] = value |
| 33 | + |
| 34 | + def clear(self) -> None: |
| 35 | + with self._lock: |
| 36 | + self._cache.clear() |
| 37 | + self._stats = {"hits": 0, "misses": 0} |
| 38 | + |
| 39 | + def get_stats(self) -> dict[str, int | float]: |
| 40 | + with self._lock: |
| 41 | + total = self._stats["hits"] + self._stats["misses"] |
| 42 | + hit_rate = self._stats["hits"] / total if total > 0 else 0 |
| 43 | + return { |
| 44 | + **self._stats, |
| 45 | + "total": total, |
| 46 | + "hit_rate": hit_rate, |
| 47 | + "cache_size": len(self._cache), |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | +# Global cache instance |
| 52 | +_kernel_cache = CuteKernelCache() |
| 53 | + |
| 54 | + |
| 55 | +def _generate_cache_key(*args, **kwargs) -> str: |
| 56 | + """Generate a cache key from function arguments""" |
| 57 | + key_parts = [] |
| 58 | + |
| 59 | + for arg in args: |
| 60 | + if isinstance(arg, cute.Tensor): |
| 61 | + # For cute tensors, use shape and dtype |
| 62 | + key_parts.append(f"tensor_shape={arg.shape}_dtype={arg._dtype}") |
| 63 | + elif hasattr(arg, "__name__"): |
| 64 | + # For functions/operators like add, mul |
| 65 | + key_parts.append(f"op={arg.__name__}") |
| 66 | + else: |
| 67 | + # For other types, use string representation |
| 68 | + key_parts.append(str(arg)) |
| 69 | + |
| 70 | + # Add kwargs |
| 71 | + for k, v in sorted(kwargs.items()): |
| 72 | + key_parts.append(f"{k}={v}") |
| 73 | + |
| 74 | + # Create hash of the key |
| 75 | + key_str = "_".join(key_parts) |
| 76 | + return hashlib.md5(key_str.encode()).hexdigest() |
| 77 | + |
| 78 | + |
| 79 | +# Keep cute_jit for backward compatibility |
| 80 | +def cute_jit(func: Callable) -> Callable: |
| 81 | + """ |
| 82 | + Deprecated: Use @cute_cache() instead. |
| 83 | + This decorator is kept for backward compatibility. |
| 84 | + """ |
| 85 | + logger.warning("@cute_jit is deprecated. Use @cute_cache() instead.") |
| 86 | + return cute_cache()(func) |
| 87 | + |
| 88 | + |
| 89 | +def cute_cache(key_params: list | None = None) -> Callable: |
| 90 | + """ |
| 91 | + Decorator that applies @cute.jit and caches compiled CUTE kernels. |
| 92 | +
|
| 93 | + Args: |
| 94 | + key_params: List of parameter names to use for cache key generation. |
| 95 | + If None, uses all parameters. |
| 96 | +
|
| 97 | + Example: |
| 98 | + @cute_cache() |
| 99 | + def elementwise_op(op, mA, mB, mC): |
| 100 | + # Kernel implementation |
| 101 | + ... |
| 102 | + """ |
| 103 | + |
| 104 | + def decorator(func: Callable) -> Callable: |
| 105 | + # Apply cute.jit once at decoration time to avoid closure issues |
| 106 | + jitted_func = cute.jit(func) |
| 107 | + |
| 108 | + @functools.wraps(func) |
| 109 | + def wrapper(*args, **kwargs): |
| 110 | + # Generate cache key |
| 111 | + if key_params: |
| 112 | + # Extract specific params for cache key |
| 113 | + import inspect |
| 114 | + |
| 115 | + sig = inspect.signature(func) |
| 116 | + bound_args = sig.bind(*args, **kwargs) |
| 117 | + bound_args.apply_defaults() |
| 118 | + |
| 119 | + key_args = [] |
| 120 | + for param in key_params: |
| 121 | + if param in bound_args.arguments: |
| 122 | + key_args.append(bound_args.arguments[param]) |
| 123 | + cache_key = _generate_cache_key(*key_args) |
| 124 | + else: |
| 125 | + # Use all arguments |
| 126 | + cache_key = _generate_cache_key(*args, **kwargs) |
| 127 | + |
| 128 | + # Add function name to cache key |
| 129 | + cache_key = f"{func.__name__}_{cache_key}" |
| 130 | + |
| 131 | + # Check cache |
| 132 | + compiled_kernel = _kernel_cache.get(cache_key) |
| 133 | + |
| 134 | + if compiled_kernel is not None: |
| 135 | + logger.debug(f"Cache hit for {func.__name__} (key: {cache_key[:8]}...)") |
| 136 | + return compiled_kernel(*args, **kwargs) |
| 137 | + |
| 138 | + logger.debug( |
| 139 | + f"Cache miss for {func.__name__} (key: {cache_key[:8]}...) - Compiling..." |
| 140 | + ) |
| 141 | + |
| 142 | + # Compile the kernel using the pre-jitted function |
| 143 | + compiled_kernel = cute.compile(jitted_func, *args, **kwargs) |
| 144 | + |
| 145 | + # Cache the compiled kernel |
| 146 | + _kernel_cache.set(cache_key, compiled_kernel) |
| 147 | + |
| 148 | + # Execute the compiled kernel |
| 149 | + return compiled_kernel(*args, **kwargs) |
| 150 | + |
| 151 | + # Add utility methods to the wrapper |
| 152 | + wrapper.clear_cache = lambda: _kernel_cache.clear() |
| 153 | + wrapper.get_cache_stats = lambda: _kernel_cache.get_stats() |
| 154 | + |
| 155 | + return wrapper |
| 156 | + |
| 157 | + return decorator |
| 158 | + |
| 159 | + |
| 160 | +# Utility functions |
| 161 | +def clear_cute_cache(): |
| 162 | + """Clear all cached kernels""" |
| 163 | + _kernel_cache.clear() |
| 164 | + |
| 165 | + |
| 166 | +def get_cache_stats(): |
| 167 | + """Get cache statistics""" |
| 168 | + return _kernel_cache.get_stats() |
0 commit comments