|
| 1 | +"""size_average and reduce are deprecated, please use reduction='mean' instead.""" |
| 2 | + |
| 3 | +import libcst as cst |
| 4 | +from ...common import TorchVisitor, get_module_name |
| 5 | +from torch.nn._reduction import legacy_get_string |
| 6 | + |
| 7 | +def call_replacement_loss(node: cst.Call) -> cst.CSTNode: |
| 8 | + """ |
| 9 | + Replace loss function that contains size_average / reduce with a new loss function |
| 10 | + that uses reduction='mean' instead. Uses the logic from torch.nn._reduction to |
| 11 | + determine the correct reduction value. |
| 12 | + |
| 13 | + Args: |
| 14 | + node: The CST Call node representing the loss function call |
| 15 | + |
| 16 | + Returns: |
| 17 | + A new CST node with updated reduction parameter |
| 18 | + """ |
| 19 | + # Extract existing arguments |
| 20 | + input_arg = TorchVisitor.get_specific_arg(node, "input", 0) |
| 21 | + target_arg = TorchVisitor.get_specific_arg(node, "target", 1) |
| 22 | + |
| 23 | + size_average_arg = TorchVisitor.get_specific_arg(node, "size_average", 2) |
| 24 | + reduce_arg = TorchVisitor.get_specific_arg(node, "reduce", 3) |
| 25 | + |
| 26 | + # Ensure input and target args maintain their commas |
| 27 | + input_arg = cst.ensure_type(input_arg, cst.Arg).with_changes( |
| 28 | + comma=cst.MaybeSentinel.DEFAULT |
| 29 | + ) |
| 30 | + |
| 31 | + target_arg = cst.ensure_type(target_arg, cst.Arg).with_changes( |
| 32 | + comma=cst.MaybeSentinel.DEFAULT |
| 33 | + ) |
| 34 | + |
| 35 | + # Extract size_average and reduce values |
| 36 | + size_average_value = None |
| 37 | + reduce_value = None |
| 38 | + |
| 39 | + if size_average_arg: |
| 40 | + size_average_value = getattr(size_average_arg.value, "value", True) |
| 41 | + if reduce_arg: |
| 42 | + reduce_value = getattr(reduce_arg.value, "value", True) |
| 43 | + |
| 44 | + if size_average_value is None and reduce_value is None: |
| 45 | + # We want to return the original call as is |
| 46 | + return node |
| 47 | + # Use legacy_get_string to determine the correct reduction value |
| 48 | + reduction = legacy_get_string(size_average_value, reduce_value, emit_warning=False) |
| 49 | + |
| 50 | + # Create new reduction argument |
| 51 | + reduction_arg = cst.Arg( |
| 52 | + value=cst.SimpleString(f"'{reduction}'"), |
| 53 | + keyword=cst.Name("reduction"), |
| 54 | + comma=cst.MaybeSentinel.DEFAULT, |
| 55 | + ) |
| 56 | + |
| 57 | + # Build new arguments list |
| 58 | + new_args = [input_arg, target_arg, reduction_arg] |
| 59 | + replacement = node.with_changes(args=new_args) |
| 60 | + return replacement |
0 commit comments