Spaces:
Runtime error
Runtime error
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .DS_Store +0 -0
- .gitattributes +8 -0
- Pytorch-Correlation-extension/.gitignore +1 -0
- Pytorch-Correlation-extension/Correlation_Module/correlation.cpp +178 -0
- Pytorch-Correlation-extension/Correlation_Module/correlation_cuda_kernel.cu +327 -0
- Pytorch-Correlation-extension/Correlation_Module/correlation_sampler.cpp +138 -0
- Pytorch-Correlation-extension/Correlation_Module/spatial_correlation_sampler/__init__.py +1 -0
- Pytorch-Correlation-extension/Correlation_Module/spatial_correlation_sampler/spatial_correlation_sampler.py +107 -0
- Pytorch-Correlation-extension/LICENSE +21 -0
- Pytorch-Correlation-extension/README.md +155 -0
- Pytorch-Correlation-extension/benchmark.py +90 -0
- Pytorch-Correlation-extension/check.py +119 -0
- Pytorch-Correlation-extension/grad_check.py +47 -0
- Pytorch-Correlation-extension/requirements.txt +2 -0
- Pytorch-Correlation-extension/setup.py +69 -0
- Pytorch-Correlation-extension/setup_cpu.py +4 -0
- sam/.DS_Store +0 -0
- sam/.flake8 +7 -0
- sam/.gitignore +37 -0
- sam/CODE_OF_CONDUCT.md +80 -0
- sam/CONTRIBUTING.md +31 -0
- sam/LICENSE +201 -0
- sam/README.md +163 -0
- sam/__init__.py +0 -0
- sam/__pycache__/__init__.cpython-310.pyc +0 -0
- sam/assets/masks1.png +3 -0
- sam/assets/masks2.jpg +0 -0
- sam/assets/model_diagram.png +0 -0
- sam/assets/notebook1.png +0 -0
- sam/assets/notebook2.png +3 -0
- sam/linter.sh +32 -0
- sam/notebooks/automatic_mask_generator_example.ipynb +0 -0
- sam/notebooks/images/dog.jpg +0 -0
- sam/notebooks/images/groceries.jpg +0 -0
- sam/notebooks/images/truck.jpg +0 -0
- sam/notebooks/onnx_model_example.ipynb +774 -0
- sam/notebooks/predictor_example.ipynb +0 -0
- sam/scripts/amg.py +238 -0
- sam/scripts/export_onnx_model.py +199 -0
- sam/segment_anything.egg-info/PKG-INFO +6 -0
- sam/segment_anything.egg-info/SOURCES.txt +24 -0
- sam/segment_anything.egg-info/dependency_links.txt +1 -0
- sam/segment_anything.egg-info/requires.txt +13 -0
- sam/segment_anything.egg-info/top_level.txt +1 -0
- sam/segment_anything/.DS_Store +0 -0
- sam/segment_anything/__init__.py +15 -0
- sam/segment_anything/__pycache__/__init__.cpython-310.pyc +0 -0
- sam/segment_anything/__pycache__/automatic_mask_generator.cpython-310.pyc +0 -0
- sam/segment_anything/__pycache__/build_sam.cpython-310.pyc +0 -0
- sam/segment_anything/__pycache__/predictor.cpython-310.pyc +0 -0
.DS_Store
CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
|
|
.gitattributes
CHANGED
@@ -40,3 +40,11 @@ assets/cars.mp4 filter=lfs diff=lfs merge=lfs -text
|
|
40 |
assets/cell.mp4 filter=lfs diff=lfs merge=lfs -text
|
41 |
assets/demo_3x2.gif filter=lfs diff=lfs merge=lfs -text
|
42 |
assets/top.gif filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
assets/cell.mp4 filter=lfs diff=lfs merge=lfs -text
|
41 |
assets/demo_3x2.gif filter=lfs diff=lfs merge=lfs -text
|
42 |
assets/top.gif filter=lfs diff=lfs merge=lfs -text
|
43 |
+
sam/assets/masks1.png filter=lfs diff=lfs merge=lfs -text
|
44 |
+
sam/assets/notebook2.png filter=lfs diff=lfs merge=lfs -text
|
45 |
+
src/groundingdino/.asset/GD_GLIGEN.png filter=lfs diff=lfs merge=lfs -text
|
46 |
+
src/groundingdino/.asset/GD_SD.png filter=lfs diff=lfs merge=lfs -text
|
47 |
+
src/groundingdino/.asset/hero_figure.png filter=lfs diff=lfs merge=lfs -text
|
48 |
+
tutorial/img/click_segment.jpg filter=lfs diff=lfs merge=lfs -text
|
49 |
+
tutorial/img/input_video.jpg filter=lfs diff=lfs merge=lfs -text
|
50 |
+
tutorial/img/start_tracking.jpg filter=lfs diff=lfs merge=lfs -text
|
Pytorch-Correlation-extension/.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
*.egg*
|
Pytorch-Correlation-extension/Correlation_Module/correlation.cpp
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include <torch/extension.h>
|
2 |
+
using namespace torch;
|
3 |
+
|
4 |
+
#include <vector>
|
5 |
+
|
6 |
+
#define WITHIN_BOUNDS(x, y, H, W) (x >= 0 && x < H && y >= 0 && y < W)
|
7 |
+
|
8 |
+
template <typename scalar_t>
|
9 |
+
static void correlate_patch(
|
10 |
+
TensorAccessor<scalar_t,3> input1,
|
11 |
+
TensorAccessor<scalar_t,3> input2,
|
12 |
+
scalar_t *dst,
|
13 |
+
int kH, int kW,
|
14 |
+
int dilationH, int dilationW,
|
15 |
+
int u, int v,
|
16 |
+
int shiftU, int shiftV){
|
17 |
+
const int C = input1.size(0);
|
18 |
+
const int iH = input1.size(1);
|
19 |
+
const int iW = input1.size(2);
|
20 |
+
for (int c=0; c<C; ++c){
|
21 |
+
for (int i=0; i<kH; ++i){
|
22 |
+
int i1 = u + i * dilationH;
|
23 |
+
int i2 = i1 + shiftU;
|
24 |
+
if WITHIN_BOUNDS(i1, i2, iH, iH){
|
25 |
+
for (int j=0; j<kW; ++j){
|
26 |
+
int j1 = v + j * dilationW;
|
27 |
+
int j2 = j1 + shiftV;
|
28 |
+
if WITHIN_BOUNDS(j1, j2, iW, iW){
|
29 |
+
scalar_t v1 = input1[c][i1][j1];
|
30 |
+
scalar_t v2 = input2[c][i2][j2];
|
31 |
+
*dst += v1 * v2;
|
32 |
+
}
|
33 |
+
}
|
34 |
+
}
|
35 |
+
}
|
36 |
+
}
|
37 |
+
}
|
38 |
+
|
39 |
+
template <typename scalar_t>
|
40 |
+
static void correlate_patch_grad(
|
41 |
+
TensorAccessor<scalar_t,3> input1,
|
42 |
+
TensorAccessor<scalar_t,3> gradInput1,
|
43 |
+
TensorAccessor<scalar_t,3> input2,
|
44 |
+
TensorAccessor<scalar_t,3> gradInput2,
|
45 |
+
scalar_t gradOutput,
|
46 |
+
int kH, int kW,
|
47 |
+
int dilationH, int dilationW,
|
48 |
+
int u, int v,
|
49 |
+
int shiftU, int shiftV){
|
50 |
+
|
51 |
+
const int C = input1.size(0);
|
52 |
+
const int iH = input1.size(1);
|
53 |
+
const int iW = input1.size(2);
|
54 |
+
|
55 |
+
for (int c=0; c<C; ++c){
|
56 |
+
for (int i=0; i<kH; ++i){
|
57 |
+
int i1 = u + i * dilationH;
|
58 |
+
int i2 = i1 + shiftU;
|
59 |
+
if WITHIN_BOUNDS(i1, i2, iH, iH){
|
60 |
+
for (int j=0; j<kW; ++j){
|
61 |
+
int j1 = v + j * dilationW;
|
62 |
+
int j2 = j1 + shiftV;
|
63 |
+
if WITHIN_BOUNDS(j1, j2, iW, iW){
|
64 |
+
scalar_t v1 = input1[c][i1][j1];
|
65 |
+
scalar_t v2 = input2[c][i2][j2];
|
66 |
+
gradInput2[c][i2][j2] += gradOutput * v1;
|
67 |
+
gradInput1[c][i1][j1] += gradOutput * v2;
|
68 |
+
}
|
69 |
+
}
|
70 |
+
}
|
71 |
+
}
|
72 |
+
}
|
73 |
+
}
|
74 |
+
|
75 |
+
torch::Tensor correlation_cpp_forward(
|
76 |
+
torch::Tensor input1,
|
77 |
+
torch::Tensor input2,
|
78 |
+
int kH, int kW,
|
79 |
+
int patchH, int patchW,
|
80 |
+
int padH, int padW,
|
81 |
+
int dilationH, int dilationW,
|
82 |
+
int dilation_patchH, int dilation_patchW,
|
83 |
+
int dH, int dW) {
|
84 |
+
|
85 |
+
const auto batch_size = input1.size(0);
|
86 |
+
const auto iH = input1.size(2);
|
87 |
+
const auto iW = input1.size(3);
|
88 |
+
const int patchRadH = (patchH - 1) / 2;
|
89 |
+
const int patchRadW = (patchW - 1) / 2;
|
90 |
+
const int dilatedKH = (kH - 1) * dilationH + 1;
|
91 |
+
const int dilatedKW = (kW - 1) * dilationW + 1;
|
92 |
+
|
93 |
+
const auto oH = (iH + 2 * padH - dilatedKH) / dH + 1;
|
94 |
+
const auto oW = (iW + 2 * padW - dilatedKW) / dW + 1;
|
95 |
+
auto output = at::zeros({batch_size, patchH, patchW, oH, oW}, input1.options());
|
96 |
+
|
97 |
+
int n, ph, pw, h, w;
|
98 |
+
#pragma omp parallel for private(n, ph, pw, h, w) collapse(2)
|
99 |
+
for (n = 0; n < batch_size; ++n) {
|
100 |
+
for(ph = 0; ph < patchH; ++ph){
|
101 |
+
for(pw = 0; pw < patchW; ++pw){
|
102 |
+
AT_DISPATCH_FLOATING_TYPES(input1.scalar_type(), "correlation_forward_cpp", ([&] {
|
103 |
+
auto input1_acc = input1.accessor<scalar_t, 4>();
|
104 |
+
auto input2_acc = input2.accessor<scalar_t, 4>();
|
105 |
+
auto output_acc = output.accessor<scalar_t, 5>();
|
106 |
+
for (h = 0; h < oH; ++h) {
|
107 |
+
for (w = 0; w < oW; ++w) {
|
108 |
+
correlate_patch(input1_acc[n],
|
109 |
+
input2_acc[n],
|
110 |
+
&output_acc[n][ph][pw][h][w],
|
111 |
+
kH, kW,
|
112 |
+
dilationH, dilationW,
|
113 |
+
-padH + h * dH,
|
114 |
+
-padW + w * dW,
|
115 |
+
(ph - patchRadH) * dilation_patchH,
|
116 |
+
(pw - patchRadW) * dilation_patchW);
|
117 |
+
}
|
118 |
+
}
|
119 |
+
}));
|
120 |
+
}
|
121 |
+
}
|
122 |
+
}
|
123 |
+
return output;
|
124 |
+
}
|
125 |
+
|
126 |
+
std::vector<torch::Tensor> correlation_cpp_backward(
|
127 |
+
torch::Tensor input1,
|
128 |
+
torch::Tensor input2,
|
129 |
+
torch::Tensor gradOutput,
|
130 |
+
int kH, int kW,
|
131 |
+
int patchH, int patchW,
|
132 |
+
int padH, int padW,
|
133 |
+
int dilationH, int dilationW,
|
134 |
+
int dilation_patchH, int dilation_patchW,
|
135 |
+
int dH, int dW) {
|
136 |
+
|
137 |
+
const int batch_size = input1.size(0);
|
138 |
+
const int patchRadH = (patchH - 1) / 2;
|
139 |
+
const int patchRadW = (patchW - 1) / 2;
|
140 |
+
const int oH = gradOutput.size(3);
|
141 |
+
const int oW = gradOutput.size(4);
|
142 |
+
|
143 |
+
auto gradInput1 = torch::zeros_like(input1);
|
144 |
+
|
145 |
+
auto gradInput2 = torch::zeros_like(input2);
|
146 |
+
|
147 |
+
int n, ph, pw, h, w;
|
148 |
+
#pragma omp parallel for private(n, ph, pw, h, w)
|
149 |
+
for (n = 0; n < batch_size; ++n) {
|
150 |
+
AT_DISPATCH_FLOATING_TYPES(input1.scalar_type(), "correlation_backward_cpp", ([&] {
|
151 |
+
auto input1_acc = input1.accessor<scalar_t, 4>();
|
152 |
+
auto gradInput1_acc = gradInput1.accessor<scalar_t, 4>();
|
153 |
+
auto input2_acc = input2.accessor<scalar_t, 4>();
|
154 |
+
auto gradInput2_acc = gradInput2.accessor<scalar_t, 4>();
|
155 |
+
auto gradOutput_acc = gradOutput.accessor<scalar_t, 5>();
|
156 |
+
|
157 |
+
for(ph = 0; ph < patchH; ++ph){
|
158 |
+
for(pw = 0; pw < patchW; ++pw){
|
159 |
+
for (h = 0; h < oH; ++h) {
|
160 |
+
for (w = 0; w < oW; ++w) {
|
161 |
+
correlate_patch_grad(input1_acc[n], gradInput1_acc[n],
|
162 |
+
input2_acc[n], gradInput2_acc[n],
|
163 |
+
gradOutput_acc[n][ph][pw][h][w],
|
164 |
+
kH, kW,
|
165 |
+
dilationH, dilationW,
|
166 |
+
-padH + h * dH,
|
167 |
+
-padW + w * dW,
|
168 |
+
(ph - patchRadH) * dilation_patchH,
|
169 |
+
(pw - patchRadW) * dilation_patchW);
|
170 |
+
}
|
171 |
+
}
|
172 |
+
}
|
173 |
+
}
|
174 |
+
}));
|
175 |
+
}
|
176 |
+
|
177 |
+
return {gradInput1, gradInput2};
|
178 |
+
}
|
Pytorch-Correlation-extension/Correlation_Module/correlation_cuda_kernel.cu
ADDED
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include <torch/types.h>
|
2 |
+
using namespace torch;
|
3 |
+
|
4 |
+
#include <cuda.h>
|
5 |
+
#include <cuda_runtime.h>
|
6 |
+
|
7 |
+
#include <vector>
|
8 |
+
#include <iostream>
|
9 |
+
|
10 |
+
// Cuda tensor accessor definitions
|
11 |
+
// restrict pointer traits piroritize speed over memory consumption
|
12 |
+
#define TensorAcc4R PackedTensorAccessor32<scalar_t,4,RestrictPtrTraits>
|
13 |
+
#define TensorAcc5R PackedTensorAccessor32<scalar_t,5,RestrictPtrTraits>
|
14 |
+
#define WITHIN_BOUNDS(x, y, H, W) (x >= 0 && x < H && y >= 0 && y < W)
|
15 |
+
|
16 |
+
#define THREADS_FORWARD 32
|
17 |
+
#define THREADS_BACKWARD 5
|
18 |
+
|
19 |
+
|
20 |
+
namespace corr {
|
21 |
+
template <typename scalar_t>
|
22 |
+
__global__ void correlation_cuda_forward_kernel(
|
23 |
+
const TensorAcc4R rInput1,
|
24 |
+
const TensorAcc4R rInput2,
|
25 |
+
TensorAcc5R output,
|
26 |
+
int kH, int kW,
|
27 |
+
int patchH, int patchW,
|
28 |
+
int padH, int padW,
|
29 |
+
int dilationH, int dilationW,
|
30 |
+
int dilation_patchH, int dilation_patchW,
|
31 |
+
int dH, int dW) {
|
32 |
+
|
33 |
+
const int iH = rInput1.size(1);
|
34 |
+
const int iW = rInput1.size(2);
|
35 |
+
const int C = rInput1.size(3);
|
36 |
+
|
37 |
+
const int n = blockIdx.x;
|
38 |
+
const int h = blockIdx.y;
|
39 |
+
const int w = blockIdx.z;
|
40 |
+
const int thread = threadIdx.x;
|
41 |
+
|
42 |
+
const int start_i = -padH + h * dH;
|
43 |
+
const int start_j = -padW + w * dW;
|
44 |
+
|
45 |
+
const int patchRadH = dilation_patchH * (patchH - 1) / 2;
|
46 |
+
const int patchRadW = dilation_patchW * (patchW - 1) / 2;
|
47 |
+
|
48 |
+
__shared__ scalar_t prod_sum[THREADS_FORWARD];
|
49 |
+
|
50 |
+
for(int ph = 0; ph < patchH; ++ph){
|
51 |
+
int ph_dilated = ph * dilation_patchH - patchRadH;
|
52 |
+
for(int pw = 0; pw < patchW; ++pw){
|
53 |
+
int pw_dilated = pw * dilation_patchW - patchRadW;
|
54 |
+
prod_sum[thread] = 0;
|
55 |
+
for (int i=0; i<kH; ++i){
|
56 |
+
int i1 = start_i + i * dilationH;
|
57 |
+
int i2 = i1 + ph_dilated;
|
58 |
+
if WITHIN_BOUNDS(i1, i2, iH, iH){
|
59 |
+
for (int j=0; j<kW; ++j){
|
60 |
+
int j1 = start_j + j * dilationW;
|
61 |
+
int j2 = j1 + pw_dilated;
|
62 |
+
if WITHIN_BOUNDS(j1, j2, iW, iW){
|
63 |
+
for (int c=thread; c<C; c += THREADS_FORWARD){
|
64 |
+
scalar_t v1 = rInput1[n][i1][j1][c];
|
65 |
+
scalar_t v2 = rInput2[n][i2][j2][c];
|
66 |
+
prod_sum[thread] += v1 * v2;
|
67 |
+
}
|
68 |
+
}
|
69 |
+
}
|
70 |
+
}
|
71 |
+
}
|
72 |
+
// accumulate
|
73 |
+
__syncthreads();
|
74 |
+
if (thread == 0) {
|
75 |
+
scalar_t reduce_sum = 0;
|
76 |
+
for (int index = 0; index < THREADS_FORWARD; ++index) {
|
77 |
+
reduce_sum += prod_sum[index];
|
78 |
+
}
|
79 |
+
output[n][ph][pw][h][w] = reduce_sum;
|
80 |
+
}
|
81 |
+
}
|
82 |
+
}
|
83 |
+
}
|
84 |
+
|
85 |
+
|
86 |
+
template <typename scalar_t>
|
87 |
+
__global__ void correlation_cuda_backward_kernel_input1(
|
88 |
+
const TensorAcc5R gradOutput,
|
89 |
+
const TensorAcc4R input2,
|
90 |
+
TensorAcc4R gradInput1,
|
91 |
+
const int kH, const int kW,
|
92 |
+
const int patchH, const int patchW,
|
93 |
+
const int padH, const int padW,
|
94 |
+
const int dilationH, const int dilationW,
|
95 |
+
const int dilation_patchH, const int dilation_patchW,
|
96 |
+
const int dH, const int dW,
|
97 |
+
const int batch) {
|
98 |
+
const int iH = input2.size(2);
|
99 |
+
const int iW = input2.size(3);
|
100 |
+
|
101 |
+
const int H = gradOutput.size(3);
|
102 |
+
const int W = gradOutput.size(4);
|
103 |
+
|
104 |
+
const int patchRadH = (patchH - 1) / 2;
|
105 |
+
const int patchRadW = (patchW - 1) / 2;
|
106 |
+
|
107 |
+
const int n = batch;
|
108 |
+
const int c = blockIdx.x;
|
109 |
+
const int h = blockIdx.y;
|
110 |
+
const int w = blockIdx.z;
|
111 |
+
const int ph_off = threadIdx.x;
|
112 |
+
const int pw_off = threadIdx.y;
|
113 |
+
|
114 |
+
const int h_2 = h + padH;
|
115 |
+
const int w_2 = w + padW;
|
116 |
+
const int min_h = h_2 - kH * dilationH;
|
117 |
+
const int min_w = w_2 - kW * dilationW;
|
118 |
+
|
119 |
+
__shared__ scalar_t prod_sum[THREADS_BACKWARD][THREADS_BACKWARD];
|
120 |
+
prod_sum[ph_off][pw_off] = 0;
|
121 |
+
|
122 |
+
for (int ph = ph_off; ph < patchH; ph += THREADS_BACKWARD) {
|
123 |
+
int i1 = h + dilation_patchH * (ph - patchRadH);
|
124 |
+
for (int pw = pw_off; pw < patchW; pw += THREADS_BACKWARD) {
|
125 |
+
int j1 = w + dilation_patchW * (pw - patchRadW);
|
126 |
+
if (WITHIN_BOUNDS(i1, j1, iH, iW)){
|
127 |
+
scalar_t val = input2[n][c][i1][j1];
|
128 |
+
for(int h_3 = h_2; h_3 > min_h; h_3 -= dilationH) {
|
129 |
+
int i2 = (h_3)/dH;
|
130 |
+
if (i2 * dH != h_3)
|
131 |
+
continue;
|
132 |
+
for(int w_3 = w_2; w_3 > min_w; w_3 -= dilationW) {
|
133 |
+
int j2 = (w_3) / dW;
|
134 |
+
if(j2 * dW != w_3)
|
135 |
+
continue;
|
136 |
+
if WITHIN_BOUNDS(i2, j2, H, W) {
|
137 |
+
prod_sum[ph_off][pw_off] += gradOutput[n][ph][pw][i2][j2] * val;
|
138 |
+
}
|
139 |
+
}
|
140 |
+
}
|
141 |
+
}
|
142 |
+
}
|
143 |
+
}
|
144 |
+
|
145 |
+
__syncthreads();
|
146 |
+
|
147 |
+
if (ph_off == 0 && pw_off == 0){
|
148 |
+
scalar_t reduce_sum =0;
|
149 |
+
for (int ph = 0; ph < THREADS_BACKWARD; ++ph){
|
150 |
+
for (int pw = 0; pw < THREADS_BACKWARD; ++pw){
|
151 |
+
reduce_sum += prod_sum[ph][pw];
|
152 |
+
}
|
153 |
+
}
|
154 |
+
gradInput1[n][c][h][w] = reduce_sum;
|
155 |
+
}
|
156 |
+
}
|
157 |
+
|
158 |
+
|
159 |
+
template <typename scalar_t>
|
160 |
+
__global__ void correlation_cuda_backward_kernel_input2(
|
161 |
+
const TensorAcc5R gradOutput,
|
162 |
+
const TensorAcc4R input1,
|
163 |
+
TensorAcc4R gradInput2,
|
164 |
+
int kH, int kW,
|
165 |
+
int patchH, int patchW,
|
166 |
+
int padH, int padW,
|
167 |
+
int dilationH, int dilationW,
|
168 |
+
int dilation_patchH, int dilation_patchW,
|
169 |
+
int dH, int dW,
|
170 |
+
int batch) {
|
171 |
+
const int iH = input1.size(2);
|
172 |
+
const int iW = input1.size(3);
|
173 |
+
|
174 |
+
const int patchRadH = (patchH - 1) / 2;
|
175 |
+
const int patchRadW = (patchW - 1) / 2;
|
176 |
+
|
177 |
+
const int H = gradOutput.size(3);
|
178 |
+
const int W = gradOutput.size(4);
|
179 |
+
|
180 |
+
const int dilatedKH = kH * dilationH;
|
181 |
+
const int dilatedKW = kW * dilationW;
|
182 |
+
|
183 |
+
const int n = batch;
|
184 |
+
const int c = blockIdx.x;
|
185 |
+
const int h = blockIdx.y;
|
186 |
+
const int w = blockIdx.z;
|
187 |
+
const int ph_off = threadIdx.x;
|
188 |
+
const int pw_off = threadIdx.y;
|
189 |
+
|
190 |
+
__shared__ scalar_t prod_sum[THREADS_BACKWARD][THREADS_BACKWARD];
|
191 |
+
prod_sum[ph_off][pw_off] = 0;
|
192 |
+
|
193 |
+
for (int ph = ph_off; ph < patchH; ph += THREADS_BACKWARD) {
|
194 |
+
int i1 = h - dilation_patchH * (ph - patchRadH);
|
195 |
+
for (int pw = pw_off; pw < patchW; pw += THREADS_BACKWARD) {
|
196 |
+
int j1 = w - dilation_patchW * (pw - patchRadW);
|
197 |
+
if WITHIN_BOUNDS(i1, j1, iH, iW) {
|
198 |
+
scalar_t val = input1[n][c][i1][j1];
|
199 |
+
|
200 |
+
const int h_2 = i1 + padH;
|
201 |
+
const int w_2 = j1 + padW;
|
202 |
+
const int min_h = h_2 - dilatedKH;
|
203 |
+
const int min_w = w_2 - dilatedKW;
|
204 |
+
|
205 |
+
for(int h_3 = h_2; h_3 > min_h; h_3 -= dilationH) {
|
206 |
+
int i2 = (h_3)/dH;
|
207 |
+
if (i2 * dH != h_3)
|
208 |
+
continue;
|
209 |
+
for(int w_3 = w_2; w_3 > min_w; w_3 -= dilationW) {
|
210 |
+
int j2 = (w_3) / dW;
|
211 |
+
if(j2 * dW != w_3)
|
212 |
+
continue;
|
213 |
+
if WITHIN_BOUNDS(i2, j2, H, W) {
|
214 |
+
prod_sum[ph_off][pw_off] += gradOutput[n][ph][pw][i2][j2] * val;
|
215 |
+
}
|
216 |
+
}
|
217 |
+
}
|
218 |
+
}
|
219 |
+
}
|
220 |
+
}
|
221 |
+
|
222 |
+
__syncthreads();
|
223 |
+
|
224 |
+
if (ph_off == 0 && pw_off == 0){
|
225 |
+
scalar_t reduce_sum =0;
|
226 |
+
for (int ph = 0; ph < THREADS_BACKWARD; ++ph){
|
227 |
+
for (int pw = 0; pw < THREADS_BACKWARD; ++pw){
|
228 |
+
reduce_sum += prod_sum[ph][pw];
|
229 |
+
}
|
230 |
+
}
|
231 |
+
gradInput2[n][c][h][w] = reduce_sum;
|
232 |
+
}
|
233 |
+
}
|
234 |
+
} // namsepace corr
|
235 |
+
|
236 |
+
torch::Tensor correlation_cuda_forward(
|
237 |
+
torch::Tensor input1,
|
238 |
+
torch::Tensor input2,
|
239 |
+
int kH, int kW,
|
240 |
+
int patchH, int patchW,
|
241 |
+
int padH, int padW,
|
242 |
+
int dilationH, int dilationW,
|
243 |
+
int dilation_patchH, int dilation_patchW,
|
244 |
+
int dH, int dW) {
|
245 |
+
|
246 |
+
const int batch_size = input1.size(0);
|
247 |
+
const int iH = input1.size(2);
|
248 |
+
const int iW = input1.size(3);
|
249 |
+
const int dilatedKH = (kH - 1) * dilationH + 1;
|
250 |
+
const int dilatedKW = (kW - 1) * dilationW + 1;
|
251 |
+
|
252 |
+
const auto oH = (iH + 2 * padH - dilatedKH) / dH + 1;
|
253 |
+
const auto oW = (iW + 2 * padW - dilatedKW) / dW + 1;
|
254 |
+
auto output = torch::zeros({batch_size, patchH, patchW, oH, oW}, input1.options());
|
255 |
+
|
256 |
+
auto trInput1 = input1.permute({0, 2, 3, 1}).contiguous();
|
257 |
+
auto trInput2 = input2.permute({0, 2, 3, 1}).contiguous();
|
258 |
+
|
259 |
+
const int threads = THREADS_FORWARD;
|
260 |
+
const dim3 blocks(batch_size, oH, oW);
|
261 |
+
|
262 |
+
AT_DISPATCH_FLOATING_TYPES_AND_HALF(input1.scalar_type(), "correlation_forward_cuda", ([&] {
|
263 |
+
TensorAcc4R trInput1_acc = trInput1.packed_accessor32<scalar_t,4,RestrictPtrTraits>();
|
264 |
+
TensorAcc4R trInput2_acc = trInput2.packed_accessor32<scalar_t,4,RestrictPtrTraits>();
|
265 |
+
TensorAcc5R output_acc = output.packed_accessor32<scalar_t,5,RestrictPtrTraits>();
|
266 |
+
corr::correlation_cuda_forward_kernel<scalar_t><<<blocks, threads>>>(
|
267 |
+
trInput1_acc, trInput2_acc, output_acc,
|
268 |
+
kH, kW, patchH, patchW, padH, padW, dilationH, dilationW,
|
269 |
+
dilation_patchH, dilation_patchW, dH, dW);
|
270 |
+
}));
|
271 |
+
|
272 |
+
return output;
|
273 |
+
}
|
274 |
+
|
275 |
+
std::vector<torch::Tensor> correlation_cuda_backward(
|
276 |
+
torch::Tensor input1,
|
277 |
+
torch::Tensor input2,
|
278 |
+
torch::Tensor gradOutput,
|
279 |
+
int kH, int kW,
|
280 |
+
int patchH, int patchW,
|
281 |
+
int padH, int padW,
|
282 |
+
int dilationH, int dilationW,
|
283 |
+
int dilation_patchH, int dilation_patchW,
|
284 |
+
int dH, int dW) {
|
285 |
+
|
286 |
+
auto gradInput1 = torch::zeros_like(input1);
|
287 |
+
auto gradInput2 = torch::zeros_like(input2);
|
288 |
+
|
289 |
+
const int batch_size = input1.size(0);
|
290 |
+
const int iH = input1.size(2);
|
291 |
+
const int iW = input1.size(3);
|
292 |
+
const int C = input1.size(1);
|
293 |
+
|
294 |
+
const dim3 blocks(C, iH, iW);
|
295 |
+
const dim3 threads(THREADS_BACKWARD, THREADS_BACKWARD);
|
296 |
+
|
297 |
+
AT_DISPATCH_FLOATING_TYPES_AND_HALF(input1.scalar_type(), "correlation_backward_cuda", ([&] {
|
298 |
+
TensorAcc4R input1_acc = input1.packed_accessor32<scalar_t,4,RestrictPtrTraits>();
|
299 |
+
TensorAcc4R input2_acc = input2.packed_accessor32<scalar_t,4,RestrictPtrTraits>();
|
300 |
+
TensorAcc4R gradInput1_acc = gradInput1.packed_accessor32<scalar_t,4,RestrictPtrTraits>();
|
301 |
+
TensorAcc4R gradInput2_acc = gradInput2.packed_accessor32<scalar_t,4,RestrictPtrTraits>();
|
302 |
+
TensorAcc5R gradOutput_acc = gradOutput.packed_accessor32<scalar_t,5,RestrictPtrTraits>();
|
303 |
+
|
304 |
+
|
305 |
+
for (int n = 0; n < batch_size; ++n){
|
306 |
+
corr::correlation_cuda_backward_kernel_input1<scalar_t><<<blocks, threads>>>(
|
307 |
+
gradOutput_acc, input2_acc, gradInput1_acc,
|
308 |
+
kH, kW, patchH, patchW, padH, padW,
|
309 |
+
dilationH, dilationW,
|
310 |
+
dilation_patchH, dilation_patchW,
|
311 |
+
dH, dW,
|
312 |
+
n);
|
313 |
+
}
|
314 |
+
|
315 |
+
for (int n = 0; n < batch_size; ++n){
|
316 |
+
corr::correlation_cuda_backward_kernel_input2<scalar_t><<<blocks, threads>>>(
|
317 |
+
gradOutput_acc, input1_acc, gradInput2_acc,
|
318 |
+
kH, kW, patchH, patchW, padH, padW,
|
319 |
+
dilationH, dilationW,
|
320 |
+
dilation_patchH, dilation_patchW,
|
321 |
+
dH, dW,
|
322 |
+
n);
|
323 |
+
}
|
324 |
+
}));
|
325 |
+
|
326 |
+
return {gradInput1, gradInput2};
|
327 |
+
}
|
Pytorch-Correlation-extension/Correlation_Module/correlation_sampler.cpp
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include <torch/extension.h>
|
2 |
+
#include <c10/cuda/CUDAGuard.h>
|
3 |
+
#include <vector>
|
4 |
+
#include <iostream>
|
5 |
+
|
6 |
+
// declarations
|
7 |
+
|
8 |
+
torch::Tensor correlation_cpp_forward(
|
9 |
+
torch::Tensor input1,
|
10 |
+
torch::Tensor input2,
|
11 |
+
int kH, int kW,
|
12 |
+
int patchH, int patchW,
|
13 |
+
int padH, int padW,
|
14 |
+
int dilationH, int dilationW,
|
15 |
+
int dilation_patchH, int dilation_patchW,
|
16 |
+
int dH, int dW);
|
17 |
+
|
18 |
+
std::vector<torch::Tensor> correlation_cpp_backward(
|
19 |
+
torch::Tensor grad_output,
|
20 |
+
torch::Tensor input1,
|
21 |
+
torch::Tensor input2,
|
22 |
+
int kH, int kW,
|
23 |
+
int patchH, int patchW,
|
24 |
+
int padH, int padW,
|
25 |
+
int dilationH, int dilationW,
|
26 |
+
int dilation_patchH, int dilation_patchW,
|
27 |
+
int dH, int dW);
|
28 |
+
|
29 |
+
#ifdef USE_CUDA
|
30 |
+
|
31 |
+
#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x, " must be a CUDA tensor")
|
32 |
+
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x, " must be contiguous")
|
33 |
+
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)
|
34 |
+
#define CHECK_SAME_DEVICE(x, y) TORCH_CHECK(x.device() == y.device(), #x " is not on same device as " #y)
|
35 |
+
|
36 |
+
torch::Tensor correlation_cuda_forward(
|
37 |
+
torch::Tensor input1,
|
38 |
+
torch::Tensor input2,
|
39 |
+
int kH, int kW,
|
40 |
+
int patchH, int patchW,
|
41 |
+
int padH, int padW,
|
42 |
+
int dilationH, int dilationW,
|
43 |
+
int dilation_patchH, int dilation_patchW,
|
44 |
+
int dH, int dW);
|
45 |
+
|
46 |
+
std::vector<torch::Tensor> correlation_cuda_backward(
|
47 |
+
torch::Tensor grad_output,
|
48 |
+
torch::Tensor input1,
|
49 |
+
torch::Tensor input2,
|
50 |
+
int kH, int kW,
|
51 |
+
int patchH, int patchW,
|
52 |
+
int padH, int padW,
|
53 |
+
int dilationH, int dilationW,
|
54 |
+
int dilation_patchH, int dilation_patchW,
|
55 |
+
int dH, int dW);
|
56 |
+
|
57 |
+
// C++ interface
|
58 |
+
|
59 |
+
torch::Tensor correlation_sample_forward(
|
60 |
+
torch::Tensor input1,
|
61 |
+
torch::Tensor input2,
|
62 |
+
int kH, int kW,
|
63 |
+
int patchH, int patchW,
|
64 |
+
int padH, int padW,
|
65 |
+
int dilationH, int dilationW,
|
66 |
+
int dilation_patchH, int dilation_patchW,
|
67 |
+
int dH, int dW) {
|
68 |
+
if (input1.device().is_cuda()){
|
69 |
+
CHECK_INPUT(input1);
|
70 |
+
CHECK_INPUT(input2);
|
71 |
+
|
72 |
+
// set device of input1 as default CUDA device
|
73 |
+
// https://pytorch.org/cppdocs/api/structc10_1_1cuda_1_1_optional_c_u_d_a_guard.html
|
74 |
+
const at::cuda::OptionalCUDAGuard guard_input1(device_of(input1));
|
75 |
+
CHECK_SAME_DEVICE(input1, input2);
|
76 |
+
|
77 |
+
return correlation_cuda_forward(input1, input2, kH, kW, patchH, patchW,
|
78 |
+
padH, padW, dilationH, dilationW,
|
79 |
+
dilation_patchH, dilation_patchW,
|
80 |
+
dH, dW);
|
81 |
+
}else{
|
82 |
+
return correlation_cpp_forward(input1, input2, kH, kW, patchH, patchW,
|
83 |
+
padH, padW, dilationH, dilationW,
|
84 |
+
dilation_patchH, dilation_patchW,
|
85 |
+
dH, dW);
|
86 |
+
}
|
87 |
+
}
|
88 |
+
|
89 |
+
std::vector<torch::Tensor> correlation_sample_backward(
|
90 |
+
torch::Tensor input1,
|
91 |
+
torch::Tensor input2,
|
92 |
+
torch::Tensor grad_output,
|
93 |
+
int kH, int kW,
|
94 |
+
int patchH, int patchW,
|
95 |
+
int padH, int padW,
|
96 |
+
int dilationH, int dilationW,
|
97 |
+
int dilation_patchH, int dilation_patchW,
|
98 |
+
int dH, int dW) {
|
99 |
+
|
100 |
+
if(grad_output.device().is_cuda()){
|
101 |
+
CHECK_INPUT(input1);
|
102 |
+
CHECK_INPUT(input2);
|
103 |
+
|
104 |
+
// set device of input1 as default CUDA device
|
105 |
+
const at::cuda::OptionalCUDAGuard guard_input1(device_of(input1));
|
106 |
+
CHECK_SAME_DEVICE(input1, input2);
|
107 |
+
CHECK_SAME_DEVICE(input1, grad_output);
|
108 |
+
|
109 |
+
return correlation_cuda_backward(input1, input2, grad_output,
|
110 |
+
kH, kW, patchH, patchW,
|
111 |
+
padH, padW,
|
112 |
+
dilationH, dilationW,
|
113 |
+
dilation_patchH, dilation_patchW,
|
114 |
+
dH, dW);
|
115 |
+
}else{
|
116 |
+
return correlation_cpp_backward(
|
117 |
+
input1, input2, grad_output,
|
118 |
+
kH, kW, patchH, patchW,
|
119 |
+
padH, padW,
|
120 |
+
dilationH, dilationW,
|
121 |
+
dilation_patchH, dilation_patchW,
|
122 |
+
dH, dW);
|
123 |
+
}
|
124 |
+
}
|
125 |
+
|
126 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
127 |
+
m.def("forward", &correlation_sample_forward, "Spatial Correlation Sampler Forward");
|
128 |
+
m.def("backward", &correlation_sample_backward, "Spatial Correlation Sampler backward");
|
129 |
+
}
|
130 |
+
|
131 |
+
#else
|
132 |
+
|
133 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
134 |
+
m.def("forward", &correlation_cpp_forward, "Spatial Correlation Sampler Forward");
|
135 |
+
m.def("backward", &correlation_cpp_backward, "Spatial Correlation Sampler backward");
|
136 |
+
}
|
137 |
+
|
138 |
+
#endif
|
Pytorch-Correlation-extension/Correlation_Module/spatial_correlation_sampler/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .spatial_correlation_sampler import SpatialCorrelationSampler, spatial_correlation_sample
|
Pytorch-Correlation-extension/Correlation_Module/spatial_correlation_sampler/spatial_correlation_sampler.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
from torch.autograd import Function
|
3 |
+
from torch.autograd.function import once_differentiable
|
4 |
+
from torch.nn.modules.utils import _pair
|
5 |
+
|
6 |
+
import spatial_correlation_sampler_backend as correlation
|
7 |
+
|
8 |
+
|
9 |
+
def spatial_correlation_sample(input1,
|
10 |
+
input2,
|
11 |
+
kernel_size=1,
|
12 |
+
patch_size=1,
|
13 |
+
stride=1,
|
14 |
+
padding=0,
|
15 |
+
dilation=1,
|
16 |
+
dilation_patch=1):
|
17 |
+
"""Apply spatial correlation sampling on from input1 to input2,
|
18 |
+
|
19 |
+
Every parameter except input1 and input2 can be either single int
|
20 |
+
or a pair of int. For more information about Spatial Correlation
|
21 |
+
Sampling, see this page.
|
22 |
+
https://lmb.informatik.uni-freiburg.de/Publications/2015/DFIB15/
|
23 |
+
|
24 |
+
Args:
|
25 |
+
input1 : The first parameter.
|
26 |
+
input2 : The second parameter.
|
27 |
+
kernel_size : total size of your correlation kernel, in pixels
|
28 |
+
patch_size : total size of your patch, determining how many
|
29 |
+
different shifts will be applied
|
30 |
+
stride : stride of the spatial sampler, will modify output
|
31 |
+
height and width
|
32 |
+
padding : padding applied to input1 and input2 before applying
|
33 |
+
the correlation sampling, will modify output height and width
|
34 |
+
dilation_patch : step for every shift in patch
|
35 |
+
|
36 |
+
Returns:
|
37 |
+
Tensor: Result of correlation sampling
|
38 |
+
|
39 |
+
"""
|
40 |
+
return SpatialCorrelationSamplerFunction.apply(input1, input2,
|
41 |
+
kernel_size, patch_size,
|
42 |
+
stride, padding, dilation, dilation_patch)
|
43 |
+
|
44 |
+
|
45 |
+
class SpatialCorrelationSamplerFunction(Function):
|
46 |
+
|
47 |
+
@staticmethod
|
48 |
+
def forward(ctx,
|
49 |
+
input1,
|
50 |
+
input2,
|
51 |
+
kernel_size=1,
|
52 |
+
patch_size=1,
|
53 |
+
stride=1,
|
54 |
+
padding=0,
|
55 |
+
dilation=1,
|
56 |
+
dilation_patch=1):
|
57 |
+
|
58 |
+
ctx.save_for_backward(input1, input2)
|
59 |
+
kH, kW = ctx.kernel_size = _pair(kernel_size)
|
60 |
+
patchH, patchW = ctx.patch_size = _pair(patch_size)
|
61 |
+
padH, padW = ctx.padding = _pair(padding)
|
62 |
+
dilationH, dilationW = ctx.dilation = _pair(dilation)
|
63 |
+
dilation_patchH, dilation_patchW = ctx.dilation_patch = _pair(dilation_patch)
|
64 |
+
dH, dW = ctx.stride = _pair(stride)
|
65 |
+
|
66 |
+
output = correlation.forward(input1, input2,
|
67 |
+
kH, kW, patchH, patchW,
|
68 |
+
padH, padW, dilationH, dilationW,
|
69 |
+
dilation_patchH, dilation_patchW,
|
70 |
+
dH, dW)
|
71 |
+
|
72 |
+
return output
|
73 |
+
|
74 |
+
@staticmethod
|
75 |
+
@once_differentiable
|
76 |
+
def backward(ctx, grad_output):
|
77 |
+
input1, input2 = ctx.saved_variables
|
78 |
+
|
79 |
+
kH, kW = ctx.kernel_size
|
80 |
+
patchH, patchW = ctx.patch_size
|
81 |
+
padH, padW = ctx.padding
|
82 |
+
dilationH, dilationW = ctx.dilation
|
83 |
+
dilation_patchH, dilation_patchW = ctx.dilation_patch
|
84 |
+
dH, dW = ctx.stride
|
85 |
+
|
86 |
+
grad_input1, grad_input2 = correlation.backward(input1, input2, grad_output,
|
87 |
+
kH, kW, patchH, patchW,
|
88 |
+
padH, padW, dilationH, dilationW,
|
89 |
+
dilation_patchH, dilation_patchW,
|
90 |
+
dH, dW)
|
91 |
+
return grad_input1, grad_input2, None, None, None, None, None, None
|
92 |
+
|
93 |
+
|
94 |
+
class SpatialCorrelationSampler(nn.Module):
|
95 |
+
def __init__(self, kernel_size=1, patch_size=1, stride=1, padding=0, dilation=1, dilation_patch=1):
|
96 |
+
super(SpatialCorrelationSampler, self).__init__()
|
97 |
+
self.kernel_size = kernel_size
|
98 |
+
self.patch_size = patch_size
|
99 |
+
self.stride = stride
|
100 |
+
self.padding = padding
|
101 |
+
self.dilation = dilation
|
102 |
+
self.dilation_patch = dilation_patch
|
103 |
+
|
104 |
+
def forward(self, input1, input2):
|
105 |
+
return SpatialCorrelationSamplerFunction.apply(input1, input2, self.kernel_size,
|
106 |
+
self.patch_size, self.stride,
|
107 |
+
self.padding, self.dilation, self.dilation_patch)
|
Pytorch-Correlation-extension/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) [year] [fullname]
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
Pytorch-Correlation-extension/README.md
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
[![PyPI](https://img.shields.io/pypi/v/spatial-correlation-sampler.svg)](https://pypi.org/project/spatial-correlation-sampler/)
|
3 |
+
|
4 |
+
|
5 |
+
# Pytorch Correlation module
|
6 |
+
|
7 |
+
this is a custom C++/Cuda implementation of Correlation module, used e.g. in [FlowNetC](https://arxiv.org/abs/1504.06852)
|
8 |
+
|
9 |
+
This [tutorial](http://pytorch.org/tutorials/advanced/cpp_extension.html) was used as a basis for implementation, as well as
|
10 |
+
[NVIDIA's cuda code](https://github.com/NVIDIA/flownet2-pytorch/tree/master/networks/correlation_package)
|
11 |
+
|
12 |
+
- Build and Install C++ and CUDA extensions by executing `python setup.py install`,
|
13 |
+
- Benchmark C++ vs. CUDA by running `python benchmark.py {cpu, cuda}`,
|
14 |
+
- Run gradient checks on the code by running `python grad_check.py --backend {cpu, cuda}`.
|
15 |
+
|
16 |
+
# Requirements
|
17 |
+
|
18 |
+
This module is expected to compile for Pytorch `2.1.0`.
|
19 |
+
|
20 |
+
Before installation please check compatibility of your GPU and CUDA (_Compute Capability_) [nvidia docs](https://developer.nvidia.com/cuda-gpus).
|
21 |
+
e.g RTX 6000 is using CC=8.9 so we are setting the environment variable to
|
22 |
+
|
23 |
+
`export TORCH_CUDA_ARCH_LIST="8.9+PTX"`
|
24 |
+
|
25 |
+
# Installation
|
26 |
+
|
27 |
+
be reminded this module requires `python3-dev` to compile C++ code, e.g. on Ubuntu run:
|
28 |
+
|
29 |
+
`apt install python3-dev`
|
30 |
+
|
31 |
+
this module is available on pip
|
32 |
+
|
33 |
+
`pip install spatial-correlation-sampler`
|
34 |
+
|
35 |
+
For a cpu-only version, you can install from source with
|
36 |
+
|
37 |
+
`python setup_cpu.py install`
|
38 |
+
|
39 |
+
# Known Problems
|
40 |
+
|
41 |
+
This module needs compatible gcc version and CUDA to be compiled.
|
42 |
+
Namely, CUDA 9.1 and below will need gcc5, while CUDA 9.2 and 10.0 will need gcc7
|
43 |
+
See [this issue](https://github.com/ClementPinard/Pytorch-Correlation-extension/issues/1) for more information
|
44 |
+
|
45 |
+
# Usage
|
46 |
+
|
47 |
+
API has a few difference with NVIDIA's module
|
48 |
+
* output is now a 5D tensor, which reflects the shifts horizontal and vertical.
|
49 |
+
```
|
50 |
+
input (B x C x H x W) -> output (B x PatchH x PatchW x oH x oW)
|
51 |
+
```
|
52 |
+
* Output sizes `oH` and `oW` are no longer dependant of patch size, but only of kernel size and padding
|
53 |
+
* Patch size `patch_size` is now the whole patch, and not only the radii.
|
54 |
+
* `stride1` is now `stride` and`stride2` is `dilation_patch`, which behave like dilated convolutions
|
55 |
+
* equivalent `max_displacement` is then `dilation_patch * (patch_size - 1) / 2`.
|
56 |
+
* `dilation` is a new parameter, it acts the same way as dilated convolution regarding the correlation kernel
|
57 |
+
* to get the right parameters for FlowNetC, you would have
|
58 |
+
```
|
59 |
+
kernel_size=1
|
60 |
+
patch_size=21,
|
61 |
+
stride=1,
|
62 |
+
padding=0,
|
63 |
+
dilation=1
|
64 |
+
dilation_patch=2
|
65 |
+
```
|
66 |
+
|
67 |
+
|
68 |
+
## Example
|
69 |
+
```python
|
70 |
+
import torch
|
71 |
+
from spatial_correlation_sampler import SpatialCorrelationSampler,
|
72 |
+
|
73 |
+
device = "cuda"
|
74 |
+
batch_size = 1
|
75 |
+
channel = 1
|
76 |
+
H = 10
|
77 |
+
W = 10
|
78 |
+
dtype = torch.float32
|
79 |
+
|
80 |
+
input1 = torch.randint(1, 4, (batch_size, channel, H, W), dtype=dtype, device=device, requires_grad=True)
|
81 |
+
input2 = torch.randint_like(input1, 1, 4).requires_grad_(True)
|
82 |
+
|
83 |
+
#You can either use the function or the module. Note that the module doesn't contain any parameter tensor.
|
84 |
+
|
85 |
+
#function
|
86 |
+
|
87 |
+
out = spatial_correlation_sample(input1,
|
88 |
+
input2,
|
89 |
+
kernel_size=3,
|
90 |
+
patch_size=1,
|
91 |
+
stride=2,
|
92 |
+
padding=0,
|
93 |
+
dilation=2,
|
94 |
+
dilation_patch=1)
|
95 |
+
|
96 |
+
#module
|
97 |
+
|
98 |
+
correlation_sampler = SpatialCorrelationSampler(
|
99 |
+
kernel_size=3,
|
100 |
+
patch_size=1,
|
101 |
+
stride=2,
|
102 |
+
padding=0,
|
103 |
+
dilation=2,
|
104 |
+
dilation_patch=1)
|
105 |
+
out = correlation_sampler(input1, input2)
|
106 |
+
|
107 |
+
```
|
108 |
+
|
109 |
+
# Benchmark
|
110 |
+
|
111 |
+
* default parameters are from `benchmark.py`, FlowNetC parameters are same as use in `FlowNetC` with a batch size of 4, described in [this paper](https://arxiv.org/abs/1504.06852), implemented [here](https://github.com/lmb-freiburg/flownet2) and [here](https://github.com/NVIDIA/flownet2-pytorch/blob/master/networks/FlowNetC.py).
|
112 |
+
* Feel free to file an issue to add entries to this with your hardware !
|
113 |
+
|
114 |
+
## CUDA Benchmark
|
115 |
+
|
116 |
+
* See [here](https://gist.github.com/ClementPinard/270e910147119831014932f67fb1b5ea) for a benchmark script working with [NVIDIA](https://github.com/NVIDIA/flownet2-pytorch/tree/master/networks/correlation_package)'s code, and Pytorch.
|
117 |
+
* Benchmark are launched with environment variable `CUDA_LAUNCH_BLOCKING` set to `1`.
|
118 |
+
* Only `float32` is benchmarked.
|
119 |
+
* FlowNetC correlation parameters where launched with the following command:
|
120 |
+
|
121 |
+
```bash
|
122 |
+
CUDA_LAUNCH_BLOCKING=1 python benchmark.py --scale ms -k1 --patch 21 -s1 -p0 --patch_dilation 2 -b4 --height 48 --width 64 -c256 cuda -d float
|
123 |
+
|
124 |
+
CUDA_LAUNCH_BLOCKING=1 python NV_correlation_benchmark.py --scale ms -k1 --patch 21 -s1 -p0 --patch_dilation 2 -b4 --height 48 --width 64 -c256
|
125 |
+
```
|
126 |
+
|
127 |
+
| implementation | Correlation parameters | device | pass | min time | avg time |
|
128 |
+
| -------------- | ---------------------- | ------- | -------- | ------------: | ------------: |
|
129 |
+
| ours | default | 980 GTX | forward | **5.745 ms** | **5.851 ms** |
|
130 |
+
| ours | default | 980 GTX | backward | 77.694 ms | 77.957 ms |
|
131 |
+
| NVIDIA | default | 980 GTX | forward | 13.779 ms | 13.853 ms |
|
132 |
+
| NVIDIA | default | 980 GTX | backward | **73.383 ms** | **73.708 ms** |
|
133 |
+
| | | | | | |
|
134 |
+
| ours | FlowNetC | 980 GTX | forward | **26.102 ms** | **26.179 ms** |
|
135 |
+
| ours | FlowNetC | 980 GTX | backward | **208.091 ms** | **208.510 ms** |
|
136 |
+
| NVIDIA | FlowNetC | 980 GTX | forward | 35.363 ms | 35.550 ms |
|
137 |
+
| NVIDIA | FlowNetC | 980 GTX | backward | 283.748 ms | 284.346 ms |
|
138 |
+
|
139 |
+
### Notes
|
140 |
+
* The overhead of our implementation regarding `kernel_size` > 1 during backward needs some investigation, feel free to
|
141 |
+
dive in the code to improve it !
|
142 |
+
* The backward pass of NVIDIA is not entirely correct when stride1 > 1 and kernel_size > 1, because not everything
|
143 |
+
is computed, see [here](https://github.com/NVIDIA/flownet2-pytorch/blob/master/networks/correlation_package/src/correlation_cuda_kernel.cu#L120).
|
144 |
+
|
145 |
+
## CPU Benchmark
|
146 |
+
|
147 |
+
* No other implementation is avalaible on CPU.
|
148 |
+
* It is obviously not recommended to run it on CPU if you have a GPU.
|
149 |
+
|
150 |
+
| Correlation parameters | device | pass | min time | avg time |
|
151 |
+
| ---------------------- | -------------------- | -------- | ----------: | ----------: |
|
152 |
+
| default | E5-2630 v3 @ 2.40GHz | forward | 159.616 ms | 188.727 ms |
|
153 |
+
| default | E5-2630 v3 @ 2.40GHz | backward | 282.641 ms | 294.194 ms |
|
154 |
+
| FlowNetC | E5-2630 v3 @ 2.40GHz | forward | 2.138 s | 2.144 s |
|
155 |
+
| FlowNetC | E5-2630 v3 @ 2.40GHz | backward | 7.006 s | 7.075 s |
|
Pytorch-Correlation-extension/benchmark.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division
|
2 |
+
from __future__ import print_function
|
3 |
+
|
4 |
+
import argparse
|
5 |
+
import time
|
6 |
+
|
7 |
+
import torch
|
8 |
+
from spatial_correlation_sampler import SpatialCorrelationSampler
|
9 |
+
from tqdm import trange
|
10 |
+
|
11 |
+
TIME_SCALES = {'s': 1, 'ms': 1000, 'us': 1000000}
|
12 |
+
|
13 |
+
parser = argparse.ArgumentParser()
|
14 |
+
parser.add_argument('backend', choices=['cpu', 'cuda'], default='cuda')
|
15 |
+
parser.add_argument('-b', '--batch-size', type=int, default=16)
|
16 |
+
parser.add_argument('-k', '--kernel-size', type=int, default=3)
|
17 |
+
parser.add_argument('--patch', type=int, default=3)
|
18 |
+
parser.add_argument('--patch_dilation', type=int, default=2)
|
19 |
+
parser.add_argument('-c', '--channel', type=int, default=64)
|
20 |
+
parser.add_argument('--height', type=int, default=100)
|
21 |
+
parser.add_argument('-w', '--width', type=int, default=100)
|
22 |
+
parser.add_argument('-s', '--stride', type=int, default=2)
|
23 |
+
parser.add_argument('-p', '--pad', type=int, default=1)
|
24 |
+
parser.add_argument('--scale', choices=['s', 'ms', 'us'], default='us')
|
25 |
+
parser.add_argument('-r', '--runs', type=int, default=100)
|
26 |
+
parser.add_argument('--dilation', type=int, default=2)
|
27 |
+
parser.add_argument('-d', '--dtype', choices=['half', 'float', 'double'])
|
28 |
+
|
29 |
+
args = parser.parse_args()
|
30 |
+
|
31 |
+
device = torch.device(args.backend)
|
32 |
+
|
33 |
+
if args.dtype == 'half':
|
34 |
+
dtype = torch.float16
|
35 |
+
elif args.dtype == 'float':
|
36 |
+
dtype = torch.float32
|
37 |
+
else:
|
38 |
+
dtype = torch.float64
|
39 |
+
|
40 |
+
|
41 |
+
input1 = torch.randn(args.batch_size,
|
42 |
+
args.channel,
|
43 |
+
args.height,
|
44 |
+
args.width,
|
45 |
+
dtype=dtype,
|
46 |
+
device=device,
|
47 |
+
requires_grad=True)
|
48 |
+
input2 = torch.randn_like(input1)
|
49 |
+
|
50 |
+
correlation_sampler = SpatialCorrelationSampler(
|
51 |
+
args.kernel_size,
|
52 |
+
args.patch,
|
53 |
+
args.stride,
|
54 |
+
args.pad,
|
55 |
+
args.dilation,
|
56 |
+
args.patch_dilation)
|
57 |
+
|
58 |
+
# Force CUDA initialization
|
59 |
+
output = correlation_sampler(input1, input2)
|
60 |
+
print(output.size())
|
61 |
+
output.mean().backward()
|
62 |
+
forward_min = float('inf')
|
63 |
+
forward_time = 0
|
64 |
+
backward_min = float('inf')
|
65 |
+
backward_time = 0
|
66 |
+
for _ in trange(args.runs):
|
67 |
+
correlation_sampler.zero_grad()
|
68 |
+
|
69 |
+
start = time.time()
|
70 |
+
output = correlation_sampler(input1, input2)
|
71 |
+
elapsed = time.time() - start
|
72 |
+
forward_min = min(forward_min, elapsed)
|
73 |
+
forward_time += elapsed
|
74 |
+
output = output.mean()
|
75 |
+
|
76 |
+
start = time.time()
|
77 |
+
(output.mean()).backward()
|
78 |
+
elapsed = time.time() - start
|
79 |
+
backward_min = min(backward_min, elapsed)
|
80 |
+
backward_time += elapsed
|
81 |
+
|
82 |
+
scale = TIME_SCALES[args.scale]
|
83 |
+
forward_min *= scale
|
84 |
+
backward_min *= scale
|
85 |
+
forward_average = forward_time / args.runs * scale
|
86 |
+
backward_average = backward_time / args.runs * scale
|
87 |
+
|
88 |
+
print('Forward: {0:.3f}/{1:.3f} {4} | Backward {2:.3f}/{3:.3f} {4}'.format(
|
89 |
+
forward_min, forward_average, backward_min, backward_average,
|
90 |
+
args.scale))
|
Pytorch-Correlation-extension/check.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import division
|
2 |
+
from __future__ import print_function
|
3 |
+
|
4 |
+
import argparse
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
|
8 |
+
from spatial_correlation_sampler import SpatialCorrelationSampler
|
9 |
+
|
10 |
+
|
11 |
+
def check_equal(first, second, verbose):
|
12 |
+
if verbose:
|
13 |
+
print()
|
14 |
+
for i, (x, y) in enumerate(zip(first, second)):
|
15 |
+
x = x.cpu().detach().numpy()
|
16 |
+
y = y.cpu().detach().numpy()
|
17 |
+
if verbose:
|
18 |
+
print("x = {}".format(x.flatten()))
|
19 |
+
print("y = {}".format(y.flatten()))
|
20 |
+
print('-' * 80)
|
21 |
+
np.testing.assert_allclose(x, y, err_msg="Index: {}".format(i))
|
22 |
+
|
23 |
+
|
24 |
+
def zero_grad(variables):
|
25 |
+
for variable in variables:
|
26 |
+
if variable.grad is not None: variable.grad.zero_()
|
27 |
+
|
28 |
+
|
29 |
+
def get_grads(variables):
|
30 |
+
return [var.grad.clone() for var in variables]
|
31 |
+
|
32 |
+
|
33 |
+
def check_forward(input1, input2, correlation_sampler, verbose, gpu_index=0):
|
34 |
+
device = torch.device(f"cuda:{gpu_index}")
|
35 |
+
|
36 |
+
cpu_values = correlation_sampler(input1, input2)
|
37 |
+
cuda_values = correlation_sampler(input1.to(device), input2.to(device))
|
38 |
+
|
39 |
+
print(f"Forward: CPU vs. CUDA device:{gpu_index} ... ", end='')
|
40 |
+
check_equal(cpu_values, cuda_values, verbose)
|
41 |
+
print('Ok')
|
42 |
+
|
43 |
+
|
44 |
+
def check_backward(input1, input2, correlation_sampler, verbose, gpu_index=0):
|
45 |
+
device = torch.device(f"cuda:{gpu_index}")
|
46 |
+
|
47 |
+
zero_grad([input1, input2])
|
48 |
+
|
49 |
+
cpu_values = correlation_sampler(input1, input2)
|
50 |
+
cpu_values.sum().backward()
|
51 |
+
grad_cpu = get_grads([input1, input2])
|
52 |
+
|
53 |
+
zero_grad([input1, input2])
|
54 |
+
|
55 |
+
cuda_values = correlation_sampler(input1.to(device), input2.to(device))
|
56 |
+
cuda_values.sum().backward()
|
57 |
+
grad_cuda = get_grads([input1, input2])
|
58 |
+
|
59 |
+
print(f"Backward: CPU vs. CUDA device:{gpu_index} ... ", end='')
|
60 |
+
check_equal(grad_cpu, grad_cuda, verbose)
|
61 |
+
print('Ok')
|
62 |
+
|
63 |
+
|
64 |
+
def check_multi_gpu_forward(correlation_sampler, verbose):
|
65 |
+
print("Multi-GPU forward")
|
66 |
+
total_gpus = torch.cuda.device_count()
|
67 |
+
for gpu in range(total_gpus):
|
68 |
+
check_forward(input1, input2, correlation_sampler, verbose, gpu_index=gpu)
|
69 |
+
|
70 |
+
def check_multi_gpu_backward(correlation_sampler, verbose):
|
71 |
+
print("Multi-GPU backward")
|
72 |
+
total_gpus = torch.cuda.device_count()
|
73 |
+
for gpu in range(total_gpus):
|
74 |
+
check_backward(input1, input2, correlation_sampler, verbose, gpu_index=gpu)
|
75 |
+
|
76 |
+
|
77 |
+
parser = argparse.ArgumentParser()
|
78 |
+
parser.add_argument('direction', choices=['forward', 'backward'], nargs='+')
|
79 |
+
parser.add_argument('-b', '--batch-size', type=int, default=1)
|
80 |
+
parser.add_argument('-k', '--kernel-size', type=int, default=3)
|
81 |
+
parser.add_argument('--patch', type=int, default=3)
|
82 |
+
parser.add_argument('--patch_dilation', type=int, default=2)
|
83 |
+
parser.add_argument('-c', '--channel', type=int, default=10)
|
84 |
+
parser.add_argument('--height', type=int, default=10)
|
85 |
+
parser.add_argument('-w', '--width', type=int, default=10)
|
86 |
+
parser.add_argument('-s', '--stride', type=int, default=2)
|
87 |
+
parser.add_argument('-p', '--pad', type=int, default=5)
|
88 |
+
parser.add_argument('-v', '--verbose', action='store_true', default=False)
|
89 |
+
parser.add_argument('-d', '--dilation', type=int, default=2)
|
90 |
+
args = parser.parse_args()
|
91 |
+
print(args)
|
92 |
+
|
93 |
+
assert(torch.cuda.is_available()), "no comparison to make"
|
94 |
+
input1 = torch.randn(args.batch_size,
|
95 |
+
args.channel,
|
96 |
+
args.height,
|
97 |
+
args.width).double()
|
98 |
+
input2 = torch.randn(args.batch_size,
|
99 |
+
args.channel,
|
100 |
+
args.height,
|
101 |
+
args.width).double()
|
102 |
+
input1.requires_grad = True
|
103 |
+
input2.requires_grad = True
|
104 |
+
|
105 |
+
correlation_sampler = SpatialCorrelationSampler(
|
106 |
+
args.kernel_size,
|
107 |
+
args.patch,
|
108 |
+
args.stride,
|
109 |
+
args.pad,
|
110 |
+
args.dilation,
|
111 |
+
args.patch_dilation)
|
112 |
+
|
113 |
+
if 'forward' in args.direction:
|
114 |
+
check_forward(input1, input2, correlation_sampler, args.verbose)
|
115 |
+
if torch.cuda.device_count() > 1: check_multi_gpu_forward(correlation_sampler, args.verbose)
|
116 |
+
|
117 |
+
if 'backward' in args.direction:
|
118 |
+
check_backward(input1, input2, correlation_sampler, args.verbose)
|
119 |
+
if torch.cuda.device_count() > 1: check_multi_gpu_backward(correlation_sampler, args.verbose)
|
Pytorch-Correlation-extension/grad_check.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import torch
|
3 |
+
# torch.set_printoptions(precision=1, threshold=10000)
|
4 |
+
from torch.autograd import gradcheck
|
5 |
+
from spatial_correlation_sampler import SpatialCorrelationSampler
|
6 |
+
|
7 |
+
parser = argparse.ArgumentParser()
|
8 |
+
parser.add_argument('backend', choices=['cpu', 'cuda'], default='cuda')
|
9 |
+
parser.add_argument('-b', '--batch-size', type=int, default=2)
|
10 |
+
parser.add_argument('-k', '--kernel-size', type=int, default=3)
|
11 |
+
parser.add_argument('--patch', type=int, default=3)
|
12 |
+
parser.add_argument('--patch_dilation', type=int, default=2)
|
13 |
+
parser.add_argument('-c', '--channel', type=int, default=2)
|
14 |
+
parser.add_argument('--height', type=int, default=10)
|
15 |
+
parser.add_argument('-w', '--width', type=int, default=10)
|
16 |
+
parser.add_argument('-s', '--stride', type=int, default=2)
|
17 |
+
parser.add_argument('-p', '--pad', type=int, default=1)
|
18 |
+
parser.add_argument('-d', '--dilation', type=int, default=2)
|
19 |
+
|
20 |
+
args = parser.parse_args()
|
21 |
+
|
22 |
+
input1 = torch.randn(args.batch_size,
|
23 |
+
args.channel,
|
24 |
+
args.height,
|
25 |
+
args.width,
|
26 |
+
dtype=torch.float64,
|
27 |
+
device=torch.device(args.backend))
|
28 |
+
input2 = torch.randn(args.batch_size,
|
29 |
+
args.channel,
|
30 |
+
args.height,
|
31 |
+
args.width,
|
32 |
+
dtype=torch.float64,
|
33 |
+
device=torch.device(args.backend))
|
34 |
+
|
35 |
+
input1.requires_grad = True
|
36 |
+
input2.requires_grad = True
|
37 |
+
|
38 |
+
correlation_sampler = SpatialCorrelationSampler(args.kernel_size,
|
39 |
+
args.patch,
|
40 |
+
args.stride,
|
41 |
+
args.pad,
|
42 |
+
args.dilation,
|
43 |
+
args.patch_dilation)
|
44 |
+
|
45 |
+
|
46 |
+
if gradcheck(correlation_sampler, [input1, input2]):
|
47 |
+
print('Ok')
|
Pytorch-Correlation-extension/requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
torch>=1.0.1
|
2 |
+
numpy
|
Pytorch-Correlation-extension/setup.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from setuptools import setup
|
3 |
+
from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CppExtension
|
4 |
+
from os.path import join
|
5 |
+
|
6 |
+
CPU_ONLY = False
|
7 |
+
project_root = 'Correlation_Module'
|
8 |
+
|
9 |
+
source_files = ['correlation.cpp', 'correlation_sampler.cpp']
|
10 |
+
|
11 |
+
cxx_args = ['-std=c++17', '-fopenmp']
|
12 |
+
|
13 |
+
def generate_nvcc_args(gpu_archs):
|
14 |
+
nvcc_args = []
|
15 |
+
for arch in gpu_archs:
|
16 |
+
nvcc_args.extend(['-gencode', f'arch=compute_{arch},code=sm_{arch}'])
|
17 |
+
return nvcc_args
|
18 |
+
|
19 |
+
gpu_arch = os.environ.get('GPU_ARCH', '').split()
|
20 |
+
nvcc_args = generate_nvcc_args(gpu_arch)
|
21 |
+
|
22 |
+
with open("README.md", "r") as fh:
|
23 |
+
long_description = fh.read()
|
24 |
+
|
25 |
+
|
26 |
+
def launch_setup():
|
27 |
+
if CPU_ONLY:
|
28 |
+
Extension = CppExtension
|
29 |
+
macro = []
|
30 |
+
else:
|
31 |
+
Extension = CUDAExtension
|
32 |
+
source_files.append('correlation_cuda_kernel.cu')
|
33 |
+
macro = [("USE_CUDA", None)]
|
34 |
+
|
35 |
+
sources = [join(project_root, file) for file in source_files]
|
36 |
+
|
37 |
+
setup(
|
38 |
+
name='spatial_correlation_sampler',
|
39 |
+
version="0.4.0",
|
40 |
+
author="Clément Pinard",
|
41 |
+
author_email="[email protected]",
|
42 |
+
description="Correlation module for pytorch",
|
43 |
+
long_description=long_description,
|
44 |
+
long_description_content_type="text/markdown",
|
45 |
+
url="https://github.com/ClementPinard/Pytorch-Correlation-extension",
|
46 |
+
install_requires=['torch>=1.1', 'numpy'],
|
47 |
+
ext_modules=[
|
48 |
+
Extension('spatial_correlation_sampler_backend',
|
49 |
+
sources,
|
50 |
+
define_macros=macro,
|
51 |
+
extra_compile_args={'cxx': cxx_args, 'nvcc': nvcc_args},
|
52 |
+
extra_link_args=['-lgomp'])
|
53 |
+
],
|
54 |
+
package_dir={'': project_root},
|
55 |
+
packages=['spatial_correlation_sampler'],
|
56 |
+
cmdclass={
|
57 |
+
'build_ext': BuildExtension
|
58 |
+
},
|
59 |
+
classifiers=[
|
60 |
+
"Programming Language :: Python :: 3",
|
61 |
+
"License :: OSI Approved :: MIT License",
|
62 |
+
"Operating System :: POSIX :: Linux",
|
63 |
+
"Intended Audience :: Science/Research",
|
64 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence"
|
65 |
+
])
|
66 |
+
|
67 |
+
|
68 |
+
if __name__ == '__main__':
|
69 |
+
launch_setup()
|
Pytorch-Correlation-extension/setup_cpu.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import setup
|
2 |
+
|
3 |
+
setup.CPU_ONLY = True
|
4 |
+
setup.launch_setup()
|
sam/.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
sam/.flake8
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[flake8]
|
2 |
+
ignore = W503, E203, E221, C901, C408, E741, C407, B017, F811, C101, EXE001, EXE002
|
3 |
+
max-line-length = 100
|
4 |
+
max-complexity = 18
|
5 |
+
select = B,C,E,F,W,T4,B9
|
6 |
+
per-file-ignores =
|
7 |
+
**/__init__.py:F401,F403,E402
|
sam/.gitignore
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.nfs*
|
2 |
+
|
3 |
+
# compilation and distribution
|
4 |
+
__pycache__
|
5 |
+
_ext
|
6 |
+
*.pyc
|
7 |
+
*.pyd
|
8 |
+
*.so
|
9 |
+
*.dll
|
10 |
+
*.egg-info/
|
11 |
+
build/
|
12 |
+
dist/
|
13 |
+
wheels/
|
14 |
+
|
15 |
+
# pytorch/python/numpy formats
|
16 |
+
*.pth
|
17 |
+
*.pkl
|
18 |
+
*.npy
|
19 |
+
*.ts
|
20 |
+
model_ts*.txt
|
21 |
+
|
22 |
+
# onnx models
|
23 |
+
*.onnx
|
24 |
+
|
25 |
+
# ipython/jupyter notebooks
|
26 |
+
**/.ipynb_checkpoints/
|
27 |
+
|
28 |
+
# Editor temporaries
|
29 |
+
*.swn
|
30 |
+
*.swo
|
31 |
+
*.swp
|
32 |
+
*~
|
33 |
+
|
34 |
+
# editor settings
|
35 |
+
.idea
|
36 |
+
.vscode
|
37 |
+
_darcs
|
sam/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Code of Conduct
|
2 |
+
|
3 |
+
## Our Pledge
|
4 |
+
|
5 |
+
In the interest of fostering an open and welcoming environment, we as
|
6 |
+
contributors and maintainers pledge to make participation in our project and
|
7 |
+
our community a harassment-free experience for everyone, regardless of age, body
|
8 |
+
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
9 |
+
level of experience, education, socio-economic status, nationality, personal
|
10 |
+
appearance, race, religion, or sexual identity and orientation.
|
11 |
+
|
12 |
+
## Our Standards
|
13 |
+
|
14 |
+
Examples of behavior that contributes to creating a positive environment
|
15 |
+
include:
|
16 |
+
|
17 |
+
* Using welcoming and inclusive language
|
18 |
+
* Being respectful of differing viewpoints and experiences
|
19 |
+
* Gracefully accepting constructive criticism
|
20 |
+
* Focusing on what is best for the community
|
21 |
+
* Showing empathy towards other community members
|
22 |
+
|
23 |
+
Examples of unacceptable behavior by participants include:
|
24 |
+
|
25 |
+
* The use of sexualized language or imagery and unwelcome sexual attention or
|
26 |
+
advances
|
27 |
+
* Trolling, insulting/derogatory comments, and personal or political attacks
|
28 |
+
* Public or private harassment
|
29 |
+
* Publishing others' private information, such as a physical or electronic
|
30 |
+
address, without explicit permission
|
31 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
32 |
+
professional setting
|
33 |
+
|
34 |
+
## Our Responsibilities
|
35 |
+
|
36 |
+
Project maintainers are responsible for clarifying the standards of acceptable
|
37 |
+
behavior and are expected to take appropriate and fair corrective action in
|
38 |
+
response to any instances of unacceptable behavior.
|
39 |
+
|
40 |
+
Project maintainers have the right and responsibility to remove, edit, or
|
41 |
+
reject comments, commits, code, wiki edits, issues, and other contributions
|
42 |
+
that are not aligned to this Code of Conduct, or to ban temporarily or
|
43 |
+
permanently any contributor for other behaviors that they deem inappropriate,
|
44 |
+
threatening, offensive, or harmful.
|
45 |
+
|
46 |
+
## Scope
|
47 |
+
|
48 |
+
This Code of Conduct applies within all project spaces, and it also applies when
|
49 |
+
an individual is representing the project or its community in public spaces.
|
50 |
+
Examples of representing a project or community include using an official
|
51 |
+
project e-mail address, posting via an official social media account, or acting
|
52 |
+
as an appointed representative at an online or offline event. Representation of
|
53 |
+
a project may be further defined and clarified by project maintainers.
|
54 |
+
|
55 |
+
This Code of Conduct also applies outside the project spaces when there is a
|
56 |
+
reasonable belief that an individual's behavior may have a negative impact on
|
57 |
+
the project or its community.
|
58 |
+
|
59 |
+
## Enforcement
|
60 |
+
|
61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62 |
+
reported by contacting the project team at <[email protected]>. All
|
63 |
+
complaints will be reviewed and investigated and will result in a response that
|
64 |
+
is deemed necessary and appropriate to the circumstances. The project team is
|
65 |
+
obligated to maintain confidentiality with regard to the reporter of an incident.
|
66 |
+
Further details of specific enforcement policies may be posted separately.
|
67 |
+
|
68 |
+
Project maintainers who do not follow or enforce the Code of Conduct in good
|
69 |
+
faith may face temporary or permanent repercussions as determined by other
|
70 |
+
members of the project's leadership.
|
71 |
+
|
72 |
+
## Attribution
|
73 |
+
|
74 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
75 |
+
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
76 |
+
|
77 |
+
[homepage]: https://www.contributor-covenant.org
|
78 |
+
|
79 |
+
For answers to common questions about this code of conduct, see
|
80 |
+
https://www.contributor-covenant.org/faq
|
sam/CONTRIBUTING.md
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to segment-anything
|
2 |
+
We want to make contributing to this project as easy and transparent as
|
3 |
+
possible.
|
4 |
+
|
5 |
+
## Pull Requests
|
6 |
+
We actively welcome your pull requests.
|
7 |
+
|
8 |
+
1. Fork the repo and create your branch from `main`.
|
9 |
+
2. If you've added code that should be tested, add tests.
|
10 |
+
3. If you've changed APIs, update the documentation.
|
11 |
+
4. Ensure the test suite passes.
|
12 |
+
5. Make sure your code lints, using the `linter.sh` script in the project's root directory. Linting requires `black==23.*`, `isort==5.12.0`, `flake8`, and `mypy`.
|
13 |
+
6. If you haven't already, complete the Contributor License Agreement ("CLA").
|
14 |
+
|
15 |
+
## Contributor License Agreement ("CLA")
|
16 |
+
In order to accept your pull request, we need you to submit a CLA. You only need
|
17 |
+
to do this once to work on any of Facebook's open source projects.
|
18 |
+
|
19 |
+
Complete your CLA here: <https://code.facebook.com/cla>
|
20 |
+
|
21 |
+
## Issues
|
22 |
+
We use GitHub issues to track public bugs. Please ensure your description is
|
23 |
+
clear and has sufficient instructions to be able to reproduce the issue.
|
24 |
+
|
25 |
+
Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
|
26 |
+
disclosure of security bugs. In those cases, please go through the process
|
27 |
+
outlined on that page and do not file a public issue.
|
28 |
+
|
29 |
+
## License
|
30 |
+
By contributing to segment-anything, you agree that your contributions will be licensed
|
31 |
+
under the LICENSE file in the root directory of this source tree.
|
sam/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.
|
sam/README.md
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Segment Anything
|
2 |
+
|
3 |
+
**[Meta AI Research, FAIR](https://ai.facebook.com/research/)**
|
4 |
+
|
5 |
+
[Alexander Kirillov](https://alexander-kirillov.github.io/), [Eric Mintun](https://ericmintun.github.io/), [Nikhila Ravi](https://nikhilaravi.com/), [Hanzi Mao](https://hanzimao.me/), Chloe Rolland, Laura Gustafson, [Tete Xiao](https://tetexiao.com), [Spencer Whitehead](https://www.spencerwhitehead.com/), Alex Berg, Wan-Yen Lo, [Piotr Dollar](https://pdollar.github.io/), [Ross Girshick](https://www.rossgirshick.info/)
|
6 |
+
|
7 |
+
[[`Paper`](https://ai.facebook.com/research/publications/segment-anything/)] [[`Project`](https://segment-anything.com/)] [[`Demo`](https://segment-anything.com/demo)] [[`Dataset`](https://segment-anything.com/dataset/index.html)] [[`Blog`](https://ai.facebook.com/blog/segment-anything-foundation-model-image-segmentation/)] [[`BibTeX`](#citing-segment-anything)]
|
8 |
+
|
9 |
+
![SAM design](assets/model_diagram.png?raw=true)
|
10 |
+
|
11 |
+
The **Segment Anything Model (SAM)** produces high quality object masks from input prompts such as points or boxes, and it can be used to generate masks for all objects in an image. It has been trained on a [dataset](https://segment-anything.com/dataset/index.html) of 11 million images and 1.1 billion masks, and has strong zero-shot performance on a variety of segmentation tasks.
|
12 |
+
|
13 |
+
<p float="left">
|
14 |
+
<img src="assets/masks1.png?raw=true" width="37.25%" />
|
15 |
+
<img src="assets/masks2.jpg?raw=true" width="61.5%" />
|
16 |
+
</p>
|
17 |
+
|
18 |
+
## Installation
|
19 |
+
|
20 |
+
The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.
|
21 |
+
|
22 |
+
Install Segment Anything:
|
23 |
+
|
24 |
+
```
|
25 |
+
pip install git+https://github.com/facebookresearch/segment-anything.git
|
26 |
+
```
|
27 |
+
|
28 |
+
or clone the repository locally and install with
|
29 |
+
|
30 |
+
```
|
31 |
+
git clone [email protected]:facebookresearch/segment-anything.git
|
32 |
+
cd segment-anything; pip install -e .
|
33 |
+
```
|
34 |
+
|
35 |
+
The following optional dependencies are necessary for mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format. `jupyter` is also required to run the example notebooks.
|
36 |
+
```
|
37 |
+
pip install opencv-python pycocotools matplotlib onnxruntime onnx
|
38 |
+
```
|
39 |
+
|
40 |
+
|
41 |
+
## <a name="GettingStarted"></a>Getting Started
|
42 |
+
|
43 |
+
First download a [model checkpoint](#model-checkpoints). Then the model can be used in just a few lines to get masks from a given prompt:
|
44 |
+
|
45 |
+
```
|
46 |
+
from segment_anything import SamPredictor, sam_model_registry
|
47 |
+
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
|
48 |
+
predictor = SamPredictor(sam)
|
49 |
+
predictor.set_image(<your_image>)
|
50 |
+
masks, _, _ = predictor.predict(<input_prompts>)
|
51 |
+
```
|
52 |
+
|
53 |
+
or generate masks for an entire image:
|
54 |
+
|
55 |
+
```
|
56 |
+
from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
|
57 |
+
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
|
58 |
+
mask_generator = SamAutomaticMaskGenerator(sam)
|
59 |
+
masks = mask_generator.generate(<your_image>)
|
60 |
+
```
|
61 |
+
|
62 |
+
Additionally, masks can be generated for images from the command line:
|
63 |
+
|
64 |
+
```
|
65 |
+
python scripts/amg.py --checkpoint <path/to/checkpoint> --model-type <model_type> --input <image_or_folder> --output <path/to/output>
|
66 |
+
```
|
67 |
+
|
68 |
+
See the examples notebooks on [using SAM with prompts](/notebooks/predictor_example.ipynb) and [automatically generating masks](/notebooks/automatic_mask_generator_example.ipynb) for more details.
|
69 |
+
|
70 |
+
<p float="left">
|
71 |
+
<img src="assets/notebook1.png?raw=true" width="49.1%" />
|
72 |
+
<img src="assets/notebook2.png?raw=true" width="48.9%" />
|
73 |
+
</p>
|
74 |
+
|
75 |
+
## ONNX Export
|
76 |
+
|
77 |
+
SAM's lightweight mask decoder can be exported to ONNX format so that it can be run in any environment that supports ONNX runtime, such as in-browser as showcased in the [demo](https://segment-anything.com/demo). Export the model with
|
78 |
+
|
79 |
+
```
|
80 |
+
python scripts/export_onnx_model.py --checkpoint <path/to/checkpoint> --model-type <model_type> --output <path/to/output>
|
81 |
+
```
|
82 |
+
|
83 |
+
See the [example notebook](https://github.com/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb) for details on how to combine image preprocessing via SAM's backbone with mask prediction using the ONNX model. It is recommended to use the latest stable version of PyTorch for ONNX export.
|
84 |
+
|
85 |
+
## <a name="Models"></a>Model Checkpoints
|
86 |
+
|
87 |
+
Three model versions of the model are available with different backbone sizes. These models can be instantiated by running
|
88 |
+
```
|
89 |
+
from segment_anything import sam_model_registry
|
90 |
+
sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
|
91 |
+
```
|
92 |
+
Click the links below to download the checkpoint for the corresponding model type.
|
93 |
+
|
94 |
+
* **`default` or `vit_h`: [ViT-H SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth)**
|
95 |
+
* `vit_l`: [ViT-L SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth)
|
96 |
+
* `vit_b`: [ViT-B SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth)
|
97 |
+
|
98 |
+
## Dataset
|
99 |
+
See [here](https://ai.facebook.com/datasets/segment-anything/) for an overview of the datastet. The dataset can be downloaded [here](https://ai.facebook.com/datasets/segment-anything-downloads/). By downloading the datasets you agree that you have read and accepted the terms of the SA-1B Dataset Research License.
|
100 |
+
|
101 |
+
We save masks per image as a json file. It can be loaded as a dictionary in python in the below format.
|
102 |
+
|
103 |
+
|
104 |
+
```python
|
105 |
+
{
|
106 |
+
"image" : image_info,
|
107 |
+
"annotations" : [annotation],
|
108 |
+
}
|
109 |
+
|
110 |
+
image_info {
|
111 |
+
"image_id" : int, # Image id
|
112 |
+
"width" : int, # Image width
|
113 |
+
"height" : int, # Image height
|
114 |
+
"file_name" : str, # Image filename
|
115 |
+
}
|
116 |
+
|
117 |
+
annotation {
|
118 |
+
"id" : int, # Annotation id
|
119 |
+
"segmentation" : dict, # Mask saved in COCO RLE format.
|
120 |
+
"bbox" : [x, y, w, h], # The box around the mask, in XYWH format
|
121 |
+
"area" : int, # The area in pixels of the mask
|
122 |
+
"predicted_iou" : float, # The model's own prediction of the mask's quality
|
123 |
+
"stability_score" : float, # A measure of the mask's quality
|
124 |
+
"crop_box" : [x, y, w, h], # The crop of the image used to generate the mask, in XYWH format
|
125 |
+
"point_coords" : [[x, y]], # The point coordinates input to the model to generate the mask
|
126 |
+
}
|
127 |
+
```
|
128 |
+
|
129 |
+
Image ids can be found in sa_images_ids.txt which can be downloaded using the above [link](https://ai.facebook.com/datasets/segment-anything-downloads/) as well.
|
130 |
+
|
131 |
+
To decode a mask in COCO RLE format into binary:
|
132 |
+
```
|
133 |
+
from pycocotools import mask as mask_utils
|
134 |
+
mask = mask_utils.decode(annotation["segmentation"])
|
135 |
+
```
|
136 |
+
See [here](https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py) for more instructions to manipulate masks stored in RLE format.
|
137 |
+
|
138 |
+
|
139 |
+
## License
|
140 |
+
The model is licensed under the [Apache 2.0 license](LICENSE).
|
141 |
+
|
142 |
+
## Contributing
|
143 |
+
|
144 |
+
See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
|
145 |
+
|
146 |
+
## Contributors
|
147 |
+
|
148 |
+
The Segment Anything project was made possible with the help of many contributors (alphabetical):
|
149 |
+
|
150 |
+
Aaron Adcock, Vaibhav Aggarwal, Morteza Behrooz, Cheng-Yang Fu, Ashley Gabriel, Ahuva Goldstand, Allen Goodman, Sumanth Gurram, Jiabo Hu, Somya Jain, Devansh Kukreja, Robert Kuo, Joshua Lane, Yanghao Li, Lilian Luong, Jitendra Malik, Mallika Malhotra, William Ngan, Omkar Parkhi, Nikhil Raina, Dirk Rowe, Neil Sejoor, Vanessa Stark, Bala Varadarajan, Bram Wasti, Zachary Winstrom
|
151 |
+
|
152 |
+
## Citing Segment Anything
|
153 |
+
|
154 |
+
If you use SAM or SA-1B in your research, please use the following BibTeX entry.
|
155 |
+
|
156 |
+
```
|
157 |
+
@article{kirillov2023segany,
|
158 |
+
title={Segment Anything},
|
159 |
+
author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross},
|
160 |
+
journal={arXiv:2304.02643},
|
161 |
+
year={2023}
|
162 |
+
}
|
163 |
+
```
|
sam/__init__.py
ADDED
File without changes
|
sam/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (181 Bytes). View file
|
|
sam/assets/masks1.png
ADDED
Git LFS Details
|
sam/assets/masks2.jpg
ADDED
sam/assets/model_diagram.png
ADDED
sam/assets/notebook1.png
ADDED
sam/assets/notebook2.png
ADDED
Git LFS Details
|
sam/linter.sh
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash -e
|
2 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
3 |
+
|
4 |
+
{
|
5 |
+
black --version | grep -E "23\." > /dev/null
|
6 |
+
} || {
|
7 |
+
echo "Linter requires 'black==23.*' !"
|
8 |
+
exit 1
|
9 |
+
}
|
10 |
+
|
11 |
+
ISORT_VERSION=$(isort --version-number)
|
12 |
+
if [[ "$ISORT_VERSION" != 5.12* ]]; then
|
13 |
+
echo "Linter requires isort==5.12.0 !"
|
14 |
+
exit 1
|
15 |
+
fi
|
16 |
+
|
17 |
+
echo "Running isort ..."
|
18 |
+
isort . --atomic
|
19 |
+
|
20 |
+
echo "Running black ..."
|
21 |
+
black -l 100 .
|
22 |
+
|
23 |
+
echo "Running flake8 ..."
|
24 |
+
if [ -x "$(command -v flake8)" ]; then
|
25 |
+
flake8 .
|
26 |
+
else
|
27 |
+
python3 -m flake8 .
|
28 |
+
fi
|
29 |
+
|
30 |
+
echo "Running mypy..."
|
31 |
+
|
32 |
+
mypy --exclude 'setup.py|notebooks' .
|
sam/notebooks/automatic_mask_generator_example.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
sam/notebooks/images/dog.jpg
ADDED
sam/notebooks/images/groceries.jpg
ADDED
sam/notebooks/images/truck.jpg
ADDED
sam/notebooks/onnx_model_example.ipynb
ADDED
@@ -0,0 +1,774 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"id": "901c8ef3",
|
7 |
+
"metadata": {},
|
8 |
+
"outputs": [],
|
9 |
+
"source": [
|
10 |
+
"# Copyright (c) Meta Platforms, Inc. and affiliates."
|
11 |
+
]
|
12 |
+
},
|
13 |
+
{
|
14 |
+
"cell_type": "markdown",
|
15 |
+
"id": "1662bb7c",
|
16 |
+
"metadata": {},
|
17 |
+
"source": [
|
18 |
+
"# Produces masks from prompts using an ONNX model"
|
19 |
+
]
|
20 |
+
},
|
21 |
+
{
|
22 |
+
"cell_type": "markdown",
|
23 |
+
"id": "7fcc21a0",
|
24 |
+
"metadata": {},
|
25 |
+
"source": [
|
26 |
+
"SAM's prompt encoder and mask decoder are very lightweight, which allows for efficient computation of a mask given user input. This notebook shows an example of how to export and use this lightweight component of the model in ONNX format, allowing it to run on a variety of platforms that support an ONNX runtime."
|
27 |
+
]
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"cell_type": "code",
|
31 |
+
"execution_count": 4,
|
32 |
+
"id": "86daff77",
|
33 |
+
"metadata": {},
|
34 |
+
"outputs": [
|
35 |
+
{
|
36 |
+
"data": {
|
37 |
+
"text/html": [
|
38 |
+
"\n",
|
39 |
+
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb\">\n",
|
40 |
+
" <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
|
41 |
+
"</a>\n"
|
42 |
+
],
|
43 |
+
"text/plain": [
|
44 |
+
"<IPython.core.display.HTML object>"
|
45 |
+
]
|
46 |
+
},
|
47 |
+
"metadata": {},
|
48 |
+
"output_type": "display_data"
|
49 |
+
}
|
50 |
+
],
|
51 |
+
"source": [
|
52 |
+
"from IPython.display import display, HTML\n",
|
53 |
+
"display(HTML(\n",
|
54 |
+
"\"\"\"\n",
|
55 |
+
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb\">\n",
|
56 |
+
" <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
|
57 |
+
"</a>\n",
|
58 |
+
"\"\"\"\n",
|
59 |
+
"))"
|
60 |
+
]
|
61 |
+
},
|
62 |
+
{
|
63 |
+
"cell_type": "markdown",
|
64 |
+
"id": "55ae4e00",
|
65 |
+
"metadata": {},
|
66 |
+
"source": [
|
67 |
+
"## Environment Set-up"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"cell_type": "markdown",
|
72 |
+
"id": "109a5cc2",
|
73 |
+
"metadata": {},
|
74 |
+
"source": [
|
75 |
+
"If running locally using jupyter, first install `segment_anything` in your environment using the [installation instructions](https://github.com/facebookresearch/segment-anything#installation) in the repository. The latest stable versions of PyTorch and ONNX are recommended for this notebook. If running from Google Colab, set `using_collab=True` below and run the cell. In Colab, be sure to select 'GPU' under 'Edit'->'Notebook Settings'->'Hardware accelerator'."
|
76 |
+
]
|
77 |
+
},
|
78 |
+
{
|
79 |
+
"cell_type": "code",
|
80 |
+
"execution_count": 5,
|
81 |
+
"id": "39b99fc4",
|
82 |
+
"metadata": {},
|
83 |
+
"outputs": [],
|
84 |
+
"source": [
|
85 |
+
"using_colab = False"
|
86 |
+
]
|
87 |
+
},
|
88 |
+
{
|
89 |
+
"cell_type": "code",
|
90 |
+
"execution_count": 6,
|
91 |
+
"id": "296a69be",
|
92 |
+
"metadata": {},
|
93 |
+
"outputs": [],
|
94 |
+
"source": [
|
95 |
+
"if using_colab:\n",
|
96 |
+
" import torch\n",
|
97 |
+
" import torchvision\n",
|
98 |
+
" print(\"PyTorch version:\", torch.__version__)\n",
|
99 |
+
" print(\"Torchvision version:\", torchvision.__version__)\n",
|
100 |
+
" print(\"CUDA is available:\", torch.cuda.is_available())\n",
|
101 |
+
" import sys\n",
|
102 |
+
" !{sys.executable} -m pip install opencv-python matplotlib onnx onnxruntime\n",
|
103 |
+
" !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/segment-anything.git'\n",
|
104 |
+
" \n",
|
105 |
+
" !mkdir images\n",
|
106 |
+
" !wget -P images https://raw.githubusercontent.com/facebookresearch/segment-anything/main/notebooks/images/truck.jpg\n",
|
107 |
+
" \n",
|
108 |
+
" !wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
|
109 |
+
]
|
110 |
+
},
|
111 |
+
{
|
112 |
+
"cell_type": "markdown",
|
113 |
+
"id": "dc4a58be",
|
114 |
+
"metadata": {},
|
115 |
+
"source": [
|
116 |
+
"## Set-up"
|
117 |
+
]
|
118 |
+
},
|
119 |
+
{
|
120 |
+
"cell_type": "markdown",
|
121 |
+
"id": "42396e8d",
|
122 |
+
"metadata": {},
|
123 |
+
"source": [
|
124 |
+
"Note that this notebook requires both the `onnx` and `onnxruntime` optional dependencies, in addition to `opencv-python` and `matplotlib` for visualization."
|
125 |
+
]
|
126 |
+
},
|
127 |
+
{
|
128 |
+
"cell_type": "code",
|
129 |
+
"execution_count": null,
|
130 |
+
"id": "2c712610",
|
131 |
+
"metadata": {},
|
132 |
+
"outputs": [],
|
133 |
+
"source": [
|
134 |
+
"import torch\n",
|
135 |
+
"import numpy as np\n",
|
136 |
+
"import cv2\n",
|
137 |
+
"import matplotlib.pyplot as plt\n",
|
138 |
+
"from segment_anything import sam_model_registry, SamPredictor\n",
|
139 |
+
"from segment_anything.utils.onnx import SamOnnxModel\n",
|
140 |
+
"\n",
|
141 |
+
"import onnxruntime\n",
|
142 |
+
"from onnxruntime.quantization import QuantType\n",
|
143 |
+
"from onnxruntime.quantization.quantize import quantize_dynamic"
|
144 |
+
]
|
145 |
+
},
|
146 |
+
{
|
147 |
+
"cell_type": "code",
|
148 |
+
"execution_count": null,
|
149 |
+
"id": "f29441b9",
|
150 |
+
"metadata": {},
|
151 |
+
"outputs": [],
|
152 |
+
"source": [
|
153 |
+
"def show_mask(mask, ax):\n",
|
154 |
+
" color = np.array([30/255, 144/255, 255/255, 0.6])\n",
|
155 |
+
" h, w = mask.shape[-2:]\n",
|
156 |
+
" mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n",
|
157 |
+
" ax.imshow(mask_image)\n",
|
158 |
+
" \n",
|
159 |
+
"def show_points(coords, labels, ax, marker_size=375):\n",
|
160 |
+
" pos_points = coords[labels==1]\n",
|
161 |
+
" neg_points = coords[labels==0]\n",
|
162 |
+
" ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)\n",
|
163 |
+
" ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25) \n",
|
164 |
+
" \n",
|
165 |
+
"def show_box(box, ax):\n",
|
166 |
+
" x0, y0 = box[0], box[1]\n",
|
167 |
+
" w, h = box[2] - box[0], box[3] - box[1]\n",
|
168 |
+
" ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) "
|
169 |
+
]
|
170 |
+
},
|
171 |
+
{
|
172 |
+
"cell_type": "markdown",
|
173 |
+
"id": "bd0f6b2b",
|
174 |
+
"metadata": {},
|
175 |
+
"source": [
|
176 |
+
"## Export an ONNX model"
|
177 |
+
]
|
178 |
+
},
|
179 |
+
{
|
180 |
+
"cell_type": "markdown",
|
181 |
+
"id": "1540f719",
|
182 |
+
"metadata": {},
|
183 |
+
"source": [
|
184 |
+
"Set the path below to a SAM model checkpoint, then load the model. This will be needed to both export the model and to calculate embeddings for the model."
|
185 |
+
]
|
186 |
+
},
|
187 |
+
{
|
188 |
+
"cell_type": "code",
|
189 |
+
"execution_count": null,
|
190 |
+
"id": "76fc53f4",
|
191 |
+
"metadata": {},
|
192 |
+
"outputs": [],
|
193 |
+
"source": [
|
194 |
+
"checkpoint = \"sam_vit_h_4b8939.pth\"\n",
|
195 |
+
"model_type = \"vit_h\""
|
196 |
+
]
|
197 |
+
},
|
198 |
+
{
|
199 |
+
"cell_type": "code",
|
200 |
+
"execution_count": null,
|
201 |
+
"id": "11bfc8aa",
|
202 |
+
"metadata": {},
|
203 |
+
"outputs": [],
|
204 |
+
"source": [
|
205 |
+
"sam = sam_model_registry[model_type](checkpoint=checkpoint)"
|
206 |
+
]
|
207 |
+
},
|
208 |
+
{
|
209 |
+
"cell_type": "markdown",
|
210 |
+
"id": "450c089c",
|
211 |
+
"metadata": {},
|
212 |
+
"source": [
|
213 |
+
"The script `segment-anything/scripts/export_onnx_model.py` can be used to export the necessary portion of SAM. Alternatively, run the following code to export an ONNX model. If you have already exported a model, set the path below and skip to the next section. Assure that the exported ONNX model aligns with the checkpoint and model type set above. This notebook expects the model was exported with the parameter `return_single_mask=True`."
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"cell_type": "code",
|
218 |
+
"execution_count": null,
|
219 |
+
"id": "38a8add8",
|
220 |
+
"metadata": {},
|
221 |
+
"outputs": [],
|
222 |
+
"source": [
|
223 |
+
"onnx_model_path = None # Set to use an already exported model, then skip to the next section."
|
224 |
+
]
|
225 |
+
},
|
226 |
+
{
|
227 |
+
"cell_type": "code",
|
228 |
+
"execution_count": null,
|
229 |
+
"id": "7da638ba",
|
230 |
+
"metadata": {
|
231 |
+
"scrolled": false
|
232 |
+
},
|
233 |
+
"outputs": [],
|
234 |
+
"source": [
|
235 |
+
"import warnings\n",
|
236 |
+
"\n",
|
237 |
+
"onnx_model_path = \"sam_onnx_example.onnx\"\n",
|
238 |
+
"\n",
|
239 |
+
"onnx_model = SamOnnxModel(sam, return_single_mask=True)\n",
|
240 |
+
"\n",
|
241 |
+
"dynamic_axes = {\n",
|
242 |
+
" \"point_coords\": {1: \"num_points\"},\n",
|
243 |
+
" \"point_labels\": {1: \"num_points\"},\n",
|
244 |
+
"}\n",
|
245 |
+
"\n",
|
246 |
+
"embed_dim = sam.prompt_encoder.embed_dim\n",
|
247 |
+
"embed_size = sam.prompt_encoder.image_embedding_size\n",
|
248 |
+
"mask_input_size = [4 * x for x in embed_size]\n",
|
249 |
+
"dummy_inputs = {\n",
|
250 |
+
" \"image_embeddings\": torch.randn(1, embed_dim, *embed_size, dtype=torch.float),\n",
|
251 |
+
" \"point_coords\": torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),\n",
|
252 |
+
" \"point_labels\": torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),\n",
|
253 |
+
" \"mask_input\": torch.randn(1, 1, *mask_input_size, dtype=torch.float),\n",
|
254 |
+
" \"has_mask_input\": torch.tensor([1], dtype=torch.float),\n",
|
255 |
+
" \"orig_im_size\": torch.tensor([1500, 2250], dtype=torch.float),\n",
|
256 |
+
"}\n",
|
257 |
+
"output_names = [\"masks\", \"iou_predictions\", \"low_res_masks\"]\n",
|
258 |
+
"\n",
|
259 |
+
"with warnings.catch_warnings():\n",
|
260 |
+
" warnings.filterwarnings(\"ignore\", category=torch.jit.TracerWarning)\n",
|
261 |
+
" warnings.filterwarnings(\"ignore\", category=UserWarning)\n",
|
262 |
+
" with open(onnx_model_path, \"wb\") as f:\n",
|
263 |
+
" torch.onnx.export(\n",
|
264 |
+
" onnx_model,\n",
|
265 |
+
" tuple(dummy_inputs.values()),\n",
|
266 |
+
" f,\n",
|
267 |
+
" export_params=True,\n",
|
268 |
+
" verbose=False,\n",
|
269 |
+
" opset_version=17,\n",
|
270 |
+
" do_constant_folding=True,\n",
|
271 |
+
" input_names=list(dummy_inputs.keys()),\n",
|
272 |
+
" output_names=output_names,\n",
|
273 |
+
" dynamic_axes=dynamic_axes,\n",
|
274 |
+
" ) "
|
275 |
+
]
|
276 |
+
},
|
277 |
+
{
|
278 |
+
"cell_type": "markdown",
|
279 |
+
"id": "c450cf1a",
|
280 |
+
"metadata": {},
|
281 |
+
"source": [
|
282 |
+
"If desired, the model can additionally be quantized and optimized. We find this improves web runtime significantly for negligible change in qualitative performance. Run the next cell to quantize the model, or skip to the next section otherwise."
|
283 |
+
]
|
284 |
+
},
|
285 |
+
{
|
286 |
+
"cell_type": "code",
|
287 |
+
"execution_count": null,
|
288 |
+
"id": "235d39fe",
|
289 |
+
"metadata": {},
|
290 |
+
"outputs": [],
|
291 |
+
"source": [
|
292 |
+
"onnx_model_quantized_path = \"sam_onnx_quantized_example.onnx\"\n",
|
293 |
+
"quantize_dynamic(\n",
|
294 |
+
" model_input=onnx_model_path,\n",
|
295 |
+
" model_output=onnx_model_quantized_path,\n",
|
296 |
+
" optimize_model=True,\n",
|
297 |
+
" per_channel=False,\n",
|
298 |
+
" reduce_range=False,\n",
|
299 |
+
" weight_type=QuantType.QUInt8,\n",
|
300 |
+
")\n",
|
301 |
+
"onnx_model_path = onnx_model_quantized_path"
|
302 |
+
]
|
303 |
+
},
|
304 |
+
{
|
305 |
+
"cell_type": "markdown",
|
306 |
+
"id": "927a928b",
|
307 |
+
"metadata": {},
|
308 |
+
"source": [
|
309 |
+
"## Example Image"
|
310 |
+
]
|
311 |
+
},
|
312 |
+
{
|
313 |
+
"cell_type": "code",
|
314 |
+
"execution_count": null,
|
315 |
+
"id": "6be6eb55",
|
316 |
+
"metadata": {},
|
317 |
+
"outputs": [],
|
318 |
+
"source": [
|
319 |
+
"image = cv2.imread('images/truck.jpg')\n",
|
320 |
+
"image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)"
|
321 |
+
]
|
322 |
+
},
|
323 |
+
{
|
324 |
+
"cell_type": "code",
|
325 |
+
"execution_count": null,
|
326 |
+
"id": "b7e9a27a",
|
327 |
+
"metadata": {},
|
328 |
+
"outputs": [],
|
329 |
+
"source": [
|
330 |
+
"plt.figure(figsize=(10,10))\n",
|
331 |
+
"plt.imshow(image)\n",
|
332 |
+
"plt.axis('on')\n",
|
333 |
+
"plt.show()"
|
334 |
+
]
|
335 |
+
},
|
336 |
+
{
|
337 |
+
"cell_type": "markdown",
|
338 |
+
"id": "027b177b",
|
339 |
+
"metadata": {},
|
340 |
+
"source": [
|
341 |
+
"## Using an ONNX model"
|
342 |
+
]
|
343 |
+
},
|
344 |
+
{
|
345 |
+
"cell_type": "markdown",
|
346 |
+
"id": "778d4593",
|
347 |
+
"metadata": {},
|
348 |
+
"source": [
|
349 |
+
"Here as an example, we use `onnxruntime` in python on CPU to execute the ONNX model. However, any platform that supports an ONNX runtime could be used in principle. Launch the runtime session below:"
|
350 |
+
]
|
351 |
+
},
|
352 |
+
{
|
353 |
+
"cell_type": "code",
|
354 |
+
"execution_count": null,
|
355 |
+
"id": "9689b1bf",
|
356 |
+
"metadata": {},
|
357 |
+
"outputs": [],
|
358 |
+
"source": [
|
359 |
+
"ort_session = onnxruntime.InferenceSession(onnx_model_path)"
|
360 |
+
]
|
361 |
+
},
|
362 |
+
{
|
363 |
+
"cell_type": "markdown",
|
364 |
+
"id": "7708ead6",
|
365 |
+
"metadata": {},
|
366 |
+
"source": [
|
367 |
+
"To use the ONNX model, the image must first be pre-processed using the SAM image encoder. This is a heavier weight process best performed on GPU. SamPredictor can be used as normal, then `.get_image_embedding()` will retreive the intermediate features."
|
368 |
+
]
|
369 |
+
},
|
370 |
+
{
|
371 |
+
"cell_type": "code",
|
372 |
+
"execution_count": null,
|
373 |
+
"id": "26e067b4",
|
374 |
+
"metadata": {},
|
375 |
+
"outputs": [],
|
376 |
+
"source": [
|
377 |
+
"sam.to(device='cuda')\n",
|
378 |
+
"predictor = SamPredictor(sam)"
|
379 |
+
]
|
380 |
+
},
|
381 |
+
{
|
382 |
+
"cell_type": "code",
|
383 |
+
"execution_count": null,
|
384 |
+
"id": "7ad3f0d6",
|
385 |
+
"metadata": {},
|
386 |
+
"outputs": [],
|
387 |
+
"source": [
|
388 |
+
"predictor.set_image(image)"
|
389 |
+
]
|
390 |
+
},
|
391 |
+
{
|
392 |
+
"cell_type": "code",
|
393 |
+
"execution_count": null,
|
394 |
+
"id": "8a6f0f07",
|
395 |
+
"metadata": {},
|
396 |
+
"outputs": [],
|
397 |
+
"source": [
|
398 |
+
"image_embedding = predictor.get_image_embedding().cpu().numpy()"
|
399 |
+
]
|
400 |
+
},
|
401 |
+
{
|
402 |
+
"cell_type": "code",
|
403 |
+
"execution_count": null,
|
404 |
+
"id": "5e112f33",
|
405 |
+
"metadata": {},
|
406 |
+
"outputs": [],
|
407 |
+
"source": [
|
408 |
+
"image_embedding.shape"
|
409 |
+
]
|
410 |
+
},
|
411 |
+
{
|
412 |
+
"cell_type": "markdown",
|
413 |
+
"id": "6337b654",
|
414 |
+
"metadata": {},
|
415 |
+
"source": [
|
416 |
+
"The ONNX model has a different input signature than `SamPredictor.predict`. The following inputs must all be supplied. Note the special cases for both point and mask inputs. All inputs are `np.float32`.\n",
|
417 |
+
"* `image_embeddings`: The image embedding from `predictor.get_image_embedding()`. Has a batch index of length 1.\n",
|
418 |
+
"* `point_coords`: Coordinates of sparse input prompts, corresponding to both point inputs and box inputs. Boxes are encoded using two points, one for the top-left corner and one for the bottom-right corner. *Coordinates must already be transformed to long-side 1024.* Has a batch index of length 1.\n",
|
419 |
+
"* `point_labels`: Labels for the sparse input prompts. 0 is a negative input point, 1 is a positive input point, 2 is a top-left box corner, 3 is a bottom-right box corner, and -1 is a padding point. *If there is no box input, a single padding point with label -1 and coordinates (0.0, 0.0) should be concatenated.*\n",
|
420 |
+
"* `mask_input`: A mask input to the model with shape 1x1x256x256. This must be supplied even if there is no mask input. In this case, it can just be zeros.\n",
|
421 |
+
"* `has_mask_input`: An indicator for the mask input. 1 indicates a mask input, 0 indicates no mask input.\n",
|
422 |
+
"* `orig_im_size`: The size of the input image in (H,W) format, before any transformation. \n",
|
423 |
+
"\n",
|
424 |
+
"Additionally, the ONNX model does not threshold the output mask logits. To obtain a binary mask, threshold at `sam.mask_threshold` (equal to 0.0)."
|
425 |
+
]
|
426 |
+
},
|
427 |
+
{
|
428 |
+
"cell_type": "markdown",
|
429 |
+
"id": "bf5a9f55",
|
430 |
+
"metadata": {},
|
431 |
+
"source": [
|
432 |
+
"### Example point input"
|
433 |
+
]
|
434 |
+
},
|
435 |
+
{
|
436 |
+
"cell_type": "code",
|
437 |
+
"execution_count": null,
|
438 |
+
"id": "1c0deef0",
|
439 |
+
"metadata": {},
|
440 |
+
"outputs": [],
|
441 |
+
"source": [
|
442 |
+
"input_point = np.array([[500, 375]])\n",
|
443 |
+
"input_label = np.array([1])"
|
444 |
+
]
|
445 |
+
},
|
446 |
+
{
|
447 |
+
"cell_type": "markdown",
|
448 |
+
"id": "7256394c",
|
449 |
+
"metadata": {},
|
450 |
+
"source": [
|
451 |
+
"Add a batch index, concatenate a padding point, and transform."
|
452 |
+
]
|
453 |
+
},
|
454 |
+
{
|
455 |
+
"cell_type": "code",
|
456 |
+
"execution_count": null,
|
457 |
+
"id": "4f69903e",
|
458 |
+
"metadata": {},
|
459 |
+
"outputs": [],
|
460 |
+
"source": [
|
461 |
+
"onnx_coord = np.concatenate([input_point, np.array([[0.0, 0.0]])], axis=0)[None, :, :]\n",
|
462 |
+
"onnx_label = np.concatenate([input_label, np.array([-1])], axis=0)[None, :].astype(np.float32)\n",
|
463 |
+
"\n",
|
464 |
+
"onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)\n"
|
465 |
+
]
|
466 |
+
},
|
467 |
+
{
|
468 |
+
"cell_type": "markdown",
|
469 |
+
"id": "b188dc53",
|
470 |
+
"metadata": {},
|
471 |
+
"source": [
|
472 |
+
"Create an empty mask input and an indicator for no mask."
|
473 |
+
]
|
474 |
+
},
|
475 |
+
{
|
476 |
+
"cell_type": "code",
|
477 |
+
"execution_count": null,
|
478 |
+
"id": "5cb52bcf",
|
479 |
+
"metadata": {},
|
480 |
+
"outputs": [],
|
481 |
+
"source": [
|
482 |
+
"onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32)\n",
|
483 |
+
"onnx_has_mask_input = np.zeros(1, dtype=np.float32)"
|
484 |
+
]
|
485 |
+
},
|
486 |
+
{
|
487 |
+
"cell_type": "markdown",
|
488 |
+
"id": "a99c2cc5",
|
489 |
+
"metadata": {},
|
490 |
+
"source": [
|
491 |
+
"Package the inputs to run in the onnx model"
|
492 |
+
]
|
493 |
+
},
|
494 |
+
{
|
495 |
+
"cell_type": "code",
|
496 |
+
"execution_count": null,
|
497 |
+
"id": "b1d7ea11",
|
498 |
+
"metadata": {},
|
499 |
+
"outputs": [],
|
500 |
+
"source": [
|
501 |
+
"ort_inputs = {\n",
|
502 |
+
" \"image_embeddings\": image_embedding,\n",
|
503 |
+
" \"point_coords\": onnx_coord,\n",
|
504 |
+
" \"point_labels\": onnx_label,\n",
|
505 |
+
" \"mask_input\": onnx_mask_input,\n",
|
506 |
+
" \"has_mask_input\": onnx_has_mask_input,\n",
|
507 |
+
" \"orig_im_size\": np.array(image.shape[:2], dtype=np.float32)\n",
|
508 |
+
"}"
|
509 |
+
]
|
510 |
+
},
|
511 |
+
{
|
512 |
+
"cell_type": "markdown",
|
513 |
+
"id": "4b6409c9",
|
514 |
+
"metadata": {},
|
515 |
+
"source": [
|
516 |
+
"Predict a mask and threshold it."
|
517 |
+
]
|
518 |
+
},
|
519 |
+
{
|
520 |
+
"cell_type": "code",
|
521 |
+
"execution_count": null,
|
522 |
+
"id": "dc4cc082",
|
523 |
+
"metadata": {
|
524 |
+
"scrolled": false
|
525 |
+
},
|
526 |
+
"outputs": [],
|
527 |
+
"source": [
|
528 |
+
"masks, _, low_res_logits = ort_session.run(None, ort_inputs)\n",
|
529 |
+
"masks = masks > predictor.model.mask_threshold"
|
530 |
+
]
|
531 |
+
},
|
532 |
+
{
|
533 |
+
"cell_type": "code",
|
534 |
+
"execution_count": null,
|
535 |
+
"id": "d778a8fb",
|
536 |
+
"metadata": {},
|
537 |
+
"outputs": [],
|
538 |
+
"source": [
|
539 |
+
"masks.shape"
|
540 |
+
]
|
541 |
+
},
|
542 |
+
{
|
543 |
+
"cell_type": "code",
|
544 |
+
"execution_count": null,
|
545 |
+
"id": "badb1175",
|
546 |
+
"metadata": {},
|
547 |
+
"outputs": [],
|
548 |
+
"source": [
|
549 |
+
"plt.figure(figsize=(10,10))\n",
|
550 |
+
"plt.imshow(image)\n",
|
551 |
+
"show_mask(masks, plt.gca())\n",
|
552 |
+
"show_points(input_point, input_label, plt.gca())\n",
|
553 |
+
"plt.axis('off')\n",
|
554 |
+
"plt.show() "
|
555 |
+
]
|
556 |
+
},
|
557 |
+
{
|
558 |
+
"cell_type": "markdown",
|
559 |
+
"id": "1f1d4d15",
|
560 |
+
"metadata": {},
|
561 |
+
"source": [
|
562 |
+
"### Example mask input"
|
563 |
+
]
|
564 |
+
},
|
565 |
+
{
|
566 |
+
"cell_type": "code",
|
567 |
+
"execution_count": null,
|
568 |
+
"id": "b319da82",
|
569 |
+
"metadata": {},
|
570 |
+
"outputs": [],
|
571 |
+
"source": [
|
572 |
+
"input_point = np.array([[500, 375], [1125, 625]])\n",
|
573 |
+
"input_label = np.array([1, 1])\n",
|
574 |
+
"\n",
|
575 |
+
"# Use the mask output from the previous run. It is already in the correct form for input to the ONNX model.\n",
|
576 |
+
"onnx_mask_input = low_res_logits"
|
577 |
+
]
|
578 |
+
},
|
579 |
+
{
|
580 |
+
"cell_type": "markdown",
|
581 |
+
"id": "b1823b37",
|
582 |
+
"metadata": {},
|
583 |
+
"source": [
|
584 |
+
"Transform the points as in the previous example."
|
585 |
+
]
|
586 |
+
},
|
587 |
+
{
|
588 |
+
"cell_type": "code",
|
589 |
+
"execution_count": null,
|
590 |
+
"id": "8885130f",
|
591 |
+
"metadata": {},
|
592 |
+
"outputs": [],
|
593 |
+
"source": [
|
594 |
+
"onnx_coord = np.concatenate([input_point, np.array([[0.0, 0.0]])], axis=0)[None, :, :]\n",
|
595 |
+
"onnx_label = np.concatenate([input_label, np.array([-1])], axis=0)[None, :].astype(np.float32)\n",
|
596 |
+
"\n",
|
597 |
+
"onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)"
|
598 |
+
]
|
599 |
+
},
|
600 |
+
{
|
601 |
+
"cell_type": "markdown",
|
602 |
+
"id": "28e47b69",
|
603 |
+
"metadata": {},
|
604 |
+
"source": [
|
605 |
+
"The `has_mask_input` indicator is now 1."
|
606 |
+
]
|
607 |
+
},
|
608 |
+
{
|
609 |
+
"cell_type": "code",
|
610 |
+
"execution_count": null,
|
611 |
+
"id": "3ab4483a",
|
612 |
+
"metadata": {},
|
613 |
+
"outputs": [],
|
614 |
+
"source": [
|
615 |
+
"onnx_has_mask_input = np.ones(1, dtype=np.float32)"
|
616 |
+
]
|
617 |
+
},
|
618 |
+
{
|
619 |
+
"cell_type": "markdown",
|
620 |
+
"id": "d3781955",
|
621 |
+
"metadata": {},
|
622 |
+
"source": [
|
623 |
+
"Package inputs, then predict and threshold the mask."
|
624 |
+
]
|
625 |
+
},
|
626 |
+
{
|
627 |
+
"cell_type": "code",
|
628 |
+
"execution_count": null,
|
629 |
+
"id": "0c1ec096",
|
630 |
+
"metadata": {},
|
631 |
+
"outputs": [],
|
632 |
+
"source": [
|
633 |
+
"ort_inputs = {\n",
|
634 |
+
" \"image_embeddings\": image_embedding,\n",
|
635 |
+
" \"point_coords\": onnx_coord,\n",
|
636 |
+
" \"point_labels\": onnx_label,\n",
|
637 |
+
" \"mask_input\": onnx_mask_input,\n",
|
638 |
+
" \"has_mask_input\": onnx_has_mask_input,\n",
|
639 |
+
" \"orig_im_size\": np.array(image.shape[:2], dtype=np.float32)\n",
|
640 |
+
"}\n",
|
641 |
+
"\n",
|
642 |
+
"masks, _, _ = ort_session.run(None, ort_inputs)\n",
|
643 |
+
"masks = masks > predictor.model.mask_threshold"
|
644 |
+
]
|
645 |
+
},
|
646 |
+
{
|
647 |
+
"cell_type": "code",
|
648 |
+
"execution_count": null,
|
649 |
+
"id": "1e36554b",
|
650 |
+
"metadata": {},
|
651 |
+
"outputs": [],
|
652 |
+
"source": [
|
653 |
+
"plt.figure(figsize=(10,10))\n",
|
654 |
+
"plt.imshow(image)\n",
|
655 |
+
"show_mask(masks, plt.gca())\n",
|
656 |
+
"show_points(input_point, input_label, plt.gca())\n",
|
657 |
+
"plt.axis('off')\n",
|
658 |
+
"plt.show() "
|
659 |
+
]
|
660 |
+
},
|
661 |
+
{
|
662 |
+
"cell_type": "markdown",
|
663 |
+
"id": "2ef211d0",
|
664 |
+
"metadata": {},
|
665 |
+
"source": [
|
666 |
+
"### Example box and point input"
|
667 |
+
]
|
668 |
+
},
|
669 |
+
{
|
670 |
+
"cell_type": "code",
|
671 |
+
"execution_count": null,
|
672 |
+
"id": "51e58d2e",
|
673 |
+
"metadata": {},
|
674 |
+
"outputs": [],
|
675 |
+
"source": [
|
676 |
+
"input_box = np.array([425, 600, 700, 875])\n",
|
677 |
+
"input_point = np.array([[575, 750]])\n",
|
678 |
+
"input_label = np.array([0])"
|
679 |
+
]
|
680 |
+
},
|
681 |
+
{
|
682 |
+
"cell_type": "markdown",
|
683 |
+
"id": "6e119dcb",
|
684 |
+
"metadata": {},
|
685 |
+
"source": [
|
686 |
+
"Add a batch index, concatenate a box and point inputs, add the appropriate labels for the box corners, and transform. There is no padding point since the input includes a box input."
|
687 |
+
]
|
688 |
+
},
|
689 |
+
{
|
690 |
+
"cell_type": "code",
|
691 |
+
"execution_count": null,
|
692 |
+
"id": "bfbe4911",
|
693 |
+
"metadata": {},
|
694 |
+
"outputs": [],
|
695 |
+
"source": [
|
696 |
+
"onnx_box_coords = input_box.reshape(2, 2)\n",
|
697 |
+
"onnx_box_labels = np.array([2,3])\n",
|
698 |
+
"\n",
|
699 |
+
"onnx_coord = np.concatenate([input_point, onnx_box_coords], axis=0)[None, :, :]\n",
|
700 |
+
"onnx_label = np.concatenate([input_label, onnx_box_labels], axis=0)[None, :].astype(np.float32)\n",
|
701 |
+
"\n",
|
702 |
+
"onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)"
|
703 |
+
]
|
704 |
+
},
|
705 |
+
{
|
706 |
+
"cell_type": "markdown",
|
707 |
+
"id": "65edabd2",
|
708 |
+
"metadata": {},
|
709 |
+
"source": [
|
710 |
+
"Package inputs, then predict and threshold the mask."
|
711 |
+
]
|
712 |
+
},
|
713 |
+
{
|
714 |
+
"cell_type": "code",
|
715 |
+
"execution_count": null,
|
716 |
+
"id": "2abfba56",
|
717 |
+
"metadata": {},
|
718 |
+
"outputs": [],
|
719 |
+
"source": [
|
720 |
+
"onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32)\n",
|
721 |
+
"onnx_has_mask_input = np.zeros(1, dtype=np.float32)\n",
|
722 |
+
"\n",
|
723 |
+
"ort_inputs = {\n",
|
724 |
+
" \"image_embeddings\": image_embedding,\n",
|
725 |
+
" \"point_coords\": onnx_coord,\n",
|
726 |
+
" \"point_labels\": onnx_label,\n",
|
727 |
+
" \"mask_input\": onnx_mask_input,\n",
|
728 |
+
" \"has_mask_input\": onnx_has_mask_input,\n",
|
729 |
+
" \"orig_im_size\": np.array(image.shape[:2], dtype=np.float32)\n",
|
730 |
+
"}\n",
|
731 |
+
"\n",
|
732 |
+
"masks, _, _ = ort_session.run(None, ort_inputs)\n",
|
733 |
+
"masks = masks > predictor.model.mask_threshold"
|
734 |
+
]
|
735 |
+
},
|
736 |
+
{
|
737 |
+
"cell_type": "code",
|
738 |
+
"execution_count": null,
|
739 |
+
"id": "8301bf33",
|
740 |
+
"metadata": {},
|
741 |
+
"outputs": [],
|
742 |
+
"source": [
|
743 |
+
"plt.figure(figsize=(10, 10))\n",
|
744 |
+
"plt.imshow(image)\n",
|
745 |
+
"show_mask(masks[0], plt.gca())\n",
|
746 |
+
"show_box(input_box, plt.gca())\n",
|
747 |
+
"show_points(input_point, input_label, plt.gca())\n",
|
748 |
+
"plt.axis('off')\n",
|
749 |
+
"plt.show()"
|
750 |
+
]
|
751 |
+
}
|
752 |
+
],
|
753 |
+
"metadata": {
|
754 |
+
"kernelspec": {
|
755 |
+
"display_name": "Python 3 (ipykernel)",
|
756 |
+
"language": "python",
|
757 |
+
"name": "python3"
|
758 |
+
},
|
759 |
+
"language_info": {
|
760 |
+
"codemirror_mode": {
|
761 |
+
"name": "ipython",
|
762 |
+
"version": 3
|
763 |
+
},
|
764 |
+
"file_extension": ".py",
|
765 |
+
"mimetype": "text/x-python",
|
766 |
+
"name": "python",
|
767 |
+
"nbconvert_exporter": "python",
|
768 |
+
"pygments_lexer": "ipython3",
|
769 |
+
"version": "3.8.0"
|
770 |
+
}
|
771 |
+
},
|
772 |
+
"nbformat": 4,
|
773 |
+
"nbformat_minor": 5
|
774 |
+
}
|
sam/notebooks/predictor_example.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
sam/scripts/amg.py
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
import cv2 # type: ignore
|
8 |
+
|
9 |
+
from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
|
10 |
+
|
11 |
+
import argparse
|
12 |
+
import json
|
13 |
+
import os
|
14 |
+
from typing import Any, Dict, List
|
15 |
+
|
16 |
+
parser = argparse.ArgumentParser(
|
17 |
+
description=(
|
18 |
+
"Runs automatic mask generation on an input image or directory of images, "
|
19 |
+
"and outputs masks as either PNGs or COCO-style RLEs. Requires open-cv, "
|
20 |
+
"as well as pycocotools if saving in RLE format."
|
21 |
+
)
|
22 |
+
)
|
23 |
+
|
24 |
+
parser.add_argument(
|
25 |
+
"--input",
|
26 |
+
type=str,
|
27 |
+
required=True,
|
28 |
+
help="Path to either a single input image or folder of images.",
|
29 |
+
)
|
30 |
+
|
31 |
+
parser.add_argument(
|
32 |
+
"--output",
|
33 |
+
type=str,
|
34 |
+
required=True,
|
35 |
+
help=(
|
36 |
+
"Path to the directory where masks will be output. Output will be either a folder "
|
37 |
+
"of PNGs per image or a single json with COCO-style masks."
|
38 |
+
),
|
39 |
+
)
|
40 |
+
|
41 |
+
parser.add_argument(
|
42 |
+
"--model-type",
|
43 |
+
type=str,
|
44 |
+
required=True,
|
45 |
+
help="The type of model to load, in ['default', 'vit_h', 'vit_l', 'vit_b']",
|
46 |
+
)
|
47 |
+
|
48 |
+
parser.add_argument(
|
49 |
+
"--checkpoint",
|
50 |
+
type=str,
|
51 |
+
required=True,
|
52 |
+
help="The path to the SAM checkpoint to use for mask generation.",
|
53 |
+
)
|
54 |
+
|
55 |
+
parser.add_argument("--device", type=str, default="cuda", help="The device to run generation on.")
|
56 |
+
|
57 |
+
parser.add_argument(
|
58 |
+
"--convert-to-rle",
|
59 |
+
action="store_true",
|
60 |
+
help=(
|
61 |
+
"Save masks as COCO RLEs in a single json instead of as a folder of PNGs. "
|
62 |
+
"Requires pycocotools."
|
63 |
+
),
|
64 |
+
)
|
65 |
+
|
66 |
+
amg_settings = parser.add_argument_group("AMG Settings")
|
67 |
+
|
68 |
+
amg_settings.add_argument(
|
69 |
+
"--points-per-side",
|
70 |
+
type=int,
|
71 |
+
default=None,
|
72 |
+
help="Generate masks by sampling a grid over the image with this many points to a side.",
|
73 |
+
)
|
74 |
+
|
75 |
+
amg_settings.add_argument(
|
76 |
+
"--points-per-batch",
|
77 |
+
type=int,
|
78 |
+
default=None,
|
79 |
+
help="How many input points to process simultaneously in one batch.",
|
80 |
+
)
|
81 |
+
|
82 |
+
amg_settings.add_argument(
|
83 |
+
"--pred-iou-thresh",
|
84 |
+
type=float,
|
85 |
+
default=None,
|
86 |
+
help="Exclude masks with a predicted score from the model that is lower than this threshold.",
|
87 |
+
)
|
88 |
+
|
89 |
+
amg_settings.add_argument(
|
90 |
+
"--stability-score-thresh",
|
91 |
+
type=float,
|
92 |
+
default=None,
|
93 |
+
help="Exclude masks with a stability score lower than this threshold.",
|
94 |
+
)
|
95 |
+
|
96 |
+
amg_settings.add_argument(
|
97 |
+
"--stability-score-offset",
|
98 |
+
type=float,
|
99 |
+
default=None,
|
100 |
+
help="Larger values perturb the mask more when measuring stability score.",
|
101 |
+
)
|
102 |
+
|
103 |
+
amg_settings.add_argument(
|
104 |
+
"--box-nms-thresh",
|
105 |
+
type=float,
|
106 |
+
default=None,
|
107 |
+
help="The overlap threshold for excluding a duplicate mask.",
|
108 |
+
)
|
109 |
+
|
110 |
+
amg_settings.add_argument(
|
111 |
+
"--crop-n-layers",
|
112 |
+
type=int,
|
113 |
+
default=None,
|
114 |
+
help=(
|
115 |
+
"If >0, mask generation is run on smaller crops of the image to generate more masks. "
|
116 |
+
"The value sets how many different scales to crop at."
|
117 |
+
),
|
118 |
+
)
|
119 |
+
|
120 |
+
amg_settings.add_argument(
|
121 |
+
"--crop-nms-thresh",
|
122 |
+
type=float,
|
123 |
+
default=None,
|
124 |
+
help="The overlap threshold for excluding duplicate masks across different crops.",
|
125 |
+
)
|
126 |
+
|
127 |
+
amg_settings.add_argument(
|
128 |
+
"--crop-overlap-ratio",
|
129 |
+
type=int,
|
130 |
+
default=None,
|
131 |
+
help="Larger numbers mean image crops will overlap more.",
|
132 |
+
)
|
133 |
+
|
134 |
+
amg_settings.add_argument(
|
135 |
+
"--crop-n-points-downscale-factor",
|
136 |
+
type=int,
|
137 |
+
default=None,
|
138 |
+
help="The number of points-per-side in each layer of crop is reduced by this factor.",
|
139 |
+
)
|
140 |
+
|
141 |
+
amg_settings.add_argument(
|
142 |
+
"--min-mask-region-area",
|
143 |
+
type=int,
|
144 |
+
default=None,
|
145 |
+
help=(
|
146 |
+
"Disconnected mask regions or holes with area smaller than this value "
|
147 |
+
"in pixels are removed by postprocessing."
|
148 |
+
),
|
149 |
+
)
|
150 |
+
|
151 |
+
|
152 |
+
def write_masks_to_folder(masks: List[Dict[str, Any]], path: str) -> None:
|
153 |
+
header = "id,area,bbox_x0,bbox_y0,bbox_w,bbox_h,point_input_x,point_input_y,predicted_iou,stability_score,crop_box_x0,crop_box_y0,crop_box_w,crop_box_h" # noqa
|
154 |
+
metadata = [header]
|
155 |
+
for i, mask_data in enumerate(masks):
|
156 |
+
mask = mask_data["segmentation"]
|
157 |
+
filename = f"{i}.png"
|
158 |
+
cv2.imwrite(os.path.join(path, filename), mask * 255)
|
159 |
+
mask_metadata = [
|
160 |
+
str(i),
|
161 |
+
str(mask_data["area"]),
|
162 |
+
*[str(x) for x in mask_data["bbox"]],
|
163 |
+
*[str(x) for x in mask_data["point_coords"][0]],
|
164 |
+
str(mask_data["predicted_iou"]),
|
165 |
+
str(mask_data["stability_score"]),
|
166 |
+
*[str(x) for x in mask_data["crop_box"]],
|
167 |
+
]
|
168 |
+
row = ",".join(mask_metadata)
|
169 |
+
metadata.append(row)
|
170 |
+
metadata_path = os.path.join(path, "metadata.csv")
|
171 |
+
with open(metadata_path, "w") as f:
|
172 |
+
f.write("\n".join(metadata))
|
173 |
+
|
174 |
+
return
|
175 |
+
|
176 |
+
|
177 |
+
def get_amg_kwargs(args):
|
178 |
+
amg_kwargs = {
|
179 |
+
"points_per_side": args.points_per_side,
|
180 |
+
"points_per_batch": args.points_per_batch,
|
181 |
+
"pred_iou_thresh": args.pred_iou_thresh,
|
182 |
+
"stability_score_thresh": args.stability_score_thresh,
|
183 |
+
"stability_score_offset": args.stability_score_offset,
|
184 |
+
"box_nms_thresh": args.box_nms_thresh,
|
185 |
+
"crop_n_layers": args.crop_n_layers,
|
186 |
+
"crop_nms_thresh": args.crop_nms_thresh,
|
187 |
+
"crop_overlap_ratio": args.crop_overlap_ratio,
|
188 |
+
"crop_n_points_downscale_factor": args.crop_n_points_downscale_factor,
|
189 |
+
"min_mask_region_area": args.min_mask_region_area,
|
190 |
+
}
|
191 |
+
amg_kwargs = {k: v for k, v in amg_kwargs.items() if v is not None}
|
192 |
+
return amg_kwargs
|
193 |
+
|
194 |
+
|
195 |
+
def main(args: argparse.Namespace) -> None:
|
196 |
+
print("Loading model...")
|
197 |
+
sam = sam_model_registry[args.model_type](checkpoint=args.checkpoint)
|
198 |
+
_ = sam.to(device=args.device)
|
199 |
+
output_mode = "coco_rle" if args.convert_to_rle else "binary_mask"
|
200 |
+
amg_kwargs = get_amg_kwargs(args)
|
201 |
+
generator = SamAutomaticMaskGenerator(sam, output_mode=output_mode, **amg_kwargs)
|
202 |
+
|
203 |
+
if not os.path.isdir(args.input):
|
204 |
+
targets = [args.input]
|
205 |
+
else:
|
206 |
+
targets = [
|
207 |
+
f for f in os.listdir(args.input) if not os.path.isdir(os.path.join(args.input, f))
|
208 |
+
]
|
209 |
+
targets = [os.path.join(args.input, f) for f in targets]
|
210 |
+
|
211 |
+
os.makedirs(args.output, exist_ok=True)
|
212 |
+
|
213 |
+
for t in targets:
|
214 |
+
print(f"Processing '{t}'...")
|
215 |
+
image = cv2.imread(t)
|
216 |
+
if image is None:
|
217 |
+
print(f"Could not load '{t}' as an image, skipping...")
|
218 |
+
continue
|
219 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
220 |
+
|
221 |
+
masks = generator.generate(image)
|
222 |
+
|
223 |
+
base = os.path.basename(t)
|
224 |
+
base = os.path.splitext(base)[0]
|
225 |
+
save_base = os.path.join(args.output, base)
|
226 |
+
if output_mode == "binary_mask":
|
227 |
+
os.makedirs(save_base, exist_ok=False)
|
228 |
+
write_masks_to_folder(masks, save_base)
|
229 |
+
else:
|
230 |
+
save_file = save_base + ".json"
|
231 |
+
with open(save_file, "w") as f:
|
232 |
+
json.dump(masks, f)
|
233 |
+
print("Done!")
|
234 |
+
|
235 |
+
|
236 |
+
if __name__ == "__main__":
|
237 |
+
args = parser.parse_args()
|
238 |
+
main(args)
|
sam/scripts/export_onnx_model.py
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
import torch
|
8 |
+
|
9 |
+
from segment_anything import sam_model_registry
|
10 |
+
from segment_anything.utils.onnx import SamOnnxModel
|
11 |
+
|
12 |
+
import argparse
|
13 |
+
import warnings
|
14 |
+
|
15 |
+
try:
|
16 |
+
import onnxruntime # type: ignore
|
17 |
+
|
18 |
+
onnxruntime_exists = True
|
19 |
+
except ImportError:
|
20 |
+
onnxruntime_exists = False
|
21 |
+
|
22 |
+
parser = argparse.ArgumentParser(
|
23 |
+
description="Export the SAM prompt encoder and mask decoder to an ONNX model."
|
24 |
+
)
|
25 |
+
|
26 |
+
parser.add_argument(
|
27 |
+
"--checkpoint", type=str, required=True, help="The path to the SAM model checkpoint."
|
28 |
+
)
|
29 |
+
|
30 |
+
parser.add_argument(
|
31 |
+
"--output", type=str, required=True, help="The filename to save the ONNX model to."
|
32 |
+
)
|
33 |
+
|
34 |
+
parser.add_argument(
|
35 |
+
"--model-type",
|
36 |
+
type=str,
|
37 |
+
required=True,
|
38 |
+
help="In ['default', 'vit_h', 'vit_l', 'vit_b']. Which type of SAM model to export.",
|
39 |
+
)
|
40 |
+
|
41 |
+
parser.add_argument(
|
42 |
+
"--return-single-mask",
|
43 |
+
action="store_true",
|
44 |
+
help=(
|
45 |
+
"If true, the exported ONNX model will only return the best mask, "
|
46 |
+
"instead of returning multiple masks. For high resolution images "
|
47 |
+
"this can improve runtime when upscaling masks is expensive."
|
48 |
+
),
|
49 |
+
)
|
50 |
+
|
51 |
+
parser.add_argument(
|
52 |
+
"--opset",
|
53 |
+
type=int,
|
54 |
+
default=17,
|
55 |
+
help="The ONNX opset version to use. Must be >=11",
|
56 |
+
)
|
57 |
+
|
58 |
+
parser.add_argument(
|
59 |
+
"--quantize-out",
|
60 |
+
type=str,
|
61 |
+
default=None,
|
62 |
+
help=(
|
63 |
+
"If set, will quantize the model and save it with this name. "
|
64 |
+
"Quantization is performed with quantize_dynamic from onnxruntime.quantization.quantize."
|
65 |
+
),
|
66 |
+
)
|
67 |
+
|
68 |
+
parser.add_argument(
|
69 |
+
"--gelu-approximate",
|
70 |
+
action="store_true",
|
71 |
+
help=(
|
72 |
+
"Replace GELU operations with approximations using tanh. Useful "
|
73 |
+
"for some runtimes that have slow or unimplemented erf ops, used in GELU."
|
74 |
+
),
|
75 |
+
)
|
76 |
+
|
77 |
+
parser.add_argument(
|
78 |
+
"--use-stability-score",
|
79 |
+
action="store_true",
|
80 |
+
help=(
|
81 |
+
"Replaces the model's predicted mask quality score with the stability "
|
82 |
+
"score calculated on the low resolution masks using an offset of 1.0. "
|
83 |
+
),
|
84 |
+
)
|
85 |
+
|
86 |
+
parser.add_argument(
|
87 |
+
"--return-extra-metrics",
|
88 |
+
action="store_true",
|
89 |
+
help=(
|
90 |
+
"The model will return five results: (masks, scores, stability_scores, "
|
91 |
+
"areas, low_res_logits) instead of the usual three. This can be "
|
92 |
+
"significantly slower for high resolution outputs."
|
93 |
+
),
|
94 |
+
)
|
95 |
+
|
96 |
+
|
97 |
+
def run_export(
|
98 |
+
model_type: str,
|
99 |
+
checkpoint: str,
|
100 |
+
output: str,
|
101 |
+
opset: int,
|
102 |
+
return_single_mask: bool,
|
103 |
+
gelu_approximate: bool = False,
|
104 |
+
use_stability_score: bool = False,
|
105 |
+
return_extra_metrics=False,
|
106 |
+
):
|
107 |
+
print("Loading model...")
|
108 |
+
sam = sam_model_registry[model_type](checkpoint=checkpoint)
|
109 |
+
|
110 |
+
onnx_model = SamOnnxModel(
|
111 |
+
model=sam,
|
112 |
+
return_single_mask=return_single_mask,
|
113 |
+
use_stability_score=use_stability_score,
|
114 |
+
return_extra_metrics=return_extra_metrics,
|
115 |
+
)
|
116 |
+
|
117 |
+
if gelu_approximate:
|
118 |
+
for n, m in onnx_model.named_modules():
|
119 |
+
if isinstance(m, torch.nn.GELU):
|
120 |
+
m.approximate = "tanh"
|
121 |
+
|
122 |
+
dynamic_axes = {
|
123 |
+
"point_coords": {1: "num_points"},
|
124 |
+
"point_labels": {1: "num_points"},
|
125 |
+
}
|
126 |
+
|
127 |
+
embed_dim = sam.prompt_encoder.embed_dim
|
128 |
+
embed_size = sam.prompt_encoder.image_embedding_size
|
129 |
+
mask_input_size = [4 * x for x in embed_size]
|
130 |
+
dummy_inputs = {
|
131 |
+
"image_embeddings": torch.randn(1, embed_dim, *embed_size, dtype=torch.float),
|
132 |
+
"point_coords": torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),
|
133 |
+
"point_labels": torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),
|
134 |
+
"mask_input": torch.randn(1, 1, *mask_input_size, dtype=torch.float),
|
135 |
+
"has_mask_input": torch.tensor([1], dtype=torch.float),
|
136 |
+
"orig_im_size": torch.tensor([1500, 2250], dtype=torch.float),
|
137 |
+
}
|
138 |
+
|
139 |
+
_ = onnx_model(**dummy_inputs)
|
140 |
+
|
141 |
+
output_names = ["masks", "iou_predictions", "low_res_masks"]
|
142 |
+
|
143 |
+
with warnings.catch_warnings():
|
144 |
+
warnings.filterwarnings("ignore", category=torch.jit.TracerWarning)
|
145 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
146 |
+
with open(output, "wb") as f:
|
147 |
+
print(f"Exporing onnx model to {output}...")
|
148 |
+
torch.onnx.export(
|
149 |
+
onnx_model,
|
150 |
+
tuple(dummy_inputs.values()),
|
151 |
+
f,
|
152 |
+
export_params=True,
|
153 |
+
verbose=False,
|
154 |
+
opset_version=opset,
|
155 |
+
do_constant_folding=True,
|
156 |
+
input_names=list(dummy_inputs.keys()),
|
157 |
+
output_names=output_names,
|
158 |
+
dynamic_axes=dynamic_axes,
|
159 |
+
)
|
160 |
+
|
161 |
+
if onnxruntime_exists:
|
162 |
+
ort_inputs = {k: to_numpy(v) for k, v in dummy_inputs.items()}
|
163 |
+
ort_session = onnxruntime.InferenceSession(output)
|
164 |
+
_ = ort_session.run(None, ort_inputs)
|
165 |
+
print("Model has successfully been run with ONNXRuntime.")
|
166 |
+
|
167 |
+
|
168 |
+
def to_numpy(tensor):
|
169 |
+
return tensor.cpu().numpy()
|
170 |
+
|
171 |
+
|
172 |
+
if __name__ == "__main__":
|
173 |
+
args = parser.parse_args()
|
174 |
+
run_export(
|
175 |
+
model_type=args.model_type,
|
176 |
+
checkpoint=args.checkpoint,
|
177 |
+
output=args.output,
|
178 |
+
opset=args.opset,
|
179 |
+
return_single_mask=args.return_single_mask,
|
180 |
+
gelu_approximate=args.gelu_approximate,
|
181 |
+
use_stability_score=args.use_stability_score,
|
182 |
+
return_extra_metrics=args.return_extra_metrics,
|
183 |
+
)
|
184 |
+
|
185 |
+
if args.quantize_out is not None:
|
186 |
+
assert onnxruntime_exists, "onnxruntime is required to quantize the model."
|
187 |
+
from onnxruntime.quantization import QuantType # type: ignore
|
188 |
+
from onnxruntime.quantization.quantize import quantize_dynamic # type: ignore
|
189 |
+
|
190 |
+
print(f"Quantizing model and writing to {args.quantize_out}...")
|
191 |
+
quantize_dynamic(
|
192 |
+
model_input=args.output,
|
193 |
+
model_output=args.quantize_out,
|
194 |
+
optimize_model=True,
|
195 |
+
per_channel=False,
|
196 |
+
reduce_range=False,
|
197 |
+
weight_type=QuantType.QUInt8,
|
198 |
+
)
|
199 |
+
print("Done!")
|
sam/segment_anything.egg-info/PKG-INFO
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: segment-anything
|
3 |
+
Version: 1.0
|
4 |
+
Provides-Extra: all
|
5 |
+
Provides-Extra: dev
|
6 |
+
License-File: LICENSE
|
sam/segment_anything.egg-info/SOURCES.txt
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
LICENSE
|
2 |
+
README.md
|
3 |
+
setup.cfg
|
4 |
+
setup.py
|
5 |
+
segment_anything/__init__.py
|
6 |
+
segment_anything/automatic_mask_generator.py
|
7 |
+
segment_anything/build_sam.py
|
8 |
+
segment_anything/predictor.py
|
9 |
+
segment_anything.egg-info/PKG-INFO
|
10 |
+
segment_anything.egg-info/SOURCES.txt
|
11 |
+
segment_anything.egg-info/dependency_links.txt
|
12 |
+
segment_anything.egg-info/requires.txt
|
13 |
+
segment_anything.egg-info/top_level.txt
|
14 |
+
segment_anything/modeling/__init__.py
|
15 |
+
segment_anything/modeling/common.py
|
16 |
+
segment_anything/modeling/image_encoder.py
|
17 |
+
segment_anything/modeling/mask_decoder.py
|
18 |
+
segment_anything/modeling/prompt_encoder.py
|
19 |
+
segment_anything/modeling/sam.py
|
20 |
+
segment_anything/modeling/transformer.py
|
21 |
+
segment_anything/utils/__init__.py
|
22 |
+
segment_anything/utils/amg.py
|
23 |
+
segment_anything/utils/onnx.py
|
24 |
+
segment_anything/utils/transforms.py
|
sam/segment_anything.egg-info/dependency_links.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
sam/segment_anything.egg-info/requires.txt
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
[all]
|
3 |
+
matplotlib
|
4 |
+
pycocotools
|
5 |
+
opencv-python
|
6 |
+
onnx
|
7 |
+
onnxruntime
|
8 |
+
|
9 |
+
[dev]
|
10 |
+
flake8
|
11 |
+
isort
|
12 |
+
black
|
13 |
+
mypy
|
sam/segment_anything.egg-info/top_level.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
segment_anything
|
sam/segment_anything/.DS_Store
ADDED
Binary file (6.15 kB). View file
|
|
sam/segment_anything/__init__.py
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
2 |
+
# All rights reserved.
|
3 |
+
|
4 |
+
# This source code is licensed under the license found in the
|
5 |
+
# LICENSE file in the root directory of this source tree.
|
6 |
+
|
7 |
+
from .build_sam import (
|
8 |
+
build_sam,
|
9 |
+
build_sam_vit_h,
|
10 |
+
build_sam_vit_l,
|
11 |
+
build_sam_vit_b,
|
12 |
+
sam_model_registry,
|
13 |
+
)
|
14 |
+
from .predictor import SamPredictor
|
15 |
+
from .automatic_mask_generator import SamAutomaticMaskGenerator
|
sam/segment_anything/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (457 Bytes). View file
|
|
sam/segment_anything/__pycache__/automatic_mask_generator.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
sam/segment_anything/__pycache__/build_sam.cpython-310.pyc
ADDED
Binary file (2.2 kB). View file
|
|
sam/segment_anything/__pycache__/predictor.cpython-310.pyc
ADDED
Binary file (9.96 kB). View file
|
|