-
Notifications
You must be signed in to change notification settings - Fork 57
Migrate catalyst dialect to new one-shot bufferization
#1708
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 13 commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
a128496
init; some boilerplate
paul0403 db5dccc
more boilerplate
paul0403 99b2487
boilerplate for quantum-opt
paul0403 a7ff16d
boilerplate...
paul0403 a94e33c
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 a30ab8a
(cherry pick) Add CustomCall bufferization
tzunghanjuang 4aeb8df
changelog
paul0403 166314d
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 7508916
add remove hint in cmakelists
paul0403 dbf3ff7
remove pattern header from quantum dialect
paul0403 3f7c608
add callback and callbackcall op
paul0403 8f59346
update cpp pipeline
paul0403 e603605
missed include
paul0403 69fcac2
remove old catalyst dialect bufferization pass
paul0403 13037be
format
paul0403 66f4ab0
codefactor
paul0403 41a7e14
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 1a3ff7d
custom call also allocates
paul0403 045b15b
do not hint memory write for custom op when not in memref land
paul0403 ad942d9
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 fdb16e0
lapack kernels might write into source array
paul0403 4d5f983
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 38bf1c4
add bufferization interface doc banner
paul0403 fe4e944
add {} to a one-line if block
paul0403 3c6dfcd
remove aliasing operand method from callback op: it does not have ten…
paul0403 098d580
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 b39f28a
(prototype) make a white list of custom calls that won't copy
paul0403 4cd1843
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 3289d19
Set identity layout map option. This avoids the strides.
paul0403 4f48b1b
no copy: jax already does the copy around the lapack kernels
paul0403 7c6759f
name
paul0403 fb5c421
Merge remote-tracking branch 'origin/main' into paul0403/new_bufferiz…
paul0403 c949ce7
add comment about jax shim layer's copy
paul0403 0b70112
a bit more comment
paul0403 b06ec69
add back finalizing bufferize pass
paul0403 d5f4d3d
add back finalizing pass in cpp pipeline
paul0403 a752ead
CI
paul0403 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
23 changes: 23 additions & 0 deletions
23
mlir/include/Catalyst/Transforms/BufferizableOpInterfaceImpl.h
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,23 @@ | ||
| // Copyright 2024-2025 Xanadu Quantum Technologies Inc. | ||
|
|
||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
|
|
||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| #pragma once | ||
|
|
||
| using namespace mlir; | ||
|
|
||
| namespace catalyst { | ||
|
|
||
| void registerBufferizableOpInterfaceExternalModels(mlir::DialectRegistry ®istry); | ||
|
|
||
| } // namespace catalyst |
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
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
285 changes: 285 additions & 0 deletions
285
mlir/lib/Catalyst/Transforms/BufferizableOpInterfaceImpl.cpp
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,285 @@ | ||
| // Copyright 2024-2025 Xanadu Quantum Technologies Inc. | ||
|
|
||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
|
|
||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h" | ||
| #include "mlir/Dialect/Bufferization/IR/Bufferization.h" | ||
| #include "mlir/Dialect/LLVMIR/LLVMDialect.h" | ||
| #include "mlir/Dialect/MemRef/IR/MemRef.h" | ||
| #include "mlir/Transforms/DialectConversion.h" | ||
|
|
||
| #include "Catalyst/IR/CatalystOps.h" | ||
| #include "Catalyst/Transforms/BufferizableOpInterfaceImpl.h" | ||
|
|
||
| using namespace mlir; | ||
| using namespace mlir::bufferization; | ||
| using namespace catalyst; | ||
|
|
||
paul0403 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| namespace { | ||
|
|
||
| /// Bufferization of catalyst.print. Get memref of printOp.val. | ||
| struct PrintOpInterface | ||
| : public bufferization::BufferizableOpInterface::ExternalModel<PrintOpInterface, | ||
| PrintOp> { | ||
| bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const { | ||
| return true; | ||
| } | ||
|
|
||
| bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const { | ||
| return false; | ||
| } | ||
|
|
||
| bufferization::AliasingValueList getAliasingValues(Operation *op, | ||
| OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const { | ||
| return {}; | ||
| } | ||
|
|
||
| LogicalResult bufferize(Operation *op, RewriterBase &rewriter, | ||
| const bufferization::BufferizationOptions &options) const { | ||
| auto printOp = cast<PrintOp>(op); | ||
| if (printOp.getVal()) { | ||
| FailureOr<Value> source = getBuffer(rewriter, printOp.getVal(), options); | ||
| if (failed(source)) { | ||
| return failure(); | ||
| } | ||
| bufferization::replaceOpWithNewBufferizedOp<PrintOp>(rewriter, op, *source, | ||
| printOp.getConstValAttr(), printOp.getPrintDescriptorAttr()); | ||
| } | ||
| return success(); | ||
| } | ||
| }; | ||
|
|
||
| /// Bufferization of catalyst.custom_call. Mainly get buffers for arguments. | ||
| struct CustomCallOpInterface | ||
| : public bufferization::BufferizableOpInterface::ExternalModel<CustomCallOpInterface, | ||
| CustomCallOp> { | ||
| bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const { | ||
| return true; | ||
| } | ||
|
|
||
| bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const { | ||
| return true; | ||
paul0403 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| bufferization::AliasingValueList getAliasingValues(Operation *op, | ||
| OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const { | ||
| return {}; | ||
| } | ||
|
|
||
| LogicalResult bufferize(Operation *op, RewriterBase &rewriter, | ||
| const bufferization::BufferizationOptions &options) const { | ||
| auto customCallOp = cast<CustomCallOp>(op); | ||
|
|
||
| // Add bufferized arguments | ||
| SmallVector<Value> bufferArgs; | ||
| ValueRange operands = customCallOp.getOperands(); | ||
| for (Value operand : operands) { | ||
| FailureOr<Value> opBuffer = getBuffer(rewriter, operand, options); | ||
| if (failed(opBuffer)) { | ||
| return failure(); | ||
| } | ||
| bufferArgs.push_back(*opBuffer); | ||
| } | ||
|
|
||
| // Add bufferized return values to the arguments | ||
| ValueRange results = customCallOp.getResults(); | ||
| for (Value result : results) { | ||
| Type resultType = result.getType(); | ||
| RankedTensorType tensorType = dyn_cast<RankedTensorType>(resultType); | ||
| if (!tensorType) { | ||
| return failure(); | ||
| } | ||
| auto options = bufferization::BufferizationOptions(); | ||
| FailureOr<Value> tensorAlloc = bufferization::allocateTensorForShapedValue( | ||
| rewriter, op->getLoc(), result, options, false); | ||
| MemRefType memrefType = | ||
| MemRefType::get(tensorType.getShape(), tensorType.getElementType()); | ||
| auto newBuffer = | ||
| rewriter.create<bufferization::ToMemrefOp>(op->getLoc(), memrefType, *tensorAlloc); | ||
| bufferArgs.push_back(newBuffer); | ||
| } | ||
|
|
||
| // Add the initial number of arguments | ||
| int32_t numArguments = static_cast<int32_t>(customCallOp.getNumOperands()); | ||
| DenseI32ArrayAttr numArgumentsDenseAttr = rewriter.getDenseI32ArrayAttr({numArguments}); | ||
|
|
||
| // Create an updated custom call operation | ||
| rewriter.create<CustomCallOp>(op->getLoc(), TypeRange{}, bufferArgs, | ||
| customCallOp.getCallTargetName(), numArgumentsDenseAttr); | ||
| size_t startIndex = bufferArgs.size() - customCallOp.getNumResults(); | ||
| SmallVector<Value> bufferResults(bufferArgs.begin() + startIndex, bufferArgs.end()); | ||
| bufferization::replaceOpWithBufferizedValues(rewriter, op, bufferResults); | ||
|
|
||
| return success(); | ||
| } | ||
| }; | ||
|
|
||
| struct CallbackOpInterface | ||
| : public bufferization::BufferizableOpInterface::ExternalModel<CallbackOpInterface, | ||
| CallbackOp> { | ||
| bool hasTensorSemantics(Operation *op) const | ||
| { | ||
| auto isaTensor = llvm::IsaPred<TensorType>; | ||
|
|
||
| // A function has tensor semantics if it has tensor arguments/results. | ||
| auto callbackOp = cast<CallbackOp>(op); | ||
| bool hasTensorArg = any_of(callbackOp.getArgumentTypes(), isaTensor); | ||
| bool hasTensorResult = any_of(callbackOp.getResultTypes(), isaTensor); | ||
| if (hasTensorArg || hasTensorResult) | ||
| return true; | ||
paul0403 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| return false; | ||
| } | ||
|
|
||
| bufferization::AliasingOpOperandList | ||
| getAliasingOpOperands(Operation *op, Value value, | ||
| const bufferization::AnalysisState &state) const | ||
| { | ||
| return {}; | ||
| } | ||
paul0403 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| LogicalResult bufferize(Operation *op, RewriterBase &rewriter, | ||
| const bufferization::BufferizationOptions &options) const | ||
| { | ||
| auto callbackOp = cast<CallbackOp>(op); | ||
|
|
||
| auto argTys = callbackOp.getArgumentTypes(); | ||
| auto retTys = callbackOp.getResultTypes(); | ||
| SmallVector<Type> emptyRets; | ||
| SmallVector<Type> args(argTys.begin(), argTys.end()); | ||
| args.insert(args.end(), retTys.begin(), retTys.end()); | ||
| SmallVector<Type> bufferArgs; | ||
| for (Type ty : args) { | ||
| auto tensorType = dyn_cast<RankedTensorType>(ty); | ||
| if (!tensorType) { | ||
| bufferArgs.push_back(ty); | ||
| } | ||
| else { | ||
| bufferArgs.push_back( | ||
| MemRefType::get(tensorType.getShape(), tensorType.getElementType())); | ||
| } | ||
| } | ||
| auto callbackTy = rewriter.getFunctionType(bufferArgs, emptyRets); | ||
| rewriter.modifyOpInPlace(op, [&] { callbackOp.setFunctionType(callbackTy); }); | ||
|
|
||
| return success(); | ||
| } | ||
| }; | ||
|
|
||
| void convertTypes(SmallVector<Type> inTypes, SmallVector<Type> &convertedResults){ | ||
| // See https://github.com/llvm/llvm-project/pull/114155/files | ||
| for (Type inType : inTypes) { | ||
| if (isa<TensorType>(inType)){ | ||
| convertedResults.push_back(bufferization::getMemRefTypeWithStaticIdentityLayout(cast<TensorType>(inType))); | ||
| } else { | ||
| convertedResults.push_back(inType); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct CallbackCallOpInterface | ||
| : public bufferization::BufferizableOpInterface::ExternalModel<CallbackCallOpInterface, | ||
| CallbackCallOp> { | ||
| bool bufferizesToAllocation(Operation *op, Value value) const { return true; } | ||
|
|
||
| bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const | ||
| { | ||
| // We can safely say false because CallbackCallOp's memrefs | ||
| // will be put in a JAX array and JAX arrays are immutable. | ||
| // | ||
| // Unlike NumPy arrays, JAX arrays are always immutable. | ||
dime10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // | ||
| // https://jax.readthedocs.io/en/latest/notebooks/thinking_in_jax.html | ||
| return false; | ||
paul0403 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| bufferization::AliasingValueList | ||
| getAliasingValues(Operation *op, OpOperand &opOperand, | ||
| const bufferization::AnalysisState &state) const | ||
| { | ||
| return {}; | ||
| } | ||
|
|
||
| LogicalResult bufferize(Operation *op, RewriterBase &rewriter, | ||
| const bufferization::BufferizationOptions &options) const | ||
| { | ||
| auto callOp = cast<CallbackCallOp>(op); | ||
|
|
||
| SmallVector<Type> convertedResults; | ||
| convertTypes(SmallVector<Type>(callOp.getResultTypes()), convertedResults); | ||
| if (callOp->getNumResults() != convertedResults.size()) { | ||
| return failure(); | ||
| } | ||
|
|
||
| SmallVector<Value> newInputs; | ||
| auto operands = callOp.getOperands(); | ||
| for (Value operand : operands) { | ||
| FailureOr<Value> opBuffer = getBuffer(rewriter, operand, options); | ||
| if (failed(opBuffer)) { | ||
| return failure(); | ||
| } | ||
| newInputs.push_back(*opBuffer); | ||
| } | ||
|
|
||
| auto results = callOp.getResults(); | ||
| auto loc = callOp->getLoc(); | ||
| SmallVector<Value> outmemrefs; | ||
| for (auto result : results) { | ||
| FailureOr<Value> tensorAlloc = | ||
| bufferization::allocateTensorForShapedValue(rewriter, loc, result, options, false); | ||
| if (failed(tensorAlloc)) { | ||
| return failure(); | ||
| } | ||
|
|
||
| auto tensor = *tensorAlloc; | ||
| RankedTensorType tensorTy = cast<RankedTensorType>(tensor.getType()); | ||
| auto shape = tensorTy.getShape(); | ||
| auto elementTy = tensorTy.getElementType(); | ||
| auto memrefType = MemRefType::get(shape, elementTy); | ||
| auto toMemrefOp = rewriter.create<bufferization::ToMemrefOp>(loc, memrefType, tensor); | ||
| auto memref = toMemrefOp.getResult(); | ||
| outmemrefs.push_back(memref); | ||
| newInputs.push_back(memref); | ||
| } | ||
|
|
||
| SmallVector<Type> emptyRets; | ||
| rewriter.create<CallbackCallOp>(loc, emptyRets, callOp.getCallee(), newInputs); | ||
| bufferization::replaceOpWithBufferizedValues(rewriter, op, outmemrefs); | ||
| return success(); | ||
| } | ||
| }; | ||
|
|
||
| } // namespace | ||
|
|
||
| void catalyst::registerBufferizableOpInterfaceExternalModels( | ||
| DialectRegistry ®istry) { | ||
| registry.addExtension(+[](MLIRContext *ctx, CatalystDialect *dialect) { | ||
| CustomCallOp::attachInterface<CustomCallOpInterface>(*ctx); | ||
| PrintOp::attachInterface<PrintOpInterface>(*ctx); | ||
| CallbackOp::attachInterface<CallbackOpInterface>(*ctx); | ||
| CallbackCallOp::attachInterface<CallbackCallOpInterface>(*ctx); | ||
| }); | ||
| } | ||
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
Oops, something went wrong.
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.