Skip to content

4867 flexible torchvision fc models#4873

Merged
wyli merged 13 commits intoProject-MONAI:devfrom
wyli:4867-torchvision-fc
Aug 10, 2022
Merged

4867 flexible torchvision fc models#4873
wyli merged 13 commits intoProject-MONAI:devfrom
wyli:4867-torchvision-fc

Conversation

@wyli
Copy link
Copy Markdown
Contributor

@wyli wyli commented Aug 9, 2022

Signed-off-by: Wenqi Li [email protected]

Fixes #4867

Description

  • enhance the model.fc replacement in netadapter
  • tested inception_v3 as a torchvision fc model

Status

Ready

Types of changes

  • Non-breaking change (fix or new feature that would not break existing functionality).
  • Breaking change (fix or new feature that would cause existing functionality to change).
  • New tests added to cover the changes.
  • Integration tests passed locally by running ./runtests.sh -f -u --net --coverage.
  • Quick tests passed locally by running ./runtests.sh --quick --unittests --disttests.
  • In-line docstrings updated.
  • Documentation updated, tested make html command in the docs/ folder.

@wyli wyli marked this pull request as ready for review August 9, 2022 11:51
@ericspod ericspod requested a review from vikashg August 9, 2022 16:57
@wyli wyli requested a review from ericspod August 9, 2022 19:22
@vikashg
Copy link
Copy Markdown

vikashg commented Aug 10, 2022

So @wyli, This patch works on models like Inception_V3 and produces the desired output. However, it fails for models like VisionTransformer torchnvision.models.vit_b_16 with the following error

  File "/raid/Vikash/Tools/review-MONAI/MONAI/monai/networks/nets/torchvision_fc.py", line 91, in __init__
    raise ValueError(f"Model ['{model_name}'] does not have a Linear layer at the end.")
ValueError: Model ['vit_b_16'] does not have a Linear layer at the end.

The error is obvious as there is the startswith Linear condition check. It might work for Inception and Resnet as the tail of the model looks like this

  )
  (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
  (dropout): Dropout(p=0.5, inplace=False)
  (fc): Linear(in_features=2048, out_features=1000, bias=True)
)

But does not work if the model terminates in a Linear layer wrapped in a Sequential module as follows

          (4): Dropout(p=0.0, inplace=False)
        )
      )
    )
    (ln): LayerNorm((768,), eps=1e-06, elementwise_affine=True)
  )
  (heads): Sequential(
    (head): Linear(in_features=768, out_features=1000, bias=True)
  )
)

So, if we can expand the if statement it will cover majority of the models in torchvision.models

@wyli wyli marked this pull request as draft August 10, 2022 11:15
Copy link
Copy Markdown

@vikashg vikashg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I try to use the VIT (torchvision.models.vit_b_16), I get the following error after the recent commit

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    model = TorchVisionFCModel(
  File "/raid/Vikash/Tools/review-MONAI/MONAI/monai/utils/deprecate_utils.py", line 224, in _wrapper
    return func(*args, **kwargs)
  File "/raid/Vikash/Tools/review-MONAI/MONAI/monai/networks/nets/torchvision_fc.py", line 93, in __init__
    if look_up_named_module(fc_name, model) is None:
  File "/raid/Vikash/Tools/review-MONAI/MONAI/monai/networks/utils.py", line 65, in look_up_named_module
    name_str = look_up_option(name, {n[0] for n in mod.named_modules()}, print_all_options=print_all_options)
  File "/raid/Vikash/Tools/review-MONAI/MONAI/monai/utils/module.py", line 120, in look_up_option
    raise ValueError(
ValueError: By 'fc', did you mean ''?
'fc' is not a valid value.

@wyli wyli force-pushed the 4867-torchvision-fc branch from b1bd545 to f75c3f9 Compare August 10, 2022 15:02
@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

thanks @vikashg the comments are helpful, I spend some time on this, it's not easy to be that flexible at the same time backwards compatible... but for the basic use cases it's ok now:

import torch
from torchvision.models import Swin_T_Weights

from monai.networks.nets import TorchVisionFCModel

model = TorchVisionFCModel(
    "vit_b_16", num_classes=4, use_conv=False, pool=None, in_channels=768, fc_name="heads.head")
output = model.forward(torch.randn(2, 3, 224, 224))
print(output.shape)  # torch.Size([2, 4])

model = TorchVisionFCModel(
    "swin_t",
    num_classes=4,
    pool="",
    use_conv=True,
    in_channels=768,
    node_name="permute",
    weights=Swin_T_Weights.IMAGENET1K_V1,
)
output = model.forward(torch.randn(2, 3, 500, 500))
print(output.shape)  # torch.Size([2, 4, 16, 16])

@wyli wyli marked this pull request as ready for review August 10, 2022 15:24
@wyli wyli requested a review from vikashg August 10, 2022 15:24
Copy link
Copy Markdown

@vikashg vikashg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @wyli for supplying an example code snippet. It all works well now. IT should be compatible with 0.9 right ?

@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/black

Thanks @wyli for supplying an example code snippet. It all works well now. IT should be compatible with 0.9 right ?

yes it's non-breaking, the previous test cases all work fine.

wyli added 8 commits August 10, 2022 19:02
Signed-off-by: Wenqi Li <[email protected]>
Signed-off-by: Wenqi Li <[email protected]>
Signed-off-by: Wenqi Li <[email protected]>
Signed-off-by: Wenqi Li <[email protected]>
@wyli wyli force-pushed the 4867-torchvision-fc branch from 8c0da62 to 88f2f2f Compare August 10, 2022 18:03
@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/build

Signed-off-by: Wenqi Li <[email protected]>
@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/build

@wyli wyli enabled auto-merge (squash) August 10, 2022 18:28
Signed-off-by: Wenqi Li <[email protected]>
@wyli wyli force-pushed the 4867-torchvision-fc branch from 62c4d04 to cefaa6e Compare August 10, 2022 19:11
@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/build

Signed-off-by: Wenqi Li <[email protected]>
@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/build

Signed-off-by: Wenqi Li <[email protected]>
@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/build

@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 10, 2022

/build

@wyli wyli merged commit 9858293 into Project-MONAI:dev Aug 10, 2022
@ctestagrose
Copy link
Copy Markdown

Will these changes be available if we install monai via pip 0.8.1? Because we are using NVFlare for federated learning following this tutorial which uses pip install monai=0.8.1 to build the docker packages. I wonder if these changes will be pushed to the pip package manager.

@wyli
Copy link
Copy Markdown
Contributor Author

wyli commented Aug 11, 2022

Hi @ctestagrose, there's currently no plan to backport this to v0.8, it will be available in the weekly dev release https://pypi.org/project/monai-weekly/#history (next one on 14th/Aug). So, early next week, you can uninstall monai with pip uninstall -y monai and run pip install monai-weekly to get this feature. This version will be very different from v0.8.1 0.8.1...dev including some breaking changes so the existing 0.8.1 pipelines may or may not work.

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

Successfully merging this pull request may close these issues.

Question about TorchVisionFC model

4 participants