code: def clone_replace(
      output: Union[Sequence[Variable], Variable],
      replace: Optional[ReplaceTypes] = None,
      **rebuild_kwds,
  ) -> Union[list[Variable], Variable]:
      """Clone a graph and replace subgraphs within it.
  
      It returns a copy of the initial subgraph with the corresponding
      substitutions.
  
      Parameters
      ----------
      output
          PyTensor expression that represents the computational graph.
      replace
          Dictionary describing which subgraphs should be replaced by what.
      rebuild_kwds
          Keywords to `rebuild_collect_shared`.
  
      """
      from pytensor.compile.function.pfunc import rebuild_collect_shared
  
      items = list(_format_replace(replace).items())
  
      tmp_replace = [(x, x.type()) for x, y in items]
      new_replace = [
          (x, y) for ((_, x), (_, y)) in zip(tmp_replace, items)
      ]
      _, _outs, _ = rebuild_collect_shared(
          output, [], tmp_replace, [], **rebuild_kwds
      )
  
      # TODO Explain why we call it twice ?!
      _, outs, _ = rebuild_collect_shared(
          _outs, [], new_replace, [], **rebuild_kwds
      )
  
      return outs
  
imports: import warnings
  from collections.abc import Iterable, Mapping, Sequence
  from functools import partial, singledispatch
  from typing import Optional, Union, cast, overload
  from pytensor.graph.basic import Apply, Constant, Variable, io_toposort, truncated_graph_inputs
  from pytensor.graph.fg import FunctionGraph
  from pytensor.graph.op import Op
label_desc: Use image node_id 4 for calling a global function with example usage: clone_replace(output, replace) and returns: outs