TensorFlow.org पर देखें | Google Colab में चलाएं | GitHub पर स्रोत देखें | नोटबुक डाउनलोड करें |
यह मार्गदर्शिका दर्शाती है कि टीपीयू पर टीपीयू पर एम्बेडिंग प्रशिक्षण को टीपीयूएस्टिमेटर के साथ TPUEstimator के साथ embedding_column एपीआई से टीपीयूस्ट्रेटी के साथ TPUEmbedding लेयर एपीआई में कैसे माइग्रेट किया TPUStrategy ।
एम्बेडिंग (बड़े) मैट्रिसेस हैं। वे लुकअप टेबल हैं जो विरल फीचर स्पेस से घने वैक्टर तक मैप करते हैं। एम्बेडिंग कुशल और सघन प्रतिनिधित्व प्रदान करते हैं, जटिल समानताओं और सुविधाओं के बीच संबंधों को कैप्चर करते हैं।
TensorFlow में TPU पर प्रशिक्षण एम्बेडिंग के लिए विशेष समर्थन शामिल है। यह टीपीयू-विशिष्ट एम्बेडिंग समर्थन आपको एम्बेडिंग को प्रशिक्षित करने की अनुमति देता है जो एकल टीपीयू डिवाइस की मेमोरी से बड़ा होता है, और टीपीयू पर विरल और रैग्ड इनपुट का उपयोग करने के लिए।
- TensorFlow 1 में,
tf.compat.v1.estimator.tpu.TPUEstimatorएक उच्च स्तरीय API है जो TPU के साथ सेवा के लिए प्रशिक्षण, मूल्यांकन, भविष्यवाणी और निर्यात को समाहित करता है। इसमेंtf.compat.v1.tpu.experimental.embedding_columnके लिए विशेष समर्थन है। - इसे TensorFlow 2 में लागू करने के लिए, TensorFlow Recommenders'
tfrs.layers.embedding.TPUEmbeddingपरत का उपयोग करें। प्रशिक्षण और मूल्यांकन के लिए,tf.distribute.TPUStrategyवितरण रणनीति का उपयोग करें- tf.distribute.TPUStrategy- जो केरस एपीआई के साथ संगत है, उदाहरण के लिए, मॉडल बिल्डिंग (tf.keras.Model), ऑप्टिमाइज़र (tf.keras.optimizers.Optimizer), औरModel.fitयाtf.functionऔरtf.GradientTapeके साथ एक कस्टम प्रशिक्षण लूप के साथ प्रशिक्षण।
अतिरिक्त जानकारी के लिए, अतिरिक्त जानकारी के लिए tfrs.layers.embedding.TPUEmbedding परत का API दस्तावेज़, साथ ही tf.tpu.experimental.embedding.TableConfig और tf.tpu.experimental.embedding.FeatureConfig दस्तावेज़ देखें। tf.distribute.TPUStrategy के अवलोकन के लिए, वितरित प्रशिक्षण मार्गदर्शिका और टीपीयू का उपयोग करें मार्गदर्शिका देखें। यदि आप TPUStrategy से TPUEstimator में माइग्रेट कर रहे हैं, तो TPU माइग्रेशन गाइड देखें।
सेट अप
TensorFlow अनुशंसाकर्ताओं को स्थापित करके और कुछ आवश्यक पैकेज आयात करके प्रारंभ करें:
pip install tensorflow-recommenders
import tensorflow as tf
import tensorflow.compat.v1 as tf1
# TPUEmbedding layer is not part of TensorFlow.
import tensorflow_recommenders as tfrs
/tmpfs/src/tf_docs_env/lib/python3.6/site-packages/requests/__init__.py:104: RequestsDependencyWarning: urllib3 (1.26.8) or chardet (2.3.0)/charset_normalizer (2.0.11) doesn't match a supported version! RequestsDependencyWarning)
और प्रदर्शन उद्देश्यों के लिए एक साधारण डेटासेट तैयार करें:
features = [[1., 1.5]]
embedding_features_indices = [[0, 0], [0, 1]]
embedding_features_values = [0, 5]
labels = [[0.3]]
eval_features = [[4., 4.5]]
eval_embedding_features_indices = [[0, 0], [0, 1]]
eval_embedding_features_values = [4, 3]
eval_labels = [[0.8]]
TensorFlow 1: टीपीयू अनुमानक के साथ टीपीयू पर ट्रेन एम्बेडिंग
TensorFlow 1 में, आप tf.compat.v1.tpu.experimental.embedding_column API का उपयोग करके TPU एम्बेडिंग सेट करते हैं और tf.compat.v1.estimator.tpu.TPUEstimator के साथ TPU पर मॉडल का प्रशिक्षण/मूल्यांकन करते हैं।
इनपुट टीपीयू एम्बेडिंग टेबल के लिए शून्य से लेकर शब्दावली आकार तक के पूर्णांक हैं। इनपुट को tf.feature_column.categorical_column_with_identity के साथ श्रेणीबद्ध आईडी में एन्कोडिंग के साथ शुरू करें। key पैरामीटर के लिए "sparse_feature" का उपयोग करें, क्योंकि इनपुट सुविधाएं पूर्णांक-मूल्यवान हैं, जबकि num_buckets एम्बेडिंग तालिका ( 10 ) के लिए शब्दावली आकार है।
embedding_id_column = (
tf1.feature_column.categorical_column_with_identity(
key="sparse_feature", num_buckets=10))
इसके बाद, विरल श्रेणीबद्ध इनपुट को tpu.experimental.embedding_column के साथ सघन प्रतिनिधित्व में बदलें, जहां dimension एम्बेडिंग तालिका की चौड़ाई है। यह प्रत्येक num_buckets के लिए एक एम्बेडिंग वेक्टर संग्रहीत करेगा।
embedding_column = tf1.tpu.experimental.embedding_column(
embedding_id_column, dimension=5)
अब, tf.estimator.tpu.experimental.EmbeddingConfigSpec के माध्यम से tf.estimator.tpu.experimental.EmbeddingConfigSpec विशिष्ट एम्बेडिंग कॉन्फ़िगरेशन को परिभाषित करें। आप इसे बाद में tf.estimator.tpu.TPUEstimator को एक embedding_config_spec पैरामीटर के रूप में पास करेंगे।
embedding_config_spec = tf1.estimator.tpu.experimental.EmbeddingConfigSpec(
feature_columns=(embedding_column,),
optimization_parameters=(
tf1.tpu.experimental.AdagradParameters(0.05)))
अगला, TPUEstimator का उपयोग करने के लिए, परिभाषित करें:
- प्रशिक्षण डेटा के लिए एक इनपुट फ़ंक्शन
- मूल्यांकन डेटा के लिए एक मूल्यांकन इनपुट फ़ंक्शन
-
TPUEstimatorको निर्देश देने के लिए एक मॉडल फ़ंक्शन कि कैसे सुविधाओं और लेबल के साथ प्रशिक्षण सेशन को परिभाषित किया जाता है
def _input_fn(params):
dataset = tf1.data.Dataset.from_tensor_slices((
{"dense_feature": features,
"sparse_feature": tf1.SparseTensor(
embedding_features_indices,
embedding_features_values, [1, 2])},
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((
{"dense_feature": eval_features,
"sparse_feature": tf1.SparseTensor(
eval_embedding_features_indices,
eval_embedding_features_values, [1, 2])},
eval_labels))
dataset = dataset.repeat()
return dataset.batch(params['batch_size'], drop_remainder=True)
def _model_fn(features, labels, mode, params):
embedding_features = tf1.keras.layers.DenseFeatures(embedding_column)(features)
concatenated_features = tf1.keras.layers.Concatenate(axis=1)(
[embedding_features, features["dense_feature"]])
logits = tf1.layers.Dense(1)(concatenated_features)
loss = tf1.losses.mean_squared_error(labels=labels, predictions=logits)
optimizer = tf1.train.AdagradOptimizer(0.05)
optimizer = tf1.tpu.CrossShardOptimizer(optimizer)
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'))
All devices: []
tpu_config = tf1.estimator.tpu.TPUConfig(
iterations_per_loop=10,
per_host_input_for_training=tf1.estimator.tpu.InputPipelineConfig
.PER_HOST_V2)
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,
embedding_config_spec=embedding_config_spec)
WARNING:tensorflow:Estimator's model_fn (<function _model_fn at 0x7eff1dbf4ae8>) includes params argument, but params are not passed to Estimator.
WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpc68an8jx
INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmpc68an8jx', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true
cluster_def {
job {
name: "worker"
tasks {
key: 0
value: "10.240.1.2:8470"
}
}
}
isolate_session_state: true
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': None, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({'worker': ['10.240.1.2:8470']}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': 'grpc://10.240.1.2:8470', '_evaluation_master': 'grpc://10.240.1.2:8470', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1, '_tpu_config': TPUConfig(iterations_per_loop=10, num_shards=None, num_cores_per_replica=None, per_host_input_for_training=3, tpu_job_name=None, initial_infeed_sleep_secs=None, input_partition_dims=None, eval_training_input_configuration=2, experimental_host_call_every_n_steps=1, experimental_allow_per_host_v2_parallel_get_next=False, experimental_feed_hook=None), '_cluster': <tensorflow.python.distribute.cluster_resolver.tpu.tpu_cluster_resolver.TPUClusterResolver object at 0x7eff1dbfa2b0>}
INFO:tensorflow:_TPUContext: eval_on_tpu True
मॉडल का प्रशिक्षण शुरू करने के लिए TPUEstimator.train पर कॉल करें:
estimator.train(_input_fn, steps=1)
INFO:tensorflow:Querying Tensorflow master (grpc://10.240.1.2:8470) for TPU system metadata. INFO:tensorflow:Found TPU system: INFO:tensorflow:*** Num TPU Cores: 8 INFO:tensorflow:*** Num TPU Workers: 1 INFO:tensorflow:*** Num TPU Cores Per Worker: 8 INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:CPU:0, CPU, -1, -3018931587863375246) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:0, TPU, 17179869184, 1249032734884062775) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:1, TPU, 17179869184, -3881759543008185868) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:2, TPU, 17179869184, -3421771184935649663) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:3, TPU, 17179869184, 8872583169621331661) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:4, TPU, 17179869184, -1222373804129613329) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:5, TPU, 17179869184, 6258068298163390748) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:6, TPU, 17179869184, 5190265587768274342) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:7, TPU, 17179869184, 3073578684150069836) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU_SYSTEM:0, TPU_SYSTEM, 17179869184, 2071242092327503173) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, -1319360343564144287) WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts. INFO:tensorflow:Calling model_fn. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/tpu/feature_column_v2.py:479: IdentityCategoricalColumn._num_buckets (from tensorflow.python.feature_column.feature_column_v2) is deprecated and will be removed in a future version. Instructions for updating: The old _FeatureColumn APIs are being deprecated. Please use the new FeatureColumn APIs instead. INFO:tensorflow:Querying Tensorflow master (grpc://10.240.1.2:8470) for TPU system metadata. INFO:tensorflow:Found TPU system: INFO:tensorflow:*** Num TPU Cores: 8 INFO:tensorflow:*** Num TPU Workers: 1 INFO:tensorflow:*** Num TPU Cores Per Worker: 8 INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:CPU:0, CPU, -1, -3018931587863375246) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:0, TPU, 17179869184, 1249032734884062775) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:1, TPU, 17179869184, -3881759543008185868) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:2, TPU, 17179869184, -3421771184935649663) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:3, TPU, 17179869184, 8872583169621331661) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:4, TPU, 17179869184, -1222373804129613329) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:5, TPU, 17179869184, 6258068298163390748) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:6, TPU, 17179869184, 5190265587768274342) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:7, TPU, 17179869184, 3073578684150069836) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU_SYSTEM:0, TPU_SYSTEM, 17179869184, 2071242092327503173) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, -1319360343564144287) WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/adagrad.py:77: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version. Instructions for updating: Call initializer instance with the dtype argument instead of passing it to the constructor INFO:tensorflow:Bypassing TPUEstimator hook INFO:tensorflow:Done calling model_fn. INFO:tensorflow:TPU job name worker INFO:tensorflow:Graph was finalized. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py:758: Variable.load (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Prefer Variable.assign which has equivalent behavior in 2.X. INFO:tensorflow:Initialized dataset iterators in 0 seconds INFO:tensorflow:Installing graceful shutdown hook. INFO:tensorflow:Creating heartbeat manager for ['/job:worker/replica:0/task:0/device:CPU:0'] INFO:tensorflow:Configuring worker heartbeat: shutdown_mode: WAIT_FOR_COORDINATOR INFO:tensorflow:Init TPU system INFO:tensorflow:Initialized TPU in 9 seconds INFO:tensorflow:Starting infeed thread controller. INFO:tensorflow:Starting outfeed thread controller. INFO:tensorflow:Enqueue next (1) batch(es) of data to infeed. INFO:tensorflow:Dequeue next (1) batch(es) of data from outfeed. INFO:tensorflow:Outfeed finished for iteration (0, 0) INFO:tensorflow:loss = 0.5212165, step = 1 INFO:tensorflow:Stop infeed thread controller INFO:tensorflow:Shutting down InfeedController thread. INFO:tensorflow:InfeedController received shutdown signal, stopping. INFO:tensorflow:Infeed thread finished, shutting down. INFO:tensorflow:infeed marked as finished INFO:tensorflow:Stop output thread controller INFO:tensorflow:Shutting down OutfeedController thread. INFO:tensorflow:OutfeedController received shutdown signal, stopping. INFO:tensorflow:Outfeed thread finished, shutting down. INFO:tensorflow:outfeed marked as finished INFO:tensorflow:Shutdown TPU system. INFO:tensorflow:Loss for final step: 0.5212165. INFO:tensorflow:training_loop marked as finished <tensorflow_estimator.python.estimator.tpu.tpu_estimator.TPUEstimator at 0x7eff1dbfa7b8>
फिर, मूल्यांकन डेटा का उपयोग करके मॉडल का मूल्यांकन करने के लिए TPUEstimator.evaluate पर कॉल करें:
estimator.evaluate(_eval_input_fn, steps=1)
INFO:tensorflow:Could not find trained model in model_dir: /tmp/tmpc68an8jx, running initialization to evaluate.
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Querying Tensorflow master (grpc://10.240.1.2:8470) for TPU system metadata.
INFO:tensorflow:Found TPU system:
INFO:tensorflow:*** Num TPU Cores: 8
INFO:tensorflow:*** Num TPU Workers: 1
INFO:tensorflow:*** Num TPU Cores Per Worker: 8
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:CPU:0, CPU, -1, -3018931587863375246)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:0, TPU, 17179869184, 1249032734884062775)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:1, TPU, 17179869184, -3881759543008185868)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:2, TPU, 17179869184, -3421771184935649663)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:3, TPU, 17179869184, 8872583169621331661)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:4, TPU, 17179869184, -1222373804129613329)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:5, TPU, 17179869184, 6258068298163390748)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:6, TPU, 17179869184, 5190265587768274342)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:7, TPU, 17179869184, 3073578684150069836)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU_SYSTEM:0, TPU_SYSTEM, 17179869184, 2071242092327503173)
INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, -1319360343564144287)
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py:3406: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Deprecated in favor of operator or tf.math.divide.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Starting evaluation at 2022-02-05T13:21:42
INFO:tensorflow:TPU job name worker
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Init TPU system
INFO:tensorflow:Initialized TPU in 11 seconds
INFO:tensorflow:Starting infeed thread controller.
INFO:tensorflow:Starting outfeed thread controller.
INFO:tensorflow:Initialized dataset iterators in 0 seconds
INFO:tensorflow:Enqueue next (1) batch(es) of data to infeed.
INFO:tensorflow:Dequeue next (1) batch(es) of data from outfeed.
INFO:tensorflow:Outfeed finished for iteration (0, 0)
INFO:tensorflow:Evaluation [1/1]
INFO:tensorflow:Stop infeed thread controller
INFO:tensorflow:Shutting down InfeedController thread.
INFO:tensorflow:InfeedController received shutdown signal, stopping.
INFO:tensorflow:Infeed thread finished, shutting down.
INFO:tensorflow:infeed marked as finished
INFO:tensorflow:Stop output thread controller
INFO:tensorflow:Shutting down OutfeedController thread.
INFO:tensorflow:OutfeedController received shutdown signal, stopping.
INFO:tensorflow:Outfeed thread finished, shutting down.
INFO:tensorflow:outfeed marked as finished
INFO:tensorflow:Shutdown TPU system.
INFO:tensorflow:Inference Time : 12.50468s
INFO:tensorflow:Finished evaluation at 2022-02-05-13:21:54
INFO:tensorflow:Saving dict for global step 1: global_step = 1, loss = 36.28813
INFO:tensorflow:evaluation_loop marked as finished
{'loss': 36.28813, 'global_step': 1}
TensorFlow 2: TPUStrategy के साथ TPU पर ट्रेन एम्बेडिंग
TensorFlow 2 में, TPU कार्यकर्ताओं को प्रशिक्षित करने के लिए, मॉडल परिभाषा और प्रशिक्षण/मूल्यांकन के लिए Keras API के साथ tf.distribute.TPUStrategy का उपयोग करें। (Keras Model.fit और एक कस्टम ट्रेनिंग लूप ( tf.function और tf.GradientTape के साथ) के साथ प्रशिक्षण के अधिक उदाहरणों के लिए उपयोग TPU गाइड देखें।)
चूंकि आपको दूरस्थ क्लस्टर से कनेक्ट करने और TPU कार्यकर्ताओं को प्रारंभ करने के लिए कुछ आरंभीकरण कार्य करने की आवश्यकता है, क्लस्टर जानकारी प्रदान करने और क्लस्टर से कनेक्ट करने के लिए TPUClusterResolver बनाकर प्रारंभ करें। ( इस्तेमाल करें टीपीयू गाइड के टीपीयू इनिशियलाइज़ेशन सेक्शन में और जानें।)
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'))
INFO:tensorflow:Clearing out eager caches INFO:tensorflow:Clearing out eager caches INFO:tensorflow:Initializing the TPU system: grpc://10.240.1.2:8470 INFO:tensorflow:Initializing the TPU system: grpc://10.240.1.2:8470 INFO:tensorflow:Finished initializing TPU system. INFO:tensorflow:Finished initializing TPU system. All devices: [LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:0', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:1', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:2', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:3', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:4', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:5', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:6', device_type='TPU'), LogicalDevice(name='/job:worker/replica:0/task:0/device:TPU:7', device_type='TPU')]
इसके बाद, अपना डेटा तैयार करें। यह उसी तरह है जैसे आपने TensorFlow 1 उदाहरण में एक डेटासेट बनाया था, सिवाय इसके कि डेटासेट फ़ंक्शन को अब एक tf.distribute.InputContext ऑब्जेक्ट के बजाय एक params डिक्टेट पास किया गया है। आप इस ऑब्जेक्ट का उपयोग स्थानीय बैच आकार को निर्धारित करने के लिए कर सकते हैं (और यह पाइपलाइन किस होस्ट के लिए है, ताकि आप अपने डेटा को ठीक से विभाजित कर सकें)।
-
tfrs.layers.embedding.TPUEmbeddingAPI का उपयोग करते समय, डेटासेट कोDataset.batchके साथ बैच करते समयdrop_remainder=Trueविकल्प शामिल करना महत्वपूर्ण है, क्योंकिTPUEmbeddingके लिए एक निश्चित बैच आकार की आवश्यकता होती है। - इसके अतिरिक्त, समान बैच आकार का उपयोग मूल्यांकन और प्रशिक्षण के लिए किया जाना चाहिए यदि वे उपकरणों के एक ही सेट पर हो रहे हैं।
- अंत में, आपको विशेष इनपुट विकल्प के साथ
tf.keras.utils.experimental.DatasetCreatorका उपयोग करना चाहिए-experimental_fetch_to_device=False-tf.distribute.InputOptions(जिसमें रणनीति-विशिष्ट कॉन्फ़िगरेशन हैं)। यह नीचे दिखाया गया है:
global_batch_size = 8
def _input_dataset(context: tf.distribute.InputContext):
dataset = tf.data.Dataset.from_tensor_slices((
{"dense_feature": features,
"sparse_feature": tf.SparseTensor(
embedding_features_indices,
embedding_features_values, [1, 2])},
labels))
dataset = dataset.shuffle(10).repeat()
dataset = dataset.batch(
context.get_per_replica_batch_size(global_batch_size),
drop_remainder=True)
return dataset.prefetch(2)
def _eval_dataset(context: tf.distribute.InputContext):
dataset = tf.data.Dataset.from_tensor_slices((
{"dense_feature": eval_features,
"sparse_feature": tf.SparseTensor(
eval_embedding_features_indices,
eval_embedding_features_values, [1, 2])},
eval_labels))
dataset = dataset.repeat()
dataset = dataset.batch(
context.get_per_replica_batch_size(global_batch_size),
drop_remainder=True)
return dataset.prefetch(2)
input_options = tf.distribute.InputOptions(
experimental_fetch_to_device=False)
input_dataset = tf.keras.utils.experimental.DatasetCreator(
_input_dataset, input_options=input_options)
eval_dataset = tf.keras.utils.experimental.DatasetCreator(
_eval_dataset, input_options=input_options)
अगला, डेटा तैयार होने के बाद, आप एक TPUStrategy , और इस रणनीति के दायरे के तहत एक मॉडल, मेट्रिक्स और एक ऑप्टिमाइज़र को परिभाषित करेंगे ( Strategy.scope )।
आपको steps_per_execution में Model.compile के लिए एक नंबर चुनना चाहिए क्योंकि यह प्रत्येक tf.function कॉल के दौरान चलने वाले बैचों की संख्या को निर्दिष्ट करता है, और प्रदर्शन के लिए महत्वपूर्ण है। यह तर्क TPUEstimator में प्रयुक्त iterations_per_loop के समान है।
TensorFlow 1 में tf.tpu.experimental.embedding_column (और tf.tpu.experimental.shared_embedding_column ) के माध्यम से निर्दिष्ट सुविधाओं और तालिका कॉन्फ़िगरेशन को सीधे TensorFlow 2 में कॉन्फ़िगरेशन ऑब्जेक्ट्स की एक जोड़ी के माध्यम से निर्दिष्ट किया जा सकता है:
(अधिक विवरण के लिए संबद्ध API दस्तावेज़ देखें।)
strategy = tf.distribute.TPUStrategy(cluster_resolver)
with strategy.scope():
optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.05)
dense_input = tf.keras.Input(shape=(2,), dtype=tf.float32, batch_size=global_batch_size)
sparse_input = tf.keras.Input(shape=(), dtype=tf.int32, batch_size=global_batch_size)
embedded_input = tfrs.layers.embedding.TPUEmbedding(
feature_config=tf.tpu.experimental.embedding.FeatureConfig(
table=tf.tpu.experimental.embedding.TableConfig(
vocabulary_size=10,
dim=5,
initializer=tf.initializers.TruncatedNormal(mean=0.0, stddev=1)),
name="sparse_input"),
optimizer=optimizer)(sparse_input)
input = tf.keras.layers.Concatenate(axis=1)([dense_input, embedded_input])
result = tf.keras.layers.Dense(1)(input)
model = tf.keras.Model(inputs={"dense_feature": dense_input, "sparse_feature": sparse_input}, outputs=result)
model.compile(optimizer, "mse", steps_per_execution=10)
INFO:tensorflow:Found TPU system: INFO:tensorflow:Found TPU system: INFO:tensorflow:*** Num TPU Cores: 8 INFO:tensorflow:*** Num TPU Cores: 8 INFO:tensorflow:*** Num TPU Workers: 1 INFO:tensorflow:*** Num TPU Workers: 1 INFO:tensorflow:*** Num TPU Cores Per Worker: 8 INFO:tensorflow:*** Num TPU Cores Per Worker: 8 INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:CPU:0, CPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:CPU:0, CPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:0, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:0, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:1, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:1, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:2, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:2, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:3, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:3, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:4, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:4, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:5, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:5, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:6, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:6, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:7, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU:7, TPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU_SYSTEM:0, TPU_SYSTEM, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:TPU_SYSTEM:0, TPU_SYSTEM, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 0, 0) INFO:tensorflow:*** Available Device: _DeviceAttributes(/job:worker/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 0, 0)
इसके साथ, आप प्रशिक्षण डेटासेट के साथ मॉडल को प्रशिक्षित करने के लिए तैयार हैं:
model.fit(input_dataset, epochs=5, steps_per_epoch=10)
Epoch 1/5 10/10 [==============================] - 2s 164ms/step - loss: 0.4005 Epoch 2/5 10/10 [==============================] - 0s 3ms/step - loss: 0.0036 Epoch 3/5 10/10 [==============================] - 0s 3ms/step - loss: 3.0932e-05 Epoch 4/5 10/10 [==============================] - 0s 3ms/step - loss: 2.5767e-07 Epoch 5/5 10/10 [==============================] - 0s 3ms/step - loss: 2.1366e-09 <keras.callbacks.History at 0x7efd8c461c18>
अंत में, मूल्यांकन डेटासेट का उपयोग करके मॉडल का मूल्यांकन करें:
model.evaluate(eval_dataset, steps=1, return_dict=True)
1/1 [==============================] - 1s 1s/step - loss: 15.3952
{'loss': 15.395216941833496}
अगले कदम
API दस्तावेज़ों में TPU-विशिष्ट एम्बेडिंग सेट करने के बारे में अधिक जानें:
-
tfrs.layers.embedding.TPUEmbedding: विशेष रूप से फीचर और टेबल कॉन्फ़िगरेशन के बारे में, ऑप्टिमाइज़र सेट करना, एक मॉडल बनाना (Keras कार्यात्मक API का उपयोग करके याtf.keras.Modelउप-वर्ग के माध्यम से), प्रशिक्षण/मूल्यांकन, औरtf.saved_modelके साथ सेवा करने वाला मॉडल -
tf.tpu.experimental.embedding.TableConfig -
tf.tpu.experimental.embedding.FeatureConfig
TensorFlow 2 में TPUStrategy के बारे में अधिक जानकारी के लिए, निम्नलिखित संसाधनों पर विचार करें:
- गाइड:
Model.fitका उपयोग करें (केरसtf.distribute.TPUStrategyके साथ प्रशिक्षण को कवरtf.function। - गाइड: TensorFlow के साथ वितरित प्रशिक्षण
- गाइड: TPUEestimator से TPStrategy में माइग्रेट करें ।
अपने प्रशिक्षण को अनुकूलित करने के बारे में अधिक जानने के लिए, देखें:
टीपीयू—मशीन लर्निंग के लिए गूगल के विशेष एएसआईसी— गूगल कोलाब, टीपीयू रिसर्च क्लाउड और क्लाउड टीपीयू के जरिए उपलब्ध हैं।
TensorFlow.org पर देखें
Google Colab में चलाएं
GitHub पर स्रोत देखें
नोटबुक डाउनलोड करें