|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Boundary dtype-narrowing pass for the Core AI backend.""" |
| 8 | + |
| 9 | +import torch |
| 10 | +from executorch.exir.dialects.edge._ops import EdgeOpOverload |
| 11 | +from executorch.exir.pass_base import PassResult |
| 12 | +from torch.fx import GraphModule |
| 13 | +from torch.fx.passes.fake_tensor_prop import FakeTensorProp |
| 14 | + |
| 15 | +# Core AI represents only up-to-32-bit dtypes (coreai-torch narrows int64->si32 |
| 16 | +# and float64->f32 internally), so it can't carry a 64-bit tensor across the |
| 17 | +# delegate boundary. |
| 18 | +_NARROW = {torch.int64: torch.int32, torch.float64: torch.float32} |
| 19 | +_SIXTY_FOUR_BIT = (torch.int64, torch.float64) |
| 20 | + |
| 21 | + |
| 22 | +class NarrowToCoreAIDtypesPass: |
| 23 | + """Narrow int64/float64 to 32-bit inside the graph while preserving I/O. |
| 24 | +
|
| 25 | + Casts int64/float64 graph inputs to 32-bit right after the placeholder, |
| 26 | + re-propagates dtypes, then casts 32-bit values feeding int64/float64 outputs |
| 27 | + back to 64-bit. The model's external input/output dtypes stay unchanged, |
| 28 | + while the interior (what Core AI sees) becomes 32-bit. |
| 29 | +
|
| 30 | + The inserted ``_to_copy`` casts keep a 64-bit operand/result, so |
| 31 | + :class:`CoreAIPartitioner` (which rejects nodes with int64/float64 tensors) |
| 32 | + leaves them outside the delegate; the delegate boundary then sees only 32-bit |
| 33 | + tensors that match what coreai declares. |
| 34 | +
|
| 35 | + Runs pre-partition (e.g. via ``get_default_passes``) at either the ATen or |
| 36 | + edge level (it picks the matching ``_to_copy`` overload). |
| 37 | + """ |
| 38 | + |
| 39 | + def __call__(self, graph_module: GraphModule) -> PassResult: |
| 40 | + graph = graph_module.graph |
| 41 | + placeholders = [n for n in graph.nodes if n.op == "placeholder"] |
| 42 | + if not any(_is_64bit(p.meta.get("val")) for p in placeholders): |
| 43 | + return PassResult(graph_module, False) |
| 44 | + |
| 45 | + uses_edge = any( |
| 46 | + isinstance(node.target, EdgeOpOverload) |
| 47 | + for node in graph.nodes |
| 48 | + if node.op == "call_function" |
| 49 | + ) |
| 50 | + if uses_edge: |
| 51 | + from executorch.exir.dialects._ops import ops as exir_ops |
| 52 | + |
| 53 | + to_copy = exir_ops.edge.aten._to_copy.default |
| 54 | + else: |
| 55 | + to_copy = torch.ops.aten._to_copy.default |
| 56 | + |
| 57 | + output_node = next(n for n in graph.nodes if n.op == "output") |
| 58 | + # Remember which outputs were 64-bit so we can restore them afterwards. |
| 59 | + orig_output_dtypes = [ |
| 60 | + val.dtype if _is_64bit(val := _node_val(a)) else None |
| 61 | + for a in output_node.args[0] |
| 62 | + ] |
| 63 | + |
| 64 | + # 1. Narrow 64-bit inputs right after the placeholder. |
| 65 | + for placeholder in placeholders: |
| 66 | + val = placeholder.meta.get("val") |
| 67 | + if not _is_64bit(val): |
| 68 | + continue |
| 69 | + narrow_dtype = _NARROW[val.dtype] |
| 70 | + with graph.inserting_after(placeholder): |
| 71 | + cast = graph.call_function( |
| 72 | + to_copy, (placeholder,), {"dtype": narrow_dtype} |
| 73 | + ) |
| 74 | + placeholder.replace_all_uses_with(cast) |
| 75 | + cast.args = (placeholder,) # restore the cast's own (detached) input |
| 76 | + |
| 77 | + # 2. Re-propagate dtypes through the (now-32-bit) interior. |
| 78 | + FakeTensorProp(graph_module).propagate(*[p.meta["val"] for p in placeholders]) |
| 79 | + |
| 80 | + # 3. Widen 32-bit values feeding originally-64-bit outputs back. |
| 81 | + out_args = list(output_node.args[0]) |
| 82 | + for i, arg in enumerate(out_args): |
| 83 | + orig_dtype = orig_output_dtypes[i] |
| 84 | + if orig_dtype is None or not isinstance(arg, torch.fx.Node): |
| 85 | + continue |
| 86 | + cur = _node_val(arg) |
| 87 | + if isinstance(cur, torch.Tensor) and cur.dtype != orig_dtype: |
| 88 | + with graph.inserting_before(output_node): |
| 89 | + widen = graph.call_function(to_copy, (arg,), {"dtype": orig_dtype}) |
| 90 | + # Set by hand: this runs after the propagate above, so nothing |
| 91 | + # else fills it in. |
| 92 | + widen.meta["val"] = cur.to(orig_dtype) |
| 93 | + out_args[i] = widen |
| 94 | + output_node.args = (tuple(out_args),) |
| 95 | + |
| 96 | + graph_module.recompile() |
| 97 | + return PassResult(graph_module, True) |
| 98 | + |
| 99 | + |
| 100 | +def _node_val(arg): |
| 101 | + return arg.meta.get("val") if isinstance(arg, torch.fx.Node) else None |
| 102 | + |
| 103 | + |
| 104 | +def _is_64bit(val) -> bool: |
| 105 | + return isinstance(val, torch.Tensor) and val.dtype in _SIXTY_FOUR_BIT |
0 commit comments