| 138 | |
| 139 | @dataclass(frozen=True) |
| 140 | class ETKernelIndex: |
| 141 | index: dict[OperatorName, dict[ETKernelKey, BackendMetadata]] |
| 142 | |
| 143 | def has_kernels(self, g: NativeFunction | NativeFunctionsGroup) -> bool: |
| 144 | m = self.get_kernels(g) |
| 145 | return m is not None |
| 146 | |
| 147 | def get_kernels( |
| 148 | self, g: NativeFunction | NativeFunctionsGroup |
| 149 | ) -> dict[ETKernelKey, BackendMetadata]: |
| 150 | if isinstance(g, NativeFunction): |
| 151 | f = g |
| 152 | elif isinstance(g, NativeFunctionsGroup): |
| 153 | f = g.functional |
| 154 | else: |
| 155 | assert_never(g) |
| 156 | if f.func.name not in self.index: |
| 157 | return {} |
| 158 | return self.index[f.func.name] |
| 159 | |
| 160 | @staticmethod |
| 161 | def grow_from_backend_indices( |
| 162 | kernel_index: dict[OperatorName, dict[ETKernelKey, BackendMetadata]], |
| 163 | backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]], |
| 164 | ) -> None: |
| 165 | for dk in backend_indices: |
| 166 | index = backend_indices[dk] |
| 167 | for op, backend_metadata in index.items(): |
| 168 | if op in kernel_index: |
| 169 | kernel_index[op][ETKernelKey(default=True)] = backend_metadata |
| 170 | else: |
| 171 | kernel_index[op] = {ETKernelKey(default=True): backend_metadata} |
| 172 | |
| 173 | @staticmethod |
| 174 | def from_backend_indices( |
| 175 | backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]], |
| 176 | ) -> ETKernelIndex: |
| 177 | kernel_index: dict[OperatorName, dict[ETKernelKey, BackendMetadata]] = ( |
| 178 | defaultdict(dict) |
| 179 | ) |
| 180 | ETKernelIndex.grow_from_backend_indices(kernel_index, backend_indices) |
| 181 | return ETKernelIndex(kernel_index) |
| 182 | |
| 183 | def grow( |
| 184 | self, backend_indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]] |
| 185 | ) -> ETKernelIndex: |
| 186 | ETKernelIndex.grow_from_backend_indices(self.index, backend_indices) |
| 187 | return self |
| 188 | |
| 189 | def _to_backend_index(self) -> BackendIndex: |
| 190 | """ |
| 191 | WARNING: this will be deprecated once all the codegen places know how to handle ETKernelIndex. |
| 192 | """ |
| 193 | index: dict[OperatorName, BackendMetadata] = {} |
| 194 | for op in self.index: |
| 195 | kernel_dict = self.index[op] |
| 196 | assert ( |
| 197 | len(kernel_dict.values()) == 1 |
no outgoing calls