czg1225 / slimsam Goto Github PK
View Code? Open in Web Editor NEWSlimSAM: 0.1% Data Makes Segment Anything Slim
License: Apache License 2.0
SlimSAM: 0.1% Data Makes Segment Anything Slim
License: Apache License 2.0
Hi 👋 thanks for the project ❤ I got an error when I tried running inference.py
(torch 2.1.0+cu118)
CUDA visible devices: 1
CUDA Device Name: Tesla T4
model_path: checkpoints/SlimSAM-77.pth
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
[<ipython-input-19-14955c5395e4>](https://localhost:8080/#) in <cell line: 165>()
164
165 if __name__ == '__main__':
--> 166 test_model()
15 frames
[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in __getattr__(self, name)
1693 if name in modules:
1694 return modules[name]
-> 1695 raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
1696
1697 def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -> None:
AttributeError: 'GELU' object has no attribute 'approximate'
Is there a way to fix it?
Thank you for your great work! Would you mind sharing the prune ratios for each step? I don't find them in the paper or code. Thanks!
Thanks for your great work. But when I try to train with my own data. The IOU score seems too low. Here is the log.
CUDA visible devices: 1
CUDA Device Name: NVIDIA GeForce RTX 4090
===========================Parameter Settings===========================
Pruning Ratio: 0.5
VIT num_heads: 12
norm_type: mean
imptype: Disturb
global: False
learning rate: 0.0001
global: False [0/1867]
learning rate: 0.0001
a_weight: 0.5
round_to 12
TRAIN_SIZE 7825 VAL_SIZE 200 GRAD_SIZE 1000 Epochs 20
===========================Pruning Start===========================
/home/user/workspace/SlimSAM-master/torch_pruning/dependency.py:639: UserWarning: Unwrapped parameters detected: ['neck.3.bias', 'neck.1.bias', 'pos_embed', '
neck.1.weight', 'neck.3.weight'].
Torch-Pruning will prune the last non-singleton dimension of a parameter. If you wish to customize this behavior, please provide an unwrapped_parameters argume
nt.
warnings.warn(warning_str)
vit_b Pruning:
Params: 89578240 => 45116800
Macs: 368858711040.0 => 185712844800.0
Output:
torch.Size([1, 256, 64, 64])
torch.Size([600, 14, 14, 768])
torch.Size([12, 64, 64, 768])
torch.Size([12, 64, 64, 3072])
torch.Size([25, 64, 64, 384])
------------------------------------------------------
save checkpoint
epoch: 0
IOU: 0.00037980064841486576 Best IOU 0.00037980064841486576
epoch: 1
IOU: 0.0003555969132073369 Best IOU 0.00037980064841486576
save checkpoint
epoch: 2
IOU: 0.0004798856262954162 Best IOU 0.0004798856262954162
epoch: 3
IOU: 0.00038100686134219785 Best IOU 0.0004798856262954162
epoch: 4
IOU: 0.00033190775964380326 Best IOU 0.0004798856262954162
epoch: 5
IOU: 0.00034291165492228654 Best IOU 0.0004798856262954162
Epoch 00007: reducing learning rate of group 0 to 5.0000e-05.
epoch: 6
IOU: 0.00033288924349753746 Best IOU 0.0004798856262954162
By the way, my mask files are transformed to COCO RLE format from the origin labeled files which only include polygons. I transformed them first to the binary masks and then to the COCO RLE format. So the transformed JSON files don't have point_coords
in the dict as the SA-1B dataset. So I altered the code in the prune_distill_step1.py
. Is that the key reason?
for example in dict_data:
sub_count += 1
# input_point = np.array(example['point_coords'])
# input_label = np.array([1])
mask = mask_utils.decode(example["segmentation"])
# point_coords = transform.apply_coords(input_point, original_image_size)
# coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=device)
# labels_torch = torch.as_tensor(input_label, dtype=torch.int, device=device)
# coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :]
# points = (coords_torch, labels_torch)
# Model inference
image_embedding,_,_,_,_ = model.image_encoder(input_image)
sparse_embeddings, dense_embeddings = model.prompt_encoder(
points=None, # points,
boxes=None,
masks=None,
)
Hi,
Can someone please tell the syntax to load SAMModel,SAMProcessor from hugging face, the library importing step is missing in documentation ?
I'm using the dataset from roboflow. Can you help me?
!CUDA_VISIBLE_DEVICES=0 python prune_distill_step1.py --traindata_path "/kaggle/working/Crop-Fields-LOD-13-14-15-4/train/_annotations.coco.json" --valdata_path "/kaggle/working/Crop-Fields-LOD-13-14-15-4/valid/_annotations.coco.json" --trainsize 480 --valsize 126 --prune_ratio 0.3 --epochs 20
===========================Parameter Settings===========================
Pruning Ratio: 0.3
VIT num_heads: 12
norm_type: mean
imptype: Disturb
global: False
learning rate: 0.0001
a_weight: 0.5
round_to 12
TRAIN_SIZE 480 VAL_SIZE 126 GRAD_SIZE 1000 Epochs 20
Traceback (most recent call last):
File "/kaggle/working/SlimSAM/prune_distill_step1.py", line 295, in
train_model()
File "/kaggle/working/SlimSAM/prune_distill_step1.py", line 118, in train_model
batch = next(grad_iter)
File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 634, in next
data = self._next_data()
File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 1346, in _next_data
return self._process_data(data)
File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line 1372, in _process_data
data.reraise()
File "/opt/conda/lib/python3.10/site-packages/torch/_utils.py", line 644, in reraise
raise exception
IndexError: Caught IndexError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/worker.py", line 308, in _worker_loop
data = fetcher.fetch(index)
File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 51, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/opt/conda/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", line 51, in
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/kaggle/working/SlimSAM/load_sam_json.py", line 39, in getitem
image = cv2.imread(self._image_paths[index])
IndexError: list index out of range
https://universe.roboflow.com/cropfields/crop-fields-lod-13-14-15/dataset/4
Hello 👋 wanted to ping you about recent transformers.js release. @xenova recently ported SlimSAM to run in browser and the demo can be found here in case you'd like check it out. https://huggingface.co/spaces/Xenova/segment-anything-web
Hi,
Can we plug in the SlimSAM weights into SAM (by recombining the q, k, v weights into a single matrix per layer)?
If yes, then SlimSAM could be ported easily to the 🤗 hub. Currently I'm getting errors like:
size mismatch for vision_encoder.layers.7.mlp.lin2.bias: copying a param with shape torch.Size([168]) from checkpoint, the shape in current model is torch.Size([768]).
size mismatch for vision_encoder.layers.8.layer_norm1.weight: copying a param with shape torch.Size([168]) from checkpoint, the shape in current model is torch.Size([768]).
It seems that the dimensions are different per layer based on the pruning. Any way to load such a state dict in PyTorch?
Hi, I found your work,it's great.
I am a newbie having some difficulties in reproducing your experiment and would like to seek your help.
I found that you did a comparison experiment in your paper, using the SA-1B dataset, and I successfully reproduced the training and validation results of SlimSAM in it.
However, since you didn't release the validation scripts for the time being, I had to follow your experimental setup(https://github.com/czg1225/SlimSAM/issues/5#issuecomment-1875436503) and write my own scripts to validate FastSAM, MobileSAM, EfficientSAM and other algorithms on SA-1B, but I couldn't reproduce the results listed in your table very well, especially the EfficientSAM(only 28%) and EdgeSAM algorithms.
I wonder if it would be convenient for you to put out the validation scripts for these comparison algorithms for learning purposes, I would appreciate it.Thank you very much!
Hi! Could you please tell me what is the meaning of del_pos_init and get_pos_init? There is no such operations in the original torch_pruning when pruning ViT or Swin transformer. Why is positional embedding removed here and what is the effect of this on pruning?
Under what license are the model and code released?
Hi @czg1225
Thanks for this repo!
Can you please tell how can I do batch prompting by giving multiple boxes as prompts to the model?
Right now, predict function takes one numpy array of length 4
Also can you please clarify that for custom dataset training, does each image file should have a corresponding json or a single json for the whole folder is enough since I am getting this error. I have se gradsize to be 100 and 1000. My training images are 1306 and validation are 293.
Hi, could you please describe in detail how the SA-1B dataset is split into the training and the validation set in this work?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.