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

How would I call individual layers of the network? yolov5 #4575

Closed
levnagy opened this issue Aug 28, 2021 · 8 comments
Closed

How would I call individual layers of the network? yolov5 #4575

levnagy opened this issue Aug 28, 2021 · 8 comments

Comments

@levnagy
Copy link

levnagy commented Aug 28, 2021

Hi,

I would like to use the last convolutional layer for gradcam visualizations, but I am not sure how to call the layer.
I can list them using this code I found in another issue, but thats as far as I get.


model = torch.hub.load('ultralytics/yolov5','yolov5s', autoshape=False)
print(model)


for k, v in model.named_parameters():
    print(k)

Output looks like this:
image

Ideally, I would wanna be able to select the layer so as to use as part of this code:
image

Where, instead of resnet I would call yolov54 (snippet above), and select the last convolutional layer for visualization.

Hopefully this is feasible. Advices are appriciated.

@github-actions
Copy link
Contributor

github-actions bot commented Aug 28, 2021

👋 Hello @Sarkanyhazy, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com.

Requirements

Python>=3.6.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

$ git clone https://github.com/ultralytics/yolov5
$ cd yolov5
$ pip install -r requirements.txt

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.

@glenn-jocher
Copy link
Member

glenn-jocher commented Aug 28, 2021

@Sarkanyhazy you can select any layer by indexing model.model:

import torch

model = torch.hub.load('ultralytics/yolov5','yolov5s', autoshape=False)
model.model[0]

Out[5]: 
Focus(
  (conv): Conv(
    (conv): Conv2d(12, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (act): SiLU(inplace=True)
  )
)

@levnagy
Copy link
Author

levnagy commented Aug 28, 2021

Thanks for your help Glenn!

@levnagy levnagy closed this as completed Aug 28, 2021
@phanisai22
Copy link

phanisai22 commented Jan 5, 2022

@Sarkanyhazy you can select any layer by indexing model.model:

import torch

model = torch.hub.load('ultralytics/yolov5','yolov5s', autoshape=False)
model.model[0]

Out[5]: 
Focus(
  (conv): Conv(
    (conv): Conv2d(12, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (act): SiLU(inplace=True)
  )
)

Hi,
I tried the above code and i'm getting this error.

image

@Michelvl92
Copy link

Michelvl92 commented Feb 7, 2022

@phanisai22 did you solve this?

@Sarkanyhazy how did you solved this in total with gradcam?

@Michelvl92
Copy link

@glenn-jocher this should be: model.model.model[0]?

But this still gives me an error:

Using cache found in /root/.cache/torch/hub/ultralytics_yolov5_master
YOLOv5 🚀 v6.0-232-g079b36d torch 1.10.1+cu113 CPU

Fusing layers... 
Model Summary: 213 layers, 7225885 parameters, 0 gradients
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_6269/3117303927.py in <module>
     24 cam = EigenCAM(model, target_layers, use_cuda=False)
     25 
---> 26 grayscale_cam = cam(tensor)
     27 # # Take the first image in the batch:
     28 # # grayscale_cam = grayscale_cam[0, :]

/opt/conda/lib/python3.8/site-packages/pytorch_grad_cam/base_cam.py in __call__(self, input_tensor, targets, aug_smooth, eigen_smooth)
    182                 input_tensor, targets, eigen_smooth)
    183 
--> 184         return self.forward(input_tensor,
    185                             targets, eigen_smooth)
    186 

/opt/conda/lib/python3.8/site-packages/pytorch_grad_cam/base_cam.py in forward(self, input_tensor, targets, eigen_smooth)
     80             self.model.zero_grad()
     81             loss = sum([target(output) for target, output in zip(targets, outputs)])
---> 82             loss.backward(retain_graph=True)
     83 
     84         # In most of the saliency attribution papers, the saliency is

/opt/conda/lib/python3.8/site-packages/torch/_tensor.py in backward(self, gradient, retain_graph, create_graph, inputs)
    305                 create_graph=create_graph,
    306                 inputs=inputs)
--> 307         torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
    308 
    309     def register_hook(self, hook):

/opt/conda/lib/python3.8/site-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    152         retain_graph = create_graph
    153 
--> 154     Variable._execution_engine.run_backward(
    155         tensors, grad_tensors_, retain_graph, create_graph, inputs,
    156         allow_unreachable=True, accumulate_grad=True)  # allow_unreachable flag

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

@glenn-jocher
Copy link
Member

@HarrySoteriou
Copy link

HarrySoteriou commented Dec 2, 2022

@Sarkanyhazy you can select any layer by indexing model.model:

import torch

model = torch.hub.load('ultralytics/yolov5','yolov5s', autoshape=False)
model.model[0]

Out[5]: 
Focus(
  (conv): Conv(
    (conv): Conv2d(12, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (act): SiLU(inplace=True)
  )
)

Hi, I tried the above code and i'm getting this error.

image

I got it to work by indexing model 4 times

model = torch.hub.load(repo_or_dir=ROOT, model="custom", source='local', path=weights) #.to(device)
#summary(model, input_size=(1, 3, 416, 416), depth=5, verbose=1)

print(model.model.model.model[:10])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants