-
Notifications
You must be signed in to change notification settings - Fork 252
Port SAM3 from inference/models to inference-models #1946
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
Draft
grzegorz-roboflow
wants to merge
6
commits into
main
Choose a base branch
from
feat/sam3-inference-models
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.
Draft
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
81daa3b
wip
grzegorz-roboflow f0127ba
add triton to requirements
grzegorz-roboflow ecb7ec5
code review
grzegorz-roboflow 5154d5e
code review
grzegorz-roboflow bb1a8a2
Add README
grzegorz-roboflow 26492f7
wip
grzegorz-roboflow 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,61 @@ | ||
| SAM License | ||
| Last Updated: November 19, 2025 | ||
|
|
||
| “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein. | ||
|
|
||
|
|
||
| “SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement. | ||
|
|
||
| “Documentation” means the specifications, manuals and documentation accompanying | ||
| SAM Materials distributed by Meta. | ||
|
|
||
|
|
||
| “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. | ||
|
|
||
|
|
||
| “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). | ||
|
|
||
|
|
||
| “Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom. | ||
|
|
||
|
|
||
| “Trade Controls” means any of the following: Sanctions and applicable export and import controls. | ||
|
|
||
| By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement. | ||
|
|
||
|
|
||
| 1. License Rights and Redistribution. | ||
|
|
||
|
|
||
| a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials. | ||
|
|
||
| b. Redistribution and Use. | ||
| i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials. | ||
|
|
||
|
|
||
| ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication. | ||
|
|
||
|
|
||
| iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws. | ||
| iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials. | ||
| v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons. | ||
| 2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind. | ||
|
|
||
|
|
||
| 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS. | ||
|
|
||
| 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. | ||
|
|
||
| 5. Intellectual Property. | ||
|
|
||
|
|
||
| a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications. | ||
|
|
||
| b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials. | ||
|
|
||
| 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement. | ||
|
|
||
| 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement. | ||
|
|
||
|
|
||
| 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta. |
Empty file.
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,162 @@ | ||
| from abc import ABC, abstractmethod | ||
| from collections import OrderedDict, defaultdict | ||
| from threading import Lock | ||
| from typing import DefaultDict, List, Optional | ||
|
|
||
| import torch | ||
|
|
||
| from inference_models.errors import EnvironmentConfigurationError | ||
| from inference_models.models.sam3.entities import ( | ||
| SAM3ImageEmbeddings, | ||
| SAM3MaskCacheEntry, | ||
| ) | ||
|
|
||
|
|
||
| class Sam3ImageEmbeddingsCache(ABC): | ||
|
|
||
| @abstractmethod | ||
| def retrieve_embeddings(self, key: str) -> Optional[SAM3ImageEmbeddings]: | ||
| pass | ||
|
|
||
| @abstractmethod | ||
| def save_embeddings(self, key: str, embeddings: SAM3ImageEmbeddings) -> None: | ||
| pass | ||
|
|
||
|
|
||
| class Sam3ImageEmbeddingsCacheNullObject(Sam3ImageEmbeddingsCache): | ||
|
|
||
| def retrieve_embeddings(self, key: str) -> Optional[SAM3ImageEmbeddings]: | ||
| pass | ||
|
|
||
| def save_embeddings(self, key: str, embeddings: SAM3ImageEmbeddings) -> None: | ||
| pass | ||
|
|
||
|
|
||
| class Sam3ImageEmbeddingsInMemoryCache(Sam3ImageEmbeddingsCache): | ||
|
|
||
| @classmethod | ||
| def init( | ||
| cls, size_limit: Optional[int], send_to_cpu: bool = True | ||
| ) -> "Sam3ImageEmbeddingsInMemoryCache": | ||
| return cls( | ||
| state=OrderedDict(), | ||
| size_limit=size_limit, | ||
| send_to_cpu=send_to_cpu, | ||
| ) | ||
|
|
||
| def __init__( | ||
| self, | ||
| state: OrderedDict, | ||
| size_limit: Optional[int], | ||
| send_to_cpu: bool = True, | ||
| ): | ||
| self._state = state | ||
| self._size_limit = size_limit | ||
| self._send_to_cpu = send_to_cpu | ||
| self._state_lock = Lock() | ||
|
|
||
| def retrieve_embeddings(self, key: str) -> Optional[SAM3ImageEmbeddings]: | ||
| return self._state.get(key) | ||
|
|
||
| def save_embeddings(self, key: str, embeddings: SAM3ImageEmbeddings) -> None: | ||
| with self._state_lock: | ||
| if key in self._state: | ||
| return None | ||
| self._ensure_cache_has_capacity() | ||
| if self._send_to_cpu: | ||
| embeddings = embeddings.to(device=torch.device("cpu")) | ||
| self._state[key] = embeddings | ||
|
|
||
| def _ensure_cache_has_capacity(self): | ||
| if self._size_limit is None: | ||
| return | ||
| if self._size_limit < 1: | ||
| raise EnvironmentConfigurationError( | ||
| message=f"In memory cache size for SAM3 embeddings was set to invalid value. " | ||
| f"If you are running inference locally - adjust settings of your deployment. If you see this " | ||
| f"error running on Roboflow platform - contact us to get help.", | ||
| help_url="https://todo", | ||
| ) | ||
| while len(self._state) > self._size_limit: | ||
| _ = self._state.popitem(last=False) | ||
|
|
||
|
|
||
| class Sam3LowResolutionMasksCache(ABC): | ||
|
|
||
| @abstractmethod | ||
| def retrieve_all_masks_for_image(self, key: str) -> List[SAM3MaskCacheEntry]: | ||
| pass | ||
|
|
||
| @abstractmethod | ||
| def save_mask(self, key: str, mask: SAM3MaskCacheEntry) -> None: | ||
| pass | ||
|
|
||
|
|
||
| class Sam3LowResolutionMasksCacheNullObject(Sam3LowResolutionMasksCache): | ||
|
|
||
| def retrieve_all_masks_for_image(self, key: str) -> List[SAM3MaskCacheEntry]: | ||
| return [] | ||
|
|
||
| def save_mask(self, key: str, mask: SAM3MaskCacheEntry) -> None: | ||
| pass | ||
|
|
||
|
|
||
| class Sam3LowResolutionMasksInMemoryCache(Sam3LowResolutionMasksCache): | ||
|
|
||
| @classmethod | ||
| def init( | ||
| cls, size_limit: Optional[int], send_to_cpu: bool = True | ||
| ) -> "Sam3LowResolutionMasksInMemoryCache": | ||
| return cls( | ||
| ordering_state=OrderedDict(), | ||
| cache_state=defaultdict(list), | ||
| size_limit=size_limit, | ||
| send_to_cpu=send_to_cpu, | ||
| ) | ||
|
|
||
| def __init__( | ||
| self, | ||
| ordering_state: OrderedDict, | ||
| cache_state: DefaultDict[str, List[SAM3MaskCacheEntry]], | ||
| size_limit: Optional[int], | ||
| send_to_cpu: bool = True, | ||
| ): | ||
| self._ordering_state = ordering_state | ||
| self._cache_state = cache_state | ||
| self._size_limit = size_limit | ||
| self._send_to_cpu = send_to_cpu | ||
| self._state_lock = Lock() | ||
|
|
||
| def retrieve_all_masks_for_image(self, key: str) -> List[SAM3MaskCacheEntry]: | ||
| return self._cache_state.get(key, []) | ||
|
|
||
| def save_mask(self, key: str, mask: SAM3MaskCacheEntry) -> None: | ||
| with self._state_lock: | ||
| if (key, mask.prompt_hash) in self._ordering_state: | ||
| return None | ||
| self._ensure_cache_has_capacity() | ||
| if self._send_to_cpu: | ||
| mask = mask.to(device=torch.device("cpu")) | ||
| self._ordering_state[(key, mask.prompt_hash)] = True | ||
| self._cache_state[key].append(mask) | ||
|
|
||
| def _ensure_cache_has_capacity(self): | ||
| if self._size_limit is None: | ||
| return | ||
| if self._size_limit < 1: | ||
| raise EnvironmentConfigurationError( | ||
| message=f"In memory cache size for SAM3 low resolution masks was set to invalid value. " | ||
| f"If you are running inference locally - adjust settings of your deployment. If you see this " | ||
| f"error running on Roboflow platform - contact us to get help.", | ||
| help_url="https://todo", | ||
| ) | ||
| while len(self._ordering_state) > self._size_limit: | ||
| image_key, prompt_hash = self._ordering_state.popitem(last=False) | ||
| entries_for_image = self._cache_state[image_key] | ||
| to_remove_idx = None | ||
| for i, element in enumerate(entries_for_image): | ||
| if element.prompt_hash == prompt_hash: | ||
| to_remove_idx = i | ||
| break | ||
| if to_remove_idx is not None: | ||
| del entries_for_image[to_remove_idx] | ||
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,50 @@ | ||
| from dataclasses import dataclass | ||
| from typing import Any, Dict, List, Optional, Tuple | ||
|
|
||
| import torch | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SAM3ImageEmbeddings: | ||
| image_hash: str | ||
| image_size_hw: Tuple[int, int] | ||
| embeddings: Dict[str, Any] | ||
|
|
||
| def to(self, device: torch.device) -> "SAM3ImageEmbeddings": | ||
| def _move_to_device(obj: Any) -> Any: | ||
| if isinstance(obj, torch.Tensor): | ||
| return obj.to(device=device) | ||
| elif isinstance(obj, dict): | ||
| return {k: _move_to_device(v) for k, v in obj.items()} | ||
| elif isinstance(obj, list): | ||
| return [_move_to_device(item) for item in obj] | ||
| elif isinstance(obj, tuple): | ||
| return tuple(_move_to_device(item) for item in obj) | ||
| return obj | ||
|
|
||
| return SAM3ImageEmbeddings( | ||
| image_hash=self.image_hash, | ||
| image_size_hw=self.image_size_hw, | ||
| embeddings=_move_to_device(self.embeddings), | ||
| ) | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SAM3Prediction: | ||
| masks: torch.Tensor | ||
| scores: torch.Tensor | ||
| logits: torch.Tensor | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SAM3MaskCacheEntry: | ||
| prompt_hash: str | ||
| serialized_prompt: List[dict] | ||
| mask: torch.Tensor | ||
|
|
||
| def to(self, device: torch.device) -> "SAM3MaskCacheEntry": | ||
| return SAM3MaskCacheEntry( | ||
| prompt_hash=self.prompt_hash, | ||
| serialized_prompt=self.serialized_prompt, | ||
| mask=self.mask.to(device=device), | ||
| ) |
Oops, something went wrong.
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.
Cache capacity check allows exceeding size limit
Low Severity
The
_ensure_cache_has_capacitymethod useswhile len(...) > self._size_limitbut is called BEFORE adding a new item. This means when the cache has exactlysize_limititems, nothing is removed, and the subsequent add causes the cache to exceed its limit by one item. The condition needs>=instead of>to properly make room before adding.Additional Locations (1)
inference_models/inference_models/models/sam3/cache.py#L152-L153