기본 콘텐츠로 건너뛰기

Python 객체 저장 - pickle, pickletools

Python 객체 저장 - pickle, pickletools

pickle, pickletools 모듈 문서

pickle - Python object serialization

  • Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.
  • Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.
  • Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
  • Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This was the default protocol in Python 3.0–3.7.
  • Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. It is the default protocol starting with Python 3.8. Refer to PEP 3154 for information about improvements brought by protocol 4.
  • Protocol version 5 was added in Python 3.8. It adds support for out-of-band data and speedup for in-band data. Refer to PEP 574 for information about improvements brought by protocol 5.

pickletools — Tools for pickle developers

명령 실행 예시

아래 소스 코드를 실행하여 튜플 (1, 2)를 x.pickle 파일로 저장합니다.

from pickle import dump, load

t = (1, 2) 

with open('x.pickle', 'wb') as f: 
    dump(t, f) 

print(f'Write Done: {t}')

x.pickle 파일에 대한 pickle, pickletools 명령 실행 예시입니다.

$ python -m pickle x.pickle 
(1, 2) 
$ python -m pickletools x.pickle 
    0: \x80 PROTO 3 
    2: K BININT1 1 
    4: K BININT1 2 
    6: \x86 TUPLE2 
    7: q BINPUT 0 
    9: . STOP 
highest protocol among opcodes = 2

위에서 pickle은 x.pickle 파일에 저장되어 있는 객체를 복원하여 출력하고 pickletools는 x.pickle 파일을 파싱하여 출력합니다.

Keras 2와 3에서 Tokenizer 객체 저장 및 읽기 테스트

Tokenizer 객체의 pickle 파일은 Keras 2와 Keras 3 간에 호환되지 않습니다. 테스트를 통해서 그 이유를 파악해 봅니다.

아래 소스 코드는 Tokenizer 객체를 tokenizer.pkl 파일에 저장합니다.

from tensorflow.keras.preprocessing.text import Tokenizer 
from pickle import dump 

sample_texts = [ 
    '산악용 자전거' , 
    '자전거 전조등 후미등' , 
    '온라인 상품권' , 
    '온라인 상품 세트' 
] 

sample_tokenizer = Tokenizer() 
sample_tokenizer.fit_on_texts(sample_texts) 

dump(sample_tokenizer, open('tokenizer.pkl', 'wb'))

위 코드를 Keras 2에서 실행하여 tokenizer.pkl 파일을 생성하고 Keras 3에서 읽기를 시도합니다.

$ python -m pickle tokenizer.pkl 
... 
ModuleNotFoundError: No module named 'keras.src.preprocessing'

Keras 2에서 생성한 tokenizer.pkl 파일을 Keras 3에서 읽는 과정에서 오류가 발생했고 pickletools로 tokenizer.pkl 파일에 대하여 좀 더 자세한 정보를 출력해 봅니다.

$ python -m pickletools tokenizer.pkl 
     0: \x80 PROTO 4 
     2: \x95 FRAME 587 
    11: \x8c SHORT_BINUNICODE 'keras.src.preprocessing.text' 
    41: \x94 MEMOIZE (as 0) 
    42: \x8c SHORT_BINUNICODE 'Tokenizer' 
    53: \x94 MEMOIZE (as 1) 
    ...

이번에는 위 코드를 Keras 3에서 실행하여 tokenizer.pkl 파일을 생성하고 Keras 2에서 읽기를 시도합니다.

$ python -m pickle tokenizer.pkl 
... 
ModuleNotFoundError: No module named 'keras.src.legacy'

Keras 3에서 생성한 tokenizer.pkl 파일을 Keras 2에서 읽는 과정에서 오류가 발생했고 pickletools로 tokenizer.pkl 파일에 대하여 좀 더 자세한 정보를 출력해 봅니다.

python -m pickletools tokenizer.pkl 
     0: \x80 PROTO 4 
     2: \x95 FRAME 594 
    11: \x8c SHORT_BINUNICODE 'keras.src.legacy.preprocessing.text' 
    48: \x94 MEMOIZE (as 0) 
    49: \x8c SHORT_BINUNICODE 'Tokenizer' 
    60: \x94 MEMOIZE (as 1) 
    ...

Keras 2와 비교하여 Keras 3에서 Tokenizer를 저장하고 읽을 때 사용하는 모듈의 이름이 바뀌었고 이름 중에 legacy가 들어가 있습니다.

  • Keras 2: keras.src.preprocessing.text
  • Keras 3: keras.src.legacy.preprocessing.text

이것은 아마도 아래와 같이 Tokenizer 상태를 DEPRECATED로 바꾼 것과 관련이 있어 보입니다.

  • Tokenizer는 DEPRECATED 상태

※ 참고: preprocessing 모듈 전체가 DEPRECATED 상태

정리

  • Tokenizer 객체의 pickle 파일은 Keras 2와 Keras 3 간에 호환되지 않습니다. 호환되지 않는 이유는 Tokenizer 직렬화에 사용하는 Keras 모듈의 이름이 바뀌었기 때문이며 pickle 프로토콜 버전과는 관련이 없습니다.

Written with StackEdit.

댓글

이 블로그의 인기 게시물

Intel MKL 예제를 Microsoft Visual C++로 빌드하기

Intel MKL 예제를 Microsoft Visual C++로 빌드하기 인텔 프로세서 시스템에서 아래의 영역에 해당하는 수학 계산을 빠르게 수행하고자 한다면 Intel MKL 라이브러리를 사용할 수 있습니다. Linear Algebra Fast Fourier Transforms (FFT) Vector Statistics & Data Fitting Vector Math & Miscellaneous Solvers 이 문서는 Intel MKL 이 제공하는 예제 파일을 Microsoft Visual C++ 로 컴파일하고 링크하여 실행 파일을 만드는 과정을 소개합니다. 빌드 환경 다음은 이 문서를 작성하는 과정에서 Intel MKL 예제를 빌드하기 위하여 사용한 환경입니다. 시스템 운영체제: Windows 10 (64비트) 프로세서: Intel Core i7 설치 제품 IDE: Microsoft Visual Studio Community 2019 (version 16) 라이브러리: Intel Math Kernel Library 2019 Update 5 환경 변수 명령 프롬프트 창을 엽니다. 아래 스크립트를 실행하여 환경 변수 INCLUDE , LIB , 그리고 PATH 를 설정합니다. @echo off set CPRO_PATH=C:\Program Files (x86)\IntelSWTools\compilers_and_libraries\windows set MKLROOT=%CPRO_PATH%\mkl set REDIST=%CPRO_PATH%\redist set INCLUDE=%MKLROOT%\include;%INCLUDE% set LIB=%MKLROOT%\lib\intel64;%LIB% set PATH=%REDIST%\intel64\mkl;%PATH% REM for OpenMP intel thread set LIB=%CPRO_PATH%\compiler\lib...

Llama 3.2로 문장 생성 및 챗팅 완성 실습

Llama 3.2로 문장 생성 및 챗팅 완성 실습 Running Meta Llama on Linux 문서의 내용을 참고하여 Llama 3.2 1B 모델로 다음 두 가지 기능을 실습합니다. 문장 완성 챗팅 완성 실습 환경 Ubuntu 20.04.6 LTS Python 3.12.7 Llama3.2-1B, Llama3.2-1B-Instruct rustc 1.83.0 NVIDIA RTX 4090 24GB 프로그램 준비 실습에서 사용할 wget , md5sum 설치 sudo apt-get install wget sudo apt-get install md5sum NVIDIA GPU 설치 여부 확인 nvidia-smi 실습 디렉토리 만들기 mkdir llama3-demo cd llama3-demo git clone https://github.com/meta-llama/llama3.git Python 3.10 이상의 버전으로 가상환경 만들고 활성화 python -m venv llama-venv . llama-venv/bin/activate Rust 컴파일러 설치 How To Install Rust on Ubuntu 20.04 문서를 참고하여 Rust 컴파일러를 설치합니다. curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh 위 명령을 실행하면 아래와 같이 세 가지 선택 옵션이 나타나는데 그냥 엔터를 쳐서 1번 옵션으로 진행합니다. ... 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation 아래 명령을 실행하여 현재 쉘에 반영하고 설치된 컴파일러 버전을 확인합니다. source $HOME/.cargo/env rustc --version 의존 라이브러리 설치 pip install ...