-
Notifications
You must be signed in to change notification settings - Fork 400
/
seq_length_warmup.py
280 lines (219 loc) · 11.6 KB
/
seq_length_warmup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Core code for sequence length warmup."""
import textwrap
from math import ceil
from typing import Dict, Mapping, Optional
import torch
import torch.utils.data
from composer.core import Algorithm, Event, State
from composer.core.precision import get_precision_context
from composer.core.time import TimeUnit
from composer.core.types import Batch
from composer.loggers import Logger
from composer.models import ComposerTransformer
from composer.utils import ensure_tuple
__all__ = ['SeqLengthWarmup', 'set_batch_sequence_length']
def set_batch_sequence_length(batch: Dict[str, torch.Tensor], curr_seq_len: int, truncate: bool = True) -> Batch:
"""Set the sequence length of a batch.
Changes the sequence length of all tensors in the provided dictionary
to ``curr_seq_len`` by either truncating the tensors (``truncate=True``)
or reshaping the tensors to create new examples from the extra tokens
(``truncate=False``).
.. note::
The schedule for ``curr_seq_len`` over training time should be managed
outside of this function.
.. note::
Variable input lengths can create CUDA OOM errors. To avoid this,
we follow the `PyTorch notes <https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html#pre-allocate-memory-in-case-of-variable-input-length>`_
and pre-allocate the memory with a blank forward and backward pass.
Args:
batch (Dict[str, Tensor]): The input batch to the model, must be a dictionary.
curr_seq_length (int): The desired sequence length to apply.
truncate (bool, optional): Truncate sequences early, or reshape tensors to create
new examples out of the extra tokens. Default: ``True``.
Returns:
Dict[str, Tensor]: a Mapping of input tensors to the model,
where all tensors have curr_seq_len in the second dimension.
Example:
.. code-block::
import composer.functional as cf
for epoch in range(num_epochs):
for X, y in train_loader:
X = cf.set_batch_sequence_length(X, sequence_length)
y_hat = model(X)
loss = loss_fn(y_hat, y)
"""
assert isinstance(batch, Mapping)
if truncate:
for k in batch.keys():
batch[k] = batch[k][:, :curr_seq_len]
else:
# ensure new tensor shape is divisible by curr_seq_len
input_ids = batch['input_ids'].view(-1)
tensor_len = (input_ids.shape[0] // curr_seq_len) * curr_seq_len
input_ids = input_ids[:tensor_len]
input_ids = input_ids.view(-1, curr_seq_len)
batch['input_ids'] = input_ids
for k, v in batch.items():
if k == 'input_ids':
continue
v = v.view(-1)
v = v[:tensor_len]
batch[k] = v.view(-1, curr_seq_len)
return batch
class SeqLengthWarmup(Algorithm):
"""Progressively increases the sequence length during training.
Changes the sequence length of all tensors in the input batch. The
sequence length increases from ``min_seq_length`` to ``max_seq_length``
in steps of ``step_size`` during the first ``duration`` fraction of
training.
The sequence length is then kept at ``max_seq_length``
for the rest of training.
Tensors are either truncated (``truncate=True``) or reshaped to
create new examples from the extra tokens (``truncate=False``).
This algorithm runs on :attr:`~composer.core.event.Event.AFTER_DATALOADER` to modify
the sequence length of a batch of data after the model and data have been moved to
accelerators.
.. note::
``step_size`` should be a `multiple of eight <https://developer.nvidia.com/blog/optimizing-gpu-performance-tensor-cores/>`_ for
optimal throughput on NVIDIA GPUs.
.. note::
Variable input lengths can create CUDA OOM errors. To avoid this,
we follow the `PyTorch notes <https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html#pre-allocate-memory-in-case-of-variable-input-length>`_
and pre-allocate the memory with a blank forward and backward pass.
See the :doc:`Method Card </method_cards/seq_length_warmup>` for more details.
Example:
.. code-block::
from composer.algorithms import SeqLengthWarmup
from composer import Trainer
seq_length_warmup = SeqLengthWarmup(duration=0.5,
min_seq_length=8,
max_seq_length=1024,
ste_size=8,
truncate=False)
trainer = Trainer(model=model,
train_dataloader=train_dataloader,
max_duration="1ep",
algorithms=[seq_length_warmup])
Args:
duration (float, optional): Fraction of total training for sequential length
learning. Default = ``0.3``.
min_seq_length (int, optional): Minimum sequence length to start the warmup.
Default = ``8``.
max_seq_length (int, optional): Maximum sequence length to stop the warmup.
Default = ``1024``.
step_size (int, optional): Step size of sequence length. Default = ``8``.
truncate (bool, optional): Truncate tensors or reshape extra tokens to new
examples. Default = ``True``.
"""
def __init__(
self,
duration: float = 0.3,
min_seq_length: int = 8,
max_seq_length: int = 1024,
step_size: int = 8,
truncate: bool = True,
):
self.duration = duration
self.min_seq_length = min_seq_length
self.max_seq_length = max_seq_length
self.step_size = step_size
self.truncate = truncate
if self.duration < 0 or self.duration > 1:
raise ValueError(f'Duration must be getween 0 and 1, got: {self.duration}')
if self.max_seq_length < self.min_seq_length:
raise ValueError(f'max_seq_length={self.max_seq_length} must be '
f'greater than min_seq_length={self.min_seq_length}')
self._activated = False
self._original_model = None
def match(self, event: Event, state: State) -> bool:
return (event == Event.INIT and self._original_model is None) or event == Event.AFTER_DATALOADER
def apply(self, event: Event, state: State, logger: Logger) -> Optional[int]:
if event == Event.INIT:
if not isinstance(state.model, ComposerTransformer):
raise RuntimeError(
textwrap.dedent(f"""\
{type(self).__name__} requires state.model to be of type {ComposerTransformer.__name__}, not of type {type(state.model)}"""
))
self._original_model = state.model
return
assert state.dataloader is not None, 'dataloader should be set on AFTER_DATALOADER'
assert state.max_duration is not None, 'max_duration should be set on AFTER_DATALOADER'
# in order to avoid OOMs, we do a forward and a backward pass on a dummy input.
if not self._activated:
# ensure that input_ids is a valid model input. since we don't need the
# results, we don't use all inputs.
assert self._original_model is not None, 'original model should be set on Event.INIT'
model_inputs = self._original_model.get_model_inputs()
if 'input_ids' not in model_inputs:
raise RuntimeError("'input_ids' must be in model inputs")
if 'labels' not in model_inputs:
raise RuntimeError("'labels' must be in model inputs")
# create fake inputs
assert self._original_model.config is not None, 'model of type HuggingFaceModel should have .config'
vocab_size = self._original_model.config.vocab_size
# simplifying assumption: Composer doesn't support model-parallelism,
# so the first parameter's device is likely the same device for
# all of the parameters
device = next(state.model.parameters()).device
try:
# Both PyTorch and FFCV dataloaders define a `batch_size` attribute
# This exception would mainly be raised if the user is passing in a custom
# iterable
per_gpu_macrobatch = getattr(state.dataloader, 'batch_size')
except AttributeError as e:
raise AttributeError(
'Sequence Length Warmup requires the `state.dataloader` to have a `batch_size` attribute.') from e
if per_gpu_macrobatch is None:
raise RuntimeError('Sequence Length Warmup algorithm requires constant batch size.')
per_gpu_batch = ceil(per_gpu_macrobatch / state.grad_accum)
input_ids = torch.randint(low=0,
high=vocab_size - 1,
size=(per_gpu_batch, self.max_seq_length),
device=device).long()
labels = input_ids.clone()
attn_mask = torch.ones_like(labels)
model_inputs = {
'input_ids': input_ids,
'labels': labels,
'attention_mask': attn_mask,
}
# start by running a forward and backward pass
# of the maximum sequence length to allocate cache.
with get_precision_context(state.precision):
outputs = state.model.forward(model_inputs)
loss = self._original_model.loss(outputs, model_inputs)
# since use_grad_scaling is in the Trainer, and we
# don't care about the loss values, skip scaling
for loss_item in ensure_tuple(loss):
loss_item.backward()
for optimizer in state.optimizers:
optimizer.zero_grad()
self._activated = True
if state.max_duration.unit == TimeUnit.EPOCH:
if state.dataloader_len is None:
raise RuntimeError('Sequential Length Warmup requires the dataloader to be sized.')
num_optimization_steps = int(state.dataloader_len) * state.max_duration.value
elif state.max_duration.unit == TimeUnit.BATCH:
num_optimization_steps = state.max_duration.value
else:
raise NotImplementedError(
textwrap.dedent("""\
To use sequential length warmup, the max_duration must be in epochs or batches.
Specifying the `max_duration` in tokens or samples for use with sequential
length warmup will be supported in a future Composer release. See
https://github.com/mosaicml/composer/issues/226."""))
num_warmup_steps = int(num_optimization_steps * self.duration) # in batches
# assume the full sequence length is the unaltered sequence length
num_update_steps = (self.max_seq_length - self.min_seq_length) // self.step_size
update_every_n_steps = num_warmup_steps // num_update_steps
curr_seq_len = self.step_size * (int(state.timestamp.batch) // update_every_n_steps)
curr_seq_len = max(curr_seq_len, self.min_seq_length)
curr_seq_len = min(curr_seq_len, self.max_seq_length)
state.batch = set_batch_sequence_length(state.batch, curr_seq_len, self.truncate)
batch_size = state.batch['input_ids'].shape[0]
logger.data_batch({
'seq_length_warmup/curr_seq_len': curr_seq_len,
'seq_length_warmup/curr_bs': batch_size,
})