register.py 19 KB
Newer Older
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
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
vLLM Helion kernel registration with pre-tuned config selection.

This module leverages Helion's internal config selection infrastructure to use
pre-tuned configs instead of runtime autotuning.

How Helion Normally Works
-------------------------
For each kernel invocation, Helion:
1. Computes a cache key from input arguments
2. Looks up the key in its internal compilation cache
3. On cache miss, runs autotuning to find the best config
4. Compiles and caches the kernel with that config

How We Override It
------------------
We override two Helion hooks to use pre-tuned configs:

1. **key**: We provide a key function (derived from config_picker) that
   computes cache keys matching our pre-tuned config keys. This ensures Helion's
   internal cache uses keys that correspond to configs we've prepared.

2. **autotuner_fn**: We provide PresetConfigSearch which, instead of autotuning,
   simply returns the pre-tuned config for the computed key. On cache miss,
   Helion calls our autotuner which returns the author-prepared config.

Both hooks use the same config_picker logic to ensure the cache key computed
by key matches the config returned by the autotuner.

Key Classes
-----------
34
35
- HelionKernelWrapper: Wraps raw kernel + config_picker, creates configured kernels
- ConfiguredHelionKernel: Platform-specific kernel with pre-tuned configs
36
37
38
39
- PresetConfigSearch: Custom autotuner that returns pre-tuned configs
"""

from collections.abc import Callable
40
from typing import Any, cast
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

import torch
from torch.library import Library

from vllm.logger import init_logger
from vllm.utils.import_utils import has_helion
from vllm.utils.torch_utils import direct_register_custom_op

if not has_helion():
    raise ImportError(
        "register module requires helion to be installed. "
        "Install it with: pip install helion"
    )

import helion
56
from helion._compat import requires_torch_version
57
58
59
60
from helion.autotuner.base_search import BaseAutotuner
from helion.runtime.config import Config
from helion.runtime.settings import default_autotuner_fn

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# TODO(gmagogsfm): Remove CustomOp fallback path (_get_or_register_custom_op,
# vllm_helion_lib, direct_register_custom_op) once vLLM requires PyTorch >= 2.11.
_HOP_AVAILABLE = requires_torch_version("2.11")

if _HOP_AVAILABLE:
    import torch.utils._pytree as pytree
    from helion._compiler._dynamo.higher_order_ops import (
        helion_kernel_side_table,
        helion_kernel_wrapper_mutation,
    )
    from helion._compiler._dynamo.variables import infer_output_spec
    from torch.fx.experimental.proxy_tensor import (
        disable_proxy_modes_tracing,
        get_proxy_mode,
    )

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
logger = init_logger(__name__)

vllm_helion_lib = Library("vllm_helion", "FRAGMENT")  # noqa


def validate_helion_settings(
    helion_settings: "helion.Settings | None", op_name: str
) -> None:
    if helion_settings is None:
        return

    settings_dict = helion_settings.to_dict()

    if (
        "autotuner_fn" in settings_dict
        and settings_dict["autotuner_fn"] is not None
        and settings_dict["autotuner_fn"] is not default_autotuner_fn
    ):
        raise ValueError(
            f"HelionKernelWrapper for '{op_name}' uses a custom autotuner via "
            f"config picker. Remove 'autotuner_fn' from helion_settings and use "
98
            f"register_kernel(..., config_picker=...) instead."
99
100
101
102
        )

    if settings_dict.get("static_shapes") is True:
        logger.warning(
103
104
105
            "Kernel '%s' has static_shapes=True in helion_settings, "
            "which will be overridden to False. vLLM requires dynamic "
            "shapes for variable batch sizes and sequence lengths.",
106
107
108
109
            op_name,
        )


110
111
112
113
114
115
116
117
118
def create_helion_decorated_kernel(
    raw_kernel_func: Callable,
    helion_settings: "helion.Settings | None" = None,
    extra_kwargs: dict[str, Any] | None = None,
) -> Any:
    kernel_kwargs: dict[str, Any] = {}
    if helion_settings:
        kernel_kwargs.update(helion_settings.to_dict())

119
120
    # vLLM requires dynamic shapes for variable batch sizes and sequence lengths
    kernel_kwargs["static_shapes"] = False
121
122
123
124
125
126
127

    if extra_kwargs:
        kernel_kwargs.update(extra_kwargs)

    return helion.kernel(**kernel_kwargs)(raw_kernel_func)


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class PresetConfigSearch(BaseAutotuner):
    """Custom autotuner that uses a preset config selector instead of autotuning."""

    def __init__(
        self,
        args: tuple[Any, ...],
        config_selector: Callable[[tuple[Any, ...]], Config],
    ):
        self.args = args
        self.config_selector = config_selector

    def autotune(self, *, skip_cache: bool = False) -> Config:
        return self.config_selector(self.args)


class ConfiguredHelionKernel:
    """A configured Helion kernel bound to a specific platform."""

    def __init__(
        self,
        op_name: str,
149
        config_picker: Callable[[tuple[Any, ...], list[str]], str | None] | None,
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
        raw_kernel_func: Callable,
        helion_settings: "helion.Settings | None" = None,
    ):
        self.op_name = op_name
        self.config_picker = config_picker
        self.raw_kernel_func = raw_kernel_func
        self.helion_settings = helion_settings
        self._decorated_kernel = self._create_decorated_kernel()

    def __call__(self, *args, **kwargs):
        return self._decorated_kernel(*args, **kwargs)

    def _create_key_computer(self):
        """
        Create a key computer function derived from the config picker.

        The returned function receives kernel arguments unpacked (*args) to match
        Helion's key signature (called as self._key_fn(*args)).
        """
        if self.config_picker is None:
            raise RuntimeError(
                f"No config picker registered for kernel '{self.op_name}'. "
172
                f"A config_picker must be provided to register_kernel()."
173
174
            )

175
176
177
        # After None check, config_picker is guaranteed to be non-None
        assert self.config_picker is not None

178
179
        def key_computer(*args):
            config_keys = list(self.configs.keys())
180
181
182
183
184
            # Cast is safe because we checked for None above
            config_picker = cast(
                Callable[[tuple[Any, ...], list[str]], str | None], self.config_picker
            )
            selected_key = config_picker(args, config_keys)
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
            if selected_key:
                return selected_key
            return "default" if "default" in self.configs else None

        return key_computer

    def _create_config_selector(self, key_computer):
        def config_selector(args):
            # args is a tuple; key_computer expects unpacked args
            selected_config_key = key_computer(*args)

            if selected_config_key is None:
                raise ValueError(
                    f"Config picker returned None for kernel '{self.op_name}' "
                    f"with available config keys: {list(self.configs.keys())}"
                )

            if selected_config_key not in self.configs:
                raise ValueError(
                    f"Config picker returned invalid config key "
                    f"'{selected_config_key}' for kernel '{self.op_name}'. "
                    f"Available keys: {list(self.configs.keys())}"
                )

            return self.configs[selected_config_key]

        return config_selector

    def _load_platform_configs(self) -> None:
        from vllm.kernels.helion.config_manager import ConfigManager
        from vllm.kernels.helion.utils import get_canonical_gpu_name

        self.platform = get_canonical_gpu_name()
218
        config_manager = ConfigManager()
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        self.configs = config_manager.get_platform_configs(self.op_name, self.platform)

        if not self.configs:
            raise ValueError(
                f"No configs available for kernel '{self.op_name}' "
                f"on platform '{self.platform}'"
            )

    def _create_decorated_kernel(self) -> Callable[..., Any]:
        self._load_platform_configs()

        key_computer = self._create_key_computer()
        config_selector = self._create_config_selector(key_computer)

233
234
235
236
        extra_kwargs = {
            "autotuner_fn": lambda _, args: PresetConfigSearch(args, config_selector),
            "key": key_computer,
        }
237
238
239
240
241
242

        logger.debug(
            "Creating decorated kernel %s with custom autotuner on platform %s",
            self.op_name,
            self.platform,
        )
243
244
245
        return create_helion_decorated_kernel(
            self.raw_kernel_func, self.helion_settings, extra_kwargs
        )
246
247
248


class HelionKernelWrapper:
249
    """Wrapper for Helion kernels with pre-tuned config selection and HOP support."""
250
251
252
253
254
255

    def __init__(
        self,
        raw_kernel_func: Callable,
        op_name: str,
        fake_impl: Callable,
256
        config_picker: Callable[[tuple[Any, ...], list[str]], str | None],
257
        helion_settings: "helion.Settings | None" = None,
258
        input_generator: Callable[[], dict[str, tuple[Any, ...]]] | None = None,
259
260
261
262
263
264
265
266
    ):
        # Validate helion_settings doesn't conflict with our custom autotuner
        validate_helion_settings(helion_settings, op_name)

        self.raw_kernel_func = raw_kernel_func
        self.op_name = op_name
        self._fake_impl = fake_impl
        self.helion_settings = helion_settings
267
268
        self._config_picker = config_picker
        self._input_generator = input_generator
269
        self._configured_kernel: ConfiguredHelionKernel | None = None
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        # TODO(@gmagogsfm): Remove this disable flag once integrated with vLLM IR,
        # which handles op enablement/disablement.
        self._disabled = False
        self._disabled_reason: str | None = None

        try:
            if not _HOP_AVAILABLE:
                self._get_or_register_custom_op()
            else:
                self.get_configured_op()
        except ValueError as e:
            self._disabled = True
            self._disabled_reason = str(e)
            logger.warning(
                "Helion kernel '%s' is disabled: %s",
                op_name,
                self._disabled_reason,
            )
288
289

    def __call__(self, *args, **kwargs):
290
291
292
293
        if self._disabled:
            raise RuntimeError(
                f"Helion kernel '{self.op_name}' is disabled: {self._disabled_reason}"
            )
294
        if not _HOP_AVAILABLE:
295
296
297
298
299
300
            op = getattr(torch.ops.vllm_helion, self.op_name)
            return op(*args, **kwargs)
        assert self._configured_kernel is not None, (
            f"Kernel '{self.op_name}' was not initialized. "
            "Please open an issue on GitHub."
        )
301
302
        if get_proxy_mode() is not None:
            return self._call_via_hop(args, kwargs)
303
        return self._configured_kernel(*args, **kwargs)
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

    def _call_via_hop(
        self,
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
    ) -> Any:
        kernel = self.get_configured_op()._decorated_kernel
        kernel_idx = helion_kernel_side_table.add_kernel(kernel)

        constant_args, tensor_args = self._partition_args(kernel, args, kwargs)

        all_named = {**constant_args, **tensor_args}
        full_args = tuple(
            all_named.get(n, p.default)
            for n, p in kernel.signature.parameters.items()  # type: ignore[attr-defined]
            if n in all_named or p.default is not p.empty
        )

        with disable_proxy_modes_tracing():
            output_spec = infer_output_spec(kernel, full_args)

        hop_result = helion_kernel_wrapper_mutation(
            kernel_idx=kernel_idx,
            constant_args=constant_args,
            tensor_args=tensor_args,
            output_spec=output_spec,
        )

        tree_spec_str = output_spec.get("tree_spec_str")
        if tree_spec_str is None:
            return None
        tree_spec = pytree.treespec_loads(tree_spec_str)

        hop_iter = iter(hop_result)
        reconstructed = []
        for spec in output_spec["leaf_specs"]:
            is_constant_scalar = spec["type"] == "scalar" and not isinstance(
                spec.get("scalar_value"), torch.SymInt
            )
            if is_constant_scalar:
                reconstructed.append(spec["scalar_value"])
            else:
                reconstructed.append(next(hop_iter))
        return pytree.tree_unflatten(reconstructed, tree_spec)

    @staticmethod
    def _partition_args(
        kernel: Any,
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
    ) -> tuple[dict[str, Any], dict[str, Any]]:
        constant_args: dict[str, Any] = {}
        tensor_args: dict[str, Any] = {}
        params = list(kernel.signature.parameters.keys())
        for i, val in enumerate(args):
            name = params[i]
            if isinstance(val, torch.Tensor):
                tensor_args[name] = val
            else:
                constant_args[name] = val
        for name, val in kwargs.items():
            if isinstance(val, torch.Tensor):
                tensor_args[name] = val
            else:
                constant_args[name] = val
        return constant_args, tensor_args
370

371
372
373
374
    def get_inputs(self) -> dict[str, tuple[Any, ...]]:
        if self._input_generator is None:
            raise NotImplementedError(
                f"No input generator registered for kernel '{self.op_name}'. "
375
                f"Use register_kernel(..., input_generator=...) to register one."
376
377
378
379
380
381
382
383
384
            )
        return self._input_generator()

    def run_autotune(
        self,
        inputs: tuple[Any, ...],
        autotune_effort: str = "quick",
    ) -> Config:
        """Run autotuning for a single input configuration."""
385
386
387
388
        extra_kwargs = {
            "autotune_effort": autotune_effort,
            "autotune_ignore_errors": True,
        }
389
390
391
392
393
        autotune_kernel = create_helion_decorated_kernel(
            self.raw_kernel_func, self.helion_settings, extra_kwargs
        )
        return autotune_kernel.autotune(inputs)

394
    def get_configured_op(self) -> ConfiguredHelionKernel:
395
396
397
398
        if self._disabled:
            raise RuntimeError(
                f"Helion kernel '{self.op_name}' is disabled: {self._disabled_reason}"
            )
399
400
401
402
403
404
405
406
407
408
        if self._configured_kernel is None:
            self._configured_kernel = ConfiguredHelionKernel(
                op_name=self.op_name,
                config_picker=self._config_picker,
                raw_kernel_func=self.raw_kernel_func,
                helion_settings=self.helion_settings,
            )
        return self._configured_kernel

    def _get_or_register_custom_op(self) -> Any:
409
410
411
        if hasattr(torch.ops.vllm_helion, self.op_name):
            return getattr(torch.ops.vllm_helion, self.op_name)

412
        configured_kernel = self.get_configured_op()
413
414
415
416

        logger.info("Registering op: vllm_helion::%s", self.op_name)
        direct_register_custom_op(
            op_name=self.op_name,
417
            op_func=configured_kernel._decorated_kernel,
418
419
420
421
422
            mutates_args=None,
            fake_impl=self._fake_impl,
            target_lib=vllm_helion_lib,
        )
        return getattr(torch.ops.vllm_helion, self.op_name)
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


# Global registry for tracking all registered HelionKernelWrapper instances
_REGISTERED_KERNELS: dict[str, HelionKernelWrapper] = {}


def get_registered_kernels() -> dict[str, HelionKernelWrapper]:
    return _REGISTERED_KERNELS.copy()


def get_kernel_by_name(kernel_name: str) -> HelionKernelWrapper | None:
    return _REGISTERED_KERNELS.get(kernel_name)


def infer_fake_impl(
    kernel_func: Callable,
    helion_settings: "helion.Settings | None" = None,
) -> Callable:
    def helion_fake_kernel(*args, **kwargs):
        kernel_kwargs = {}
        if helion_settings:
            kernel_kwargs.update(helion_settings.to_dict())

        temp_decorated_kernel = helion.kernel(**kernel_kwargs)(kernel_func)

        # Bind with args to get config_spec, then get a valid default config
        bound = temp_decorated_kernel.bind(args)
        default_config = bound.config_spec.default_config()
        compiled_runner = bound.compile_config(default_config)

        return compiled_runner(*args, **kwargs, _launcher=lambda *a, **kw: None)

    return helion_fake_kernel


def register_kernel(
459
    op_name: str | None = None,
460
    *,
461
    config_picker: Callable[[tuple[Any, ...], list[str]], str | None],
462
463
    fake_impl: Callable | None = None,
    helion_settings: "helion.Settings | None" = None,
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
    input_generator: Callable[[], dict[str, tuple[Any, ...]]] | None = None,
) -> Callable[[Callable], HelionKernelWrapper]:
    """Register a Helion kernel with pre-tuned config selection.

    Wraps the kernel function in a HelionKernelWrapper that eagerly builds
    the configured kernel and (on older PyTorch) registers a custom op.

    Args:
        config_picker: Required. Function with signature
            ``(args: tuple, config_keys: list[str]) -> str | None``
            that picks the best config key from available options.
            Return ``None`` to fall back to ``"default"``.

            Example::

                def pick_config(args, config_keys):
                    x = args[0]
                    hidden_size = x.shape[-1]
                    batch_size = x.shape[0]
                    for key in config_keys:
                        if key == f"hiddensize_{hidden_size}_batchsize_{batch_size}":
                            return key
                    return "default" if "default" in config_keys else None

        input_generator: Optional. Function that returns
            ``dict[str, tuple]`` where each key is a configuration
            identifier (e.g. ``"4096"``, ``"hidden_4096"``) and each
            value is a tuple of arguments to pass to the kernel.

            Example::

                def generate_inputs():
                    return {
                        "4096": (torch.randn(4096, device="cuda"), 0.5),
                        "8192": (torch.randn(8192, device="cuda"), 0.5),
                    }
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
    """

    def decorator(kernel_func: Callable) -> HelionKernelWrapper:
        final_op_name = op_name if op_name else kernel_func.__name__

        if final_op_name in _REGISTERED_KERNELS:
            raise ValueError(
                f"Helion kernel '{final_op_name}' is already registered. "
                f"Use a different op_name or check for duplicate registrations."
            )

        final_fake_impl = fake_impl
        if final_fake_impl is None:
            final_fake_impl = infer_fake_impl(kernel_func, helion_settings)
            logger.debug(
                "Auto-generated fake_impl for Helion kernel '%s'",
                kernel_func.__name__,
            )

        kernel_wrapper = HelionKernelWrapper(
            raw_kernel_func=kernel_func,
            op_name=final_op_name,
            fake_impl=final_fake_impl,
523
            config_picker=config_picker,
524
            helion_settings=helion_settings,
525
            input_generator=input_generator,
526
527
528
529
530
531
532
533
534
535
536
        )

        _REGISTERED_KERNELS[final_op_name] = kernel_wrapper

        logger.info(
            "Registered Helion kernel '%s' as HelionKernelWrapper",
            kernel_func.__name__,
        )

        return kernel_wrapper

537
    return decorator