Repository navigation
Cai pytorch 7 #1588
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
Open
manuelpaeza
wants to merge
7
commits into
flatironinstitute:dev
Choose a base branch
from
manuelpaeza:cai-pytorch-7
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Cai pytorch 7 #1588
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ae927d3
Add PyTorch VolPy Mask R-CNN pipeline
manuelpaeza 8ef7696
Restore interactive VolPy training notebook
manuelpaeza e174605
Use standard CaImAn model directory
manuelpaeza fd07f47
Fix VolPy and demo compatibility and clean portable examples
manuelpaeza 9c7cd1b
Add regression tests for VolPy extraction and component display
manuelpaeza 126fd20
Merge upstream dev and preserve both VolPy regression suites
manuelpaeza 01e64a3
Update model file_dict with new entries
manuelpaeza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,16 +10,19 @@ | |
| Revised by Eric Thompson, Chanjia Cai, and Manuel Paez | ||
| """ | ||
|
|
||
| import numpy as np | ||
| import torch | ||
| import pickle | ||
| import warnings | ||
|
|
||
| import torch | ||
|
Comment on lines
+13
to
+16
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we keep these alphabetical? |
||
| import torchvision | ||
| from torchvision.models.detection.faster_rcnn import FastRCNNPredictor | ||
| from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor | ||
|
|
||
| from caiman.source_extraction.volpy.mrcnn.utils import ScaleImage, data_transform | ||
| from torchvision.models.detection.mask_rcnn import ( | ||
| MaskRCNNPredictor, | ||
| MaskRCNN_ResNet50_FPN_V2_Weights, | ||
| ) | ||
|
|
||
| # Model (Pre-trained on the COCO Dataset) | ||
| def get_model_instance_segmentation(num_classes): | ||
| def get_model_instance_segmentation(num_classes, pretrained=True): | ||
| """ | ||
| Loads a pre-trained Mask R-CNN model and modifies its classification | ||
| and mask prediction heads for a custom number of classes. | ||
|
|
@@ -31,8 +34,12 @@ def get_model_instance_segmentation(num_classes): | |
| Returns: | ||
| torch.nn.Module: The modified Mask R-CNN model ready for fine-tuning. | ||
| """ | ||
| # load an instance segmentation model pre-trained on COCO, fpn_v2 provides better performance | ||
| model = torchvision.models.detection.maskrcnn_resnet50_fpn_v2(weights='COCO_V1', trainable_backbone_layers=3) | ||
| weights = MaskRCNN_ResNet50_FPN_V2_Weights.DEFAULT if pretrained else None | ||
| model = torchvision.models.detection.maskrcnn_resnet50_fpn_v2( | ||
| weights=weights, | ||
| weights_backbone=None, | ||
| trainable_backbone_layers=3 if pretrained else None, | ||
| ) | ||
|
|
||
| # get number of input features for the classifier | ||
| in_features = model.roi_heads.box_predictor.cls_score.in_features | ||
|
|
@@ -50,11 +57,37 @@ def get_model_instance_segmentation(num_classes): | |
| num_classes) | ||
| return model | ||
|
|
||
|
|
||
| def load_mrcnn_weights(model, weights_path, device): | ||
| """Load legacy state dictionaries and metadata-bearing checkpoints.""" | ||
| try: | ||
| checkpoint = torch.load(weights_path, map_location=device, weights_only=True) | ||
| except TypeError: # torch < 2.0 compatibility | ||
| checkpoint = torch.load(weights_path, map_location=device) | ||
| except pickle.UnpicklingError: | ||
| warnings.warn( | ||
| "This legacy checkpoint requires pickle loading. Only load model files " | ||
| "from a trusted source.", | ||
| RuntimeWarning, | ||
| stacklevel=2, | ||
| ) | ||
| checkpoint = torch.load(weights_path, map_location=device, weights_only=False) | ||
| if isinstance(checkpoint, torch.nn.Module): | ||
| state_dict = checkpoint.state_dict() | ||
| elif isinstance(checkpoint, dict): | ||
| state_dict = checkpoint.get('model_state_dict', checkpoint) | ||
| else: | ||
| raise TypeError(f"Unsupported Mask R-CNN checkpoint type: {type(checkpoint).__name__}") | ||
| model.load_state_dict(state_dict) | ||
| return checkpoint | ||
|
|
||
| def mrcnn_inference(model, | ||
| img, | ||
| eval_transform, | ||
| device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu'), | ||
| thresh=0.5): | ||
| thresh=0.5, | ||
| mask_threshold=0.5, | ||
| return_scores=False): | ||
| """ | ||
| inference using Mask R-CNN network | ||
| """ | ||
|
|
@@ -66,16 +99,22 @@ def mrcnn_inference(model, | |
| predictions = model([x, ]) | ||
| pred = predictions[0] | ||
|
|
||
| predicted_masks, predicted_boxes = thresholded_predictions(pred, threshold=thresh) | ||
| binarized_masks = (0.5+predicted_masks).detach().cpu().numpy().astype(np.uint8) | ||
| predicted_masks, predicted_boxes, predicted_scores = thresholded_predictions( | ||
| pred, threshold=thresh | ||
| ) | ||
| binarized_masks = (predicted_masks >= mask_threshold).to(torch.uint8).cpu().numpy() | ||
|
|
||
| if return_scores: | ||
| return predicted_masks, predicted_boxes, binarized_masks, predicted_scores | ||
| return predicted_masks, predicted_boxes, binarized_masks | ||
|
|
||
| def thresholded_predictions(pred, threshold=0.7): | ||
| """ | ||
| Get masks and boxes for those above threshold | ||
| """ | ||
| numels = len(torch.where(pred['scores'] >= threshold)[0]) | ||
| masks = pred['masks'][:numels].squeeze() | ||
| boxes = pred['boxes'][:numels] | ||
|
|
||
| return masks, boxes | ||
| keep = pred['scores'] >= threshold | ||
| masks = pred['masks'][keep, 0] | ||
| boxes = pred['boxes'][keep] | ||
| scores = pred['scores'][keep] | ||
|
|
||
| return masks, boxes, scores | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for catching this