RoIAlign & crop_and_resize for PyTorch

Overview

RoIAlign for PyTorch

This is a PyTorch version of RoIAlign. This implementation is based on crop_and_resize and supports both forward and backward on CPU and GPU.

NOTE: Thanks meikuam for updating this repo for PyTorch 1.0. You can find the original version for torch <= 0.4.1 in pytorch_0.4 branch.

Introduction

The crop_and_resize function is ported from tensorflow, and has the same interface with tensorflow version, except the input feature map should be in NCHW order in PyTorch. They also have the same output value (error < 1e-5) for both forward and backward as we expected, see the comparision in test.py.

Note: Document of crop_and_resize can be found here. And RoIAlign is a wrap of crop_and_resize that uses boxes with unnormalized (x1, y1, x2, y2) as input (while crop_and_resize use normalized (y1, x1, y2, x2) as input). See more details about the difference of RoIAlign and crop_and_resize in tensorpack.

Warning: Currently it only works using the default GPU (index 0)

Usage

  • Install and test

    python setup.py install
    ./test.sh
    
  • Use RoIAlign or crop_and_resize

    Since PyTorch 1.2.0 Legacy autograd function with non-static forward method is deprecated. We use new-style autograd function with static forward method. Example:

    import torch
    from roi_align import RoIAlign      # RoIAlign module
    from roi_align import CropAndResize # crop_and_resize module
    
    # input feature maps (suppose that we have batch_size==2)
    image = torch.arange(0., 49).view(1, 1, 7, 7).repeat(2, 1, 1, 1)
    image[0] += 10
    print('image: ', image)
    
    
    # for example, we have two bboxes with coords xyxy (first with batch_id=0, second with batch_id=1).
    boxes = torch.Tensor([[1, 0, 5, 4],
                         [0.5, 3.5, 4, 7]])
    
    box_index = torch.tensor([0, 1], dtype=torch.int) # index of bbox in batch
    
    # RoIAlign layer with crop sizes:
    crop_height = 4
    crop_width = 4
    roi_align = RoIAlign(crop_height, crop_width)
    
    # make crops:
    crops = roi_align(image, boxes, box_index)
    
    print('crops:', crops)

    Output:

    image:  tensor([[[[10., 11., 12., 13., 14., 15., 16.],
          [17., 18., 19., 20., 21., 22., 23.],
          [24., 25., 26., 27., 28., 29., 30.],
          [31., 32., 33., 34., 35., 36., 37.],
          [38., 39., 40., 41., 42., 43., 44.],
          [45., 46., 47., 48., 49., 50., 51.],
          [52., 53., 54., 55., 56., 57., 58.]]],
    
    
        [[[ 0.,  1.,  2.,  3.,  4.,  5.,  6.],
          [ 7.,  8.,  9., 10., 11., 12., 13.],
          [14., 15., 16., 17., 18., 19., 20.],
          [21., 22., 23., 24., 25., 26., 27.],
          [28., 29., 30., 31., 32., 33., 34.],
          [35., 36., 37., 38., 39., 40., 41.],
          [42., 43., 44., 45., 46., 47., 48.]]]])
          
    crops: tensor([[[[11.0000, 12.0000, 13.0000, 14.0000],
              [18.0000, 19.0000, 20.0000, 21.0000],
              [25.0000, 26.0000, 27.0000, 28.0000],
              [32.0000, 33.0000, 34.0000, 35.0000]]],
    
    
            [[[24.5000, 25.3750, 26.2500, 27.1250],
              [30.6250, 31.5000, 32.3750, 33.2500],
              [36.7500, 37.6250, 38.5000, 39.3750],
              [ 0.0000,  0.0000,  0.0000,  0.0000]]]])
Comments
  • install error

    install error

    Hi, thank you for your work and share. The system is ubuntu16.04 with pytorch 0.5.0. When I run ./install.sh, an error: dereferencing pointer to incomplete type 'THTensor {aka struct THTensor}' const int batch_size = image->size[0]; occurred. I cannot find a solution on google, could you give me a cue to solve this error. Thank you very much!

    opened by dami23 10
  • pytorch-1.0

    pytorch-1.0

    Hi, I cannot install your RoIAlign with the latest pytorch version (stable 1.0). I get the following error when I run the install.sh:

    Compiling crop_and_resize kernels by nvcc...
    ./install.sh: ligne 7: /usr/local/cuda/bin/nvcc: Aucun fichier ou dossier de ce type
    Traceback (most recent call last):
      File "build.py", line 3, in <module>
        from torch.utils.ffi import create_extension
      File "/home/fbaradel/anaconda3/envs/pytorch-1.0/lib/python3.6/site-packages/torch/utils/ffi/__init__.py", line 1, in <module>
        raise ImportError("torch.utils.ffi is deprecated. Please use cpp extensions instead.")
    ImportError: torch.utils.ffi is deprecated. Please use cpp extensions instead.
    running install
    running bdist_egg
    running egg_info
    creating roi_align.egg-info
    writing roi_align.egg-info/PKG-INFO
    writing dependency_links to roi_align.egg-info/dependency_links.txt
    writing requirements to roi_align.egg-info/requires.txt
    writing top-level names to roi_align.egg-info/top_level.txt
    writing manifest file 'roi_align.egg-info/SOURCES.txt'
    reading manifest file 'roi_align.egg-info/SOURCES.txt'
    writing manifest file 'roi_align.egg-info/SOURCES.txt'
    installing library code to build/bdist.linux-x86_64/egg
    running install_lib
    running build_py
    creating build
    creating build/lib
    creating build/lib/roi_align
    copying roi_align/build.py -> build/lib/roi_align
    copying roi_align/crop_and_resize.py -> build/lib/roi_align
    copying roi_align/roi_align.py -> build/lib/roi_align
    copying roi_align/__init__.py -> build/lib/roi_align
    creating build/lib/roi_align/_ext
    copying roi_align/_ext/__init__.py -> build/lib/roi_align/_ext
    creating build/lib/roi_align/_ext/crop_and_resize
    copying roi_align/_ext/crop_and_resize/__init__.py -> build/lib/roi_align/_ext/crop_and_resize
    creating build/bdist.linux-x86_64
    creating build/bdist.linux-x86_64/egg
    creating build/bdist.linux-x86_64/egg/roi_align
    copying build/lib/roi_align/build.py -> build/bdist.linux-x86_64/egg/roi_align
    copying build/lib/roi_align/crop_and_resize.py -> build/bdist.linux-x86_64/egg/roi_align
    creating build/bdist.linux-x86_64/egg/roi_align/_ext
    creating build/bdist.linux-x86_64/egg/roi_align/_ext/crop_and_resize
    copying build/lib/roi_align/_ext/crop_and_resize/__init__.py -> build/bdist.linux-x86_64/egg/roi_align/_ext/crop_and_resize
    copying build/lib/roi_align/_ext/__init__.py -> build/bdist.linux-x86_64/egg/roi_align/_ext
    copying build/lib/roi_align/roi_align.py -> build/bdist.linux-x86_64/egg/roi_align
    copying build/lib/roi_align/__init__.py -> build/bdist.linux-x86_64/egg/roi_align
    byte-compiling build/bdist.linux-x86_64/egg/roi_align/build.py to build.cpython-36.pyc
    byte-compiling build/bdist.linux-x86_64/egg/roi_align/crop_and_resize.py to crop_and_resize.cpython-36.pyc
    byte-compiling build/bdist.linux-x86_64/egg/roi_align/_ext/crop_and_resize/__init__.py to __init__.cpython-36.pyc
    byte-compiling build/bdist.linux-x86_64/egg/roi_align/_ext/__init__.py to __init__.cpython-36.pyc
    byte-compiling build/bdist.linux-x86_64/egg/roi_align/roi_align.py to roi_align.cpython-36.pyc
    byte-compiling build/bdist.linux-x86_64/egg/roi_align/__init__.py to __init__.cpython-36.pyc
    creating build/bdist.linux-x86_64/egg/EGG-INFO
    copying roi_align.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
    copying roi_align.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
    copying roi_align.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
    copying roi_align.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
    copying roi_align.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
    zip_safe flag not set; analyzing archive contents...
    roi_align.__pycache__.build.cpython-36: module references __file__
    creating dist
    creating 'dist/roi_align-0.0.1-py3.6.egg' and adding 'build/bdist.linux-x86_64/egg' to it
    removing 'build/bdist.linux-x86_64/egg' (and everything under it)
    Processing roi_align-0.0.1-py3.6.egg
    creating /home/fbaradel/anaconda3/envs/pytorch-1.0/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg
    Extracting roi_align-0.0.1-py3.6.egg to /home/fbaradel/anaconda3/envs/pytorch-1.0/lib/python3.6/site-packages
    Adding roi-align 0.0.1 to easy-install.pth file
    
    Installed /home/fbaradel/anaconda3/envs/pytorch-1.0/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg
    Processing dependencies for roi-align==0.0.1
    Searching for cffi==1.11.5
    Best match: cffi 1.11.5
    Adding cffi 1.11.5 to easy-install.pth file
    
    Using /home/fbaradel/anaconda3/envs/pytorch-1.0/lib/python3.6/site-packages
    Searching for pycparser==2.19
    Best match: pycparser 2.19
    Adding pycparser 2.19 to easy-install.pth file
    
    Using /home/fbaradel/anaconda3/envs/pytorch-1.0/lib/python3.6/site-packages
    Finished processing dependencies for roi-align==0.0.1
    

    It seems that the create_extension has moved somewhere else... Thanks for your answer.

    opened by fabienbaradel 3
  • GPU support

    GPU support

    Hi, thank you very much for this code!

    The code works fine for me if I change the capability of the gpu in make.sh as:

    $CUDA_PATH/bin/nvcc -c -o crop_and_resize_kernel.cu.o crop_and_resize_kernel.cu -x cu -Xcompiler -fPIC -arch=sm_50

    Because I have a GPU with 5.0 capability which is slightly less than sm_52 as you wrote. Maybe it is worth mentioning it in the README to check the capability of the GPU before building.

    opened by simo23 2
  •     from ._crop_and_resize import lib as _lib, ffi as _ffi ModuleNotFoundError: No module named 'roi_align._ext.crop_and_resize._crop_and_resize'

    from ._crop_and_resize import lib as _lib, ffi as _ffi ModuleNotFoundError: No module named 'roi_align._ext.crop_and_resize._crop_and_resize'

    when i test,i saw the problem. how can i solve it? ying@ying-TM1701:~/下载/RoIAlign.pytorch-pytorch_0.4$ ./tests bash: ./tests: 是一个目录 (pytorch0.4.1_group) ying@ying-TM1701:~/下载/RoIAlign.pytorch-pytorch_0.4$ ./test.sh Unexpected error: <class 'ModuleNotFoundError'> Traceback (most recent call last): File "tests/test.py", line 13, in from roi_align.crop_and_resize import CropAndResizeFunction File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/crop_and_resize.py", line 7, in from ._ext import crop_and_resize as _backend File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/_ext/crop_and_resize/init.py", line 3, in from ._crop_and_resize import lib as _lib, ffi as _ffi ModuleNotFoundError: No module named 'roi_align._ext.crop_and_resize._crop_and_resize' Traceback (most recent call last): File "tests/test2.py", line 5, in from roi_align.roi_align import RoIAlign File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/roi_align.py", line 4, in from .crop_and_resize import CropAndResizeFunction, CropAndResize File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/crop_and_resize.py", line 7, in from ._ext import crop_and_resize as _backend File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/_ext/crop_and_resize/init.py", line 3, in from ._crop_and_resize import lib as _lib, ffi as _ffi ModuleNotFoundError: No module named 'roi_align._ext.crop_and_resize._crop_and_resize' Traceback (most recent call last): File "tests/crop_and_resize_example.py", line 5, in from roi_align.crop_and_resize import CropAndResizeFunction File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/crop_and_resize.py", line 7, in from ._ext import crop_and_resize as _backend File "/home/ying/.conda/envs/pytorch0.4.1_group/lib/python3.6/site-packages/roi_align-0.0.1-py3.6.egg/roi_align/_ext/crop_and_resize/init.py", line 3, in from ._crop_and_resize import lib as _lib, ffi as _ffi ModuleNotFoundError: No module named 'roi_align._ext.crop_and_resize._crop_and_resize'

    opened by yingkaining 1
  • pytorch1.0 ffi was deprecated

    pytorch1.0 ffi was deprecated

    Traceback (most recent call last): File "build.py", line 3, in from torch.utils.ffi import create_extension File "/home/lzy/.local/lib/python2.7/site-packages/torch/utils/ffi/init.py", line 1, in raise ImportError("torch.utils.ffi is deprecated. Please use cpp extensions instead.") ImportError: torch.utils.ffi is deprecated. Please use cpp extensions instead.

    opened by xiaoshihoua 1
  • Crop height and Crop width

    Crop height and Crop width

    I get the following issue for Extrapolation value:

    TypeError: initializer for ctype 'struct THCudaIntTensor *' must be a pointer to same type, not cdata 'struct THCudaLongTensor *'

    opened by medhini 0
  • Conda install support. Test support for CPU.

    Conda install support. Test support for CPU.

    This PR allows installing RoIAlign as a module in Conda. Examples support python3 and CPU. Conda support will hopefully ease installing roi_align in the conda environment and hopefully ease and boost its adoption.

    I took the photos myself using my phone and haven't been published in any social media nor photo sharing and thus they are royalty free and suitable to use in an opensource project.

    opened by paucarre 0
  • a bug: spacing_w -> spacing_h

    a bug: spacing_w -> spacing_h

                nh = spacing_w * float(self.crop_height - 1) / float(image_height - 1)
    # should be
                nh = spacing_h * float(self.crop_height - 1) / float(image_height - 1)
    
    opened by CharlesShang 0
  • RuntimeError: image.is_contiguous()INTERNAL ASSERT FAILED at

    RuntimeError: image.is_contiguous()INTERNAL ASSERT FAILED at ".\\RoIAlign\\roi_align\\src\\crop_and_resize_gpu.cpp":27, please report a bug to PyTorch. image must be contiguous

    Hellow ,thanks for your work. I reload this work in pytorch1.11.0 and foud a RuntimeError

    The error log follows:

    Traceback (most recent call last):
      File "c:/Users/29006/Desktop/GAR/scripts/train_volleyball_stage1.py", line 21, in <module>
        train_net(cfg)
      File ".\train_net.py", line 110, in train_net
        return forward_call(*input, **kwargs)
      File ".\base_model.py", line 117, in forward
        boxes_idx_flat)  #B*T*N, D, K, K,
      File "D:\Anaconda\envs\GCN\lib\site-packages\torch\nn\modules\module.py", line 1110, in _call_impl
        return forward_call(*input, **kwargs)
      File "D:\Anaconda\envs\GCN\lib\site-packages\roi_align-0.0.2-py3.7-win-amd64.egg\roi_align\roi_align.py", line 48, in forward
        return CropAndResizeFunction.apply(featuremap, boxes, box_ind, self.crop_height, self.crop_width, self.extrapolation_value)
      File "D:\Anaconda\envs\GCN\lib\site-packages\roi_align-0.0.2-py3.7-win-amd64.egg\roi_align\crop_and_resize.py", line 25, in forward        
        ctx.extrapolation_value, ctx.crop_height, ctx.crop_width, crops)
    RuntimeError: image.is_contiguous()INTERNAL ASSERT FAILED at "C:\\Users\\29006\\Desktop\\RoIAlign\\roi_align\\src\\crop_and_resize_gpu.cpp":27, please report a bug to PyTorch. image must be contiguous
    

    So, does any one can solve this?

    opened by Kev1n3zz 0
  •  LinkError: command 'gcc' failed with exit status 1

    LinkError: command 'gcc' failed with exit status 1

    LinkError: command 'gcc' failed with exit status 1 During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "build.py", line 40, in ffi.build() File "/home/wei.li/anaconda3/envs/group_1/lib/python3.6/site-packages/torch/utils/ffi/init.py", line 189, in build _build_extension(ffi, cffi_wrapper_name, target_dir, verbose) File "/home/wei.li/anaconda3/envs/group_1/lib/python3.6/site-packages/torch/utils/ffi/init.py", line 111, in _build_extension outfile = ffi.compile(tmpdir=tmpdir, verbose=verbose, target=libname) File "/home/wei.li/anaconda3/envs/group_1/lib/python3.6/site-packages/cffi-1.15.0-py3.6-linux-x86_64.egg/cffi/api.py", line 727, in compile compiler_verbose=verbose, debug=debug, **kwds) File "/home/wei.li/anaconda3/envs/group_1/lib/python3.6/site-packages/cffi-1.15.0-py3.6-linux-x86_64.egg/cffi/recompiler.py", line 1565, in recompile compiler_verbose, debug) File "/home/wei.li/anaconda3/envs/group_1/lib/python3.6/site-packages/cffi-1.15.0-py3.6-linux-x86_64.egg/cffi/ffiplatform.py", line 22, in compile outputfilename = _build(tmpdir, ext, compiler_verbose, debug) File "/home/wei.li/anaconda3/envs/group_1/lib/python3.6/site-packages/cffi-1.15.0-py3.6-linux-x86_64.egg/cffi/ffiplatform.py", line 58, in _build raise VerificationError('%s: %s' % (e.class.name, e)) cffi.VerificationError: LinkError: command 'gcc' failed with exit status 1

    opened by SkyBroY 0
  • Error compiling objects for extension (PyTorch=1.9.0 in anaconda)?

    Error compiling objects for extension (PyTorch=1.9.0 in anaconda)?

    Hi,

    I am getting the following compiling error. Does RoIAlign work with Pytorch 1.9.0?

      File "C:\Users\...\Anaconda3\lib\site-packages\torch\utils\cpp_extension.py", line 1682, in _run_ninja_build
        raise RuntimeError(message) from e
    
    RuntimeError: Error compiling objects for extension
    

    Thanks.

    opened by dominikj2 2
  • License

    License

    Hello everyone,

    First of all, thanks for the material! I tried to look for the licensing terms under which the software is distributed, but I did not find anything. Since it is inspired by a Tensorflow function, I guess that everything is under Apache 2.0. Am I correct? :-)

    Thanks a lot, Matteo

    opened by mp-17 0
Owner
Long Chen
Computer Vision
Long Chen
RealFormer-Pytorch Implementation of RealFormer using pytorch

RealFormer-Pytorch Implementation of RealFormer using pytorch. Includes comparison with classical Transformer on image classification task (ViT) wrt C

Simo Ryu 90 Dec 8, 2022
Generic template to bootstrap your PyTorch project with PyTorch Lightning, Hydra, W&B, and DVC.

NN Template Generic template to bootstrap your PyTorch project. Click on Use this Template and avoid writing boilerplate code for: PyTorch Lightning,

Luca Moschella 520 Dec 30, 2022
A PyTorch Extension: Tools for easy mixed precision and distributed training in Pytorch

This repository holds NVIDIA-maintained utilities to streamline mixed precision and distributed training in Pytorch. Some of the code here will be included in upstream Pytorch eventually. The intention of Apex is to make up-to-date utilities available to users as quickly as possible.

NVIDIA Corporation 6.9k Jan 3, 2023
Objective of the repository is to learn and build machine learning models using Pytorch. 30DaysofML Using Pytorch

30 Days Of Machine Learning Using Pytorch Objective of the repository is to learn and build machine learning models using Pytorch. List of Algorithms

Mayur 119 Nov 24, 2022
Pretrained SOTA Deep Learning models, callbacks and more for research and production with PyTorch Lightning and PyTorch

Pretrained SOTA Deep Learning models, callbacks and more for research and production with PyTorch Lightning and PyTorch

Pytorch Lightning 1.4k Jan 1, 2023
Amazon Forest Computer Vision: Satellite Image tagging code using PyTorch / Keras with lots of PyTorch tricks

Amazon Forest Computer Vision Satellite Image tagging code using PyTorch / Keras Here is a sample of images we had to work with Source: https://www.ka

Mamy Ratsimbazafy 360 Dec 10, 2022
The Incredible PyTorch: a curated list of tutorials, papers, projects, communities and more relating to PyTorch.

This is a curated list of tutorials, projects, libraries, videos, papers, books and anything related to the incredible PyTorch. Feel free to make a pu

Ritchie Ng 9.2k Jan 2, 2023
A PyTorch implementation of the paper Mixup: Beyond Empirical Risk Minimization in PyTorch

Mixup: Beyond Empirical Risk Minimization in PyTorch This is an unofficial PyTorch implementation of mixup: Beyond Empirical Risk Minimization. The co

Harry Yang 121 Dec 17, 2022
A pytorch implementation of Pytorch-Sketch-RNN

Pytorch-Sketch-RNN A pytorch implementation of https://arxiv.org/abs/1704.03477 In order to draw other things than cats, you will find more drawing da

Alexis David Jacq 172 Dec 12, 2022
PyTorch implementation of Advantage async actor-critic Algorithms (A3C) in PyTorch

Advantage async actor-critic Algorithms (A3C) in PyTorch @inproceedings{mnih2016asynchronous, title={Asynchronous methods for deep reinforcement lea

LEI TAI 111 Dec 8, 2022
Amazon Forest Computer Vision: Satellite Image tagging code using PyTorch / Keras with lots of PyTorch tricks

Amazon Forest Computer Vision Satellite Image tagging code using PyTorch / Keras Here is a sample of images we had to work with Source: https://www.ka

Mamy Ratsimbazafy 359 Jan 5, 2023
A bunch of random PyTorch models using PyTorch's C++ frontend

PyTorch Deep Learning Models using the C++ frontend Gettting started Clone the repo 1. https://github.com/mrdvince/pytorchcpp 2. cd fashionmnist or

Vince 0 Jul 13, 2021
PyTorch Autoencoders - Implementing a Variational Autoencoder (VAE) Series in Pytorch.

PyTorch Autoencoders Implementing a Variational Autoencoder (VAE) Series in Pytorch. Inspired by this repository Model List check model paper conferen

Subin An 8 Nov 21, 2022
PyTorch-LIT is the Lite Inference Toolkit (LIT) for PyTorch which focuses on easy and fast inference of large models on end-devices.

PyTorch-LIT PyTorch-LIT is the Lite Inference Toolkit (LIT) for PyTorch which focuses on easy and fast inference of large models on end-devices. With

Amin Rezaei 157 Dec 11, 2022
A general framework for deep learning experiments under PyTorch based on pytorch-lightning

torchx Torchx is a general framework for deep learning experiments under PyTorch based on pytorch-lightning. TODO list gan-like training wrapper text

Yingtian Liu 6 Mar 17, 2022
A PyTorch Extension: Tools for easy mixed precision and distributed training in Pytorch

Introduction This is a Python package available on PyPI for NVIDIA-maintained utilities to streamline mixed precision and distributed training in Pyto

Artit 'Art' Wangperawong 5 Sep 29, 2021
Pytorch-diffusion - A basic PyTorch implementation of 'Denoising Diffusion Probabilistic Models'

PyTorch implementation of 'Denoising Diffusion Probabilistic Models' This reposi

Arthur Juliani 76 Jan 7, 2023
Fang Zhonghao 13 Nov 19, 2022
ALBERT-pytorch-implementation - ALBERT pytorch implementation

ALBERT-pytorch-implementation developing... 모델의 개념이해를 돕기 위한 구현물로 현재 변수명을 상세히 적었고

BG Kim 3 Oct 6, 2022