|
1 | 1 | import mlx.core as mx |
2 | 2 |
|
| 3 | +from pytensor.graph import FunctionGraph |
3 | 4 | from pytensor.link.mlx.dispatch import mlx_funcify |
4 | 5 | from pytensor.tensor.blockwise import Blockwise |
5 | 6 |
|
| 7 | + |
6 | 8 | @mlx_funcify.register(Blockwise) |
7 | 9 | def funcify_Blockwise(op: Blockwise, node, *args, **kwargs): |
8 | | - core_f = mlx_funcify(op.core_op) |
9 | | - batched_f = core_f |
10 | | - for _ in range(op.batch_ndim(node)): |
11 | | - batched_f = mx.vmap(batched_f) |
12 | | - |
13 | | - def wrapped_blockwise_f(*inputs): |
14 | | - return batched_f(*inputs) |
15 | | - |
16 | | - return wrapped_blockwise_f |
| 10 | + # Create a function graph for the core operation |
| 11 | + core_node = op._create_dummy_core_node(node.inputs) |
| 12 | + core_fgraph = FunctionGraph(inputs=core_node.inputs, outputs=core_node.outputs) |
| 13 | + |
| 14 | + # Convert the core function graph to an MLX function |
| 15 | + tuple_core_fn = mlx_funcify(core_fgraph, **kwargs) |
| 16 | + |
| 17 | + # If there's only one output, unwrap it from the tuple |
| 18 | + if len(node.outputs) == 1: |
| 19 | + |
| 20 | + def core_fn(*inputs): |
| 21 | + return tuple_core_fn(*inputs)[0] |
| 22 | + else: |
| 23 | + core_fn = tuple_core_fn |
| 24 | + |
| 25 | + # Apply vmap for each batch dimension |
| 26 | + batch_ndims = op.batch_ndim(node) |
| 27 | + vmap_fn = core_fn |
| 28 | + for _ in range(batch_ndims): |
| 29 | + vmap_fn = mx.vmap(vmap_fn) |
| 30 | + |
| 31 | + def blockwise_fn(*inputs): |
| 32 | + # Check for runtime broadcasting compatibility |
| 33 | + op._check_runtime_broadcast(node, inputs) |
| 34 | + |
| 35 | + # Handle broadcasting for batched dimensions |
| 36 | + if batch_ndims > 0: |
| 37 | + # Get batch shapes for broadcasting |
| 38 | + batch_shapes = [inp.shape[:batch_ndims] for inp in inputs] |
| 39 | + |
| 40 | + # Calculate the broadcasted batch shape |
| 41 | + from functools import reduce |
| 42 | + |
| 43 | + def broadcast_shapes(shape1, shape2): |
| 44 | + return tuple(max(s1, s2) for s1, s2 in zip(shape1, shape2, strict=True)) |
| 45 | + |
| 46 | + if batch_shapes: |
| 47 | + broadcasted_shape = reduce(broadcast_shapes, batch_shapes) |
| 48 | + |
| 49 | + # Broadcast inputs to the common batch shape |
| 50 | + broadcasted_inputs = [] |
| 51 | + for inp in inputs: |
| 52 | + if inp.shape[:batch_ndims] != broadcasted_shape: |
| 53 | + # Create the full target shape |
| 54 | + target_shape = broadcasted_shape + inp.shape[batch_ndims:] |
| 55 | + # Broadcast the input |
| 56 | + broadcasted_inputs.append(mx.broadcast_to(inp, target_shape)) |
| 57 | + else: |
| 58 | + broadcasted_inputs.append(inp) |
| 59 | + |
| 60 | + # Apply the vectorized function to the broadcasted inputs |
| 61 | + return vmap_fn(*broadcasted_inputs) |
| 62 | + |
| 63 | + # No broadcasting needed |
| 64 | + return vmap_fn(*inputs) |
| 65 | + |
| 66 | + return blockwise_fn |
0 commit comments