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

📝 Add Example Notebook for Foundation Models #887

Merged
merged 23 commits into from
Dec 3, 2024

Conversation

adamshephard
Copy link
Contributor

@adamshephard adamshephard commented Nov 29, 2024

  • Add Example Notebook to explain how to use Foundation Models from timm module in TIAToolbox.

Copy link

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

@adamshephard adamshephard changed the title ADD: Add feature extraction notebook Add feature extraction notebook Nov 29, 2024
@shaneahmed shaneahmed added the documentation Improvements or additions to documentation label Nov 29, 2024
@shaneahmed shaneahmed added this to the Release v1.6.0 milestone Nov 29, 2024
@shaneahmed shaneahmed changed the title Add feature extraction notebook 📝 Add Example Notebook for Foundation Models Nov 29, 2024
@GeorgeBatch
Copy link
Contributor

GeorgeBatch commented Dec 1, 2024

I just realised that in my code, like in this example notebook, we do not explicitly put the model into the .eval() mode.
The same is true for the older example notebooks on which I based my code:

I got worried that I was using models in train mode and that I would need to recompute all the features I computed over the last couple of weeks, but then I checked the source code and realised that we rely on the _infer_batch() function, which runs model.eval() for all models that use it (line 173):

def _infer_batch(
model: nn.Module,
batch_data: torch.Tensor,
device: str,
) -> dict[str, np.ndarray]:
"""Run inference on an input batch.
Contains logic for forward operation as well as i/o aggregation.
Args:
model (nn.Module):
PyTorch defined model.
batch_data (torch.Tensor):
A batch of data generated by
`torch.utils.data.DataLoader`.
device (str):
Transfers model to the specified device. Default is "cpu".
"""
img_patches_device = batch_data.to(device=device).type(
torch.float32,
) # to NCHW
img_patches_device = img_patches_device.permute(0, 3, 1, 2).contiguous()
# Inference mode
model.eval()
# Do not compute the gradient (not training)
with torch.inference_mode():
output = model(img_patches_device)
# Output should be a single tensor or scalar
return output.cpu().numpy()

I think this behaviour is as it should be, but maybe adding a message specifying that the models are being put into eval mode would be beneficial.

@shaneahmed
Copy link
Member

Please remember to update https://github.com/TissueImageAnalytics/tiatoolbox/blob/feature-extractor-example/examples/README.md

Copy link

codecov bot commented Dec 2, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 99.90%. Comparing base (442bd3f) to head (44e2897).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop     #887   +/-   ##
========================================
  Coverage    99.90%   99.90%           
========================================
  Files           69       69           
  Lines         8715     8715           
  Branches      1149     1149           
========================================
  Hits          8707     8707           
  Misses           3        3           
  Partials         5        5           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@adamshephard adamshephard requested a review from ruqayya December 2, 2024 15:35
@shaneahmed shaneahmed changed the title 📝 Add Example Notebook for Foundation Models [skip ci]📝 Add Example Notebook for Foundation Models Dec 2, 2024
Copy link
Member

@shaneahmed shaneahmed left a comment

Choose a reason for hiding this comment

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

Thanks @adamshephard . Please can you re-run the Jupyter notebook. This will update the title on the last image. Please update the feature_extraction.png with the new title. Please crop it to the image area before uploading.

@shaneahmed shaneahmed changed the title [skip ci]📝 Add Example Notebook for Foundation Models 📝 Add Example Notebook for Foundation Models Dec 3, 2024
@shaneahmed shaneahmed merged commit 6b214fe into develop Dec 3, 2024
3 checks passed
@shaneahmed
Copy link
Member

I just realised that in my code, like in this example notebook, we do not explicitly put the model into the .eval() mode. The same is true for the older example notebooks on which I based my code:

I got worried that I was using models in train mode and that I would need to recompute all the features I computed over the last couple of weeks, but then I checked the source code and realised that we rely on the _infer_batch() function, which runs model.eval() for all models that use it (line 173):

def _infer_batch(
model: nn.Module,
batch_data: torch.Tensor,
device: str,
) -> dict[str, np.ndarray]:
"""Run inference on an input batch.
Contains logic for forward operation as well as i/o aggregation.
Args:
model (nn.Module):
PyTorch defined model.
batch_data (torch.Tensor):
A batch of data generated by
`torch.utils.data.DataLoader`.
device (str):
Transfers model to the specified device. Default is "cpu".
"""
img_patches_device = batch_data.to(device=device).type(
torch.float32,
) # to NCHW
img_patches_device = img_patches_device.permute(0, 3, 1, 2).contiguous()
# Inference mode
model.eval()
# Do not compute the gradient (not training)
with torch.inference_mode():
output = model(img_patches_device)
# Output should be a single tensor or scalar
return output.cpu().numpy()

I think this behaviour is as it should be, but maybe adding a message specifying that the models are being put into eval mode would be beneficial.

Thanks @GeorgeBatch. As I am now finalising release v1.6.0, we can address this in the next release. Feel free to raise an issue or a PR for this.

@shaneahmed shaneahmed deleted the feature-extractor-example branch December 3, 2024 14:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants