Skip to content

Transform to remove Minibatch from model #7746

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
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
26 changes: 25 additions & 1 deletion pymc/model/transform/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
# limitations under the License.
from collections.abc import Sequence

from pytensor import Variable
from pytensor import Variable, clone_replace
from pytensor.graph import ancestors
from pytensor.graph.fg import FunctionGraph

from pymc.data import MinibatchOp
from pymc.model.core import Model
from pymc.model.fgraph import (
ModelObservedRV,
Expand Down Expand Up @@ -58,3 +60,25 @@ def parse_vars(model: Model, vars: ModelVariable | Sequence[ModelVariable]) -> l
else:
vars_seq = (vars,)
return [model[var] if isinstance(var, str) else var for var in vars_seq]


def remove_minibatched_nodes(model: Model) -> Model:
"""Remove all uses of pm.Minibatch in the Model."""
fgraph, _ = fgraph_from_model(model)

replacements = {}
for var in fgraph.apply_nodes:
if isinstance(var.op, MinibatchOp):
for inp, out in zip(var.inputs, var.outputs):
replacements[out] = inp

old_outs, old_coords, old_dim_lengths = fgraph.outputs, fgraph._coords, fgraph._dim_lengths # type: ignore[attr-defined]
# Using `rebuild_strict=False` means all coords, names, and dim information is lost
# So we need to restore it from the old fgraph
new_outs = clone_replace(old_outs, replacements, rebuild_strict=False) # type: ignore[arg-type]
for old_out, new_out in zip(old_outs, new_outs):
new_out.name = old_out.name
fgraph = FunctionGraph(outputs=new_outs, clone=False)
fgraph._coords = old_coords # type: ignore[attr-defined]
fgraph._dim_lengths = old_dim_lengths # type: ignore[attr-defined]
return model_from_fgraph(fgraph, mutate_fgraph=True)
18 changes: 17 additions & 1 deletion tests/model/transform/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
# 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.
import numpy as np

import pymc as pm

from pymc.model.transform.basic import prune_vars_detached_from_observed
from pymc.model.transform.basic import prune_vars_detached_from_observed, remove_minibatched_nodes


def test_prune_vars_detached_from_observed():
Expand All @@ -30,3 +32,17 @@ def test_prune_vars_detached_from_observed():
assert set(m.named_vars.keys()) == {"obs_data", "a0", "a1", "a2", "obs", "d0", "d1"}
pruned_m = prune_vars_detached_from_observed(m)
assert set(pruned_m.named_vars.keys()) == {"obs_data", "a0", "a1", "a2", "obs"}


def test_remove_minibatches():
data_size = 100
data = np.zeros((data_size,))
batch_size = 10
with pm.Model() as m1:
mb = pm.Minibatch(data, batch_size=batch_size)
x = pm.Normal("x")
y = pm.Normal("y", x, observed=mb, total_size=100)

m2 = remove_minibatched_nodes(m1)
assert m1.y.shape[0].eval() == batch_size
assert m2.y.shape[0].eval() == data_size
Loading