1# MLIR Python Bindings 2 3Current status: Under development and not enabled by default 4 5 6## Building 7 8### Pre-requisites 9 10* [`pybind11`](https://github.com/pybind/pybind11) must be installed and able to 11 be located by CMake. 12* A relatively recent Python3 installation 13 14### CMake variables 15 16* **`MLIR_BINDINGS_PYTHON_ENABLED`**`:BOOL` 17 18 Enables building the Python bindings. Defaults to `OFF`. 19 20* **`MLIR_PYTHON_BINDINGS_VERSION_LOCKED`**`:BOOL` 21 22 Links the native extension against the Python runtime library, which is 23 optional on some platforms. While setting this to `OFF` can yield some greater 24 deployment flexibility, linking in this way allows the linker to report 25 compile time errors for unresolved symbols on all platforms, which makes for a 26 smoother development workflow. Defaults to `ON`. 27 28* **`PYTHON_EXECUTABLE`**:`STRING` 29 30 Specifies the `python` executable used for the LLVM build, including for 31 determining header/link flags for the Python bindings. On systems with 32 multiple Python implementations, setting this explicitly to the preferred 33 `python3` executable is strongly recommended. 34 35 36## Design 37 38### Use cases 39 40There are likely two primary use cases for the MLIR python bindings: 41 421. Support users who expect that an installed version of LLVM/MLIR will yield 43 the ability to `import mlir` and use the API in a pure way out of the box. 44 452. Downstream integrations will likely want to include parts of the API in their 46 private namespace or specially built libraries, probably mixing it with other 47 python native bits. 48 49 50### Composable modules 51 52In order to support use case #2, the Python bindings are organized into 53composable modules that downstream integrators can include and re-export into 54their own namespace if desired. This forces several design points: 55 56* Separate the construction/populating of a `py::module` from `PYBIND11_MODULE` 57 global constructor. 58 59* Introduce headers for C++-only wrapper classes as other related C++ modules 60 will need to interop with it. 61 62* Separate any initialization routines that depend on optional components into 63 its own module/dependency (currently, things like `registerAllDialects` fall 64 into this category). 65 66There are a lot of co-related issues of shared library linkage, distribution 67concerns, etc that affect such things. Organizing the code into composable 68modules (versus a monolithic `cpp` file) allows the flexibility to address many 69of these as needed over time. Also, compilation time for all of the template 70meta-programming in pybind scales with the number of things you define in a 71translation unit. Breaking into multiple translation units can significantly aid 72compile times for APIs with a large surface area. 73 74### Submodules 75 76Generally, the C++ codebase namespaces most things into the `mlir` namespace. 77However, in order to modularize and make the Python bindings easier to 78understand, sub-packages are defined that map roughly to the directory structure 79of functional units in MLIR. 80 81Examples: 82 83* `mlir.ir` 84* `mlir.passes` (`pass` is a reserved word :( ) 85* `mlir.dialect` 86* `mlir.execution_engine` (aside from namespacing, it is important that 87 "bulky"/optional parts like this are isolated) 88 89In addition, initialization functions that imply optional dependencies should 90be in underscored (notionally private) modules such as `_init` and linked 91separately. This allows downstream integrators to completely customize what is 92included "in the box" and covers things like dialect registration, 93pass registration, etc. 94 95### Loader 96 97LLVM/MLIR is a non-trivial python-native project that is likely to co-exist with 98other non-trivial native extensions. As such, the native extension (i.e. the 99`.so`/`.pyd`/`.dylib`) is exported as a notionally private top-level symbol 100(`_mlir`), while a small set of Python code is provided in `mlir/__init__.py` 101and siblings which loads and re-exports it. This split provides a place to stage 102code that needs to prepare the environment *before* the shared library is loaded 103into the Python runtime, and also provides a place that one-time initialization 104code can be invoked apart from module constructors. 105 106To start with the `mlir/__init__.py` loader shim can be very simple and scale to 107future need: 108 109```python 110from _mlir import * 111``` 112 113### Limited use of globals 114 115For normal operations, parent-child constructor relationships are realized with 116constructor methods on a parent class as opposed to requiring 117invocation/creation from a global symbol. 118 119For example, consider two code fragments: 120 121```python 122 123op = build_my_op() 124 125region = mlir.Region(op) 126 127``` 128 129vs 130 131```python 132 133op = build_my_op() 134 135region = op.new_region() 136 137``` 138 139For tightly coupled data structures like `Operation`, the latter is generally 140preferred because: 141 142* It is syntactically less possible to create something that is going to access 143 illegal memory (less error handling in the bindings, less testing, etc). 144 145* It reduces the global-API surface area for creating related entities. This 146 makes it more likely that if constructing IR based on an Operation instance of 147 unknown providence, receiving code can just call methods on it to do what they 148 want versus needing to reach back into the global namespace and find the right 149 `Region` class. 150 151* It leaks fewer things that are in place for C++ convenience (i.e. default 152 constructors to invalid instances). 153 154### Use the C-API 155 156The Python APIs should seek to layer on top of the C-API to the degree possible. 157Especially for the core, dialect-independent parts, such a binding enables 158packaging decisions that would be difficult or impossible if spanning a C++ ABI 159boundary. In addition, factoring in this way side-steps some very difficult 160issues that arise when combining RTTI-based modules (which pybind derived things 161are) with non-RTTI polymorphic C++ code (the default compilation mode of LLVM). 162 163 164### Ownership in the Core IR 165 166There are several top-level types in the core IR that are strongly owned by their python-side reference: 167 168* `PyContext` (`mlir.ir.Context`) 169* `PyModule` (`mlir.ir.Module`) 170* `PyOperation` (`mlir.ir.Operation`) - but with caveats 171 172All other objects are dependent. All objects maintain a back-reference (keep-alive) to their closest containing top-level object. Further, dependent objects fall into two categories: a) uniqued (which live for the life-time of the context) and b) mutable. Mutable objects need additional machinery for keeping track of when the C++ instance that backs their Python object is no longer valid (typically due to some specific mutation of the IR, deletion, or bulk operation). 173 174#### Operation hierarchy 175 176As mentioned above, `PyOperation` is special because it can exist in either a top-level or dependent state. The life-cycle is unidirectional: operations can be created detached (top-level) and once added to another operation, they are then dependent for the remainder of their lifetime. The situation is more complicated when considering construction scenarios where an operation is added to a transitive parent that is still detached, necessitating further accounting at such transition points (i.e. all such added children are initially added to the IR with a parent of their outer-most detached operation, but then once it is added to an attached operation, they need to be re-parented to the containing module). 177 178Due to the validity and parenting accounting needs, `PyOperation` is the owner for regions and blocks and needs to be a top-level type that we can count on not aliasing. This let's us do things like selectively invalidating instances when mutations occur without worrying that there is some alias to the same operation in the hierarchy. Operations are also the only entity that are allowed to be in a detached state, and they are interned at the context level so that there is never more than one Python `mlir.ir.Operation` object for a unique `MlirOperation`, regardless of how it is obtained. 179 180The C/C++ API allows for Region/Block to also be detached, but it simplifies the ownership model a lot to eliminate that possibility in this API, allowing the Region/Block to be completely dependent on its owning operation for accounting. The aliasing of Python `Region`/`Block` instances to underlying `MlirRegion`/`MlirBlock` is considered benign and these objects are not interned in the context (unlike operations). 181 182If we ever want to re-introduce detached regions/blocks, we could do so with new "DetachedRegion" class or similar and also avoid the complexity of accounting. With the way it is now, we can avoid having a global live list for regions and blocks. We may end up needing an op-local one at some point TBD, depending on how hard it is to guarantee how mutations interact with their Python peer objects. We can cross that bridge easily when we get there. 183 184Module, when used purely from the Python API, can't alias anyway, so we can use it as a top-level ref type without a live-list for interning. If the API ever changes such that this cannot be guaranteed (i.e. by letting you marshal a native-defined Module in), then there would need to be a live table for it too. 185 186## Style 187 188In general, for the core parts of MLIR, the Python bindings should be largely 189isomorphic with the underlying C++ structures. However, concessions are made 190either for practicality or to give the resulting library an appropriately 191"Pythonic" flavor. 192 193### Properties vs get*() methods 194 195Generally favor converting trivial methods like `getContext()`, `getName()`, 196`isEntryBlock()`, etc to read-only Python properties (i.e. `context`). It is 197primarily a matter of calling `def_property_readonly` vs `def` in binding code, 198and makes things feel much nicer to the Python side. 199 200For example, prefer: 201 202```c++ 203m.def_property_readonly("context", ...) 204``` 205 206Over: 207 208```c++ 209m.def("getContext", ...) 210``` 211 212### __repr__ methods 213 214Things that have nice printed representations are really great :) If there is a 215reasonable printed form, it can be a significant productivity boost to wire that 216to the `__repr__` method (and verify it with a [doctest](#sample-doctest)). 217 218### CamelCase vs snake_case 219 220Name functions/methods/properties in `snake_case` and classes in `CamelCase`. As 221a mechanical concession to Python style, this can go a long way to making the 222API feel like it fits in with its peers in the Python landscape. 223 224If in doubt, choose names that will flow properly with other 225[PEP 8 style names](https://pep8.org/#descriptive-naming-styles). 226 227### Prefer pseudo-containers 228 229Many core IR constructs provide methods directly on the instance to query count 230and begin/end iterators. Prefer hoisting these to dedicated pseudo containers. 231 232For example, a direct mapping of blocks within regions could be done this way: 233 234```python 235region = ... 236 237for block in region: 238 239 pass 240``` 241 242However, this way is preferred: 243 244```python 245region = ... 246 247for block in region.blocks: 248 249 pass 250 251print(len(region.blocks)) 252print(region.blocks[0]) 253print(region.blocks[-1]) 254``` 255 256Instead of leaking STL-derived identifiers (`front`, `back`, etc), translate 257them to appropriate `__dunder__` methods and iterator wrappers in the bindings. 258 259Note that this can be taken too far, so use good judgment. For example, block 260arguments may appear container-like but have defined methods for lookup and 261mutation that would be hard to model properly without making semantics 262complicated. If running into these, just mirror the C/C++ API. 263 264### Provide one stop helpers for common things 265 266One stop helpers that aggregate over multiple low level entities can be 267incredibly helpful and are encouraged within reason. For example, making 268`Context` have a `parse_asm` or equivalent that avoids needing to explicitly 269construct a SourceMgr can be quite nice. One stop helpers do not have to be 270mutually exclusive with a more complete mapping of the backing constructs. 271 272## Testing 273 274Tests should be added in the `test/Bindings/Python` directory and should 275typically be `.py` files that have a lit run line. 276 277While lit can run any python module, prefer to lay tests out according to these 278rules: 279 280* For tests of the API surface area, prefer 281 [`doctest`](https://docs.python.org/3/library/doctest.html). 282* For generative tests (those that produce IR), define a Python module that 283 constructs/prints the IR and pipe it through `FileCheck`. 284* Parsing should be kept self-contained within the module under test by use of 285 raw constants and an appropriate `parse_asm` call. 286* Any file I/O code should be staged through a tempfile vs relying on file 287 artifacts/paths outside of the test module. 288 289### Sample Doctest 290 291```python 292# RUN: %PYTHON %s 293 294""" 295 >>> m = load_test_module() 296Test basics: 297 >>> m.operation.name 298 "module" 299 >>> m.operation.is_registered 300 True 301 >>> ... etc ... 302 303Verify that repr prints: 304 >>> m.operation 305 <operation 'module'> 306""" 307 308import mlir 309 310TEST_MLIR_ASM = r""" 311func @test_operation_correct_regions() { 312 // ... 313} 314""" 315 316# TODO: Move to a test utility class once any of this actually exists. 317def load_test_module(): 318 ctx = mlir.ir.Context() 319 ctx.allow_unregistered_dialects = True 320 module = ctx.parse_asm(TEST_MLIR_ASM) 321 return module 322 323 324if __name__ == "__main__": 325 import doctest 326 doctest.testmod() 327``` 328 329### Sample FileCheck test 330 331```python 332# RUN: %PYTHON %s | mlir-opt -split-input-file | FileCheck 333 334# TODO: Move to a test utility class once any of this actually exists. 335def print_module(f): 336 m = f() 337 print("// -----") 338 print("// TEST_FUNCTION:", f.__name__) 339 print(m.to_asm()) 340 return f 341 342# CHECK-LABEL: TEST_FUNCTION: create_my_op 343@print_module 344def create_my_op(): 345 m = mlir.ir.Module() 346 builder = m.new_op_builder() 347 # CHECK: mydialect.my_operation ... 348 builder.my_op() 349 return m 350``` 351