|
| 1 | +# Copyright 2025 The AI Edge Torch Authors. |
| 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 | +# ============================================================================== |
| 15 | +"""Pass to cast all inputs with torch.bfloat16 type to torch.float32.""" |
| 16 | + |
| 17 | + |
| 18 | +from ai_edge_torch import fx_infra |
| 19 | +import torch |
| 20 | + |
| 21 | + |
| 22 | +def cast_f32(x): |
| 23 | + return x.to(torch.float32) |
| 24 | + |
| 25 | + |
| 26 | +class CastInputsBf16ToF32Pass(fx_infra.ExportedProgramPassBase): |
| 27 | + """This pass casts all inputs with torch.bfloat16 type to torch.float32.""" |
| 28 | + |
| 29 | + def call(self, exported_program: torch.export.ExportedProgram): |
| 30 | + modified = False |
| 31 | + for node in exported_program.graph.nodes: |
| 32 | + if ( |
| 33 | + node.op == "placeholder" |
| 34 | + and node.meta.get("val").dtype == torch.bfloat16 |
| 35 | + ): |
| 36 | + if not node.users: |
| 37 | + continue |
| 38 | + |
| 39 | + modified = True |
| 40 | + user = next(iter(node.users)) |
| 41 | + with exported_program.graph.inserting_before(user): |
| 42 | + cast_node = exported_program.graph.call_function( |
| 43 | + cast_f32, |
| 44 | + (node,), |
| 45 | + ) |
| 46 | + node.replace_all_uses_with(cast_node) |
| 47 | + cast_node.replace_input_with(cast_node, node) |
| 48 | + |
| 49 | + exported_program.graph_module.recompile() |
| 50 | + return fx_infra.ExportedProgramPassResult(exported_program, modified) |
0 commit comments