-
Notifications
You must be signed in to change notification settings - Fork 7
feat: add feature vector extraction to classification responses #77
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
mohamedelabbas1996
wants to merge
23
commits into
main
Choose a base branch
from
feat/add-classification-features-to-response
base: main
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
Changes from 18 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
368edc2
feat: Added features field to the classification response
mohamedelabbas1996 4484f2e
feat: add support for returning features in APIMothClassifier response
mohamedelabbas1996 3cc31ad
added fallback get_features method to the InferenceBaseClass
mohamedelabbas1996 8071168
feat: implemented get_features for Resnet50TimmClassifier class
mohamedelabbas1996 52f0f62
chore: moved features dim to constants
mohamedelabbas1996 b4c3af7
Default to None if get_features is not implemented
mohamedelabbas1996 ae62dd5
Added features extraction tests
mohamedelabbas1996 88c8220
Removed prints
mohamedelabbas1996 fa7dee8
Added clustering using K-Means and visualization
mohamedelabbas1996 cce38f3
Added plotly dependency
mohamedelabbas1996 902331b
Added sklearn dependency
mohamedelabbas1996 9306bd0
chore: make plotly optional, fix type warnings
mihow 71768a2
merge: resolve conflicts with main, preserve Mohamed's feature extrac…
mihow 4159333
feat: add get_features() to InferenceBaseClass and Resnet50TimmClassi…
mihow dc5fc49
feat: add include_features and include_logits config toggles
mihow 7028ce6
feat: wire feature and logits extraction into APIMothClassifier
mihow 2afe1e7
feat: pass include_features and include_logits from API and worker
mihow 3183ee4
test: add feature and logits extraction API tests
mihow aa530fc
merge: update to latest main (GPU utilization fixes)
mihow f48effb
fix: resolve timing bug and update existing tests for opt-in logits
mihow 598d6ed
test: add worker-path and feature validity tests
mihow b4b0fbf
fix: release feature tensor after use, add settings UI metadata
mihow 9189018
merge: pick up memory leak threshold bump from main (#124)
mihow 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
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
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 |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| import pathlib | ||
| from unittest import TestCase | ||
|
|
||
| from fastapi.testclient import TestClient | ||
|
|
||
| from trapdata.api.api import PipelineChoice, PipelineRequest, PipelineResponse, app | ||
| from trapdata.api.schemas import PipelineConfigRequest, SourceImageRequest | ||
| from trapdata.api.tests.image_server import StaticFileTestServer | ||
| from trapdata.tests import TEST_IMAGES_BASE_PATH | ||
|
|
||
|
|
||
| class TestFeatureAndLogitsExtractionAPI(TestCase): | ||
| @classmethod | ||
| def setUpClass(cls): | ||
| cls.test_images_dir = pathlib.Path(TEST_IMAGES_BASE_PATH) | ||
| cls.file_server = StaticFileTestServer(cls.test_images_dir) | ||
| cls.client = TestClient(app) | ||
|
|
||
| @classmethod | ||
| def tearDownClass(cls): | ||
| cls.file_server.stop() | ||
|
|
||
| def get_local_test_images(self, num=1): | ||
| image_paths = [ | ||
| "panama/01-20231110214539-snapshot.jpg", | ||
| "panama/01-20231111032659-snapshot.jpg", | ||
| "panama/01-20231111015309-snapshot.jpg", | ||
| ] | ||
| return [ | ||
| SourceImageRequest(id=str(i), url=self.file_server.get_url(path)) | ||
| for i, path in enumerate(image_paths[:num]) | ||
| ] | ||
|
|
||
| def _run_pipeline( | ||
| self, | ||
| include_features: bool = False, | ||
| include_logits: bool = False, | ||
| num_images: int = 1, | ||
| ): | ||
| test_images = self.get_local_test_images(num=num_images) | ||
| config = PipelineConfigRequest( | ||
| include_features=include_features, | ||
| include_logits=include_logits, | ||
| ) | ||
| pipeline_request = PipelineRequest( | ||
| pipeline=PipelineChoice["global_moths_2024"], | ||
| source_images=test_images, | ||
| config=config, | ||
| ) | ||
| with self.file_server: | ||
| response = self.client.post("/process", json=pipeline_request.model_dump()) | ||
| assert response.status_code == 200 | ||
| return PipelineResponse(**response.json()) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| def test_features_included_when_enabled(self): | ||
| """Features are present and valid when include_features=True.""" | ||
| result = self._run_pipeline(include_features=True) | ||
| self.assertTrue(result.detections, "No detections returned") | ||
| for detection in result.detections: | ||
| for classification in detection.classifications: | ||
| if classification.terminal: | ||
| self.assertIsNotNone( | ||
| classification.features, | ||
| "Features should not be None when enabled", | ||
| ) | ||
| self.assertIsInstance(classification.features, list) | ||
| self.assertTrue( | ||
| all(isinstance(x, float) for x in classification.features) | ||
| ) | ||
| self.assertEqual(len(classification.features), 2048) | ||
|
|
||
| def test_features_absent_when_disabled(self): | ||
| """Features are None when include_features=False (default).""" | ||
| result = self._run_pipeline(include_features=False) | ||
| self.assertTrue(result.detections, "No detections returned") | ||
| for detection in result.detections: | ||
| for classification in detection.classifications: | ||
| self.assertIsNone( | ||
| classification.features, | ||
| "Features should be None when disabled", | ||
| ) | ||
|
|
||
| def test_logits_included_when_enabled(self): | ||
| """Logits are present when include_logits=True.""" | ||
| result = self._run_pipeline(include_logits=True) | ||
| self.assertTrue(result.detections, "No detections returned") | ||
| for detection in result.detections: | ||
| for classification in detection.classifications: | ||
| if classification.terminal: | ||
| self.assertIsNotNone( | ||
| classification.logits, | ||
| "Logits should not be None when enabled", | ||
| ) | ||
| self.assertIsInstance(classification.logits, list) | ||
| self.assertTrue( | ||
| all(isinstance(x, float) for x in classification.logits) | ||
| ) | ||
|
|
||
| def test_logits_absent_when_disabled(self): | ||
| """Logits are None when include_logits=False (default).""" | ||
| result = self._run_pipeline(include_logits=False) | ||
| self.assertTrue(result.detections, "No detections returned") | ||
| for detection in result.detections: | ||
| for classification in detection.classifications: | ||
| self.assertIsNone( | ||
| classification.logits, | ||
| "Logits should be None when disabled", | ||
| ) | ||
|
|
||
| def test_both_features_and_logits(self): | ||
| """Both features and logits present when both flags enabled.""" | ||
| result = self._run_pipeline(include_features=True, include_logits=True) | ||
| self.assertTrue(result.detections, "No detections returned") | ||
| for detection in result.detections: | ||
| for classification in detection.classifications: | ||
| if classification.terminal: | ||
| self.assertIsNotNone(classification.features) | ||
| self.assertIsNotNone(classification.logits) | ||
|
|
||
| def test_default_config_has_nothing_extra(self): | ||
| """Default PipelineConfigRequest disables both features and logits.""" | ||
| config = PipelineConfigRequest() | ||
| self.assertFalse(config.include_features) | ||
| self.assertFalse(config.include_logits) | ||
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
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 |
|---|---|---|
|
|
@@ -293,6 +293,18 @@ def get_model(self): | |
| model.eval() | ||
| return model | ||
|
|
||
| @torch.no_grad() | ||
| def get_features(self, batch_input: torch.Tensor) -> torch.Tensor: | ||
|
Collaborator
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. Nice work on this method of extracting features! It seems more flexible than our current feature extractor. Perhaps we should add a comment in both feature extractors that the other one exists. And eventually update the old one to use this code. |
||
| """Extract 2048-dim feature vectors from the ResNet50 backbone. | ||
|
|
||
| Uses timm's forward_features() which returns (B, 2048, H, W) spatial | ||
| feature maps for ResNet50. Pooled to (B, 2048) via adaptive avg pool. | ||
| """ | ||
| features = self.model.forward_features(batch_input) | ||
| features = torch.nn.functional.adaptive_avg_pool2d(features, (1, 1)) | ||
| features = features.view(features.size(0), -1) | ||
| return features | ||
|
|
||
|
|
||
| class BinaryClassifier(Resnet50ClassifierLowRes): | ||
| stage = 2 | ||
|
|
||
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
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.
Uh oh!
There was an error while loading. Please reload this page.