|
| 1 | +from pytensor.compile import optdb |
| 2 | +from pytensor.graph import node_rewriter |
| 3 | +from pytensor.graph.basic import applys_between |
| 4 | +from pytensor.graph.rewriting.basic import out2in |
| 5 | +from pytensor.tensor.basic import as_tensor, constant |
| 6 | +from pytensor.tensor.blockwise import Blockwise, BlockwiseWithCoreShape |
| 7 | + |
| 8 | + |
| 9 | +@node_rewriter([Blockwise]) |
| 10 | +def introduce_explicit_core_shape_blockwise(fgraph, node): |
| 11 | + """Introduce the core shape of a Blockwise. |
| 12 | +
|
| 13 | + We wrap Blockwise graphs into a BlockwiseWithCoreShape OpFromGraph |
| 14 | + that has an extra "non-functional" input that represents the core shape of the Blockwise variable. |
| 15 | + This core_shape is used by the numba backend to pre-allocate the output array. |
| 16 | +
|
| 17 | + If available, the core shape is extracted from the shape feature of the graph, |
| 18 | + which has a higher change of having been simplified, optimized, constant-folded. |
| 19 | + If missing, we fall back to the op._supp_shape_from_params method. |
| 20 | +
|
| 21 | + This rewrite is required for the numba backend implementation of Blockwise. |
| 22 | +
|
| 23 | + Example |
| 24 | + ------- |
| 25 | +
|
| 26 | + .. code-block:: python |
| 27 | +
|
| 28 | + import pytensor |
| 29 | + import pytensor.tensor as pt |
| 30 | +
|
| 31 | + x = pt.random.dirichlet(alphas=[1, 2, 3], size=(5,)) |
| 32 | + pytensor.dprint(x, print_type=True) |
| 33 | + # dirichlet_rv{"(a)->(a)"}.1 [id A] <Matrix(float64, shape=(5, 3))> |
| 34 | + # ├─ RNG(<Generator(PCG64) at 0x7F09E59C18C0>) [id B] <RandomGeneratorType> |
| 35 | + # ├─ [5] [id C] <Vector(int64, shape=(1,))> |
| 36 | + # └─ ExpandDims{axis=0} [id D] <Matrix(int64, shape=(1, 3))> |
| 37 | + # └─ [1 2 3] [id E] <Vector(int64, shape=(3,))> |
| 38 | +
|
| 39 | + # After the rewrite, note the new core shape input [3] [id B] |
| 40 | + fn = pytensor.function([], x, mode="NUMBA") |
| 41 | + pytensor.dprint(fn.maker.fgraph) |
| 42 | + # [dirichlet_rv{"(a)->(a)"}].1 [id A] 0 |
| 43 | + # ├─ [3] [id B] |
| 44 | + # ├─ RNG(<Generator(PCG64) at 0x7F15B8E844A0>) [id C] |
| 45 | + # ├─ [5] [id D] |
| 46 | + # └─ [[1 2 3]] [id E] |
| 47 | + # Inner graphs: |
| 48 | + # [dirichlet_rv{"(a)->(a)"}] [id A] |
| 49 | + # ← dirichlet_rv{"(a)->(a)"}.0 [id F] |
| 50 | + # ├─ *1-<RandomGeneratorType> [id G] |
| 51 | + # ├─ *2-<Vector(int64, shape=(1,))> [id H] |
| 52 | + # └─ *3-<Matrix(int64, shape=(1, 3))> [id I] |
| 53 | + # ← dirichlet_rv{"(a)->(a)"}.1 [id F] |
| 54 | + # └─ ··· |
| 55 | + """ |
| 56 | + op: Blockwise = node.op # type: ignore[annotation-unchecked] |
| 57 | + batch_ndim = op.batch_ndim(node) |
| 58 | + |
| 59 | + shape_feature: ShapeFeature | None = getattr(fgraph, "shape_feature", None) # type: ignore[annotation-unchecked] |
| 60 | + if shape_feature: |
| 61 | + core_shapes = [ |
| 62 | + [shape_feature.get_shape(out, i) for i in range(batch_ndim, out.type.ndim)] |
| 63 | + for out in node.outputs |
| 64 | + ] |
| 65 | + else: |
| 66 | + raise ValueError |
| 67 | + core_shapes = op._supp_shape_from_params(op.dist_params(node)) |
| 68 | + |
| 69 | + core_shapes = [ |
| 70 | + as_tensor(core_shape) if len(core_shape) else constant([], dtype="int64") |
| 71 | + for core_shape in core_shapes |
| 72 | + ] |
| 73 | + |
| 74 | + if any( |
| 75 | + isinstance(node.op, Blockwise) |
| 76 | + for node in applys_between(node.inputs, core_shapes) |
| 77 | + ): |
| 78 | + # If Blockwise shows up in the shape graph we can't introduce the core shape |
| 79 | + return None |
| 80 | + |
| 81 | + return ( |
| 82 | + BlockwiseWithCoreShape( |
| 83 | + [*node.inputs, *core_shapes], |
| 84 | + node.outputs, |
| 85 | + destroy_map=op.destroy_map, |
| 86 | + ) |
| 87 | + .make_node(*node.inputs, *core_shapes) |
| 88 | + .outputs |
| 89 | + ) |
| 90 | + |
| 91 | + |
| 92 | +optdb.register( |
| 93 | + introduce_explicit_core_shape_blockwise.__name__, |
| 94 | + out2in(introduce_explicit_core_shape_blockwise), |
| 95 | + "numba", |
| 96 | + position=100, |
| 97 | +) |
0 commit comments