Skip to content

Allow string keys in eval utility #242

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 7 commits into from
Mar 22, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions pytensor/graph/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,39 @@ def get_parents(self):
return [self.owner]
return []

def convert_string_keys_to_pytensor_variables(self, inputs_to_values):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given we are in pytensor, no need to mention it in the name. If you want you can specify the return type is Dict[Variable, Variable]

Suggested change
def convert_string_keys_to_pytensor_variables(self, inputs_to_values):
def convert_string_keys_to_variables(self, inputs_to_values):

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good, will replace the function name with suggested one.

r"""Convert the string keys to corresponding `Variable` with nearest name.

Parameters
----------
inputs_to_values :
A dictionary mapping PyTensor `Variable`\s to values.

Examples
--------

>>> import numpy as np
>>> import pytensor.tensor as at
>>> x = at.dscalar('x')
>>> y = at.dscalar('y')
>>> z = x + y
>>> np.allclose(z.eval({'x' : 3, 'y' : 1}), 4)
True
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not show a use of the function. In any case we don't need a docstring with an example I think

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we are making it internal to eval I also think that the doc-string will be no more required.

"""
process_input_to_values = {}
for i in inputs_to_values:
if isinstance(i, str):
nodes_with_matching_names = get_var_by_name([self], i)
if len(nodes_with_matching_names) == 0:
raise Exception(f"{i} not found in graph")
else:
process_input_to_values[
nodes_with_matching_names[0]
] = inputs_to_values[i]
else:
process_input_to_values[i] = inputs_to_values[i]
return process_input_to_values

def eval(self, inputs_to_values=None):
r"""Evaluate the `Variable`.

Expand Down Expand Up @@ -597,6 +630,10 @@ def eval(self, inputs_to_values=None):
if inputs_to_values is None:
inputs_to_values = {}

inputs_to_values = self.convert_string_keys_to_pytensor_variables(
inputs_to_values
)

if not hasattr(self, "_fn_cache"):
self._fn_cache = dict()

Expand Down
8 changes: 8 additions & 0 deletions tests/graph/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,14 @@ def test_eval(self):
pickle.loads(pickle.dumps(self.w)), "_fn_cache"
), "temporary functions must not be serialized"

def test_eval_with_strings(self):
assert self.w.eval({"x": 1.0, "y": 2.0}) == 6.0
assert self.w.eval({self.z: 3}) == 6.0
assert hasattr(self.w, "_fn_cache"), "variable must have cache after eval"
assert not hasattr(
pickle.loads(pickle.dumps(self.w)), "_fn_cache"
), "temporary functions must not be serialized"


class TestAutoName:
def test_auto_name(self):
Expand Down