|
| 1 | +# Copyright 2025 The HuggingFace Team. All rights reserved. |
| 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 | +import warnings |
| 15 | +from collections import defaultdict |
| 16 | +from functools import wraps |
| 17 | + |
| 18 | +from transformers.utils.generic import _CAN_RECORD_REGISTRY, OutputRecorder, logger |
| 19 | + |
| 20 | + |
| 21 | +# This is a fixed version of transformers.utils.generic.check_model_inputs |
| 22 | +# that fixes issues related to onnx export and tracing |
| 23 | +# - adds support for positional args (use_cache), without which use_cache end up being passed twice |
| 24 | +# - fixes issue with default capture_flags being None for some models |
| 25 | +def traceable_check_model_inputs(func): |
| 26 | + @wraps(func) |
| 27 | + def wrapper(self, *args, **kwargs): |
| 28 | + use_cache = ( |
| 29 | + kwargs["use_cache"] if kwargs.get("use_cache") is not None else getattr(self.config, "use_cache", None) |
| 30 | + ) |
| 31 | + if use_cache is not None: |
| 32 | + if getattr(self, "gradient_checkpointing", False) and self.training and use_cache: |
| 33 | + logger.warning_once( |
| 34 | + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." |
| 35 | + ) |
| 36 | + use_cache = False |
| 37 | + |
| 38 | + # Prevent passing use_cache twice |
| 39 | + if "use_cache" in func.__code__.co_varnames: |
| 40 | + use_cache_idx = func.__code__.co_varnames.index("use_cache") - 1 # minus 1 for 'self' |
| 41 | + if len(args) > use_cache_idx: |
| 42 | + args = list(args) |
| 43 | + args[use_cache_idx] = use_cache |
| 44 | + args = tuple(args) |
| 45 | + else: |
| 46 | + kwargs["use_cache"] = use_cache |
| 47 | + |
| 48 | + return_dict = kwargs.pop("return_dict", None) |
| 49 | + if return_dict is None: |
| 50 | + return_dict = getattr(self.config, "return_dict", True) |
| 51 | + |
| 52 | + all_args = kwargs.copy() |
| 53 | + if "kwargs" in all_args: |
| 54 | + for k, v in all_args["kwargs"].items(): |
| 55 | + all_args[k] = v |
| 56 | + |
| 57 | + capture_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__)) or {} # there is a weak ref for executorch |
| 58 | + |
| 59 | + recordable_keys = { |
| 60 | + f"output_{k}": all_args.get( |
| 61 | + f"output_{k}", |
| 62 | + getattr( |
| 63 | + self.config, |
| 64 | + f"output_{k}", |
| 65 | + all_args.get("output_attentions", getattr(self.config, "output_attentions", False)), |
| 66 | + ), |
| 67 | + ) |
| 68 | + for k in capture_flags |
| 69 | + } |
| 70 | + |
| 71 | + # We let cross attentions to be saved separately because some models add `cross-attn` layer |
| 72 | + # when certain condtions are met. Let's output cross attention if attentions are requested (for BC) |
| 73 | + if "output_attentions" in recordable_keys: |
| 74 | + recordable_keys["output_cross_attentions"] = recordable_keys["output_attentions"] |
| 75 | + |
| 76 | + collected_outputs = defaultdict(tuple) |
| 77 | + monkey_patched_layers = [] |
| 78 | + |
| 79 | + # Check attention implementation is properly set for capturing attention outputs |
| 80 | + if recordable_keys.get("output_attentions", False): |
| 81 | + supported_attn = ["eager", "eager_paged", "flex_attention"] |
| 82 | + config_attn = getattr(self.config, "_attn_implementation", None) |
| 83 | + sub_configs = [getattr(self.config, key, None) for key in self.config.sub_configs] |
| 84 | + sub_configs_attn = [ |
| 85 | + getattr(config, "_attn_implementation", None) for config in sub_configs if config is not None |
| 86 | + ] |
| 87 | + if config_attn not in supported_attn or any(attn not in supported_attn for attn in sub_configs_attn): |
| 88 | + warnings.warn( |
| 89 | + f"`output_attentions=True` is not supported with `attn_implementation` other than {supported_attn}. " |
| 90 | + "Please use `model.set_attn_implementation('eager')` to enable capturing attention outputs.", |
| 91 | + UserWarning, |
| 92 | + stacklevel=2, |
| 93 | + ) |
| 94 | + |
| 95 | + def make_capture_wrapper(module, orig_forward, key, index): |
| 96 | + @wraps(orig_forward) |
| 97 | + def wrapped_forward(*args, **kwargs): |
| 98 | + if key == "hidden_states" and len(collected_outputs[key]) == 0: |
| 99 | + collected_outputs[key] += (args[0],) |
| 100 | + output = orig_forward(*args, **kwargs) |
| 101 | + if not isinstance(output, tuple): |
| 102 | + collected_outputs[key] += (output,) |
| 103 | + elif output[index] is not None: |
| 104 | + if key not in collected_outputs: |
| 105 | + collected_outputs[key] = (output[index],) |
| 106 | + else: |
| 107 | + collected_outputs[key] += (output[index],) |
| 108 | + return output |
| 109 | + |
| 110 | + return wrapped_forward |
| 111 | + |
| 112 | + if any(recordable_keys.values()): |
| 113 | + capture_tasks = [] |
| 114 | + for key, layer_specs in capture_flags.items(): |
| 115 | + if not recordable_keys.get(f"output_{key}", False): |
| 116 | + continue |
| 117 | + if not isinstance(layer_specs, list): |
| 118 | + layer_specs = [layer_specs] |
| 119 | + for specs in layer_specs: |
| 120 | + if not isinstance(specs, OutputRecorder): |
| 121 | + index = 0 if "hidden_states" in key else 1 |
| 122 | + class_name = None if not isinstance(specs, str) else specs |
| 123 | + target_class = specs if not isinstance(specs, str) else None |
| 124 | + specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name) |
| 125 | + capture_tasks.append((key, specs)) |
| 126 | + |
| 127 | + for name, module in self.named_modules(): |
| 128 | + for key, specs in capture_tasks: |
| 129 | + # The second check is for multimodals where only backbone layer suffix is available |
| 130 | + if (specs.target_class is not None and isinstance(module, specs.target_class)) or ( |
| 131 | + specs.class_name is not None and name.endswith(specs.class_name) |
| 132 | + ): |
| 133 | + if specs.layer_name is not None and specs.layer_name not in name: |
| 134 | + continue |
| 135 | + # Monkey patch forward |
| 136 | + original_forward = module.forward |
| 137 | + module.forward = make_capture_wrapper(module, original_forward, key, specs.index) |
| 138 | + monkey_patched_layers.append((module, original_forward)) |
| 139 | + |
| 140 | + outputs = func(self, *args, **kwargs) |
| 141 | + # Restore original forward methods |
| 142 | + for module, original_forward in monkey_patched_layers: |
| 143 | + module.forward = original_forward |
| 144 | + |
| 145 | + # Inject collected outputs into model output |
| 146 | + for key in collected_outputs: |
| 147 | + if key == "hidden_states": |
| 148 | + if hasattr(outputs, "vision_hidden_states"): |
| 149 | + collected_outputs[key] = collected_outputs[key][:-1] |
| 150 | + collected_outputs[key] += (outputs.vision_hidden_states,) |
| 151 | + elif hasattr(outputs, "last_hidden_state"): |
| 152 | + collected_outputs[key] = collected_outputs[key][:-1] |
| 153 | + collected_outputs[key] += (outputs.last_hidden_state,) |
| 154 | + |
| 155 | + outputs[key] = collected_outputs[key] |
| 156 | + elif key == "attentions": |
| 157 | + if isinstance(capture_flags[key], list) and len(capture_flags[key]) == 2: |
| 158 | + outputs[key] = collected_outputs[key][0::2] |
| 159 | + outputs["cross_" + key] = collected_outputs[key][1::2] |
| 160 | + else: |
| 161 | + outputs[key] = collected_outputs[key] |
| 162 | + else: |
| 163 | + outputs[key] = collected_outputs[key] |
| 164 | + if return_dict is False: |
| 165 | + outputs = outputs.to_tuple() |
| 166 | + return outputs |
| 167 | + |
| 168 | + return wrapper |
0 commit comments