-
Notifications
You must be signed in to change notification settings - Fork 4
[ingress][torch-mlir][RFC] Initial version of fx-importer script using torch-mlir #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
1a4b755
[ingress][torch-mlir] Add utility functions to import models using to…
dchigarev 1c6df47
add .gitignore for python files
dchigarev 370e3c0
delete old torch ingress
dchigarev b984314
add readme
dchigarev 2897e0c
fix 02-* tutorial
dchigarev fa7d1de
fix grammar & typos
dchigarev eaf8c9e
change docstrings from numpy to google format
dchigarev 889314d
add kwarg functions to 'import_from_file' fn
dchigarev 0a188e5
fix incode-comments and doc-strings wording
dchigarev 11240bd
Merge remote-tracking branch 'origin/main' into dchigarev/fx_importer
dchigarev 1068bf9
fix tutorials
dchigarev aafffef
Merge remote-tracking branch 'origin/main' into dchigarev/fx_importer
dchigarev 0912de1
fix whitespaces for type annotations according to pep
dchigarev d5c710c
fix ImportError message
dchigarev 029b8ad
apply review suggestions
dchigarev 2215980
remove passManager from ingress examples
dchigarev 8bec558
do not create .pth for model-mlp
dchigarev a1a1ddd
make example's docstring clearer on what 'pytorch mode' means
dchigarev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
dchigarev marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| """Defines a simple PyTorch model to be used in lighthouse's ingress examples.""" | ||
|
|
||
| import torch | ||
| import torch.nn as nn | ||
|
|
||
| import os | ||
|
|
||
| class MLPModel(nn.Module): | ||
| def __init__(self): | ||
| super().__init__() | ||
| self.net = nn.Sequential( | ||
| nn.Linear(10, 32), | ||
| nn.ReLU(), | ||
| nn.Linear(32, 2) | ||
| ) | ||
|
|
||
| def forward(self, x): | ||
| return self.net(x) | ||
|
|
||
|
|
||
| def get_init_inputs(): | ||
| """Function to return args to pass to MLPModel.__init__()""" | ||
| return () | ||
|
|
||
|
|
||
| def get_sample_inputs(): | ||
| """Arguments to pass to MLPModel.forward()""" | ||
| return (torch.randn(1, 10),) |
dchigarev marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| """ | ||
| Example demonstrating how to load a PyTorch model to MLIR using Lighthouse | ||
| without initializing the model class on the user's side. | ||
|
|
||
| The script uses 'lighthouse.ingress.torch.import_from_file' function that | ||
| takes a path to a Python file containing the model definition (a Python class derived from 'nn.Module'), | ||
| along with the names of functions to get model init arguments and sample inputs. The function | ||
| imports the model class on its own, initializes it, and passes it to torch_mlir | ||
| to get a MLIR module in the specified dialect. | ||
|
|
||
| The script uses the model from 'MLPModel/model.py' as an example. | ||
| """ | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
|
|
||
| # MLIR infrastructure imports (only needed if you want to manipulate the MLIR module) | ||
| import mlir.dialects.func as func | ||
| from mlir import ir | ||
|
|
||
| # Lighthouse imports | ||
| from lighthouse.ingress.torch import import_from_file | ||
|
|
||
| # Step 1: Set up paths to locate the model definition file | ||
| script_dir = Path(os.path.dirname(os.path.abspath(__file__))) | ||
| model_path = script_dir / "MLPModel" / "model.py" | ||
|
|
||
| ir_context = ir.Context() | ||
|
|
||
| # Step 2: Convert PyTorch model to MLIR | ||
| # Conversion step where Lighthouse: | ||
| # - Loads the MLPModel class and instantiates it with arguments obtained from 'get_init_inputs()' | ||
| # - Calls get_sample_inputs() to get sample input tensors for shape inference | ||
| # - Converts PyTorch model to linalg-on-tensors dialect operations using torch_mlir | ||
| mlir_module_ir: ir.Module = import_from_file( | ||
| model_path, # Path to the Python file containing the model | ||
| model_class_name="MLPModel", # Name of the PyTorch nn.Module class to convert | ||
| init_args_fn_name="get_init_inputs", # Function that returns args for model.__init__() | ||
| sample_args_fn_name="get_sample_inputs", # Function that returns sample inputs to pass to 'model(...)' | ||
| dialect="linalg-on-tensors", # Target MLIR dialect (linalg ops on tensor types) | ||
| ir_context=ir_context # MLIR context for the conversion | ||
| ) | ||
|
|
||
| # The PyTorch model is now converted to MLIR at this point. You can now convert | ||
| # the MLIR module to a text form (e.g. 'str(mlir_module_ir)') and save it to a file. | ||
| # | ||
| # The following optional MLIR-processing steps are to give you an idea of what can | ||
| # also be done with the MLIR module. | ||
|
|
||
| # Step 3: Extract the main function operation from the MLIR module and print its metadata | ||
| func_op: func.FuncOp = mlir_module_ir.operation.regions[0].blocks[0].operations[0] | ||
| print(f"entry-point name: {func_op.name}") | ||
| print(f"entry-point type: {func_op.type}") | ||
|
|
||
| # Step 4: output the imported MLIR module | ||
| print("\n\nModule dump:") | ||
| mlir_module_ir.dump() | ||
|
|
||
| # You can alternatively write the MLIR module to a file: | ||
| # with open("output.mlir", "w") as f: | ||
| # f.write(str(mlir_module_ir)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| """ | ||
| Example demonstrating how to load an already initialized PyTorch model | ||
| to MLIR using Lighthouse. | ||
|
|
||
| The script uses the 'lighthouse.ingress.torch.import_from_model' function that | ||
| takes an initialized PyTorch model (an instance of a Python class derived from 'nn.Module'), | ||
| along with its sample inputs. The function passes the model to torch_mlir | ||
| to get a MLIR module in the specified dialect. | ||
|
|
||
| The script uses a model from 'MLPModel/model.py' as an example. | ||
| """ | ||
|
|
||
| import torch | ||
|
|
||
| # MLIR infrastructure imports (only needed if you want to manipulate the MLIR module) | ||
| import mlir.dialects.func as func | ||
| from mlir import ir | ||
|
|
||
| # Lighthouse imports | ||
| from lighthouse.ingress.torch import import_from_model | ||
|
|
||
| # Import a sample model definition | ||
| from MLPModel.model import MLPModel | ||
|
|
||
| # Step 1: Instantiate a model class and prepare sample input | ||
| model = MLPModel() | ||
| sample_input = torch.randn(1, 10) | ||
|
|
||
| ir_context = ir.Context() | ||
| # Step 2: Convert the PyTorch model to MLIR | ||
| mlir_module_ir: ir.Module = import_from_model( | ||
| model, | ||
| sample_args=(sample_input,), | ||
| ir_context=ir_context | ||
| ) | ||
|
|
||
| # The PyTorch model is now converted to MLIR at this point. You can now convert | ||
| # the MLIR module to a text form (e.g. 'str(mlir_module_ir)') and save it to a file. | ||
| # | ||
| # The following optional MLIR-processing steps are to give you an idea of what can | ||
| # also be done with the MLIR module. | ||
|
|
||
| # Step 3: Extract the main function operation from the MLIR module and print its metadata | ||
| func_op: func.FuncOp = mlir_module_ir.operation.regions[0].blocks[0].operations[0] | ||
| print(f"entry-point name: {func_op.name}") | ||
| print(f"entry-point type: {func_op.type}") | ||
|
|
||
| # Step 4: output the imported MLIR module | ||
| print("\n\nModule dump:") | ||
| mlir_module_ir.dump() | ||
|
|
||
| # You can alternatively write the MLIR module to a file: | ||
| # with open("output.mlir", "w") as f: | ||
| # f.write(str(mlir_module_ir)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| # Lighthouse Ingress | ||
|
|
||
| The `lighthouse.ingress` module converts various input formats to MLIR modules. | ||
|
|
||
| ## Supported Formats | ||
|
|
||
| #### Torch | ||
| Converts PyTorch models to MLIR using `lighthouse.ingress.torch`. | ||
|
|
||
| **Examples:** [torch examples](https://github.com/llvm/lighthouse/tree/main/python/examples/ingress/torch) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """Provides functions to convert source objects (code, models, designs) into MLIR files that the MLIR project can consume""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| """Provides functions to convert PyTorch models to MLIR.""" | ||
|
|
||
| from .importer import import_from_file, import_from_model |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.