-
Notifications
You must be signed in to change notification settings - Fork 6
Merge UKCEH/Turing regional classifiers (#72) #112
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
mihow
wants to merge
14
commits into
main
Choose a base branch
from
ukceh-merge-pr72
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 all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
f4e8316
Add UKCEH models
KatrionaGoldmann 5645129
Add UKCEH models
KatrionaGoldmann 3e6d5c0
Merge branch 'RolnickLab:main' into main
KatrionaGoldmann 786e6ce
uncomment models
KatrionaGoldmann b3b5364
Merge origin
KatrionaGoldmann e064385
fix catch
KatrionaGoldmann 73f1e7e
wrong labels file
KatrionaGoldmann 58674fe
Merge AMI-system/main: Add UKCEH/Turing regional classifiers (#72)
mihow 2a54ae6
feat: upload UKCEH model weights and add anguilla v02 pipeline
mihow 755b13c
fix: disable Singapore pipeline (category map not available)
mihow 5badf14
fix: disable Thailand pipeline (category map/weights mismatch)
mihow 0bb6f43
fix: re-enable Thailand pipeline with corrected category map (3800 cl…
mihow 3319fb1
fix: prevent memory leak in _process_job batch processing
mihow 84b20fa
test: add memory leak regression test for batch processing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| """Memory leak regression test for _process_job batch processing. | ||
|
|
||
| Verifies that RSS does not grow unboundedly across batches by using the | ||
| on_batch_complete callback to sample memory after each batch. | ||
|
|
||
| Uses the same test infrastructure as test_worker.py (mock Antenna API, | ||
| StaticFileTestServer, real ML inference). | ||
| """ | ||
|
|
||
| import os | ||
| import pathlib | ||
| from unittest import TestCase | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
| from fastapi.testclient import TestClient | ||
|
|
||
| from trapdata.antenna.schemas import AntennaPipelineProcessingTask | ||
| from trapdata.antenna.tests import antenna_api_server | ||
| from trapdata.antenna.tests.antenna_api_server import app as antenna_app | ||
| from trapdata.antenna.worker import _process_job | ||
| from trapdata.api.tests.image_server import StaticFileTestServer | ||
| from trapdata.api.tests.utils import get_test_image_urls, patch_antenna_api_requests | ||
| from trapdata.tests import TEST_IMAGES_BASE_PATH | ||
|
|
||
|
|
||
| def _get_rss_mb() -> float: | ||
| """Current RSS in MB, read from /proc/self/statm (Linux-only).""" | ||
| with open("/proc/self/statm") as f: | ||
| pages = int(f.read().split()[1]) # resident pages | ||
| return pages * os.sysconf("SC_PAGE_SIZE") / (1024 * 1024) | ||
|
|
||
|
|
||
| class TestMemoryLeak(TestCase): | ||
| """Regression test: RSS must not grow linearly with batch count.""" | ||
|
|
||
| @classmethod | ||
| def setUpClass(cls): | ||
| cls.test_images_dir = pathlib.Path(TEST_IMAGES_BASE_PATH) | ||
| cls.file_server = StaticFileTestServer(cls.test_images_dir) | ||
| cls.file_server.start() | ||
| cls.antenna_client = TestClient(antenna_app) | ||
|
|
||
| @classmethod | ||
| def tearDownClass(cls): | ||
| cls.file_server.stop() | ||
|
|
||
| def setUp(self): | ||
| antenna_api_server.reset() | ||
|
|
||
| def _make_settings(self): | ||
| settings = MagicMock() | ||
| settings.antenna_api_base_url = "http://testserver/api/v2" | ||
| settings.antenna_api_auth_token = "test-token" | ||
| settings.antenna_api_batch_size = 2 | ||
| settings.num_workers = 0 | ||
| settings.localization_batch_size = 2 | ||
| return settings | ||
|
|
||
| @pytest.mark.slow | ||
| def test_rss_stable_across_batches(self): | ||
| """RSS should not grow more than 150 MB across 25+ batches. | ||
|
|
||
| With the old code, all_detections accumulated ~220K DetectionResponse | ||
| objects over a large job, growing RSS by ~4 GB/hr. After the fix, | ||
| each batch's intermediates go out of scope in _process_batch(). | ||
|
|
||
| The 150 MB threshold accounts for normal PyTorch/CUDA allocator | ||
| fragmentation and memory pool behavior, which is not a true leak. | ||
| """ | ||
| # Create 50 tasks by cycling through the 3 available test images | ||
| image_urls = get_test_image_urls( | ||
| self.file_server, self.test_images_dir, subdir="vermont", num=3 | ||
| ) | ||
| num_tasks = 50 | ||
| tasks = [ | ||
| AntennaPipelineProcessingTask( | ||
| id=f"task_{i}", | ||
| image_id=f"img_{i}", | ||
| image_url=image_urls[i % len(image_urls)], | ||
| reply_subject=f"reply_{i}", | ||
| ) | ||
| for i in range(num_tasks) | ||
| ] | ||
| antenna_api_server.setup_job(job_id=999, tasks=tasks) | ||
|
|
||
| # Collect RSS samples via callback | ||
| rss_samples: list[float] = [] | ||
|
|
||
| def on_batch(batch_num: int, items: int): | ||
| rss_samples.append(_get_rss_mb()) | ||
|
|
||
| with patch_antenna_api_requests(self.antenna_client): | ||
| result = _process_job( | ||
| "quebec_vermont_moths_2023", | ||
| 999, | ||
| self._make_settings(), | ||
| on_batch_complete=on_batch, | ||
| ) | ||
|
|
||
| assert result is True | ||
| assert ( | ||
| len(rss_samples) >= 10 | ||
| ), f"Expected at least 10 batches, got {len(rss_samples)}" | ||
|
|
||
| # Compare RSS at end vs after first 2 batches (allow model warmup) | ||
| warmup_rss = rss_samples[2] | ||
| final_rss = rss_samples[-1] | ||
| growth_mb = final_rss - warmup_rss | ||
|
|
||
| print(f"\nMemory profile ({len(rss_samples)} batches):") | ||
| print(f" After warmup (batch 2): {warmup_rss:.1f} MB") | ||
| print(f" Final (batch {len(rss_samples) - 1}): {final_rss:.1f} MB") | ||
| print(f" Growth: {growth_mb:.1f} MB") | ||
| for i, rss in enumerate(rss_samples): | ||
| print(f" Batch {i}: {rss:.1f} MB") | ||
|
|
||
| # Threshold: 150 MB accounts for PyTorch/CUDA allocator pools and | ||
| # Python memory fragmentation — not a true leak. Before the fix, | ||
| # all_detections accumulated every DetectionResponse across all batches. | ||
| # At scale (31K images, ~7 detections/image), that was ~220K objects = GB. | ||
| assert growth_mb < 150, ( | ||
| f"RSS grew {growth_mb:.1f} MB across {len(rss_samples)} batches " | ||
| f"(warmup={warmup_rss:.1f} MB, final={final_rss:.1f} MB). " | ||
| f"Likely memory leak in batch processing." | ||
| ) | ||
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.
Linux-only implementation will fail on macOS/Windows.
The
/proc/self/statmfile only exists on Linux. This test will raiseFileNotFoundErroron macOS or Windows CI runners.Consider adding a platform skip marker or using a cross-platform memory measurement.
🛠️ Proposed fix using pytest skip marker
Alternatively, for cross-platform support:
🤖 Prompt for AI Agents