├── .github └── workflows │ ├── build_mlir.yml │ └── bump_revisions.yml ├── .gitignore ├── .style.yapf ├── LICENSE ├── README.md ├── llvm-project.version ├── packages └── mlir │ └── setup.py ├── requirements.txt ├── scripts └── checkout_repo.py └── testing.md /.github/workflows/build_mlir.yml: -------------------------------------------------------------------------------- 1 | name: Build MLIR Wheels 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | package_suffix: 7 | description: 'Suffix to append to package names' 8 | required: true 9 | default: '-cidev' 10 | package_version: 11 | description: 'Version of the package' 12 | required: true 13 | default: '0.1a1' 14 | release_id: 15 | description: 'Release id to upload artifacts to' 16 | required: true 17 | default: '' 18 | 19 | jobs: 20 | build_wheels: 21 | name: "${{ matrix.os }} :: Build MLIR wheels" 22 | runs-on: ${{ matrix.os }} 23 | continue-on-error: ${{ matrix.experimental }} 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | os: [ubuntu-18.04] 28 | experimental: [false] 29 | include: 30 | - os: macos-latest 31 | experimental: true 32 | - os: windows-2019 33 | experimental: true 34 | 35 | env: 36 | CIBW_BUILD_VERBOSITY: 1 37 | CIBW_BEFORE_BUILD_LINUX: pip install -r main_checkout/requirements.txt 38 | CIBW_BEFORE_BUILD_MACOS: pip install -r main_checkout/requirements.txt 39 | CIBW_BEFORE_BUILD_WINDOWS: pip install -r main_checkout\\requirements.txt 40 | # Note that on Linux, we run under docker with an altered path. 41 | CIBW_ENVIRONMENT_LINUX: "REPO_DIR=/project/main_checkout" 42 | CIBW_ENVIRONMENT_MACOS: "REPO_DIR=${{ github.workspace }}/main_checkout" 43 | CIBW_ENVIRONMENT_WINDOWS: "REPO_DIR='${{ github.workspace }}\\main_checkout'" 44 | 45 | CIBW_MANYLINUX_X86_64_IMAGE: manylinux2014 46 | CIBW_BUILD: "cp36-* cp37-* cp38-* cp39-*" 47 | CIBW_SKIP: "*-win32 *-manylinux_i686" 48 | 49 | steps: 50 | - uses: actions/checkout@v2 51 | with: 52 | path: 'main_checkout' 53 | 54 | - uses: actions/setup-python@v2 55 | name: Install Python 56 | with: 57 | python-version: '3.7' 58 | 59 | - name: Checkout LLVM 60 | shell: bash 61 | run: | 62 | python ./main_checkout/scripts/checkout_repo.py \ 63 | ./llvm-project \ 64 | https://github.com/llvm/llvm-project.git \ 65 | main \ 66 | ./main_checkout/llvm-project.version 67 | 68 | - name: Write version info 69 | shell: bash 70 | run: | 71 | cat << EOF > ./main_checkout/version_info.json 72 | { 73 | "package-suffix": "${{ github.event.inputs.package_suffix }}", 74 | "package-version": "${{ github.event.inputs.package_version }}", 75 | "llvm-revision": "$(cd ./llvm-project && git rev-parse HEAD)" 76 | } 77 | EOF 78 | cat ./main_checkout/version_info.json 79 | 80 | - name: Set up Visual Studio shell 81 | if: "contains(matrix.os, 'windows')" 82 | uses: egor-tensin/vs-shell@v2 83 | with: 84 | arch: x64 85 | 86 | - name: Install cibuildwheel 87 | shell: bash 88 | run: | 89 | python -m pip install cibuildwheel==1.7.2 90 | 91 | - name: Build wheels 92 | shell: bash 93 | run: | 94 | python -m cibuildwheel --output-dir wheelhouse \ 95 | ./main_checkout/packages/mlir 96 | 97 | - uses: actions/upload-artifact@v2 98 | with: 99 | path: ./wheelhouse/*.whl 100 | 101 | - name: Upload Release Assets 102 | if: github.event.inputs.release_id != '' 103 | id: upload-release-assets 104 | uses: dwenegar/upload-release-assets@v1 105 | env: 106 | GITHUB_TOKEN: ${{ secrets.WRITE_ACCESS_TOKEN }} 107 | with: 108 | release_id: ${{ github.event.inputs.release_id }} 109 | assets_path: ./wheelhouse/*.whl 110 | -------------------------------------------------------------------------------- /.github/workflows/bump_revisions.yml: -------------------------------------------------------------------------------- 1 | name: Bump Revisions 2 | 3 | on: 4 | #schedule: 5 | # - cron: '0 10,22 * * *' 6 | 7 | workflow_dispatch: 8 | inputs: 9 | force_workflow: 10 | description: "Force run the workflows even if no changes" 11 | required: false 12 | default: "true" 13 | 14 | jobs: 15 | bump_revisions: 16 | name: "Bump revisions" 17 | runs-on: ubuntu-18.04 18 | steps: 19 | - name: Checking out repository 20 | uses: actions/checkout@v2 21 | with: 22 | token: ${{ secrets.WRITE_ACCESS_TOKEN }} 23 | 24 | - name: Fetch tags 25 | run: git fetch --depth=1 origin +refs/tags/*:refs/tags/* 26 | 27 | - name: Update revisions 28 | run: | 29 | llvm_head="$(git ls-remote -h --refs --exit-code https://github.com/llvm/llvm-project.git main | awk '{print $1}')" 30 | echo "llvm-project revision: ${llvm_head}" 31 | if [ -z "${llvm_head}" ]; then 32 | echo "Could not get head" 33 | exit 1 34 | fi 35 | echo "llvm_head=${llvm_head}" >> $GITHUB_ENV 36 | echo "${llvm_head}" > ./llvm-project.version 37 | git add ./llvm-project.version 38 | echo "has_diff=false" >> $GITHUB_ENV 39 | git diff --cached --exit-code || echo "has_diff=true" >> $GITHUB_ENV 40 | package_version="$(printf '%(%Y%m%d)T.${{ github.run_number }}')" 41 | tag_name="snapshot-${package_version}" 42 | echo "package_version=${package_version}" >> $GITHUB_ENV 43 | echo "tag_name=${tag_name}" >> $GITHUB_ENV 44 | 45 | - name: Committing updates 46 | if: env.has_diff == 'true' 47 | run: | 48 | git config --local user.email "mlir-py-release-bot-noreply@llvm.org" 49 | git config --local user.name "Bump revision action" 50 | git commit -am "Automatically updated llvm-project to ${llvm_head}" 51 | 52 | - name: Updating snapshot tag 53 | run: | 54 | git tag "${tag_name}" 55 | 56 | - name: Pushing changes 57 | uses: ad-m/github-push-action@v0.6.0 58 | with: 59 | github_token: ${{ secrets.WRITE_ACCESS_TOKEN }} 60 | branch: main 61 | tags: true 62 | 63 | - name: Create Release 64 | id: create_release 65 | uses: actions/create-release@v1 66 | env: 67 | GITHUB_TOKEN: ${{ secrets.WRITE_ACCESS_TOKEN }} 68 | with: 69 | tag_name: ${{ env.tag_name }} 70 | release_name: mlir binaries ${{ env.tag_name }} 71 | body: | 72 | Automatic release of llvm-project@${{ env.llvm_head }} 73 | draft: false 74 | prerelease: true 75 | 76 | - name: "Invoke workflow :: Build MLIR Wheels" 77 | if: "env.has_diff == 'true' || github.event.inputs.force_workflow == 'true'" 78 | uses: benc-uk/workflow-dispatch@v1 79 | with: 80 | workflow: Build MLIR Wheels 81 | token: ${{ secrets.WRITE_ACCESS_TOKEN }} 82 | ref: "${{ env.tag_name }}" 83 | inputs: '{"package_suffix": "-snapshot", "package_version": "${{ env.package_version }}", "release_id": "${{ steps.create_release.outputs.id }}"}' 84 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | *.code-workspace 3 | build/ 4 | install/ 5 | dist/ 6 | *.egg-info 7 | version_info.json 8 | -------------------------------------------------------------------------------- /.style.yapf: -------------------------------------------------------------------------------- 1 | [style] 2 | based_on_style = google 3 | column_limit = 80 4 | indent_width = 2 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MLIR Python Release Scripts 2 | 3 | This repository contains setup and packaging scripts for MLIR related 4 | projects that need to build together. They may eventually go to their 5 | respective homes, but developing them together for now helps. 6 | 7 | [![Build MLIR Wheels](https://github.com/stellaraccident/mlir-py-release/workflows/Build%20MLIR%20Wheels/badge.svg)](https://github.com/stellaraccident/mlir-py-release/actions?query=workflow%3A%22Build+MLIR+Wheels%22+branch%3Amain) 8 | 9 | [![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/stellaraccident/mlir-py-release?include_prereleases)](https://github.com/stellaraccident/mlir-py-release/releases) 10 | 11 | 12 | ## Installation 13 | 14 | Note that this is a prototype of a real MLIR release process being run by 15 | a member of the community. These are not official releases of the LLVM 16 | Foundation in any way, and they are likely only going to be useful to people 17 | actually working on LLVM/MLIR until we get things productionized. 18 | 19 | Links to more official places: 20 | 21 | * Overall [LLVM page](https://llvm.org/) 22 | * [MLIR main page](https://mlir.llvm.org/) 23 | * [MLIR Channel within LLVM Discourse](https://llvm.discourse.group/c/mlir/31) 24 | * [MLIR Python Bindings Doc](https://mlir.llvm.org/docs/Bindings/Python/) 25 | 26 | We are currently only producing snapshot releases twice a day at llvm-project 27 | head. Each time we bump the revision, we create a new "snapshot" release on 28 | the [releases page](https://github.com/stellaraccident/mlir-py-release/releases). 29 | 30 | You can use pip to install the latest for your platform directly from that 31 | page (or use a link to a specific release). Note that tests have not yet been 32 | integrated: these may not work at all. 33 | 34 | ```shell 35 | python -m pip install --upgrade mlir-snapshot -f https://github.com/stellaraccident/mlir-py-release/releases 36 | ``` 37 | 38 | And verify some things: 39 | 40 | ```python 41 | >>> import mlir 42 | >>> help(mlir._cext.ir) # TODO: Should be available under mlir.ir directly 43 | >>> from mlir.dialects import std 44 | >>> help(std) 45 | ``` 46 | 47 | Show version info: 48 | 49 | ```python 50 | # TODO: These should come from the main mlir module. 51 | >>> import _mlir_libs 52 | >>> _mlir_libs.LLVM_COMMIT 53 | '8d541a1fbe6d92a3fadf6d7d8e8209ed6c76e092' 54 | >>> _mlir_libs.VERSION 55 | '20201231.14' 56 | >>> _mlir_libs.get_lib_dir() 57 | >>> _mlir_libs.get_include_dir() 58 | ``` 59 | 60 | ## Manually packaging releases 61 | 62 | This is intended for people working on the release pipeline itself. If you 63 | just want binaries, see above. 64 | 65 | ### Prep 66 | 67 | This repository is meant to be checked out adjacent to source repositories: 68 | 69 | * `../llvm-project` : https://github.com/llvm/llvm-project.git 70 | * `../mlir-npcomp` : https://github.com/llvm/mlir-npcomp.git 71 | 72 | #### Create a virtual environment: 73 | 74 | Not strictly necessary, and if you know what you are doing, do that. Otherwise: 75 | 76 | ```shell 77 | python -m venv create ~/.venv/mlir 78 | source ~/.venv/mlir/bin/activate 79 | ``` 80 | 81 | #### Install common dependencies: 82 | 83 | ```shell 84 | python -m pip -r requirements.txt 85 | ``` 86 | 87 | NOTE: Some older distributions still have `python` as python 2. Make sure you 88 | are running python3, which on these systems is often `python3`. 89 | 90 | ### Install into current python environment 91 | 92 | If you are just looking to get packages that you can import and use, do: 93 | 94 | ```shell 95 | python ./setup_mlir.py install 96 | ``` 97 | 98 | ### Build wheel files (installable archives) 99 | 100 | ```shell 101 | python ./setup_mlir.py bdist_wheel 102 | ``` 103 | 104 | ## Design methodology 105 | 106 | The binary distribution is taking the approach of building minimal packages 107 | with the API granularity that we intend to make public. This means that some 108 | things are not available yet, usually because their underlying public APIs 109 | are still in progress (or not started). It is much more effective to only 110 | add things that you intend to support vs adding everything in a haphazzard 111 | way and never be able to trim it down again. 112 | 113 | As an example, a static, visibility hidden build of `libMLIRPublicAPI.so` 114 | comes in at 6MiB on manylinux2014 (and the entire python wheel compresses down 115 | to ~2.5MiB). To contrast this, a dynamic build of `libMLIR.so` is roughly 4x 116 | that size, and `libLLVM.so` even more-so (by multiples). Included in the 117 | smaller library are all core dialects, the public C-API, public C-API headers, 118 | and core transformations. For things that *only* need this, the size is fairly 119 | compelling. 120 | 121 | There is definitely work to layer the other features that are useful, such 122 | as JIT-ing, execution engines, LLVM code generation, etc, but these are 123 | solvable technical problems that should only add cost to the people who 124 | need them. By starting small and adding, we should be able to get to a 125 | reasonable place and acrete good API boundaries in the process. This may mean 126 | that some integrations need to wait, but that is fine. 127 | 128 | It should also be noted that while a lot of people come to MLIR as a gateway 129 | to LLVM code generation, it is useful for much more than that. As an example, 130 | a full, linear algebra compilation system to SPIR-V based GPUs *only* needs 131 | roughly the features in the above core API. Ditto for systems like IREE when 132 | not targeting CPUs via LLVM. 133 | -------------------------------------------------------------------------------- /llvm-project.version: -------------------------------------------------------------------------------- 1 | 10cb03622325e699d53fbca819e03dca2519f5aa 2 | -------------------------------------------------------------------------------- /packages/mlir/setup.py: -------------------------------------------------------------------------------- 1 | # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 2 | # See https://llvm.org/LICENSE.txt for license information. 3 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 4 | 5 | # This setup.py file adapted from many places, including: 6 | # https://github.com/pytorch/pytorch/blob/master/setup.py 7 | # various places on stack overflow 8 | # IREE setup files 9 | # (does anyone write these things except by copy-paste-mash-keys until it 10 | # works?) 11 | 12 | # This future is needed to print Python2 EOL message 13 | from __future__ import print_function 14 | import sys 15 | if sys.version_info < (3,): 16 | print("Python 2 has reached end-of-life and is no longer supported.") 17 | sys.exit(-1) 18 | if sys.platform == 'win32' and sys.maxsize.bit_length() == 31: 19 | print( 20 | "32-bit Windows Python runtime is not supported. Please switch to 64-bit Python." 21 | ) 22 | sys.exit(-1) 23 | 24 | import importlib 25 | import platform 26 | python_min_version = (3, 6, 2) 27 | python_min_version_str = '.'.join(map(str, python_min_version)) 28 | if sys.version_info < python_min_version: 29 | print("You are using Python {}. Python >={} is required.".format( 30 | platform.python_version(), python_min_version_str)) 31 | sys.exit(-1) 32 | 33 | import json 34 | import os 35 | import pathlib 36 | import subprocess 37 | import shutil 38 | import sysconfig 39 | 40 | from distutils.command.install_data import install_data 41 | from setuptools import setup, Extension, distutils, find_packages 42 | from setuptools.command.build_ext import build_ext 43 | from setuptools.command.install_lib import install_lib 44 | from setuptools.command.install_scripts import install_scripts 45 | from distutils import core 46 | from distutils.core import Distribution 47 | from distutils.errors import DistutilsArgError 48 | 49 | ################################################################################ 50 | # Parameters parsed from environment 51 | ################################################################################ 52 | 53 | is_windows = platform.system() == 'Windows' 54 | 55 | VERBOSE_SCRIPT = True 56 | RUN_BUILD_DEPS = True 57 | # see if the user passed a quiet flag to setup.py arguments and respect 58 | # that in our parts of the build 59 | EMIT_BUILD_WARNING = False 60 | RERUN_CMAKE = False 61 | CMAKE_ONLY = False 62 | filtered_args = [] 63 | for i, arg in enumerate(sys.argv): 64 | if arg == '--cmake': 65 | RERUN_CMAKE = True 66 | continue 67 | if arg == '--cmake-only': 68 | # Stop once cmake terminates. Leave users a chance to adjust build 69 | # options. 70 | CMAKE_ONLY = True 71 | continue 72 | if arg == "--": 73 | filtered_args += sys.argv[i:] 74 | break 75 | if arg == '-q' or arg == '--quiet': 76 | VERBOSE_SCRIPT = False 77 | filtered_args.append(arg) 78 | sys.argv = filtered_args 79 | 80 | if VERBOSE_SCRIPT: 81 | 82 | def report(*args): 83 | print('--', *args) 84 | else: 85 | 86 | def report(*args): 87 | pass 88 | 89 | 90 | def abort(*args): 91 | print('!! ERROR:', *args) 92 | sys.exit(1) 93 | 94 | 95 | def get_setting(varname, default_value): 96 | value = os.environ.get(varname) 97 | if value is None: 98 | return default_value 99 | return value 100 | 101 | 102 | def get_bool_setting(varname, default_value): 103 | value = get_setting(varname, default_value) 104 | if value is True or value is False: 105 | return value 106 | return value == '' or value == 'ON' or value == '1' 107 | 108 | 109 | def which(thefile): 110 | path = os.environ.get("PATH", os.defpath).split(os.pathsep) 111 | for d in path: 112 | fname = os.path.join(d, thefile) 113 | fnames = [fname] 114 | if sys.platform == 'win32': 115 | exts = os.environ.get('PATHEXT', '').split(os.pathsep) 116 | fnames += [fname + ext for ext in exts] 117 | for name in fnames: 118 | if os.access(name, os.F_OK | os.X_OK) and not os.path.isdir(name): 119 | return name 120 | return None 121 | 122 | 123 | def use_tool_path(toolname): 124 | value = get_setting(f'USE_{toolname.upper()}', 'ON') 125 | if value.upper() == 'OFF': 126 | return None 127 | if value.upper() == 'ON' or value == '': 128 | return which(toolname) 129 | if os.access(value, os.F_OK | os.X_OK) and not os.path.isdir(value): 130 | return value 131 | 132 | 133 | ################################################################################ 134 | # Build deps. 135 | ################################################################################ 136 | def check_py_dep(modulename, package): 137 | try: 138 | importlib.import_module(modulename) 139 | except ModuleNotFoundError: 140 | abort( 141 | f'Could not find required build-time module "{modulename}"\n' 142 | f' (typically installed via "{sys.executable} -m pip install {package}")' 143 | ) 144 | 145 | 146 | check_py_dep('pybind11', 'pybind11') 147 | check_py_dep('numpy', 'numpy') 148 | 149 | ################################################################################ 150 | # Figure out where we are and where we are going. 151 | ################################################################################ 152 | # report("Environment:") 153 | # for env_key in os.environ: 154 | # report(f" : {env_key} = {os.environ.get(env_key)}") 155 | repo_root = os.path.abspath( 156 | get_setting('REPO_DIR', os.path.join(os.path.dirname(__file__), '..', 157 | '..'))) 158 | report(f'Using REPO_DIR = {repo_root}') 159 | llvm_repo_dir = get_setting( 160 | 'LLVM_REPO_DIR', 161 | os.path.abspath(os.path.join(repo_root, '..', 'llvm-project'))) 162 | report(f'Using LLVM_REPO_DIR = {llvm_repo_dir}') 163 | if not os.path.isfile(os.path.join(llvm_repo_dir, 'llvm', 'CMakeLists.txt')): 164 | abort(f'Could not find LLVM sources in {llvm_repo_dir}') 165 | build_dir = os.path.join(repo_root, 'build', 'llvm') 166 | install_dir = os.path.join(repo_root, 'install', 'llvm') 167 | 168 | ################################################################################ 169 | # Load version_info.json 170 | ################################################################################ 171 | 172 | def load_version_info(): 173 | with open(os.path.join(repo_root, 'version_info.json'), 'rt') as f: 174 | return json.load(f) 175 | try: 176 | version_info = load_version_info() 177 | except FileNotFoundError: 178 | version_info = {} 179 | 180 | ################################################################################ 181 | # Clean up CMakeCache.txt. 182 | # This may seem counter-intuitive, but for a CI that may cycle through a 183 | # couple of configurations, just clearing the cache between runs can let us 184 | # get some incrementality to the artifacts while building for different 185 | # python versions. 186 | ################################################################################ 187 | 188 | cmake_cache_file = os.path.join(build_dir, 'CMakeCache.txt') 189 | if os.path.exists(cmake_cache_file): 190 | report('Removing existing CMakeCache.txt') 191 | os.unlink(cmake_cache_file) 192 | 193 | ################################################################################ 194 | # CMake configure. 195 | ################################################################################ 196 | release_mode = get_bool_setting('RELEASE_MODE', True) 197 | assertions = get_bool_setting('LLVM_ASSERTIONS', False) 198 | stripped = '-stripped' if release_mode else '' 199 | 200 | cmake_args = [ 201 | f'-S{os.path.join(llvm_repo_dir, "llvm")}', 202 | f'-B{build_dir}', 203 | '-DCMAKE_CXX_VISIBILITY_PRESET=hidden', 204 | '-DCMAKE_VISIBILITY_INLINES_HIDDEN=ON', 205 | # We use private libs and special fixups to find everything. 206 | '-DCMAKE_PLATFORM_NO_VERSIONED_SONAME=ON', 207 | f'-DCMAKE_INSTALL_PREFIX={install_dir}', 208 | f'-DCMAKE_BUILD_TYPE={"Release" if release_mode else "RelWithDebInfo"}', 209 | f'-DLLVM_ENABLE_ASSERTIONS={"ON" if assertions else "OFF"}', 210 | '-DLLVM_TARGETS_TO_BUILD=host', 211 | '-DLLVM_ENABLE_PROJECTS=mlir', 212 | '-DMLIR_BINDINGS_PYTHON_ENABLED=ON', 213 | '-DMLIR_PYTHON_BINDINGS_VERSION_LOCKED=OFF', 214 | f'-DPython3_EXECUTABLE:FILEPATH={sys.executable}', 215 | # Configure the obsolete python executable property too. It can latch 216 | # incorrectly if it hits the wrong way. 217 | f'-DPYTHON_EXECUTABLE:FILEPATH={sys.executable}', 218 | f'-DPython3_INCLUDE_DIR:PATH={sysconfig.get_path("include")}', 219 | ] 220 | 221 | cmake_targets = [ 222 | # Headers. 223 | 'install-mlir-headers', 224 | # Python bindings. 225 | 'install-MLIRBindingsPythonSources', 226 | 'install-MLIRBindingsPythonDialects', 227 | # C-API shared library/DLL. 228 | f'install-MLIRPublicAPI{stripped}', 229 | # Python extensions. 230 | f'install-MLIRTransformsBindingsPythonExtension{stripped}', 231 | f'install-MLIRCoreBindingsPythonExtension{stripped}', 232 | ] 233 | 234 | ### HACK: Add a Python3_LIBRARY because cmake needs it, but it legitimately 235 | ### does not exist on manylinux (or any linux static python). 236 | # Need to explicitly tell cmake about the python library. 237 | python_libdir = sysconfig.get_config_var('LIBDIR') 238 | python_library = sysconfig.get_config_var('LIBRARY') 239 | if python_libdir and not os.path.isabs(python_library): 240 | python_library = os.path.join(python_libdir, python_library) 241 | 242 | # On manylinux, python is a static build, which should be fine, but CMake 243 | # disagrees. Fake it by letting it see a library that will never be needed. 244 | if python_library and not os.path.exists(python_library): 245 | python_libdir = os.path.join(install_dir, 'fake_python/lib') 246 | os.makedirs(python_libdir, exist_ok=True) 247 | python_library = os.path.join(python_libdir, 248 | sysconfig.get_config_var('LIBRARY')) 249 | with open(python_library, 'wb') as f: 250 | pass 251 | 252 | if python_library: 253 | cmake_args.append(f'-DPython3_LIBRARY:PATH={python_library}') 254 | 255 | ### Only enable shared library build on non-windows. 256 | ### TODO: Break this out into a separate dev package. 257 | if not is_windows and False: 258 | cmake_args.append('-DLLVM_BUILD_LLVM_DYLIB=ON') 259 | # Enable development mode targets. 260 | cmake_targets.extend([ 261 | # Headers. 262 | 'install-llvm-headers', 263 | 'install-mlir-headers', 264 | # CMake exports. 265 | 'install-cmake-exports', 266 | 'install-mlir-cmake-exports', 267 | # Shared libs. 268 | f'install-MLIR{stripped}', 269 | f'install-LLVM{stripped}', 270 | # Tools needed to build. 271 | f'install-mlir-tblgen{stripped}', 272 | ]) 273 | 274 | ### Detect generator. 275 | if use_tool_path('ninja'): 276 | report('Using ninja') 277 | cmake_args.append('-GNinja') 278 | elif is_windows: 279 | cmake_args.extend(['-G', 'NMake Makefiles']) 280 | 281 | # Detect other build tools. 282 | use_ccache = use_tool_path('ccache') 283 | if use_ccache: 284 | report(f'Using ccache {use_ccache}') 285 | cmake_args.append(f'-DCMAKE_CXX_COMPILER_LAUNCHER={use_ccache}') 286 | use_lld = use_tool_path('lld') 287 | if not is_windows and use_lld: 288 | report(f'Using linker {use_lld}') 289 | cmake_args.append('-DLLVM_USE_LINKER=lld') 290 | 291 | report(f'Running cmake (generate): {" ".join(cmake_args)}') 292 | subprocess.check_call(['cmake'] + cmake_args) 293 | if CMAKE_ONLY: 294 | sys.exit(0) 295 | 296 | cmake_build_args = [ 297 | 'cmake', 298 | '--build', 299 | build_dir, 300 | '--target', 301 | ] + cmake_targets 302 | report(f'Running cmake (build/install): {" ".join(cmake_build_args)}') 303 | subprocess.check_call(cmake_build_args) 304 | 305 | ### Hand-off to setuptools. 306 | # Parse the command line and check the arguments 307 | # before we proceed with building deps and setup 308 | dist = Distribution() 309 | dist.script_name = sys.argv[0] 310 | dist.script_args = sys.argv[1:] 311 | try: 312 | ok = dist.parse_command_line() 313 | except DistutilsArgError as msg: 314 | raise SystemExit(core.gen_usage(dist.script_name) + "\nerror: %s" % msg) 315 | if not ok: 316 | report('Finished running cmake configure and configured to exit.') 317 | report(f'You can continue manually in the build dir: {build_dir}') 318 | sys.exit() 319 | 320 | # We do something tricky here with the directory layouts, synthesizing a 321 | # top-level |mlir| package for the pure-python parts from $install_dir/python. 322 | # Then we synthesize a "package" out of the install directory itself, 323 | # including it as a |_mlir_libs| top-level package that then contains the 324 | # native extensions under |_mlir_libs.python|, just like they are laid out 325 | # on disk by the build system. This has the nice side-effect of letting us 326 | # basically just emit the LLVM install dir as a python package and have 327 | # everything work. The upstream |mlir| __init__.py is smart enough to 328 | # see if it is in such an arrangement and change its behavior for such an 329 | # out of tree distribution. 330 | # We then put an __init__.py in the top-level install directory with a little 331 | # API to query for build info and load extensions. 332 | 333 | package_dir = os.path.join(install_dir, 'python') 334 | packages = find_packages(where=package_dir) 335 | report('Found packages:', packages) 336 | 337 | header_files = [ 338 | str(p.relative_to(install_dir)) 339 | for p in pathlib.Path(install_dir).glob('include/mlir-c/**/*') 340 | ] 341 | 342 | MLIR_LIB_INIT = f''' 343 | import importlib 344 | import os 345 | import platform 346 | 347 | SUFFIX = "{version_info.get('package-suffix') or ''}" 348 | VERSION = "{version_info.get('package-version') or '0.1a1'}" 349 | LLVM_COMMIT = "{version_info.get('llvm-revision') or 'UNKNOWN'}" 350 | 351 | _is_windows = platform.system() == "Windows" 352 | _this_directory = os.path.dirname(__file__) 353 | 354 | def get_install_dir(): 355 | """Gets the install directory of the LLVM tree.""" 356 | return os.path.dirname(__file__) 357 | 358 | def get_include_dir(): 359 | """Gets the directory for include files.""" 360 | return os.path.join(get_install_dir(), "include") 361 | 362 | def get_lib_dir(): 363 | """Gets the directory for include files.""" 364 | return os.path.join(get_install_dir(), "lib") 365 | 366 | def load_extension(name): 367 | """Loads a native extension bundled with these libraries.""" 368 | return importlib.import_module("_mlir_libs.python." + name) 369 | 370 | # The standard LLVM distribution tree for Windows is laid out as: 371 | # __init__.py (this file) 372 | # bin/ 373 | # MLIRPublicAPI.dll 374 | # python/ 375 | # _mlir.*.pyd (dll extension) 376 | # First check the bin/ directory level for DLLs co-located with the pyd 377 | # file, and then fall back to searching the python/ directory. 378 | _dll_search_path = [ 379 | os.path.join(_this_directory, "bin"), 380 | os.path.join(_this_directory, "python"), 381 | ] 382 | 383 | # Stash loaded DLLs to keep them alive. 384 | _loaded_dlls = [] 385 | 386 | def preload_dependency(public_name): 387 | """Preloads a dylib by its soname or DLL name. 388 | 389 | On Windows and Linux, doing this prior to loading a dependency will populate 390 | the library in the flat namespace so that a subsequent library that depend 391 | on it will resolve to this preloaded version. 392 | 393 | On OSX, resolution is completely path based so this facility no-ops. On 394 | Linux, as long as RPATHs are setup properly, resolution is path based but 395 | this facility can still act as an escape hatch for relocatable distributions. 396 | """ 397 | if _is_windows: 398 | _preload_dependency_windows(public_name) 399 | 400 | 401 | def _preload_dependency_windows(public_name): 402 | dll_basename = public_name + ".dll" 403 | found_path = None 404 | for search_dir in _dll_search_path: 405 | candidate_path = os.path.join(search_dir, dll_basename) 406 | if os.path.exists(candidate_path): 407 | found_path = candidate_path 408 | break 409 | 410 | if found_path is None: 411 | raise RuntimeError( 412 | "Unable to find dependency DLL %s in search " 413 | "path %r" % (dll_basename, _dll_search_path)) 414 | 415 | import ctypes 416 | _loaded_dlls.append(ctypes.CDLL(found_path)) 417 | 418 | ''' 419 | 420 | # Turn the install directory into a valid package. 421 | with open(os.path.join(install_dir, '__init__.py'), 'wt') as init_file: 422 | init_file.write(MLIR_LIB_INIT) 423 | with open(os.path.join(install_dir, 'python', '__init__.py'), 424 | 'wt') as init_file: 425 | pass 426 | 427 | setup( 428 | name=f'mlir{version_info.get("package-suffix") or ""}', 429 | version=version_info.get("package-version") or "0.1a1", 430 | packages=packages + [ 431 | '_mlir_libs', 432 | '_mlir_libs.python', 433 | ], 434 | package_dir={ 435 | 'mlir': os.path.join(install_dir, 'python', 'mlir'), 436 | '_mlir_libs': os.path.join(install_dir), 437 | }, 438 | ext_modules=[ 439 | # Note that this matches the build/install directory structure, 440 | # which makes rpath work properly. 441 | Extension(name="_mlir_libs.python._mlir", sources=[]), 442 | Extension(name="_mlir_libs.python._mlirTransforms", sources=[]), 443 | ], 444 | package_data={ 445 | '_mlir_libs': [ 446 | # By including the build extensions as package data, it keeps 447 | # the setuptools auto-builder from "compiling" them into a 448 | # static binary. 449 | f'python/*{sysconfig.get_config_var("EXT_SUFFIX")}', 450 | 451 | # Windows DLLs go in the bin dir and are otherwise not linked. 452 | # Import libs go in the lib dir. 453 | 'bin/*.dll', 454 | 'lib/*.lib', 455 | # Note that wild-carding all *.so duplicates all of the symlinks, 456 | # so we list one by one just the public names. 457 | 'lib/libMLIRPublicAPI.so', 458 | 'lib/libMLIRPublicAPI.dylib', 459 | 460 | # Cmake files. 461 | 'lib/cmake/llvm/*.cmake', 462 | 'lib/cmake/mlir/*.cmake', 463 | 464 | # Build tools. 465 | 'bin/mlir-tblgen*', 466 | ] + header_files, 467 | }, 468 | description='MLIR Python API', 469 | long_description=open( 470 | os.path.join(llvm_repo_dir, 'mlir', 'docs', 'Bindings', 'Python.md'), 471 | 'r').read(), 472 | long_description_content_type="text/markdown", 473 | keywords="llvm, mlir", 474 | classifiers=[ 475 | "Intended Audience :: Developers", "License :: OSI Approved :: " 476 | "Apache-2.0 WITH LLVM-exception", "Natural Language :: English", 477 | "Programming Language :: C", "Programming Language :: C++", 478 | "Programming Language :: Python", 479 | "Programming Language :: Python :: Implementation :: CPython" 480 | ], 481 | license='Apache-2.0 WITH LLVM-exception', 482 | zip_safe=False) 483 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy>=1.19.4 2 | pybind11>=2.6.1 3 | # More recent cmake needed for Python3 build in static setup 4 | cmake>=3.18.4 5 | ninja 6 | wheel 7 | -------------------------------------------------------------------------------- /scripts/checkout_repo.py: -------------------------------------------------------------------------------- 1 | # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 2 | # See https://llvm.org/LICENSE.txt for license information. 3 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 4 | 5 | # Usage: 6 | # checkout_repo.py path repo_url branch version_file 7 | 8 | import os 9 | import subprocess 10 | import sys 11 | 12 | repo_path, repo_url, branch, version_file = sys.argv[1:] 13 | 14 | with open(version_file, "rt") as f: 15 | revision = f.read().strip() 16 | 17 | print(f"Checkout out repo {repo_path} from {repo_url} at revision {revision}") 18 | 19 | os.makedirs(repo_path) 20 | 21 | 22 | def run(*args, cwd=repo_path): 23 | print(f"Run: {' '.join(args)} [from {cwd}]") 24 | subprocess.check_call(args, cwd=cwd) 25 | 26 | 27 | run("git", "init") 28 | run("git", "remote", "add", "origin", repo_url) 29 | run("git", "config", "--local", "gc.auto", "0") 30 | run("git", "-c", "protocol.version=2", "fetch", "--no-tags", "--prune", 31 | "--progress", "--no-recurse-submodules", "--depth=1", "origin", 32 | f"+{revision}:refs/remotes/origin/{branch}") 33 | run("git", "checkout", "--progress", "--force", "-B", branch, 34 | "refs/remotes/origin/main") 35 | run("git", "log", "-1", "--format='%H'") 36 | -------------------------------------------------------------------------------- /testing.md: -------------------------------------------------------------------------------- 1 | #MLIR-Py-Release Testing Matrix 2 | 3 | MLIR-Py-Release process and functionality has been tested successfully on the following OS/Python versions: 4 | 5 | ##Linux 6 | 7 | - Ubuntu 20.04 LTS with Python 3.8.5 8 | - Ubuntu 18.04 LTS with Python 3.6.9 9 | - [TODO] Ubuntu 16.04 LTS with Python 3.5.2 10 | 11 | ##Windows 12 | 13 | - Windows 10 Pro with Python 3.8.7 [WITH HACKS] 14 | 15 | ##Mac OS X 16 | 17 | - macOS 11 (Big Sur) with Python 3.9.1 18 | - macOS 10.15 (Catalina) with Python 3.7.9 19 | --------------------------------------------------------------------------------