Skip to content

Commit ec93c97

Browse files
committed
Update README, LICENSE and add some basic code
Docs and initial script for installing torch-mlir for AMD/NV/Intel
1 parent 4a55b18 commit ec93c97

File tree

5 files changed

+312
-23
lines changed

5 files changed

+312
-23
lines changed

LICENSE

Lines changed: 98 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1+
==============================================================================
2+
The Lighthouse Project is under the Apache License v2.0 with LLVM Exceptions:
3+
==============================================================================
4+
15
Apache License
26
Version 2.0, January 2004
37
http://www.apache.org/licenses/
48

5-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
610

7-
1. Definitions.
11+
1. Definitions.
812

913
"License" shall mean the terms and conditions for use, reproduction,
1014
and distribution as defined by Sections 1 through 9 of this document.
@@ -63,14 +67,14 @@
6367
on behalf of whom a Contribution has been received by Licensor and
6468
subsequently incorporated within the Work.
6569

66-
2. Grant of Copyright License. Subject to the terms and conditions of
70+
2. Grant of Copyright License. Subject to the terms and conditions of
6771
this License, each Contributor hereby grants to You a perpetual,
6872
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6973
copyright license to reproduce, prepare Derivative Works of,
7074
publicly display, publicly perform, sublicense, and distribute the
7175
Work and such Derivative Works in Source or Object form.
7276

73-
3. Grant of Patent License. Subject to the terms and conditions of
77+
3. Grant of Patent License. Subject to the terms and conditions of
7478
this License, each Contributor hereby grants to You a perpetual,
7579
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7680
(except as stated in this section) patent license to make, have made,
@@ -86,7 +90,7 @@
8690
granted to You under this License for that Work shall terminate
8791
as of the date such litigation is filed.
8892

89-
4. Redistribution. You may reproduce and distribute copies of the
93+
4. Redistribution. You may reproduce and distribute copies of the
9094
Work or Derivative Works thereof in any medium, with or without
9195
modifications, and in Source or Object form, provided that You
9296
meet the following conditions:
@@ -127,20 +131,20 @@
127131
reproduction, and distribution of the Work otherwise complies with
128132
the conditions stated in this License.
129133

130-
5. Submission of Contributions. Unless You explicitly state otherwise,
134+
5. Submission of Contributions. Unless You explicitly state otherwise,
131135
any Contribution intentionally submitted for inclusion in the Work
132136
by You to the Licensor shall be under the terms and conditions of
133137
this License, without any additional terms or conditions.
134138
Notwithstanding the above, nothing herein shall supersede or modify
135139
the terms of any separate license agreement you may have executed
136140
with Licensor regarding such Contributions.
137141

138-
6. Trademarks. This License does not grant permission to use the trade
142+
6. Trademarks. This License does not grant permission to use the trade
139143
names, trademarks, service marks, or product names of the Licensor,
140144
except as required for reasonable and customary use in describing the
141145
origin of the Work and reproducing the content of the NOTICE file.
142146

143-
7. Disclaimer of Warranty. Unless required by applicable law or
147+
7. Disclaimer of Warranty. Unless required by applicable law or
144148
agreed to in writing, Licensor provides the Work (and each
145149
Contributor provides its Contributions) on an "AS IS" BASIS,
146150
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
@@ -150,7 +154,7 @@
150154
appropriateness of using or redistributing the Work and assume any
151155
risks associated with Your exercise of permissions under this License.
152156

153-
8. Limitation of Liability. In no event and under no legal theory,
157+
8. Limitation of Liability. In no event and under no legal theory,
154158
whether in tort (including negligence), contract, or otherwise,
155159
unless required by applicable law (such as deliberate and grossly
156160
negligent acts) or agreed to in writing, shall any Contributor be
@@ -162,7 +166,7 @@
162166
other commercial damages or losses), even if such Contributor
163167
has been advised of the possibility of such damages.
164168

165-
9. Accepting Warranty or Additional Liability. While redistributing
169+
9. Accepting Warranty or Additional Liability. While redistributing
166170
the Work or Derivative Works thereof, You may choose to offer,
167171
and charge a fee for, acceptance of support, warranty, indemnity,
168172
or other liability obligations and/or rights consistent with this
@@ -173,9 +177,9 @@
173177
incurred by, or claims asserted against, such Contributor by reason
174178
of your accepting any such warranty or additional liability.
175179

176-
END OF TERMS AND CONDITIONS
180+
END OF TERMS AND CONDITIONS
177181

178-
APPENDIX: How to apply the Apache License to your work.
182+
APPENDIX: How to apply the Apache License to your work.
179183

180184
To apply the Apache License to your work, attach the following
181185
boilerplate notice, with the fields enclosed by brackets "[]"
@@ -186,16 +190,89 @@
186190
same "printed page" as the copyright notice for easier
187191
identification within third-party archives.
188192

189-
Copyright [yyyy] [name of copyright owner]
193+
Copyright [yyyy] [name of copyright owner]
190194

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
195+
Licensed under the Apache License, Version 2.0 (the "License");
196+
you may not use this file except in compliance with the License.
197+
You may obtain a copy of the License at
194198

195199
http://www.apache.org/licenses/LICENSE-2.0
196200

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.
201+
Unless required by applicable law or agreed to in writing, software
202+
distributed under the License is distributed on an "AS IS" BASIS,
203+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204+
See the License for the specific language governing permissions and
205+
limitations under the License.
206+
207+
208+
---- LLVM Exceptions to the Apache 2.0 License ----
209+
210+
As an exception, if, as a result of your compiling your source code, portions
211+
of this Software are embedded into an Object form of such source code, you
212+
may redistribute such embedded portions in such Object form without complying
213+
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
214+
215+
In addition, if you combine or link compiled forms of this Software with
216+
software that is licensed under the GPLv2 ("Combined Software") and if a
217+
court of competent jurisdiction determines that the patent provision (Section
218+
3), the indemnity provision (Section 9) or other Section of the License
219+
conflicts with the conditions of the GPLv2, you may retroactively and
220+
prospectively choose to deem waived or otherwise exclude such Section(s) of
221+
the License, but only in their entirety and only with respect to the Combined
222+
Software.
223+
224+
==============================================================================
225+
Software from third parties included in the LLVM Project:
226+
==============================================================================
227+
The LLVM Project contains third party software which is under different license
228+
terms. All such code will be identified clearly using at least one of two
229+
mechanisms:
230+
1) It will be in a separate directory tree with its own `LICENSE.txt` or
231+
`LICENSE` file at the top containing the specific license and restrictions
232+
which apply to that software, or
233+
2) It will contain specific license and restriction terms at the top of every
234+
file.
235+
236+
==============================================================================
237+
Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy):
238+
==============================================================================
239+
University of Illinois/NCSA
240+
Open Source License
241+
242+
Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign.
243+
All rights reserved.
244+
245+
Developed by:
246+
247+
LLVM Team
248+
249+
University of Illinois at Urbana-Champaign
250+
251+
http://llvm.org
252+
253+
Permission is hereby granted, free of charge, to any person obtaining a copy of
254+
this software and associated documentation files (the "Software"), to deal with
255+
the Software without restriction, including without limitation the rights to
256+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
257+
of the Software, and to permit persons to whom the Software is furnished to do
258+
so, subject to the following conditions:
259+
260+
* Redistributions of source code must retain the above copyright notice,
261+
this list of conditions and the following disclaimers.
262+
263+
* Redistributions in binary form must reproduce the above copyright notice,
264+
this list of conditions and the following disclaimers in the
265+
documentation and/or other materials provided with the distribution.
266+
267+
* Neither the names of the LLVM Team, University of Illinois at
268+
Urbana-Champaign, nor the names of its contributors may be used to
269+
endorse or promote products derived from this Software without specific
270+
prior written permission.
271+
272+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
273+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
274+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
275+
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
276+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
277+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
278+
SOFTWARE.

README.md

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,49 @@
1-
# lighthouse
2-
MLIR Lighthouse Project
1+
# MLIR Lighthouse Project
2+
3+
This project implements the RFC: https://discourse.llvm.org/t/rfc-mlir-project-lighthouse/86738
4+
5+
_"In essence, this project should guide you through using MLIR for your own projects, showing the way, but not forcing you to follow a particular path. Essentially, the role of a lighthouse."_
6+
7+
### Disclaimer
8+
9+
This project uses LLVM to test and validate various pipelines and assumptions about the MLIR project, but it is not part of any LLVM releases, nor is a dependency for MLIR to operate.
10+
11+
You should use this project to guide you through MLIR pipelines, schedules and transforms, as well as understanding how to connect ingress frameworks and how to execute the egress on appropriate hardware.
12+
13+
## Project Overview
14+
15+
The project is separated into three parts:
16+
* **Ingress:** Frameworks that convert source objects (code, models, designs) into MLIR files that the MLIR project can consume.
17+
* **Scheduler**: The core MLIR component that allows one to choose particular schedules, transforms, dialects to construct pipelines and pass that MLIR ingress through and reach some egress format (LLVM IR, SPIR-V, etc).
18+
* **Runtime**: Environments that can consume the egress format, install/load the appropriate libraries and tools, and execute the output on some target (hardware, simulator, further tools).
19+
20+
The upstream _lighthouse_ project needs to keep the three parts restricted to upstream / publicly available technology. In essence, public ingress and conversion projects, upstream MLIR dialects and transforms, and public execution engines that can be automatically installed and executed without going through private repositories, license agreement, etc.
21+
22+
A downstream fork of the _lighthouse_ project could extend any and all of the three parts to reach private repositories and tools, execute downstream schedules, load private dialects, etc.
23+
24+
The main purposes of this project, in chronological order, are:
25+
1. To **test and validate the existing assumptions in the upstream MLIR repository**, by encoding common ingress paths, transform schedules, pipelines, target differentiation and basic execution.
26+
2. To help MLIR developers **find common patterns on their pipelines**, and propose actions to merge and reuse upstream code for the same purposes.
27+
3. Once common patterns are detected, to **discuss and agree on dialect design, canonical shapes, and common invariants**, to promote upstream and downstream collaboration on the same grounds.
28+
4. Build a solid base to guide downstream projects (open or closed source) to **fork this project and build on top of it**, making it easier to separate upstream/downstream parts and make it easier to upstream the delta to MLIR and/or the _lighthouse_.
29+
5. In time, this could eventually be the **seed for official upstream tooling that uses MLIR in production environments**, like Clang is to LLVM.
30+
31+
### Upstream MLIR / upstream Lighthouse
32+
33+
One key point in the proposal was to not hold _"load bearing"_ code in this repository, but instead, upstream it to MLIR proper and _use_ it here.
34+
35+
It should be fine to have schedule descriptions, aggregation transforms and passes that _use_ the upstream MLIR transforms and passes, but we should _not_ add actual transforms, dialects and passes here to _complement_ the MLIR story.
36+
37+
## Testing Framework
38+
39+
This project should have the same initial purpose as the LLVM Test Suite [https://github.com/llvm/llvm-test-suite], but for MLIR.
40+
41+
### How To Run Tests
42+
43+
#### Choose Your Ingress
44+
45+
#### Choose Your Schedules
46+
47+
#### Choose Your Target
48+
49+
#### Run The Tests
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import os
5+
import torch
6+
import torch.nn as nn
7+
from torch_mlir import fx
8+
from torch_mlir.fx import OutputType
9+
10+
# Parse arguments for selecting which model to load and which MLIR dialect to generate
11+
def parse_args():
12+
parser = argparse.ArgumentParser(description="Generate MLIR for Torch-MLIR models.")
13+
parser.add_argument(
14+
"--model",
15+
type=str,
16+
required=True,
17+
help="Path to the Torch model file.",
18+
)
19+
parser.add_argument(
20+
"--dialect",
21+
type=str,
22+
choices=["torch", "linalg", "stablehlo", "tosa"],
23+
default="linalg",
24+
help="MLIR dialect to generate.",
25+
)
26+
return parser.parse_args()
27+
28+
# Functin to load the Torch model
29+
def load_torch_model(model_path):
30+
31+
if not os.path.exists(model_path):
32+
raise FileNotFoundError(f"Model file {model_path} does not exist.")
33+
34+
model = torch.load(model_path)
35+
return model
36+
37+
# Function to generate MLIR from the Torch model
38+
# See: https://github.com/MrSidims/PytorchExplorer/blob/main/backend/server.py#L237
39+
def generate_mlir(model, dialect):
40+
41+
# Convert the Torch model to MLIR
42+
output_type = None
43+
if dialect == "torch":
44+
output_type = OutputType.TORCH
45+
elif dialect == "linalg":
46+
output_type = OutputType.LINALG
47+
elif dialect == "stablehlo":
48+
output_type = OutputType.STABLEHLO
49+
elif dialect == "tosa":
50+
output_type = OutputType.TOSA
51+
else:
52+
raise ValueError(f"Unsupported dialect: {dialect}")
53+
54+
module = fx.export_and_import(model, "", output_type=output_type)
55+
return module
56+
57+
# Main function to execute the script
58+
def main():
59+
args = parse_args()
60+
61+
# Load the Torch model
62+
model = load_torch_model(args.model)
63+
64+
# Generate MLIR from the model
65+
mlir_module = generate_mlir(model, args.dialect)
66+
67+
# Print or save the MLIR module
68+
print(mlir_module)
69+
70+
# Entry point for the script
71+
if __name__ == "__main__":
72+
main()
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env bash
2+
3+
# Command line argument for model to load and MLIR dialect to generate
4+
while getopts "m:d:" opt; do
5+
case $opt in
6+
m)
7+
MODEL=$OPTARG
8+
;;
9+
d)
10+
DIALECT=$OPTARG
11+
;;
12+
*)
13+
echo "Usage: $0 [-m model] [-d dialect]"
14+
exit 1
15+
;;
16+
esac
17+
done
18+
if [ -z "$MODEL" ]; then
19+
echo "Model not specified. Please provide a model using -m option."
20+
exit 1
21+
fi
22+
if [ -z "$DIALECT" ]; then
23+
DIALECT="linalg"
24+
fi
25+
26+
# Enable local virtualenv created by install-virtualenv.sh
27+
if [ ! -d "torch-mlir-venv" ]; then
28+
echo "Virtual environment not found. Please run install-virtualenv.sh first."
29+
exit 1
30+
fi
31+
source torch-mlir-venv/bin/activate
32+
33+
# Find script directory
34+
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
35+
36+
# Use the Python script to generate MLIR
37+
echo "Generating MLIR for model '$MODEL' with dialect '$DIALECT'..."
38+
python $SCRIPT_DIR/generate-mlir.py --model "$MODEL" --dialect "$DIALECT"
39+
if [ $? -ne 0 ]; then
40+
echo "Failed to generate MLIR for model '$MODEL'."
41+
exit 1
42+
fi

0 commit comments

Comments
 (0)