|
| 1 | +# Copyright 2024 The PyMC Developers |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from pytensor import clone_replace |
| 15 | +from pytensor.compile import SharedVariable |
| 16 | +from pytensor.graph import FunctionGraph |
| 17 | +from pytensor.tensor import constant |
| 18 | + |
| 19 | +from pymc import Model |
| 20 | +from pymc.model.fgraph import ModelFreeRV, fgraph_from_model, model_from_fgraph |
| 21 | + |
| 22 | + |
| 23 | +def freeze_dims_and_data(model: Model) -> Model: |
| 24 | + """Recreate a Model with fixed RV dimensions and Data values. |
| 25 | +
|
| 26 | + The dimensions of the pre-existing RVs will no longer follow changes to the coordinates. |
| 27 | + Likewise, it will not be possible to update pre-existing Data in the new model. |
| 28 | +
|
| 29 | + Note that any new RVs and Data created after calling this function will still be "unfrozen". |
| 30 | +
|
| 31 | + This transformation may allow more performant sampling, or compiling model functions to backends that |
| 32 | + are more restrictive about dynamic shapes such as JAX. |
| 33 | + """ |
| 34 | + fg, memo = fgraph_from_model(model) |
| 35 | + |
| 36 | + # Replace mutable dim lengths and data by constants |
| 37 | + frozen_vars = { |
| 38 | + memo[dim_length]: constant( |
| 39 | + dim_length.get_value(), name=dim_length.name, dtype=dim_length.type.dtype |
| 40 | + ) |
| 41 | + for dim_length in model.dim_lengths.values() |
| 42 | + if isinstance(dim_length, SharedVariable) |
| 43 | + } |
| 44 | + frozen_vars |= { |
| 45 | + memo[data_var].owner.inputs[0]: constant( |
| 46 | + data_var.get_value(), name=data_var.name, dtype=data_var.type.dtype |
| 47 | + ) |
| 48 | + for data_var in model.named_vars.values() |
| 49 | + if isinstance(data_var, SharedVariable) |
| 50 | + } |
| 51 | + |
| 52 | + old_outs, coords = fg.outputs, fg._coords # type: ignore |
| 53 | + # Rebuild strict will force the recreation of RV nodes with updated static types |
| 54 | + new_outs = clone_replace(old_outs, replace=frozen_vars, rebuild_strict=False) # type: ignore |
| 55 | + for old_out, new_out in zip(old_outs, new_outs): |
| 56 | + new_out.name = old_out.name |
| 57 | + fg = FunctionGraph(outputs=new_outs, clone=False) |
| 58 | + fg._coords = coords # type: ignore |
| 59 | + |
| 60 | + # Recreate value variables from new RVs to propagate static types to logp graphs |
| 61 | + replacements = {} |
| 62 | + for node in fg.apply_nodes: |
| 63 | + if not isinstance(node.op, ModelFreeRV): |
| 64 | + continue |
| 65 | + rv, old_value, *dims = node.inputs |
| 66 | + if dims is None: |
| 67 | + continue |
| 68 | + transform = node.op.transform |
| 69 | + if transform is None: |
| 70 | + new_value = rv.type() |
| 71 | + else: |
| 72 | + new_value = transform.forward(rv, *rv.owner.inputs).type() # type: ignore |
| 73 | + new_value.name = old_value.name |
| 74 | + replacements[old_value] = new_value |
| 75 | + fg.replace_all(tuple(replacements.items()), import_missing=True) |
| 76 | + |
| 77 | + return model_from_fgraph(fg) |
| 78 | + |
| 79 | + |
| 80 | +__all__ = ("freeze_dims_and_data",) |
0 commit comments