|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass, field |
| 4 | +from typing import TYPE_CHECKING |
| 5 | + |
| 6 | +from .repos import RepositoryProtocol |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from torch import nn |
| 10 | + |
| 11 | + |
| 12 | +@dataclass(frozen=True) |
| 13 | +class KernelizedLayer: |
| 14 | + """ |
| 15 | + A kernelized layer and the repository that its kernel was retrieved from. |
| 16 | +
|
| 17 | + Attributes: |
| 18 | + module (`nn.Module`): |
| 19 | + The kernelized layer. |
| 20 | + repo (`RepositoryProtocol`): |
| 21 | + The repository that the kernel was retrieved from. |
| 22 | + """ |
| 23 | + |
| 24 | + module: nn.Module |
| 25 | + repo: RepositoryProtocol |
| 26 | + |
| 27 | + |
| 28 | +@dataclass(frozen=True) |
| 29 | +class KernelizedFunc: |
| 30 | + """ |
| 31 | + A kernelized function and the repository that its kernel was retrieved from. |
| 32 | +
|
| 33 | + Attributes: |
| 34 | + module (`nn.Module`): |
| 35 | + The module that wraps the kernelized function. |
| 36 | + repo (`RepositoryProtocol`): |
| 37 | + The repository that the kernel was retrieved from. |
| 38 | + """ |
| 39 | + |
| 40 | + module: nn.Module |
| 41 | + repo: RepositoryProtocol |
| 42 | + |
| 43 | + |
| 44 | +@dataclass(frozen=True) |
| 45 | +class KernelizedLayers: |
| 46 | + """ |
| 47 | + The kernels that are in use by a kernelized model, as returned by |
| 48 | + [`~kernels.get_kernelized_layers`]. |
| 49 | +
|
| 50 | + Attributes: |
| 51 | + layers (`dict[str, KernelizedLayer]`): |
| 52 | + A mapping of each kernelized layer name to the layer and its repository. The |
| 53 | + names are the same as returned by Torch's `named_modules`. |
| 54 | + funcs (`dict[tuple[str, str], KernelizedFunc]`): |
| 55 | + A mapping of each kernelized function to the function and its repository. The |
| 56 | + key of the mapping is a tuple of the layer name that the function is attached |
| 57 | + to and the name of the function itself. |
| 58 | + """ |
| 59 | + |
| 60 | + layers: dict[str, KernelizedLayer] = field(default_factory=dict) |
| 61 | + funcs: dict[tuple[str, str], KernelizedFunc] = field(default_factory=dict) |
| 62 | + |
| 63 | + |
| 64 | +def get_kernelized_layers(model: "nn.Module") -> KernelizedLayers: |
| 65 | + """ |
| 66 | + Return the repositories of the kernel layers and functions that are used by the model. |
| 67 | +
|
| 68 | + Args: |
| 69 | + model (`nn.Module`): |
| 70 | + The kernelized model. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + [`~kernels.KernelizedLayers`]: The kernelized layers. |
| 74 | +
|
| 75 | + Example: |
| 76 | + ```python |
| 77 | + import torch |
| 78 | + import torch.nn as nn |
| 79 | + import torch.nn.functional as F |
| 80 | +
|
| 81 | + from kernels import LayerRepository, Mode, get_kernelized_layers, kernelize |
| 82 | + from kernels import use_kernel_forward_from_hub, use_kernel_mapping |
| 83 | +
|
| 84 | + @use_kernel_forward_from_hub("SiluAndMul") |
| 85 | + class SiluAndMul(nn.Module): |
| 86 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 87 | + d = x.shape[-1] // 2 |
| 88 | + return F.silu(x[..., :d]) * x[..., d:] |
| 89 | +
|
| 90 | + mapping = { |
| 91 | + "SiluAndMul": { |
| 92 | + "cuda": LayerRepository( |
| 93 | + repo_id="kernels-community/activation", |
| 94 | + layer_name="SiluAndMul", |
| 95 | + version=1, |
| 96 | + ) |
| 97 | + } |
| 98 | + } |
| 99 | +
|
| 100 | + class MLP(nn.Module): |
| 101 | + def __init__(self): |
| 102 | + super().__init__() |
| 103 | + self.up_proj = nn.Linear(1024, 2048) |
| 104 | + self.act_fn = SiluAndMul() |
| 105 | +
|
| 106 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 107 | + return self.act_fn(self.up_proj(x)) |
| 108 | +
|
| 109 | + model = MLP().to("cuda") |
| 110 | +
|
| 111 | + with use_kernel_mapping(mapping): |
| 112 | + model = kernelize(model, mode=Mode.INFERENCE) |
| 113 | +
|
| 114 | + kernelized = get_kernelized_layers(model) |
| 115 | + print(kernelized.layers) |
| 116 | + # {'act_fn': KernelizedLayer(module=..., repo=LayerRepository(...))} |
| 117 | + print(kernelized.funcs) |
| 118 | + # {} (no kernel functions are attached to this model) |
| 119 | + ``` |
| 120 | + """ |
| 121 | + kernelized = KernelizedLayers() |
| 122 | + |
| 123 | + for module_name, module in model.named_modules(): |
| 124 | + repo = module.__dict__.get("_kernel_repo") |
| 125 | + if repo is not None: |
| 126 | + kernelized.layers[module_name] = KernelizedLayer(module, repo) |
| 127 | + |
| 128 | + # Kernel functions attached through `use_kernelized_func` are plain |
| 129 | + # attributes, so they are not part of `named_modules`. |
| 130 | + for func_name, kernel_func in getattr(module, "_kernel_funcs", {}).items(): |
| 131 | + repo = kernel_func.__dict__.get("_kernel_repo") |
| 132 | + if repo is not None: |
| 133 | + kernelized.funcs[(module_name, func_name)] = KernelizedFunc(kernel_func, repo) |
| 134 | + |
| 135 | + return kernelized |
0 commit comments