xref: /aosp_15_r20/external/executorch/exir/backend/backend_details.py (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the BSD-style license found in the
5# LICENSE file in the root directory of this source tree.
6
7from abc import ABC, abstractmethod
8from dataclasses import dataclass
9
10from typing import Dict, List, Optional, Tuple, Union
11
12from executorch.exir.backend.compile_spec_schema import CompileSpec
13from torch.export.exported_program import ExportedProgram
14
15
16def enforcedmethod(func):
17    func.__enforcedmethod__ = True
18    return func
19
20
21@dataclass
22class PreprocessResult:
23    processed_bytes: bytes = bytes()
24    debug_handle_map: Optional[Union[Dict[int, Tuple[int]], Dict[str, Tuple[int]]]] = (
25        None
26    )
27
28
29"""
30How to create a backend (for example, BackendWithCompilerDemo):
311. Create a python file, like backend_with_compiler_demo.py, with
32a custom class BackendWithCompilerDemo, derived from BackendDetails.
33
34How to use the backend (for example, BackendWithCompilerDemo):
352. Import this class, like
36from executorch.exir.backend.backend_with_compiler_demo import BackendWithCompilerDemo
37"""
38
39
40class BackendDetails(ABC):
41    """
42    A base interface to lower the implementation to the according backend. With
43    the decorators, this interface will be static, abstract and all inheritances are
44    enforced to implement this method.
45
46    Args:
47        edge_program: The original exported program. It will not be modified in place.
48        compile_specs: List of values needed for compilation
49
50    Returns:
51        PreprocessResult: It wraps the following information:
52            processed_bytes -> bytes: A compiled blob - a binary that can run the desired program in the backend.
53            debug_handle_map (Optional[Dict[int, Tuple[int]]]): For profiling purposes, a map from the node_id in the final graph (either EXIR or the user's self-defined IR)
54            to debug handle id attached in the original exported program.
55    """
56
57    @staticmethod
58    # all backends need to implement this method
59    @enforcedmethod
60    # it's a virtual method and inheritant class needs to implement the actual function
61    @abstractmethod
62    def preprocess(
63        edge_program: ExportedProgram,
64        compile_specs: List[CompileSpec],
65    ) -> PreprocessResult:
66        # Users should return a compiled blob - a binary that can run the desired
67        # program in the backend.
68        pass
69