-
Notifications
You must be signed in to change notification settings - Fork 134
Implement Scalar Scan (as dummy Op) #174
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
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 |
---|---|---|
@@ -0,0 +1,23 @@ | ||
from pytensor.scalar.basic import ScalarOp, same_out | ||
|
||
|
||
class ScalarScanOp(ScalarOp): | ||
"""Dummy Scalar Op that encapsulates a scalar scan operation. | ||
|
||
This Op is never supposed to be evaluated. It can safely be converted | ||
to an Elemwise which is rewritten into a Scan node during compilation. | ||
|
||
TODO: FINISH DOCSTRINGS | ||
TODO: ABC for fn property | ||
""" | ||
|
||
def __init__(self, output_types_preference=None, **kwargs): | ||
if output_types_preference is None: | ||
|
||
def output_types_preference(*types): | ||
return tuple(same_out(type)[0] for type in types[: self.nout]) | ||
|
||
super().__init__(output_types_preference=output_types_preference, **kwargs) | ||
|
||
def impl(self, *args, **kwargs): | ||
raise RuntimeError("Scalar Scan Ops should never be evaluated!") |
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 |
---|---|---|
|
@@ -7,7 +7,7 @@ | |
import pytensor | ||
import pytensor.scalar.basic as aes | ||
from pytensor import compile | ||
from pytensor.compile.mode import get_target_language | ||
from pytensor.compile.mode import get_target_language, optdb | ||
from pytensor.configdefaults import config | ||
from pytensor.graph.basic import Apply, Constant, io_toposort | ||
from pytensor.graph.features import ReplaceValidate | ||
|
@@ -20,11 +20,14 @@ | |
) | ||
from pytensor.graph.rewriting.db import SequenceDB | ||
from pytensor.graph.utils import InconsistencyError, MethodNotDefined, TestValueError | ||
from pytensor.scalar import ScalarScanOp | ||
from pytensor.tensor.basic import MakeVector, alloc, cast, get_scalar_constant_value | ||
from pytensor.tensor.elemwise import CAReduce, DimShuffle, Elemwise | ||
from pytensor.tensor.exceptions import NotScalarConstantError | ||
from pytensor.tensor.extra_ops import broadcast_arrays | ||
from pytensor.tensor.rewriting.basic import register_canonicalize, register_specialize | ||
from pytensor.tensor.shape import shape_padleft | ||
from pytensor.tensor.subtensor import IncSubtensor | ||
from pytensor.tensor.var import TensorConstant | ||
|
||
|
||
|
@@ -1025,3 +1028,57 @@ def local_careduce_fusion(fgraph, node): | |
"fusion", | ||
position=49, | ||
) | ||
|
||
|
||
@node_rewriter([Elemwise]) | ||
def inline_elemwise_scan(fgraph, node): | ||
from pytensor.scan.basic import scan | ||
from pytensor.scan.utils import expand_empty | ||
|
||
scalar_op = node.op.scalar_op | ||
|
||
if not isinstance(scalar_op, ScalarScanOp): | ||
return None | ||
|
||
# TODO: Add non-batched implementation? That should be better for scans with big difference in required n_steps | ||
bcasted_inputs = broadcast_arrays(*node.inputs) | ||
ret, updates = scan( | ||
scalar_op.fn, | ||
outputs_info=bcasted_inputs[: scalar_op.nout], | ||
non_sequences=bcasted_inputs[scalar_op.nout :], | ||
n_steps=scalar_op.n_steps, | ||
sequences=None, | ||
strict=True, | ||
) | ||
if updates: | ||
raise ValueError("Scalar scan should never return updates") | ||
if scalar_op.nout == 1: | ||
ret = (ret,) | ||
|
||
# Scan output size is given by the size of the input leading dimension, by default its n_steps + 1. | ||
# If we only want to store the last elements we can shorten the leading dimension to 1 | ||
scan_node = ret[0].owner.inputs[0].owner | ||
scan_inputs = scan_node.inputs | ||
n_steps = scan_inputs[0] | ||
n_non_seqs = scan_node.op.info.n_non_seqs | ||
carried_inputs = scan_inputs[1 : len(scan_inputs) - n_non_seqs :] | ||
constant_inputs = scan_inputs[len(scan_inputs) - n_non_seqs :] | ||
new_carried_inputs = [] | ||
for carried_input in carried_inputs: | ||
assert isinstance(carried_input.owner.op, IncSubtensor) | ||
fill_value = carried_input.owner.inputs[1] | ||
# TODO: Check for the global flag where this is controlled | ||
new_carried_inputs.append(expand_empty(fill_value, 1)) | ||
ret = scan_node.op.make_node(n_steps, *new_carried_inputs, *constant_inputs).outputs | ||
Comment on lines
+1058
to
+1072
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. One shouldn't have to hack into scan internals to avoid saving the intermediate results... This is needed because of #178 |
||
|
||
return [r[1] for r in ret] | ||
|
||
|
||
# We want to run this after the scan save mem rewrite, as we already applied it here | ||
optdb.register( | ||
"inline_elemwise_scan", | ||
in2out(inline_elemwise_scan), | ||
"fast_compile", | ||
"fast_run", | ||
position=1.62, | ||
) |
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.