분산 교육

분산 훈련은 컴퓨팅 리소스 요구 사항(예: CPU, RAM)이 여러 컴퓨터에 분산되는 모델 훈련 유형입니다. 분산 훈련을 사용하면 더 큰 데이터 세트(최대 수십억 개의 예)에서 더 빠르게 훈련할 수 있습니다.

분산 훈련은 여러 모델이 병렬로 훈련되는 자동화된 하이퍼 매개변수 최적화 에도 유용합니다.

이 문서에서는 다음 방법을 배웁니다.

  • 분산 학습을 사용하여 TF-DF 모델을 학습합니다.
  • 분산 훈련을 사용하여 TF-DF 모델의 초매개변수를 조정합니다.

제한사항

현재 분산 교육은 다음에 대해 지원됩니다.

  • tfdf.keras.DistributedGradientBoostedTreesModel 을 사용하여 Gradient Boosted Trees 모델을 훈련합니다. 분산형 그래디언트 부스팅 트리 모델은 비분산형 모델과 동일합니다.
  • 모든 TF-DF 모델 유형에 대한 하이퍼 매개변수 검색.

분산 교육을 활성화하는 방법

이 섹션에는 분산 교육을 활성화하는 단계가 나열되어 있습니다. 전체 예를 보려면 다음 섹션을 참조하세요.

ParameterServerStrategy 범위

모델과 데이터 세트는 ParameterServerStrategy 범위에 정의됩니다.

strategy = tf.distribute.experimental.ParameterServerStrategy(...)
with strategy.scope():
  model = tfdf.keras.DistributedGradientBoostedTreesModel()
  distributed_train_dataset = strategy.distribute_datasets_from_function(dataset_fn)
model.fit(distributed_train_dataset)

데이터 세트 형식

비분산 훈련과 마찬가지로 데이터 세트는 다음과 같이 제공될 수 있습니다.

  1. 유한한 텐서플로우 분산 데이터 세트 또는
  2. 호환되는 데이터 세트 형식 중 하나를 사용하는 데이터 세트 파일의 경로입니다.

샤딩된 파일을 사용하는 것은 유한 텐서플로우 분산 데이터 세트 접근 방식(1줄 대 ~20줄의 코드)을 사용하는 것보다 훨씬 간단합니다. 그러나 TensorFlow 데이터 세트 접근 방식만이 TensorFlow 사전 처리를 지원합니다. 파이프라인에 사전 처리가 포함되어 있지 않은 경우 샤딩된 데이터 세트 옵션이 권장됩니다.

두 경우 모두 데이터세트 읽기를 효율적으로 배포하려면 데이터세트를 여러 파일로 분할해야 합니다.

작업자 설정

주요 프로세스는 TensorFlow 모델을 정의하는 Python 코드를 실행하는 프로그램입니다. 이 프로세스는 과도한 계산을 실행하지 않습니다. 효과적인 훈련 계산은 작업자 가 수행합니다. 작업자는 TensorFlow 매개변수 서버를 실행하는 프로세스입니다.

Chief는 작업자의 IP 주소로 구성되어야 합니다. 이는 TF_CONFIG 환경 변수를 사용하거나 ClusterResolver 생성하여 수행할 수 있습니다. 자세한 내용은 ParameterServerStrategy를 사용한 매개변수 서버 교육을 참조하세요.

TensorFlow의 ParameterServerStrategy는 "작업자"와 "매개변수 서버"라는 두 가지 유형의 작업자를 정의합니다. TensorFlow에서는 각 작업자 유형 중 하나 이상이 인스턴스화되어야 합니다. 그러나 TF-DF는 "작업자"만 사용합니다. 따라서 하나의 "매개변수 서버"를 인스턴스화해야 하지만 TF-DF에서는 사용되지 않습니다. 예를 들어 TF-DF 교육 구성은 다음과 같습니다.

  • 1 수석
  • 50명의 노동자
  • 1 매개변수 서버

작업자는 TensorFlow Decision Forests의 커스텀 학습 작업에 액세스해야 합니다. 액세스를 활성화하는 두 가지 옵션이 있습니다.

  1. 사전 구성된 TF-DF C++ 매개변수 서버 //third_party/tensorflow_decision_forests/tensorflow/distribute:tensorflow_std_server 사용합니다.
  2. tf.distribute.Server() 를 호출하여 매개변수 서버를 생성하세요. 이 경우 TF-DF를 import tensorflow_decision_forests 가져와야 합니다.

이 섹션에서는 분산 학습 구성의 전체 예를 보여줍니다. 더 많은 예시를 보려면 TF-DF 단위 테스트를 확인하세요.

예: 데이터 세트 경로에 대한 분산 교육

호환되는 데이터세트 형식 중 하나를 사용하여 데이터세트를 분할된 파일 세트로 나눕니다. 예를 들어 /path/to/dataset/train-<5 digit index>-of-<total files> 같이 파일 이름을 지정하는 것이 좋습니다.

/path/to/dataset/train-00000-of-00100
/path/to/dataset/train-00001-of-00005
/path/to/dataset/train-00002-of-00005
...

효율성을 최대화하려면 파일 수가 작업자 수의 10배 이상이어야 합니다. 예를 들어 100명의 작업자를 대상으로 훈련하는 경우 데이터세트가 최소 1000개 이상의 파일로 나누어져 있는지 확인하세요.

그러면 다음과 같은 샤딩 표현식을 사용하여 파일을 참조할 수 있습니다.

  • /경로/대상/데이터세트/train@1000
  • /경로/대상/데이터세트/train@*

분산 훈련은 다음과 같이 수행됩니다. 이 예에서 데이터 세트는 TensorFlow 예제의 TFRecord( tfrecord+tfe 키로 정의됨)로 저장됩니다.

import tensorflow_decision_forests as tfdf
import tensorflow as tf

strategy = tf.distribute.experimental.ParameterServerStrategy(...)

with strategy.scope():
  model = tfdf.keras.DistributedGradientBoostedTreesModel()

model.fit_on_dataset_path(
    train_path="/path/to/dataset/train@1000",
    label_key="label_key",
    dataset_format="tfrecord+tfe")

print("Trained model")
model.summary()

예: 유한한 TensorFlow 분산 데이터 세트에 대한 분산 학습

TF-DF는 분산된 유한 작업자 분할 TensorFlow 데이터 세트를 기대합니다.

  • 분산형 : 분산되지 않은 데이터세트는 strategy.distribute_datasets_from_function 에 래핑됩니다.
  • finite : 데이터세트는 각 예시를 정확히 한 번 읽어야 합니다. 데이터세트에는 repeat 지침이 포함되어서는 됩니다.
  • Worker-sharded : 각 작업자는 데이터 세트의 별도 부분을 읽어야 합니다.

예는 다음과 같습니다.

import tensorflow_decision_forests as tfdf
import tensorflow as tf


def dataset_fn(context, paths):
  """Create a worker-sharded finite dataset from paths.

  Like for non-distributed training, each example should be visited exactly
  once (and by only one worker) during the training. In addition, for optimal
  training speed, the reading of the examples should be distributed among the
  workers (instead of being read by a single worker, or read and discarded
  multiple times).

  In other words, don't add a "repeat" statement and make sure to shard the
  dataset at the file level and not at the example level.
  """

  # List the dataset files
  ds_path = tf.data.Dataset.from_tensor_slices(paths)

  # Make sure the dataset is used with distributed training.
  assert context is not None


  # Split the among the workers.
  #
  # Note: The "shard" is applied on the file path. The shard should not be
  # applied on the examples directly.
  # Note: You cannot use 'context.num_input_pipelines' with ParameterServerV2.
  current_worker = tfdf.keras.get_worker_idx_and_num_workers(context)
  ds_path = ds_path.shard(
      num_shards=current_worker.num_workers,
      index=current_worker.worker_idx)

  def read_csv_file(path):
    """Reads a single csv file."""

    numerical = tf.constant([0.0], dtype=tf.float32)
    categorical_string = tf.constant(["NA"], dtype=tf.string)
    csv_columns = [
        numerical,  # feature 1
        categorical_string,  # feature 2
        numerical,  # feature 3
        # ... define the features here.
    ]
    return tf.data.experimental.CsvDataset(path, csv_columns, header=True)

  ds_columns = ds_path.interleave(read_csv_file)

  # We assume a binary classification label with the following possible values.
  label_values = ["<=50K", ">50K"]

  # Convert the text labels into integers:
  # "<=50K" => 0
  # ">50K" => 1
  init_label_table = tf.lookup.KeyValueTensorInitializer(
      keys=tf.constant(label_values),
      values=tf.constant(range(label_values), dtype=tf.int64))
  label_table = tf.lookup.StaticVocabularyTable(
      init_label_table, num_oov_buckets=1)

  def extract_label(*columns):
    return columns[0:-1], label_table.lookup(columns[-1])

  ds_dataset = ds_columns.map(extract_label)

  # The batch size has no impact on the quality of the model. However, a larger
  # batch size generally is faster.
  ds_dataset = ds_dataset.batch(500)
  return ds_dataset


strategy = tf.distribute.experimental.ParameterServerStrategy(...)
with strategy.scope():
  model = tfdf.keras.DistributedGradientBoostedTreesModel()

  train_dataset = strategy.distribute_datasets_from_function(
      lambda context: dataset_fn(context, [...list of csv files...])
  )

model.fit(train_dataset)

print("Trained model")
model.summary()

예: 데이터세트 경로의 분산 하이퍼 매개변수 조정

데이터 세트 경로의 분산 하이퍼 매개변수 조정은 분산 학습과 유사합니다. 유일한 차이점은 이 옵션이 비분산 모델과 호환된다는 것입니다. 예를 들어 (비분산) Gradient Boosted Trees 모델의 하이퍼 매개변수 조정을 분산할 수 있습니다.

with strategy.scope():
  tuner = tfdf.tuner.RandomSearch(num_trials=30, use_predefined_hps=True)
  model = tfdf.keras.GradientBoostedTreesModel(tuner=tuner)

training_history = model.fit_on_dataset_path(
  train_path=train_path,
  label_key=label,
  dataset_format="csv",
  valid_path=test_path)

logging.info("Trained model:")
model.summary()

예: 단위 테스트

분산 교육을 단위 테스트하려면 모의 작업자 프로세스를 생성하면 됩니다. 자세한 내용은 TF-DF 단위 테스트_create_in_process_tf_ps_cluster 메서드를 참조하세요.