├── .conda └── meta.yaml ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── config.yml │ └── feature_request.yml ├── PULL_REQUEST_TEMPLATE.md ├── collect_env.py ├── dependabot.yml ├── labeler.yml ├── release.yml ├── verify_deps_sync.py ├── verify_labels.py └── workflows │ ├── build.yml │ ├── page-build.yml │ ├── pr-edited.yml │ ├── pr-merged.yml │ ├── push.yaml │ ├── release.yml │ ├── style.yml │ ├── tests.yml │ └── triage.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CITATION.cff ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── README.md ├── demo └── app.py ├── docs ├── Makefile ├── README.md ├── build.sh └── source │ ├── _static │ ├── css │ │ └── custom_theme.css │ └── js │ │ └── custom.js │ ├── changelog.rst │ ├── conf.py │ ├── index.rst │ ├── installing.rst │ ├── methods.rst │ ├── metrics.rst │ ├── notebooks.md │ ├── notebooks │ ├── latency_benchmark.rst │ └── quicktour.rst │ └── utils.rst ├── notebooks └── README.md ├── pyproject.toml ├── scripts ├── cam_example.py ├── eval_latency.py ├── eval_perf.py ├── requirements.txt └── results.csv ├── setup.py ├── tests ├── conftest.py ├── test_methods_activation.py ├── test_methods_core.py ├── test_methods_gradient.py ├── test_methods_utils.py ├── test_metrics.py └── test_utils.py └── torchcam ├── __init__.py ├── methods ├── __init__.py ├── _utils.py ├── activation.py ├── core.py └── gradient.py ├── metrics.py └── utils.py /.conda/meta.yaml: -------------------------------------------------------------------------------- 1 | {% set pyproject = load_file_data('../pyproject.toml', from_recipe_dir=True) %} 2 | {% set project = pyproject.get('project') %} 3 | {% set urls = pyproject.get('project', {}).get('urls') %} 4 | {% set version = environ.get('BUILD_VERSION', '0.4.1.dev0') %} 5 | package: 6 | name: {{ project.get('name') }} 7 | version: {{ version }} 8 | 9 | source: 10 | fn: {{ project.get('name') }}-{{ version }}.tar.gz 11 | url: ../dist/{{ project.get('name') }}-{{ version }}.tar.gz 12 | 13 | build: 14 | noarch: python 15 | script: python setup.py install --single-version-externally-managed --record=record.txt 16 | 17 | requirements: 18 | host: 19 | - python>=3.8, <4.0 20 | - setuptools 21 | 22 | run: 23 | - pytorch >=2.0.0, <3.0.0 24 | - numpy >=1.17.2, <2.0.0 25 | - pillow >=8.4.0, !=9.2.0 26 | - matplotlib >=3.7.0, <4.0.0 27 | 28 | test: 29 | # Python imports 30 | imports: 31 | - torchcam 32 | - torchcam.methods 33 | - torchcam.metrics 34 | - torchcam.utils 35 | requires: 36 | - python 37 | 38 | about: 39 | home: {{ urls.get('repository') }} 40 | license: Apache 2.0 41 | license_file: {{ project.get('license', {}).get('file') }} 42 | summary: {{ project.get('description') }} 43 | # description: | 44 | # {{ data['long_description'] | replace("\n", "\n ") | replace("#", '\#')}} 45 | doc_url: {{ urls.get('documentation') }} 46 | dev_url: {{ urls.get('repository') }} 47 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: frgfm 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with an OpenCollective account 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: 🐛 Bug report 2 | description: Create a report to help us improve the library 3 | labels: 'type: bug' 4 | assignees: frgfm 5 | 6 | body: 7 | - type: markdown 8 | attributes: 9 | value: > 10 | #### Before reporting a bug, please check that the issue hasn't already been addressed in [the existing and past issues](https://github.com/frgfm/torch-cam/issues?q=is%3Aissue). 11 | - type: textarea 12 | attributes: 13 | label: Bug description 14 | description: | 15 | A clear and concise description of what the bug is. 16 | 17 | Please explain the result you observed and the behavior you were expecting. 18 | placeholder: | 19 | A clear and concise description of what the bug is. 20 | validations: 21 | required: true 22 | 23 | - type: textarea 24 | attributes: 25 | label: Code snippet to reproduce the bug 26 | description: | 27 | Sample code to reproduce the problem. 28 | 29 | Please wrap your code snippet with ```` ```triple quotes blocks``` ```` for readability. 30 | placeholder: | 31 | ```python 32 | Sample code to reproduce the problem 33 | ``` 34 | validations: 35 | required: true 36 | - type: textarea 37 | attributes: 38 | label: Error traceback 39 | description: | 40 | The error message you received running the code snippet, with the full traceback. 41 | 42 | Please wrap your error message with ```` ```triple quotes blocks``` ```` for readability. 43 | placeholder: | 44 | ``` 45 | The error message you got, with the full traceback. 46 | ``` 47 | validations: 48 | required: true 49 | - type: textarea 50 | attributes: 51 | label: Environment 52 | description: | 53 | Please run the following command and paste the output below. 54 | ```sh 55 | wget https://raw.githubusercontent.com/frgfm/torch-cam/main/.github/collect_env.py 56 | # For security purposes, please check the contents of collect_env.py before running it. 57 | python collect_env.py 58 | ``` 59 | validations: 60 | required: true 61 | - type: markdown 62 | attributes: 63 | value: > 64 | Thanks for helping us improve the library! 65 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | contact_links: 3 | - name: Usage questions 4 | url: https://github.com/frgfm/torch-cam/discussions 5 | about: Ask questions and discuss with other TorchCAM community members 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: 🚀 Feature request 2 | description: Submit a proposal/request for a new feature for TorchCAM 3 | labels: 'type: new feature' 4 | assignees: frgfm 5 | 6 | body: 7 | - type: textarea 8 | attributes: 9 | label: 🚀 Feature 10 | description: > 11 | A clear and concise description of the feature proposal 12 | validations: 13 | required: true 14 | - type: textarea 15 | attributes: 16 | label: Motivation & pitch 17 | description: > 18 | Please outline the motivation for the proposal. Is your feature request related to a specific problem? e.g., *"I'm working on X and would like Y to be possible"*. If this is related to another GitHub issue, please link here too. 19 | validations: 20 | required: true 21 | - type: textarea 22 | attributes: 23 | label: Alternatives 24 | description: > 25 | A description of any alternative solutions or features you've considered, if any. 26 | - type: textarea 27 | attributes: 28 | label: Additional context 29 | description: > 30 | Add any other context or screenshots about the feature request. 31 | - type: markdown 32 | attributes: 33 | value: > 34 | Thanks for contributing 🎉 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # What does this PR do? 2 | 3 | 9 | 10 | 11 | 12 | Closes # (issue) 13 | 14 | 15 | ## Before submitting 16 | - [ ] Was this discussed/approved in a Github [issue](https://github.com/frgfm/torch-cam/issues?q=is%3Aissue) or a [discussion](https://github.com/frgfm/torch-cam/discussions)? Please add a link to it if that's the case. 17 | - [ ] You have read the [contribution guidelines](https://github.com/frgfm/torch-cam/blob/main/CONTRIBUTING.md#submitting-a-pull-request) and followed them in this PR. 18 | - [ ] Did you make sure to update the documentation with your changes? Here are the 19 | [documentation guidelines](https://github.com/frgm/torch-cam/tree/main/docs). 20 | - [ ] Did you write any new necessary tests? 21 | -------------------------------------------------------------------------------- /.github/collect_env.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | """ 7 | Based on https://github.com/pytorch/pytorch/blob/master/torch/utils/collect_env.py 8 | This script outputs relevant system environment info 9 | Run it with `python collect_env.py`. 10 | """ 11 | 12 | from __future__ import absolute_import, division, print_function, unicode_literals 13 | 14 | import locale 15 | import os 16 | import re 17 | import subprocess # noqa S404 18 | import sys 19 | from pathlib import Path 20 | from typing import NamedTuple 21 | 22 | try: 23 | import torchcam 24 | 25 | TORCHCAM_AVAILABLE = True 26 | except (ImportError, NameError, AttributeError, OSError): 27 | TORCHCAM_AVAILABLE = False 28 | 29 | try: 30 | import torch 31 | 32 | TORCH_AVAILABLE = True 33 | except (ImportError, NameError, AttributeError, OSError): 34 | TORCH_AVAILABLE = False 35 | 36 | PY3 = sys.version_info >= (3, 0) 37 | 38 | 39 | # System Environment Information 40 | class SystemEnv(NamedTuple): 41 | torchcam_version: str 42 | torch_version: str 43 | os: str 44 | python_version: str 45 | is_cuda_available: bool 46 | cuda_runtime_version: str 47 | nvidia_driver_version: str 48 | nvidia_gpu_models: str 49 | cudnn_version: str 50 | 51 | 52 | def run(command): 53 | """Returns (return-code, stdout, stderr)""" 54 | p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 55 | output, err = p.communicate() 56 | rc = p.returncode 57 | if PY3: 58 | enc = locale.getpreferredencoding() 59 | output = output.decode(enc) 60 | err = err.decode(enc) 61 | return rc, output.strip(), err.strip() 62 | 63 | 64 | def run_and_read_all(run_lambda, command): 65 | """Runs command using run_lambda; reads and returns entire output if rc is 0""" 66 | rc, out, _ = run_lambda(command) 67 | if rc != 0: 68 | return None 69 | return out 70 | 71 | 72 | def run_and_parse_first_match(run_lambda, command, regex): 73 | """Runs command using run_lambda, returns the first regex match if it exists""" 74 | rc, out, _ = run_lambda(command) 75 | if rc != 0: 76 | return None 77 | match = re.search(regex, out) 78 | if match is None: 79 | return None 80 | return match.group(1) 81 | 82 | 83 | def get_nvidia_driver_version(run_lambda): 84 | if get_platform() == "darwin": 85 | cmd = "kextstat | grep -i cuda" 86 | return run_and_parse_first_match(run_lambda, cmd, r"com[.]nvidia[.]CUDA [(](.*?)[)]") 87 | smi = get_nvidia_smi() 88 | return run_and_parse_first_match(run_lambda, smi, r"Driver Version: (.*?) ") 89 | 90 | 91 | def get_gpu_info(run_lambda): 92 | if get_platform() == "darwin": 93 | if TORCH_AVAILABLE and torch.cuda.is_available(): 94 | return torch.cuda.get_device_name(None) 95 | return None 96 | smi = get_nvidia_smi() 97 | uuid_regex = re.compile(r" \(UUID: .+?\)") 98 | rc, out, _ = run_lambda(smi + " -L") 99 | if rc != 0: 100 | return None 101 | # Anonymize GPUs by removing their UUID 102 | return re.sub(uuid_regex, "", out) 103 | 104 | 105 | def get_running_cuda_version(run_lambda): 106 | return run_and_parse_first_match(run_lambda, "nvcc --version", r"release .+ V(.*)") 107 | 108 | 109 | def get_cudnn_version(run_lambda): 110 | """This will return a list of libcudnn.so; it's hard to tell which one is being used""" 111 | if get_platform() == "win32": 112 | cudnn_cmd = 'where /R "%CUDA_PATH%\\bin" cudnn*.dll' 113 | elif get_platform() == "darwin": 114 | # CUDA libraries and drivers can be found in /usr/local/cuda/. See 115 | # https://docs.nvidia.com/cuda/cuda-installation-guide-mac-os-x/index.html#install 116 | # https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#installmac 117 | # Use CUDNN_LIBRARY when cudnn library is installed elsewhere. 118 | cudnn_cmd = "ls /usr/local/cuda/lib/libcudnn*" 119 | else: 120 | cudnn_cmd = 'ldconfig -p | grep libcudnn | rev | cut -d" " -f1 | rev' 121 | rc, out, _ = run_lambda(cudnn_cmd) 122 | # find will return 1 if there are permission errors or if not found 123 | if len(out) == 0 or rc not in (1, 0): 124 | lib = os.environ.get("CUDNN_LIBRARY") 125 | if lib is not None and Path(lib).is_file(): 126 | return os.path.realpath(lib) 127 | return None 128 | files = set() 129 | for fn in out.split("\n"): 130 | fn = os.path.realpath(fn) # eliminate symbolic links 131 | if Path(fn).is_file(): 132 | files.add(fn) 133 | if not files: 134 | return None 135 | # Alphabetize the result because the order is non-deterministic otherwise 136 | files = sorted(files) 137 | if len(files) == 1: 138 | return files[0] 139 | result = "\n".join(files) 140 | return "Probably one of the following:\n{}".format(result) 141 | 142 | 143 | def get_nvidia_smi(): 144 | # Note: nvidia-smi is currently available only on Windows and Linux 145 | smi = "nvidia-smi" 146 | if get_platform() == "win32": 147 | system_root = os.environ.get("SYSTEMROOT", "C:\\Windows") 148 | program_files_root = os.environ.get("PROGRAMFILES", "C:\\Program Files") 149 | legacy_path = Path(program_files_root) / "NVIDIA Corporation" / "NVSMI" / smi 150 | new_path = Path(system_root) / "System32" / smi 151 | smis = [new_path, legacy_path] 152 | for candidate_smi in smis: 153 | if Path(candidate_smi).exists(): 154 | smi = '"{}"'.format(candidate_smi) 155 | break 156 | return smi 157 | 158 | 159 | def get_platform(): 160 | if sys.platform.startswith("linux"): 161 | return "linux" 162 | if sys.platform.startswith("win32"): 163 | return "win32" 164 | if sys.platform.startswith("cygwin"): 165 | return "cygwin" 166 | if sys.platform.startswith("darwin"): 167 | return "darwin" 168 | return sys.platform 169 | 170 | 171 | def get_mac_version(run_lambda): 172 | return run_and_parse_first_match(run_lambda, "sw_vers -productVersion", r"(.*)") 173 | 174 | 175 | def get_windows_version(run_lambda): 176 | return run_and_read_all(run_lambda, "wmic os get Caption | findstr /v Caption") 177 | 178 | 179 | def get_lsb_version(run_lambda): 180 | return run_and_parse_first_match(run_lambda, "lsb_release -a", r"Description:\t(.*)") 181 | 182 | 183 | def check_release_file(run_lambda): 184 | return run_and_parse_first_match(run_lambda, "cat /etc/*-release", r'PRETTY_NAME="(.*)"') 185 | 186 | 187 | def get_os(run_lambda): 188 | platform = get_platform() 189 | 190 | if platform in ("win32", "cygwin"): 191 | return get_windows_version(run_lambda) 192 | 193 | if platform == "darwin": 194 | version = get_mac_version(run_lambda) 195 | if version is None: 196 | return None 197 | return "Mac OSX {}".format(version) 198 | 199 | if platform == "linux": 200 | # Ubuntu/Debian based 201 | desc = get_lsb_version(run_lambda) 202 | if desc is not None: 203 | return desc 204 | 205 | # Try reading /etc/*-release 206 | desc = check_release_file(run_lambda) 207 | if desc is not None: 208 | return desc 209 | 210 | return platform 211 | 212 | # Unknown platform 213 | return platform 214 | 215 | 216 | def get_env_info(): 217 | run_lambda = run 218 | 219 | torchcam_str = torchcam.__version__ if TORCHCAM_AVAILABLE else "N/A" 220 | 221 | if TORCH_AVAILABLE: 222 | torch_str = torch.__version__ 223 | cuda_available_str = torch.cuda.is_available() 224 | else: 225 | torch_str = cuda_available_str = "N/A" 226 | 227 | return SystemEnv( 228 | torchcam_version=torchcam_str, 229 | torch_version=torch_str, 230 | python_version=".".join(map(str, sys.version_info[:3])), 231 | is_cuda_available=cuda_available_str, 232 | cuda_runtime_version=get_running_cuda_version(run_lambda), 233 | nvidia_gpu_models=get_gpu_info(run_lambda), 234 | nvidia_driver_version=get_nvidia_driver_version(run_lambda), 235 | cudnn_version=get_cudnn_version(run_lambda), 236 | os=get_os(run_lambda), 237 | ) 238 | 239 | 240 | env_info_fmt = """ 241 | TorchCAM version: {torchcam_version} 242 | PyTorch version: {torch_version} 243 | 244 | OS: {os} 245 | 246 | Python version: {python_version} 247 | Is CUDA available: {is_cuda_available} 248 | CUDA runtime version: {cuda_runtime_version} 249 | GPU models and configuration: {nvidia_gpu_models} 250 | Nvidia driver version: {nvidia_driver_version} 251 | cuDNN version: {cudnn_version} 252 | """.strip() 253 | 254 | 255 | def pretty_str(envinfo): 256 | def replace_nones(dct, replacement="Could not collect"): 257 | for key in dct: 258 | if dct[key] is not None: 259 | continue 260 | dct[key] = replacement 261 | return dct 262 | 263 | def replace_bools(dct, true="Yes", false="No"): 264 | for key in dct: 265 | if dct[key] is True: 266 | dct[key] = true 267 | elif dct[key] is False: 268 | dct[key] = false 269 | return dct 270 | 271 | def maybe_start_on_next_line(string): 272 | # If `string` is multiline, prepend a \n to it. 273 | if string is not None and len(string.split("\n")) > 1: 274 | return "\n{}\n".format(string) 275 | return string 276 | 277 | mutable_dict = envinfo._asdict() 278 | 279 | # If nvidia_gpu_models is multiline, start on the next line 280 | mutable_dict["nvidia_gpu_models"] = maybe_start_on_next_line(envinfo.nvidia_gpu_models) 281 | 282 | # If the machine doesn't have CUDA, report some fields as 'No CUDA' 283 | dynamic_cuda_fields = [ 284 | "cuda_runtime_version", 285 | "nvidia_gpu_models", 286 | "nvidia_driver_version", 287 | ] 288 | all_cuda_fields = [*dynamic_cuda_fields, "cudnn_version"] 289 | all_dynamic_cuda_fields_missing = all(mutable_dict[field] is None for field in dynamic_cuda_fields) 290 | if TORCH_AVAILABLE and not torch.cuda.is_available() and all_dynamic_cuda_fields_missing: 291 | for field in all_cuda_fields: 292 | mutable_dict[field] = "No CUDA" 293 | 294 | # Replace True with Yes, False with No 295 | mutable_dict = replace_bools(mutable_dict) 296 | 297 | # Replace all None objects with 'Could not collect' 298 | mutable_dict = replace_nones(mutable_dict) 299 | 300 | return env_info_fmt.format(**mutable_dict) 301 | 302 | 303 | def get_pretty_env_info(): 304 | """Collects environment information for debugging purposes 305 | 306 | Returns: 307 | str: environment information 308 | """ 309 | return pretty_str(get_env_info()) 310 | 311 | 312 | def main(): 313 | print("Collecting environment information...") 314 | output = get_pretty_env_info() 315 | print(output) 316 | 317 | 318 | if __name__ == "__main__": 319 | main() 320 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | - package-ecosystem: "pip" 13 | directory: "/" 14 | schedule: 15 | interval: "daily" 16 | allow: 17 | - dependency-name: "ruff" 18 | - dependency-name: "mypy" 19 | - dependency-name: "pre-commit" 20 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | 'module: methods': 2 | - changed-files: 3 | - any-glob-to-any-file: torchcam/methods/* 4 | 5 | 'module: metrics': 6 | - changed-files: 7 | - any-glob-to-any-file: torchcam/metrics.py 8 | 9 | 'module: utils': 10 | - changed-files: 11 | - any-glob-to-any-file: torchcam/utils.py 12 | 13 | 'ext: demo': 14 | - changed-files: 15 | - any-glob-to-any-file: demo/* 16 | 17 | 'ext: docs': 18 | - changed-files: 19 | - any-glob-to-any-file: docs/* 20 | 21 | 'ext: scripts': 22 | - changed-files: 23 | - any-glob-to-any-file: scripts/* 24 | 25 | 'ext: tests': 26 | - changed-files: 27 | - any-glob-to-any-file: tests/* 28 | 29 | 'topic: ci': 30 | - changed-files: 31 | - any-glob-to-any-file: .github/* 32 | 33 | 'topic: docs': 34 | - changed-files: 35 | - any-glob-to-any-file: 36 | - notebooks/* 37 | - README.md 38 | - CONTRIBUTING.md 39 | - CODFE_OF_CONDUCT.md 40 | - CITATION.cff 41 | - LICENSE 42 | 43 | 'topic: build': 44 | - changed-files: 45 | - any-glob-to-any-file: 46 | - setup.py 47 | - pyproject.toml 48 | 49 | 'topic: style': 50 | - changed-files: 51 | - any-glob-to-any-file: .pre-commit-config.yaml 52 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | exclude: 3 | labels: 4 | - ignore-for-release 5 | categories: 6 | - title: Breaking Changes 🛠 7 | labels: 8 | - "type: breaking change" 9 | # NEW FEATURES 10 | - title: New Features 🚀 11 | labels: 12 | - "type: new feature" 13 | # BUG FIXES 14 | - title: Bug Fixes 🐛 15 | labels: 16 | - "type: bug" 17 | # IMPROVEMENTS 18 | - title: Improvements 19 | labels: 20 | - "type: enhancement" 21 | # MISC 22 | - title: Miscellaneous 23 | labels: 24 | - "type: misc" 25 | -------------------------------------------------------------------------------- /.github/verify_deps_sync.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2024-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | from pathlib import Path 7 | 8 | import tomllib 9 | import yaml 10 | 11 | PRECOMMIT_PATH = ".pre-commit-config.yaml" 12 | PYPROJECT_PATH = "pyproject.toml" 13 | 14 | 15 | def main(): 16 | # Retrieve & parse all deps files 17 | deps_dict = {} 18 | # UV: Dockerfile, precommit, .github 19 | # Parse precommit 20 | with Path(PRECOMMIT_PATH).open("r") as f: 21 | precommit = yaml.safe_load(f) 22 | 23 | for repo in precommit["repos"]: 24 | if repo["repo"] == "https://github.com/astral-sh/uv-pre-commit": 25 | if "uv" not in deps_dict: 26 | deps_dict["uv"] = [] 27 | deps_dict["uv"].append({"file": PRECOMMIT_PATH, "version": repo["rev"].lstrip("v")}) 28 | elif repo["repo"] == "https://github.com/charliermarsh/ruff-pre-commit": 29 | if "ruff" not in deps_dict: 30 | deps_dict["ruff"] = [] 31 | deps_dict["ruff"].append({"file": PRECOMMIT_PATH, "version": repo["rev"].lstrip("v")}) 32 | 33 | # Parse pyproject.toml 34 | with Path(PYPROJECT_PATH).open("rb") as f: 35 | pyproject = tomllib.load(f) 36 | 37 | dev_deps = pyproject["project"]["optional-dependencies"]["quality"] 38 | for dep in dev_deps: 39 | if dep.startswith("ruff=="): 40 | if "ruff" not in deps_dict: 41 | deps_dict["ruff"] = [] 42 | deps_dict["ruff"].append({"file": PYPROJECT_PATH, "version": dep.split("==")[1]}) 43 | elif dep.startswith("mypy=="): 44 | if "mypy" not in deps_dict: 45 | deps_dict["mypy"] = [] 46 | deps_dict["mypy"].append({"file": PYPROJECT_PATH, "version": dep.split("==")[1]}) 47 | 48 | # Parse github/workflows/... 49 | for workflow_file in Path(".github/workflows").glob("*.yml"): 50 | with workflow_file.open("r") as f: 51 | workflow = yaml.safe_load(f) 52 | if "env" in workflow and "UV_VERSION" in workflow["env"]: 53 | if "uv" not in deps_dict: 54 | deps_dict["uv"] = [] 55 | deps_dict["uv"].append({ 56 | "file": str(workflow_file), 57 | "version": workflow["env"]["UV_VERSION"].lstrip("v"), 58 | }) 59 | 60 | # Assert all deps are in sync 61 | troubles = [] 62 | for dep, versions in deps_dict.items(): 63 | versions_ = {v["version"] for v in versions} 64 | if len(versions_) != 1: 65 | inv_dict = {v: set() for v in versions_} 66 | for version in versions: 67 | inv_dict[version["version"]].add(version["file"]) 68 | troubles.extend([ 69 | f"{dep}:", 70 | "\n".join(f"- '{v}': {', '.join(files)}" for v, files in inv_dict.items()), 71 | ]) 72 | 73 | if len(troubles) > 0: 74 | raise AssertionError("Some dependencies are out of sync:\n\n" + "\n".join(troubles)) 75 | 76 | 77 | if __name__ == "__main__": 78 | main() 79 | -------------------------------------------------------------------------------- /.github/verify_labels.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | """ 7 | Borrowed & adapted from https://github.com/pytorch/vision/blob/main/.github/process_commit.py 8 | This script finds the merger responsible for labeling a PR by a commit SHA. It is used by the workflow in 9 | '.github/workflows/pr-labels.yml'. If there exists no PR associated with the commit or the PR is properly labeled, 10 | this script is a no-op. 11 | Note: we ping the merger only, not the reviewers, as the reviewers can sometimes be external to torchvision 12 | with no labeling responsibility, so we don't want to bother them. 13 | """ 14 | 15 | from typing import Any, Set, Tuple 16 | 17 | import requests 18 | 19 | # For a PR to be properly labeled it should have one primary label and one secondary label 20 | 21 | # Should specify the type of change 22 | PRIMARY_LABELS = { 23 | "type: feat", 24 | "type: fix", 25 | "type: improvement", 26 | "type: misc", 27 | } 28 | 29 | # Should specify what has been modified 30 | SECONDARY_LABELS = { 31 | "topic: docs", 32 | "topic: build", 33 | "topic: ci", 34 | "topic: style", 35 | "ext: demo", 36 | "ext: docs", 37 | "ext: scripts", 38 | "ext: tests", 39 | "module: methods", 40 | "module: metrics", 41 | "module: utils", 42 | } 43 | 44 | GH_ORG = "frgfm" 45 | GH_REPO = "torch-cam" 46 | 47 | 48 | def query_repo(cmd: str, *, accept) -> Any: 49 | response = requests.get( 50 | f"https://api.github.com/repos/{GH_ORG}/{GH_REPO}/{cmd}", 51 | headers={"Accept": accept}, 52 | timeout=5, 53 | ) 54 | return response.json() 55 | 56 | 57 | def get_pr_merger_and_labels(pr_number: int) -> Tuple[str, Set[str]]: 58 | # See https://docs.github.com/en/rest/reference/pulls#get-a-pull-request 59 | data = query_repo(f"pulls/{pr_number}", accept="application/vnd.github.v3+json") 60 | merger = data.get("merged_by", {}).get("login") 61 | labels = {label["name"] for label in data["labels"]} 62 | return merger, labels 63 | 64 | 65 | def main(args): 66 | merger, labels = get_pr_merger_and_labels(args.pr) 67 | is_properly_labeled = bool(PRIMARY_LABELS.intersection(labels) and SECONDARY_LABELS.intersection(labels)) 68 | if isinstance(merger, str) and not is_properly_labeled: 69 | print(f"@{merger}") 70 | 71 | 72 | def parse_args(): 73 | import argparse 74 | 75 | parser = argparse.ArgumentParser( 76 | description="PR label checker", 77 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 78 | ) 79 | 80 | parser.add_argument("pr", type=int, help="PR number") 81 | return parser.parse_args() 82 | 83 | 84 | if __name__ == "__main__": 85 | args = parse_args() 86 | main(args) 87 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: main 6 | pull_request: 7 | branches: main 8 | 9 | env: 10 | PYTHON_VERSION: "3.11" 11 | UV_VERSION: "0.5.13" 12 | 13 | jobs: 14 | package: 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | os: [ubuntu-latest, macos-latest, windows-latest] 20 | python: [3.9, '3.10', 3.11, 3.12] 21 | exclude: 22 | - os: macos-latest 23 | python: 3.9 24 | - os: macos-latest 25 | python: '3.10' 26 | steps: 27 | - uses: actions/checkout@v4 28 | - uses: actions/setup-python@v5 29 | with: 30 | python-version: ${{ matrix.python }} 31 | architecture: x64 32 | - uses: astral-sh/setup-uv@v6 33 | with: 34 | version: ${{ env.UV_VERSION }} 35 | - name: Install package 36 | run: uv pip install --system --upgrade -e . 37 | - name: Import package 38 | run: python -c "import torchcam; print(torchcam.__version__)" 39 | 40 | pypi: 41 | runs-on: ubuntu-latest 42 | steps: 43 | - uses: actions/checkout@v4 44 | - uses: actions/setup-python@v5 45 | with: 46 | python-version: ${{ env.PYTHON_VERSION }} 47 | architecture: x64 48 | - uses: astral-sh/setup-uv@v6 49 | with: 50 | version: ${{ env.UV_VERSION }} 51 | - name: Install dependencies 52 | run: uv pip install --system --upgrade setuptools wheel twine 53 | - run: | 54 | python setup.py sdist bdist_wheel 55 | twine check dist/* 56 | 57 | conda: 58 | runs-on: ubuntu-latest 59 | steps: 60 | - uses: actions/checkout@v4 61 | - uses: conda-incubator/setup-miniconda@v3 62 | with: 63 | auto-update-conda: true 64 | python-version: ${{ env.PYTHON_VERSION }} 65 | - name: Install dependencies 66 | shell: bash -el {0} 67 | run: conda install -y conda-build conda-verify 68 | - name: Build conda 69 | shell: bash -el {0} 70 | run: | 71 | python setup.py sdist 72 | mkdir conda-dist 73 | conda env list 74 | conda build .conda/ -c pytorch --output-folder conda-dist 75 | ls -l conda-dist/noarch/*tar.bz2 76 | 77 | demo: 78 | runs-on: ubuntu-latest 79 | steps: 80 | - uses: actions/checkout@v4 81 | - uses: actions/setup-python@v5 82 | with: 83 | python-version: ${{ env.PYTHON_VERSION }} 84 | architecture: x64 85 | - uses: astral-sh/setup-uv@v6 86 | with: 87 | version: ${{ env.UV_VERSION }} 88 | - name: Install dependencies 89 | run: uv pip install --system --upgrade -e ".[demo]" 90 | - name: Run demo app 91 | run: | 92 | screen -dm streamlit run demo/app.py --server.port 8080 93 | sleep 10 && nc -vz localhost 8080 94 | 95 | docs: 96 | runs-on: ubuntu-latest 97 | steps: 98 | - uses: actions/checkout@v4 99 | - uses: actions/setup-python@v5 100 | with: 101 | python-version: ${{ env.PYTHON_VERSION }} 102 | architecture: x64 103 | - uses: astral-sh/setup-uv@v6 104 | with: 105 | version: ${{ env.UV_VERSION }} 106 | - name: Build documentation 107 | run: | 108 | make install-docs 109 | make full-docs 110 | - name: Documentation sanity check 111 | run: test -e docs/build/index.html || exit 112 | -------------------------------------------------------------------------------- /.github/workflows/page-build.yml: -------------------------------------------------------------------------------- 1 | name: page-build 2 | on: 3 | page_build 4 | 5 | env: 6 | PYTHON_VERSION: "3.11" 7 | UV_VERSION: "0.5.13" 8 | 9 | jobs: 10 | check-gh-pages: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/setup-python@v5 14 | with: 15 | python-version: ${{ env.PYTHON_VERSION }} 16 | architecture: x64 17 | - uses: astral-sh/setup-uv@v6 18 | with: 19 | version: ${{ env.UV_VERSION }} 20 | - name: check status 21 | run: | 22 | import os 23 | status, errormsg = os.getenv('STATUS'), os.getenv('ERROR') 24 | if status != 'built': raise AssertionError(f"There was an error building the page on GitHub pages.\n\nStatus: {status}\n\nError messsage: {errormsg}") 25 | shell: python 26 | env: 27 | STATUS: ${{ github.event.build.status }} 28 | ERROR: ${{ github.event.build.error.message }} 29 | -------------------------------------------------------------------------------- /.github/workflows/pr-edited.yml: -------------------------------------------------------------------------------- 1 | name: pr-edited 2 | 3 | on: 4 | pull_request_target: 5 | types: [opened, reopened, edited, synchronize] 6 | pull_request: 7 | types: [opened, reopened, edited, synchronize] 8 | 9 | jobs: 10 | lint-title: 11 | runs-on: ubuntu-latest 12 | permissions: read-all 13 | steps: 14 | - uses: amannn/action-semantic-pull-request@v5 15 | with: 16 | subjectPattern: ^(?![A-Z]).+$ 17 | subjectPatternError: | 18 | The subject "{subject}" found in the pull request title "{title}" 19 | didn't match the configured pattern. Please ensure that the subject 20 | doesn't start with an uppercase character. 21 | env: 22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | -------------------------------------------------------------------------------- /.github/workflows/pr-merged.yml: -------------------------------------------------------------------------------- 1 | name: pr-merged 2 | 3 | on: 4 | pull_request: 5 | branches: main 6 | types: closed 7 | 8 | env: 9 | PYTHON_VERSION: "3.11" 10 | UV_VERSION: "0.5.13" 11 | 12 | jobs: 13 | is-properly-labeled: 14 | if: github.event.pull_request.merged == true 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: actions/setup-python@v5 19 | with: 20 | python-version: ${{ env.PYTHON_VERSION }} 21 | architecture: x64 22 | - uses: astral-sh/setup-uv@v6 23 | with: 24 | version: ${{ env.UV_VERSION }} 25 | - name: Install requests 26 | run: uv pip install --system requests 27 | - name: Process commit and find merger responsible for labeling 28 | id: commit 29 | run: echo "::set-output name=merger::$(python .github/verify_labels.py ${{ github.event.pull_request.number }})" 30 | - name: Comment PR 31 | uses: actions/github-script@v7 32 | if: ${{ steps.commit.outputs.merger != '' }} 33 | with: 34 | github-token: ${{ secrets.GITHUB_TOKEN }} 35 | script: | 36 | const { issue: { number: issue_number }, repo: { owner, repo } } = context; 37 | github.issues.createComment({ issue_number, owner, repo, body: 'Hey ${{ steps.commit.outputs.merger }} 👋\nYou merged this PR, but it is not correctly labeled. The list of valid labels is available at https://github.com/frgfm/torch-cam/blob/main/.github/verify_labels.py' }); 38 | -------------------------------------------------------------------------------- /.github/workflows/push.yaml: -------------------------------------------------------------------------------- 1 | name: push 2 | on: 3 | push: 4 | branches: main 5 | 6 | env: 7 | PYTHON_VERSION: "3.11" 8 | UV_VERSION: "0.5.13" 9 | 10 | jobs: 11 | docs-deploy: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | with: 16 | persist-credentials: false 17 | - uses: actions/setup-python@v5 18 | with: 19 | python-version: ${{ env.PYTHON_VERSION }} 20 | architecture: x64 21 | - uses: astral-sh/setup-uv@v6 22 | with: 23 | version: ${{ env.UV_VERSION }} 24 | - name: Build documentation 25 | run: | 26 | make install-docs 27 | make full-docs 28 | - name: Documentation sanity check 29 | run: test -e docs/build/index.html || exit 30 | - name: Install SSH Client 🔑 31 | uses: webfactory/ssh-agent@v0.9.1 32 | with: 33 | ssh-private-key: ${{ secrets.SSH_DEPLOY_KEY }} 34 | - name: Deploy to Github Pages 35 | uses: JamesIves/github-pages-deploy-action@v4.7.3 36 | with: 37 | branch: gh-pages 38 | folder: 'docs/build' 39 | commit-message: '[skip ci] Documentation updates' 40 | clean: true 41 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | env: 8 | PYTHON_VERSION: "3.11" 9 | UV_VERSION: "0.5.13" 10 | 11 | jobs: 12 | pypi: 13 | if: "!github.event.release.prerelease" 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-python@v5 18 | with: 19 | python-version: ${{ env.PYTHON_VERSION }} 20 | architecture: x64 21 | - uses: astral-sh/setup-uv@v6 22 | with: 23 | version: ${{ env.UV_VERSION }} 24 | - name: Install dependencies 25 | run: uv pip install --system --upgrade setuptools wheel twine 26 | - name: Build and publish 27 | env: 28 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 29 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 30 | run: | 31 | echo "BUILD_VERSION=${GITHUB_REF#refs/*/}" | cut -c 2- >> $GITHUB_ENV 32 | python setup.py sdist bdist_wheel 33 | twine check dist/* 34 | twine upload dist/* 35 | 36 | pypi-check: 37 | if: "!github.event.release.prerelease" 38 | runs-on: ubuntu-latest 39 | needs: pypi 40 | steps: 41 | - uses: actions/checkout@v4 42 | - uses: actions/setup-python@v5 43 | with: 44 | python-version: ${{ env.PYTHON_VERSION }} 45 | architecture: x64 46 | - uses: astral-sh/setup-uv@v6 47 | with: 48 | version: ${{ env.UV_VERSION }} 49 | - name: Install package 50 | run: | 51 | uv pip install --system torchcam 52 | python -c "import torchcam; print(torchcam.__version__)" 53 | 54 | conda: 55 | if: "!github.event.release.prerelease" 56 | runs-on: ubuntu-latest 57 | steps: 58 | - uses: actions/checkout@v4 59 | - name: Miniconda setup 60 | uses: conda-incubator/setup-miniconda@v3 61 | with: 62 | auto-update-conda: true 63 | python-version: ${{ env.PYTHON_VERSION }} 64 | - name: Install dependencies 65 | shell: bash -el {0} 66 | run: conda install -y conda-build conda-verify anaconda-client 67 | - name: Build and publish 68 | shell: bash -el {0} 69 | env: 70 | ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_TOKEN }} 71 | run: | 72 | echo "BUILD_VERSION=${GITHUB_REF#refs/*/}" | cut -c 2- >> $GITHUB_ENV 73 | python setup.py sdist 74 | mkdir conda-dist 75 | conda build .conda/ -c pytorch --output-folder conda-dist 76 | ls -l conda-dist/noarch/*tar.bz2 77 | anaconda upload conda-dist/noarch/*tar.bz2 78 | 79 | conda-check: 80 | if: "!github.event.release.prerelease" 81 | runs-on: ubuntu-latest 82 | needs: conda 83 | steps: 84 | - uses: conda-incubator/setup-miniconda@v3 85 | with: 86 | auto-update-conda: true 87 | python-version: ${{ env.PYTHON_VERSION }} 88 | - name: Install package 89 | shell: bash -el {0} 90 | run: | 91 | conda install -c frgfm torchcam 92 | python -c "import torchcam; print(torchcam.__version__)" 93 | -------------------------------------------------------------------------------- /.github/workflows/style.yml: -------------------------------------------------------------------------------- 1 | name: style 2 | 3 | on: 4 | push: 5 | branches: main 6 | pull_request: 7 | branches: main 8 | 9 | env: 10 | PYTHON_VERSION: "3.11" 11 | UV_VERSION: "0.5.13" 12 | 13 | jobs: 14 | ruff: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: actions/setup-python@v5 19 | with: 20 | python-version: ${{ env.PYTHON_VERSION }} 21 | architecture: x64 22 | - uses: astral-sh/setup-uv@v6 23 | with: 24 | version: ${{ env.UV_VERSION }} 25 | - name: Run ruff 26 | run: | 27 | make install-quality 28 | ruff --version 29 | make lint-check 30 | 31 | mypy: 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | - uses: actions/setup-python@v5 36 | with: 37 | python-version: ${{ env.PYTHON_VERSION }} 38 | architecture: x64 39 | - uses: astral-sh/setup-uv@v6 40 | with: 41 | version: ${{ env.UV_VERSION }} 42 | - name: Run mypy 43 | run: | 44 | make install-quality 45 | mypy --version 46 | make typing-check 47 | 48 | precommit-hooks: 49 | runs-on: ubuntu-latest 50 | steps: 51 | - uses: actions/checkout@v4 52 | - uses: actions/setup-python@v5 53 | with: 54 | python-version: ${{ env.PYTHON_VERSION }} 55 | architecture: x64 56 | - uses: astral-sh/setup-uv@v6 57 | with: 58 | version: ${{ env.UV_VERSION }} 59 | - name: Run pre-commit hooks 60 | run: | 61 | make install-quality 62 | git checkout -b temp 63 | pre-commit install 64 | pre-commit --version 65 | make precommit 66 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: main 6 | pull_request: 7 | branches: main 8 | 9 | env: 10 | PYTHON_VERSION: "3.11" 11 | UV_VERSION: "0.5.13" 12 | 13 | 14 | jobs: 15 | deps-sync: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: actions/setup-python@v5 20 | with: 21 | python-version: ${{ env.PYTHON_VERSION }} 22 | architecture: x64 23 | - uses: astral-sh/setup-uv@v6 24 | with: 25 | version: ${{ env.UV_VERSION }} 26 | - name: Run dependency sync checker 27 | run: | 28 | uv pip install --system PyYAML 29 | make deps-check 30 | 31 | pytest: 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | with: 36 | persist-credentials: false 37 | - uses: actions/setup-python@v5 38 | with: 39 | python-version: ${{ env.PYTHON_VERSION }} 40 | architecture: x64 41 | - uses: astral-sh/setup-uv@v6 42 | with: 43 | version: ${{ env.UV_VERSION }} 44 | - name: Run tests 45 | run: | 46 | uv pip install --system -e ".[test]" 47 | pytest --cov=torchcam --cov-report xml tests/ 48 | - uses: actions/upload-artifact@v4 49 | with: 50 | name: coverage-reports 51 | path: ./coverage.xml 52 | 53 | codecov-upload: 54 | runs-on: ubuntu-latest 55 | needs: pytest 56 | steps: 57 | - uses: actions/checkout@v4 58 | with: 59 | persist-credentials: false 60 | - uses: actions/download-artifact@v4 61 | - uses: codecov/codecov-action@v5 62 | with: 63 | token: ${{ secrets.CODECOV_TOKEN }} 64 | flags: unittests 65 | directory: ./coverage-reports 66 | fail_ci_if_error: true 67 | 68 | headers: 69 | runs-on: ubuntu-latest 70 | steps: 71 | - uses: actions/checkout@v4 72 | with: 73 | persist-credentials: false 74 | - name: Check the headers 75 | uses: frgfm/validate-python-headers@main 76 | with: 77 | license: 'Apache-2.0' 78 | owner: 'François-Guillaume Fernandez' 79 | starting-year: 2020 80 | folders: 'torchcam,scripts,demo,docs,.github' 81 | ignore-files: 'version.py,__init__.py' 82 | 83 | cam-example: 84 | runs-on: ubuntu-latest 85 | steps: 86 | - uses: actions/checkout@v4 87 | - uses: actions/setup-python@v5 88 | with: 89 | python-version: ${{ env.PYTHON_VERSION }} 90 | architecture: x64 91 | - uses: astral-sh/setup-uv@v6 92 | with: 93 | version: ${{ env.UV_VERSION }} 94 | - name: Install dependencies 95 | run: | 96 | uv pip install --system --upgrade -e . 97 | uv pip install --system -r scripts/requirements.txt 98 | 99 | - name: Run analysis script 100 | run: python scripts/cam_example.py --arch resnet18 --class-idx 232 --noblock --method LayerCAM 101 | 102 | eval-latency: 103 | runs-on: ubuntu-latest 104 | steps: 105 | - uses: actions/checkout@v4 106 | - uses: actions/setup-python@v5 107 | with: 108 | python-version: ${{ env.PYTHON_VERSION }} 109 | architecture: x64 110 | - uses: astral-sh/setup-uv@v6 111 | with: 112 | version: ${{ env.UV_VERSION }} 113 | - name: Install dependencies 114 | run: | 115 | uv pip install --system --upgrade -e . 116 | uv pip install --system -r scripts/requirements.txt 117 | 118 | - name: Run analysis script 119 | run: python scripts/eval_latency.py --arch resnet18 LayerCAM 120 | -------------------------------------------------------------------------------- /.github/workflows/triage.yml: -------------------------------------------------------------------------------- 1 | name: triage 2 | 3 | on: 4 | pull_request: 5 | branches: main 6 | 7 | jobs: 8 | autolabel: 9 | permissions: 10 | contents: read 11 | pull-requests: write 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/labeler@v5 15 | with: 16 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Package version 132 | torchcam/version.py 133 | 134 | # Conda distribution 135 | conda-dist/ 136 | .vscode/ 137 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_language_version: 2 | python: python3.11 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v4.5.0 6 | hooks: 7 | - id: check-added-large-files 8 | - id: check-ast 9 | - id: check-case-conflict 10 | - id: check-json 11 | - id: check-merge-conflict 12 | - id: check-symlinks 13 | - id: check-toml 14 | - id: check-xml 15 | - id: check-yaml 16 | exclude: .conda 17 | - id: debug-statements 18 | language_version: python3 19 | - id: end-of-file-fixer 20 | - id: no-commit-to-branch 21 | args: ['--branch', 'main'] 22 | - id: requirements-txt-fixer 23 | - id: trailing-whitespace 24 | - repo: https://github.com/compilerla/conventional-pre-commit 25 | rev: 'v4.0.0' 26 | hooks: 27 | - id: conventional-pre-commit 28 | stages: [commit-msg] 29 | - repo: https://github.com/charliermarsh/ruff-pre-commit 30 | rev: 'v0.11.9' 31 | hooks: 32 | - id: ruff 33 | args: 34 | - --fix 35 | - id: ruff-format 36 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | type: software 3 | message: "If you use this software in your work, please cite it as below." 4 | authors: 5 | - family-names: "Fernandez" 6 | given-names: "François-Guillaume" 7 | title: "TorchCAM: class activation explorer" 8 | date-released: 2020-05-24 9 | url: "https://github.com/frgfm/torch-cam" 10 | preferred-citation: 11 | type: conference-paper 12 | authors: 13 | - family-names: "Fernandez" 14 | given-names: "François-Guillaume" 15 | title: "TorchCAM: class activation explorer" 16 | year: 2021 17 | publisher: "PyTorch Developer Day 2021" 18 | url: "https://s3.amazonaws.com/assets.pytorch.org/ptdd2021/posters/B5.png" 19 | address: "Online" 20 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | fg-feedback@protonmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to torchcam 2 | 3 | Everything you need to know to contribute efficiently to the project! 4 | 5 | Whatever the way you wish to contribute to the project, please respect the [code of conduct](CODE_OF_CONDUCT.md). 6 | 7 | 8 | 9 | ## Codebase structure 10 | 11 | - [torchcam](https://github.com/frgfm/torch-cam/blob/main/torchcam) - The actual torchcam library 12 | - [tests](https://github.com/frgfm/torch-cam/blob/main/tests) - Python unit tests 13 | - [docs](https://github.com/frgfm/torch-cam/blob/main/docs) - Sphinx documentation building 14 | - [scripts](https://github.com/frgfm/torch-cam/blob/main/scripts) - Example and utilities scripts 15 | - [demo](https://github.com/frgfm/torch-cam//blob/main/demo) - Small demo app to showcase TorchCAM capabilities 16 | 17 | 18 | 19 | ## Continuous Integration 20 | 21 | This project uses the following integrations to ensure proper codebase maintenance: 22 | 23 | - [Github Worklow](https://help.github.com/en/actions/configuring-and-managing-workflows/configuring-a-workflow) - run jobs for package build and coverage 24 | - [Codacy](https://www.codacy.com/) - analyzes commits for code quality 25 | - [Codecov](https://codecov.io/) - reports back coverage results 26 | 27 | As a contributor, you will only have to ensure coverage of your code by adding appropriate unit testing of your code. 28 | 29 | 30 | 31 | ## Feedback 32 | 33 | ### Feature requests & bug report 34 | 35 | Whether you encountered a problem, or you have a feature suggestion, your input has value and can be used by contributors to reference it in their developments. For this purpose, we advise you to use Github [issues](https://github.com/frgfm/torch-cam/issues). 36 | 37 | First, check whether the topic wasn't already covered in an open / closed issue. If not, feel free to open a new one! When doing so, use issue templates whenever possible and provide enough information for other contributors to jump in. 38 | 39 | ### Questions 40 | 41 | If you are wondering how to do something with TorchCAM, or a more general question, you should consider checking out Github [discussions](https://github.com/frgfm/torch-cam/discussions). See it as a Q&A forum, or the TorchCAM-specific StackOverflow! 42 | 43 | 44 | 45 | ## Submitting a Pull Request 46 | 47 | ### Preparing your local branch 48 | 49 | 1 - Fork this [repository](https://github.com/frgfm/torch-cam) by clicking on the "Fork" button at the top right of the page. This will create a copy of the project under your GitHub account (cf. [Fork a repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo)). 50 | 51 | 2 - [Clone your fork](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) to your local disk and set the upstream to this repo 52 | ```shell 53 | git clone git@github.com:/torch-cam.git 54 | cd torch-cam 55 | git remote add upstream https://github.com/frgfm/torch-cam.git 56 | ``` 57 | 58 | 3 - You should not work on the `main` branch, so let's create a new one 59 | ```shell 60 | git checkout -b a-short-description 61 | ``` 62 | 63 | 4 - You only have to set your development environment now. First uninstall any existing installation of the library with `pip uninstall torchcam`, then: 64 | ```shell 65 | pip install -e ".[dev]" 66 | pre-commit install 67 | ``` 68 | 69 | ### Developing your feature 70 | 71 | #### Commits 72 | 73 | - **Code**: ensure to provide docstrings to your Python code. In doing so, please follow [Google-style](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html) so it can ease the process of documentation later. 74 | - **Commit message**: please follow [Udacity guide](http://udacity.github.io/git-styleguide/) 75 | 76 | #### Unit tests 77 | 78 | In order to run the same unit tests as the CI workflows, you can run unittests locally: 79 | 80 | ```shell 81 | make test 82 | ``` 83 | 84 | #### Code quality 85 | 86 | The CI will also run some sanity checks (header format, dependency consistency, etc.), which you can run as follows: 87 | 88 | ```shell 89 | make quality 90 | ``` 91 | 92 | This will read `pyproject.toml` and run: 93 | - lint checking, formatting ([ruff](https://docs.astral.sh/ruff/)) 94 | - type annotation checking ([mypy](https://github.com/python/mypy)) 95 | 96 | You can apply automatic fix to most of those by running: 97 | 98 | ```shell 99 | make style 100 | ``` 101 | 102 | ### Submit your modifications 103 | 104 | Push your last modifications to your remote branch 105 | ```shell 106 | git push -u origin a-short-description 107 | ``` 108 | 109 | Then [open a Pull Request](https://docs.github.com/en/github/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) from your fork's branch. Follow the instructions of the Pull Request template and then click on "Create a pull request". 110 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PYPROJECT_FILE = ./pyproject.toml 2 | DEMO_FILE = ./demo/app.py 3 | TESTS_DIR = ./tests 4 | DOCS_DIR = ./docs 5 | 6 | ######################################################## 7 | # Code checks 8 | ######################################################## 9 | 10 | install-quality: ${PYPROJECT_FILE} 11 | uv pip install --system -e ".[quality]" 12 | pre-commit install 13 | 14 | lint-check: ${PYPROJECT_FILE} 15 | ruff format --check . --config ${PYPROJECT_FILE} 16 | ruff check . --config ${PYPROJECT_FILE} 17 | 18 | lint-format: ${PYPROJECT_FILE} 19 | ruff format . --config ${PYPROJECT_FILE} 20 | ruff check --fix . --config ${PYPROJECT_FILE} 21 | 22 | precommit: ${PYTHON_CONFIG_FILE} .pre-commit-config.yaml 23 | pre-commit run --all-files 24 | 25 | typing-check: ${PYPROJECT_FILE} 26 | mypy --config-file ${PYPROJECT_FILE} 27 | 28 | deps-check: .github/verify_deps_sync.py 29 | python .github/verify_deps_sync.py 30 | 31 | # this target runs checks on all files 32 | quality: lint-check typing-check deps-check 33 | 34 | style: lint-format precommit 35 | 36 | ######################################################## 37 | # Build & tests 38 | ######################################################## 39 | 40 | install-test: ${PYPROJECT_FILE} 41 | uv pip install --system -e ".[test]" 42 | 43 | # Run tests for the library 44 | test: ${TESTS_DIR} 45 | pytest --cov=torchcam ${TESTS_DIR} 46 | 47 | install-docs: ${PYPROJECT_FILE} 48 | uv pip install --system -e ".[docs]" 49 | 50 | # Build documentation for current version 51 | single-docs: ${DOCS_DIR} 52 | sphinx-build ${DOCS_DIR}/source ${DOCS_DIR}/_build -a 53 | 54 | # Check that docs can build 55 | full-docs: ${DOCS_DIR} 56 | cd ${DOCS_DIR} && bash build.sh 57 | 58 | install-demo: ${PYPROJECT_FILE} 59 | uv pip install --system -e ".[demo]" 60 | 61 | # Run the Gradio demo 62 | run-demo: ${DEMO_FILE} 63 | streamlit run ${DEMO_FILE} 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | TorchCAM: class activation explorer 3 |

4 | 5 |

6 | 7 | CI Status 8 | 9 | 10 | ruff 11 | 12 | 13 | ruff 14 | 15 | 16 | 17 | Test coverage percentage 18 | 19 |

20 |

21 | 22 | PyPi Version 23 | 24 | 25 | Conda Version 26 | 27 | pyversions 28 | 29 | License 30 | 31 |

32 |

33 | 34 | Huggingface Spaces 35 | 36 | 37 | Open in Colab 38 | 39 |

40 |

41 | 42 | Documentation Status 43 | 44 |

45 | 46 | Simple way to leverage the class-specific activation of convolutional layers in PyTorch. 47 | 48 |

49 | 50 | 51 |

52 |

53 | Source: image from woopets (activation maps created with a pretrained Resnet-18) 54 |

55 | 56 | 57 | ## Quick Tour 58 | 59 | ### Setting your CAM 60 | 61 | TorchCAM leverages [PyTorch hooking mechanisms](https://pytorch.org/tutorials/beginner/former_torchies/nnft_tutorial.html#forward-and-backward-function-hooks) to seamlessly retrieve all required information to produce the class activation without additional efforts from the user. Each CAM object acts as a wrapper around your model. 62 | 63 | You can find the exhaustive list of supported CAM methods in the [documentation](https://frgfm.github.io/torch-cam/methods.html), then use it as follows: 64 | 65 | ```python 66 | # Define your model 67 | from torchvision.models import resnet18 68 | model = resnet18(pretrained=True).eval() 69 | 70 | # Set your CAM extractor 71 | from torchcam.methods import SmoothGradCAMpp 72 | cam_extractor = SmoothGradCAMpp(model) 73 | ``` 74 | 75 | *Please note that by default, the layer at which the CAM is retrieved is set to the last non-reduced convolutional layer. If you wish to investigate a specific layer, use the `target_layer` argument in the constructor.* 76 | 77 | 78 | 79 | ### Retrieving the class activation map 80 | 81 | Once your CAM extractor is set, you only need to use your model to infer on your data as usual. If any additional information is required, the extractor will get it for you automatically. 82 | 83 | ```python 84 | from torchvision.io.image import read_image 85 | from torchvision.transforms.functional import normalize, resize, to_pil_image 86 | from torchvision.models import resnet18 87 | from torchcam.methods import SmoothGradCAMpp 88 | 89 | model = resnet18(pretrained=True).eval() 90 | # Get your input 91 | img = read_image("path/to/your/image.png") 92 | # Preprocess it for your chosen model 93 | input_tensor = normalize(resize(img, (224, 224)) / 255., [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) 94 | 95 | with SmoothGradCAMpp(model) as cam_extractor: 96 | # Preprocess your data and feed it to the model 97 | out = model(input_tensor.unsqueeze(0)) 98 | # Retrieve the CAM by passing the class index and the model output 99 | activation_map = cam_extractor(out.squeeze(0).argmax().item(), out) 100 | ``` 101 | 102 | If you want to visualize your heatmap, you only need to cast the CAM to a numpy ndarray: 103 | 104 | ```python 105 | import matplotlib.pyplot as plt 106 | # Visualize the raw CAM 107 | plt.imshow(activation_map[0].squeeze(0).numpy()); plt.axis('off'); plt.tight_layout(); plt.show() 108 | ``` 109 | 110 | ![raw_heatmap](https://github.com/frgfm/torch-cam/releases/download/v0.1.2/raw_heatmap.png) 111 | 112 | Or if you wish to overlay it on your input image: 113 | 114 | ```python 115 | import matplotlib.pyplot as plt 116 | from torchcam.utils import overlay_mask 117 | 118 | # Resize the CAM and overlay it 119 | result = overlay_mask(to_pil_image(img), to_pil_image(activation_map[0].squeeze(0), mode='F'), alpha=0.5) 120 | # Display it 121 | plt.imshow(result); plt.axis('off'); plt.tight_layout(); plt.show() 122 | ``` 123 | 124 | ![overlayed_heatmap](https://github.com/frgfm/torch-cam/releases/download/v0.1.2/overlayed_heatmap.png) 125 | 126 | ## Setup 127 | 128 | Python 3.9 (or higher) and [uv](https://docs.astral.sh/uv/)/[conda](https://docs.conda.io/en/latest/miniconda.html) are required to install TorchCAM. 129 | 130 | ### Stable release 131 | 132 | You can install the last stable release of the package using [pypi](https://pypi.org/project/torchcam/) as follows: 133 | 134 | ```shell 135 | pip install torchcam 136 | ``` 137 | 138 | or using [conda](https://anaconda.org/frgfm/torchcam): 139 | 140 | ```shell 141 | conda install -c frgfm torchcam 142 | ``` 143 | 144 | ### Developer installation 145 | 146 | Alternatively, if you wish to use the latest features of the project that haven't made their way to a release yet, you can install the package from source: 147 | 148 | ```shell 149 | git clone https://github.com/frgfm/torch-cam.git 150 | pip install -e torch-cam/. 151 | ``` 152 | 153 | 154 | 155 | ## CAM Zoo 156 | 157 | This project is developed and maintained by the repo owner, but the implementation was based on the following research papers: 158 | 159 | - [Learning Deep Features for Discriminative Localization](https://arxiv.org/abs/1512.04150): the original CAM paper 160 | - [Grad-CAM](https://arxiv.org/abs/1610.02391): GradCAM paper, generalizing CAM to models without global average pooling. 161 | - [Grad-CAM++](https://arxiv.org/abs/1710.11063): improvement of GradCAM++ for more accurate pixel-level contribution to the activation. 162 | - [Smooth Grad-CAM++](https://arxiv.org/abs/1908.01224): SmoothGrad mechanism coupled with GradCAM. 163 | - [Score-CAM](https://arxiv.org/abs/1910.01279): score-weighting of class activation for better interpretability. 164 | - [SS-CAM](https://arxiv.org/abs/2006.14255): SmoothGrad mechanism coupled with Score-CAM. 165 | - [IS-CAM](https://arxiv.org/abs/2010.03023): integration-based variant of Score-CAM. 166 | - [XGrad-CAM](https://arxiv.org/abs/2008.02312): improved version of Grad-CAM in terms of sensitivity and conservation. 167 | - [Layer-CAM](http://mftp.mmcheng.net/Papers/21TIP_LayerCAM.pdf): Grad-CAM alternative leveraging pixel-wise contribution of the gradient to the activation. 168 | 169 |

170 | 171 | 172 |

173 |

174 | Source: YouTube video (activation maps created by Layer-CAM with a pretrained ResNet-18) 175 |

176 | 177 | 178 | 179 | ## What else 180 | 181 | ### Documentation 182 | 183 | The full package documentation is available [here](https://frgfm.github.io/torch-cam/) for detailed specifications. 184 | 185 | ### Demo app 186 | 187 | A minimal demo app is provided for you to play with the supported CAM methods! Feel free to check out the live demo on [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/frgfm/torch-cam) 188 | 189 | If you prefer running the demo by yourself, you will need an extra dependency ([Streamlit](https://streamlit.io/)) for the app to run: 190 | 191 | ``` 192 | pip install -e ".[demo]" 193 | ``` 194 | 195 | You can then easily run your app in your default browser by running: 196 | 197 | ``` 198 | streamlit run demo/app.py 199 | ``` 200 | 201 | ![torchcam_demo](https://github.com/frgfm/torch-cam/releases/download/v0.2.0/torchcam_demo.png) 202 | 203 | ### Example script 204 | 205 | An example script is provided for you to benchmark the heatmaps produced by multiple CAM approaches on the same image: 206 | 207 | ```shell 208 | python scripts/cam_example.py --arch resnet18 --class-idx 232 --rows 2 209 | ``` 210 | 211 | ![gradcam_sample](https://github.com/frgfm/torch-cam/releases/download/v0.3.1/example.png) 212 | 213 | *All script arguments can be checked using `python scripts/cam_example.py --help`* 214 | 215 | 216 | 217 | ### Latency benchmark 218 | 219 | You crave for beautiful activation maps, but you don't know whether it fits your needs in terms of latency? 220 | 221 | In the table below, you will find a latency benchmark (forward pass not included) for all CAM methods: 222 | 223 | | CAM method | Arch | GPU mean (std) | CPU mean (std) | 224 | | ------------------------------------------------------------ | ------------------ | ------------------ | -------------------- | 225 | | [CAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.CAM) | resnet18 | 0.11ms (0.02ms) | 0.14ms (0.03ms) | 226 | | [GradCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.GradCAM) | resnet18 | 3.71ms (1.11ms) | 40.66ms (1.82ms) | 227 | | [GradCAMpp](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.GradCAMpp) | resnet18 | 5.21ms (1.22ms) | 41.61ms (3.24ms) | 228 | | [SmoothGradCAMpp](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.SmoothGradCAMpp) | resnet18 | 33.67ms (2.51ms) | 239.27ms (7.85ms) | 229 | | [ScoreCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.ScoreCAM) | resnet18 | 304.74ms (11.54ms) | 6796.89ms (415.14ms) | 230 | | [SSCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.SSCAM) | resnet18 | | | 231 | | [ISCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.ISCAM) | resnet18 | | | 232 | | [XGradCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.XGradCAM) | resnet18 | 3.78ms (0.96ms) | 40.63ms (2.03ms) | 233 | | [LayerCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.LayerCAM) | resnet18 | 3.65ms (1.04ms) | 40.91ms (1.79ms) | 234 | | [CAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.CAM) | mobilenet_v3_large | N/A* | N/A* | 235 | | [GradCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.GradCAM) | mobilenet_v3_large | 8.61ms (1.04ms) | 26.64ms (3.46ms) | 236 | | [GradCAMpp](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.GradCAMpp) | mobilenet_v3_large | 8.83ms (1.29ms) | 25.50ms (3.10ms) | 237 | | [SmoothGradCAMpp](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.SmoothGradCAMpp) | mobilenet_v3_large | 77.38ms (3.83ms) | 156.25ms (4.89ms) | 238 | | [ScoreCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.ScoreCAM) | mobilenet_v3_large | 35.19ms (2.11ms) | 679.16ms (55.04ms) | 239 | | [SSCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.SSCAM) | mobilenet_v3_large | | | 240 | | [ISCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.ISCAM) | mobilenet_v3_large | | | 241 | | [XGradCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.XGradCAM) | mobilenet_v3_large | 8.41ms (0.98ms) | 24.21ms (2.94ms) | 242 | | [LayerCAM](https://frgfm.github.io/torch-cam/latest/methods.html#torchcam.methods.LayerCAM) | mobilenet_v3_large | 8.02ms (0.95ms) | 25.14ms (3.17ms) | 243 | 244 | **The base CAM method cannot work with architectures that have multiple fully-connected layers* 245 | 246 | This benchmark was performed over 100 iterations on (224, 224) inputs, on a laptop to better reflect performances that can be expected by common users. The hardware setup includes an [Intel(R) Core(TM) i7-10750H](https://ark.intel.com/content/www/us/en/ark/products/201837/intel-core-i710750h-processor-12m-cache-up-to-5-00-ghz.html) for the CPU, and a [NVIDIA GeForce RTX 2070 with Max-Q Design](https://www.nvidia.com/fr-fr/geforce/graphics-cards/rtx-2070/) for the GPU. 247 | 248 | You can run this latency benchmark for any CAM method on your hardware as follows: 249 | 250 | ```bash 251 | python scripts/eval_latency.py SmoothGradCAMpp 252 | ``` 253 | 254 | *All script arguments can be checked using `python scripts/eval_latency.py --help`* 255 | 256 | ### Example notebooks 257 | 258 | Looking for more illustrations of TorchCAM features? 259 | You might want to check the [Jupyter notebooks](notebooks) designed to give you a broader overview. 260 | 261 | 262 | 263 | ## Citation 264 | 265 | If you wish to cite this project, feel free to use this [BibTeX](http://www.bibtex.org/) reference: 266 | 267 | ```bibtex 268 | @misc{torcham2020, 269 | title={TorchCAM: class activation explorer}, 270 | author={François-Guillaume Fernandez}, 271 | year={2020}, 272 | month={March}, 273 | publisher = {GitHub}, 274 | howpublished = {\url{https://github.com/frgfm/torch-cam}} 275 | } 276 | ``` 277 | 278 | 279 | 280 | ## Contributing 281 | 282 | Feeling like extending the range of possibilities of CAM? Or perhaps submitting a paper implementation? Any sort of contribution is greatly appreciated! 283 | 284 | You can find a short guide in [`CONTRIBUTING`](CONTRIBUTING.md) to help grow this project! 285 | 286 | 287 | 288 | ## License 289 | 290 | Distributed under the Apache 2.0 License. See [`LICENSE`](LICENSE) for more information. 291 | 292 | [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Ffrgfm%2Ftorch-cam.svg?type=large&issueType=license)](https://app.fossa.com/projects/git%2Bgithub.com%2Ffrgfm%2Ftorch-cam?ref=badge_large&issueType=license) 293 | -------------------------------------------------------------------------------- /demo/app.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | from io import BytesIO 7 | 8 | import matplotlib.pyplot as plt 9 | import requests 10 | import streamlit as st 11 | import torch 12 | from PIL import Image 13 | from torchvision import models 14 | from torchvision.transforms.functional import normalize, resize, to_pil_image, to_tensor 15 | 16 | from torchcam import methods 17 | from torchcam.methods._utils import locate_candidate_layer 18 | from torchcam.utils import overlay_mask 19 | 20 | CAM_METHODS = [ 21 | "CAM", 22 | "GradCAM", 23 | "GradCAMpp", 24 | "SmoothGradCAMpp", 25 | "ScoreCAM", 26 | "SSCAM", 27 | "ISCAM", 28 | "XGradCAM", 29 | "LayerCAM", 30 | ] 31 | TV_MODELS = [ 32 | "resnet18", 33 | "resnet50", 34 | "mobilenet_v3_small", 35 | "mobilenet_v3_large", 36 | "regnet_y_400mf", 37 | "convnext_tiny", 38 | "convnext_small", 39 | ] 40 | LABEL_MAP = requests.get( 41 | "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json", 42 | timeout=10, 43 | ).json() 44 | 45 | 46 | def main(): 47 | # Wide mode 48 | st.set_page_config(page_title="TorchCAM - Class activation explorer", layout="wide") 49 | 50 | # Designing the interface 51 | st.title("TorchCAM: class activation explorer") 52 | # For newline 53 | st.write("\n") 54 | # Set the columns 55 | cols = st.columns((1, 1, 1)) 56 | cols[0].header("Input image") 57 | cols[1].header("Raw CAM") 58 | cols[-1].header("Overlayed CAM") 59 | 60 | # Sidebar 61 | # File selection 62 | st.sidebar.title("Input selection") 63 | # Disabling warning 64 | st.set_option("deprecation.showfileUploaderEncoding", False) 65 | # Choose your own image 66 | uploaded_file = st.sidebar.file_uploader("Upload files", type=["png", "jpeg", "jpg"]) 67 | if uploaded_file is not None: 68 | img = Image.open(BytesIO(uploaded_file.read()), mode="r").convert("RGB") 69 | 70 | cols[0].image(img, use_column_width=True) 71 | 72 | # Model selection 73 | st.sidebar.title("Setup") 74 | tv_model = st.sidebar.selectbox( 75 | "Classification model", 76 | TV_MODELS, 77 | help="Supported models from Torchvision", 78 | ) 79 | default_layer = "" 80 | if tv_model is not None: 81 | with st.spinner("Loading model..."): 82 | model = models.__dict__[tv_model](pretrained=True).eval() 83 | default_layer = locate_candidate_layer(model, (3, 224, 224)) 84 | 85 | if torch.cuda.is_available(): 86 | model = model.cuda() 87 | 88 | target_layer = st.sidebar.text_input( 89 | "Target layer", 90 | default_layer, 91 | help='If you want to target several layers, add a "+" separator (e.g. "layer3+layer4")', 92 | ) 93 | cam_method = st.sidebar.selectbox( 94 | "CAM method", 95 | CAM_METHODS, 96 | help="The way your class activation map will be computed", 97 | ) 98 | if cam_method is not None: 99 | cam_extractor = methods.__dict__[cam_method]( 100 | model, 101 | target_layer=[s.strip() for s in target_layer.split("+")] if len(target_layer) > 0 else None, 102 | ) 103 | 104 | class_choices = [f"{idx + 1} - {class_name}" for idx, class_name in enumerate(LABEL_MAP)] 105 | class_selection = st.sidebar.selectbox("Class selection", ["Predicted class (argmax)", *class_choices]) 106 | 107 | # For newline 108 | st.sidebar.write("\n") 109 | 110 | if st.sidebar.button("Compute CAM"): 111 | if uploaded_file is None: 112 | st.sidebar.error("Please upload an image first") 113 | 114 | else: 115 | with st.spinner("Analyzing..."): 116 | # Preprocess image 117 | img_tensor = normalize( 118 | to_tensor(resize(img, (224, 224))), 119 | [0.485, 0.456, 0.406], 120 | [0.229, 0.224, 0.225], 121 | ) 122 | 123 | if torch.cuda.is_available(): 124 | img_tensor = img_tensor.cuda() 125 | 126 | # Forward the image to the model 127 | out = model(img_tensor.unsqueeze(0)) 128 | # Select the target class 129 | if class_selection == "Predicted class (argmax)": 130 | class_idx = out.squeeze(0).argmax().item() 131 | else: 132 | class_idx = LABEL_MAP.index(class_selection.rpartition(" - ")[-1]) 133 | # Retrieve the CAM 134 | act_maps = cam_extractor(class_idx, out) 135 | # Fuse the CAMs if there are several 136 | activation_map = act_maps[0] if len(act_maps) == 1 else cam_extractor.fuse_cams(act_maps) 137 | # Plot the raw heatmap 138 | fig, ax = plt.subplots() 139 | ax.imshow(activation_map.squeeze(0).cpu().numpy()) 140 | ax.axis("off") 141 | cols[1].pyplot(fig) 142 | 143 | # Overlayed CAM 144 | fig, ax = plt.subplots() 145 | result = overlay_mask(img, to_pil_image(activation_map, mode="F"), alpha=0.5) 146 | ax.imshow(result) 147 | ax.axis("off") 148 | cols[-1].pyplot(fig) 149 | 150 | 151 | if __name__ == "__main__": 152 | main() 153 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Changing the documentation 2 | 3 | The documentation of this project is built using `sphinx`. In order to install all the build dependencies, run the following command from the root folder of the repository: 4 | ```shell 5 | pip install -e ".[docs]" 6 | ``` 7 | 8 | --- 9 | **NOTE** 10 | 11 | You are only generating the documentation to inspect it locally. Only the source files are pushed to the remote repository, the documentation will be built automatically by the CI. 12 | 13 | --- 14 | 15 | ## Build the documentation 16 | 17 | ### Latest version 18 | 19 | In most cases, you will only be changing the documentation of the latest version (dev version). In this case, you can build the documentation (the HTML files) with the following command: 20 | 21 | ```shell 22 | sphinx-build docs/source docs/_build -a 23 | ``` 24 | 25 | Then open `docs/_build/index.html` in your web browser to navigate in it. 26 | 27 | 28 | ### Multi-version documentation 29 | 30 | In rare cases, you might want to modify the documentation for other versions. You will then have to build the documentation for the multiple versions of the package, which you can do by running this command from the `docs` folder: 31 | ```shell 32 | bash build.sh 33 | ``` 34 | -------------------------------------------------------------------------------- /docs/build.sh: -------------------------------------------------------------------------------- 1 | function deploy_doc(){ 2 | if [ ! -z "$1" ] 3 | then 4 | git checkout $1 5 | fi 6 | COMMIT=$(git rev-parse --short HEAD) 7 | echo "Creating doc at commit" $COMMIT "and pushing to folder $2" 8 | pip install -U .. 9 | if [ ! -z "$2" ] 10 | then 11 | if [ "$2" == "latest" ]; then 12 | echo "Pushing main" 13 | sphinx-build source build/$2 -a 14 | elif [ -d build/$2 ]; then 15 | echo "Directory" $2 "already exists" 16 | else 17 | echo "Pushing version" $2 18 | cp -r _static source/ && cp _conf.py source/conf.py 19 | sphinx-build source _build -a 20 | fi 21 | else 22 | echo "Pushing stable" 23 | cp -r _static source/ && cp _conf.py source/conf.py 24 | sphinx-build source build -a 25 | fi 26 | git checkout source/ && git clean -f source/ 27 | } 28 | 29 | # exit when any command fails 30 | set -e 31 | # You can find the commit for each tag on https://github.com/frgfm/torch-cam/tags 32 | if [ -d build ]; then rm -Rf build; fi 33 | mkdir build 34 | cp -r source/_static . 35 | cp source/conf.py _conf.py 36 | git fetch --all --tags --unshallow 37 | deploy_doc "" latest 38 | deploy_doc "eb9427e" v0.2.0 39 | deploy_doc "d8d722d" v0.3.0 40 | deploy_doc "e34fc42" v0.3.1 41 | deploy_doc "1b6f37d" v0.3.2 42 | deploy_doc "53e9dfe" # v0.4.0 Latest stable release 43 | rm -rf _build _static _conf.py 44 | -------------------------------------------------------------------------------- /docs/source/_static/css/custom_theme.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | font-size: 240%; 3 | } 4 | 5 | /* Github button */ 6 | 7 | .github-repo { 8 | display: flex; 9 | justify-content: center; 10 | } 11 | 12 | /* Version control */ 13 | 14 | .version-button { 15 | color: gray; 16 | border: none; 17 | padding: 5px; 18 | font-size: 15px; 19 | cursor: pointer; 20 | } 21 | 22 | .version-button:hover, .version-button:focus { 23 | color: white; 24 | background-color: gray; 25 | } 26 | 27 | .version-dropdown { 28 | display: none; 29 | min-width: 160px; 30 | overflow: auto; 31 | font-size: 15px; 32 | } 33 | 34 | .version-dropdown a { 35 | color: gray; 36 | padding: 3px 4px; 37 | text-decoration: none; 38 | display: block; 39 | } 40 | 41 | .version-dropdown a:hover { 42 | color: white; 43 | background-color: gray; 44 | } 45 | 46 | .version-show { 47 | display: block; 48 | } 49 | -------------------------------------------------------------------------------- /docs/source/_static/js/custom.js: -------------------------------------------------------------------------------- 1 | // Based on https://github.com/huggingface/transformers/blob/master/docs/source/_static/js/custom.js 2 | 3 | 4 | // These two things need to be updated at each release for the version selector. 5 | // Last stable version 6 | const stableVersion = "v0.4.0" 7 | // Dictionary doc folder to label. The last stable version should have an empty key. 8 | const versionMapping = { 9 | "latest": "latest", 10 | "": "v0.4.0 (stable)", 11 | "v0.3.2": "v0.3.2", 12 | "v0.3.1": "v0.3.1", 13 | "v0.3.0": "v0.3.0", 14 | "v0.2.0": "v0.2.0", 15 | } 16 | 17 | function addGithubButton() { 18 | const div = ` 19 |
20 | Star 26 |
27 | `; 28 | document.querySelector(".sidebar-brand").insertAdjacentHTML('afterend', div); 29 | } 30 | 31 | function addVersionControl() { 32 | // To grab the version currently in view, we parse the url 33 | const parts = location.toString().split('/'); 34 | let versionIndex = parts.length - 2; 35 | // Index page may not have a last part with filename.html so we need to go up 36 | if (parts[parts.length - 1] != "" && ! parts[parts.length - 1].match(/\.html$|^search.html?/)) { 37 | versionIndex = parts.length - 1; 38 | } 39 | const version = parts[versionIndex]; 40 | 41 | // Menu with all the links, 42 | const versionMenu = document.createElement("div"); 43 | 44 | const htmlLines = []; 45 | for (const [key, value] of Object.entries(versionMapping)) { 46 | let baseUrlIndex = (version == "torch-cam") ? versionIndex + 1: versionIndex; 47 | var urlParts = parts.slice(0, baseUrlIndex); 48 | if (key != "") { 49 | urlParts = urlParts.concat([key]); 50 | } 51 | urlParts = urlParts.concat(parts.slice(versionIndex+1)); 52 | htmlLines.push(`${value}`); 53 | } 54 | 55 | versionMenu.classList.add("version-dropdown"); 56 | versionMenu.innerHTML = htmlLines.join('\n'); 57 | 58 | // Button for version selection 59 | const versionButton = document.createElement("div"); 60 | versionButton.classList.add("version-button"); 61 | let label = (version == "torch-cam") ? stableVersion : version 62 | versionButton.innerText = label.concat(" ▼"); 63 | 64 | // Toggle the menu when we click on the button 65 | versionButton.addEventListener("click", () => { 66 | versionMenu.classList.toggle("version-show"); 67 | }); 68 | 69 | // Hide the menu when we click elsewhere 70 | window.addEventListener("click", (event) => { 71 | if (event.target != versionButton){ 72 | versionMenu.classList.remove('version-show'); 73 | } 74 | }); 75 | 76 | // Container 77 | const div = document.createElement("div"); 78 | div.appendChild(versionButton); 79 | div.appendChild(versionMenu); 80 | div.style.paddingTop = '5px'; 81 | div.style.paddingBottom = '5px'; 82 | div.style.display = 'block'; 83 | div.style.textAlign = 'center'; 84 | 85 | const scrollDiv = document.querySelector(".sidebar-brand"); 86 | scrollDiv.insertBefore(div, scrollDiv.children[1]); 87 | } 88 | 89 | /*! 90 | * github-buttons v2.2.10 91 | * (c) 2019 なつき 92 | * @license BSD-2-Clause 93 | */ 94 | /** 95 | * modified to run programmatically 96 | */ 97 | function parseGithubButtons (){"use strict";var e=window.document,t=e.location,o=window.encodeURIComponent,r=window.decodeURIComponent,n=window.Math,a=window.HTMLElement,i=window.XMLHttpRequest,l="https://unpkg.com/github-buttons@2.2.10/dist/buttons.html",c=i&&i.prototype&&"withCredentials"in i.prototype,d=c&&a&&a.prototype.attachShadow&&!a.prototype.attachShadow.prototype,s=function(e,t,o){e.addEventListener?e.addEventListener(t,o):e.attachEvent("on"+t,o)},u=function(e,t,o){e.removeEventListener?e.removeEventListener(t,o):e.detachEvent("on"+t,o)},h=function(e,t,o){var r=function(n){return u(e,t,r),o(n)};s(e,t,r)},f=function(e,t,o){var r=function(n){if(t.test(e.readyState))return u(e,"readystatechange",r),o(n)};s(e,"readystatechange",r)},p=function(e){return function(t,o,r){var n=e.createElement(t);if(o)for(var a in o){var i=o[a];null!=i&&(null!=n[a]?n[a]=i:n.setAttribute(a,i))}if(r)for(var l=0,c=r.length;l'},eye:{width:16,height:16,path:''},star:{width:14,height:16,path:''},"repo-forked":{width:10,height:16,path:''},"issue-opened":{width:14,height:16,path:''},"cloud-download":{width:16,height:16,path:''}},w={},x=function(e,t,o){var r=p(e.ownerDocument),n=e.appendChild(r("style",{type:"text/css"}));n.styleSheet?n.styleSheet.cssText=m:n.appendChild(e.ownerDocument.createTextNode(m));var a,l,d=r("a",{className:"btn",href:t.href,target:"_blank",innerHTML:(a=t["data-icon"],l=/^large$/i.test(t["data-size"])?16:14,a=(""+a).toLowerCase().replace(/^octicon-/,""),{}.hasOwnProperty.call(v,a)||(a="mark-github"),'"),"aria-label":t["aria-label"]||void 0},[" ",r("span",{},[t["data-text"]||""])]);/\.github\.com$/.test("."+d.hostname)?/^https?:\/\/((gist\.)?github\.com\/[^\/?#]+\/[^\/?#]+\/archive\/|github\.com\/[^\/?#]+\/[^\/?#]+\/releases\/download\/|codeload\.github\.com\/)/.test(d.href)&&(d.target="_top"):(d.href="#",d.target="_self");var u,h,g,x,y=e.appendChild(r("div",{className:"widget"+(/^large$/i.test(t["data-size"])?" lg":"")},[d]));/^(true|1)$/i.test(t["data-show-count"])&&"github.com"===d.hostname&&(u=d.pathname.replace(/^(?!\/)/,"/").match(/^\/([^\/?#]+)(?:\/([^\/?#]+)(?:\/(?:(subscription)|(fork)|(issues)|([^\/?#]+)))?)?(?:[\/?#]|$)/))&&!u[6]?(u[2]?(h="/repos/"+u[1]+"/"+u[2],u[3]?(x="subscribers_count",g="watchers"):u[4]?(x="forks_count",g="network"):u[5]?(x="open_issues_count",g="issues"):(x="stargazers_count",g="stargazers")):(h="/users/"+u[1],g=x="followers"),function(e,t){var o=w[e]||(w[e]=[]);if(!(o.push(t)>1)){var r=b(function(){for(delete w[e];t=o.shift();)t.apply(null,arguments)});if(c){var n=new i;s(n,"abort",r),s(n,"error",r),s(n,"load",function(){var e;try{e=JSON.parse(n.responseText)}catch(e){return void r(e)}r(200!==n.status,e)}),n.open("GET",e),n.send()}else{var a=this||window;a._=function(e){a._=null,r(200!==e.meta.status,e.data)};var l=p(a.document)("script",{async:!0,src:e+(/\?/.test(e)?"&":"?")+"callback=_"}),d=function(){a._&&a._({meta:{}})};s(l,"load",d),s(l,"error",d),l.readyState&&f(l,/de|m/,d),a.document.getElementsByTagName("head")[0].appendChild(l)}}}.call(this,"https://api.github.com"+h,function(e,t){if(!e){var n=t[x];y.appendChild(r("a",{className:"social-count",href:t.html_url+"/"+g,target:"_blank","aria-label":n+" "+x.replace(/_count$/,"").replace("_"," ").slice(0,n<2?-1:void 0)+" on GitHub"},[r("b"),r("i"),r("span",{},[(""+n).replace(/\B(?=(\d{3})+(?!\d))/g,",")])]))}o&&o(y)})):o&&o(y)},y=window.devicePixelRatio||1,C=function(e){return(y>1?n.ceil(n.round(e*y)/y*2)/2:n.ceil(e))||0},F=function(e,t){e.style.width=t[0]+"px",e.style.height=t[1]+"px"},k=function(t,r){if(null!=t&&null!=r)if(t.getAttribute&&(t=function(e){for(var t={href:e.href,title:e.title,"aria-label":e.getAttribute("aria-label")},o=["icon","text","size","show-count"],r=0,n=o.length;r`_ 7 | 8 | v0.3.2 (2022-08-02) 9 | ------------------- 10 | Release note: `v0.3.2 `_ 11 | 12 | v0.3.1 (2021-10-31) 13 | ------------------- 14 | Release note: `v0.3.1 `_ 15 | 16 | v0.3.0 (2021-10-31) 17 | ------------------- 18 | Release note: `v0.3.0 `_ 19 | 20 | v0.2.0 (2021-04-10) 21 | ------------------- 22 | Release note: `v0.2.0 `_ 23 | 24 | v0.1.2 (2020-12-27) 25 | ------------------- 26 | Release note: `v0.1.2 `_ 27 | 28 | v0.1.1 (2020-08-03) 29 | ------------------- 30 | Release note: `v0.1.1 `_ 31 | 32 | v0.1.0 (2020-03-24) 33 | ------------------- 34 | Release note: `v0.1.0 `_ 35 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | # Configuration file for the Sphinx documentation builder. 7 | # 8 | # This file only contains a selection of the most common options. For a full 9 | # list see the documentation: 10 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 11 | 12 | # -- Path setup -------------------------------------------------------------- 13 | 14 | # If extensions (or modules to document with autodoc) are in another directory, 15 | # add these directories to sys.path here. If the directory is relative to the 16 | # documentation root, use os.path.abspath to make it absolute, like shown here. 17 | # 18 | import sys 19 | from datetime import datetime 20 | from pathlib import Path 21 | 22 | sys.path.insert(0, Path().cwd().parent.parent) 23 | import torchcam 24 | 25 | # -- Project information ----------------------------------------------------- 26 | 27 | master_doc = "index" 28 | project = "torchcam" 29 | copyright = f"2020-{datetime.now().year}, François-Guillaume Fernandez" 30 | author = "François-Guillaume Fernandez" 31 | 32 | # The full version, including alpha/beta/rc tags 33 | version = torchcam.__version__ 34 | release = torchcam.__version__ + "-git" 35 | 36 | 37 | # -- General configuration --------------------------------------------------- 38 | 39 | # Add any Sphinx extension module names here, as strings. They can be 40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 41 | # ones. 42 | extensions = [ 43 | "sphinx.ext.autodoc", 44 | "sphinx.ext.napoleon", 45 | "sphinx.ext.viewcode", 46 | "sphinx.ext.autosummary", 47 | "sphinx.ext.mathjax", 48 | "sphinxemoji.sphinxemoji", # cf. https://sphinxemojicodes.readthedocs.io/en/stable/ 49 | "sphinx_copybutton", 50 | "recommonmark", 51 | "sphinx_markdown_tables", 52 | ] 53 | 54 | napoleon_use_ivar = True 55 | 56 | # Add any paths that contain templates here, relative to this directory. 57 | templates_path = ["_templates"] 58 | 59 | # List of patterns, relative to source directory, that match files and 60 | # directories to ignore when looking for source files. 61 | # This pattern also affects html_static_path and html_extra_path. 62 | exclude_patterns = ["notebooks/*.rst"] 63 | 64 | 65 | # The name of the Pygments (syntax highlighting) style to use. 66 | pygments_style = "friendly" 67 | pygments_dark_style = "monokai" 68 | highlight_language = "python3" 69 | 70 | # -- Options for HTML output ------------------------------------------------- 71 | 72 | # The theme to use for HTML and HTML Help pages. See the documentation for 73 | # a list of builtin themes. 74 | # 75 | html_theme = "furo" 76 | 77 | html_title = "TorchCAM" 78 | # html_logo = "_static/images/logo.png" 79 | # html_favicon = "_static/images/favicon.ico" 80 | language = "en" 81 | 82 | # Theme options are theme-specific and customize the look and feel of a theme 83 | # further. For a list of options available for each theme, see the 84 | # documentation. 85 | # 86 | html_theme_options = { 87 | "footer_icons": [ 88 | { 89 | "name": "GitHub", 90 | "url": "https://github.com/frgfm/torch-cam", 91 | "html": """ 92 | 93 | 94 | 95 | """, 96 | "class": "", 97 | }, 98 | ], 99 | "source_repository": "https://github.com/frgfm/torch-cam/", 100 | "source_branch": "main", 101 | "source_directory": "docs/source/", 102 | } 103 | 104 | 105 | # Add any paths that contain custom static files (such as style sheets) here, 106 | # relative to this directory. They are copied after the builtin static files, 107 | # so a file named "default.css" will overwrite the builtin "default.css". 108 | html_static_path = ["_static"] 109 | 110 | 111 | # Add googleanalytics id 112 | # ref: https://github.com/orenhecht/googleanalytics/blob/master/sphinxcontrib/googleanalytics.py 113 | def add_ga_javascript(app, pagename, templatename, context, doctree): 114 | metatags = context.get("metatags", "") 115 | metatags += """ 116 | 117 | 118 | 124 | """.format(app.config.googleanalytics_id) 125 | context["metatags"] = metatags 126 | 127 | 128 | def setup(app): 129 | app.add_config_value("googleanalytics_id", "UA-148140560-4", "html") 130 | app.add_css_file("css/custom_theme.css") 131 | app.add_js_file("js/custom.js") 132 | app.connect("html-page-context", add_ga_javascript) 133 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | *********************************** 2 | TorchCAM: class activation explorer 3 | *********************************** 4 | 5 | TorchCAM provides a minimal yet flexible way to explore the spatial importance of features on your PyTorch model outputs. Check out the live demo on `HuggingFace Spaces `_ |:hugging_face:| 6 | 7 | 8 | .. image:: https://github.com/frgfm/torch-cam/releases/download/v0.3.1/carbon.png 9 | :alt: code_snippet 10 | :align: center 11 | 12 | 13 | This project is meant for: 14 | 15 | * |:zap:| **exploration**: easily assess the influence of spatial features on your model's outputs 16 | * |:woman_scientist:| **research**: quickly implement your own ideas for new CAM methods 17 | 18 | 19 | .. toctree:: 20 | :maxdepth: 1 21 | :caption: Getting Started 22 | :hidden: 23 | 24 | installing 25 | notebooks 26 | 27 | 28 | 29 | CAM zoo 30 | ^^^^^^^ 31 | 32 | Activation-based methods 33 | """""""""""""""""""""""" 34 | * CAM from `"Learning Deep Features for Discriminative Localization" `_ 35 | * Score-CAM from `"Score-CAM: Score-Weighted Visual Explanations for Convolutional Neural Networks" `_ 36 | * SS-CAM from `"SS-CAM: Smoothed Score-CAM for Sharper Visual Feature Localization" `_ 37 | * IS-CAM from `"IS-CAM: Integrated Score-CAM for axiomatic-based explanations" `_ 38 | 39 | Gradient-based methods 40 | """""""""""""""""""""" 41 | * Grad-CAM from `"Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization" `_ 42 | * Grad-CAM++ from `"Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks" `_ 43 | * Smooth Grad-CAM++ from `"Smooth Grad-CAM++: An Enhanced Inference Level Visualization Technique for Deep Convolutional Neural Network Models" `_ 44 | * X-Grad-CAM from `"Axiom-based Grad-CAM: Towards Accurate Visualization and Explanation of CNNs" `_ 45 | * Layer-CAM from `"LayerCAM: Exploring Hierarchical Class Activation Maps for Localization" `_ 46 | 47 | 48 | .. toctree:: 49 | :maxdepth: 2 50 | :caption: Package Reference 51 | :hidden: 52 | 53 | methods 54 | metrics 55 | utils 56 | 57 | 58 | .. toctree:: 59 | :maxdepth: 1 60 | :caption: Notes 61 | :hidden: 62 | 63 | changelog 64 | -------------------------------------------------------------------------------- /docs/source/installing.rst: -------------------------------------------------------------------------------- 1 | 2 | ************ 3 | Installation 4 | ************ 5 | 6 | This library requires `Python `_ 3.9 or higher. 7 | 8 | Via Python Package 9 | ================== 10 | 11 | Install the last stable release of the package using `uv `_: 12 | 13 | .. code:: bash 14 | 15 | uv pip install torchcam 16 | 17 | 18 | Via Conda 19 | ========= 20 | 21 | Install the last stable release of the package using `conda `_: 22 | 23 | .. code:: bash 24 | 25 | conda install -c frgfm torchcam 26 | 27 | 28 | Via Git 29 | ======= 30 | 31 | Install the library in developer mode: 32 | 33 | .. code:: bash 34 | 35 | git clone https://github.com/frgfm/torch-cam.git 36 | uv pip install -e torch-cam/. 37 | -------------------------------------------------------------------------------- /docs/source/methods.rst: -------------------------------------------------------------------------------- 1 | torchcam.methods 2 | ================ 3 | 4 | 5 | .. currentmodule:: torchcam.methods 6 | 7 | 8 | Class activation map 9 | -------------------- 10 | The class activation map gives you the importance of each region of a feature map on a model's output. 11 | More specifically, a class activation map is relative to: 12 | 13 | * the layer at which it is computed (e.g. the N-th layer of your model) 14 | * the model's classification output (e.g. the raw logits of the model) 15 | * the class index to focus on 16 | 17 | With TorchCAM, the target layer is selected when you create your CAM extractor. You will need to pass the model logits to the extractor and a class index for it to do its magic! 18 | 19 | 20 | Activation-based methods 21 | ------------------------ 22 | Methods related to activation-based class activation maps. 23 | 24 | 25 | .. autoclass:: CAM 26 | 27 | .. autoclass:: ScoreCAM 28 | 29 | .. autoclass:: SSCAM 30 | 31 | .. autoclass:: ISCAM 32 | 33 | 34 | Gradient-based methods 35 | ---------------------- 36 | Methods related to gradient-based class activation maps. 37 | 38 | 39 | .. autoclass:: GradCAM 40 | 41 | .. autoclass:: GradCAMpp 42 | 43 | .. autoclass:: SmoothGradCAMpp 44 | 45 | .. autoclass:: XGradCAM 46 | 47 | .. autoclass:: LayerCAM 48 | 49 | .. automethod:: fuse_cams 50 | -------------------------------------------------------------------------------- /docs/source/metrics.rst: -------------------------------------------------------------------------------- 1 | torchcam.metrics 2 | ================ 3 | 4 | 5 | .. currentmodule:: torchcam.metrics 6 | 7 | 8 | Apart from qualitative visual comparison, it is important to have a refined evaluation metric for class activation maps. This submodule is dedicated to the evaluation of CAM methods. 9 | 10 | .. autoclass:: ClassificationMetric 11 | 12 | .. automethod:: update 13 | .. automethod:: summary 14 | -------------------------------------------------------------------------------- /docs/source/notebooks.md: -------------------------------------------------------------------------------- 1 | ../../notebooks/README.md -------------------------------------------------------------------------------- /docs/source/notebooks/latency_benchmark.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | In this tutorial, you will need the entire project codebase. So first, 5 | we clone the project’s GitHub repository and install from source. 6 | 7 | .. code-block::python 8 | 9 | >>> !git clone https://github.com/frgfm/torch-cam.git 10 | >>> !pip install -e torch-cam/. 11 | 12 | 13 | Hardware information 14 | ==================== 15 | 16 | GPU information 17 | --------------- 18 | 19 | To be able to run the benchmark on GPU, you need to have the correct 20 | driver and CUDA installation. If you get a message starting with: > 21 | NVIDIA-SMI has failed… 22 | 23 | The script will be running on CPU as PyTorch isn’t able to access any 24 | CUDA-capable device. 25 | 26 | .. code-block::python 27 | 28 | >>> !nvidia-smi 29 | NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running. 30 | 31 | 32 | CPU information 33 | --------------- 34 | 35 | Latency will vary greatly depending on the capabilities of your CPU. 36 | Some models are optimized for CPU architectures (MobileNet V3 for 37 | instance), while others were only designed for GPU and will thus yield 38 | poor latency when run on CPU. 39 | 40 | .. code-block::python 41 | 42 | >>> !lscpu 43 | Architecture: x86_64 44 | CPU op-mode(s): 32-bit, 64-bit 45 | Byte Order: Little Endian 46 | CPU(s): 2 47 | On-line CPU(s) list: 0,1 48 | Thread(s) per core: 2 49 | Core(s) per socket: 1 50 | Socket(s): 1 51 | NUMA node(s): 1 52 | Vendor ID: AuthenticAMD 53 | CPU family: 23 54 | Model: 49 55 | Model name: AMD EPYC 7B12 56 | Stepping: 0 57 | CPU MHz: 2249.998 58 | BogoMIPS: 4499.99 59 | Hypervisor vendor: KVM 60 | Virtualization type: full 61 | L1d cache: 32K 62 | L1i cache: 32K 63 | L2 cache: 512K 64 | L3 cache: 16384K 65 | NUMA node0 CPU(s): 0,1 66 | Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid tsc_known_freq pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw topoext ssbd ibrs ibpb stibp vmmcall fsgsbase tsc_adjust bmi1 avx2 smep bmi2 rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 clzero xsaveerptr arat npt nrip_save umip rdpid 67 | 68 | 69 | Usage 70 | ===== 71 | 72 | The latency evaluation script provides several options for you to play 73 | with: change the input size, the architecture or the CAM method to 74 | better reflect your use case. 75 | 76 | .. code-block::python 77 | 78 | >>> !cd torch-cam/ && python scripts/eval_latency.py --help 79 | usage: eval_latency.py [-h] [--arch ARCH] [--size SIZE] 80 | [--class-idx CLASS_IDX] [--device DEVICE] [--it IT] 81 | method 82 | 83 | CAM method latency benchmark 84 | 85 | positional arguments: 86 | method CAM method to use 87 | 88 | optional arguments: 89 | -h, --help show this help message and exit 90 | --arch ARCH Name of the torchvision architecture (default: 91 | resnet18) 92 | --size SIZE The image input size (default: 224) 93 | --class-idx CLASS_IDX 94 | Index of the class to inspect (default: 232) 95 | --device DEVICE Default device to perform computation on (default: 96 | None) 97 | --it IT Number of iterations to run (default: 100) 98 | 99 | 100 | Architecture designed for GPU 101 | ----------------------------- 102 | 103 | Let’s benchmark the latency of CAM methods with the popular ResNet 104 | architecture 105 | 106 | .. code-block::python 107 | 108 | >>> !cd torch-cam/ && python scripts/eval_latency.py SmoothGradCAMpp --arch resnet18 109 | Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /root/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth 110 | 100% 44.7M/44.7M [00:00<00:00, 85.9MB/s] 111 | /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at /pytorch/c10/core/TensorImpl.h:1156.) 112 | return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode) 113 | WARNING:root:no value was provided for `target_layer`, thus set to 'layer4'. 114 | SmoothGradCAMpp w/ resnet18 (100 runs on (224, 224) inputs) 115 | mean 1143.17ms, std 36.79ms 116 | 117 | 118 | .. code-block::python 119 | 120 | >>> !cd torch-cam/ && python scripts/eval_latency.py LayerCAM --arch resnet18 121 | /usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at /pytorch/c10/core/TensorImpl.h:1156.) 122 | return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode) 123 | WARNING:root:no value was provided for `target_layer`, thus set to 'layer4'. 124 | LayerCAM w/ resnet18 (100 runs on (224, 224) inputs) 125 | mean 189.64ms, std 8.82ms 126 | 127 | 128 | Architecture designed for CPU 129 | ----------------------------- 130 | 131 | As mentioned, we’ll consider MobileNet V3 here. 132 | 133 | .. code-block::python 134 | 135 | >>> !cd torch-cam/ && python scripts/eval_latency.py SmoothGradCAMpp --arch mobilenet_v3_large 136 | Downloading: "https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth" to /root/.cache/torch/hub/checkpoints/mobilenet_v3_large-8738ca79.pth 137 | 100% 21.1M/21.1M [00:00<00:00, 71.5MB/s] 138 | WARNING:root:no value was provided for `target_layer`, thus set to 'features.4.block.1'. 139 | SmoothGradCAMpp w/ mobilenet_v3_large (100 runs on (224, 224) inputs) 140 | mean 762.18ms, std 26.95ms 141 | 142 | 143 | .. code-block::python 144 | 145 | >>> !cd torch-cam/ && python scripts/eval_latency.py LayerCAM --arch mobilenet_v3_large 146 | WARNING:root:no value was provided for `target_layer`, thus set to 'features.4.block.1'. 147 | LayerCAM w/ mobilenet_v3_large (100 runs on (224, 224) inputs) 148 | mean 148.76ms, std 7.86ms 149 | -------------------------------------------------------------------------------- /docs/source/notebooks/quicktour.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | Install all the dependencies to make the most out of TorchCAM 5 | 6 | .. code-block::python 7 | 8 | >>> !pip install torchvision matplotlib 9 | 10 | 11 | Latest stable release 12 | --------------------- 13 | 14 | .. code-block:: python 15 | 16 | >>> !pip install torchcam 17 | 18 | From source 19 | ----------- 20 | 21 | .. code-block:: python 22 | 23 | >>> # Install the most up-to-date version from GitHub 24 | >>> !pip install -e git+https://github.com/frgfm/torch-cam.git#egg=torchcam 25 | 26 | 27 | Now go to ``Runtime/Restart runtime`` for your changes to take effect! 28 | 29 | Basic usage 30 | =========== 31 | 32 | .. code-block:: python 33 | 34 | >>> %matplotlib inline 35 | >>> # All imports 36 | >>> import matplotlib.pyplot as plt 37 | >>> import torch 38 | >>> from torch.nn.functional import softmax, interpolate 39 | >>> from torchvision.io.image import read_image 40 | >>> from torchvision.models import resnet18 41 | >>> from torchvision.transforms.functional import normalize, resize, to_pil_image 42 | >>> 43 | >>> from torchcam.methods import SmoothGradCAMpp, LayerCAM 44 | >>> from torchcam.utils import overlay_mask 45 | 46 | .. code-block:: python 47 | 48 | >>> # Download an image 49 | >>> !wget https://www.woopets.fr/assets/races/000/066/big-portrait/border-collie.jpg 50 | >>> # Set this to your image path if you wish to run it on your own data 51 | >>> img_path = "border-collie.jpg" 52 | 53 | 54 | .. code-block:: python 55 | 56 | >>> # Instantiate your model here 57 | >>> model = resnet18(pretrained=True).eval() 58 | 59 | 60 | 61 | Illustrate your classifier capabilities 62 | --------------------------------------- 63 | 64 | .. code-block:: python 65 | 66 | >>> cam_extractor = SmoothGradCAMpp(model) 67 | >>> # Get your input 68 | >>> img = read_image(img_path) 69 | >>> # Preprocess it for your chosen model 70 | >>> input_tensor = normalize(resize(img, (224, 224)) / 255., [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) 71 | >>> # Preprocess your data and feed it to the model 72 | >>> out = model(input_tensor.unsqueeze(0)) 73 | >>> # Retrieve the CAM by passing the class index and the model output 74 | >>> cams = cam_extractor(out.squeeze(0).argmax().item(), out) 75 | WARNING:root:no value was provided for `target_layer`, thus set to 'layer4'. 76 | 77 | .. code-block:: python 78 | 79 | >>> # Notice that there is one CAM per target layer (here only 1) 80 | >>> for cam in cams: 81 | >>> print(cam.shape) 82 | torch.Size([7, 7]) 83 | 84 | 85 | .. code-block:: python 86 | 87 | >>> # The raw CAM 88 | >>> for name, cam in zip(cam_extractor.target_names, cams): 89 | >>> plt.imshow(cam.numpy()); plt.axis('off'); plt.title(name); plt.show() 90 | 91 | 92 | .. code-block:: python 93 | 94 | >>> # Overlayed on the image 95 | >>> for name, cam in zip(cam_extractor.target_names, cams): 96 | >>> result = overlay_mask(to_pil_image(img), to_pil_image(cam, mode='F'), alpha=0.5) 97 | >>> plt.imshow(result); plt.axis('off'); plt.title(name); plt.show() 98 | 99 | 100 | .. code-block:: python 101 | 102 | >>> # Once you're finished, clear the hooks on your model 103 | >>> cam_extractor.remove_hooks() 104 | 105 | Advanced tricks 106 | =============== 107 | 108 | Extract localization cues 109 | ------------------------- 110 | 111 | .. code-block::python 112 | 113 | >>> # Retrieve the CAM from several layers at the same time 114 | >>> cam_extractor = LayerCAM(model) 115 | >>> # Preprocess your data and feed it to the model 116 | >>> out = model(input_tensor.unsqueeze(0)) 117 | >>> print(softmax(out, dim=1).max()) 118 | WARNING:root:no value was provided for `target_layer`, thus set to 'layer4'. 119 | tensor(0.9115, grad_fn=) 120 | 121 | 122 | .. code-block::python 123 | 124 | >>> cams = cam_extractor(out.squeeze(0).argmax().item(), out) 125 | 126 | .. code-block::python 127 | 128 | >>> # Resize it 129 | >>> resized_cams = [resize(to_pil_image(cam), img.shape[-2:]) for cam in cams] 130 | >>> segmaps = [to_pil_image((resize(cam.unsqueeze(0), img.shape[-2:]).squeeze(0) >= 0.5).to(dtype=torch.float32)) for cam in cams] 131 | >>> # Plot it 132 | >>> for name, cam, seg in zip(cam_extractor.target_names, resized_cams, segmaps): 133 | >>> _, axes = plt.subplots(1, 2) 134 | >>> axes[0].imshow(cam); axes[0].axis('off'); axes[0].set_title(name) 135 | >>> axes[1].imshow(seg); axes[1].axis('off'); axes[1].set_title(name) 136 | >>> plt.show() 137 | 138 | .. code-block:: python 139 | 140 | >>> # Once you're finished, clear the hooks on your model 141 | >>> cam_extractor.remove_hooks() 142 | 143 | 144 | Fuse CAMs from multiple layers 145 | ------------------------------ 146 | 147 | .. code-block::python 148 | 149 | >>> # Retrieve the CAM from several layers at the same time 150 | >>> cam_extractor = LayerCAM(model, ["layer2", "layer3", "layer4"]) 151 | >>> # Preprocess your data and feed it to the model 152 | >>> out = model(input_tensor.unsqueeze(0)) 153 | >>> # Retrieve the CAM by passing the class index and the model output 154 | >>> cams = cam_extractor(out.squeeze(0).argmax().item(), out) 155 | 156 | .. code-block::python 157 | 158 | >>> # This time, there are several CAMs 159 | >>> for cam in cams: 160 | >>> print(cam.shape) 161 | torch.Size([28, 28]) 162 | torch.Size([14, 14]) 163 | torch.Size([7, 7]) 164 | 165 | 166 | .. code-block::python 167 | 168 | >>> # The raw CAM 169 | >>> _, axes = plt.subplots(1, len(cam_extractor.target_names)) 170 | >>> for idx, name, cam in zip(range(len(cam_extractor.target_names)), cam_extractor.target_names, cams): 171 | >>> axes[idx].imshow(cam.numpy()); axes[idx].axis('off'); axes[idx].set_title(name); 172 | >>> plt.show() 173 | 174 | 175 | .. code-block::python 176 | 177 | >>> # Let's fuse them 178 | >>> fused_cam = cam_extractor.fuse_cams(cams) 179 | >>> # Plot the raw version 180 | >>> plt.imshow(fused_cam.numpy()); plt.axis('off'); plt.title(" + ".join(cam_extractor.target_names)); plt.show() 181 | >>> # Plot the overlayed version 182 | >>> result = overlay_mask(to_pil_image(img), to_pil_image(fused_cam, mode='F'), alpha=0.5) 183 | >>> plt.imshow(result); plt.axis('off'); plt.title(" + ".join(cam_extractor.target_names)); plt.show() 184 | 185 | .. code-block:: python 186 | 187 | >>> # Once you're finished, clear the hooks on your model 188 | >>> cam_extractor.remove_hooks() 189 | -------------------------------------------------------------------------------- /docs/source/utils.rst: -------------------------------------------------------------------------------- 1 | torchcam.utils 2 | =============== 3 | 4 | .. currentmodule:: torchcam.utils 5 | 6 | .. autofunction:: overlay_mask 7 | -------------------------------------------------------------------------------- /notebooks/README.md: -------------------------------------------------------------------------------- 1 | # TorchCAM Notebooks 2 | 3 | Here are some notebooks compiled for users to better leverage the library capabilities: 4 | 5 | | Notebook | Description | | 6 | |:----------|:-------------|------:| 7 | | [Quicktour](https://github.com/frgfm/notebooks/blob/main/torch-cam/quicktour.ipynb) | A presentation of the main features of TorchCAM | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/frgfm/notebooks/blob/main/torch-cam/quicktour.ipynb) | 8 | | [Latency benchmark](https://github.com/frgfm/notebooks/blob/main/torch-cam/latency_benchmark.ipynb) | How to benchmark the latency of a CAM method | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/frgfm/notebooks/blob/main/torch-cam/latency_benchmark.ipynb) | 9 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "torchcam" 7 | description = "Class activation maps for your PyTorch CNN models" 8 | authors = [ 9 | {name = "François-Guillaume Fernandez", email = "fg-feedback@protonmail.com"} 10 | ] 11 | readme = "README.md" 12 | requires-python = ">=3.9,<4" 13 | license = {file = "LICENSE"} 14 | keywords = ["pytorch", "deep learning", "class activation map", "cnn", "gradcam"] 15 | classifiers = [ 16 | "Development Status :: 4 - Beta", 17 | "Intended Audience :: Developers", 18 | "Intended Audience :: Science/Research", 19 | "License :: OSI Approved :: Apache Software License", 20 | "Natural Language :: English", 21 | "Operating System :: OS Independent", 22 | "Programming Language :: Python :: 3", 23 | "Programming Language :: Python :: 3.9", 24 | "Programming Language :: Python :: 3.10", 25 | "Programming Language :: Python :: 3.11", 26 | "Programming Language :: Python :: 3.12", 27 | "Topic :: Scientific/Engineering", 28 | "Topic :: Scientific/Engineering :: Mathematics", 29 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 30 | ] 31 | dynamic = ["version"] 32 | dependencies = [ 33 | # cf. https://github.com/frgfm/torch-cam/discussions/148 34 | "torch>=2.0.0,<3.0.0", 35 | "numpy>=1.17.2,<2.0.0", 36 | # cf. https://github.com/advisories/GHSA-98vv-pw6r-q6q4 37 | # cf. https://github.com/pytorch/vision/issues/4934 38 | # https://github.com/frgfm/Holocron/security/dependabot/5 39 | "Pillow>=8.4.0,!=9.2.0", 40 | "matplotlib>=3.7.0,<4.0.0", 41 | ] 42 | 43 | [project.optional-dependencies] 44 | test = [ 45 | "requests>=2.20.0,<3.0.0", 46 | "torchvision>=0.15.0,<1.0.0", 47 | "pytest>=7.3.2", 48 | "pytest-cov>=3.0.0,<5.0.0", 49 | "pytest-pretty>=1.0.0,<2.0.0", 50 | ] 51 | quality = [ 52 | "ruff==0.11.9", 53 | "mypy==1.15.0", 54 | "types-Pillow", 55 | "pre-commit>=3.0.0,<5.0.0", 56 | ] 57 | docs = [ 58 | "sphinx>=3.0.0,!=3.5.0", 59 | "furo>=2022.3.4", 60 | "sphinxemoji>=0.1.8", 61 | "sphinx-copybutton>=0.3.1", 62 | "recommonmark>=0.7.1", 63 | "sphinx-markdown-tables>=0.0.15", 64 | # Indirect deps 65 | # cf. https://github.com/readthedocs/readthedocs.org/issues/9038 66 | "Jinja2<3.1", 67 | ] 68 | demo = [ 69 | "streamlit>=0.65.0,<2.0.0", 70 | "torchvision>=0.15.0,<1.0.0", 71 | ] 72 | 73 | 74 | [project.urls] 75 | documentation = "https://frgfm.github.io/torch-cam" 76 | repository = "https://github.com/frgfm/torch-cam" 77 | tracker = "https://github.com/frgfm/torch-cam/issues" 78 | changelog = "https://frgfm.github.io/torch-cam/latest/changelog.html" 79 | 80 | [tool.setuptools] 81 | zip-safe = true 82 | 83 | [tool.setuptools.packages.find] 84 | exclude = ["demo*", "docs*", "notebooks*", "scripts*", "tests*"] 85 | 86 | [tool.pytest.ini_options] 87 | testpaths = ["torchcam/"] 88 | 89 | [tool.coverage.run] 90 | source = ["torchcam/"] 91 | 92 | [tool.ruff] 93 | line-length = 120 94 | target-version = "py39" 95 | preview = true 96 | 97 | [tool.ruff.lint] 98 | select = [ 99 | "F", # pyflakes 100 | "E", # pycodestyle errors 101 | "W", # pycodestyle warnings 102 | "I", # isort 103 | "N", # pep8-naming 104 | "D101", "D103", # pydocstyle missing docstring in public function/class 105 | "D201","D202","D207","D208","D214","D215","D300","D301","D417", "D419", # pydocstyle 106 | "YTT", # flake8-2020 107 | "ANN", # flake8-annotations 108 | "ASYNC", # flake8-async 109 | "S", # flake8-bandit 110 | "BLE", # flake8-blind-except 111 | "B", # flake8-bugbear 112 | "A", # flake8-builtins 113 | "COM", # flake8-commas 114 | "CPY", # flake8-copyright 115 | "C4", # flake8-comprehensions 116 | "T10", # flake8-debugger 117 | "ISC", # flake8-implicit-str-concat 118 | "ICN", # flake8-import-conventions 119 | "LOG", # flake8-logging 120 | "PIE", # flake8-pie 121 | "T20", # flake8-print 122 | "PYI", # flake8-pyi 123 | "PT", # flake8-pytest-style 124 | "Q", # flake8-quotes 125 | "RET", # flake8-return 126 | "SLF", # flake8-self 127 | "SIM", # flake8-simplify 128 | "ARG", # flake8-unused-arguments 129 | "PTH", # flake8-use-pathlib 130 | "PERF", # perflint 131 | "NPY", # numpy 132 | "FAST", # fastapi 133 | "FURB", # refurb 134 | "RUF", # ruff specific 135 | "N", # pep8-naming 136 | ] 137 | ignore = [ 138 | "E501", # line too long, handled by black 139 | "B008", # do not perform function calls in argument defaults 140 | "B904", # raise from 141 | "C901", # too complex 142 | "F403", # star imports 143 | "E731", # lambda assignment 144 | "C416", # list comprehension to list() 145 | "ANN002", # missing type annotations on *args 146 | "ANN003", # missing type annotations on **kwargs 147 | "COM812", # trailing comma missing 148 | "N812", # lowercase imported as non-lowercase 149 | "ISC001", # implicit string concatenation (handled by format) 150 | "ANN401", # Dynamically typed expressions (typing.Any) are disallowed 151 | ] 152 | exclude = [".git"] 153 | 154 | [tool.ruff.lint.flake8-quotes] 155 | docstring-quotes = "double" 156 | 157 | [tool.ruff.lint.isort] 158 | known-first-party = ["torchcam", "app"] 159 | known-third-party = ["torch", "torchvision"] 160 | 161 | [tool.ruff.lint.per-file-ignores] 162 | "**/__init__.py" = ["I001", "F401", "CPY001"] 163 | "scripts/**.py" = ["D", "T201", "N812", "S101", "ANN"] 164 | ".github/**.py" = ["D", "T201", "S602", "S101", "ANN"] 165 | "docs/**.py" = ["E402", "D103", "ANN", "A001", "ARG001"] 166 | "tests/**.py" = ["D103", "CPY001", "S101", "PT011", "ANN", "SLF001"] 167 | "demo/**.py" = ["D103", "ANN"] 168 | "setup.py" = ["T201"] 169 | 170 | [tool.ruff.format] 171 | quote-style = "double" 172 | indent-style = "space" 173 | 174 | [tool.mypy] 175 | python_version = "3.9" 176 | files = "torchcam/" 177 | show_error_codes = true 178 | pretty = true 179 | warn_unused_ignores = true 180 | warn_redundant_casts = true 181 | warn_return_any = true 182 | no_implicit_optional = true 183 | check_untyped_defs = true 184 | implicit_reexport = false 185 | disallow_untyped_defs = true 186 | explicit_package_bases = true 187 | 188 | [[tool.mypy.overrides]] 189 | module = [ 190 | "PIL", 191 | "matplotlib" 192 | ] 193 | ignore_missing_imports = true 194 | -------------------------------------------------------------------------------- /scripts/cam_example.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | """ 7 | CAM visualization 8 | """ 9 | 10 | import argparse 11 | import math 12 | from io import BytesIO 13 | 14 | import matplotlib.pyplot as plt 15 | import requests 16 | import torch 17 | from PIL import Image 18 | from torchvision import models 19 | from torchvision.transforms.functional import normalize, resize, to_pil_image, to_tensor 20 | 21 | from torchcam import methods 22 | from torchcam.utils import overlay_mask 23 | 24 | 25 | def main(args): 26 | if args.device is None: 27 | args.device = "cuda:0" if torch.cuda.is_available() else "cpu" 28 | 29 | device = torch.device(args.device) 30 | 31 | # Pretrained imagenet model 32 | model = models.__dict__[args.arch](pretrained=True).to(device=device) 33 | # Freeze the model 34 | for p in model.parameters(): 35 | p.requires_grad_(False) 36 | 37 | # Image 38 | img_path = BytesIO(requests.get(args.img, timeout=5).content) if args.img.startswith("http") else args.img 39 | pil_img = Image.open(img_path, mode="r").convert("RGB") 40 | 41 | # Preprocess image 42 | img_tensor = normalize( 43 | to_tensor(resize(pil_img, (224, 224))), 44 | [0.485, 0.456, 0.406], 45 | [0.229, 0.224, 0.225], 46 | ).to(device=device) 47 | img_tensor.requires_grad_(True) 48 | 49 | if isinstance(args.method, str): 50 | cam_methods = args.method.split(",") 51 | else: 52 | cam_methods = [ 53 | "CAM", 54 | "GradCAM", 55 | "GradCAMpp", 56 | "SmoothGradCAMpp", 57 | "ScoreCAM", 58 | "SSCAM", 59 | "ISCAM", 60 | "XGradCAM", 61 | "LayerCAM", 62 | ] 63 | # Hook the corresponding layer in the model 64 | cam_extractors = [ 65 | methods.__dict__[name](model, target_layer=args.target, enable_hooks=False) for name in cam_methods 66 | ] 67 | 68 | # Homogenize number of elements in each row 69 | num_cols = math.ceil((len(cam_extractors) + 1) / args.rows) 70 | _, axes = plt.subplots(args.rows, num_cols, figsize=(6, 4)) 71 | # Display input 72 | ax = axes[0][0] if args.rows > 1 else axes[0] if num_cols > 1 else axes 73 | ax.imshow(pil_img) 74 | ax.set_title("Input", size=8) 75 | 76 | for idx, extractor in zip(range(1, len(cam_extractors) + 1), cam_extractors): 77 | extractor.enable_hooks() 78 | model.zero_grad() 79 | scores = model(img_tensor.unsqueeze(0)) 80 | 81 | # Select the class index 82 | class_idx = scores.squeeze(0).argmax().item() if args.class_idx is None else args.class_idx 83 | 84 | # Use the hooked data to compute activation map 85 | activation_map = extractor(class_idx, scores)[0].squeeze(0).cpu() 86 | 87 | # Clean data 88 | extractor.disable_hooks() 89 | extractor.remove_hooks() 90 | # Convert it to PIL image 91 | # The indexing below means first image in batch 92 | heatmap = to_pil_image(activation_map, mode="F") 93 | # Plot the result 94 | result = overlay_mask(pil_img, heatmap, alpha=args.alpha) 95 | 96 | ax = axes[idx // num_cols][idx % num_cols] if args.rows > 1 else axes[idx] if num_cols > 1 else axes 97 | 98 | ax.imshow(result) 99 | ax.set_title(extractor.__class__.__name__, size=8) 100 | 101 | # Clear axes 102 | if num_cols > 1: 103 | for _axes in axes: 104 | if args.rows > 1: 105 | for ax in _axes: 106 | ax.axis("off") 107 | else: 108 | _axes.axis("off") 109 | 110 | else: 111 | axes.axis("off") 112 | 113 | plt.tight_layout() 114 | if args.savefig: 115 | plt.savefig(args.savefig, dpi=200, transparent=True, bbox_inches="tight", pad_inches=0) 116 | plt.show(block=not args.noblock) 117 | 118 | 119 | if __name__ == "__main__": 120 | parser = argparse.ArgumentParser( 121 | description="Saliency Map comparison", 122 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 123 | ) 124 | parser.add_argument("--arch", type=str, default="resnet18", help="Name of the architecture") 125 | parser.add_argument( 126 | "--img", 127 | type=str, 128 | default="https://www.woopets.fr/assets/races/000/066/big-portrait/border-collie.jpg", 129 | help="The image to extract CAM from", 130 | ) 131 | parser.add_argument("--class-idx", type=int, default=232, help="Index of the class to inspect") 132 | parser.add_argument( 133 | "--device", 134 | type=str, 135 | default=None, 136 | help="Default device to perform computation on", 137 | ) 138 | parser.add_argument("--savefig", type=str, default=None, help="Path to save figure") 139 | parser.add_argument("--method", type=str, default=None, help="CAM method to use") 140 | parser.add_argument("--target", type=str, default=None, help="the target layer") 141 | parser.add_argument("--alpha", type=float, default=0.5, help="Transparency of the heatmap") 142 | parser.add_argument("--rows", type=int, default=1, help="Number of rows for the layout") 143 | parser.add_argument( 144 | "--noblock", 145 | dest="noblock", 146 | help="Disables blocking visualization", 147 | action="store_true", 148 | ) 149 | args = parser.parse_args() 150 | 151 | main(args) 152 | -------------------------------------------------------------------------------- /scripts/eval_latency.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2021-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | """ 7 | CAM latency benchmark 8 | """ 9 | 10 | import argparse 11 | import time 12 | 13 | import numpy as np 14 | import torch 15 | from torchvision import models 16 | 17 | from torchcam import methods 18 | 19 | 20 | def main(args): 21 | if args.device is None: 22 | args.device = "cuda:0" if torch.cuda.is_available() else "cpu" 23 | 24 | device = torch.device(args.device) 25 | 26 | # Pretrained imagenet model 27 | model = models.__dict__[args.arch](pretrained=True).to(device=device) 28 | # Freeze the model 29 | for p in model.parameters(): 30 | p.requires_grad_(False) 31 | 32 | # Input 33 | img_tensor = torch.rand((1, 3, args.size, args.size)).to(device=device) 34 | img_tensor.requires_grad_(True) 35 | 36 | # Warmup 37 | for _ in range(10): 38 | with torch.no_grad(): 39 | _ = model(img_tensor) 40 | 41 | timings = [] 42 | 43 | # Evaluation runs 44 | with methods.__dict__[args.method](model) as cam_extractor: 45 | for _ in range(args.it): 46 | scores = model(img_tensor) 47 | 48 | # Select the class index 49 | class_idx = scores.squeeze(0).argmax().item() if args.class_idx is None else args.class_idx 50 | 51 | # Use the hooked data to compute activation map 52 | start_ts = time.perf_counter() 53 | _ = cam_extractor(class_idx, scores) 54 | timings.append(time.perf_counter() - start_ts) 55 | 56 | timings_ = np.array(timings) 57 | print(f"{args.method} w/ {args.arch} ({args.it} runs on ({args.size}, {args.size}) inputs)") 58 | print(f"mean {1000 * timings_.mean():.2f}ms, std {1000 * timings_.std():.2f}ms") 59 | 60 | 61 | if __name__ == "__main__": 62 | parser = argparse.ArgumentParser( 63 | description="CAM method latency benchmark", 64 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 65 | ) 66 | parser.add_argument("method", type=str, help="CAM method to use") 67 | parser.add_argument( 68 | "--arch", 69 | type=str, 70 | default="resnet18", 71 | help="Name of the torchvision architecture", 72 | ) 73 | parser.add_argument("--size", type=int, default=224, help="The image input size") 74 | parser.add_argument("--class-idx", type=int, default=232, help="Index of the class to inspect") 75 | parser.add_argument( 76 | "--device", 77 | type=str, 78 | default=None, 79 | help="Default device to perform computation on", 80 | ) 81 | parser.add_argument("--it", type=int, default=100, help="Number of iterations to run") 82 | args = parser.parse_args() 83 | 84 | main(args) 85 | -------------------------------------------------------------------------------- /scripts/eval_perf.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2022-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | """ 7 | CAM performance evaluation 8 | """ 9 | 10 | import argparse 11 | import math 12 | import os 13 | from functools import partial 14 | from pathlib import Path 15 | 16 | import torch 17 | from torch.utils.data import SequentialSampler 18 | from torchvision import models 19 | from torchvision.datasets import ImageFolder 20 | from torchvision.transforms import transforms as T 21 | 22 | from torchcam import methods 23 | from torchcam.metrics import ClassificationMetric 24 | 25 | 26 | def main(args): 27 | if args.device is None: 28 | args.device = "cuda:0" if torch.cuda.is_available() else "cpu" 29 | 30 | device = torch.device(args.device) 31 | 32 | # Pretrained imagenet model 33 | model = models.__dict__[args.arch](pretrained=True).to(device=device) 34 | # Freeze the model 35 | for p in model.parameters(): 36 | p.requires_grad_(False) 37 | 38 | eval_tf = [] 39 | crop_pct = 0.875 40 | scale_size = min(math.floor(args.size / crop_pct), 320) 41 | if scale_size < 320: 42 | eval_tf.append(T.Resize(scale_size)) 43 | eval_tf.extend([ 44 | T.CenterCrop(args.size), 45 | T.PILToTensor(), 46 | T.ConvertImageDtype(torch.float32), 47 | T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), 48 | ]) 49 | 50 | ds = ImageFolder( 51 | Path(args.data_path).joinpath("val"), 52 | T.Compose(eval_tf), 53 | ) 54 | loader = torch.utils.data.DataLoader( 55 | ds, 56 | batch_size=args.batch_size, 57 | drop_last=False, 58 | sampler=SequentialSampler(ds), 59 | num_workers=args.workers, 60 | pin_memory=True, 61 | ) 62 | 63 | # Hook the corresponding layer in the model 64 | with methods.__dict__[args.method](model, args.target.split(",")) as cam_extractor: 65 | metric = ClassificationMetric(cam_extractor, partial(torch.softmax, dim=-1)) 66 | 67 | # Evaluation runs 68 | for x, _ in loader: 69 | model.zero_grad() 70 | x = x.to(device=device) 71 | x.requires_grad_(True) 72 | metric.update(x) 73 | 74 | print(f"{args.method} w/ {args.arch} (validation set of Imagenette on ({args.size}, {args.size}) inputs)") 75 | metrics_dict = metric.summary() 76 | print(f"Average Drop {metrics_dict['avg_drop']:.2%}, Increase in Confidence {metrics_dict['conf_increase']:.2%}") 77 | 78 | 79 | if __name__ == "__main__": 80 | parser = argparse.ArgumentParser( 81 | description="CAM method performance evaluation", 82 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 83 | ) 84 | parser.add_argument("data_path", type=str, help="path to dataset folder") 85 | parser.add_argument("method", type=str, help="CAM method to use") 86 | parser.add_argument( 87 | "--arch", 88 | type=str, 89 | default="mobilenet_v3_large", 90 | help="Name of the torchvision architecture", 91 | ) 92 | parser.add_argument("--target", type=str, default=None, help="Target layer name") 93 | parser.add_argument("--size", type=int, default=224, help="The image input size") 94 | parser.add_argument("-b", "--batch-size", default=32, type=int, help="batch size") 95 | parser.add_argument( 96 | "--device", 97 | type=str, 98 | default=None, 99 | help="Default device to perform computation on", 100 | ) 101 | parser.add_argument( 102 | "-j", 103 | "--workers", 104 | default=min(os.cpu_count(), 16), 105 | type=int, 106 | help="number of data loading workers", 107 | ) 108 | args = parser.parse_args() 109 | 110 | main(args) 111 | -------------------------------------------------------------------------------- /scripts/requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.20.0,<3.0.0 2 | torchvision>=0.4.0,<1.0.0 3 | -------------------------------------------------------------------------------- /scripts/results.csv: -------------------------------------------------------------------------------- 1 | method,architecture,input_shape,dataset,avg_drop,conf_increase 2 | CAM,mobilenet_v3_large,"(224, 224)",imagenette,nan,nan 3 | ScoreCAM,mobilenet_v3_large,"(224, 224)",imagenette,tbd,tbd 4 | SSCAM,mobilenet_v3_large,"(224, 224)",imagenette,tbd,tbd 5 | ISCAM,mobilenet_v3_large,"(224, 224)",imagenette,tbd,tbd 6 | GradCAM,mobilenet_v3_large,"(224, 224)",imagenette,0.4063,0.1368 7 | GradCAMpp,mobilenet_v3_large,"(224, 224)",imagenette,0.3320,0.1445 8 | SmoothGradCAMpp,mobilenet_v3_large,"(224, 224)",imagenette,0.3028,0.1478 9 | XGradCAM,mobilenet_v3_large,"(224, 224)",imagenette,0.4063,0.1368 10 | LayerCAM,mobilenet_v3_large,"(224, 224)",imagenette,0.2790,0.1712 11 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | 7 | import os 8 | from pathlib import Path 9 | 10 | from setuptools import setup 11 | 12 | PKG_NAME = "torchcam" 13 | VERSION = os.getenv("BUILD_VERSION", "0.4.1.dev0") 14 | 15 | 16 | if __name__ == "__main__": 17 | print(f"Building wheel {PKG_NAME}-{VERSION}") 18 | 19 | # Dynamically set the __version__ attribute 20 | cwd = Path(__file__).parent.absolute() 21 | with cwd.joinpath("torchcam", "version.py").open("w", encoding="utf-8") as f: 22 | f.write(f"__version__ = '{VERSION}'\n") 23 | 24 | setup(name=PKG_NAME, version=VERSION) 25 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from io import BytesIO 2 | 3 | import pytest 4 | import requests 5 | import torch 6 | from PIL import Image 7 | from torch import nn 8 | from torchvision.transforms.functional import normalize, resize, to_tensor 9 | 10 | 11 | @pytest.fixture(scope="session") 12 | def mock_img_tensor(): 13 | try: 14 | # Get a dog image 15 | url = "https://www.woopets.fr/assets/races/000/066/big-portrait/border-collie.jpg" 16 | response = requests.get(url, timeout=5) 17 | 18 | # Forward an image 19 | pil_img = Image.open(BytesIO(response.content), mode="r").convert("RGB") 20 | img_tensor = normalize( 21 | to_tensor(resize(pil_img, (224, 224))), 22 | [0.485, 0.456, 0.406], 23 | [0.229, 0.224, 0.225], 24 | ).unsqueeze(0) 25 | except ConnectionError: 26 | img_tensor = torch.rand((1, 3, 224, 224)) 27 | 28 | img_tensor.requires_grad_(True) 29 | return img_tensor 30 | 31 | 32 | @pytest.fixture(scope="session") 33 | def mock_video_tensor(): 34 | return torch.rand((1, 3, 8, 16, 16), requires_grad=True) 35 | 36 | 37 | @pytest.fixture(scope="session") 38 | def mock_video_model(): 39 | model = nn.Sequential( 40 | nn.Sequential( 41 | nn.Conv3d(3, 8, 3, padding=1), 42 | nn.ReLU(), 43 | nn.Conv3d(8, 16, 3, padding=1), 44 | nn.ReLU(), 45 | nn.AdaptiveAvgPool3d((1, 1, 1)), 46 | ), 47 | nn.Flatten(1), 48 | nn.Linear(16, 1), 49 | ) 50 | for p in model: 51 | p.requires_grad_(False) 52 | return model 53 | 54 | 55 | @pytest.fixture(scope="session") 56 | def mock_img_model(): 57 | model = nn.Sequential( 58 | nn.Sequential( 59 | nn.Conv2d(3, 8, 3, padding=1), 60 | nn.ReLU(), 61 | nn.Conv2d(8, 16, 3, padding=1), 62 | nn.ReLU(), 63 | nn.AdaptiveAvgPool2d((1, 1)), 64 | ), 65 | nn.Flatten(1), 66 | nn.Linear(16, 1), 67 | ) 68 | for p in model: 69 | p.requires_grad_(False) 70 | return model 71 | 72 | 73 | @pytest.fixture(scope="session") 74 | def mock_fullyconv_model(): 75 | model = nn.Sequential( 76 | nn.Sequential( 77 | nn.Conv2d(3, 8, 3, padding=1), 78 | nn.ReLU(), 79 | nn.Conv2d(8, 16, 3, padding=1), 80 | nn.ReLU(), 81 | nn.AdaptiveAvgPool2d((1, 1)), 82 | ), 83 | nn.Conv2d(16, 1, 1), 84 | nn.Flatten(1), 85 | ) 86 | for p in model: 87 | p.requires_grad_(False) 88 | return model 89 | -------------------------------------------------------------------------------- /tests/test_methods_activation.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | from torchvision.models import mobilenet_v2 4 | 5 | from torchcam.methods import activation 6 | 7 | 8 | def test_base_cam_constructor(): 9 | model = mobilenet_v2(weights=None).eval() 10 | for p in model.parameters(): 11 | p.requires_grad_(False) 12 | # Check that multiple target layers is disabled for base CAM 13 | with pytest.raises(ValueError): 14 | activation.CAM(model, ["classifier.1", "classifier.2"]) 15 | 16 | # FC layer checks 17 | with pytest.raises(TypeError): 18 | activation.CAM(model, fc_layer=3) 19 | 20 | 21 | def _verify_cam(activation_map, output_size): 22 | # Simple verifications 23 | assert isinstance(activation_map, torch.Tensor) 24 | assert activation_map.shape == output_size 25 | assert not torch.isnan(activation_map).any() 26 | 27 | 28 | @pytest.mark.parametrize( 29 | ( 30 | "cam_name", 31 | "target_layer", 32 | "fc_layer", 33 | "num_samples", 34 | "output_size", 35 | "batch_size", 36 | ), 37 | [ 38 | ("CAM", None, None, None, (7, 7), 1), 39 | ("CAM", None, None, None, (7, 7), 2), 40 | ("CAM", None, "classifier.1", None, (7, 7), 1), 41 | ("CAM", None, lambda m: m.classifier[1], None, (7, 7), 1), 42 | ("ScoreCAM", "features.16.conv.3", None, None, (7, 7), 1), 43 | ("ScoreCAM", lambda m: m.features[16].conv[3], None, None, (7, 7), 1), 44 | ("SSCAM", "features.16.conv.3", None, 4, (7, 7), 1), 45 | ("ISCAM", "features.16.conv.3", None, 4, (7, 7), 1), 46 | ], 47 | ) 48 | def test_img_cams( 49 | cam_name, 50 | target_layer, 51 | fc_layer, 52 | num_samples, 53 | output_size, 54 | batch_size, 55 | mock_img_tensor, 56 | ): 57 | model = mobilenet_v2(weights=None).eval() 58 | for p in model.parameters(): 59 | p.requires_grad_(False) 60 | kwargs = {} 61 | # Speed up testing by reducing the number of samples 62 | if isinstance(num_samples, int): 63 | kwargs["num_samples"] = num_samples 64 | 65 | if fc_layer is not None: 66 | kwargs["fc_layer"] = fc_layer(model) if callable(fc_layer) else fc_layer 67 | 68 | target_layer = target_layer(model) if callable(target_layer) else target_layer 69 | # Hook the corresponding layer in the model 70 | with activation.__dict__[cam_name](model, target_layer, **kwargs) as extractor, torch.no_grad(): 71 | scores = model(mock_img_tensor.repeat((batch_size,) + (1,) * (mock_img_tensor.ndim - 1))) 72 | # Use the hooked data to compute activation map 73 | _verify_cam(extractor(scores[0].argmax().item(), scores)[0], (batch_size, *output_size)) 74 | # Multiple class indices 75 | _verify_cam(extractor(list(range(batch_size)), scores)[0], (batch_size, *output_size)) 76 | 77 | 78 | def test_cam_conv1x1(mock_fullyconv_model): 79 | with activation.CAM(mock_fullyconv_model, fc_layer="1") as extractor, torch.no_grad(): 80 | scores = mock_fullyconv_model(torch.rand((1, 3, 32, 32))) 81 | # Use the hooked data to compute activation map 82 | _verify_cam(extractor(scores[0].argmax().item(), scores)[0], (1, 32, 32)) 83 | 84 | 85 | @pytest.mark.parametrize( 86 | ("cam_name", "target_layer", "num_samples", "output_size"), 87 | [ 88 | ("CAM", "0.3", None, (1, 8, 16, 16)), 89 | ("ScoreCAM", "0.3", None, (1, 8, 16, 16)), 90 | ("SSCAM", "0.3", 4, (1, 8, 16, 16)), 91 | ("ISCAM", "0.3", 4, (1, 8, 16, 16)), 92 | ], 93 | ) 94 | def test_video_cams( 95 | cam_name, 96 | target_layer, 97 | num_samples, 98 | output_size, 99 | mock_video_model, 100 | mock_video_tensor, 101 | ): 102 | model = mock_video_model.eval() 103 | kwargs = {} 104 | # Speed up testing by reducing the number of samples 105 | if isinstance(num_samples, int): 106 | kwargs["num_samples"] = num_samples 107 | 108 | # Hook the corresponding layer in the model 109 | with activation.__dict__[cam_name](model, target_layer, **kwargs) as extractor, torch.no_grad(): 110 | scores = model(mock_video_tensor) 111 | # Use the hooked data to compute activation map 112 | _verify_cam(extractor(scores[0].argmax().item(), scores)[0], output_size) 113 | -------------------------------------------------------------------------------- /tests/test_methods_core.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | 4 | from torchcam.methods import core 5 | 6 | 7 | def test_cam_constructor(mock_img_model): 8 | model = mock_img_model.eval() 9 | # Check that wrong target_layer raises an error 10 | with pytest.raises(ValueError): 11 | core._CAM(model, "3") 12 | 13 | # Wrong types 14 | with pytest.raises(TypeError): 15 | core._CAM(model, 3) 16 | with pytest.raises(TypeError): 17 | core._CAM(model, [3]) 18 | 19 | # Unrelated module 20 | with pytest.raises(ValueError): 21 | core._CAM(model, torch.nn.ReLU()) 22 | 23 | 24 | def test_cam_context_manager(mock_img_model): 25 | model = mock_img_model.eval() 26 | with core._CAM(model): 27 | # Model is hooked 28 | assert sum(len(mod._forward_hooks) for mod in model.modules()) == 1 29 | # Exit should remove hooks 30 | assert all(len(mod._forward_hooks) == 0 for mod in model.modules()) 31 | 32 | 33 | def test_cam_precheck(mock_img_model, mock_img_tensor): 34 | model = mock_img_model.eval() 35 | with core._CAM(model, "0.3") as extractor, torch.no_grad(): 36 | # Check missing forward raises Error 37 | with pytest.raises(AssertionError): 38 | extractor(0) 39 | 40 | # Correct forward 41 | model(mock_img_tensor) 42 | 43 | # Check incorrect class index 44 | with pytest.raises(ValueError): 45 | extractor(-1) 46 | 47 | # Check incorrect class index 48 | with pytest.raises(ValueError): 49 | extractor([-1]) 50 | 51 | # Check missing score 52 | if extractor._score_used: 53 | with pytest.raises(ValueError): 54 | extractor(0) 55 | 56 | 57 | @pytest.mark.parametrize( 58 | ("input_shape", "spatial_dims"), 59 | [ 60 | ((8, 8), None), 61 | ((8, 8, 8), None), 62 | ((8, 8, 8), 2), 63 | ((8, 8, 8, 8), None), 64 | ((8, 8, 8, 8), 3), 65 | ], 66 | ) 67 | def test_cam_normalize(input_shape, spatial_dims): 68 | input_tensor = torch.rand(input_shape) 69 | normalized_tensor = core._CAM._normalize(input_tensor, spatial_dims) 70 | # Shape check 71 | assert normalized_tensor.shape == input_shape 72 | # Value check 73 | assert not torch.any(torch.isnan(normalized_tensor)) 74 | assert torch.all(normalized_tensor <= 1) 75 | assert torch.all(normalized_tensor >= 0) 76 | 77 | 78 | def test_cam_remove_hooks(mock_img_model): 79 | model = mock_img_model.eval() 80 | with core._CAM(model, "0.3") as extractor: 81 | assert len(extractor.hook_handles) == 1 82 | # Check that there is only one hook on the model 83 | assert all(act is None for act in extractor.hook_a) 84 | with torch.no_grad(): 85 | _ = model(torch.rand((1, 3, 32, 32))) 86 | assert all(isinstance(act, torch.Tensor) for act in extractor.hook_a) 87 | 88 | # Remove it 89 | extractor.remove_hooks() 90 | assert len(extractor.hook_handles) == 0 91 | # Reset the hooked values 92 | extractor.reset_hooks() 93 | with torch.no_grad(): 94 | _ = model(torch.rand((1, 3, 32, 32))) 95 | assert all(act is None for act in extractor.hook_a) 96 | 97 | 98 | def test_cam_repr(mock_img_model): 99 | model = mock_img_model.eval() 100 | with core._CAM(model, "0.3") as extractor: 101 | assert repr(extractor) == "_CAM(target_layer=['0.3'])" 102 | 103 | 104 | def test_fuse_cams(): 105 | with pytest.raises(TypeError): 106 | core._CAM.fuse_cams(torch.zeros((3, 32, 32))) 107 | 108 | with pytest.raises(ValueError): 109 | core._CAM.fuse_cams([]) 110 | 111 | cams = [torch.rand((1, 32, 32)), torch.rand((1, 16, 16))] 112 | 113 | # Single CAM 114 | assert torch.equal(cams[0], core._CAM.fuse_cams(cams[:1])) 115 | 116 | # Fusion 117 | cam = core._CAM.fuse_cams(cams) 118 | assert isinstance(cam, torch.Tensor) 119 | assert cam.ndim == cams[0].ndim 120 | assert cam.shape == (1, 32, 32) 121 | 122 | # Specify target shape 123 | cam = core._CAM.fuse_cams(cams, (16, 16)) 124 | assert isinstance(cam, torch.Tensor) 125 | assert cam.ndim == cams[0].ndim 126 | assert cam.shape == (1, 16, 16) 127 | -------------------------------------------------------------------------------- /tests/test_methods_gradient.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | from torch import nn 4 | from torchvision.models import mobilenet_v2 5 | 6 | from torchcam.methods import gradient 7 | 8 | 9 | def _verify_cam(activation_map, output_size): 10 | # Simple verifications 11 | assert isinstance(activation_map, torch.Tensor) 12 | assert activation_map.shape == output_size 13 | assert not torch.isnan(activation_map).any() 14 | 15 | 16 | @pytest.mark.parametrize( 17 | ("cam_name", "target_layer", "output_size", "batch_size"), 18 | [ 19 | ("GradCAM", "features.18.0", (7, 7), 1), 20 | ("GradCAMpp", "features.18.0", (7, 7), 1), 21 | ("SmoothGradCAMpp", lambda m: m.features[18][0], (7, 7), 1), 22 | ("SmoothGradCAMpp", "features.18.0", (7, 7), 1), 23 | ("XGradCAM", "features.18.0", (7, 7), 1), 24 | ("LayerCAM", "features.18.0", (7, 7), 1), 25 | ("LayerCAM", "features.18.0", (7, 7), 2), 26 | ], 27 | ) 28 | def test_img_cams(cam_name, target_layer, output_size, batch_size, mock_img_tensor): 29 | model = mobilenet_v2(weights=None).eval() 30 | for p in model.parameters(): 31 | p.requires_grad_(False) 32 | 33 | target_layer = target_layer(model) if callable(target_layer) else target_layer 34 | # Hook the corresponding layer in the model 35 | with gradient.__dict__[cam_name](model, target_layer) as extractor: 36 | scores = model(mock_img_tensor.repeat((batch_size,) + (1,) * (mock_img_tensor.ndim - 1))) 37 | # Use the hooked data to compute activation map 38 | _verify_cam( 39 | extractor(scores[0].argmax().item(), scores, retain_graph=True)[0], 40 | (batch_size, *output_size), 41 | ) 42 | # Multiple class indices 43 | _verify_cam(extractor(list(range(batch_size)), scores)[0], (batch_size, *output_size)) 44 | 45 | # Inplace model 46 | model = nn.Sequential( 47 | nn.Conv2d(3, 8, 3, padding=1), 48 | nn.ReLU(), 49 | nn.Conv2d(8, 8, 3, padding=1), 50 | nn.ReLU(inplace=True), 51 | nn.AdaptiveAvgPool2d((1, 1)), 52 | nn.Flatten(1), 53 | nn.Linear(8, 10), 54 | ) 55 | for p in model.parameters(): 56 | p.requires_grad_(False) 57 | 58 | # Hook before the inplace ops 59 | with gradient.__dict__[cam_name](model, "2") as extractor: 60 | scores = model(mock_img_tensor) 61 | # Use the hooked data to compute activation map 62 | _verify_cam(extractor(scores[0].argmax().item(), scores)[0], (1, 224, 224)) 63 | 64 | 65 | @pytest.mark.parametrize( 66 | ("cam_name", "target_layer", "output_size"), 67 | [ 68 | ("GradCAM", "0.3", (1, 8, 16, 16)), 69 | ("GradCAMpp", "0.3", (1, 8, 16, 16)), 70 | ("SmoothGradCAMpp", "0.3", (1, 8, 16, 16)), 71 | ("XGradCAM", "0.3", (1, 8, 16, 16)), 72 | ("LayerCAM", "0.3", (1, 8, 16, 16)), 73 | ], 74 | ) 75 | def test_video_cams(cam_name, target_layer, output_size, mock_video_model, mock_video_tensor): 76 | model = mock_video_model.eval() 77 | # Hook the corresponding layer in the model 78 | with gradient.__dict__[cam_name](model, target_layer) as extractor: 79 | scores = model(mock_video_tensor) 80 | # Use the hooked data to compute activation map 81 | _verify_cam(extractor(scores[0].argmax().item(), scores)[0], output_size) 82 | 83 | 84 | def test_smoothgradcampp_repr(): 85 | model = mobilenet_v2(weights=None).eval() 86 | 87 | # Hook the corresponding layer in the model 88 | with gradient.SmoothGradCAMpp(model, "features.18.0") as extractor: 89 | assert repr(extractor) == "SmoothGradCAMpp(target_layer=['features.18.0'], num_samples=4, std=0.3)" 90 | 91 | 92 | def test_layercam_fuse_cams(): 93 | with pytest.raises(TypeError): 94 | gradient.LayerCAM.fuse_cams(torch.zeros((3, 32, 32))) 95 | 96 | with pytest.raises(ValueError): 97 | gradient.LayerCAM.fuse_cams([]) 98 | 99 | cams = [torch.rand((1, 32, 32)), torch.rand((1, 16, 16))] 100 | 101 | # Single CAM 102 | assert torch.equal(cams[0], gradient.LayerCAM.fuse_cams(cams[:1])) 103 | 104 | # Fusion 105 | cam = gradient.LayerCAM.fuse_cams(cams) 106 | assert isinstance(cam, torch.Tensor) 107 | assert cam.ndim == cams[0].ndim 108 | assert cam.shape == (1, 32, 32) 109 | 110 | # Specify target shape 111 | cam = gradient.LayerCAM.fuse_cams(cams, (16, 16)) 112 | assert isinstance(cam, torch.Tensor) 113 | assert cam.ndim == cams[0].ndim 114 | assert cam.shape == (1, 16, 16) 115 | -------------------------------------------------------------------------------- /tests/test_methods_utils.py: -------------------------------------------------------------------------------- 1 | from torchvision.models import mobilenet_v3_large, resnet18 2 | 3 | from torchcam.methods import _utils 4 | 5 | 6 | def test_locate_candidate_layer(mock_img_model): 7 | # ResNet-18 8 | mod = resnet18().eval() 9 | for p in mod.parameters(): 10 | p.requires_grad_(False) 11 | assert _utils.locate_candidate_layer(mod) == "layer4" 12 | 13 | # Mobilenet V3 Large 14 | mod = mobilenet_v3_large().eval() 15 | for p in mod.parameters(): 16 | p.requires_grad_(False) 17 | assert _utils.locate_candidate_layer(mod) == "features" 18 | 19 | # Custom model 20 | mod = mock_img_model.train() 21 | 22 | assert _utils.locate_candidate_layer(mod) == "0.3" 23 | # Check that the model is switched back to its origin mode afterwards 24 | assert mod.training 25 | 26 | 27 | def test_locate_linear_layer(mock_img_model): 28 | # ResNet-18 29 | mod = resnet18().eval() 30 | for p in mod.parameters(): 31 | p.requires_grad_(False) 32 | assert _utils.locate_linear_layer(mod) == "fc" 33 | 34 | # Custom model 35 | mod = mock_img_model 36 | assert _utils.locate_linear_layer(mod) == "2" 37 | -------------------------------------------------------------------------------- /tests/test_metrics.py: -------------------------------------------------------------------------------- 1 | from functools import partial 2 | 3 | import torch 4 | from torchvision.models import mobilenet_v3_small 5 | 6 | from torchcam import metrics 7 | from torchcam.methods import LayerCAM 8 | 9 | 10 | def test_classification_metric(): 11 | model = mobilenet_v3_small(weights=None) 12 | with LayerCAM(model, "features.12") as extractor: 13 | metric = metrics.ClassificationMetric(extractor, partial(torch.softmax, dim=-1)) 14 | 15 | # Fixed class 16 | metric.update(torch.rand((2, 3, 224, 224), dtype=torch.float32), class_idx=0) 17 | # Top predicted class 18 | metric.update(torch.rand((2, 3, 224, 224), dtype=torch.float32)) 19 | out = metric.summary() 20 | 21 | assert len(out) == 2 22 | assert all(0 <= v <= 1 for k, v in out.items()) 23 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from PIL import Image 3 | 4 | from torchcam import utils 5 | 6 | 7 | def test_overlay_mask(): 8 | img = Image.fromarray(np.zeros((4, 4, 3)).astype(np.uint8)) 9 | mask = Image.fromarray(255 * np.ones((4, 4)).astype(np.uint8)) 10 | 11 | overlayed = utils.overlay_mask(img, mask, alpha=0.7) 12 | 13 | # Check object type 14 | assert isinstance(overlayed, Image.Image) 15 | # Verify value 16 | assert np.all(np.asarray(overlayed)[..., 0] == 0) 17 | assert np.all(np.asarray(overlayed)[..., 1] == 0) 18 | assert np.all(np.asarray(overlayed)[..., 2] == 39) 19 | -------------------------------------------------------------------------------- /torchcam/__init__.py: -------------------------------------------------------------------------------- 1 | from contextlib import suppress 2 | from torchcam import methods, metrics, utils 3 | 4 | with suppress(ImportError): 5 | from .version import __version__ 6 | -------------------------------------------------------------------------------- /torchcam/methods/__init__.py: -------------------------------------------------------------------------------- 1 | from .activation import * 2 | from .gradient import * 3 | -------------------------------------------------------------------------------- /torchcam/methods/_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | from functools import partial 7 | from typing import List, Optional, Tuple 8 | 9 | import torch 10 | from torch import Tensor, nn 11 | 12 | __all__ = ["locate_candidate_layer", "locate_linear_layer"] 13 | 14 | 15 | def locate_candidate_layer(mod: nn.Module, input_shape: Tuple[int, ...] = (3, 224, 224)) -> Optional[str]: 16 | """Attempts to find a candidate layer to use for CAM extraction 17 | 18 | Args: 19 | mod: the module to inspect 20 | input_shape: the expected shape of input tensor excluding the batch dimension 21 | 22 | Returns: 23 | str: the candidate layer for CAM 24 | """ 25 | # Set module in eval mode 26 | module_mode = mod.training 27 | mod.eval() 28 | 29 | output_shapes: List[Tuple[Optional[str], Tuple[int, ...]]] = [] 30 | 31 | def _record_output_shape(_: nn.Module, _input: Tensor, output: Tensor, name: Optional[str] = None) -> None: 32 | """Activation hook.""" 33 | output_shapes.append((name, output.shape)) 34 | 35 | hook_handles: List[torch.utils.hooks.RemovableHandle] = [] 36 | # forward hook on all layers 37 | for n, m in mod.named_modules(): 38 | hook_handles.append(m.register_forward_hook(partial(_record_output_shape, name=n))) 39 | 40 | # forward empty 41 | with torch.no_grad(): 42 | _ = mod(torch.zeros((1, *input_shape), device=next(mod.parameters()).data.device)) 43 | 44 | # Remove all temporary hooks 45 | for handle in hook_handles: 46 | handle.remove() 47 | 48 | # Put back the model in the corresponding mode 49 | mod.training = module_mode 50 | 51 | # Check output shapes 52 | candidate_layer = None 53 | for layer_name, output_shape in reversed(output_shapes): 54 | # Stop before flattening or global pooling 55 | if len(output_shape) == (len(input_shape) + 1) and any(v != 1 for v in output_shape[2:]): 56 | candidate_layer = layer_name 57 | break 58 | 59 | return candidate_layer 60 | 61 | 62 | def locate_linear_layer(mod: nn.Module) -> Optional[str]: 63 | """Attempts to find a fully connecter layer to use for CAM extraction 64 | 65 | Args: 66 | mod: the module to inspect 67 | 68 | Returns: 69 | str: the candidate layer 70 | """ 71 | candidate_layer = None 72 | for layer_name, m in mod.named_modules(): 73 | if isinstance(m, nn.Linear): 74 | candidate_layer = layer_name 75 | break 76 | 77 | return candidate_layer 78 | -------------------------------------------------------------------------------- /torchcam/methods/core.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | import logging 7 | import sys 8 | from abc import abstractmethod 9 | from functools import partial 10 | from types import TracebackType 11 | from typing import Any, List, Optional, Tuple, Type, Union 12 | 13 | import torch 14 | import torch.nn.functional as F 15 | from torch import Tensor, nn 16 | 17 | from ._utils import locate_candidate_layer 18 | 19 | __all__ = ["_CAM"] 20 | 21 | logger = logging.getLogger(__name__) 22 | logger.setLevel(logging.DEBUG) 23 | stream_handler = logging.StreamHandler(sys.stdout) 24 | log_formatter = logging.Formatter("%(levelname)s: %(message)s") 25 | stream_handler.setFormatter(log_formatter) 26 | logger.addHandler(stream_handler) 27 | 28 | 29 | class _CAM: 30 | """Implements a class activation map extractor 31 | 32 | Args: 33 | model: input model 34 | target_layer: either the target layer itself or its name 35 | input_shape: shape of the expected input tensor excluding the batch dimension 36 | enable_hooks: should hooks be enabled by default 37 | """ 38 | 39 | def __init__( 40 | self, 41 | model: nn.Module, 42 | target_layer: Optional[Union[Union[nn.Module, str], List[Union[nn.Module, str]]]] = None, 43 | input_shape: Tuple[int, ...] = (3, 224, 224), 44 | enable_hooks: bool = True, 45 | ) -> None: 46 | # Obtain a mapping from module name to module instance for each layer in the model 47 | self.submodule_dict = dict(model.named_modules()) 48 | 49 | if isinstance(target_layer, str): 50 | target_names = [target_layer] 51 | elif isinstance(target_layer, nn.Module): 52 | # Find the location of the module 53 | target_names = [self._resolve_layer_name(target_layer)] 54 | elif isinstance(target_layer, list): 55 | if any(not isinstance(elt, (str, nn.Module)) for elt in target_layer): 56 | raise TypeError("invalid argument type for `target_layer`") 57 | target_names = [ 58 | self._resolve_layer_name(layer) if isinstance(layer, nn.Module) else layer for layer in target_layer 59 | ] 60 | elif target_layer is None: 61 | # If the layer is not specified, try automatic resolution 62 | target_name = locate_candidate_layer(model, input_shape) 63 | # Warn the user of the choice 64 | if isinstance(target_name, str): 65 | logger.warning(f"no value was provided for `target_layer`, thus set to '{target_name}'.") 66 | target_names = [target_name] 67 | else: 68 | raise ValueError("unable to resolve `target_layer` automatically, please specify its value.") 69 | else: 70 | raise TypeError("invalid argument type for `target_layer`") 71 | 72 | if any(name not in self.submodule_dict for name in target_names): 73 | raise ValueError(f"Unable to find all submodules {target_names} in the model") 74 | self.target_names = target_names 75 | self.model = model 76 | # Init hooks 77 | self.reset_hooks() 78 | self.hook_handles: List[torch.utils.hooks.RemovableHandle] = [] 79 | # Forward hook 80 | for idx, name in enumerate(self.target_names): 81 | self.hook_handles.append(self.submodule_dict[name].register_forward_hook(partial(self._hook_a, idx=idx))) 82 | # Enable hooks 83 | self._hooks_enabled = enable_hooks 84 | # Should ReLU be used before normalization 85 | self._relu = False 86 | # Model output is used by the extractor 87 | self._score_used = False 88 | 89 | def enable_hooks(self) -> None: 90 | """Enable hooks.""" 91 | self._hooks_enabled = True 92 | 93 | def disable_hooks(self) -> None: 94 | """Disable hooks.""" 95 | self._hooks_enabled = False 96 | 97 | def __enter__(self) -> "_CAM": 98 | return self 99 | 100 | def __exit__( 101 | self, 102 | exct_type: Union[Type[BaseException], None], 103 | exce_value: Union[BaseException, None], 104 | traceback: Union[TracebackType, None], 105 | ) -> None: 106 | self.remove_hooks() 107 | self.reset_hooks() 108 | 109 | def _resolve_layer_name(self, target_layer: nn.Module) -> str: 110 | """Resolves the name of a given layer inside the hooked model.""" 111 | found = False 112 | target_name: str 113 | for k, v in self.submodule_dict.items(): 114 | if id(v) == id(target_layer): 115 | target_name = k 116 | found = True 117 | break 118 | if not found: 119 | raise ValueError("unable to locate module inside the specified model.") 120 | 121 | return target_name 122 | 123 | def _hook_a(self, _: nn.Module, _input: Tuple[Tensor, ...], output: Tensor, idx: int = 0) -> None: 124 | """Activation hook.""" 125 | if self._hooks_enabled: 126 | self.hook_a[idx] = output.data 127 | 128 | def reset_hooks(self) -> None: 129 | """Clear stored activation and gradients.""" 130 | self.hook_a: List[Optional[Tensor]] = [None] * len(self.target_names) 131 | self.hook_g: List[Optional[Tensor]] = [None] * len(self.target_names) 132 | 133 | def remove_hooks(self) -> None: 134 | """Clear model hooks.""" 135 | for handle in self.hook_handles: 136 | handle.remove() 137 | self.hook_handles.clear() 138 | 139 | @staticmethod 140 | @torch.no_grad() 141 | def _normalize(cams: Tensor, spatial_dims: Optional[int] = None, eps: float = 1e-8) -> Tensor: 142 | """CAM normalization.""" 143 | spatial_dims = cams.ndim - 1 if spatial_dims is None else spatial_dims 144 | cams.sub_(cams.flatten(start_dim=-spatial_dims).min(-1).values[(...,) + (None,) * spatial_dims]) 145 | # Avoid division by zero 146 | cams.div_(cams.flatten(start_dim=-spatial_dims).max(-1).values[(...,) + (None,) * spatial_dims] + eps) 147 | 148 | return cams 149 | 150 | @abstractmethod 151 | def _get_weights(self, class_idx: Union[int, List[int]], *args: Any, **kwargs: Any) -> List[Tensor]: 152 | raise NotImplementedError 153 | 154 | def _precheck(self, class_idx: Union[int, List[int]], scores: Optional[Tensor] = None) -> None: 155 | """Check for invalid computation cases.""" 156 | for fmap in self.hook_a: 157 | # Check that forward has already occurred 158 | if not isinstance(fmap, Tensor): 159 | raise AssertionError("Inputs need to be forwarded in the model for the conv features to be hooked") 160 | # Check batch size 161 | if not isinstance(class_idx, int) and fmap.shape[0] != len(class_idx): 162 | raise ValueError("expected batch size and length of `class_idx` to be the same.") 163 | 164 | # Check class_idx value 165 | if (not isinstance(class_idx, int) or class_idx < 0) and ( 166 | not isinstance(class_idx, list) or any(_idx < 0 for _idx in class_idx) 167 | ): 168 | raise ValueError("Incorrect `class_idx` argument value") 169 | 170 | # Check scores arg 171 | if self._score_used and not isinstance(scores, torch.Tensor): 172 | raise ValueError("model output scores is required to be passed to compute CAMs") 173 | 174 | def __call__( 175 | self, 176 | class_idx: Union[int, List[int]], 177 | scores: Optional[Tensor] = None, 178 | normalized: bool = True, 179 | **kwargs: Any, 180 | ) -> List[Tensor]: 181 | # Integrity check 182 | self._precheck(class_idx, scores) 183 | 184 | # Compute CAM 185 | return self.compute_cams(class_idx, scores, normalized, **kwargs) 186 | 187 | def compute_cams( 188 | self, 189 | class_idx: Union[int, List[int]], 190 | scores: Optional[Tensor] = None, 191 | normalized: bool = True, 192 | **kwargs: Any, 193 | ) -> List[Tensor]: 194 | """Compute the CAM for a specific output class. 195 | 196 | Args: 197 | class_idx: the class index of the class to compute the CAM of, or a list of class indices. If it is a list, 198 | the list needs to have valid class indices and have a length equal to the batch size. 199 | scores: forward output scores of the hooked model of shape (N, K) 200 | normalized: whether the CAM should be normalized 201 | kwargs: keyword args of `_get_weights` method 202 | 203 | Returns: 204 | list of class activation maps of shape (N, H, W), one for each hooked layer. If a list of class indices 205 | was passed to arg `class_idx`, the k-th element along the batch axis will be the activation map for 206 | the k-th element of the input batch for class index equal to the k-th element of `class_idx`. 207 | """ 208 | # Get map weight & unsqueeze it 209 | weights = self._get_weights(class_idx, scores, **kwargs) 210 | 211 | cams: List[Tensor] = [] 212 | 213 | with torch.no_grad(): 214 | for weight, activation in zip(weights, self.hook_a): 215 | missing_dims = activation.ndim - weight.ndim # type: ignore[union-attr] 216 | weight = weight[(...,) + (None,) * missing_dims] 217 | 218 | # Perform the weighted combination to get the CAM 219 | cam = torch.nansum(weight * activation, dim=1) 220 | 221 | if self._relu: 222 | cam = F.relu(cam, inplace=True) 223 | 224 | # Normalize the CAM 225 | if normalized: 226 | cam = self._normalize(cam) 227 | 228 | cams.append(cam) 229 | 230 | return cams 231 | 232 | def extra_repr(self) -> str: 233 | return f"target_layer={self.target_names}" 234 | 235 | def __repr__(self) -> str: 236 | return f"{self.__class__.__name__}({self.extra_repr()})" 237 | 238 | @classmethod 239 | def fuse_cams(cls, cams: List[Tensor], target_shape: Optional[Tuple[int, int]] = None) -> Tensor: 240 | """Fuse class activation maps from different layers. 241 | 242 | Args: 243 | cams: the list of activation maps (for the same input) 244 | target_shape: expected spatial shape of the fused activation map (default to the biggest spatial shape 245 | among input maps) 246 | 247 | Returns: 248 | torch.Tensor: fused class activation map 249 | """ 250 | if not isinstance(cams, list) or any(not isinstance(elt, Tensor) for elt in cams): 251 | raise TypeError("invalid argument type for `cams`") 252 | 253 | if len(cams) == 0: 254 | raise ValueError("argument `cams` cannot be an empty list") 255 | if len(cams) == 1: 256 | return cams[0] 257 | # Resize to the biggest CAM if no value was provided for `target_shape` 258 | if isinstance(target_shape, tuple): 259 | shape = target_shape 260 | else: 261 | shape = tuple(map(max, zip(*[tuple(cam.shape[1:]) for cam in cams]))) 262 | # Scale cams 263 | scaled_cams = cls._scale_cams(cams) 264 | return cls._fuse_cams(scaled_cams, shape) 265 | 266 | @staticmethod 267 | def _scale_cams(cams: List[Tensor]) -> List[Tensor]: 268 | return cams 269 | 270 | @staticmethod 271 | def _fuse_cams(cams: List[Tensor], target_shape: Tuple[int, int]) -> Tensor: 272 | # Interpolate all CAMs 273 | interpolation_mode = "bilinear" if cams[0].ndim == 3 else "trilinear" if cams[0].ndim == 4 else "nearest" 274 | scaled_cams = [ 275 | F.interpolate( 276 | cam.unsqueeze(1), 277 | target_shape, 278 | mode=interpolation_mode, 279 | align_corners=False, 280 | ) 281 | for cam in cams 282 | ] 283 | 284 | # Fuse them 285 | return torch.stack(scaled_cams).max(dim=0).values.squeeze(1) 286 | -------------------------------------------------------------------------------- /torchcam/methods/gradient.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | from functools import partial 7 | from typing import Any, List, Optional, Tuple, Union 8 | 9 | import torch 10 | from torch import Tensor, nn 11 | 12 | from .core import _CAM 13 | 14 | __all__ = ["GradCAM", "GradCAMpp", "LayerCAM", "SmoothGradCAMpp", "XGradCAM"] 15 | 16 | 17 | class _GradCAM(_CAM): 18 | """Implements a gradient-based class activation map extractor. 19 | 20 | Args: 21 | model: input model 22 | target_layer: either the target layer itself or its name, or a list of those 23 | input_shape: shape of the expected input tensor excluding the batch dimension 24 | """ 25 | 26 | def __init__( 27 | self, 28 | model: nn.Module, 29 | target_layer: Optional[Union[Union[nn.Module, str], List[Union[nn.Module, str]]]] = None, 30 | input_shape: Tuple[int, ...] = (3, 224, 224), 31 | **kwargs: Any, 32 | ) -> None: 33 | super().__init__(model, target_layer, input_shape, **kwargs) 34 | # Ensure ReLU is applied before normalization 35 | self._relu = True 36 | # Model output is used by the extractor 37 | self._score_used = True 38 | for idx, name in enumerate(self.target_names): 39 | # Trick to avoid issues with inplace operations cf. https://github.com/pytorch/pytorch/issues/61519 40 | self.hook_handles.append(self.submodule_dict[name].register_forward_hook(partial(self._hook_g, idx=idx))) 41 | 42 | def _store_grad(self, grad: Tensor, idx: int = 0) -> None: 43 | if self._hooks_enabled: 44 | self.hook_g[idx] = grad.data 45 | 46 | def _hook_g(self, _: nn.Module, _input: Tuple[Tensor, ...], output: Tensor, idx: int = 0) -> None: 47 | """Gradient hook""" 48 | if self._hooks_enabled: 49 | self.hook_handles.append(output.register_hook(partial(self._store_grad, idx=idx))) 50 | 51 | def _backprop( 52 | self, 53 | scores: Tensor, 54 | class_idx: Union[int, List[int]], 55 | retain_graph: bool = False, 56 | ) -> None: 57 | """Backpropagate the loss for a specific output class""" 58 | # Backpropagate to get the gradients on the hooked layer 59 | if isinstance(class_idx, int): 60 | loss = scores[:, class_idx].sum() 61 | else: 62 | loss = scores.gather(1, torch.tensor(class_idx, device=scores.device).view(-1, 1)).sum() 63 | self.model.zero_grad() 64 | loss.backward(retain_graph=retain_graph) 65 | 66 | 67 | class GradCAM(_GradCAM): 68 | r"""Implements a class activation map extractor as described in `"Grad-CAM: Visual Explanations from Deep Networks 69 | via Gradient-based Localization" `_. 70 | 71 | The localization map is computed as follows: 72 | 73 | .. math:: 74 | L^{(c)}_{Grad-CAM}(x, y) = ReLU\Big(\sum\limits_k w_k^{(c)} A_k(x, y)\Big) 75 | 76 | with the coefficient :math:`w_k^{(c)}` being defined as: 77 | 78 | .. math:: 79 | w_k^{(c)} = \frac{1}{H \cdot W} \sum\limits_{i=1}^H \sum\limits_{j=1}^W 80 | \frac{\partial Y^{(c)}}{\partial A_k(i, j)} 81 | 82 | where :math:`A_k(x, y)` is the activation of node :math:`k` in the target layer of the model at 83 | position :math:`(x, y)`, 84 | and :math:`Y^{(c)}` is the model output score for class :math:`c` before softmax. 85 | 86 | >>> from torchvision.models import resnet18 87 | >>> from torchcam.methods import GradCAM 88 | >>> model = resnet18(pretrained=True).eval() 89 | >>> cam = GradCAM(model, 'layer4') 90 | >>> scores = model(input_tensor) 91 | >>> cam(class_idx=100, scores=scores) 92 | 93 | Args: 94 | model: input model 95 | target_layer: either the target layer itself or its name, or a list of those 96 | input_shape: shape of the expected input tensor excluding the batch dimension 97 | """ 98 | 99 | def _get_weights(self, class_idx: Union[int, List[int]], scores: Tensor, **kwargs: Any) -> List[Tensor]: 100 | """Computes the weight coefficients of the hooked activation maps.""" 101 | # Backpropagate 102 | self._backprop(scores, class_idx, **kwargs) 103 | 104 | self.hook_g: List[Tensor] # type: ignore[assignment] 105 | # Global average pool the gradients over spatial dimensions 106 | return [grad.flatten(2).mean(-1) for grad in self.hook_g] 107 | 108 | 109 | class GradCAMpp(_GradCAM): 110 | r"""Implements a class activation map extractor as described in `"Grad-CAM++: Improved Visual Explanations for 111 | Deep Convolutional Networks" `_. 112 | 113 | The localization map is computed as follows: 114 | 115 | .. math:: 116 | L^{(c)}_{Grad-CAM++}(x, y) = \sum\limits_k w_k^{(c)} A_k(x, y) 117 | 118 | with the coefficient :math:`w_k^{(c)}` being defined as: 119 | 120 | .. math:: 121 | w_k^{(c)} = \sum\limits_{i=1}^H \sum\limits_{j=1}^W \alpha_k^{(c)}(i, j) \cdot 122 | ReLU\Big(\frac{\partial Y^{(c)}}{\partial A_k(i, j)}\Big) 123 | 124 | where :math:`A_k(x, y)` is the activation of node :math:`k` in the target layer of the model at 125 | position :math:`(x, y)`, 126 | :math:`Y^{(c)}` is the model output score for class :math:`c` before softmax, 127 | and :math:`\alpha_k^{(c)}(i, j)` being defined as: 128 | 129 | .. math:: 130 | \alpha_k^{(c)}(i, j) = \frac{1}{\sum\limits_{i, j} \frac{\partial Y^{(c)}}{\partial A_k(i, j)}} 131 | = \frac{\frac{\partial^2 Y^{(c)}}{(\partial A_k(i,j))^2}}{2 \cdot 132 | \frac{\partial^2 Y^{(c)}}{(\partial A_k(i,j))^2} + \sum\limits_{a,b} A_k (a,b) \cdot 133 | \frac{\partial^3 Y^{(c)}}{(\partial A_k(i,j))^3}} 134 | 135 | if :math:`\frac{\partial Y^{(c)}}{\partial A_k(i, j)} = 1` else :math:`0`. 136 | 137 | >>> from torchvision.models import resnet18 138 | >>> from torchcam.methods import GradCAMpp 139 | >>> model = resnet18(pretrained=True).eval() 140 | >>> cam = GradCAMpp(model, 'layer4') 141 | >>> scores = model(input_tensor) 142 | >>> cam(class_idx=100, scores=scores) 143 | 144 | Args: 145 | model: input model 146 | target_layer: either the target layer itself or its name, or a list of those 147 | input_shape: shape of the expected input tensor excluding the batch dimension 148 | """ 149 | 150 | def _get_weights( 151 | self, 152 | class_idx: Union[int, List[int]], 153 | scores: Tensor, 154 | eps: float = 1e-8, 155 | **kwargs: Any, 156 | ) -> List[Tensor]: 157 | """Computes the weight coefficients of the hooked activation maps.""" 158 | # Backpropagate 159 | self._backprop(scores, class_idx, **kwargs) 160 | self.hook_a: List[Tensor] # type: ignore[assignment] 161 | self.hook_g: List[Tensor] # type: ignore[assignment] 162 | # Alpha coefficient for each pixel 163 | grad_2 = [grad.pow(2) for grad in self.hook_g] 164 | grad_3 = [g2 * grad for g2, grad in zip(grad_2, self.hook_g)] 165 | # Watch out for NaNs produced by underflow 166 | spatial_dims = self.hook_a[0].ndim - 2 167 | denom = [ 168 | 2 * g2 + (g3 * act).flatten(2).sum(-1)[(...,) + (None,) * spatial_dims] 169 | for g2, g3, act in zip(grad_2, grad_3, self.hook_a) 170 | ] 171 | nan_mask = [g2 > 0 for g2 in grad_2] 172 | alpha = grad_2 173 | for idx, d, mask in zip(range(len(grad_2)), denom, nan_mask): 174 | alpha[idx][mask].div_(d[mask] + eps) 175 | 176 | # Apply pixel coefficient in each weight 177 | return [a.mul_(torch.relu(grad)).flatten(2).sum(-1) for a, grad in zip(alpha, self.hook_g)] 178 | 179 | 180 | class SmoothGradCAMpp(_GradCAM): 181 | r"""Implements a class activation map extractor as described in `"Smooth Grad-CAM++: An Enhanced Inference Level 182 | Visualization Technique for Deep Convolutional Neural Network Models" `_ 183 | with a personal correction to the paper (alpha coefficient numerator). 184 | 185 | The localization map is computed as follows: 186 | 187 | .. math:: 188 | L^{(c)}_{Smooth Grad-CAM++}(x, y) = \sum\limits_k w_k^{(c)} A_k(x, y) 189 | 190 | with the coefficient :math:`w_k^{(c)}` being defined as: 191 | 192 | .. math:: 193 | w_k^{(c)} = \sum\limits_{i=1}^H \sum\limits_{j=1}^W \alpha_k^{(c)}(i, j) \cdot 194 | ReLU\Big(\frac{\partial Y^{(c)}}{\partial A_k(i, j)}\Big) 195 | 196 | where :math:`A_k(x, y)` is the activation of node :math:`k` in the target layer of the model at 197 | position :math:`(x, y)`, 198 | :math:`Y^{(c)}` is the model output score for class :math:`c` before softmax, 199 | and :math:`\alpha_k^{(c)}(i, j)` being defined as: 200 | 201 | .. math:: 202 | \alpha_k^{(c)}(i, j) 203 | = \frac{\frac{\partial^2 Y^{(c)}}{(\partial A_k(i,j))^2}}{2 \cdot 204 | \frac{\partial^2 Y^{(c)}}{(\partial A_k(i,j))^2} + \sum\limits_{a,b} A_k (a,b) \cdot 205 | \frac{\partial^3 Y^{(c)}}{(\partial A_k(i,j))^3}} 206 | = \frac{\frac{1}{n} \sum\limits_{m=1}^n D^{(c, 2)}_k(i, j)}{ 207 | \frac{2}{n} \sum\limits_{m=1}^n D^{(c, 2)}_k(i, j) + \sum\limits_{a,b} A_k (a,b) \cdot 208 | \frac{1}{n} \sum\limits_{m=1}^n D^{(c, 3)}_k(i, j)} 209 | 210 | if :math:`\frac{\partial Y^{(c)}}{\partial A_k(i, j)} = 1` else :math:`0`. Here :math:`D^{(c, p)}_k(i, j)` 211 | refers to the p-th partial derivative of the class score of class :math:`c` relatively to the activation in layer 212 | :math:`k` at position :math:`(i, j)`, and :math:`n` is the number of samples used to get the gradient estimate. 213 | 214 | Please note the difference in the numerator of :math:`\alpha_k^{(c)}(i, j)`, 215 | which is actually :math:`\frac{1}{n} \sum\limits_{k=1}^n D^{(c, 1)}_k(i,j)` in the paper. 216 | 217 | >>> from torchvision.models import resnet18 218 | >>> from torchcam.methods import SmoothGradCAMpp 219 | >>> model = resnet18(pretrained=True).eval() 220 | >>> cam = SmoothGradCAMpp(model, 'layer4') 221 | >>> scores = model(input_tensor) 222 | >>> cam(class_idx=100) 223 | 224 | Args: 225 | model: input model 226 | target_layer: either the target layer itself or its name, or a list of those 227 | num_samples: number of samples to use for smoothing 228 | std: standard deviation of the noise 229 | input_shape: shape of the expected input tensor excluding the batch dimension 230 | """ 231 | 232 | def __init__( 233 | self, 234 | model: nn.Module, 235 | target_layer: Optional[Union[Union[nn.Module, str], List[Union[nn.Module, str]]]] = None, 236 | num_samples: int = 4, 237 | std: float = 0.3, 238 | input_shape: Tuple[int, ...] = (3, 224, 224), 239 | **kwargs: Any, 240 | ) -> None: 241 | super().__init__(model, target_layer, input_shape, **kwargs) 242 | # Model scores is not used by the extractor 243 | self._score_used = False 244 | 245 | # Input hook 246 | self.hook_handles.append(model.register_forward_pre_hook(self._store_input)) # type: ignore[arg-type] 247 | # Noise distribution 248 | self.num_samples = num_samples 249 | self.std = std 250 | self._distrib = torch.distributions.normal.Normal(0, self.std) 251 | # Specific input hook updater 252 | self._ihook_enabled = True 253 | 254 | def _store_input(self, _: nn.Module, input_: Tensor) -> None: 255 | """Store model input tensor.""" 256 | if self._ihook_enabled: 257 | self._input = input_[0].data.clone() 258 | 259 | def _get_weights( 260 | self, 261 | class_idx: Union[int, List[int]], 262 | _: Union[Tensor, None] = None, 263 | eps: float = 1e-8, 264 | **kwargs: Any, 265 | ) -> List[Tensor]: 266 | """Computes the weight coefficients of the hooked activation maps.""" 267 | # Disable input update 268 | self._ihook_enabled = False 269 | # Keep initial activation 270 | self.hook_a: List[Tensor] # type: ignore[assignment] 271 | self.hook_g: List[Tensor] # type: ignore[assignment] 272 | init_fmap = [act.clone() for act in self.hook_a] 273 | # Initialize our gradient estimates 274 | grad_2 = [torch.zeros_like(act) for act in self.hook_a] 275 | grad_3 = [torch.zeros_like(act) for act in self.hook_a] 276 | # Perform the operations N times 277 | for _idx in range(self.num_samples): 278 | # Add noise 279 | noisy_input = self._input + self._distrib.sample(self._input.size()).to(device=self._input.device) 280 | noisy_input.requires_grad_(True) 281 | # Forward & Backward 282 | out = self.model(noisy_input) 283 | self.model.zero_grad() 284 | self._backprop(out, class_idx, **kwargs) 285 | 286 | # Sum partial derivatives 287 | grad_2 = [g2.add_(grad.pow(2)) for g2, grad in zip(grad_2, self.hook_g)] 288 | grad_3 = [g3.add_(grad.pow(3)) for g3, grad in zip(grad_3, self.hook_g)] 289 | 290 | # Reenable input update 291 | self._ihook_enabled = True 292 | 293 | # Average the gradient estimates 294 | grad_2 = [g2.div_(self.num_samples) for g2 in grad_2] 295 | grad_3 = [g3.div_(self.num_samples) for g3 in grad_3] 296 | 297 | # Alpha coefficient for each pixel 298 | spatial_dims = self.hook_a[0].ndim - 2 299 | alpha = [ 300 | g2 / (2 * g2 + (g3 * act).flatten(2).sum(-1)[(...,) + (None,) * spatial_dims] + eps) 301 | for g2, g3, act in zip(grad_2, grad_3, init_fmap) 302 | ] 303 | 304 | # Apply pixel coefficient in each weight 305 | return [a.mul_(torch.relu(grad)).flatten(2).sum(-1) for a, grad in zip(alpha, self.hook_g)] 306 | 307 | def extra_repr(self) -> str: 308 | return f"target_layer={self.target_names}, num_samples={self.num_samples}, std={self.std}" 309 | 310 | 311 | class XGradCAM(_GradCAM): 312 | r"""Implements a class activation map extractor as described in `"Axiom-based Grad-CAM: Towards Accurate 313 | Visualization and Explanation of CNNs" `_. 314 | 315 | The localization map is computed as follows: 316 | 317 | .. math:: 318 | L^{(c)}_{XGrad-CAM}(x, y) = ReLU\Big(\sum\limits_k w_k^{(c)} A_k(x, y)\Big) 319 | 320 | with the coefficient :math:`w_k^{(c)}` being defined as: 321 | 322 | .. math:: 323 | w_k^{(c)} = \sum\limits_{i=1}^H \sum\limits_{j=1}^W 324 | \Big( \frac{\partial Y^{(c)}}{\partial A_k(i, j)} \cdot 325 | \frac{A_k(i, j)}{\sum\limits_{m=1}^H \sum\limits_{n=1}^W A_k(m, n)} \Big) 326 | 327 | where :math:`A_k(x, y)` is the activation of node :math:`k` in the target layer of the model at 328 | position :math:`(x, y)`, 329 | and :math:`Y^{(c)}` is the model output score for class :math:`c` before softmax. 330 | 331 | >>> from torchvision.models import resnet18 332 | >>> from torchcam.methods import XGradCAM 333 | >>> model = resnet18(pretrained=True).eval() 334 | >>> cam = XGradCAM(model, 'layer4') 335 | >>> scores = model(input_tensor) 336 | >>> cam(class_idx=100, scores=scores) 337 | 338 | Args: 339 | model: input model 340 | target_layer: either the target layer itself or its name, or a list of those 341 | input_shape: shape of the expected input tensor excluding the batch dimension 342 | """ 343 | 344 | def _get_weights( 345 | self, 346 | class_idx: Union[int, List[int]], 347 | scores: Tensor, 348 | eps: float = 1e-8, 349 | **kwargs: Any, 350 | ) -> List[Tensor]: 351 | """Computes the weight coefficients of the hooked activation maps.""" 352 | # Backpropagate 353 | self._backprop(scores, class_idx, **kwargs) 354 | 355 | self.hook_a: List[Tensor] # type: ignore[assignment] 356 | self.hook_g: List[Tensor] # type: ignore[assignment] 357 | return [ 358 | (grad * act).flatten(2).sum(-1) / act.flatten(2).sum(-1).add(eps) 359 | for act, grad in zip(self.hook_a, self.hook_g) 360 | ] 361 | 362 | 363 | class LayerCAM(_GradCAM): 364 | r"""Implements a class activation map extractor as described in `"LayerCAM: Exploring Hierarchical Class Activation 365 | Maps for Localization" `_. 366 | 367 | The localization map is computed as follows: 368 | 369 | .. math:: 370 | L^{(c)}_{Layer-CAM}(x, y) = ReLU\Big(\sum\limits_k w_k^{(c)}(x, y) \cdot A_k(x, y)\Big) 371 | 372 | with the coefficient :math:`w_k^{(c)}(x, y)` being defined as: 373 | 374 | .. math:: 375 | w_k^{(c)}(x, y) = ReLU\Big(\frac{\partial Y^{(c)}}{\partial A_k(i, j)}(x, y)\Big) 376 | 377 | where :math:`A_k(x, y)` is the activation of node :math:`k` in the target layer of the model at 378 | position :math:`(x, y)`, 379 | and :math:`Y^{(c)}` is the model output score for class :math:`c` before softmax. 380 | 381 | >>> from torchvision.models import resnet18 382 | >>> from torchcam.methods import LayerCAM 383 | >>> model = resnet18(pretrained=True).eval() 384 | >>> extractor = LayerCAM(model, 'layer4') 385 | >>> scores = model(input_tensor) 386 | >>> cams = extractor(class_idx=100, scores=scores) 387 | >>> fused_cam = extractor.fuse_cams(cams) 388 | 389 | Args: 390 | model: input model 391 | target_layer: either the target layer itself or its name, or a list of those 392 | input_shape: shape of the expected input tensor excluding the batch dimension 393 | """ 394 | 395 | def _get_weights(self, class_idx: Union[int, List[int]], scores: Tensor, **kwargs: Any) -> List[Tensor]: 396 | """Computes the weight coefficients of the hooked activation maps.""" 397 | # Backpropagate 398 | self._backprop(scores, class_idx, **kwargs) 399 | 400 | self.hook_g: List[Tensor] # type: ignore[assignment] 401 | # List of (N, C, H, W) 402 | return [torch.relu(grad) for grad in self.hook_g] 403 | 404 | @staticmethod 405 | def _scale_cams(cams: List[Tensor], gamma: float = 2.0) -> List[Tensor]: 406 | # cf. Equation 9 in the paper 407 | return [torch.tanh(gamma * cam) for cam in cams] 408 | -------------------------------------------------------------------------------- /torchcam/metrics.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2022-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | from typing import Callable, Dict, Union, cast 7 | 8 | import torch 9 | 10 | from .methods.core import _CAM 11 | 12 | 13 | class ClassificationMetric: 14 | r"""Implements Average Drop and Increase in Confidence from `"Grad-CAM++: Improved Visual Explanations for Deep 15 | Convolutional Networks." `_. 16 | 17 | The raw aggregated metric is computed as follows: 18 | 19 | .. math:: 20 | \forall N, H, W \in \mathbb{N}, \forall X \in \mathbb{R}^{N*3*H*W}, 21 | \forall m \in \mathcal{M}, \forall c \in \mathcal{C}, \\ 22 | AvgDrop_{m, c}(X) = \frac{1}{N} \sum\limits_{i=1}^N f_{m, c}(X_i) \\ 23 | IncrConf_{m, c}(X) = \frac{1}{N} \sum\limits_{i=1}^N g_{m, c}(X_i) 24 | 25 | where :math:`\mathcal{C}` is the set of class activation generators, 26 | :math:`\mathcal{M}` is the set of classification models, 27 | with the function :math:`f_{m, c}` defined as: 28 | 29 | .. math:: 30 | \forall x \in \mathbb{R}^{3*H*W}, 31 | f_{m, c}(x) = \frac{\max(0, m(x) - m(E_{m, c}(x) * x))}{m(x)} 32 | 33 | where :math:`E_{m, c}(x)` is the class activation map of :math:`m` for input :math:`x` with method :math:`m`, 34 | resized to (H, W), 35 | 36 | and with the function :math:`g_{m, c}` defined as: 37 | 38 | .. math:: 39 | \forall x \in \mathbb{R}^{3*H*W}, 40 | g_{m, c}(x) = \left\{ 41 | \begin{array}{ll} 42 | 1 & \mbox{if } m(x) < m(E_{m, c}(x) * x) \\ 43 | 0 & \mbox{otherwise.} 44 | \end{array} 45 | \right. 46 | 47 | 48 | >>> from functools import partial 49 | >>> from torchcam.metrics import ClassificationMetric 50 | >>> metric = ClassificationMetric(cam_extractor, partial(torch.softmax, dim=-1)) 51 | >>> metric.update(input_tensor) 52 | >>> metric.summary() 53 | """ 54 | 55 | def __init__( 56 | self, 57 | cam_extractor: _CAM, 58 | logits_fn: Union[Callable[[torch.Tensor], torch.Tensor], None] = None, 59 | ) -> None: 60 | # This is a typa, I don't know how to rites 61 | self.cam_extractor = cam_extractor 62 | self.logits_fn = logits_fn 63 | self.reset() 64 | 65 | def _get_probs(self, input_tensor: torch.Tensor) -> torch.Tensor: 66 | logits = self.cam_extractor.model(input_tensor) 67 | return cast(torch.Tensor, logits if self.logits_fn is None else self.logits_fn(logits)) 68 | 69 | def my_function(self) -> str: 70 | """Returns a greeting message 71 | 72 | Returns: 73 | str: greeting message 74 | """ 75 | return "Hello" 76 | 77 | def update( 78 | self, 79 | input_tensor: torch.Tensor, 80 | class_idx: Union[int, None] = None, 81 | ) -> None: 82 | """Update the state of the metric with new predictions 83 | 84 | Args: 85 | input_tensor: preprocessed input tensor for the model 86 | class_idx: class index to focus on (default: index of the top predicted class for each sample) 87 | """ 88 | self.cam_extractor.model.eval() 89 | probs = self._get_probs(input_tensor) 90 | # Take the top preds for the cam 91 | if isinstance(class_idx, int): 92 | cams = self.cam_extractor(class_idx, probs) 93 | cam = self.cam_extractor.fuse_cams(cams) 94 | probs = probs[:, class_idx] 95 | else: 96 | preds = probs.argmax(dim=-1) 97 | cams = self.cam_extractor(preds.cpu().numpy().tolist(), probs) 98 | cam = self.cam_extractor.fuse_cams(cams) 99 | probs = probs.gather(1, preds.unsqueeze(1)).squeeze(1) 100 | self.cam_extractor.disable_hooks() 101 | # Safeguard: replace NaNs 102 | cam[torch.isnan(cam)] = 0 103 | # Resize the CAM 104 | cam = torch.nn.functional.interpolate(cam.unsqueeze(1), input_tensor.shape[-2:], mode="bilinear") 105 | # Create the explanation map & get the new probs 106 | with torch.inference_mode(): 107 | masked_probs = self._get_probs(cam * input_tensor) 108 | masked_probs = ( 109 | masked_probs[:, class_idx] 110 | if isinstance(class_idx, int) 111 | else masked_probs.gather(1, preds.unsqueeze(1)).squeeze(1) 112 | ) 113 | # Drop (avoid division by zero) 114 | drop = torch.relu(probs - masked_probs).div(probs + 1e-7) 115 | 116 | # Increase 117 | increase = probs < masked_probs 118 | 119 | self.cam_extractor.enable_hooks() 120 | 121 | self.drop += drop.sum().item() 122 | self.increase += increase.sum().item() 123 | self.total += input_tensor.shape[0] 124 | 125 | def summary(self) -> Dict[str, float]: 126 | """Computes the aggregated metrics 127 | 128 | Returns: 129 | a dictionary with the average drop and the increase in confidence 130 | """ 131 | if self.total == 0: 132 | raise AssertionError("you need to update the metric before getting the summary") 133 | 134 | return { 135 | "avg_drop": self.drop / self.total, 136 | "conf_increase": self.increase / self.total, 137 | } 138 | 139 | def reset(self) -> None: 140 | self.drop = 0.0 141 | self.increase = 0.0 142 | self.total = 0 143 | -------------------------------------------------------------------------------- /torchcam/utils.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020-2025, François-Guillaume Fernandez. 2 | 3 | # This program is licensed under the Apache License 2.0. 4 | # See LICENSE or go to for full license details. 5 | 6 | from typing import cast 7 | 8 | import numpy as np 9 | from matplotlib import colormaps as cm 10 | from PIL.Image import Image, Resampling, fromarray 11 | 12 | 13 | def overlay_mask(img: Image, mask: Image, colormap: str = "jet", alpha: float = 0.7) -> Image: 14 | """Overlay a colormapped mask on a background image 15 | 16 | >>> from PIL import Image 17 | >>> import matplotlib.pyplot as plt 18 | >>> from torchcam.utils import overlay_mask 19 | >>> img = ... 20 | >>> cam = ... 21 | >>> overlay = overlay_mask(img, cam) 22 | 23 | Args: 24 | img: background image 25 | mask: mask to be overlayed in grayscale 26 | colormap: colormap to be applied on the mask 27 | alpha: transparency of the background image 28 | 29 | Returns: 30 | overlayed image 31 | 32 | Raises: 33 | TypeError: when the arguments have invalid types 34 | ValueError: when the alpha argument has an incorrect value 35 | """ 36 | if not isinstance(img, Image) or not isinstance(mask, Image): 37 | raise TypeError("img and mask arguments need to be PIL.Image") 38 | 39 | if not isinstance(alpha, float) or alpha < 0 or alpha >= 1: 40 | raise ValueError("alpha argument is expected to be of type float between 0 and 1") 41 | 42 | cmap = cm.get_cmap(colormap) 43 | # Resize mask and apply colormap 44 | overlay = mask.resize(img.size, resample=Resampling.BICUBIC) 45 | overlay = (255 * cmap(np.asarray(overlay) ** 2)[:, :, :3]).astype(np.uint8) 46 | # Overlay the image with the mask 47 | return fromarray((alpha * np.asarray(img) + (1 - alpha) * cast(np.ndarray, overlay)).astype(np.uint8)) 48 | --------------------------------------------------------------------------------