Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

build(deps-dev): bump ruff from 0.5.2 to 0.5.5 #266

Merged
merged 5 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions .github/collect_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,13 @@ def get_nvidia_smi():
def get_platform():
if sys.platform.startswith("linux"):
return "linux"
elif sys.platform.startswith("win32"):
if sys.platform.startswith("win32"):
return "win32"
elif sys.platform.startswith("cygwin"):
if sys.platform.startswith("cygwin"):
return "cygwin"
elif sys.platform.startswith("darwin"):
if sys.platform.startswith("darwin"):
return "darwin"
else:
return sys.platform
return sys.platform


def get_mac_version(run_lambda):
Expand Down
4 changes: 1 addition & 3 deletions .github/verify_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ def parse_args():
)

parser.add_argument("pr", type=int, help="PR number")
args = parser.parse_args()

return args
return parser.parse_args()


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/style.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
- name: Run ruff
run: |
python -m pip install --upgrade uv
uv pip install --system ruff==0.3.0
uv pip install --system --upgrade -e ".[quality]"
ruff --version
ruff check --diff .
Expand Down Expand Up @@ -62,7 +62,7 @@ jobs:
- name: Run ruff
run: |
python -m pip install --upgrade uv
uv pip install --system ruff==0.3.0
uv pip install --system --upgrade -e ".[quality]"
ruff --version
ruff format --check --diff .
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ repos:
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.5.2'
rev: 'v0.5.5'
hooks:
- id: ruff
args:
Expand Down
48 changes: 27 additions & 21 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ test = [
"pytest-pretty>=1.0.0,<2.0.0",
]
quality = [
"ruff==0.5.2",
"ruff==0.5.5",
"mypy==1.10.0",
"types-Pillow",
"pre-commit>=3.0.0,<4.0.0",
Expand Down Expand Up @@ -77,7 +77,7 @@ dev = [
"pytest-cov>=4.0.0,<5.0.0",
"pytest-pretty>=1.0.0,<2.0.0",
# style
"ruff==0.5.2",
"ruff==0.5.5",
"mypy==1.10.0",
"types-Pillow",
"pre-commit>=3.0.0,<4.0.0",
Expand Down Expand Up @@ -116,37 +116,43 @@ preview = true

[tool.ruff.lint]
select = [
"F", # pyflakes
"E", # pycodestyle errors
"W", # pycodestyle warnings
"D101", "D103", # pydocstyle missing docstring in public function/class
"D201","D202","D207","D208","D214","D215","D300","D301","D417", "D419", # pydocstyle
"F", # pyflakes
"I", # isort
"C4", # flake8-comprehensions
"B", # flake8-bugbear
"CPY001", # flake8-copyright
"ISC", # flake8-implicit-str-concat
"PYI", # flake8-pyi
"NPY", # numpy
"PERF", # perflint
"RUF", # ruff specific
"PTH", # flake8-use-pathlib
"S", # flake8-bandit
"N", # pep8-naming
"T10", # flake8-debugger
"T20", # flake8-print
"PT", # flake8-pytest-style
"LOG", # flake8-logging
"SIM", # flake8-simplify
"D101", "D103", # pydocstyle missing docstring in public function/class
"D201","D202","D207","D208","D214","D215","D300","D301","D417", "D419", # pydocstyle
"YTT", # flake8-2020
"ANN", # flake8-annotations
"ASYNC", # flake8-async
"S", # flake8-bandit
"BLE", # flake8-blind-except
"B", # flake8-bugbear
"A", # flake8-builtins
"COM", # flake8-commas
"CPY", # flake8-copyright
"C4", # flake8-comprehensions
"T10", # flake8-debugger
"ISC", # flake8-implicit-str-concat
"ICN", # flake8-import-conventions
"LOG", # flake8-logging
"PIE", # flake8-pie
"T20", # flake8-print
"PYI", # flake8-pyi
"PT", # flake8-pytest-style
"Q", # flake8-quotes
"RET", # flake8-return
"SLF", # flake8-self
"SIM", # flake8-simplify
"ARG", # flake8-unused-arguments
"PTH", # flake8-use-pathlib
"PERF", # perflint
"NPY", # numpy
"FAST", # fastapi
"FURB", # refurb
"RUF", # ruff specific
"N", # pep8-naming
]
ignore = [
"E501", # line too long, handled by black
Expand Down Expand Up @@ -179,7 +185,7 @@ known-third-party = ["torch", "torchvision"]
"scripts/**.py" = ["D", "T201", "N812", "S101", "ANN"]
".github/**.py" = ["D", "T201", "S602", "S101", "ANN"]
"docs/**.py" = ["E402", "D103", "ANN", "A001", "ARG001"]
"tests/**.py" = ["D103", "CPY001", "S101", "PT011", "ANN"]
"tests/**.py" = ["D103", "CPY001", "S101", "PT011", "ANN", "SLF001"]
"demo/**.py" = ["D103", "ANN"]
"setup.py" = ["T201"]

Expand Down
4 changes: 2 additions & 2 deletions scripts/cam_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def main(args):
ax.set_title("Input", size=8)

for idx, extractor in zip(range(1, len(cam_extractors) + 1), cam_extractors):
extractor._hooks_enabled = True
extractor.enable_hooks()
model.zero_grad()
scores = model(img_tensor.unsqueeze(0))

Expand All @@ -85,8 +85,8 @@ def main(args):
activation_map = extractor(class_idx, scores)[0].squeeze(0).cpu()

# Clean data
extractor.disable_hooks()
extractor.remove_hooks()
extractor._hooks_enabled = False
# Convert it to PIL image
# The indexing below means first image in batch
heatmap = to_pil_image(activation_map, mode="F")
Expand Down
7 changes: 3 additions & 4 deletions torchcam/methods/activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ def _get_weights(
# Take the FC weights of the target class
if isinstance(class_idx, int):
return [self._fc_weights[class_idx, :].unsqueeze(0)]
else:
return [self._fc_weights[class_idx, :]]
return [self._fc_weights[class_idx, :]]


class ScoreCAM(_CAM):
Expand Down Expand Up @@ -214,15 +213,15 @@ def _get_weights(
]

# Disable hook updates
self._hooks_enabled = False
self.disable_hooks()
# Switch to eval
origin_mode = self.model.training
self.model.eval()

weights: List[Tensor] = self._get_score_weights(upsampled_a, class_idx)

# Reenable hook updates
self._hooks_enabled = True
self.enable_hooks()
# Put back the model in the correct mode
self.model.training = origin_mode

Expand Down
25 changes: 16 additions & 9 deletions torchcam/methods/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ def __init__(
# Model output is used by the extractor
self._score_used = False

def enable_hooks(self) -> None:
"""Enable hooks."""
self._hooks_enabled = True

def disable_hooks(self) -> None:
"""Disable hooks."""
self._hooks_enabled = False

def __enter__(self) -> "_CAM":
return self

Expand Down Expand Up @@ -236,17 +244,16 @@ def fuse_cams(cls, cams: List[Tensor], target_shape: Optional[Tuple[int, int]] =

if len(cams) == 0:
raise ValueError("argument `cams` cannot be an empty list")
elif len(cams) == 1:
if len(cams) == 1:
return cams[0]
# Resize to the biggest CAM if no value was provided for `target_shape`
if isinstance(target_shape, tuple):
_shape = target_shape
else:
# Resize to the biggest CAM if no value was provided for `target_shape`
if isinstance(target_shape, tuple):
_shape = target_shape
else:
_shape = tuple(map(max, zip(*[tuple(cam.shape[1:]) for cam in cams])))
# Scale cams
scaled_cams = cls._scale_cams(cams)
return cls._fuse_cams(scaled_cams, _shape)
_shape = tuple(map(max, zip(*[tuple(cam.shape[1:]) for cam in cams])))
# Scale cams
scaled_cams = cls._scale_cams(cams)
return cls._fuse_cams(scaled_cams, _shape)

@staticmethod
def _scale_cams(cams: List[Tensor]) -> List[Tensor]:
Expand Down
4 changes: 2 additions & 2 deletions torchcam/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def update(
cams = self.cam_extractor(preds.cpu().numpy().tolist(), probs)
cam = self.cam_extractor.fuse_cams(cams)
probs = probs.gather(1, preds.unsqueeze(1)).squeeze(1)
self.cam_extractor._hooks_enabled = False
self.cam_extractor.disable_hooks()
# Safeguard: replace NaNs
cam[torch.isnan(cam)] = 0
# Resize the CAM
Expand All @@ -116,7 +116,7 @@ def update(
# Increase
increase = probs < masked_probs

self.cam_extractor._hooks_enabled = True
self.cam_extractor.enable_hooks()

self.drop += drop.sum().item()
self.increase += increase.sum().item()
Expand Down
Loading