model_debugging_utils.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. # Copyright 2025 The HuggingFace Inc. team.
  2. # All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import functools
  16. import json
  17. import os
  18. import re
  19. from contextlib import contextmanager, redirect_stdout
  20. from io import StringIO
  21. from .utils import logging
  22. from .utils.import_utils import is_torch_available, requires
  23. if is_torch_available():
  24. import torch
  25. from safetensors.torch import save_file
  26. _torch_distributed_available = False
  27. # Note to code inspectors: this toolbox is intended for people who add models to `transformers`.
  28. if torch.distributed.is_available():
  29. import torch.distributed.tensor
  30. _torch_distributed_available = True
  31. else:
  32. _torch_distributed_available = False
  33. logger = logging.get_logger(__name__)
  34. def _is_rank_zero():
  35. """Return True if rank=0 or we aren't running distributed."""
  36. if not (_torch_distributed_available and torch.distributed.is_initialized()):
  37. return True
  38. return torch.distributed.get_rank() == 0
  39. MEMORY_ADDRESS_REGEX = re.compile(r"object at 0x[0-9A-Fa-f]+")
  40. def _sanitize_repr_for_diff(x_str: str) -> str:
  41. """
  42. Replace memory addresses in an object's repr with a stable placeholder
  43. so that beautiful JSON diffs won't be ruined by ephemeral addresses.
  44. """
  45. return MEMORY_ADDRESS_REGEX.sub("object at 0xXXXXXXXX", x_str)
  46. def _dtensor_repr(x):
  47. """Return a stable string representation for a DTensor-like object."""
  48. if _is_rank_zero():
  49. return f"DTensor (rank0) -> {repr(x._local_tensor)}"
  50. return "DTensor(non-rank0)"
  51. def _serialize_tensor_like_io(
  52. value, debug_path: str | None = None, use_repr: bool = True, path_to_value: str | None = None
  53. ):
  54. """
  55. Converts Tensors and DTensors to a JSON-serializable dictionary representation.
  56. Args:
  57. value: Any Python object, often including torch Tensors, lists, dicts, etc.
  58. debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files.
  59. use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensor as the
  60. `value` property in the asscoiated FULL_TENSORS.json file, or to store the full tensors in separate
  61. SafeTensors file and store the relative path to that file in the `value` property in the dictionary.
  62. path_to_value (`str`, *optional*, defaults to `None`): The file name for the SafeTensors file holding the full
  63. tensor value if `use_repr=False`.
  64. Returns:
  65. A nested Python structure (list, dict, or sanitized string) that is safe to json.dump.
  66. """
  67. torch.set_printoptions(sci_mode=True)
  68. if use_repr:
  69. value_out = _repr_to_list(value)
  70. elif path_to_value:
  71. if not path_to_value.endswith(".safetensors"):
  72. path_to_value += ".safetensors"
  73. filepath = os.path.join(debug_path, path_to_value) if debug_path else path_to_value
  74. save_file({"data": value.contiguous().detach().cpu()}, filepath)
  75. value_out = f"./{path_to_value}"
  76. else:
  77. raise ValueError(f"{use_repr=} and {path_to_value=} cannot both be falsy.")
  78. out = {
  79. "shape": repr(value.shape),
  80. "dtype": repr(value.dtype),
  81. "value": value_out,
  82. }
  83. if value.dtype in {torch.float16, torch.float32, torch.bfloat16}:
  84. out.update(
  85. {
  86. "mean": _sanitize_repr_for_diff(repr(value.mean())),
  87. "std": _sanitize_repr_for_diff(repr(value.std())),
  88. "min": _sanitize_repr_for_diff(repr(value.min())),
  89. "max": _sanitize_repr_for_diff(repr(value.max())),
  90. }
  91. )
  92. return out
  93. def _serialize_io(value, debug_path: str | None = None, use_repr: bool = True, path_to_value: str | None = None):
  94. """
  95. Recursively build a JSON-serializable Python structure from `value`.
  96. Tensors and DTensors become either sanitized repr strings, or are saved to disk as SafeTensors files and their
  97. relative paths are recorded in the returned Python structure.
  98. Lists/tuples/dicts are recursed into.
  99. All memory addresses are replaced with a stable placeholder.
  100. Args:
  101. value: Any Python object, often including torch Tensors, lists, dicts, etc.
  102. debug_path (`str`, *optional*, defaults to `None`): Directory to dump debug JSON and SafeTensors files.
  103. use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensors as the
  104. `value` property in the asscoiated FULL_TENSORS.json file, or to store full tensors in separate SafeTensors
  105. files and store the relative path to that file in the `value` property.
  106. path_to_value (`str`, *optional*, defaults to `None`): The file name for the SafeTensors file holding the full
  107. tensor value if `use_repr=False`.
  108. Returns:
  109. A nested Python structure (list, dict, or sanitized string) that is safe to json.dump.
  110. """
  111. if isinstance(value, (list, tuple)):
  112. return [
  113. _serialize_io(v, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{path_to_value}_{i}")
  114. for i, v in enumerate(value)
  115. ]
  116. if isinstance(value, dict):
  117. return {
  118. k: _serialize_io(v, debug_path=debug_path, use_repr=use_repr, path_to_value=f"{path_to_value}_{k}")
  119. for k, v in value.items()
  120. }
  121. if hasattr(value, "_local_tensor"):
  122. return _serialize_tensor_like_io(
  123. value._local_tensor, debug_path=debug_path, use_repr=use_repr, path_to_value=path_to_value
  124. )
  125. if isinstance(value, torch.Tensor):
  126. return _serialize_tensor_like_io(value, debug_path=debug_path, use_repr=use_repr, path_to_value=path_to_value)
  127. return _sanitize_repr_for_diff(repr(value))
  128. def _repr_to_list(value: torch.Tensor):
  129. """
  130. Converts a tensor into a sanitized multi-line string representation.
  131. Args:
  132. value (`torch.Tensor`): The tensor to represent.
  133. Returns:
  134. `list[str]`: List of string lines representing the tensor.
  135. """
  136. torch.set_printoptions(sci_mode=True, linewidth=120)
  137. with StringIO() as buf, redirect_stdout(buf):
  138. print(value) # to redirected stdout to avoid line splits
  139. raw = buf.getvalue()
  140. return _sanitize_repr_for_diff(raw).splitlines()
  141. def prune_outputs_if_children(node):
  142. # if there are children, remove this node's "outputs"
  143. # so we only see outputs at the leaf level
  144. if node.get("children"):
  145. node.pop("outputs", None)
  146. for child in node["children"]:
  147. prune_outputs_if_children(child)
  148. LAYER_SUFFIX_RE = re.compile(r"(.*)\.(\d+)$") # should be generic enough, ends with a number
  149. def is_layer_block(node):
  150. """
  151. Checks whether a node represents a layer block with submodules.
  152. Args:
  153. node (`dict`): A node from the call tree.
  154. Returns:
  155. `bool`: Whether the node is a layer block.
  156. """
  157. match = LAYER_SUFFIX_RE.match(node.get("module_path", ""))
  158. if not match or not node.get("children"):
  159. return False
  160. number = match.group(2)
  161. return any(f".{number}." in child.get("module_path", "") for child in node["children"])
  162. def prune_intermediate_layers(node):
  163. """
  164. Recursively removes intermediate layers from the tree to improve readability.
  165. Keeps at least the first and last layers if many consecutive layers are present.
  166. Args:
  167. node (`dict`): The root or subnode to prune recursively.
  168. """
  169. if not node.get("children"):
  170. return
  171. layer_blocks = [(i, child) for i, child in enumerate(node["children"]) if is_layer_block(child)]
  172. if len(layer_blocks) > 2:
  173. to_remove = [i for i, _ in layer_blocks[1:-1]]
  174. node["children"] = [child for i, child in enumerate(node["children"]) if i not in to_remove]
  175. for child in node["children"]:
  176. prune_intermediate_layers(child)
  177. def log_model_debug_trace(debug_path: str | None, model):
  178. if debug_path:
  179. try:
  180. os.makedirs(debug_path, exist_ok=True)
  181. base = os.path.join(debug_path, model._debugger_module_dump_name + "_debug_tree")
  182. except Exception as e:
  183. raise ValueError(f"Unexpected or existing debug_path={debug_path}.") from e
  184. else:
  185. base = model._debugger_module_dump_name + "_debug_tree"
  186. logger.info(f"Writing model trace at {base}.json")
  187. full_path = base + "_FULL_TENSORS.json"
  188. summary_path = base + "_SUMMARY.json"
  189. prune_outputs_if_children(model._call_tree)
  190. with open(full_path, "w") as f:
  191. json.dump(model._call_tree, f, indent=2)
  192. # summary-only version for readability - traversing the tree again #TODO optimize?
  193. def strip_values(node):
  194. def clean(val):
  195. if isinstance(val, dict):
  196. val.pop("value", None)
  197. for v in val.values():
  198. clean(v)
  199. elif isinstance(val, list):
  200. for item in val:
  201. clean(item)
  202. clean(node.get("inputs", {}))
  203. clean(node.get("outputs", {}))
  204. for child in node.get("children", []):
  205. strip_values(child)
  206. tree_copy = json.loads(json.dumps(model._call_tree)) # deep copy
  207. strip_values(tree_copy)
  208. with open(summary_path, "w") as f:
  209. json.dump(tree_copy, f, indent=2)
  210. def _attach_debugger_logic(
  211. model,
  212. debug_path: str = ".",
  213. do_prune_layers: bool = True,
  214. use_repr: bool = True,
  215. ):
  216. """
  217. Attaches a debugging wrapper to every module in the model.
  218. This records structured inputs and outputs during the forward pass into a call tree.
  219. Args:
  220. model (`PreTrainedModel`, `nn.Module`): Model to wrap.
  221. debug_path (`str`): Optional directory to dump debug JSON files.
  222. do_prune_layers (`bool`, *optional*, defaults to `True`): Whether to prune intermediate layers.
  223. use_repr (bool, *optional*, defaults to `True`): Whether to save a `repr()`-ized version of the tensors as the
  224. `value` property in the associated FULL_TENSORS.json file, or to store full tensors in separate SafeTensors
  225. files and store the relative path to that file in the `value` property.
  226. """
  227. class_name = model.__class__.__name__
  228. # Prepare data structures on the model object
  229. model._call_tree = {"module_path": class_name, "inputs": None, "outputs": None, "children": []}
  230. model._debugger_model_call_stack = []
  231. model._debugger_module_dump_name = class_name # used for final JSON filename
  232. if debug_path:
  233. try:
  234. os.makedirs(debug_path, exist_ok=True)
  235. except Exception as e:
  236. raise ValueError(f"Unexpected or existing debug_path={debug_path}.") from e
  237. def wrap_forward(module, full_path):
  238. orig_forward = module.forward
  239. @functools.wraps(orig_forward)
  240. def wrapped_forward(*inps, **kws):
  241. if _is_rank_zero():
  242. dict_inputs = {"args": inps, "kwargs": kws}
  243. dict_inputs = {k: dict_inputs[k] for k in dict_inputs if len(dict_inputs[k]) > 0}
  244. node = {
  245. "module_path": full_path,
  246. "inputs": _serialize_io(
  247. dict_inputs,
  248. debug_path=debug_path,
  249. use_repr=use_repr,
  250. path_to_value=f"{full_path}_inputs",
  251. ),
  252. "outputs": None,
  253. "children": [],
  254. }
  255. model._debugger_model_call_stack.append(node)
  256. with torch.no_grad():
  257. out = orig_forward(*inps, **kws)
  258. if _is_rank_zero():
  259. if sum(1 for _ in module.named_children()) > 0:
  260. node["outputs"] = None
  261. else:
  262. node["outputs"] = _serialize_io(
  263. out,
  264. debug_path=debug_path,
  265. use_repr=use_repr,
  266. path_to_value=f"{full_path}_outputs",
  267. )
  268. finished = model._debugger_model_call_stack.pop()
  269. # prune empty vertices here as well (mostly empty children nodes)
  270. if not finished["children"]:
  271. finished.pop("children")
  272. if model._debugger_model_call_stack:
  273. model._debugger_model_call_stack[-1]["children"].append(finished)
  274. return out
  275. module.forward = wrapped_forward
  276. # wrap all submodules
  277. for name, submodule in model.named_modules():
  278. if name == "":
  279. continue
  280. wrap_forward(submodule, f"{class_name}.{name}")
  281. # wrap top-level forward
  282. real_top_forward = model.forward
  283. @functools.wraps(real_top_forward)
  284. def top_wrapped_forward(*inps, **kws):
  285. if _is_rank_zero():
  286. top_node = {
  287. "module_path": f"{class_name} (top-level)",
  288. "inputs": _serialize_io(
  289. {"args": inps, "kwargs": kws},
  290. debug_path=debug_path,
  291. use_repr=use_repr,
  292. path_to_value=f"{class_name}_inputs",
  293. ),
  294. "outputs": None,
  295. "children": [],
  296. }
  297. model._debugger_model_call_stack.append(top_node)
  298. out = real_top_forward(*inps, **kws)
  299. if _is_rank_zero() and model._debugger_model_call_stack:
  300. top_node["outputs"] = _serialize_io(
  301. out,
  302. debug_path=debug_path,
  303. use_repr=use_repr,
  304. path_to_value=f"{class_name}_outputs",
  305. )
  306. finished = model._debugger_model_call_stack.pop()
  307. model._call_tree["inputs"] = finished["inputs"]
  308. model._call_tree["outputs"] = finished["outputs"]
  309. model._call_tree["children"] = finished["children"]
  310. # prune empty stuff for visibility
  311. [model._call_tree.pop(k, None) for k in list(model._call_tree.keys()) if not model._call_tree[k]]
  312. # prune layers that are not 0 or last
  313. if do_prune_layers:
  314. prune_intermediate_layers(model._call_tree)
  315. # Write final JSON trace here
  316. log_model_debug_trace(debug_path=debug_path, model=model)
  317. return out
  318. model.forward = top_wrapped_forward
  319. @requires(backends=("torch",))
  320. @contextmanager
  321. def model_addition_debugger_context(
  322. model,
  323. debug_path: str | None = None,
  324. do_prune_layers: bool = True,
  325. use_repr: bool = True,
  326. ):
  327. """
  328. # Model addition debugger - context manager for model adders
  329. This context manager is a power user tool intended for model adders.
  330. It tracks all forward calls within a model forward and logs a slice of each input and output on a nested JSON file.
  331. If `use_repr=True` (the default), the JSON file will record a `repr()`-ized version of the tensors as a list of
  332. strings. If `use_repr=False`, the full tensors will be stored in separate SafeTensors files and the JSON file will
  333. provide a relative path to that file.
  334. To note, this context manager enforces `torch.no_grad()`.
  335. ## Usage
  336. add the context manager to a model to debug
  337. ```python
  338. import torch
  339. from PIL import Image
  340. from transformers import LlavaProcessor, LlavaForConditionalGeneration, model_addition_debugger_context
  341. torch.random.manual_seed(673)
  342. # load pretrained model and processor
  343. model_id = "llava-hf/llava-1.5-7b-hf"
  344. processor = LlavaProcessor.from_pretrained(model_id)
  345. model = LlavaForConditionalGeneration.from_pretrained(model_id)
  346. # create random image input
  347. random_image = Image.fromarray(torch.randint(0, 256, (224, 224, 3), dtype=torch.uint8).numpy())
  348. # prompt
  349. prompt = "<image>Describe this image."
  350. # process inputs
  351. inputs = processor(text=prompt, images=random_image, return_tensors="pt")
  352. # call forward method (not .generate!)
  353. with model_addition_debugger_context(model, debug_path="Your_debug_path", do_prune_layers=False):
  354. output = model.forward(**inputs)
  355. ```
  356. """
  357. orig_forwards = {m: m.forward for _, m in model.named_modules()}
  358. orig_forwards[model] = model.forward
  359. _attach_debugger_logic(model, debug_path, do_prune_layers, use_repr)
  360. try:
  361. yield model
  362. finally:
  363. for module_instance, forward_method in orig_forwards.items():
  364. module_instance.forward = forward_method