pytorch-labs / segment-anything-fast

A batched offline inference oriented version of segment-anything
Apache License 2.0
1.19k stars 70 forks source link

ValueError: Expected query, key, and value to all be be jagged at dimension 2, but got query._ragged_idx: 1, key._ragged_idx: 1 and value._ragged_idx: 1 instead. #99

Closed sanshe316 closed 9 months ago

sanshe316 commented 9 months ago

Reproduce:

import cv2
from segment_anything_fast import sam_model_registry, SamPredictor, SamAutomaticMaskGenerator

img_path = 'amg_example/dog.jpg'
model_type = 'vit_b'
checkpoint = 'checkpoints/sam_vit_b_01ec64.pth'

sam = sam_model_registry[model_type](checkpoint=checkpoint)

img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

mask_generator = SamAutomaticMaskGenerator(sam)
masks = mask_generator.generate(img)

Error stack:

Traceback (most recent call last):
  File "/home/gxw/workspace/sam/segment-anything-fast/scripts/gen_mask.py", line 21, in <module>
    masks = mask_generator.generate(img)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
    return func(*args, **kwargs)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/automatic_mask_generator.py", line 170, in generate
    mask_data = self._generate_masks(image)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/automatic_mask_generator.py", line 213, in _generate_masks
    crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/automatic_mask_generator.py", line 255, in _process_crop
    batch_data = self._process_batch(some_points, cropped_im_size, crop_box, orig_size)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/automatic_mask_generator.py", line 298, in _process_batch
    nt_masks, nt_iou_preds, _ = self.predictor.predict_torch(
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
    return func(*args, **kwargs)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/predictor.py", line 230, in predict_torch
    low_res_masks, iou_predictions = self.model.mask_decoder(
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/modeling/mask_decoder.py", line 99, in forward
    masks, iou_pred = self.predict_masks_nested(
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/modeling/mask_decoder.py", line 188, in predict_masks_nested
    hs, src = self.transformer(src, pos_src, tokens)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/modeling/transformer.py", line 91, in forward
    queries, keys = layer(
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/modeling/transformer.py", line 155, in forward
    queries = self.self_attn(q=queries, k=queries, v=queries)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/gxw/workspace/sam/segment-anything-fast/segment_anything_fast/modeling/transformer.py", line 227, in forward
    out = torch.nn.functional.scaled_dot_product_attention(q, k, v)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nested/_internal/nested_tensor.py", line 229, in __torch_function__
    return jagged_torch_function(func, *args, **kwargs)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nested/_internal/ops.py", line 265, in jagged_torch_function
    return jagged_scaled_dot_product_attention(*args, **kwargs)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nested/_internal/sdpa.py", line 640, in jagged_scaled_dot_product_attention
    _validate_sdpa_input(query, key, value, attn_mask, dropout_p, is_causal, scale)
  File "/home/gxw/miniconda3/envs/triton/lib/python3.10/site-packages/torch/nested/_internal/sdpa.py", line 59, in _validate_sdpa_input
    raise ValueError(
ValueError: Expected query, key, and value to all be be jagged at dimension 2, but got query._ragged_idx: 1, key._ragged_idx: 1 and value._ragged_idx: 1 instead.

collect_env:

Collecting environment information...
PyTorch version: 2.2.0.dev20231206+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.2.0-37-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090

Nvidia driver version: 530.30.02
cuDNN version: Probably one of the following:
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn.so.8.9.5
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.9.5
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.9.5
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.9.5
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.9.5
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.9.5
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.9.5
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             48
On-line CPU(s) list:                0-47
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Silver 4310 CPU @ 2.10GHz
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 12
Socket(s):                          2
Stepping:                           6
BogoMIPS:                           4200.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          1.1 MiB (24 instances)
L1i cache:                          768 KiB (24 instances)
L2 cache:                           30 MiB (24 instances)
L3 cache:                           36 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46
NUMA node1 CPU(s):                  1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.2
[pip3] onnx==1.15.0
[pip3] onnxruntime==1.16.3
[pip3] pytorch-labs-segment-anything-fast==0.2
[pip3] pytorch-triton==2.1.0+bcad9dabe1
[pip3] torch==2.2.0.dev20231206+cu121
[pip3] torchao==0.0.1
[pip3] torchaudio==2.2.0.dev20231206+cu121
[pip3] torchvision==0.17.0.dev20231206+cu121
[pip3] triton==2.1.0
[conda] numpy                     1.26.2                   pypi_0    pypi
[conda] pytorch-labs-segment-anything-fast 0.2                       dev_0    <develop>
[conda] pytorch-triton            2.1.0+bcad9dabe1          pypi_0    pypi
[conda] torch                     2.2.0.dev20231206+cu121          pypi_0    pypi
[conda] torchao                   0.0.1                    pypi_0    pypi
[conda] torchaudio                2.2.0.dev20231206+cu121          pypi_0    pypi
[conda] torchvision               0.17.0.dev20231206+cu121          pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi

It seems a problem with nested_tensor, but I don't know what causes it and how to fix it.

cpuhrsch commented 9 months ago

@sanshe316 I'm able to reproduce this error for both the 2.2 RC and current nightly. cc @jbschlosser @soulitzer .

jbschlosser commented 9 months ago

#114164 broke this and sadly landed the last day of the 2.2 RC. I'm working on a fix.

cpuhrsch commented 9 months ago

Ok @sanshe316 I just reran the snippet on the latest nightly (December 13th) and also landed https://github.com/pytorch-labs/segment-anything-fast/pull/105 to make sure it works on CPU (in case that was your intention). We'll make sure the fix also makes it into 2.2. Thank you for opening the issue! Could I kindly ask you to try again? Thank you.

sanshe316 commented 9 months ago

After upgrading from torch-2.2.0.dev20231206+cu121 -> torch-2.3.0.dev20231217+cu121, the problem fixed. Thank you