Mask Generation
sam2
swift-object-cutout
segment-anything
interactive-segmentation
background-removal
core-ai
apple-silicon
macos
Instructions to use arraypress/cutout-sam2-tiny with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sam2
How to use arraypress/cutout-sam2-tiny with sam2:
# Use SAM2 with images import torch from sam2.sam2_image_predictor import SAM2ImagePredictor predictor = SAM2ImagePredictor.from_pretrained("arraypress/cutout-sam2-tiny") with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): predictor.set_image(<your_image>) masks, _, _ = predictor.predict(<input_prompts>)# Use SAM2 with videos import torch from sam2.sam2_video_predictor import SAM2VideoPredictor predictor = SAM2VideoPredictor.from_pretrained("arraypress/cutout-sam2-tiny") 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(state, <your_prompts>) # propagate the prompts to get masklets throughout the video for frame_idx, object_ids, masks in predictor.propagate_in_video(state): ... - Notebooks
- Google Colab
- Kaggle
SAM 2.1 tiny as a Core AI .aimodel (float16, encode + decode), with README, licence and export script
Browse files- .gitattributes +1 -0
- LICENSE +201 -0
- NOTICE +15 -0
- README.md +96 -0
- cutout-sam2-tiny-float16.aimodel/main.hash +2 -0
- cutout-sam2-tiny-float16.aimodel/main.mlirb +3 -0
- cutout-sam2-tiny-float16.aimodel/metadata.json +8 -0
- export_sam2.py +152 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
cutout-sam2-tiny-float16.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cutout-sam2-tiny: SAM 2.1 hiera tiny, Copyright (c) Meta Platforms, Inc. and
|
| 2 |
+
affiliates. Code: facebookresearch/sam2 at commit
|
| 3 |
+
2b90b9f5ceec907a1c18123530e92e794ad901a4. Weights: facebook/sam2.1-hiera-tiny
|
| 4 |
+
at revision de431c4043854a71d8101e17995dfe596bf101a5 (sam2.1_hiera_tiny.pt).
|
| 5 |
+
Both Apache License 2.0; see LICENSE.
|
| 6 |
+
|
| 7 |
+
Changed for Core AI, in export_sam2.py:
|
| 8 |
+
- The image predictor's own steps are traced as two entry points: `encode`
|
| 9 |
+
(normalisation, image encoder, no-memory embedding) and `decode` (prompt
|
| 10 |
+
encoder for one point, mask decoder, multimask output).
|
| 11 |
+
- Weights and arithmetic are float16, except the prompt encoder, which stays
|
| 12 |
+
float32; every input and output is float32.
|
| 13 |
+
- The 256x256 mask logits are returned unclamped (the PyTorch predictor clamps
|
| 14 |
+
them to +/-32; the host thresholds them).
|
| 15 |
+
The trained weights are otherwise the authors', unmodified.
|
README.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
base_model: facebook/sam2.1-hiera-tiny
|
| 4 |
+
tags:
|
| 5 |
+
- segment-anything
|
| 6 |
+
- sam2
|
| 7 |
+
- interactive-segmentation
|
| 8 |
+
- background-removal
|
| 9 |
+
- core-ai
|
| 10 |
+
- apple-silicon
|
| 11 |
+
- macos
|
| 12 |
+
library_name: swift-object-cutout
|
| 13 |
+
pipeline_tag: mask-generation
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# cutout-sam2-tiny: SAM 2.1 tiny for Core AI (macOS 27)
|
| 17 |
+
|
| 18 |
+
[SAM 2.1](https://github.com/facebookresearch/sam2) hiera tiny (Ravi et al., Meta, *SAM 2: Segment
|
| 19 |
+
Anything in Images and Videos*, 2024; code and weights Apache-2.0), exported to an Apple Core AI
|
| 20 |
+
`.aimodel`. Click a point on a picture and it returns the object under it: three candidate masks
|
| 21 |
+
and the network's own estimate of how good each one is.
|
| 22 |
+
|
| 23 |
+
[`cutout`](https://github.com/arraypress/swift-cutout-cli) uses it for `--at` (click to cut), through
|
| 24 |
+
[swift-object-cutout](https://github.com/arraypress/swift-object-cutout). It downloads this
|
| 25 |
+
repository by itself the first time it is needed, pinned to one commit, with every file checked
|
| 26 |
+
against its published hash.
|
| 27 |
+
|
| 28 |
+
## Files
|
| 29 |
+
|
| 30 |
+
| Path | What |
|
| 31 |
+
|---|---|
|
| 32 |
+
| `cutout-sam2-tiny-float16.aimodel/` | Two entry points (below). Float16 weights and arithmetic, float32 inputs and outputs, 63 MB. |
|
| 33 |
+
| `export_sam2.py` | The export script (`SAM2_BUILD_CUDA=0 uv run export_sam2.py --dtype float16`). |
|
| 34 |
+
| `LICENSE`, `NOTICE` | The authors' Apache-2.0 licence, and what the export changed. |
|
| 35 |
+
|
| 36 |
+
**`encode`**: `image` `[1,3,1024,1024]` float32, RGB in 0…1 → `image_embedding` `[1,256,64,64]`,
|
| 37 |
+
`feats_s0` `[1,32,256,256]`, `feats_s1` `[1,64,128,128]`. The host stretches the picture to
|
| 38 |
+
1024×1024 without keeping its aspect ratio, as SAM 2's own predictor does; the ImageNet
|
| 39 |
+
normalisation and SAM 2's no-memory embedding are inside.
|
| 40 |
+
|
| 41 |
+
**`decode`**: the three encoder outputs, `point` `[1,1,2]` (x then y, in pixels of the 1024² square)
|
| 42 |
+
and `label` `[1,1]` (1 = the object, 0 = not it) → `masks` `[1,3,256,256]` logits and `scores`
|
| 43 |
+
`[1,3]`, the predicted IoU of each. Take the best-scoring mask, threshold it at 0 and stretch it back
|
| 44 |
+
over the picture. One encoding serves any number of clicks.
|
| 45 |
+
|
| 46 |
+
Nothing in the network is rewritten: the two entry points are the official
|
| 47 |
+
`SAM2ImagePredictor.set_image` and `_predict` steps, traced as they are. In float32 on the CPU the
|
| 48 |
+
traced steps match the predictor to 8 × 10⁻⁵ in the logits.
|
| 49 |
+
|
| 50 |
+
## Fidelity
|
| 51 |
+
|
| 52 |
+
60 clicks (two per picture) on 30 generated pictures: 20 AI-generated room and house scenes at
|
| 53 |
+
1024², and 10 synthetic shape scenes at sizes from 640×480 to 1600×900. The same 1024² pixels went
|
| 54 |
+
to every runtime. The reference is the PyTorch original in float32 on the CPU; "chosen" is the
|
| 55 |
+
best-scoring mask, which is the one a click returns.
|
| 56 |
+
|
| 57 |
+
| Runtime | Chosen-mask IoU, mean | worst | Clicks ≥ 0.99 | Same mask chosen | Score error, worst |
|
| 58 |
+
|---|---|---|---|---|---|
|
| 59 |
+
| this export, float16 (this repo) | 0.9996 | 0.9959 | 60 of 60 | 60 of 60 | 0.006 |
|
| 60 |
+
| this export, float32 (not published) | 1.0000 | 1.0000 | 60 of 60 | 60 of 60 | < 10⁻⁴ |
|
| 61 |
+
| Apple's Core ML conversion (`apple/coreml-sam2.1-tiny`, FLOAT16) | 0.968 | 0.500 | 34 of 60 | 56 of 60 | 0.22 |
|
| 62 |
+
|
| 63 |
+
Apple's Core ML conversion is what `cutout` ran before. Its masks drift from the original on
|
| 64 |
+
textured scenes, where it sometimes picks a different mask (IoU 0.50 on one click). This export
|
| 65 |
+
agrees with the original on every click. On the synthetic scenes the two runtimes agree to
|
| 66 |
+
0.99 or better, end to end; on the generated rooms they differ by as much as Apple's conversion differs
|
| 67 |
+
from the original.
|
| 68 |
+
|
| 69 |
+
## Speed and memory
|
| 70 |
+
|
| 71 |
+
Apple M3 Max, macOS 27, GPU, measured through `cutout`:
|
| 72 |
+
|
| 73 |
+
- **First load:** compiles the model for the Mac in well under a second and keeps a 60 MB compiled
|
| 74 |
+
copy in `~/Library/Caches/coreai-cache`.
|
| 75 |
+
- **Per click:** `encode` takes 0.15 s and `decode` 5 ms. One `cutout --at` run takes 0.6–1.0 s from
|
| 76 |
+
start to finish, against 4.5 s for the Core ML conversion, most of which went on loading.
|
| 77 |
+
- **Batches:** a folder of 30 pictures took 0.51 s per picture (decode, model, edge, PNG), against
|
| 78 |
+
0.42 s for the Core ML conversion, which ran on the Neural Engine.
|
| 79 |
+
- **Memory:** the folder run peaked at 1.2 GB, against 1.4 GB for the Core ML conversion.
|
| 80 |
+
|
| 81 |
+
## Use
|
| 82 |
+
|
| 83 |
+
```sh
|
| 84 |
+
cutout photo.jpg --at 0.32,0.6 # fetches this model on first use
|
| 85 |
+
cutout ./shots --at 0.5,0.45 --out cut # a folder, the model loaded once
|
| 86 |
+
cutout model remove click # the model and its compiled copy
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
Or by hand: `hf download arraypress/cutout-sam2-tiny --local-dir models`, then point
|
| 90 |
+
`$CUTOUT_CLICK_MODEL` at the `.aimodel`. Requires macOS 27 (Core AI) on Apple silicon. Converted
|
| 91 |
+
with coreai-torch 0.4.3, coreai-core 1.0.0b3, torch 2.9.0, hydra-core 1.3.2 and sam2 at 2b90b9f.
|
| 92 |
+
|
| 93 |
+
## Licence
|
| 94 |
+
|
| 95 |
+
Apache-2.0, as the original: see `LICENSE` (the authors' licence) and `NOTICE` (the copyright, and
|
| 96 |
+
what the export changed).
|
cutout-sam2-tiny-float16.aimodel/main.hash
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
�B��o��ɸp��%��
|
| 2 |
+
�i|�<1�k��Y�;�@
|
cutout-sam2-tiny-float16.aimodel/main.mlirb
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:df42c3de6f9ee9c9b870b2a225b4fc0d2b91697c843c318c6bf08c59b13bb940
|
| 3 |
+
size 62768685
|
cutout-sam2-tiny-float16.aimodel/metadata.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"assetVersion" : "2.0",
|
| 3 |
+
"description" : "SAM 2.1 hiera tiny (facebook\/sam2.1-hiera-tiny@de431c4, code facebookresearch\/sam2@2b90b9f), float16. 'encode': image [1,3,1024,1024] float32 RGB 0…1 → image_embedding, feats_s0, feats_s1. 'decode': those + point [1,1,2] (pixels of the 1024² square) + label [1,1] → masks [1,3,256,256] logits, scores [1,3].",
|
| 4 |
+
"author" : "Ravi, Gabeur, Hu, Hu, Ryali, Ma, Khedr, Rädle, Rolland, Gustafson, et al. (Meta) — SAM 2.1 tiny; Core AI export by ObjectCutout",
|
| 5 |
+
"creationDate" : "20261017T062235Z",
|
| 6 |
+
"license" : "Apache-2.0",
|
| 7 |
+
"producer" : "coreai-core 1.0.0b3"
|
| 8 |
+
}
|
export_sam2.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11,<3.13"
|
| 3 |
+
# dependencies = ["torch==2.9.0", "torchvision==0.24.0", "numpy", "pillow", "huggingface_hub", "hydra-core==1.3.2",
|
| 4 |
+
# "sam-2 @ git+https://github.com/facebookresearch/sam2.git@2b90b9f5ceec907a1c18123530e92e794ad901a4",
|
| 5 |
+
# "coreai-torch==0.4.3", "coreai-core==1.0.0b3"]
|
| 6 |
+
# ///
|
| 7 |
+
"""SAM 2.1 tiny (Meta, Apache-2.0) → cutout-sam2-tiny-<dtype>.aimodel, for the click.
|
| 8 |
+
|
| 9 |
+
SAM2_BUILD_CUDA=0 uv run Tools/export_sam2.py [--dtype float16|float32] [--out Tools/exports] [--check image.jpg …]
|
| 10 |
+
|
| 11 |
+
The network is the authors' own: facebookresearch/sam2 at a pinned commit, with the official SAM 2.1 tiny checkpoint
|
| 12 |
+
(facebook/sam2.1-hiera-tiny at a pinned revision). Nothing in it is rewritten; the two entry points are the image
|
| 13 |
+
predictor's own steps (SAM2ImagePredictor.set_image and ._predict), traced as they are.
|
| 14 |
+
|
| 15 |
+
Two entry points, so one encoded picture serves any number of clicks:
|
| 16 |
+
|
| 17 |
+
encode `image` [1,3,1024,1024] float32 RGB in 0…1 (stretched to the square by the host)
|
| 18 |
+
→ `image_embedding` [1,256,64,64], `feats_s0` [1,32,256,256], `feats_s1` [1,64,128,128]
|
| 19 |
+
The ImageNet normalisation and SAM 2's no-memory embedding are inside.
|
| 20 |
+
decode those three, `point` [1,1,2] float32 (pixels of the 1024² square, x then y) and `label` [1,1] float32
|
| 21 |
+
(1 = the object, 0 = not it) → `masks` [1,3,256,256] logits and `scores` [1,3] (predicted IoU).
|
| 22 |
+
The prompt encoder and the mask decoder, multimask output, SAM's padding point added inside.
|
| 23 |
+
|
| 24 |
+
In a float16 export the weights and arithmetic are half; every input and output stays float32.
|
| 25 |
+
|
| 26 |
+
--check runs the official SAM2ImagePredictor and the two traced steps on each image (a click at the centre) in
|
| 27 |
+
float32 on the CPU and prints the difference, before anything is exported."""
|
| 28 |
+
import argparse, sys, time, shutil
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
import numpy as np, torch, torch.nn as nn
|
| 31 |
+
|
| 32 |
+
HERE = Path(__file__).resolve().parent
|
| 33 |
+
REPOSITORY = "facebook/sam2.1-hiera-tiny"
|
| 34 |
+
REVISION = "de431c4043854a71d8101e17995dfe596bf101a5"
|
| 35 |
+
CHECKPOINT = "sam2.1_hiera_tiny.pt"
|
| 36 |
+
CODE = "facebookresearch/sam2@2b90b9f"
|
| 37 |
+
SIZE = 1024
|
| 38 |
+
|
| 39 |
+
ap = argparse.ArgumentParser()
|
| 40 |
+
ap.add_argument("--dtype", default="float16", choices=["float16", "float32"])
|
| 41 |
+
ap.add_argument("--out", default=str(HERE / "exports"))
|
| 42 |
+
ap.add_argument("--weights", default=None, help="a folder to keep the checkpoint in (default: the HF cache)")
|
| 43 |
+
ap.add_argument("--check", nargs="*", default=[], help="images to compare the predictor and the traced steps on")
|
| 44 |
+
ap.add_argument("--no-export", action="store_true")
|
| 45 |
+
args = ap.parse_args()
|
| 46 |
+
|
| 47 |
+
from huggingface_hub import hf_hub_download
|
| 48 |
+
from sam2.build_sam import build_sam2
|
| 49 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 50 |
+
|
| 51 |
+
torch.set_num_threads(4)
|
| 52 |
+
ckpt = hf_hub_download(REPOSITORY, CHECKPOINT, revision=REVISION, local_dir=args.weights)
|
| 53 |
+
sam = build_sam2("configs/sam2.1/sam2.1_hiera_t.yaml", ckpt, device="cpu", mode="eval")
|
| 54 |
+
print(f"SAM 2.1 tiny @ {REVISION[:7]}: {sum(p.numel() for p in sam.parameters())/1e6:.1f} M parameters", flush=True)
|
| 55 |
+
FEAT_SIZES = [(256, 256), (128, 128), (64, 64)] # SAM2ImagePredictor._bb_feat_sizes at 1024²
|
| 56 |
+
MEAN = torch.tensor([0.485, 0.456, 0.406]).reshape(1, 3, 1, 1)
|
| 57 |
+
STD = torch.tensor([0.229, 0.224, 0.225]).reshape(1, 3, 1, 1)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Encode(nn.Module):
|
| 61 |
+
"""SAM2ImagePredictor.set_image after its resize: normalise, backbone, no-memory embedding, reshape."""
|
| 62 |
+
def __init__(self, m, dtype):
|
| 63 |
+
super().__init__(); self.m = m; self.dtype = dtype
|
| 64 |
+
self.register_buffer("mean", MEAN.to(dtype)); self.register_buffer("std", STD.to(dtype))
|
| 65 |
+
def forward(self, image):
|
| 66 |
+
x = (image.to(self.dtype) - self.mean) / self.std
|
| 67 |
+
backbone_out = self.m.forward_image(x)
|
| 68 |
+
_, vision_feats, _, _ = self.m._prepare_backbone_features(backbone_out)
|
| 69 |
+
if self.m.directly_add_no_mem_embed:
|
| 70 |
+
vision_feats[-1] = vision_feats[-1] + self.m.no_mem_embed
|
| 71 |
+
feats = [f.permute(1, 2, 0).reshape(1, -1, *s) for f, s in zip(vision_feats[::-1], FEAT_SIZES[::-1])][::-1]
|
| 72 |
+
return feats[2].to(torch.float32), feats[0].to(torch.float32), feats[1].to(torch.float32)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Decode(nn.Module):
|
| 76 |
+
"""SAM2ImagePredictor._predict for one point, multimask: prompt encoder, mask decoder."""
|
| 77 |
+
def __init__(self, m, dtype):
|
| 78 |
+
super().__init__(); self.m = m; self.dtype = dtype
|
| 79 |
+
def forward(self, image_embedding, feats_s0, feats_s1, point, label):
|
| 80 |
+
d = self.dtype
|
| 81 |
+
# The prompt encoder stays float32 (it is tiny, and its padding point is made float32 inside).
|
| 82 |
+
sparse, dense = self.m.sam_prompt_encoder(points=(point, label.to(torch.int32)), boxes=None, masks=None)
|
| 83 |
+
masks, scores, _, _ = self.m.sam_mask_decoder(
|
| 84 |
+
image_embeddings=image_embedding.to(d), image_pe=self.m.sam_prompt_encoder.get_dense_pe().to(d),
|
| 85 |
+
sparse_prompt_embeddings=sparse.to(d), dense_prompt_embeddings=dense.to(d), multimask_output=True,
|
| 86 |
+
repeat_image=False, high_res_features=[feats_s0.to(d), feats_s1.to(d)])
|
| 87 |
+
return masks.to(torch.float32), scores.to(torch.float32)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def square(path):
|
| 91 |
+
from PIL import Image
|
| 92 |
+
im = Image.open(path).convert("RGB")
|
| 93 |
+
return im, torch.from_numpy(np.asarray(im.resize((SIZE, SIZE), Image.BILINEAR), np.float32) / 255).permute(2, 0, 1)[None]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if args.check:
|
| 97 |
+
predictor = SAM2ImagePredictor(sam)
|
| 98 |
+
enc, dec = Encode(sam, torch.float32).eval(), Decode(sam, torch.float32).eval()
|
| 99 |
+
with torch.no_grad():
|
| 100 |
+
for path in args.check:
|
| 101 |
+
im, x = square(path)
|
| 102 |
+
predictor.set_image(np.asarray(im))
|
| 103 |
+
w, h = im.size
|
| 104 |
+
_, s_ref, low_ref = predictor.predict(point_coords=np.array([[w / 2, h / 2]]), point_labels=np.array([1]),
|
| 105 |
+
multimask_output=True, return_logits=True)
|
| 106 |
+
# The predictor resizes with its own transform; feed the traced steps its tensor so only the steps differ.
|
| 107 |
+
x = predictor._transforms(np.asarray(im))[None]
|
| 108 |
+
x = x * STD + MEAN
|
| 109 |
+
e, s0, s1 = enc(x)
|
| 110 |
+
m, s = dec(e, s0, s1, torch.tensor([[[SIZE / 2, SIZE / 2]]]), torch.ones(1, 1))
|
| 111 |
+
# The predictor clamps its low-resolution logits to ±32; the export does not (the host thresholds).
|
| 112 |
+
dm = np.abs(m[0].clamp(-32, 32).numpy() - low_ref).max()
|
| 113 |
+
print(f"{Path(path).name}: |predictor − traced| masks {dm:.2e} scores {np.abs(s[0].numpy() - s_ref).max():.2e}",
|
| 114 |
+
flush=True)
|
| 115 |
+
|
| 116 |
+
if args.no_export:
|
| 117 |
+
sys.exit(0)
|
| 118 |
+
|
| 119 |
+
import coreai_torch
|
| 120 |
+
from coreai.runtime import AIModelAssetMetadata
|
| 121 |
+
dtype = torch.float16 if args.dtype == "float16" else torch.float32
|
| 122 |
+
sam = sam.to(dtype)
|
| 123 |
+
sam.sam_prompt_encoder.float()
|
| 124 |
+
enc, dec = Encode(sam, dtype).eval(), Decode(sam, dtype).eval()
|
| 125 |
+
t0 = time.time()
|
| 126 |
+
converter = coreai_torch.TorchConverter(mode=coreai_torch.TorchConverter.Mode.RELEASE)
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
x = torch.rand(1, 3, SIZE, SIZE)
|
| 129 |
+
ex = torch.export.export(enc, (x,)).run_decompositions(coreai_torch.get_decomp_table())
|
| 130 |
+
converter.add_exported_program(ex, input_names=["image"],
|
| 131 |
+
output_names=["image_embedding", "feats_s0", "feats_s1"], entrypoint_name="encode")
|
| 132 |
+
e, s0, s1 = enc(x)
|
| 133 |
+
ex = torch.export.export(dec, (e, s0, s1, torch.tensor([[[300.0, 400.0]]]), torch.ones(1, 1))
|
| 134 |
+
).run_decompositions(coreai_torch.get_decomp_table())
|
| 135 |
+
converter.add_exported_program(ex, input_names=["image_embedding", "feats_s0", "feats_s1", "point", "label"],
|
| 136 |
+
output_names=["masks", "scores"], entrypoint_name="decode")
|
| 137 |
+
print(f"traced in {time.time()-t0:.0f} s", flush=True)
|
| 138 |
+
program = converter.to_coreai()
|
| 139 |
+
print(f"converted in {time.time()-t0:.0f} s", flush=True)
|
| 140 |
+
meta = AIModelAssetMetadata()
|
| 141 |
+
meta.author = "Ravi, Gabeur, Hu, Hu, Ryali, Ma, Khedr, Rädle, Rolland, Gustafson, et al. (Meta) — SAM 2.1 tiny; Core AI export by ObjectCutout"
|
| 142 |
+
meta.license = "Apache-2.0"
|
| 143 |
+
meta.model_description = (f"SAM 2.1 hiera tiny ({REPOSITORY}@{REVISION[:7]}, code {CODE}), {args.dtype}. "
|
| 144 |
+
f"'encode': image [1,3,{SIZE},{SIZE}] float32 RGB 0…1 → image_embedding, feats_s0, feats_s1. "
|
| 145 |
+
f"'decode': those + point [1,1,2] (pixels of the {SIZE}² square) + label [1,1] "
|
| 146 |
+
f"→ masks [1,3,256,256] logits, scores [1,3].")
|
| 147 |
+
meta.creation_date = int(time.time())
|
| 148 |
+
out = Path(args.out); out.mkdir(parents=True, exist_ok=True)
|
| 149 |
+
asset = out / f"cutout-sam2-tiny-{args.dtype}.aimodel"
|
| 150 |
+
if asset.exists(): shutil.rmtree(asset)
|
| 151 |
+
program.save_asset(asset, meta)
|
| 152 |
+
print(f"saved {asset} ({sum(f.stat().st_size for f in asset.rglob('*'))/1e6:.0f} MB) in {time.time()-t0:.0f} s", flush=True)
|