-
Notifications
You must be signed in to change notification settings - Fork 135
Optimize matmuls involving block diagonal matrices #1493
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
Open
jessegrabowski
wants to merge
5
commits into
pymc-devs:main
Choose a base branch
from
jessegrabowski:block-diag-dot-rewrite
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+151
−4
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9ad9540
block_diag dot rewrite
jessegrabowski ffb71d3
Handle right-multiplication case
jessegrabowski c5137d7
The robot was right!
jessegrabowski 3b66eba
Respond to feedback
jessegrabowski 09bddf1
Use `rewrite_mode` defined in `test_math.py` for testing
jessegrabowski 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,9 +29,11 @@ | |
cast, | ||
constant, | ||
get_underlying_scalar_constant_value, | ||
join, | ||
moveaxis, | ||
ones_like, | ||
register_infer_shape, | ||
split, | ||
switch, | ||
zeros_like, | ||
) | ||
|
@@ -99,6 +101,7 @@ | |
) | ||
from pytensor.tensor.rewriting.elemwise import apply_local_dimshuffle_lift | ||
from pytensor.tensor.shape import Shape, Shape_i | ||
from pytensor.tensor.slinalg import BlockDiagonal | ||
from pytensor.tensor.subtensor import Subtensor | ||
from pytensor.tensor.type import ( | ||
complex_dtypes, | ||
|
@@ -167,6 +170,76 @@ | |
return [constant_zero] | ||
|
||
|
||
@register_stabilize | ||
@node_rewriter([Blockwise]) | ||
def local_block_diag_dot_to_dot_block_diag(fgraph, node): | ||
r""" | ||
Perform the rewrite ``dot(block_diag(A, B), C) -> concat(dot(A, C), dot(B, C))`` | ||
|
||
BlockDiag results in the creation of a matrix of shape ``(n1 * n2, m1 * m2)``. Because dot has complexity | ||
of approximately O(n^3), it's always better to perform two dot products on the smaller matrices, rather than | ||
a single dot on the larger matrix. | ||
""" | ||
if not isinstance(node.op.core_op, BlockDiagonal): | ||
return | ||
|
||
def check_for_block_diag(x): | ||
return x.owner and ( | ||
isinstance(x.owner.op, BlockDiagonal) | ||
or isinstance(x.owner.op, Blockwise) | ||
and isinstance(x.owner.op.core_op, BlockDiagonal) | ||
) | ||
|
||
# Check that the BlockDiagonal is an input to a Dot node: | ||
clients = list(get_clients_at_depth(fgraph, node, depth=1)) | ||
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. You should iterate over the clients and return when there's a match (just indent the code below inside the loop). Why is it a problem if the BlockDiagonal has more clients? |
||
if not clients or len(clients) > 1 or not isinstance(clients[0].op, Dot): | ||
return | ||
|
||
[dot_node] = clients | ||
op = dot_node.op | ||
x, y = dot_node.inputs | ||
|
||
if not (check_for_block_diag(x) or check_for_block_diag(y)): | ||
return None | ||
|
||
# Case 1: Only one input is BlockDiagonal. In this case, multiply all components of the block-diagonal with the | ||
# non-block diagonal, and return a new block diagonal | ||
if check_for_block_diag(x) and not check_for_block_diag(y): | ||
components = x.owner.inputs | ||
y_splits = split( | ||
y, | ||
splits_size=[component.shape[-1] for component in components], | ||
n_splits=len(components), | ||
) | ||
new_components = [ | ||
op(component, y_split) for component, y_split in zip(components, y_splits) | ||
] | ||
new_output = join(0, *new_components) | ||
|
||
elif not check_for_block_diag(x) and check_for_block_diag(y): | ||
components = y.owner.inputs | ||
x_splits = split( | ||
x, | ||
splits_size=[component.shape[0] for component in components], | ||
n_splits=len(components), | ||
axis=1, | ||
) | ||
|
||
new_components = [ | ||
op(x_split, component) for component, x_split in zip(components, x_splits) | ||
] | ||
new_output = join(1, *new_components) | ||
|
||
# Case 2: Both inputs are BlockDiagonal. Do nothing | ||
else: | ||
# TODO: If shapes are statically known and all components have equal shapes, we could rewrite | ||
# this case to block_diag(*[dot(comp_1, comp_2) for comp_1, comp_2 in zip(x.owner.inputs, y.owner.inputs)]) | ||
return None | ||
jessegrabowski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
copy_stack_trace(node.outputs[0], new_output) | ||
return {dot_node.outputs[0]: new_output} | ||
|
||
|
||
@register_canonicalize | ||
@node_rewriter([DimShuffle]) | ||
def local_lift_transpose_through_dot(fgraph, node): | ||
|
@@ -2496,7 +2569,6 @@ | |
name="add_canonizer_group", | ||
) | ||
|
||
|
||
register_canonicalize(local_add_canonizer, "shape_unsafe", name="local_add_canonizer") | ||
|
||
|
||
|
@@ -3619,7 +3691,6 @@ | |
) | ||
register_stabilize(logdiffexp_to_log1mexpdiff, name="logdiffexp_to_log1mexpdiff") | ||
|
||
|
||
# log(sigmoid(x) / (1 - sigmoid(x))) -> x | ||
# i.e logit(sigmoid(x)) -> x | ||
local_logit_sigmoid = PatternNodeRewriter( | ||
|
@@ -3633,7 +3704,6 @@ | |
register_canonicalize(local_logit_sigmoid) | ||
register_specialize(local_logit_sigmoid) | ||
|
||
|
||
# sigmoid(log(x / (1-x)) -> x | ||
# i.e., sigmoid(logit(x)) -> x | ||
local_sigmoid_logit = PatternNodeRewriter( | ||
|
@@ -3674,7 +3744,6 @@ | |
|
||
register_specialize(local_polygamma_to_tri_gamma) | ||
|
||
|
||
local_log_kv = PatternNodeRewriter( | ||
# Rewrite log(kv(v, x)) = log(kve(v, x) * exp(-x)) -> log(kve(v, x)) - x | ||
# During stabilize -x is converted to -1.0 * x | ||
|
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
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.