Run Facebook’s Segment Anything Model 2 (SAM 2) on Modal

This example demonstrates how to deploy Facebook’s SAM 2 on Modal. SAM2 is a powerful, flexible image and video segmentation model that can be used for various computer vision tasks like object detection, instance segmentation, and even as a foundation for more complex computer vision applications. SAM2 extends the capabilities of the original SAM to include video segmentation.

In particular, this example segments this video of a man jumping off the cliff.

The output should look something like this:

Set up dependencies for SAM 2 

First, we set up the necessary dependencies, including torch, opencv, huggingface_hub, torchvision, and the sam2 library.

We also install ffmpeg, which we will use to manipulate videos, and a Python wrapper called ffmpeg-python for a clean interface.

Wrapping the SAM 2 model in a Modal class 

Next, we define the Model class that will handle SAM 2 operations for both image and video.

We use the @modal.enter() decorators here for optimization: it makes sure the initialization method runs only once, when a new container starts, instead of in the path of every call. We’ll also use a modal Volume to cache the model weights so that they don’t need to be downloaded repeatedly when we start new containers. For more on storing model weights on Modal, see this guide.

Segmenting videos from the command line 

Finally, we define a local_entrypoint to run the segmentation from our local machine’s terminal.

There are several ways to pass files between the local machine and the Modal Function.

One way is to upload the files onto a Modal Volume, which acts as a distributed filesystem.

The other way is to convert the file to bytes and pass the bytes back and forth as the input or output of Python functions. We use this method to get the video file with the segmentation results in it back to the local machine.

Helper functions for SAM 2 inference 

Above, we used some helper functions to for some of the details, like breaking the video into frames. These are defined below.