본문으로 건너뛰기
기술 노트 목록

TensorFlow 분산 학습 (2025-08 검수)

AI/TensorFlow. 2024-12-13에 씀. 7분 분량

AI, TensorFlow

TensorFlow 분산 학습 (2025-08 검수)

2025-08 NOTE: 전략 API 내용은 2.17 → 최신 안정 버전에서도 동일 핵심 패턴. 추가 참고: (1) jit_compile=True로 XLA 가속 시 통신 경계(AllReduce) 직전 그래프 최적화 가능, (2) 다중 노드 환경에서 TF_CONFIG + 동일 Python 버전/패키지 해시 고정, (3) NCCL 환경 변수 (NCCL_DEBUG=INFO, NCCL_P2P_DISABLE=1 등)로 통신 병목 디버깅.

개요

TensorFlow의 tf.distribute.Strategy API를 사용하여 여러 GPU, 여러 장비, 또는 TPU에서 모델 학습을 분산하는 방법을 다룹니다.

1. 분산 전략 (Distribution Strategies)

TensorFlow는 다양한 분산 학습 시나리오를 지원하는 여러 전략을 제공합니다.

tf.distribute.MirroredStrategy

  • 용도: 단일 장비 내의 여러 GPU에서 동기식 분산 학습.
  • 작동 방식:
    • 모든 변수가 각 GPU에 미러링(복제)됩니다.
    • 각 GPU는 입력 데이터의 일부를 처리합니다.
    • 그래디언트는 모든 GPU에서 합산(all-reduce)된 후 각 GPU의 모델 복사본에 동일하게 적용됩니다.
  • 장점: 구현이 비교적 간단하고, 단일 장비에서 효율적입니다.
import tensorflow as tf
from tensorflow import keras

# MirroredStrategy 생성
strategy = tf.distribute.MirroredStrategy()
# 특정 GPU 지정: strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])

print(f'Number of devices: {strategy.num_replicas_in_sync}')

# 전략 범위 내에서 모델 생성 및 컴파일
with strategy.scope():
    # 모델 정의 (예시)
    model = keras.Sequential([
        keras.layers.Dense(128, activation='relu', input_shape=(784,)),
        keras.layers.Dense(10, activation='softmax')
    ])
    
    model.compile(
        optimizer=keras.optimizers.Adam(),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy']
    )

# 데이터셋 준비 (전역 배치 크기 사용)
# BATCH_SIZE_PER_REPLICA = 64
# GLOBAL_BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync
# train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(GLOBAL_BATCH_SIZE)
# test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(GLOBAL_BATCH_SIZE)

# 모델 학습
# model.fit(train_dataset, epochs=5, validation_data=test_dataset)

tf.distribute.MultiWorkerMirroredStrategy

  • 용도: 여러 장비(워커)에 걸쳐 동기식 분산 학습. 각 장비는 여러 GPU를 가질 수 있습니다.
  • 작동 방식: MirroredStrategy와 유사하지만, 여러 장비로 확장됩니다. TF_CONFIG 환경 변수를 통해 클러스터 정보를 설정해야 합니다.
  • 장점: 대규모 모델 및 데이터셋 학습에 적합합니다.
# TF_CONFIG 설정 (예시)
# import json
# import os
# os.environ['TF_CONFIG'] = json.dumps({
#     'cluster': {
#         'worker': ["host1:port", "host2:port", "host3:port"]
#     },
#     'task': {'type': 'worker', 'index': 0} # 각 워커마다 index 변경
# })

# MultiWorkerMirroredStrategy 생성
# strategy = tf.distribute.MultiWorkerMirroredStrategy()

# 이후 코드는 MirroredStrategy와 유사 (strategy.scope() 사용)

tf.distribute.TPUStrategy

  • 용도: Google TPU(Tensor Processing Unit)에서 학습.
  • 작동 방식: TPU 하드웨어에 최적화된 방식으로 분산 학습을 수행합니다.
  • 장점: TPU의 강력한 연산 능력을 활용하여 매우 빠른 학습이 가능합니다.
# TPU 초기화 및 전략 생성 (Colab 예시)
# resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') # Colab에서 TPU 자동 감지
# tf.config.experimental_connect_to_cluster(resolver)
# tf.tpu.experimental.initialize_tpu_system(resolver)
# strategy = tf.distribute.TPUStrategy(resolver)

# 이후 코드는 MirroredStrategy와 유사 (strategy.scope() 사용)

tf.distribute.ParameterServerStrategy

  • 용도: 여러 장비에 걸쳐 비동기식 또는 동기식 파라미터 서버 학습.
  • 작동 방식:
    • 모델 변수는 파라미터 서버에 저장됩니다.
    • 워커는 파라미터 서버에서 변수를 가져와 학습을 수행하고, 그래디언트를 파라미터 서버로 보냅니다.
  • 장점: 매우 큰 모델(단일 장비 메모리에 맞지 않는) 학습에 유용하며, 네트워크 대역폭 요구 사항이 낮을 수 있습니다.
  • 주의: 비동기 업데이트는 학습 안정성에 영향을 줄 수 있습니다.
# TF_CONFIG 설정 (파라미터 서버 및 워커 포함)
# strategy = tf.distribute.experimental.ParameterServerStrategy()
# 이후 코드는 MirroredStrategy와 유사 (strategy.scope() 사용)

tf.distribute.CentralStorageStrategy

  • 용도: 단일 장비, 다중 GPU 환경에서 변수를 CPU에 저장하고 연산만 GPU에서 수행.
  • 작동 방식: 변수는 CPU에 중앙 집중식으로 저장되고, 각 GPU는 연산에 필요한 변수를 가져와 사용합니다.
  • 장점: GPU 메모리가 부족할 때 유용할 수 있지만, 일반적으로 MirroredStrategy보다 성능이 낮습니다.
# CentralStorageStrategy 생성
# strategy = tf.distribute.experimental.CentralStorageStrategy()
# strategy = tf.distribute.experimental.CentralStorageStrategy(compute_devices=["/gpu:0", "/gpu:1"], parameter_device="/cpu:0")

# 이후 코드는 MirroredStrategy와 유사 (strategy.scope() 사용)

2. tf.distribute.Strategy 사용법

1. 전략 객체 생성

  • 사용할 시나리오에 맞는 전략 객체를 선택하여 생성합니다.

2. strategy.scope() 내에서 모델 구축

  • 모델 생성, 옵티마이저 생성, 메트릭 생성 등 분산되어야 하는 모든 TensorFlow 객체는 strategy.scope() 컨텍스트 내에서 정의되어야 합니다.
    with strategy.scope():
        model = create_my_model()
        optimizer = keras.optimizers.Adam()
        # 메트릭 등

3. 데이터셋 준비

  • 전역 배치 크기 (Global Batch Size): BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync로 설정합니다.
  • tf.data.Dataset을 사용하여 입력 파이프라인을 구성합니다.
  • Dataset.batch(GLOBAL_BATCH_SIZE)를 사용합니다.
  • Dataset.shard()나 experimental_distribute_dataset은 Keras fit 메서드 사용 시 자동으로 처리됩니다. 사용자 정의 학습 루프에서는 명시적으로 처리해야 할 수 있습니다.

4. 모델 학습 (Keras fit 사용)

  • Keras의 model.fit() 메서드는 대부분의 분산 전략과 호환됩니다.
  • 별도의 코드 수정 없이 분산 학습을 수행할 수 있습니다.

5. 사용자 정의 학습 루프 (Custom Training Loop)

  • 더 세밀한 제어가 필요한 경우 사용자 정의 학습 루프를 작성할 수 있습니다.
  • strategy.run(): 각 복제본에서 함수를 실행합니다.
  • strategy.reduce(): 여러 복제본의 값을 집계합니다.
# 사용자 정의 학습 루프 예시 (MirroredStrategy)
# with strategy.scope():
#     # 모델, 옵티마이저, 손실 함수, 메트릭 정의
#     ...

# def train_step(inputs):
#     images, labels = inputs
#     with tf.GradientTape() as tape:
#         predictions = model(images, training=True)
#         per_example_loss = loss_object(labels, predictions)
#         # 전역 배치 크기로 정규화된 손실 계산
#         loss = tf.nn.compute_average_loss(per_example_loss, global_batch_size=GLOBAL_BATCH_SIZE)
    
#     gradients = tape.gradient(loss, model.trainable_variables)
#     optimizer.apply_gradients(zip(gradients, model.trainable_variables))
#     train_accuracy.update_state(labels, predictions)
#     return loss

# @tf.function
# def distributed_train_step(dataset_inputs):
#     per_replica_losses = strategy.run(train_step, args=(dataset_inputs,))
#     return strategy.reduce(tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)

# for epoch in range(EPOCHS):
#     total_loss = 0.0
#     num_batches = 0
#     for x in train_dist_dataset: # strategy.experimental_distribute_dataset(train_dataset)
#         total_loss += distributed_train_step(x)
#         num_batches += 1
#     train_loss = total_loss / num_batches
#     # ... (로그 출력, 메트릭 초기화 등)

3. TF_CONFIG 환경 변수

MultiWorkerMirroredStrategy 및 ParameterServerStrategy와 같이 여러 장비를 사용하는 전략에서는 TF_CONFIG 환경 변수를 설정하여 클러스터의 각 작업(task)에 대한 정보를 제공해야 합니다.

  • cluster: 클러스터의 모든 작업(워커, 파라미터 서버 등)의 주소와 포트를 정의합니다.
  • task: 현재 스크립트를 실행하는 작업의 유형(type)과 인덱스(index)를 정의합니다.

예시 TF_CONFIG (워커 2개):

워커 0:

{
    "cluster": {
        "worker": ["my-worker-0.example.com:2222", "my-worker-1.example.com:2222"]
    },
    "task": {"type": "worker", "index": 0}
}

워커 1:

{
    "cluster": {
        "worker": ["my-worker-0.example.com:2222", "my-worker-1.example.com:2222"]
    },
    "task": {"type": "worker", "index": 1}
}
  • 이 환경 변수는 각 워커 머신에서 TensorFlow 스크립트 실행 전에 설정되어야 합니다.

4. 저장 및 로딩

분산 전략을 사용하여 학습된 모델을 저장하고 로드하는 것은 일반적인 모델과 유사합니다.

  • model.save() 및 tf.keras.models.load_model():

    • strategy.scope() 외부에서 호출하는 것이 일반적입니다.
    • MirroredStrategy의 경우, 모든 복제본이 동일한 가중치를 가지므로 어떤 복제본에서 저장하든 동일합니다.
    • MultiWorkerMirroredStrategy의 경우, 일반적으로 수석 워커(chief worker, 보통 index 0)에서만 저장하도록 로직을 추가합니다.
      # if tf.distribute.get_strategy().cluster_resolver.task_type == 'worker' and \
      #    tf.distribute.get_strategy().cluster_resolver.task_id == 0:
      #     model.save(...)
  • 체크포인트:

    • tf.train.Checkpoint와 tf.train.CheckpointManager를 strategy.scope() 내에서 사용할 수 있습니다.
    • 저장 및 복원 시 모든 장치에서 동기화됩니다.

5. 팁 및 모범 사례

  • 배치 크기: 전역 배치 크기를 적절히 설정합니다. 너무 작으면 GPU 활용도가 낮아지고, 너무 크면 메모리 부족이나 학습 불안정을 유발할 수 있습니다.
  • 학습률: 전역 배치 크기가 커지면 학습률을 조정해야 할 수 있습니다 (예: 선형적으로 증가).
  • 데이터 파이프라인: tf.data를 사용하여 효율적인 입력 파이프라인을 구축하고, prefetch 및 AUTOTUNE을 활용합니다.
  • 작은 모델부터 시작: 분산 학습 설정을 테스트할 때는 간단하고 작은 모델부터 시작하여 점진적으로 복잡도를 높입니다.
  • 로그 및 디버깅: 각 워커의 로그를 확인하고, TensorBoard를 사용하여 학습 과정을 모니터링합니다.
  • 네트워크: MultiWorkerMirroredStrategy 사용 시 고속 네트워크 연결이 중요합니다.

테스트 코드

import tensorflow as tf
from tensorflow import keras
import numpy as np

def test_mirrored_strategy():
    """MirroredStrategy 테스트 (GPU가 2개 이상일 때 의미 있음)"""
    
    print("=== MirroredStrategy 테스트 ===\n")
    
    # 사용 가능한 GPU 수 확인
    gpus = tf.config.list_physical_devices('GPU')
    if len(gpus) < 1: # 테스트를 위해 1개 이상으로 변경
        print("GPU가 없어 MirroredStrategy 테스트를 실제 분산 없이 진행합니다.")
        # CPU에서 실행되도록 강제 (테스트 목적)
        strategy = tf.distribute.OneDeviceStrategy(device="/cpu:0")
    else:
        print(f"사용 가능한 GPU 수: {len(gpus)}")
        strategy = tf.distribute.MirroredStrategy()

    print(f'Number of devices: {strategy.num_replicas_in_sync}')

    # 더미 데이터 및 모델
    BATCH_SIZE_PER_REPLICA = 16
    GLOBAL_BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync
    
    x_data = np.random.random((100, 5))
    y_data = np.random.randint(0, 2, 100)
    
    dataset = tf.data.Dataset.from_tensor_slices((x_data, y_data)).batch(GLOBAL_BATCH_SIZE)

    with strategy.scope():
        model = keras.Sequential([
            keras.layers.Dense(8, activation='relu', input_shape=(5,)),
            keras.layers.Dense(1, activation='sigmoid')
        ])
        model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

    # 학습
    history = model.fit(dataset, epochs=3, verbose=1)
    
    assert 'loss' in history.history, "학습 이력에 손실이 없습니다."
    print("✓ MirroredStrategy (또는 OneDeviceStrategy) 학습 성공")
    
    # 모델 저장 테스트
    model_path = "test_distributed_model"
    model.save(model_path)
    loaded_model = keras.models.load_model(model_path)
    assert loaded_model is not None, "분산 모델 저장/로딩 실패"
    print("✓ 분산 모델 저장/로딩 성공")
    
    # 테스트 후 디렉토리 삭제
    import shutil
    shutil.rmtree(model_path)


if __name__ == "__main__":
    test_mirrored_strategy()
    print("\n분산 학습 테스트 완료.")

주의사항

  1. strategy.scope(): 모델, 옵티마이저, 메트릭 등 분산 대상 객체는 반드시 이 범위 내에서 생성해야 합니다.
  2. 데이터 로딩: tf.data.Dataset을 사용하고 전역 배치 크기를 올바르게 설정해야 합니다.
  3. TF_CONFIG: 멀티 워커 환경에서는 정확한 TF_CONFIG 설정이 필수적입니다.
  4. 디버깅: 분산 환경에서의 디버깅은 단일 환경보다 복잡할 수 있습니다. 각 워커의 로그를 면밀히 확인해야 합니다.

다음 단계

다른 기술 노트 보기