File size: 4,286 Bytes
db704cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2025 the LlamaFactory team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""The definition of kernel interface.

Init Phase:
1. Scan all kernels.
2. Register default kernels.
3. Define kernel plugin.

"""

import importlib
from pathlib import Path

from ....utils import logging
from ....utils.plugin import BasePlugin
from ....utils.types import HFModel
from .registry import Registry


logger = logging.get_logger(__name__)


def scan_all_kernels():
    """Scan all kernels in the ``ops`` directory.

    Scans the ``ops`` directory for all ``.py`` files and attempts to import them.
    Importing triggers the :func:`~registry.register_kernel` decorator, which automatically registers the kernels.

    Returns:
        dict[str, type[BaseKernel]]: A dictionary of registered kernels.

    .. note::
        This function assumes that the ``ops`` directory is located in the same directory as this file.
        It recursively searches for ``.py`` files and constructs the module path for import.
    """
    ops_path = Path(__file__).parent / "ops"

    if not ops_path.exists():
        return

    base_package = __package__

    for file_path in ops_path.rglob("*.py"):
        if file_path.name == "__init__.py":
            continue

        # calculate the relative path:
        # file_path = .../kernels_v2/ops/mlp/npu_swiglu.py
        # rel_path  = ops/mlp/npu_swiglu.py
        rel_path = file_path.relative_to(Path(__file__).parent)

        # build module path:
        module_name = ".".join(rel_path.parts)[:-3]
        full_module_name = f"{base_package}.{module_name}"

        try:
            importlib.import_module(full_module_name)
        except Exception as e:
            logger.warning(f"[Kernel Registry] Failed to import {full_module_name} when loading kernels: {e}")

    return Registry.get_registered_kernels()


default_kernels = scan_all_kernels()


def get_default_kernels():
    """Get a list of default registered kernel IDs.

    Returns:
        list[str]: List of kernel IDs.
    """
    return list(default_kernels.keys())


def apply_kernel(kernel_id: str, **kwargs):
    """Applies a specific kernel to the model.

    Args:
        kernel_id (str): The ID of the kernel to apply.
        **kwargs: Keyword arguments passed to the kernel application function.
                  Typically includes the model instance.

    Returns:
        HFModel: The model with applied kernel.
    """
    kernel = default_kernels.get(kernel_id)
    if kernel is None:
        raise ValueError(f"Kernel {kernel_id} not found")

    kernel.apply(**kwargs)


class KernelPlugin(BasePlugin):
    """Plugin for managing kernel optimizations."""

    pass


@KernelPlugin("auto").register()
def apply_default_kernels(model: HFModel, include_kernels: str = None) -> HFModel:
    """Applies all default registered kernels to the model.

    Args:
        model (HFModel): The model instance to apply kernels to.
        include_kernels (str, optional): Comma-separated list of kernel IDs to apply.
                                         If "auto" or True, applies all default kernels.
                                         If None or False, no kernels are applied.
                                         Defaults to None.

    Returns:
        HFModel: The model with applied kernels.
    """
    if not include_kernels:
        return model
    elif include_kernels == "auto" or include_kernels is True:
        use_kernels = default_kernels.keys()
    else:
        use_kernels = include_kernels.split(",")  # "kernel_id1,kernel_id2,kernel_id3"

    for kernel in use_kernels:
        if kernel not in default_kernels:
            raise ValueError(f"Kernel {kernel} not found")

        apply_kernel(kernel, model=model)

    return model