|
| 1 | +# Copyright 2023 MOSEC Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# refer to https://github.com/facebookresearch/sam2/blob/main/notebooks/image_predictor_example.ipynb |
| 16 | + |
| 17 | +import numbin |
| 18 | +import torch # type: ignore |
| 19 | +from sam2.sam2_image_predictor import SAM2ImagePredictor # type: ignore |
| 20 | + |
| 21 | +from mosec import Server, Worker, get_logger |
| 22 | +from mosec.mixin import MsgpackMixin |
| 23 | + |
| 24 | +logger = get_logger() |
| 25 | +MIN_TF32_MAJOR = 8 |
| 26 | + |
| 27 | + |
| 28 | +class SegmentAnything(MsgpackMixin, Worker): |
| 29 | + def __init__(self): |
| 30 | + # select the device for computation |
| 31 | + if torch.cuda.is_available(): |
| 32 | + device = torch.device("cuda") |
| 33 | + elif torch.backends.mps.is_available(): |
| 34 | + device = torch.device("mps") |
| 35 | + else: |
| 36 | + device = torch.device("cpu") |
| 37 | + logger.info("using device: %s", device) |
| 38 | + |
| 39 | + self.predictor = SAM2ImagePredictor.from_pretrained( |
| 40 | + "facebook/sam2-hiera-large", device=device |
| 41 | + ) |
| 42 | + |
| 43 | + if device.type == "cuda": |
| 44 | + # use bfloat16 |
| 45 | + torch.autocast("cuda", dtype=torch.bfloat16).__enter__() |
| 46 | + # turn on tf32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices) |
| 47 | + if torch.cuda.get_device_properties(0).major >= MIN_TF32_MAJOR: |
| 48 | + torch.backends.cuda.matmul.allow_tf32 = True |
| 49 | + torch.backends.cudnn.allow_tf32 = True |
| 50 | + |
| 51 | + def forward(self, data: dict) -> bytes: |
| 52 | + with torch.inference_mode(): |
| 53 | + self.predictor.set_image(numbin.loads(data["image"])) |
| 54 | + masks, _, _ = self.predictor.predict( |
| 55 | + point_coords=data["point_coords"], |
| 56 | + point_labels=data["labels"], |
| 57 | + mask_input=numbin.loads(data["mask"])[None, :, :], |
| 58 | + multimask_output=False, |
| 59 | + ) |
| 60 | + return numbin.dumps(masks[0]) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + server = Server() |
| 65 | + server.append_worker(SegmentAnything, num=1, max_batch_size=1) |
| 66 | + server.run() |
0 commit comments