-
Notifications
You must be signed in to change notification settings - Fork 14.8k
[mlir][python] automatic location inference #151246
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
+347
−57
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
e5960dc
[mlir][python] auto-locs
makslevental 105e6dd
guard reading as well
makslevental eb48702
fix comments
makslevental 2942fc2
add frame limit test
makslevental 98294d8
Merge branch 'main' into makslevental/auto-locs
jpienaar 7cc2a1c
Merge branch 'main' into makslevental/auto-locs
makslevental 83091aa
Update auto_location.py
makslevental 6e5cd75
make get_default_loc_context return None
makslevental a4bc05a
fix live contexts
makslevental 21d68e6
fix location is None test
makslevental 70244f3
upper bound kMaxFrames
makslevental 2e63eee
add comment
makslevental 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 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
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 |
---|---|---|
|
@@ -20,11 +20,8 @@ | |
#include "nanobind/nanobind.h" | ||
#include "llvm/ADT/ArrayRef.h" | ||
#include "llvm/ADT/SmallVector.h" | ||
#include "llvm/Support/raw_ostream.h" | ||
|
||
#include <optional> | ||
#include <system_error> | ||
#include <utility> | ||
|
||
namespace nb = nanobind; | ||
using namespace nb::literals; | ||
|
@@ -1523,7 +1520,7 @@ nb::object PyOperation::create(std::string_view name, | |
llvm::ArrayRef<MlirValue> operands, | ||
std::optional<nb::dict> attributes, | ||
std::optional<std::vector<PyBlock *>> successors, | ||
int regions, DefaultingPyLocation location, | ||
int regions, PyLocation &location, | ||
const nb::object &maybeIp, bool inferType) { | ||
llvm::SmallVector<MlirType, 4> mlirResults; | ||
llvm::SmallVector<MlirBlock, 4> mlirSuccessors; | ||
|
@@ -1627,7 +1624,7 @@ nb::object PyOperation::create(std::string_view name, | |
if (!operation.ptr) | ||
throw nb::value_error("Operation creation failed"); | ||
PyOperationRef created = | ||
PyOperation::createDetached(location->getContext(), operation); | ||
PyOperation::createDetached(location.getContext(), operation); | ||
maybeInsertOperation(created, maybeIp); | ||
|
||
return created.getObject(); | ||
|
@@ -1937,9 +1934,9 @@ nb::object PyOpView::buildGeneric( | |
std::optional<nb::list> resultTypeList, nb::list operandList, | ||
std::optional<nb::dict> attributes, | ||
std::optional<std::vector<PyBlock *>> successors, | ||
std::optional<int> regions, DefaultingPyLocation location, | ||
std::optional<int> regions, PyLocation &location, | ||
const nb::object &maybeIp) { | ||
PyMlirContextRef context = location->getContext(); | ||
PyMlirContextRef context = location.getContext(); | ||
|
||
// Class level operation construction metadata. | ||
// Operand and result segment specs are either none, which does no | ||
|
@@ -2789,6 +2786,90 @@ class PyOpAttributeMap { | |
PyOperationRef operation; | ||
}; | ||
|
||
MlirLocation tracebackToLocation(MlirContext ctx) { | ||
size_t framesLimit = | ||
PyGlobals::get().getTracebackLoc().locTracebackFramesLimit(); | ||
// Use a thread_local here to avoid requiring a large amount of space. | ||
thread_local std::array<MlirLocation, PyGlobals::TracebackLoc::kMaxFrames> | ||
frames; | ||
size_t count = 0; | ||
|
||
nb::gil_scoped_acquire acquire; | ||
PyThreadState *tstate = PyThreadState_GET(); | ||
PyFrameObject *next; | ||
PyFrameObject *pyFrame = PyThreadState_GetFrame(tstate); | ||
// In the increment expression: | ||
// 1. get the next prev frame; | ||
// 2. decrement the ref count on the current frame (in order that it can get | ||
// gc'd, along with any objects in its closure and etc); | ||
// 3. set current = next. | ||
for (; pyFrame != nullptr && count < framesLimit; | ||
next = PyFrame_GetBack(pyFrame), Py_XDECREF(pyFrame), pyFrame = next) { | ||
PyCodeObject *code = PyFrame_GetCode(pyFrame); | ||
auto fileNameStr = | ||
nb::cast<std::string>(nb::borrow<nb::str>(code->co_filename)); | ||
llvm::StringRef fileName(fileNameStr); | ||
if (!PyGlobals::get().getTracebackLoc().isUserTracebackFilename(fileName)) | ||
continue; | ||
|
||
#if PY_VERSION_HEX < 0x030b00f0 | ||
std::string name = | ||
nb::cast<std::string>(nb::borrow<nb::str>(code->co_name)); | ||
llvm::StringRef funcName(name); | ||
int startLine = PyFrame_GetLineNumber(pyFrame); | ||
MlirLocation loc = | ||
mlirLocationFileLineColGet(ctx, wrap(fileName), startLine, 0); | ||
#else | ||
// co_qualname and PyCode_Addr2Location added in py3.11 | ||
std::string name = | ||
nb::cast<std::string>(nb::borrow<nb::str>(code->co_qualname)); | ||
llvm::StringRef funcName(name); | ||
int startLine, startCol, endLine, endCol; | ||
int lasti = PyFrame_GetLasti(pyFrame); | ||
if (!PyCode_Addr2Location(code, lasti, &startLine, &startCol, &endLine, | ||
&endCol)) { | ||
throw nb::python_error(); | ||
} | ||
MlirLocation loc = mlirLocationFileLineColRangeGet( | ||
ctx, wrap(fileName), startLine, startCol, endLine, endCol); | ||
#endif | ||
|
||
frames[count] = mlirLocationNameGet(ctx, wrap(funcName), loc); | ||
++count; | ||
} | ||
// When the loop breaks (after the last iter), current frame (if non-null) | ||
// is leaked without this. | ||
Py_XDECREF(pyFrame); | ||
|
||
if (count == 0) | ||
return mlirLocationUnknownGet(ctx); | ||
|
||
MlirLocation callee = frames[0]; | ||
assert(!mlirLocationIsNull(callee) && "expected non-null callee location"); | ||
if (count == 1) | ||
return callee; | ||
|
||
MlirLocation caller = frames[count - 1]; | ||
assert(!mlirLocationIsNull(caller) && "expected non-null caller location"); | ||
for (int i = count - 2; i >= 1; i--) | ||
caller = mlirLocationCallSiteGet(frames[i], caller); | ||
|
||
return mlirLocationCallSiteGet(callee, caller); | ||
} | ||
|
||
PyLocation | ||
maybeGetTracebackLocation(const std::optional<PyLocation> &location) { | ||
if (location.has_value()) | ||
return location.value(); | ||
if (!PyGlobals::get().getTracebackLoc().locTracebacksEnabled()) | ||
return DefaultingPyLocation::resolve(); | ||
|
||
PyMlirContext &ctx = DefaultingPyMlirContext::resolve(); | ||
MlirLocation mlirLoc = tracebackToLocation(ctx.get()); | ||
PyMlirContextRef ref = PyMlirContext::forContext(ctx.get()); | ||
return {ref, mlirLoc}; | ||
} | ||
|
||
} // namespace | ||
|
||
//------------------------------------------------------------------------------ | ||
|
@@ -3052,10 +3133,10 @@ void mlir::python::populateIRCore(nb::module_ &m) { | |
.def("__eq__", [](PyLocation &self, nb::object other) { return false; }) | ||
.def_prop_ro_static( | ||
"current", | ||
[](nb::object & /*class*/) { | ||
[](nb::object & /*class*/) -> std::optional<PyLocation *> { | ||
auto *loc = PyThreadContextEntry::getDefaultLocation(); | ||
if (!loc) | ||
throw nb::value_error("No current Location"); | ||
return std::nullopt; | ||
Comment on lines
+3136
to
+3139
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. change |
||
return loc; | ||
}, | ||
"Gets the Location bound to the current thread or raises ValueError") | ||
|
@@ -3240,8 +3321,9 @@ void mlir::python::populateIRCore(nb::module_ &m) { | |
kModuleParseDocstring) | ||
.def_static( | ||
"create", | ||
[](DefaultingPyLocation loc) { | ||
MlirModule module = mlirModuleCreateEmpty(loc); | ||
[](const std::optional<PyLocation> &loc) { | ||
PyLocation pyLoc = maybeGetTracebackLocation(loc); | ||
MlirModule module = mlirModuleCreateEmpty(pyLoc.get()); | ||
return PyModule::forModule(module).releaseObject(); | ||
}, | ||
nb::arg("loc").none() = nb::none(), "Creates an empty module") | ||
|
@@ -3454,8 +3536,8 @@ void mlir::python::populateIRCore(nb::module_ &m) { | |
std::optional<std::vector<PyValue *>> operands, | ||
std::optional<nb::dict> attributes, | ||
std::optional<std::vector<PyBlock *>> successors, int regions, | ||
DefaultingPyLocation location, const nb::object &maybeIp, | ||
bool inferType) { | ||
const std::optional<PyLocation> &location, | ||
const nb::object &maybeIp, bool inferType) { | ||
// Unpack/validate operands. | ||
llvm::SmallVector<MlirValue, 4> mlirOperands; | ||
if (operands) { | ||
|
@@ -3467,8 +3549,9 @@ void mlir::python::populateIRCore(nb::module_ &m) { | |
} | ||
} | ||
|
||
PyLocation pyLoc = maybeGetTracebackLocation(location); | ||
return PyOperation::create(name, results, mlirOperands, attributes, | ||
successors, regions, location, maybeIp, | ||
successors, regions, pyLoc, maybeIp, | ||
inferType); | ||
}, | ||
nb::arg("name"), nb::arg("results").none() = nb::none(), | ||
|
@@ -3512,12 +3595,14 @@ void mlir::python::populateIRCore(nb::module_ &m) { | |
std::optional<nb::list> resultTypeList, nb::list operandList, | ||
std::optional<nb::dict> attributes, | ||
std::optional<std::vector<PyBlock *>> successors, | ||
std::optional<int> regions, DefaultingPyLocation location, | ||
std::optional<int> regions, | ||
const std::optional<PyLocation> &location, | ||
const nb::object &maybeIp) { | ||
PyLocation pyLoc = maybeGetTracebackLocation(location); | ||
new (self) PyOpView(PyOpView::buildGeneric( | ||
name, opRegionSpec, operandSegmentSpecObj, | ||
resultSegmentSpecObj, resultTypeList, operandList, | ||
attributes, successors, regions, location, maybeIp)); | ||
attributes, successors, regions, pyLoc, maybeIp)); | ||
}, | ||
nb::arg("name"), nb::arg("opRegionSpec"), | ||
nb::arg("operandSegmentSpecObj").none() = nb::none(), | ||
|
@@ -3551,17 +3636,18 @@ void mlir::python::populateIRCore(nb::module_ &m) { | |
[](nb::handle cls, std::optional<nb::list> resultTypeList, | ||
nb::list operandList, std::optional<nb::dict> attributes, | ||
std::optional<std::vector<PyBlock *>> successors, | ||
std::optional<int> regions, DefaultingPyLocation location, | ||
std::optional<int> regions, std::optional<PyLocation> location, | ||
const nb::object &maybeIp) { | ||
std::string name = nb::cast<std::string>(cls.attr("OPERATION_NAME")); | ||
std::tuple<int, bool> opRegionSpec = | ||
nb::cast<std::tuple<int, bool>>(cls.attr("_ODS_REGIONS")); | ||
nb::object operandSegmentSpec = cls.attr("_ODS_OPERAND_SEGMENTS"); | ||
nb::object resultSegmentSpec = cls.attr("_ODS_RESULT_SEGMENTS"); | ||
PyLocation pyLoc = maybeGetTracebackLocation(location); | ||
return PyOpView::buildGeneric(name, opRegionSpec, operandSegmentSpec, | ||
resultSegmentSpec, resultTypeList, | ||
operandList, attributes, successors, | ||
regions, location, maybeIp); | ||
regions, pyLoc, maybeIp); | ||
}, | ||
nb::arg("cls"), nb::arg("results").none() = nb::none(), | ||
nb::arg("operands").none() = nb::none(), | ||
|
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
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.