Refactor image editing script for clarity and performance#4
Refactor image editing script for clarity and performance#4kollarsandor wants to merge 1 commit into
Conversation
Refactor argument parsing and improve error handling. Update image encoding and model loading processes for better clarity and performance.
There was a problem hiding this comment.
Code Review
This pull request refactors the image editing script to improve robustness, input validation, and memory management. It introduces specialized argument parsing, path normalization, and detailed verification for image tokens and grid metadata. Additionally, model loading and inference have been optimized with better error handling and resource cleanup. A security concern was identified in the weight-loading utility, where a broad exception handler could potentially allow the execution of unsafe code by bypassing security checks.
| def _torch_load(path): | ||
| try: | ||
| return torch.load(path, map_location="cpu", weights_only=True) | ||
| except TypeError: | ||
| return torch.load(path, map_location="cpu") | ||
| except Exception: | ||
| return torch.load(path, map_location="cpu", weights_only=False) |
There was a problem hiding this comment.
The broad except Exception block that falls back to weights_only=False bypasses the security benefits of weights_only=True. If the first attempt fails due to unsafe content (e.g., a pickle.UnpicklingError when loading untrusted classes), the second attempt will execute it anyway, potentially leading to arbitrary code execution. It is safer to only catch TypeError to handle older PyTorch versions and let other exceptions propagate.
| def _torch_load(path): | |
| try: | |
| return torch.load(path, map_location="cpu", weights_only=True) | |
| except TypeError: | |
| return torch.load(path, map_location="cpu") | |
| except Exception: | |
| return torch.load(path, map_location="cpu", weights_only=False) | |
| def _torch_load(path): | |
| try: | |
| return torch.load(path, map_location="cpu", weights_only=True) | |
| except TypeError: | |
| # Fallback for older PyTorch versions (< 1.13) which do not support weights_only | |
| return torch.load(path, map_location="cpu") |
Refactor argument parsing and improve error handling. Update image encoding and model loading processes for better clarity and performance.