티스토리 뷰

반응형
[딥러닝] Tensorflow에서 데이터로더 병렬처리 방법

개요

tensorflow에서 sequence 데이터로더를 사용하여 학습할 때, 데이터로더 처리 시간이 길어 gpu 사용률(Volatile GPU-Util)이 낮은 경우가 있다. gpu 사용률이 낮은건 다양한 이유가 있지만, 그 중 cpu 처리 속도가 느려 데이터를 로드하는 시간이 길어 학습 연산하는 gpu가 놀고 있는 경우도 있다. 이런 경우에는 학습 시간이 오래 걸리기 때문에, 데이터를 불러오는 시간을 줄여야 한다. 이 때, tensorflow에서 지원하는 OrderedEnqueuer를 사용하면 sequence를 병렬처리하여 시간을 단축시킬 수 있다.

OrderedEnqueuer 사용법

Sequence 데이터로더 생성

Sequence를 상속받아 Dataloader 클래스를 생성한다. 아래는 테스트를 위해 길이가 10인 랜덤한 시간(1~2초)을 sleep한 후에 return 하는 loader를 생성하였다.

import time, random, datetime
import numpy as np
import tensorflow as tf

class DataLoader(tf.keras.utils.Sequence):
    def __len__(self):
        return 10
    def __getitem__(self, i):
        time.sleep(random.randint(1,2))
        #you could add a print here to see that it's out of order
        return i

데이터 로더의 시간 측정

병렬처리할 cpu 코어 수를 workers 파라미터에 지정한다.

위에서 만든 DataLoader를 OrderedEnqueuer로 wrapping해 주고 데이터 gen을 만든다.

총 30번 로더를 호출하여 걸리는 시간을 측정해 본다.

def test(workers):
    enq = tf.keras.utils.OrderedEnqueuer(DataLoader())
    enq.start(workers = workers)
    gen = enq.get()

    results = []
    start = datetime.datetime.now()
    for i in range(30):
        results.append(next(gen))
    enq.stop()
    print('test with', workers, 'workers took', datetime.datetime.now() - start)
    print("results:", results)

Results

test함수를 호출할 때, workers의 수를 다르게 한 경우 각각 시간을 비교하면 아래와 같다. 1개로 할 때는 약 49초, 8개로 로드 할 때에는 약 9초로 훨씬 빨라진다. 병렬처리를 하더라도 데이터의 순서는 바뀌지 않고 원하는 대로 append 되어진걸 확인 할 수 있다.

test(1)
# test with 1 workers took 0:00:49.095993
# results: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

test(8)
# test with 8 workers took 0:00:09.029947
# results: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

참고자료

[1] https://stackoverflow.com/questions/59213040/is-the-order-of-batches-guaranteed-in-keras-orderedenqueuer, stackoverflow

[2] https://www.tensorflow.org/api_docs/python/tf/keras/utils/OrderedEnqueuer, tensorflow API

반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday