Instructions to use CollectionStudio/sam2-hiera-base-plus with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use CollectionStudio/sam2-hiera-base-plus with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("mask-generation", model="CollectionStudio/sam2-hiera-base-plus")# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModel processor = AutoProcessor.from_pretrained("CollectionStudio/sam2-hiera-base-plus") model = AutoModel.from_pretrained("CollectionStudio/sam2-hiera-base-plus", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Commit ·
5e8b907
0
Parent(s):
Duplicate from facebook/sam2-hiera-base-plus
Browse filesCo-authored-by: Haitham Khedr <hkhedr@users.noreply.huggingface.co>
Files changed (9)
- .gitattributesAdded+35
- README.mdAdded+542
- config.jsonAdded+233
- model.safetensorsAdded+3
- preprocessor_config.jsonAdded+36
- processor_config.jsonAdded+5
- sam2_hiera_b+.yamlAdded+113
- sam2_hiera_base_plus.ptAdded+3
- video_preprocessor_config.jsonAdded+36
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542---license: apache-2.0pipeline_tag: mask-generationlibrary_name: transformers---
Repository for SAM 2: Segment Anything in Images and Videos, a foundation model towards solving promptable visual segmentation in images and videos from FAIR. See the [SAM 2 paper](https://arxiv.org/abs/2408.00714) for more information.
The official code is publicly release in this [repo](https://github.com/facebookresearch/segment-anything-2/).
## Usage
For image prediction:
```pythonimport torchfrom sam2.sam2_image_predictor import SAM2ImagePredictor
predictor = SAM2ImagePredictor.from_pretrained("facebook/sam2-hiera-base-plus")
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): predictor.set_image(<your_image>) masks, _, _ = predictor.predict(<input_prompts>)```
For video prediction:
```pythonimport torchfrom sam2.sam2_video_predictor import SAM2VideoPredictor
predictor = SAM2VideoPredictor.from_pretrained("facebook/sam2-hiera-base-plus")
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): state = predictor.init_state(<your_video>)
# add new prompts and instantly get the output on the same frame frame_idx, object_ids, masks = predictor.add_new_points_or_box(state, <your_prompts>):
# propagate the prompts to get masklets throughout the video for frame_idx, object_ids, masks in predictor.propagate_in_video(state): ...```
Refer to the [demo notebooks](https://github.com/facebookresearch/segment-anything-2/tree/main/notebooks) for details.
## Usage with 🤗 Transformers
### Automatic Mask Generation with Pipeline
SAM2 can be used for automatic mask generation to segment all objects in an image using the `mask-generation` pipeline:
```python>>> from transformers import pipeline
>>> generator = pipeline("mask-generation", model="facebook/sam2-hiera-base-plus", device=0)>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg">>> outputs = generator(image_url, points_per_batch=64)
>>> len(outputs["masks"]) # Number of masks generated39```
### Basic Image Segmentation
#### Single Point Click
You can segment objects by providing a single point click on the object you want to segment:
```python>>> from transformers import Sam2Processor, Sam2Model>>> import torch>>> from PIL import Image>>> import requests
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = Sam2Model.from_pretrained("facebook/sam2-hiera-base-plus").to(device)>>> processor = Sam2Processor.from_pretrained("facebook/sam2-hiera-base-plus")
>>> image_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg">>> raw_image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
>>> input_points = [[[[500, 375]]]] # Single point click, 4 dimensions (image_dim, object_dim, point_per_object_dim, coordinates)>>> input_labels = [[[1]]] # 1 for positive click, 0 for negative click, 3 dimensions (image_dim, object_dim, point_label)
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]
>>> # The model outputs multiple mask predictions ranked by quality score>>> print(f"Generated {masks.shape[1]} masks with shape {masks.shape}")Generated 3 masks with shape torch.Size(1, 3, 1500, 2250)```
#### Multiple Points for Refinement
You can provide multiple points to refine the segmentation:
```python>>> # Add both positive and negative points to refine the mask>>> input_points = [[[[500, 375], [1125, 625]]]] # Multiple points for refinement>>> input_labels = [[[1, 1]]] # Both positive clicks
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]```
#### Bounding Box Input
SAM2 also supports bounding box inputs for segmentation:
```python>>> # Define bounding box as [x_min, y_min, x_max, y_max]>>> input_boxes = [[[75, 275, 1725, 850]]]
>>> inputs = processor(images=raw_image, input_boxes=input_boxes, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs)
>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]```
#### Multiple Objects Segmentation
You can segment multiple objects simultaneously:
```python>>> # Define points for two different objects>>> input_points = [[[[500, 375]], [[650, 750]]]] # Points for two objects in same image>>> input_labels = [[[1], [1]]] # Positive clicks for both objects
>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs, multimask_output=False)
>>> # Each object gets its own mask>>> masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])[0]>>> print(f"Generated masks for {masks.shape[0]} objects")Generated masks for 2 objects```
### Batch Inference
#### Batched Images
Process multiple images simultaneously for improved efficiency:
```python>>> from transformers import Sam2Processor, Sam2Model>>> import torch>>> from PIL import Image>>> import requests
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = Sam2Model.from_pretrained("facebook/sam2-hiera-base-plus").to(device)>>> processor = Sam2Processor.from_pretrained("facebook/sam2-hiera-base-plus")
>>> # Load multiple images>>> image_urls = [... "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/truck.jpg",... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/dog-sam.png"... ]>>> raw_images = [Image.open(requests.get(url, stream=True).raw).convert("RGB") for url in image_urls]
>>> # Single point per image>>> input_points = [[[[500, 375]]], [[[770, 200]]]] # One point for each image>>> input_labels = [[[1]], [[1]]] # Positive clicks for both images
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs, multimask_output=False)
>>> # Post-process masks for each image>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])>>> print(f"Processed {len(all_masks)} images, each with {all_masks[0].shape[0]} objects")Processed 2 images, each with 1 objects```
#### Batched Objects per Image
Segment multiple objects within each image using batch inference:
```python>>> # Multiple objects per image - different numbers of objects per image>>> input_points = [... [[[500, 375]], [[650, 750]]], # Truck image: 2 objects... [[[770, 200]]] # Dog image: 1 object... ]>>> input_labels = [... [[1], [1]], # Truck image: positive clicks for both objects... [[1]] # Dog image: positive click for the object... ]
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs, multimask_output=False)
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])```
#### Batched Images with Batched Objects and Multiple Points
Handle complex batch scenarios with multiple points per object:
```python>>> # Add groceries image for more complex example>>> groceries_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/groceries.jpg">>> groceries_image = Image.open(requests.get(groceries_url, stream=True).raw).convert("RGB")>>> raw_images = [raw_images[0], groceries_image] # Use truck and groceries images
>>> # Complex batching: multiple images, multiple objects, multiple points per object>>> input_points = [... [[[500, 375]], [[650, 750]]], # Truck image: 2 objects with 1 point each... [[[400, 300]], [[630, 300], [550, 300]]] # Groceries image: obj1 has 1 point, obj2 has 2 points... ]>>> input_labels = [... [[1], [1]], # Truck image: positive clicks... [[1], [1, 1]] # Groceries image: positive clicks for refinement... ]
>>> inputs = processor(images=raw_images, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs, multimask_output=False)
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])```
#### Batched Bounding Boxes
Process multiple images with bounding box inputs:
```python>>> # Multiple bounding boxes per image (using truck and groceries images)>>> input_boxes = [... [[75, 275, 1725, 850], [425, 600, 700, 875], [1375, 550, 1650, 800], [1240, 675, 1400, 750]], # Truck image: 4 boxes... [[450, 170, 520, 350], [350, 190, 450, 350], [500, 170, 580, 350], [580, 170, 640, 350]] # Groceries image: 4 boxes... ]
>>> # Update images for this example>>> raw_images = [raw_images[0], groceries_image] # truck and groceries
>>> inputs = processor(images=raw_images, input_boxes=input_boxes, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs, multimask_output=False)
>>> all_masks = processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"])>>> print(f"Processed {len(input_boxes)} images with {len(input_boxes[0])} and {len(input_boxes[1])} boxes respectively")Processed 2 images with 4 and 4 boxes respectively```
### Using Previous Masks as Input
SAM2 can use masks from previous predictions as input to refine segmentation:
```python>>> # Get initial segmentation>>> input_points = [[[[500, 375]]]]>>> input_labels = [[[1]]]>>> inputs = processor(images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():... outputs = model(**inputs)
>>> # Use the best mask as input for refinement>>> mask_input = outputs.pred_masks[:, :, torch.argmax(outputs.iou_scores.squeeze())]
>>> # Add additional points with the mask input>>> new_input_points = [[[[500, 375], [450, 300]]]]>>> new_input_labels = [[[1, 1]]]>>> inputs = processor(... input_points=new_input_points,... input_labels=new_input_labels,... original_sizes=inputs["original_sizes"],... return_tensors="pt",... ).to(device)
>>> with torch.no_grad():... refined_outputs = model(... **inputs,... input_masks=mask_input,... image_embeddings=outputs.image_embeddings,... multimask_output=False,... )```
### Video Segmentation and Tracking
SAM2's key strength is its ability to track objects across video frames. Here's how to use it for video segmentation:
#### Basic Video Tracking
```python>>> from transformers import Sam2VideoModel, Sam2VideoProcessor>>> import torch
>>> device = "cuda" if torch.cuda.is_available() else "cpu">>> model = Sam2VideoModel.from_pretrained("facebook/sam2-hiera-base-plus").to(device, dtype=torch.bfloat16)>>> processor = Sam2VideoProcessor.from_pretrained("facebook/sam2-hiera-base-plus")
>>> # Load video frames (example assumes you have a list of PIL Images)>>> # video_frames = [Image.open(f"frame_{i:05d}.jpg") for i in range(num_frames)]
>>> # For this example, we'll use the video loading utility>>> from transformers.video_utils import load_video>>> video_url = "https://huggingface.co/datasets/hf-internal-testing/sam2-fixtures/resolve/main/bedroom.mp4">>> video_frames, _ = load_video(video_url)
>>> # Initialize video inference session>>> inference_session = processor.init_video_session(... video=video_frames,... inference_device=device,... torch_dtype=torch.bfloat16,... )
>>> # Add click on first frame to select object>>> ann_frame_idx = 0>>> ann_obj_id = 1>>> points = [[[[210, 350]]]]>>> labels = [[[1]]]
>>> processor.add_inputs_to_inference_session(... inference_session=inference_session,... frame_idx=ann_frame_idx,... obj_ids=ann_obj_id,... input_points=points,... input_labels=labels,... )
>>> # Segment the object on the first frame>>> outputs = model(... inference_session=inference_session,... frame_idx=ann_frame_idx,... )>>> video_res_masks = processor.post_process_masks(... [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]>>> print(f"Segmentation shape: {video_res_masks.shape}")Segmentation shape: torch.Size([1, 1, 480, 854])
>>> # Propagate through the entire video>>> video_segments = {}>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):... video_res_masks = processor.post_process_masks(... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]... video_segments[sam2_video_output.frame_idx] = video_res_masks
>>> print(f"Tracked object through {len(video_segments)} frames")Tracked object through 180 frames```
#### Multi-Object Video Tracking
Track multiple objects simultaneously across video frames:
```python>>> # Reset for new tracking session>>> inference_session.reset_inference_session()
>>> # Add multiple objects on the first frame>>> ann_frame_idx = 0>>> obj_ids = [2, 3]>>> input_points = [[[[200, 300]], [[400, 150]]]] # Points for two objects (batched)>>> input_labels = [[[1], [1]]]
>>> processor.add_inputs_to_inference_session(... inference_session=inference_session,... frame_idx=ann_frame_idx,... obj_ids=obj_ids,... input_points=input_points,... input_labels=input_labels,... )
>>> # Get masks for both objects on first frame>>> outputs = model(... inference_session=inference_session,... frame_idx=ann_frame_idx,... )
>>> # Propagate both objects through video>>> video_segments = {}>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):... video_res_masks = processor.post_process_masks(... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]... video_segments[sam2_video_output.frame_idx] = {... obj_id: video_res_masks[i]... for i, obj_id in enumerate(inference_session.obj_ids)... }
>>> print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")Tracked 2 objects through 180 frames```
#### Refining Video Segmentation
You can add additional clicks on any frame to refine the tracking:
```python>>> # Add refinement click on a later frame>>> refine_frame_idx = 50>>> ann_obj_id = 2 # Refining first object>>> points = [[[[220, 280]]]] # Additional point>>> labels = [[[1]]] # Positive click
>>> processor.add_inputs_to_inference_session(... inference_session=inference_session,... frame_idx=refine_frame_idx,... obj_ids=ann_obj_id,... input_points=points,... input_labels=labels,... )
>>> # Re-propagate with the additional information>>> video_segments = {}>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):... video_res_masks = processor.post_process_masks(... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]... video_segments[sam2_video_output.frame_idx] = video_res_masks```
### Streaming Video Inference
For real-time applications, SAM2 supports processing video frames as they arrive:
```python>>> # Initialize session for streaming>>> inference_session = processor.init_video_session(... inference_device=device,... torch_dtype=torch.bfloat16,... )
>>> # Process frames one by one>>> for frame_idx, frame in enumerate(video_frames[:10]): # Process first 10 frames... inputs = processor(images=frame, device=device, return_tensors="pt")...... if frame_idx == 0:... # Add point input on first frame... processor.add_inputs_to_inference_session(... inference_session=inference_session,... frame_idx=0,... obj_ids=1,... input_points=[[[[210, 350], [250, 220]]]],... input_labels=[[[1, 1]]],... original_size=inputs.original_sizes[0], # need to be provided when using streaming video inference... )...... # Process current frame... sam2_video_output = model(inference_session=inference_session, frame=inputs.pixel_values[0])...... video_res_masks = processor.post_process_masks(... [sam2_video_output.pred_masks], original_sizes=inputs.original_sizes, binarize=False... )[0]... print(f"Frame {frame_idx}: mask shape {video_res_masks.shape}")```
#### Video Batch Processing for Multiple Objects
Track multiple objects simultaneously in video by adding them all at once:
```python>>> # Initialize video session>>> inference_session = processor.init_video_session(... video=video_frames,... inference_device=device,... torch_dtype=torch.bfloat16,... )
>>> # Add multiple objects on the first frame using batch processing>>> ann_frame_idx = 0>>> obj_ids = [2, 3] # Track two different objects>>> input_points = [... [[[200, 300], [230, 250], [275, 175]], [[400, 150]]]... ] # Object 2: 3 points (2 positive, 1 negative); Object 3: 1 point>>> input_labels = [... [[1, 1, 0], [1]]... ] # Object 2: positive, positive, negative; Object 3: positive
>>> processor.add_inputs_to_inference_session(... inference_session=inference_session,... frame_idx=ann_frame_idx,... obj_ids=obj_ids,... input_points=input_points,... input_labels=input_labels,... )
>>> # Get masks for all objects on the first frame>>> outputs = model(... inference_session=inference_session,... frame_idx=ann_frame_idx,... )>>> video_res_masks = processor.post_process_masks(... [outputs.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]>>> print(f"Generated masks for {video_res_masks.shape[0]} objects")Generated masks for 2 objects
>>> # Propagate all objects through the video>>> video_segments = {}>>> for sam2_video_output in model.propagate_in_video_iterator(inference_session):... video_res_masks = processor.post_process_masks(... [sam2_video_output.pred_masks], original_sizes=[[inference_session.video_height, inference_session.video_width]], binarize=False... )[0]... video_segments[sam2_video_output.frame_idx] = {... obj_id: video_res_masks[i]... for i, obj_id in enumerate(inference_session.obj_ids)... }
>>> print(f"Tracked {len(inference_session.obj_ids)} objects through {len(video_segments)} frames")Tracked 2 objects through 180 frames```
### Citation
To cite the paper, model, or software, please use the below:```@article{ravi2024sam2, title={SAM 2: Segment Anything in Images and Videos}, author={Ravi, Nikhila and Gabeur, Valentin and Hu, Yuan-Ting and Hu, Ronghang and Ryali, Chaitanya and Ma, Tengyu and Khedr, Haitham and R{\"a}dle, Roman and Rolland, Chloe and Gustafson, Laura and Mintun, Eric and Pan, Junting and Alwala, Kalyan Vasudev and Carion, Nicolas and Wu, Chao-Yuan and Girshick, Ross and Doll{\'a}r, Piotr and Feichtenhofer, Christoph}, journal={arXiv preprint arXiv:2408.00714}, url={https://arxiv.org/abs/2408.00714}, year={2024}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233{ "architectures": [ "Sam2VideoModel" ], "enable_occlusion_spatial_embedding": false, "enable_temporal_pos_encoding_for_object_pointers": false, "image_size": 1024, "initializer_range": 0.02, "mask_decoder_config": { "attention_downsample_rate": 2, "dynamic_multimask_stability_delta": 0.05, "dynamic_multimask_stability_thresh": 0.98, "dynamic_multimask_via_stability": true, "hidden_act": "gelu", "hidden_size": 256, "iou_head_depth": 3, "iou_head_hidden_dim": 256, "mlp_dim": 2048, "model_type": "", "num_attention_heads": 8, "num_hidden_layers": 2, "num_multimask_outputs": 3 }, "mask_downsampler_embed_dim": 256, "mask_downsampler_hidden_act": "gelu", "mask_downsampler_kernel_size": 3, "mask_downsampler_padding": 1, "mask_downsampler_stride": 2, "mask_downsampler_total_stride": 16, "max_object_pointers_in_encoder": 16, "memory_attention_downsample_rate": 1, "memory_attention_dropout": 0.1, "memory_attention_feed_forward_hidden_act": "relu", "memory_attention_feed_forward_hidden_size": 2048, "memory_attention_hidden_size": 256, "memory_attention_num_attention_heads": 1, "memory_attention_num_layers": 4, "memory_attention_rope_dropout": 0.1, "memory_attention_rope_feat_sizes": [ 64, 64 ], "memory_attention_rope_theta": 10000, "memory_encoder_hidden_size": 256, "memory_encoder_output_channels": 64, "memory_fuser_embed_dim": 256, "memory_fuser_hidden_act": "gelu", "memory_fuser_intermediate_dim": 1024, "memory_fuser_kernel_size": 7, "memory_fuser_layer_scale_init_value": 1e-06, "memory_fuser_num_layers": 2, "memory_fuser_padding": 3, "model_type": "sam2_video", "multimask_max_pt_num": 1, "multimask_min_pt_num": 0, "multimask_output_for_tracking": true, "multimask_output_in_sam": true, "num_maskmem": 7, "prompt_encoder_config": { "hidden_act": "gelu", "hidden_size": 256, "image_size": 1024, "layer_norm_eps": 1e-06, "mask_input_channels": 16, "model_type": "", "num_point_embeddings": 4, "patch_size": 16, "scale": 1 }, "sigmoid_bias_for_mem_enc": -10.0, "sigmoid_scale_for_mem_enc": 20.0, "torch_dtype": "float32", "transformers_version": "4.56.0.dev0", "vision_config": { "backbone_channel_list": [ 896, 448, 224, 112 ], "backbone_config": { "_name_or_path": "", "add_cross_attention": false, "architectures": null, "bad_words_ids": null, "begin_suppress_tokens": null, "blocks_per_stage": [ 2, 3, 16, 3 ], "bos_token_id": null, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "early_stopping": false, "embed_dim_per_stage": [ 112, 224, 448, 896 ], "encoder_no_repeat_ngram_size": 0, "eos_token_id": null, "exponential_decay_length_penalty": null, "finetuning_task": null, "forced_bos_token_id": null, "forced_eos_token_id": null, "global_attention_blocks": [ 12, 16, 20 ], "hidden_act": "gelu", "hidden_size": 112, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "image_size": [ 1024, 1024 ], "initializer_range": 0.02, "is_decoder": false, "is_encoder_decoder": false, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "layer_norm_eps": 1e-06, "length_penalty": 1.0, "max_length": 20, "min_length": 0, "mlp_ratio": 4.0, "model_type": "sam2_hiera_det_model", "no_repeat_ngram_size": 0, "num_attention_heads": 1, "num_attention_heads_per_stage": [ 2, 4, 8, 16 ], "num_beam_groups": 1, "num_beams": 1, "num_channels": 3, "num_query_pool_stages": 3, "num_return_sequences": 1, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": null, "patch_kernel_size": [ 7, 7 ], "patch_padding": [ 3, 3 ], "patch_stride": [ 4, 4 ], "prefix": null, "problem_type": null, "pruned_heads": {}, "query_stride": [ 2, 2 ], "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "sep_token_id": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": true, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "torch_dtype": null, "torchscript": false, "typical_p": 1.0, "use_bfloat16": false, "window_positional_embedding_background_size": [ 14, 14 ], "window_size_per_stage": [ 8, 4, 14, 7 ] }, "backbone_feature_sizes": [ [ 256, 256 ], [ 128, 128 ], [ 64, 64 ] ], "fpn_hidden_size": 256, "fpn_kernel_size": 1, "fpn_padding": 0, "fpn_stride": 1, "fpn_top_down_levels": [ 2, 3 ], "hidden_act": "gelu", "initializer_range": 0.02, "layer_norm_eps": 1e-06, "model_type": "sam2_vision_model", "num_feature_levels": 3 }}123version https://git-lfs.github.com/spec/v1oid sha256:cce38e86bf9fb50a6c7a454776d280b992ea16f763ed0db3f9db9fde4655b3f1size 323409896123456789101112131415161718192021222324252627282930313233343536{ "crop_size": null, "data_format": "channels_first", "default_to_square": true, "device": null, "disable_grouping": null, "do_center_crop": null, "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.485, 0.456, 0.406 ], "image_processor_type": "Sam2ImageProcessorFast", "image_std": [ 0.229, 0.224, 0.225 ], "input_data_format": null, "mask_size": { "height": 256, "width": 256 }, "processor_class": "Sam2VideoProcessor", "resample": 2, "rescale_factor": 0.00392156862745098, "return_tensors": null, "size": { "height": 1024, "width": 1024 }}12345{ "point_pad_value": -10, "processor_class": "Sam2VideoProcessor", "target_size": 1024}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# @package _global_
# Modelmodel: _target_: sam2.modeling.sam2_base.SAM2Base image_encoder: _target_: sam2.modeling.backbones.image_encoder.ImageEncoder scalp: 1 trunk: _target_: sam2.modeling.backbones.hieradet.Hiera embed_dim: 112 num_heads: 2 neck: _target_: sam2.modeling.backbones.image_encoder.FpnNeck position_encoding: _target_: sam2.modeling.position_encoding.PositionEmbeddingSine num_pos_feats: 256 normalize: true scale: null temperature: 10000 d_model: 256 backbone_channel_list: [896, 448, 224, 112] fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features fpn_interp_model: nearest
memory_attention: _target_: sam2.modeling.memory_attention.MemoryAttention d_model: 256 pos_enc_at_input: true layer: _target_: sam2.modeling.memory_attention.MemoryAttentionLayer activation: relu dim_feedforward: 2048 dropout: 0.1 pos_enc_at_attn: false self_attention: _target_: sam2.modeling.sam.transformer.RoPEAttention rope_theta: 10000.0 feat_sizes: [32, 32] embedding_dim: 256 num_heads: 1 downsample_rate: 1 dropout: 0.1 d_model: 256 pos_enc_at_cross_attn_keys: true pos_enc_at_cross_attn_queries: false cross_attention: _target_: sam2.modeling.sam.transformer.RoPEAttention rope_theta: 10000.0 feat_sizes: [32, 32] rope_k_repeat: True embedding_dim: 256 num_heads: 1 downsample_rate: 1 dropout: 0.1 kv_in_dim: 64 num_layers: 4
memory_encoder: _target_: sam2.modeling.memory_encoder.MemoryEncoder out_dim: 64 position_encoding: _target_: sam2.modeling.position_encoding.PositionEmbeddingSine num_pos_feats: 64 normalize: true scale: null temperature: 10000 mask_downsampler: _target_: sam2.modeling.memory_encoder.MaskDownSampler kernel_size: 3 stride: 2 padding: 1 fuser: _target_: sam2.modeling.memory_encoder.Fuser layer: _target_: sam2.modeling.memory_encoder.CXBlock dim: 256 kernel_size: 7 padding: 3 layer_scale_init_value: 1e-6 use_dwconv: True # depth-wise convs num_layers: 2
num_maskmem: 7 image_size: 1024 # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask sigmoid_scale_for_mem_enc: 20.0 sigmoid_bias_for_mem_enc: -10.0 use_mask_input_as_output_without_sam: true # Memory directly_add_no_mem_embed: true # use high-resolution feature map in the SAM mask decoder use_high_res_features_in_sam: true # output 3 masks on the first click on initial conditioning frames multimask_output_in_sam: true # SAM heads iou_prediction_use_sigmoid: True # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder use_obj_ptrs_in_encoder: true add_tpos_enc_to_obj_ptrs: false only_obj_ptrs_in_the_past_for_eval: true # object occlusion prediction pred_obj_scores: true pred_obj_scores_mlp: true fixed_no_obj_ptr: true # multimask tracking settings multimask_output_for_tracking: true use_multimask_token_for_obj_ptr: true multimask_min_pt_num: 0 multimask_max_pt_num: 1 use_mlp_for_obj_ptr_proj: true # Compilation flag compile_image_encoder: False123version https://git-lfs.github.com/spec/v1oid sha256:d0bb7f236400a49669ffdd1be617959a8b1d1065081789d7bbff88eded3a8071size 323493298123456789101112131415161718192021222324252627282930313233343536{ "crop_size": null, "data_format": "channels_first", "default_to_square": true, "device": null, "do_center_crop": null, "do_convert_rgb": true, "do_normalize": true, "do_pad": null, "do_rescale": true, "do_resize": true, "do_sample_frames": null, "fps": null, "image_mean": [ 0.485, 0.456, 0.406 ], "image_std": [ 0.229, 0.224, 0.225 ], "input_data_format": null, "num_frames": null, "processor_class": "Sam2VideoProcessor", "resample": 2, "rescale_factor": 0.00392156862745098, "size": { "height": 1024, "width": 1024 }, "size_divisor": null, "video_metadata": null, "video_processor_type": "Sam2VideoVideoProcessor"}.gitattributesAdded+35
README.mdAdded+542
config.jsonAdded+233
model.safetensorsAdded+3
preprocessor_config.jsonAdded+36
processor_config.jsonAdded+5
sam2_hiera_b+.yamlAdded+113
sam2_hiera_base_plus.ptAdded+3
video_preprocessor_config.jsonAdded+36