LSM571 commited on
Commit
ecf394b
·
verified ·
1 Parent(s): 5415f1a

New Update

Browse files
Files changed (2) hide show
  1. README.md +3 -1
  2. laragen/modules/transformer.py +40 -127
README.md CHANGED
@@ -24,6 +24,8 @@ python generate.py --arousal 7.4 --valence 5.8 --seed 204000 --output outputs/ex
24
 
25
  Use matched PyTorch/torchaudio wheels for your platform. CUDA is recommended; `--device cpu` supports slow CPU inference. The WAV is 30 seconds, 32 kHz, mono, with loudness normalization. `--duration` accepts 0.5–30 seconds. A JSON sidecar records the inputs and seed.
26
 
 
 
27
  Arousal and valence are continuous values in **[1, 9]**. Numeric conditioning uses `[arousal, valence]`, normalized by `(x-5)/4`. The original prompt spelling is preserved: `Genarate an instrumental music with arousal 7.40 and valence 5.80.` Sampling uses temperature 1, top-k 250, top-p 0 and CFG 3. Paper samples use seeds `204000 + sample index`.
28
 
29
  ```python
@@ -51,7 +53,7 @@ export HF_HUB_OFFLINE=1
51
  export TRANSFORMERS_OFFLINE=1
52
  ```
53
 
54
- Then run `generate.py` as above. The loader uses FP32 modules with FP16 LM autocast on CUDA. Short CPU inference is tested; CUDA and full 30-second numerical parity have not been validated in this release environment.
55
 
56
  ## License
57
 
 
24
 
25
  Use matched PyTorch/torchaudio wheels for your platform. CUDA is recommended; `--device cpu` supports slow CPU inference. The WAV is 30 seconds, 32 kHz, mono, with loudness normalization. `--duration` accepts 0.5–30 seconds. A JSON sidecar records the inputs and seed.
26
 
27
+ Attention uses native PyTorch SDPA with `backend='torch'` and `memory_efficient=true`. No xformers installation is required. Streaming generation retains its KV cache, including support for decoding multiple new tokens per call.
28
+
29
  Arousal and valence are continuous values in **[1, 9]**. Numeric conditioning uses `[arousal, valence]`, normalized by `(x-5)/4`. The original prompt spelling is preserved: `Genarate an instrumental music with arousal 7.40 and valence 5.80.` Sampling uses temperature 1, top-k 250, top-p 0 and CFG 3. Paper samples use seeds `204000 + sample index`.
30
 
31
  ```python
 
53
  export TRANSFORMERS_OFFLINE=1
54
  ```
55
 
56
+ Then run `generate.py` as above. The loader uses FP32 modules with FP16 LM autocast on CUDA. Validated without xformers using PyTorch 2.1.1: CPU attention/streaming checks, CUDA FP16 streaming checks, and full 30-second generation on an NVIDIA A100 (32 kHz, mono, 960,000 samples).
57
 
58
  ## License
59
 
laragen/modules/transformer.py CHANGED
@@ -5,7 +5,7 @@
5
  # LICENSE-CODE file in the root directory of this release.
6
 
7
  """
8
- Transformer model, with streaming support, xformer attention support
9
  and easy causal attention with a potentially finite receptive field.
10
 
11
  See `StreamingTransformer` for more information.
@@ -20,38 +20,19 @@ import torch
20
  import torch.nn as nn
21
  from torch.nn import functional as F
22
  from torch.utils.checkpoint import checkpoint as torch_checkpoint
23
- try:
24
- from xformers import ops
25
- except ImportError:
26
- ops = None # Release uses the torch SDPA backend.
27
 
28
  from .rope import RotaryEmbedding
29
  from .streaming import StreamingModule
30
 
31
- _efficient_attention_backend: str = 'torch'
32
-
33
 
34
  def set_efficient_attention_backend(backend: str = 'torch'):
35
- # Using torch by default, it seems a bit faster on older P100 GPUs (~20% faster).
36
- global _efficient_attention_backend
37
- assert _efficient_attention_backend in ['xformers', 'torch']
38
- _efficient_attention_backend = backend
39
 
40
 
41
  def _get_attention_time_dimension(memory_efficient: bool) -> int:
42
- if _efficient_attention_backend == 'torch' and memory_efficient:
43
- return 2
44
- else:
45
- return 1
46
-
47
-
48
- def _is_profiled() -> bool:
49
- # Return true if we are currently running with a xformers profiler activated.
50
- try:
51
- from xformers.profiler import profiler
52
- except ImportError:
53
- return False
54
- return profiler._Profiler._CURRENT_PROFILER is not None
55
 
56
 
57
  def create_norm_fn(norm_type: str, dim: int, **kwargs) -> nn.Module:
@@ -93,10 +74,10 @@ def create_sin_embedding(positions: torch.Tensor, dim: int, max_period: float =
93
 
94
 
95
  def expand_repeated_kv(x: torch.Tensor, n_rep: int, memory_efficient: bool) -> torch.Tensor:
96
- """torch.repeat_interleave(x, dim=2, repeats=n_rep) from xlformers."""
97
  if n_rep == 1:
98
  return x
99
- if _efficient_attention_backend == 'torch' and memory_efficient:
100
  bs, n_kv_heads, slen, head_dim = x.shape
101
  return (
102
  x[:, :, None, :, :]
@@ -149,7 +130,7 @@ class StreamingMultiheadAttention(StreamingModule):
149
  causal (bool): Causal mask applied automatically.
150
  past_context (int, optional): Receptive field for the causal mask, infinite if None.
151
  custom (bool): Use custom MHA implementation, for testing / benchmarking.
152
- memory_efficient (bool): Use xformers based memory efficient attention.
153
  attention_as_float32 (bool): Perform the attention as float32
154
  (especially important with memory_efficient as autocast won't do this automatically).
155
  rope (`RotaryEmbedding`, optional): Rope embedding to use.
@@ -157,7 +138,7 @@ class StreamingMultiheadAttention(StreamingModule):
157
  All keys and values must be available at once, streaming is only for the queries.
158
  Cannot be used with `causal` or `rope` (as it wouldn't make sens to
159
  interpret the time steps in the keys relative to those in the queries).
160
- safe_streaming (bool): Bug fix, will go away with xformers update.
161
  qk_layer_norm (bool): Layer normalization applied to queries and keys before dot product.
162
  kv_repeat (int): If > 1, will repeat keys and queries multiple times (need to divide num_heads).
163
  This will lead to faster decoding time on A100 or other GPUs with tensorcore.
@@ -190,9 +171,6 @@ class StreamingMultiheadAttention(StreamingModule):
190
  assert not causal, "Causal cannot work with cross attention."
191
  assert rope is None, "Rope cannot work with cross attention."
192
 
193
- if memory_efficient:
194
- _verify_xformers_memory_efficient_compat()
195
-
196
  self.custom = _is_custom(custom, memory_efficient)
197
  if self.custom:
198
  out_dim = embed_dim
@@ -236,24 +214,21 @@ class StreamingMultiheadAttention(StreamingModule):
236
  def _get_mask(self, current_steps: int, device: torch.device, dtype: torch.dtype):
237
  # Return a causal mask, accounting for potentially stored past keys/values
238
  # We actually return a bias for the attention score, as this has the same
239
- # convention both in the builtin MHA in Pytorch, and Xformers functions.
240
  time_dim = _get_attention_time_dimension(self.memory_efficient)
241
- if self.memory_efficient:
242
- from xformers.ops import LowerTriangularMask
243
- if current_steps == 1:
244
- # If we only have one step, then we do not need a mask.
245
- return None
246
- elif 'past_keys' in self._streaming_state:
247
- raise RuntimeError("Not supported at the moment")
248
- else:
249
- # Then we can safely use a lower triangular mask
250
- return LowerTriangularMask()
251
- if self._streaming_state:
252
  past_keys = self._streaming_state['past_keys']
253
  past_steps = past_keys.shape[time_dim]
254
  else:
255
  past_steps = 0
256
 
 
 
 
 
 
 
 
257
  queries_pos = torch.arange(
258
  past_steps, current_steps + past_steps, device=device).view(-1, 1)
259
  keys_pos = torch.arange(past_steps + current_steps, device=device).view(1, -1)
@@ -291,13 +266,13 @@ class StreamingMultiheadAttention(StreamingModule):
291
  if self.past_context is not None:
292
  offset = max(0, nk.shape[time_dim] - self.past_context)
293
  if self._is_streaming:
294
- self._streaming_state['past_keys'] = nk[:, offset:]
295
  if v is not k:
296
- self._streaming_state['past_values'] = nv[:, offset:]
297
  if 'offset' in self._streaming_state:
298
  self._streaming_state['offset'] += offset
299
  else:
300
- self._streaming_state['offset'] = torch.tensor(0)
301
  return nk, nv
302
 
303
  def _apply_rope(self, query: torch.Tensor, key: torch.Tensor):
@@ -305,7 +280,7 @@ class StreamingMultiheadAttention(StreamingModule):
305
  # Apply rope embeddings to query and key tensors.
306
  assert self.rope is not None
307
  if 'past_keys' in self._streaming_state:
308
- past_keys_offset = self._streaming_state['past_keys'].shape[1]
309
  else:
310
  past_keys_offset = 0
311
  if 'offset' in self._streaming_state:
@@ -331,8 +306,6 @@ class StreamingMultiheadAttention(StreamingModule):
331
  assert self.causal or self.cross_attention, \
332
  "Streaming only available for causal or cross attention"
333
 
334
- custom_attn_mask = attn_mask is not None
335
-
336
  if self.causal:
337
  assert attn_mask is None
338
  # At the moment we specialize only for the self-attention case.
@@ -363,10 +336,8 @@ class StreamingMultiheadAttention(StreamingModule):
363
  k = self.k_layer_norm(k)
364
  q, k, v = [rearrange(x, f"b t (h d) -> {layout}", h=self.num_heads) for x in [q, k, v]]
365
  else:
366
- if not _is_profiled():
367
- # profiling breaks that propertysomehow.
368
- assert query is key, "specialized implementation"
369
- assert value is key, "specialized implementation"
370
  projected = nn.functional.linear(query, self.in_proj_weight, self.in_proj_bias)
371
  if self.kv_repeat == 1:
372
  if time_dim == 2:
@@ -374,7 +345,7 @@ class StreamingMultiheadAttention(StreamingModule):
374
  else:
375
  bound_layout = "b t p h d"
376
  packed = rearrange(projected, f"b t (p h d) -> {bound_layout}", p=3, h=self.num_heads)
377
- q, k, v = ops.unbind(packed, dim=2)
378
  else:
379
  embed_dim = self.embed_dim
380
  per_head_dim = (embed_dim // self.num_heads)
@@ -403,20 +374,18 @@ class StreamingMultiheadAttention(StreamingModule):
403
  if self.attention_as_float32:
404
  q, k, v = [x.float() for x in [q, k, v]]
405
  if self.memory_efficient:
406
- if custom_attn_mask:
407
- # When using a custom attn mask:
408
- # Move to query's device, repeat for each sample, remove align8 padding
409
- seq_len = query.shape[1]
410
- attn_mask = attn_mask.to(q.dtype)
411
- attn_mask = attn_mask.repeat((q.shape[0], 1, 1, 1))
412
- attn_mask = attn_mask[..., :seq_len, :seq_len]
413
-
414
  p = self.dropout if self.training else 0
415
- if _efficient_attention_backend == 'torch':
416
- x = torch.nn.functional.scaled_dot_product_attention(
417
- q, k, v, is_causal=attn_mask is not None, dropout_p=p)
418
- else:
419
- x = ops.memory_efficient_attention(q, k, v, attn_mask, p=p)
420
  else:
421
  # We include the dot product as float32, for consistency
422
  # with the other implementations that include that step
@@ -469,7 +438,7 @@ class StreamingTransformerLayer(nn.TransformerEncoderLayer):
469
  causal (bool): Causal mask applied automatically.
470
  past_context (int, optional): Receptive field for the causal mask, infinite if None.
471
  custom (bool): Use custom MHA implementation, for testing / benchmarking.
472
- memory_efficient (bool): Use xformers based memory efficient attention.
473
  attention_as_float32 (bool): Perform the attention as float32
474
  (especially important with memory_efficient as autocast won't do this automatically).
475
  qk_layer_norm (bool): Layer normalization applied to queries and keys before dot product in attention.
@@ -590,7 +559,7 @@ class StreamingTransformer(StreamingModule):
590
  causal (bool): Causal mask applied automatically.
591
  past_context (int, optional): Receptive field for the causal mask, infinite if None.
592
  custom (bool): Use custom MHA implementation, for testing / benchmarking.
593
- memory_efficient (bool): Use xformers based memory efficient attention.
594
  attention_as_float32 (bool): Perform the attention as float32
595
  (especially important with memory_efficient as autocast won't do this automatically).
596
  cross_attention (bool): If True, expect to get secondary input for cross-attention.
@@ -607,9 +576,7 @@ class StreamingTransformer(StreamingModule):
607
  checkpointing (str): Checkpointing strategy to reduce memory usage.
608
  No checkpointing if set to 'none'. Per layer checkpointing using PyTorch
609
  if set to 'torch' (entire layer checkpointed, i.e. linears are evaluated twice,
610
- minimal memory usage, but maximal runtime). Finally, `xformers_default` provide
611
- a policy for opting-out some operations of the checkpointing like
612
- linear layers and attention, providing a middle ground between speed and memory.
613
  device (torch.device, optional): Device on which to initialize.
614
  dtype (torch.dtype, optional): dtype to use.
615
  **kwargs: See `nn.TransformerEncoderLayer`.
@@ -641,9 +608,7 @@ class StreamingTransformer(StreamingModule):
641
 
642
  self.checkpointing = checkpointing
643
 
644
- assert checkpointing in ['none', 'torch', 'xformers_default', 'xformers_mm']
645
- if self.checkpointing.startswith('xformers'):
646
- _verify_xformers_internal_compat()
647
 
648
  self.layers = nn.ModuleList()
649
  for idx in range(num_layers):
@@ -668,28 +633,6 @@ class StreamingTransformer(StreamingModule):
668
  return layer(*args, **kwargs)
669
  elif method == 'torch':
670
  return torch_checkpoint(layer, *args, use_reentrant=False, **kwargs)
671
- elif method.startswith('xformers'):
672
- from xformers.checkpoint_fairinternal import checkpoint, _get_default_policy
673
- if method == 'xformers_default':
674
- # those operations will be saved, and not recomputed.
675
- # According to Francisco we can get smarter policies but this is a good start.
676
- allow_list = [
677
- "xformers.efficient_attention_forward_cutlass.default",
678
- "xformers_flash.flash_fwd.default",
679
- "aten.addmm.default",
680
- "aten.mm.default",
681
- ]
682
- elif method == 'xformers_mm':
683
- # those operations will be saved, and not recomputed.
684
- # According to Francisco we can get smarter policies but this is a good start.
685
- allow_list = [
686
- "aten.addmm.default",
687
- "aten.mm.default",
688
- ]
689
- else:
690
- raise ValueError(f"xformers checkpointing xformers policy {method} is not known.")
691
- policy_fn = _get_default_policy(allow_list)
692
- return checkpoint(layer, *args, policy_fn=policy_fn, **kwargs)
693
  else:
694
  raise ValueError(f"Checkpointing method {method} is unknown.")
695
 
@@ -724,35 +667,5 @@ class StreamingTransformer(StreamingModule):
724
  return group
725
 
726
 
727
- # special attention related function
728
-
729
- def _verify_xformers_memory_efficient_compat():
730
- try:
731
- from xformers.ops import memory_efficient_attention, LowerTriangularMask # noqa
732
- except ImportError:
733
- raise ImportError(
734
- "xformers is not installed. Please install it and try again.\n"
735
- "To install on AWS and Azure, run \n"
736
- "FORCE_CUDA=1 TORCH_CUDA_ARCH_LIST='8.0'\\\n"
737
- "pip install -U git+https://git@github.com/fairinternal/xformers.git#egg=xformers\n"
738
- "To install on FAIR Cluster, run \n"
739
- "FORCE_CUDA=1 TORCH_CUDA_ARCH_LIST='6.0;7.0'\\\n"
740
- "pip install -U git+https://git@github.com/fairinternal/xformers.git#egg=xformers\n")
741
-
742
-
743
- def _verify_xformers_internal_compat():
744
- try:
745
- from xformers.checkpoint_fairinternal import checkpoint, _get_default_policy # noqa
746
- except ImportError:
747
- raise ImportError(
748
- "Francisco's fairinternal xformers is not installed. Please install it and try again.\n"
749
- "To install on AWS and Azure, run \n"
750
- "FORCE_CUDA=1 TORCH_CUDA_ARCH_LIST='8.0'\\\n"
751
- "pip install -U git+https://git@github.com/fairinternal/xformers.git#egg=xformers\n"
752
- "To install on FAIR Cluster, run \n"
753
- "FORCE_CUDA=1 TORCH_CUDA_ARCH_LIST='6.0;7.0'\\\n"
754
- "pip install -U git+https://git@github.com/fairinternal/xformers.git#egg=xformers\n")
755
-
756
-
757
  def _is_custom(custom: bool, memory_efficient: bool):
758
  return custom or memory_efficient
 
5
  # LICENSE-CODE file in the root directory of this release.
6
 
7
  """
8
+ Transformer model, with streaming support, PyTorch SDPA attention
9
  and easy causal attention with a potentially finite receptive field.
10
 
11
  See `StreamingTransformer` for more information.
 
20
  import torch.nn as nn
21
  from torch.nn import functional as F
22
  from torch.utils.checkpoint import checkpoint as torch_checkpoint
 
 
 
 
23
 
24
  from .rope import RotaryEmbedding
25
  from .streaming import StreamingModule
26
 
 
 
27
 
28
  def set_efficient_attention_backend(backend: str = 'torch'):
29
+ """Keep the inference backend selection API; only PyTorch SDPA is supported."""
30
+ if backend != 'torch':
31
+ raise ValueError(f"Only the torch attention backend is supported, got {backend!r}.")
 
32
 
33
 
34
  def _get_attention_time_dimension(memory_efficient: bool) -> int:
35
+ return 2 if memory_efficient else 1
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
 
38
  def create_norm_fn(norm_type: str, dim: int, **kwargs) -> nn.Module:
 
74
 
75
 
76
  def expand_repeated_kv(x: torch.Tensor, n_rep: int, memory_efficient: bool) -> torch.Tensor:
77
+ """Repeat KV heads in the attention implementation's tensor layout."""
78
  if n_rep == 1:
79
  return x
80
+ if memory_efficient:
81
  bs, n_kv_heads, slen, head_dim = x.shape
82
  return (
83
  x[:, :, None, :, :]
 
130
  causal (bool): Causal mask applied automatically.
131
  past_context (int, optional): Receptive field for the causal mask, infinite if None.
132
  custom (bool): Use custom MHA implementation, for testing / benchmarking.
133
+ memory_efficient (bool): Use PyTorch scaled dot product attention (SDPA).
134
  attention_as_float32 (bool): Perform the attention as float32
135
  (especially important with memory_efficient as autocast won't do this automatically).
136
  rope (`RotaryEmbedding`, optional): Rope embedding to use.
 
138
  All keys and values must be available at once, streaming is only for the queries.
139
  Cannot be used with `causal` or `rope` (as it wouldn't make sens to
140
  interpret the time steps in the keys relative to those in the queries).
141
+ safe_streaming (bool): Compute manual streaming attention scores in FP32 on CUDA.
142
  qk_layer_norm (bool): Layer normalization applied to queries and keys before dot product.
143
  kv_repeat (int): If > 1, will repeat keys and queries multiple times (need to divide num_heads).
144
  This will lead to faster decoding time on A100 or other GPUs with tensorcore.
 
171
  assert not causal, "Causal cannot work with cross attention."
172
  assert rope is None, "Rope cannot work with cross attention."
173
 
 
 
 
174
  self.custom = _is_custom(custom, memory_efficient)
175
  if self.custom:
176
  out_dim = embed_dim
 
214
  def _get_mask(self, current_steps: int, device: torch.device, dtype: torch.dtype):
215
  # Return a causal mask, accounting for potentially stored past keys/values
216
  # We actually return a bias for the attention score, as this has the same
217
+ # convention in both builtin PyTorch MHA and SDPA.
218
  time_dim = _get_attention_time_dimension(self.memory_efficient)
219
+ if 'past_keys' in self._streaming_state:
 
 
 
 
 
 
 
 
 
 
220
  past_keys = self._streaming_state['past_keys']
221
  past_steps = past_keys.shape[time_dim]
222
  else:
223
  past_steps = 0
224
 
225
+ if self.memory_efficient and self.past_context is None:
226
+ # SDPA handles an uncached square causal attention natively. A single
227
+ # cached query can attend to all keys; a cached chunk needs the
228
+ # offset-aware mask below rather than SDPA's upper-left triangle.
229
+ if past_steps == 0 or current_steps == 1:
230
+ return None
231
+
232
  queries_pos = torch.arange(
233
  past_steps, current_steps + past_steps, device=device).view(-1, 1)
234
  keys_pos = torch.arange(past_steps + current_steps, device=device).view(1, -1)
 
266
  if self.past_context is not None:
267
  offset = max(0, nk.shape[time_dim] - self.past_context)
268
  if self._is_streaming:
269
+ self._streaming_state['past_keys'] = nk.narrow(time_dim, offset, nk.shape[time_dim] - offset)
270
  if v is not k:
271
+ self._streaming_state['past_values'] = nv.narrow(time_dim, offset, nv.shape[time_dim] - offset)
272
  if 'offset' in self._streaming_state:
273
  self._streaming_state['offset'] += offset
274
  else:
275
+ self._streaming_state['offset'] = torch.tensor(offset)
276
  return nk, nv
277
 
278
  def _apply_rope(self, query: torch.Tensor, key: torch.Tensor):
 
280
  # Apply rope embeddings to query and key tensors.
281
  assert self.rope is not None
282
  if 'past_keys' in self._streaming_state:
283
+ past_keys_offset = self._streaming_state['past_keys'].shape[time_dim]
284
  else:
285
  past_keys_offset = 0
286
  if 'offset' in self._streaming_state:
 
306
  assert self.causal or self.cross_attention, \
307
  "Streaming only available for causal or cross attention"
308
 
 
 
309
  if self.causal:
310
  assert attn_mask is None
311
  # At the moment we specialize only for the self-attention case.
 
336
  k = self.k_layer_norm(k)
337
  q, k, v = [rearrange(x, f"b t (h d) -> {layout}", h=self.num_heads) for x in [q, k, v]]
338
  else:
339
+ assert query is key, "specialized implementation"
340
+ assert value is key, "specialized implementation"
 
 
341
  projected = nn.functional.linear(query, self.in_proj_weight, self.in_proj_bias)
342
  if self.kv_repeat == 1:
343
  if time_dim == 2:
 
345
  else:
346
  bound_layout = "b t p h d"
347
  packed = rearrange(projected, f"b t (p h d) -> {bound_layout}", p=3, h=self.num_heads)
348
+ q, k, v = torch.unbind(packed, dim=2)
349
  else:
350
  embed_dim = self.embed_dim
351
  per_head_dim = (embed_dim // self.num_heads)
 
374
  if self.attention_as_float32:
375
  q, k, v = [x.float() for x in [q, k, v]]
376
  if self.memory_efficient:
377
+ if attn_mask is not None:
378
+ # Preserve MHA's boolean convention: True masks out a key.
379
+ if attn_mask.dtype == torch.bool:
380
+ attn_mask = torch.zeros_like(attn_mask, dtype=q.dtype).masked_fill(
381
+ attn_mask, float('-inf'))
382
+ attn_mask = attn_mask.to(device=q.device, dtype=q.dtype)
383
+ if attn_mask.dim() == 3 and attn_mask.shape[0] == q.shape[0] * self.num_heads:
384
+ attn_mask = attn_mask.unflatten(0, (q.shape[0], self.num_heads))
385
  p = self.dropout if self.training else 0
386
+ sdpa_is_causal = self.causal and attn_mask is None and q.shape[2] == k.shape[2]
387
+ x = F.scaled_dot_product_attention(
388
+ q, k, v, attn_mask=attn_mask, is_causal=sdpa_is_causal, dropout_p=p)
 
 
389
  else:
390
  # We include the dot product as float32, for consistency
391
  # with the other implementations that include that step
 
438
  causal (bool): Causal mask applied automatically.
439
  past_context (int, optional): Receptive field for the causal mask, infinite if None.
440
  custom (bool): Use custom MHA implementation, for testing / benchmarking.
441
+ memory_efficient (bool): Use PyTorch scaled dot product attention (SDPA).
442
  attention_as_float32 (bool): Perform the attention as float32
443
  (especially important with memory_efficient as autocast won't do this automatically).
444
  qk_layer_norm (bool): Layer normalization applied to queries and keys before dot product in attention.
 
559
  causal (bool): Causal mask applied automatically.
560
  past_context (int, optional): Receptive field for the causal mask, infinite if None.
561
  custom (bool): Use custom MHA implementation, for testing / benchmarking.
562
+ memory_efficient (bool): Use PyTorch scaled dot product attention (SDPA).
563
  attention_as_float32 (bool): Perform the attention as float32
564
  (especially important with memory_efficient as autocast won't do this automatically).
565
  cross_attention (bool): If True, expect to get secondary input for cross-attention.
 
576
  checkpointing (str): Checkpointing strategy to reduce memory usage.
577
  No checkpointing if set to 'none'. Per layer checkpointing using PyTorch
578
  if set to 'torch' (entire layer checkpointed, i.e. linears are evaluated twice,
579
+ minimal memory usage, but maximal runtime).
 
 
580
  device (torch.device, optional): Device on which to initialize.
581
  dtype (torch.dtype, optional): dtype to use.
582
  **kwargs: See `nn.TransformerEncoderLayer`.
 
608
 
609
  self.checkpointing = checkpointing
610
 
611
+ assert checkpointing in ['none', 'torch']
 
 
612
 
613
  self.layers = nn.ModuleList()
614
  for idx in range(num_layers):
 
633
  return layer(*args, **kwargs)
634
  elif method == 'torch':
635
  return torch_checkpoint(layer, *args, use_reentrant=False, **kwargs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
636
  else:
637
  raise ValueError(f"Checkpointing method {method} is unknown.")
638
 
 
667
  return group
668
 
669
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  def _is_custom(custom: bool, memory_efficient: bool):
671
  return custom or memory_efficient