본문 바로가기

Python

Docker기반의 RESTful api로 pytorch model 배포하기[4-5]

  1. Flask RESTful을 이용하여, HTTP로 호출할 수 있는 RESTful api 만들기
  2. 학습한 모델의 weight와 graph를 하나의 파일로 만들기(torchscript)
  3. 보안을 위해, 2번에서 만든 torchscript파일을 encryption하기
  4. 보안을 위해, cython을 이용하여 python script를 library형태로 만들기
  5. Docker image 만들고 배포하기

 

앞선 글에서는 torchscript 파일을 암호화하여 model의 구조를 타인이 보지 못하도록 하였다.

 

그러나 application이나 구조에 따라서는 중요한 코드가 model에 포함되어 있지 않거나, post-process코드가 성능에 큰 영향을 끼쳐서 중요할 경우에는 파일을 암호화하는 것보다 code를 암호화하는 것이 필요하다.

 

code를 encryption할 수 있으나, 여기서는 python code를 c/c++을 compile한 것과 같이 native binary library로 만들고자 한다.

python에서는 아주 간단하게 binary로 compile할 수 있는 방법을 제공하고 있는데, 이 때 확장자는 .pyc 형태로 제공된다. 그러나 이 pyc 형태의 binary는 손쉽게 decomplie하다고 알려져있다.

 

본문에서는 cython을 이용하여 python script를 binary library로 export하는 방법에 대해 소개한다.

 

먼저 cython을 설치한다.

 

pip install cython

 

그리고 cython을 이용하여 build를 하기 위해 build 정보를 python script로 작성한다. (compile.py)

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [
    Extension("mymodule1",  ["mymodule1.py"]),
    Extension("mymodule2",  ["mymodule2.py"]),
    ''' your modules that need be compiled '''
    ]
    
setup(
    name = 'My Program',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)

위의 코드를 간단하게 설명하면, compile하고자 하는 python file(.py)을 ext_modules에 추가한다.

그리고 setup tool에서 cmdclass에 build_ext를 추가하고, 이때 사용될 util로 cython의 module을 이용한다.

 

자세한 정보는 docs를 참고해보는 것을 추천한다.

docs.python.org/3/distutils/setupscript.html

cython.readthedocs.io/en/latest/src/reference/compilation.html#compiling-with-distutils

 

2. Writing the Setup Script — Python 3.9.1 documentation

2. Writing the Setup Script The setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the var

docs.python.org

 

setup script를 만든 뒤에는 terminal에서 아래와 같이 build를 할 수 있다.

python compile.py build_ext --inplace

 

build가 성공적으로 수행될 경우 ubunut 환경에서는 .c와 .so 파일이 생성된다.

.c 파일은 .so 파일을 build하기 위해 생성된 임시 파일이므로, so 파일이 정상적으로 build가 되었다면 삭제해도 된다.

이 때, 성공적으로 build가 되었다면 더 이상 .py 파일이 존재하지 않더라도 다른 python code에서 class나 function을 정상적으로 호출할 수 있다.

 

참고로 윈도우 환경에서는 .dll이 아닌 .pyd 파일이 생성되며, cython의 build tool은 cross platform을 지원하지 않는다.