benchmark_tf.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # coding=utf-8
  2. # Copyright 2018 The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """
  17. Benchmarking the library on inference and training in PyTorch.
  18. """
  19. import random
  20. import timeit
  21. from functools import wraps
  22. from typing import Callable, Optional
  23. from ..configuration_utils import PretrainedConfig
  24. from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
  25. from ..utils import is_py3nvml_available, is_tf_available, logging
  26. from .benchmark_utils import (
  27. Benchmark,
  28. Memory,
  29. MemorySummary,
  30. measure_peak_memory_cpu,
  31. start_memory_tracing,
  32. stop_memory_tracing,
  33. )
  34. if is_tf_available():
  35. import tensorflow as tf
  36. from tensorflow.python.framework.errors_impl import ResourceExhaustedError
  37. from .benchmark_args_tf import TensorFlowBenchmarkArguments
  38. if is_py3nvml_available():
  39. import py3nvml.py3nvml as nvml
  40. logger = logging.get_logger(__name__)
  41. def run_with_tf_optimizations(do_eager_mode: bool, use_xla: bool):
  42. def run_func(func):
  43. @wraps(func)
  44. def run_in_eager_mode(*args, **kwargs):
  45. return func(*args, **kwargs)
  46. @wraps(func)
  47. @tf.function(experimental_compile=use_xla)
  48. def run_in_graph_mode(*args, **kwargs):
  49. return func(*args, **kwargs)
  50. if do_eager_mode is True:
  51. if use_xla is not False:
  52. raise ValueError(
  53. "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."
  54. )
  55. return run_in_eager_mode
  56. else:
  57. return run_in_graph_mode
  58. return run_func
  59. def random_input_ids(batch_size: int, sequence_length: int, vocab_size: int) -> ["tf.Tensor"]:
  60. rng = random.Random()
  61. values = [rng.randint(0, vocab_size - 1) for i in range(batch_size * sequence_length)]
  62. return tf.constant(values, shape=(batch_size, sequence_length), dtype=tf.int32)
  63. class TensorFlowBenchmark(Benchmark):
  64. args: TensorFlowBenchmarkArguments
  65. configs: PretrainedConfig
  66. framework: str = "TensorFlow"
  67. @property
  68. def framework_version(self):
  69. return tf.__version__
  70. def _inference_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
  71. # initialize GPU on separate process
  72. strategy = self.args.strategy
  73. if strategy is None:
  74. raise ValueError("A device strategy has to be initialized before using TensorFlow.")
  75. _inference = self._prepare_inference_func(model_name, batch_size, sequence_length)
  76. return self._measure_speed(_inference)
  77. def _train_speed(self, model_name: str, batch_size: int, sequence_length: int) -> float:
  78. strategy = self.args.strategy
  79. if strategy is None:
  80. raise ValueError("A device strategy has to be initialized before using TensorFlow.")
  81. _train = self._prepare_train_func(model_name, batch_size, sequence_length)
  82. return self._measure_speed(_train)
  83. def _inference_memory(
  84. self, model_name: str, batch_size: int, sequence_length: int
  85. ) -> [Memory, Optional[MemorySummary]]:
  86. # initialize GPU on separate process
  87. if self.args.is_gpu:
  88. tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx], True)
  89. strategy = self.args.strategy
  90. if strategy is None:
  91. raise ValueError("A device strategy has to be initialized before using TensorFlow.")
  92. _inference = self._prepare_inference_func(model_name, batch_size, sequence_length)
  93. return self._measure_memory(_inference)
  94. def _train_memory(
  95. self, model_name: str, batch_size: int, sequence_length: int
  96. ) -> [Memory, Optional[MemorySummary]]:
  97. if self.args.is_gpu:
  98. tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx], True)
  99. strategy = self.args.strategy
  100. if strategy is None:
  101. raise ValueError("A device strategy has to be initialized before using TensorFlow.")
  102. _train = self._prepare_train_func(model_name, batch_size, sequence_length)
  103. return self._measure_memory(_train)
  104. def _prepare_inference_func(self, model_name: str, batch_size: int, sequence_length: int) -> Callable[[], None]:
  105. config = self.config_dict[model_name]
  106. if self.args.fp16:
  107. raise NotImplementedError("Mixed precision is currently not supported.")
  108. has_model_class_in_config = (
  109. hasattr(config, "architectures")
  110. and isinstance(config.architectures, list)
  111. and len(config.architectures) > 0
  112. )
  113. if not self.args.only_pretrain_model and has_model_class_in_config:
  114. try:
  115. model_class = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model
  116. transformers_module = __import__("transformers", fromlist=[model_class])
  117. model_cls = getattr(transformers_module, model_class)
  118. model = model_cls(config)
  119. except ImportError:
  120. raise ImportError(
  121. f"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
  122. " set `--only_pretrain_model` or `args.only_pretrain_model=True`."
  123. )
  124. else:
  125. model = TF_MODEL_MAPPING[config.__class__](config)
  126. # encoder-decoder has vocab size saved differently
  127. vocab_size = config.vocab_size if hasattr(config, "vocab_size") else config.encoder.vocab_size
  128. input_ids = random_input_ids(batch_size, sequence_length, vocab_size)
  129. @run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
  130. def encoder_decoder_forward():
  131. return model(input_ids, decoder_input_ids=input_ids, training=False)
  132. @run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
  133. def encoder_forward():
  134. return model(input_ids, training=False)
  135. _inference = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
  136. return _inference
  137. def _prepare_train_func(self, model_name: str, batch_size: int, sequence_length: int) -> Callable[[], None]:
  138. config = self.config_dict[model_name]
  139. if self.args.eager_mode is not False:
  140. raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.")
  141. if self.args.fp16:
  142. raise NotImplementedError("Mixed precision is currently not supported.")
  143. has_model_class_in_config = (
  144. hasattr(config, "architectures")
  145. and isinstance(config.architectures, list)
  146. and len(config.architectures) > 0
  147. )
  148. if not self.args.only_pretrain_model and has_model_class_in_config:
  149. try:
  150. model_class = "TF" + config.architectures[0] # prepend 'TF' for tensorflow model
  151. transformers_module = __import__("transformers", fromlist=[model_class])
  152. model_cls = getattr(transformers_module, model_class)
  153. model = model_cls(config)
  154. except ImportError:
  155. raise ImportError(
  156. f"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
  157. " set `--only_pretrain_model` or `args.only_pretrain_model=True`."
  158. )
  159. else:
  160. model = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](config)
  161. # encoder-decoder has vocab size saved differently
  162. vocab_size = config.vocab_size if hasattr(config, "vocab_size") else config.encoder.vocab_size
  163. input_ids = random_input_ids(batch_size, sequence_length, vocab_size)
  164. @run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
  165. def encoder_decoder_train():
  166. loss = model(input_ids, decoder_input_ids=input_ids, labels=input_ids, training=True)[0]
  167. gradients = tf.gradients(loss, model.trainable_variables)
  168. return gradients
  169. @run_with_tf_optimizations(self.args.eager_mode, self.args.use_xla)
  170. def encoder_train():
  171. loss = model(input_ids, labels=input_ids, training=True)[0]
  172. gradients = tf.gradients(loss, model.trainable_variables)
  173. return gradients
  174. _train = encoder_decoder_train if config.is_encoder_decoder else encoder_train
  175. return _train
  176. def _measure_speed(self, func) -> float:
  177. with self.args.strategy.scope():
  178. try:
  179. if self.args.is_tpu or self.args.use_xla:
  180. # run additional 10 times to stabilize compilation for tpu
  181. logger.info("Do inference on TPU. Running model 5 times to stabilize compilation")
  182. timeit.repeat(func, repeat=1, number=5)
  183. # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
  184. runtimes = timeit.repeat(
  185. func,
  186. repeat=self.args.repeat,
  187. number=10,
  188. )
  189. return min(runtimes) / 10.0
  190. except ResourceExhaustedError as e:
  191. self.print_fn(f"Doesn't fit on GPU. {e}")
  192. def _measure_memory(self, func: Callable[[], None]) -> [Memory, MemorySummary]:
  193. logger.info(
  194. "Note that TensorFlow allocates more memory than "
  195. "it might need to speed up computation. "
  196. "The memory reported here corresponds to the memory "
  197. "reported by `nvidia-smi`, which can vary depending "
  198. "on total available memory on the GPU that is used."
  199. )
  200. with self.args.strategy.scope():
  201. try:
  202. if self.args.trace_memory_line_by_line:
  203. if not self.args.eager_mode:
  204. raise ValueError(
  205. "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
  206. " consumption line by line."
  207. )
  208. trace = start_memory_tracing("transformers")
  209. if self.args.is_tpu:
  210. # tpu
  211. raise NotImplementedError(
  212. "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"
  213. " with `args.memory=False`"
  214. )
  215. elif self.args.is_gpu:
  216. # gpu
  217. if not is_py3nvml_available():
  218. logger.warning(
  219. "py3nvml not installed, we won't log GPU memory usage. "
  220. "Install py3nvml (pip install py3nvml) to log information about GPU."
  221. )
  222. memory = "N/A"
  223. else:
  224. logger.info(
  225. "Measuring total GPU usage on GPU device. Make sure to not have additional processes"
  226. " running on the same GPU."
  227. )
  228. # init nvml
  229. nvml.nvmlInit()
  230. func()
  231. handle = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx)
  232. meminfo = nvml.nvmlDeviceGetMemoryInfo(handle)
  233. max_bytes_in_use = meminfo.used
  234. memory = Memory(max_bytes_in_use)
  235. # shutdown nvml
  236. nvml.nvmlShutdown()
  237. else:
  238. # cpu
  239. if self.args.trace_memory_line_by_line:
  240. logger.info(
  241. "When enabling line by line tracing, the max peak memory for CPU is inaccurate in"
  242. " TensorFlow."
  243. )
  244. memory = None
  245. else:
  246. memory_bytes = measure_peak_memory_cpu(func)
  247. memory = Memory(memory_bytes) if isinstance(memory_bytes, int) else memory_bytes
  248. if self.args.trace_memory_line_by_line:
  249. summary = stop_memory_tracing(trace)
  250. if memory is None:
  251. memory = summary.total
  252. else:
  253. summary = None
  254. return memory, summary
  255. except ResourceExhaustedError as e:
  256. self.print_fn(f"Doesn't fit on GPU. {e}")
  257. return "N/A", None