From 8f0b7f4d4e7eda2ed606ebde6702c93359ad01da Mon Sep 17 00:00:00 2001 From: Marco Dal Farra Date: Thu, 13 Aug 2026 22:33:07 -0700 Subject: [PATCH] Restore autocast state on video predictor shutdown Summary: During development of an end2end test I encountered this bug. SAM3's tracker enters a long-lived bfloat16 autocast context during model construction. Exit and clear that context when the owning video predictor shuts down so subsequent work in the same thread is not silently autocast. ___ Differential Revision: D115565123 fbshipit-source-id: 87dd514e974345d41b22a89569dd0ea3200bc53a --- sam3/model/sam3_video_predictor.py | 11 +++++++++++ test/test_video_predictor.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 test/test_video_predictor.py diff --git a/sam3/model/sam3_video_predictor.py b/sam3/model/sam3_video_predictor.py index a7660af..dcb53b0 100644 --- a/sam3/model/sam3_video_predictor.py +++ b/sam3/model/sam3_video_predictor.py @@ -96,6 +96,17 @@ class Sam3VideoPredictor(Sam3BasePredictor): f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}" ) + def shutdown(self): + tracker = getattr(self.model, "tracker", None) + bf16_context = getattr(tracker, "bf16_context", None) + try: + if bf16_context is not None: + bf16_context.__exit__(None, None, None) + finally: + if tracker is not None: + tracker.bf16_context = None + super().shutdown() + class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor): def __init__(self, *model_args, gpus_to_use=None, **model_kwargs): diff --git a/test/test_video_predictor.py b/test/test_video_predictor.py new file mode 100644 index 0000000..0427bb9 --- /dev/null +++ b/test/test_video_predictor.py @@ -0,0 +1,28 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved + +import types +import unittest + +import torch +from sam3.model.sam3_video_predictor import Sam3VideoPredictor + + +class TestVideoPredictorShutdown(unittest.TestCase): + def test_exits_tracker_autocast_context(self) -> None: + predictor = Sam3VideoPredictor.__new__(Sam3VideoPredictor) + context = torch.amp.autocast("cpu", dtype=torch.bfloat16) + context.__enter__() + tracker = types.SimpleNamespace(bf16_context=context) + predictor.model = types.SimpleNamespace(tracker=tracker) + predictor._all_inference_states = {} + self.assertTrue(torch.is_autocast_enabled("cpu")) + + predictor.shutdown() + predictor.shutdown() + + self.assertFalse(torch.is_autocast_enabled("cpu")) + self.assertIsNone(tracker.bf16_context) + + +if __name__ == "__main__": + unittest.main()