기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
TensorFlow
자체 TensorFlow 모델을 SageMaker AI로 가져오고 SageMaker 훈련 컴파일러를 사용하여 훈련 작업을 실행합니다.
TensorFlow 모델
SageMaker 훈련 컴파일러는 네이티브 TensorFlow API 또는 고급 Keras API를 기반으로 구축된 모델 훈련 워크로드를 자동으로 최적화합니다.
작은 정보
입력 데이터 세트를 사전 처리하려면 정적 입력 셰이프를 사용해야 합니다. 동적 입력 셰이프는 모델의 리컴파일을 시작하고 총 훈련 시간을 늘릴 수 있습니다.
Keras 사용 (권장)
최상의 컴파일러 가속을 위해서는 TensorFlow Keras(tf.keras.Model
단일 GPU 훈련용
훈련 스크립트에서 추가로 변경해야 할 사항은 없습니다.
Keras 미사용
SageMaker 훈련 컴파일러는 TensorFlow에서의 빠른 실행을 지원하지 않습니다. 따라서 컴파일러 가속을 활용하려면 TensorFlow 함수 데코레이터(@tf.function
)로 모델 및 훈련 루프를 래핑해야 합니다.
SageMaker 훈련 컴파일러는 그래프 수준 최적화를 수행하고 데코레이터를 사용하여 TensorFlow 함수가 그래프 모드
단일 GPU 훈련용
TensorFlow 2.0 이상에서는 기본적으로 즉시 실행 기능이 켜져 있으므로 TensorFlow 모델을 구성하는 데 사용하는 모든 함수 앞에 @tf.function
데코레이터를 추가해야 합니다.
Hugging Face 변환기를 사용한 TensorFlow 모델
Hugging Face 변환기HuggingFace
컴파일러 구성 클래스와 함께 SageMaker AI 예측기를 사용하여 훈련 스크립트를 실행할 수 있습니다SageMaker 훈련 컴파일러로 TensorFlow 훈련 작업 실행.
SageMaker 훈련 컴파일러는 네이티브 TensorFlow API 또는 고급 Keras API를 기반으로 구축된 모델 훈련 워크로드를 자동으로 최적화합니다(예: TensorFlow 변환기 모델).
작은 정보
훈련 스크립트에서 변환기를 사용하여 NLP 모델용 토크나이저를 만들 때는 padding='max_length'
를 지정하여 반드시 정적 입력 텐서 셰이프를 사용해야 합니다. 배치에서 가장 긴 시퀀스에 패딩하면 각 훈련 배치의 텐서 쉐이프가 변경될 수 있으므로 padding='longest'
를 사용하지 마세요. 동적 입력 셰이프는 모델의 리컴파일을 시작하고 총 훈련 시간을 늘릴 수 있습니다. 변환기 토크나이저의 패딩 옵션에 대한 추가 정보는 Hugging Face 변환기 설명서
Keras 사용
최상의 컴파일러 가속을 위해서는 TensorFlow Keras(tf.keras.Model
단일 GPU 훈련용
훈련 스크립트에서 추가로 변경해야 할 사항은 없습니다.
분산형 훈련용
SageMaker 훈련 컴파일러 가속화는 tf.distribute.Strategy.scope()
-
올바른 분산형 훈련 전략을 선택하세요.
-
단일 노드 멀티 GPU의 경우
tf.distribute.MirroredStrategy
을 사용하여 전략을 설정합니다.strategy = tf.distribute.MirroredStrategy()
-
여러 노드 멀티 GPU의 경우 전략을 만들기 전에 다음 코드를 추가하여 TensorFlow 분산형 훈련 구성을 올바르게 설정하세요.
def set_sm_dist_config(): DEFAULT_PORT = '8890' DEFAULT_CONFIG_FILE = '/opt/ml/input/config/resourceconfig.json' with open(DEFAULT_CONFIG_FILE) as f: config = json.loads(f.read()) current_host = config['current_host'] tf_config = { 'cluster': { 'worker': [] }, 'task': {'type': 'worker', 'index': -1} } for i, host in enumerate(config['hosts']): tf_config['cluster']['worker'].append("%s:%s" % (host, DEFAULT_PORT)) if current_host == host: tf_config['task']['index'] = i os.environ['TF_CONFIG'] = json.dumps(tf_config) set_sm_dist_config()
tf.distribute.MultiWorkerMirroredStrategy
를 사용하여 전략을 설정합니다.strategy = tf.distribute.MultiWorkerMirroredStrategy()
-
-
선택한 전략을 사용하여 모델을 래핑합니다.
with strategy.scope(): # create a model and do fit
Keras 미사용
Keras 없이 TensorFlow를 사용하여 사용자 지정 훈련 루프가 있는 사용자 지정 모델을 가져오려면 TensorFlow 함수 데코레이터(@tf.function
)로 모델과 훈련 루프를 래핑하여 컴파일러 가속을 활용해야 합니다.
SageMaker 훈련 컴파일러는 그래프 수준 최적화를 수행하고 데코레이터를 사용하여 TensorFlow 함수가 그래프 모드에서 실행되도록 설정되어 있는지 확인합니다.
단일 GPU 훈련용
TensorFlow 2.0 이상에서는 기본적으로 즉시 실행 기능이 켜져 있으므로 TensorFlow 모델을 구성하는 데 사용하는 모든 함수 앞에 @tf.function
데코레이터를 추가해야 합니다.
분산형 훈련용
분산형 훈련을 위해 Keras를 사용하는 데 필요한 변경 사항 외에도 각 GPU에서 실행되는 함수에 @tf.function
로 주석을 달고 GPU 간 통신 함수에는 주석을 달지 않도록 해야 합니다. 훈련 코드 예제는 다음과 같아야 합니다.
@tf.function() def compiled_step(inputs, outputs): with tf.GradientTape() as tape: pred=model(inputs, training=True) total_loss=loss_object(outputs, pred)/args.batch_size gradients=tape.gradient(total_loss, model.trainable_variables) return total_loss, pred, gradients def train_step(inputs, outputs): total_loss, pred, gradients=compiled_step(inputs, outputs) if args.weight_decay > 0.: gradients=[g+v*args.weight_decay for g,v in zip(gradients, model.trainable_variables)] optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss.update_state(total_loss) train_accuracy.update_state(outputs, pred) @tf.function() def train_step_dist(inputs, outputs): strategy.run(train_step, args= (inputs, outputs))
참고로 이 지침은 단일 노드 멀티 GPU와 여러 노드 멀티 GPU 모두에 사용할 수 있습니다.