Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ko/guide/migrate/tpu_estimator.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

이 가이드는 TPU 에서 실행되는 워크플로를 TensorFlow 1의 TPUEstimator API에서 TensorFlow 2의 TPUStrategy API로 마이그레이션하는 방법을 보여줍니다.

  • TensorFlow 1에서 tf.compat.v1.estimator.tpu.TPUEstimator API를 사용하면 모델을 훈련 및 평가할 수 있을 뿐만 아니라 추론을 수행하고 (클라우드) TPU에서 모델(제공용)을 저장할 수 있습니다.

  • Tensorflow 2에서, to perform synchronous training on TPUs and TPU Pods (a collection of TPU devices connected by dedicated high-speed network interfaces), you need to use a TPU distribution strategy—tf.distribute.TPUStrategy. The strategy can work with the Keras APIs—including for model building (tf.keras.Model), optimizers (tf.keras.optimizers.Optimizer), and training (Model.fit)—as well as a custom training loop (with tf.function and tf.GradientTape).

종단 간 TensorFlow 2 예제는 TPU 사용 가이드(즉, TPU 의 분류 섹션)와 TPU의 BERT를 사용하여 GLUE 작업 해결 자습서를 확인하세요. TPUStrategy 포함한 모든 TensorFlow 배포 전략을 다루는 Distributed 교육 가이드가 유용할 수 있습니다.

설정

데모용으로 가져오기 및 간단한 데이터세트로 시작합니다.

import tensorflow as tf import tensorflow.compat.v1 as tf1
features = [[1., 1.5]] labels = [[0.3]] eval_features = [[4., 4.5]] eval_labels = [[0.8]]

TensorFlow 1: TPUEstimator를 사용하여 TPU에서 모델 구동

이 가이드 섹션에서는 TensorFlow 1에서 tf.compat.v1.estimator.tpu.TPUEstimator 를 사용하여 교육 및 평가를 수행하는 방법을 보여줍니다.

TPUEstimator 를 사용하려면 먼저 몇 가지 함수를 정의합니다. 학습 데이터에 대한 입력 함수, 평가 데이터에 대한 평가 입력 함수, 학습 작업이 기능 및 레이블로 정의되는 방식을 TPUEstimator

def _input_fn(params): dataset = tf1.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.repeat() return dataset.batch(params['batch_size'], drop_remainder=True) def _eval_input_fn(params): dataset = tf1.data.Dataset.from_tensor_slices((eval_features, eval_labels)) dataset = dataset.repeat() return dataset.batch(params['batch_size'], drop_remainder=True) def _model_fn(features, labels, mode, params): logits = tf1.layers.Dense(1)(features) loss = tf1.losses.mean_squared_error(labels=labels, predictions=logits) optimizer = tf1.train.AdagradOptimizer(0.05) train_op = optimizer.minimize(loss, global_step=tf1.train.get_global_step()) return tf1.estimator.tpu.TPUEstimatorSpec(mode, loss=loss, train_op=train_op)

이러한 기능은 정의와 더불어, 생성 tf.distribute.cluster_resolver.TPUClusterResolver 클러스터 정보를 제공하며, tf.compat.v1.estimator.tpu.RunConfig 객체를. 정의한 모델 함수와 함께 이제 TPUEstimator 만들 수 있습니다. 여기에서는 체크포인트 절약을 건너뛰어 흐름을 단순화합니다. TPUEstimator 대한 훈련 및 평가 모두에 대한 배치 크기를 지정합니다.

cluster_resolver = tf1.distribute.cluster_resolver.TPUClusterResolver(tpu='') print("All devices: ", tf1.config.list_logical_devices('TPU'))
tpu_config = tf1.estimator.tpu.TPUConfig(iterations_per_loop=10) config = tf1.estimator.tpu.RunConfig( cluster=cluster_resolver, save_checkpoints_steps=None, tpu_config=tpu_config) estimator = tf1.estimator.tpu.TPUEstimator( model_fn=_model_fn, config=config, train_batch_size=8, eval_batch_size=8)

TPUEstimator.train 을 호출하여 모델 학습을 시작합니다.

estimator.train(_input_fn, steps=1)

그런 다음 TPUEstimator.evaluate 를 호출하여 평가 데이터를 사용하여 모델을 평가합니다.

estimator.evaluate(_eval_input_fn, steps=1)

TensorFlow 2: Keras Model.fit 및 TPUStrategy를 사용하여 TPU에서 모델 구동

TensorFlow 2에서 TPU 작업자를 교육하려면 모델 정의 및 교육/평가를 tf.distribute.TPUStrategy Model.fit 및 사용자 지정 훈련 루프( tf.functiontf.GradientTape )를 사용한 훈련에 대한 더 많은 예제는 TPU 사용 가이드를 참조하십시오.)

원격 클러스터에 연결하고 TPU 작업자를 초기화하려면 일부 초기화 작업을 수행해야 하므로 먼저 TPUClusterResolver 를 생성하여 클러스터 정보를 제공하고 클러스터에 연결합니다. (TPU 사용 가이드의 TPU 초기화 섹션에서 자세히 알아보세요.)

cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') tf.config.experimental_connect_to_cluster(cluster_resolver) tf.tpu.experimental.initialize_tpu_system(cluster_resolver) print("All devices: ", tf.config.list_logical_devices('TPU'))

다음으로, 데이터가 준비되면 TPUStrategy 를 만들고 이 전략의 범위에서 모델, 메트릭 및 옵티마이저를 정의합니다.

TPUStrategy 비슷한 훈련 속도를 얻으려면 tf.function 호출 중에 실행할 배치 수를 지정하고 성능에 중요하기 steps_per_execution 에서 Model.compile 대한 숫자를 선택해야 합니다. 이 인수는 TPUEstimator 에서 사용되는 iterations_per_loop 와 유사합니다. 사용자 지정 훈련 루프를 사용하는 경우 tf.function -ed 훈련 함수 내에서 여러 단계를 실행해야 합니다. 자세한 내용은 TPU 사용 가이드의 tf.function 섹션에서 여러 단계로 성능 향상 을 참조하세요.

tf.distribute.TPUStrategy 는 경계가 있는 동적 모양을 지원할 수 있으며, 이는 동적 모양 계산의 상한을 유추할 수 있는 경우입니다. 그러나 동적 모양은 정적 모양에 비해 약간의 성능 오버헤드를 유발할 수 있습니다. 따라서, 특히 훈련에서 가능하면 입력 모양을 정적으로 만드는 것이 일반적으로 권장됩니다. 스트림에 남아 있는 샘플 수가 배치 크기보다 작을 수 있으므로 동적 모양을 반환하는 일반적인 작업 중 하나는 tf.data.Dataset.batch(batch_size) 따라서 TPU에서 훈련할 때 최상의 훈련 성능을 위해 tf.data.Dataset.batch(..., drop_remainder=True)

dataset = tf.data.Dataset.from_tensor_slices( (features, labels)).shuffle(10).repeat().batch( 8, drop_remainder=True).prefetch(2) eval_dataset = tf.data.Dataset.from_tensor_slices( (eval_features, eval_labels)).batch(1, drop_remainder=True) strategy = tf.distribute.TPUStrategy(cluster_resolver) with strategy.scope(): model = tf.keras.models.Sequential([tf.keras.layers.Dense(1)]) optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05) model.compile(optimizer, "mse", steps_per_execution=10)

이것으로 훈련 데이터 세트로 모델을 훈련할 준비가 되었습니다.

model.fit(dataset, epochs=5, steps_per_epoch=10)

마지막으로 평가 데이터 세트를 사용하여 모델을 평가합니다.

model.evaluate(eval_dataset, return_dict=True)

다음 단계

TPUStrategy 에 대해 자세히 알아보려면 다음 리소스를 고려하세요.

훈련 사용자 지정에 대한 자세한 내용은 다음을 참조하십시오.

기계 학습을 위한 Google의 특수 ASIC인 TPU는 Google Colab , TPU Research CloudCloud TPU를 통해 사용할 수 있습니다.