Skip to content

Commit 94564b2

Browse files
nikalrajoaosaffran
authored and
joaosaffran
committed
[mlir] Python: Parse ModuleOp from file path (llvm#126572)
For extremely large models, it may be inefficient to load the model into memory in Python prior to passing it to the MLIR C APIs for deserialization. This change adds an API to parse a ModuleOp directly from a file path. Re-lands [4e14b8a](llvm@4e14b8a).
1 parent 9f9ed98 commit 94564b2

File tree

5 files changed

+56
-1
lines changed

5 files changed

+56
-1
lines changed

mlir/include/mlir-c/IR.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,10 @@ MLIR_CAPI_EXPORTED MlirModule mlirModuleCreateEmpty(MlirLocation location);
309309
MLIR_CAPI_EXPORTED MlirModule mlirModuleCreateParse(MlirContext context,
310310
MlirStringRef module);
311311

312+
/// Parses a module from file and transfers ownership to the caller.
313+
MLIR_CAPI_EXPORTED MlirModule
314+
mlirModuleCreateParseFromFile(MlirContext context, MlirStringRef fileName);
315+
312316
/// Gets the context that a module was created with.
313317
MLIR_CAPI_EXPORTED MlirContext mlirModuleGetContext(MlirModule module);
314318

mlir/lib/Bindings/Python/IRCore.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ struct PyAttrBuilderMap {
299299
return *builder;
300300
}
301301
static void dunderSetItemNamed(const std::string &attributeKind,
302-
nb::callable func, bool replace) {
302+
nb::callable func, bool replace) {
303303
PyGlobals::get().registerAttributeBuilder(attributeKind, std::move(func),
304304
replace);
305305
}
@@ -3049,6 +3049,18 @@ void mlir::python::populateIRCore(nb::module_ &m) {
30493049
},
30503050
nb::arg("asm"), nb::arg("context").none() = nb::none(),
30513051
kModuleParseDocstring)
3052+
.def_static(
3053+
"parseFile",
3054+
[](const std::string &path, DefaultingPyMlirContext context) {
3055+
PyMlirContext::ErrorCapture errors(context->getRef());
3056+
MlirModule module = mlirModuleCreateParseFromFile(
3057+
context->get(), toMlirStringRef(path));
3058+
if (mlirModuleIsNull(module))
3059+
throw MLIRError("Unable to parse module assembly", errors.take());
3060+
return PyModule::forModule(module).releaseObject();
3061+
},
3062+
nb::arg("path"), nb::arg("context").none() = nb::none(),
3063+
kModuleParseDocstring)
30523064
.def_static(
30533065
"create",
30543066
[](DefaultingPyLocation loc) {

mlir/lib/CAPI/IR/IR.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include "mlir/IR/Location.h"
2323
#include "mlir/IR/Operation.h"
2424
#include "mlir/IR/OperationSupport.h"
25+
#include "mlir/IR/OwningOpRef.h"
2526
#include "mlir/IR/Types.h"
2627
#include "mlir/IR/Value.h"
2728
#include "mlir/IR/Verifier.h"
@@ -328,6 +329,15 @@ MlirModule mlirModuleCreateParse(MlirContext context, MlirStringRef module) {
328329
return MlirModule{owning.release().getOperation()};
329330
}
330331

332+
MlirModule mlirModuleCreateParseFromFile(MlirContext context,
333+
MlirStringRef fileName) {
334+
OwningOpRef<ModuleOp> owning =
335+
parseSourceFile<ModuleOp>(unwrap(fileName), unwrap(context));
336+
if (!owning)
337+
return MlirModule{nullptr};
338+
return MlirModule{owning.release().getOperation()};
339+
}
340+
331341
MlirContext mlirModuleGetContext(MlirModule module) {
332342
return wrap(unwrap(module).getContext());
333343
}

mlir/python/mlir/_mlir_libs/_mlir/ir.pyi

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import abc
4646
import collections
4747
from collections.abc import Callable, Sequence
4848
import io
49+
from pathlib import Path
4950
from typing import Any, ClassVar, TypeVar, overload
5051

5152
__all__ = [
@@ -2129,6 +2130,15 @@ class Module:
21292130
21302131
Returns a new MlirModule or raises an MLIRError if the parsing fails.
21312132
2133+
See also: https://mlir.llvm.org/docs/LangRef/
2134+
"""
2135+
@staticmethod
2136+
def parseFile(path: str, context: Context | None = None) -> Module:
2137+
"""
2138+
Parses a module's assembly format from file.
2139+
2140+
Returns a new MlirModule or raises an MLIRError if the parsing fails.
2141+
21322142
See also: https://mlir.llvm.org/docs/LangRef/
21332143
"""
21342144
def _CAPICreate(self) -> Any: ...

mlir/test/python/ir/module.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# RUN: %PYTHON %s | FileCheck %s
22

33
import gc
4+
from tempfile import NamedTemporaryFile
45
from mlir.ir import *
56

67

@@ -27,6 +28,24 @@ def testParseSuccess():
2728
print(str(module))
2829

2930

31+
# Verify successful parse from file.
32+
# CHECK-LABEL: TEST: testParseFromFileSuccess
33+
# CHECK: module @successfulParse
34+
@run
35+
def testParseFromFileSuccess():
36+
ctx = Context()
37+
with NamedTemporaryFile(mode="w") as tmp_file:
38+
tmp_file.write(r"""module @successfulParse {}""")
39+
tmp_file.flush()
40+
module = Module.parseFile(tmp_file.name, ctx)
41+
assert module.context is ctx
42+
print("CLEAR CONTEXT")
43+
ctx = None # Ensure that module captures the context.
44+
gc.collect()
45+
module.operation.verify()
46+
print(str(module))
47+
48+
3049
# Verify parse error.
3150
# CHECK-LABEL: TEST: testParseError
3251
# CHECK: testParseError: <

0 commit comments

Comments
 (0)