Contiguous memory buffer. Allocate a contiguous memory of type `dtype` and size `numel`. It is used to reduce memory fragmentation. Usage: After the allocation, the `_start` index is set tot the first index of the memory. A memory chunk starting from `_start` index
| 35 | |
| 36 | |
| 37 | class MemoryBuffer: |
| 38 | """Contiguous memory buffer. |
| 39 | Allocate a contiguous memory of type `dtype` and size `numel`. It is |
| 40 | used to reduce memory fragmentation. |
| 41 | |
| 42 | Usage: After the allocation, the `_start` index is set tot the first |
| 43 | index of the memory. A memory chunk starting from `_start` index |
| 44 | can be `allocated` for an input tensor, with the elements of the |
| 45 | tensor being coppied. The buffer can be reused by resetting the |
| 46 | `_start` index. |
| 47 | |
| 48 | """ |
| 49 | def __init__(self, name, numel, dtype, track_usage): |
| 50 | if torch.distributed.get_rank() == 0: |
| 51 | element_size = torch.tensor([], dtype=dtype).element_size() |
| 52 | print('> building the {} memory buffer with {} num elements ' |
| 53 | 'and {} dtype ({:.1f} MB)...'.format( |
| 54 | name, numel, dtype, numel*element_size/1024/1024), |
| 55 | flush=True) |
| 56 | self.name = name |
| 57 | self.numel = numel |
| 58 | self.dtype = dtype |
| 59 | self.data = torch.empty(self.numel, |
| 60 | dtype=self.dtype, |
| 61 | device=torch.cuda.current_device(), |
| 62 | requires_grad=False) |
| 63 | |
| 64 | # Index tracking the start of the free memory. |
| 65 | self._start = 0 |
| 66 | |
| 67 | # Values used for tracking usage. |
| 68 | self.track_usage = track_usage |
| 69 | if self.track_usage: |
| 70 | self.in_use_value = 0.0 |
| 71 | self.total_value = 0.0 |
| 72 | |
| 73 | |
| 74 | def reset(self): |
| 75 | """Reset the buffer start index to the beginning of the buffer.""" |
| 76 | self._start = 0 |
| 77 | |
| 78 | |
| 79 | def is_in_use(self): |
| 80 | """Whether the current buffer hold on to any memory.""" |
| 81 | return self._start > 0 |
| 82 | |
| 83 | |
| 84 | def numel_in_use(self): |
| 85 | """Return number of elements in use.""" |
| 86 | return self._start |
| 87 | |
| 88 | |
| 89 | def add(self, tensor): |
| 90 | """Allocate a chunk of memory from the buffer to tensor and copy |
| 91 | the values.""" |
| 92 | assert tensor.dtype == self.dtype, \ |
| 93 | 'Input tensor type {} different from buffer type {}'.format( |
| 94 | tensor.dtype, self.dtype) |