|
| 1 | +import logging |
| 2 | +from typing import Callable, Tuple |
| 3 | + |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from deepmd.utils.errors import OutOfMemoryError |
| 7 | + |
| 8 | +class AutoBatchSize: |
| 9 | + """This class allows DeePMD-kit to automatically decide the maximum |
| 10 | + batch size that will not cause an OOM error. |
| 11 | + |
| 12 | + Notes |
| 13 | + ----- |
| 14 | + We assume all OOM error will raise :metd:`OutOfMemoryError`. |
| 15 | +
|
| 16 | + Parameters |
| 17 | + ---------- |
| 18 | + initial_batch_size : int, default: 1024 |
| 19 | + initial batch size (number of total atoms) |
| 20 | + factor : float, default: 2. |
| 21 | + increased factor |
| 22 | +
|
| 23 | + Attributes |
| 24 | + ---------- |
| 25 | + current_batch_size : int |
| 26 | + current batch size (number of total atoms) |
| 27 | + maximum_working_batch_size : int |
| 28 | + maximum working batch size |
| 29 | + minimal_not_working_batch_size : int |
| 30 | + minimal not working batch size |
| 31 | + """ |
| 32 | + def __init__(self, initial_batch_size: int = 1024, factor: float = 2.) -> None: |
| 33 | + # See also PyTorchLightning/pytorch-lightning#1638 |
| 34 | + # TODO: discuss a proper initial batch size |
| 35 | + self.current_batch_size = initial_batch_size |
| 36 | + self.maximum_working_batch_size = 0 |
| 37 | + self.minimal_not_working_batch_size = 2**31 |
| 38 | + self.factor = factor |
| 39 | + |
| 40 | + def execute(self, callable: Callable, start_index: int, natoms: int) -> Tuple[int, tuple]: |
| 41 | + """Excuate a method with given batch size. |
| 42 | + |
| 43 | + Parameters |
| 44 | + ---------- |
| 45 | + callable : Callable |
| 46 | + The method should accept the batch size and start_index as parameters, |
| 47 | + and returns executed batch size and data. |
| 48 | + start_index : int |
| 49 | + start index |
| 50 | + natoms : int |
| 51 | + natoms |
| 52 | + |
| 53 | + Returns |
| 54 | + ------- |
| 55 | + int |
| 56 | + executed batch size * number of atoms |
| 57 | + tuple |
| 58 | + result from callable, None if failing to execute |
| 59 | +
|
| 60 | + Raises |
| 61 | + ------ |
| 62 | + OutOfMemoryError |
| 63 | + OOM when batch size is 1 |
| 64 | + """ |
| 65 | + try: |
| 66 | + n_batch, result = callable(max(self.current_batch_size // natoms, 1), start_index) |
| 67 | + except OutOfMemoryError as e: |
| 68 | + # TODO: it's very slow to catch OOM error; I don't know what TF is doing here |
| 69 | + # but luckily we only need to catch once |
| 70 | + self.minimal_not_working_batch_size = min(self.minimal_not_working_batch_size, self.current_batch_size) |
| 71 | + if self.maximum_working_batch_size >= self.minimal_not_working_batch_size: |
| 72 | + self.maximum_working_batch_size = int(self.minimal_not_working_batch_size / self.factor) |
| 73 | + if self.minimal_not_working_batch_size <= natoms: |
| 74 | + raise OutOfMemoryError("The callable still throws an out-of-memory (OOM) error even when batch size is 1!") from e |
| 75 | + # adjust the next batch size |
| 76 | + self._adjust_batch_size(1./self.factor) |
| 77 | + return 0, None |
| 78 | + else: |
| 79 | + n_tot = n_batch * natoms |
| 80 | + self.maximum_working_batch_size = max(self.maximum_working_batch_size, n_tot) |
| 81 | + # adjust the next batch size |
| 82 | + if n_tot >= self.current_batch_size and self.current_batch_size * self.factor < self.minimal_not_working_batch_size: |
| 83 | + self._adjust_batch_size(self.factor) |
| 84 | + return n_batch, result |
| 85 | + |
| 86 | + def _adjust_batch_size(self, factor: float): |
| 87 | + old_batch_size = self.current_batch_size |
| 88 | + self.current_batch_size = int(self.current_batch_size * factor) |
| 89 | + logging.info("Adjust batch size from %d to %d" % (old_batch_size, self.current_batch_size)) |
| 90 | + |
| 91 | + def execute_all(self, callable: Callable, total_size: int, natoms: int, *args, **kwargs) -> Tuple[np.ndarray]: |
| 92 | + """Excuate a method with all given data. |
| 93 | + |
| 94 | + Parameters |
| 95 | + ---------- |
| 96 | + callable : Callable |
| 97 | + The method should accept *args and **kwargs as input and return the similiar array. |
| 98 | + total_size : int |
| 99 | + Total size |
| 100 | + natoms : int |
| 101 | + The number of atoms |
| 102 | + **kwargs |
| 103 | + If 2D np.ndarray, assume the first axis is batch; otherwise do nothing. |
| 104 | + """ |
| 105 | + def execute_with_batch_size(batch_size: int, start_index: int) -> Tuple[int, Tuple[np.ndarray]]: |
| 106 | + end_index = start_index + batch_size |
| 107 | + end_index = min(end_index, total_size) |
| 108 | + return (end_index - start_index), callable( |
| 109 | + *[(vv[start_index:end_index] if isinstance(vv, np.ndarray) and vv.ndim > 1 else vv) for vv in args], |
| 110 | + **{kk: (vv[start_index:end_index] if isinstance(vv, np.ndarray) and vv.ndim > 1 else vv) for kk, vv in kwargs.items()}, |
| 111 | + ) |
| 112 | + |
| 113 | + index = 0 |
| 114 | + results = [] |
| 115 | + while index < total_size: |
| 116 | + n_batch, result = self.execute(execute_with_batch_size, index, natoms) |
| 117 | + if not isinstance(result, tuple): |
| 118 | + result = (result,) |
| 119 | + index += n_batch |
| 120 | + if n_batch: |
| 121 | + for rr in result: |
| 122 | + rr.reshape((n_batch, -1)) |
| 123 | + results.append(result) |
| 124 | + |
| 125 | + r = tuple([np.concatenate(r, axis=0) for r in zip(*results)]) |
| 126 | + if len(r) == 1: |
| 127 | + # avoid returning tuple if callable doesn't return tuple |
| 128 | + r = r[0] |
| 129 | + return r |
0 commit comments