ltttttttttttttt commited on
Commit
e256e9b
·
verified ·
1 Parent(s): 151baa0

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. REGEN-main/cosmos_policy/_src/imaginaire/__init__.py +15 -0
  2. REGEN-main/cosmos_policy/_src/imaginaire/attention/README.md +47 -0
  3. REGEN-main/cosmos_policy/_src/imaginaire/attention/__init__.py +29 -0
  4. REGEN-main/cosmos_policy/_src/imaginaire/attention/backends.py +348 -0
  5. REGEN-main/cosmos_policy/_src/imaginaire/attention/checks.py +500 -0
  6. REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/__init__.py +97 -0
  7. REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/checks.py +128 -0
  8. REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/cudnn_forward.py +411 -0
  9. REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/functions.py +262 -0
  10. REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/meta.py +63 -0
  11. REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/stubs.py +46 -0
  12. REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/README.md +10 -0
  13. REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/apis.md +28 -0
  14. REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/backends.md +73 -0
  15. REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/features.md +151 -0
  16. REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/multi-dim.md +111 -0
  17. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/README.md +71 -0
  18. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/__init__.py +96 -0
  19. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/checks.py +112 -0
  20. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/functions.py +170 -0
  21. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/meta.py +64 -0
  22. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/stubs.py +46 -0
  23. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/__init__.py +94 -0
  24. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/checks.py +134 -0
  25. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/functions.py +184 -0
  26. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/meta.py +64 -0
  27. REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/stubs.py +46 -0
  28. REGEN-main/cosmos_policy/_src/imaginaire/attention/frontend.py +587 -0
  29. REGEN-main/cosmos_policy/_src/imaginaire/attention/masks.py +61 -0
  30. REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/__init__.py +95 -0
  31. REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/checks.py +391 -0
  32. REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/functions.py +293 -0
  33. REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/meta.py +67 -0
  34. REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/stubs.py +64 -0
  35. REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/multi_dim_test.py +503 -0
  36. REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/sdpa_test.py +1015 -0
  37. REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/torch_compile_test.py +365 -0
  38. REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/varlen_test.py +711 -0
  39. REGEN-main/cosmos_policy/_src/imaginaire/attention/utils/__init__.py +83 -0
  40. REGEN-main/cosmos_policy/_src/imaginaire/attention/utils/environment.py +36 -0
  41. REGEN-main/cosmos_policy/_src/imaginaire/attention/utils/safe_log.py +65 -0
  42. REGEN-main/cosmos_policy/_src/imaginaire/attention/varlen.py +120 -0
  43. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/__init__.py +14 -0
  44. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/__init__.py +14 -0
  45. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/__init__.py +14 -0
  46. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/blocklist.py +248 -0
  47. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/blocklist_test.py +57 -0
  48. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/profile_blocklist.py +59 -0
  49. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/utils.py +45 -0
  50. REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/common/__init__.py +14 -0
REGEN-main/cosmos_policy/_src/imaginaire/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
REGEN-main/cosmos_policy/_src/imaginaire/attention/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Imaginaire Attention Subpackage
2
+
3
+ A subpackage within cosmos_policy._src.imaginaire that integrates only the best and most reliable
4
+ solutions, and provides simple APIs to end-users.
5
+
6
+ For more information, please refer to the [docs](docs/).
7
+
8
+ ## Basic API
9
+
10
+ ```python
11
+ from cosmos_policy._src.imaginaire.attention import attention
12
+
13
+ output = attention(
14
+ query=query,
15
+ key=key,
16
+ value=value,
17
+ )
18
+ ```
19
+
20
+ * **Optional** `scale`: attention (softmax/dot product) scale. Defaults to `head_dim ** -0.5`.
21
+ * **Optional** `return_lse`: returns logsumexp if `True`
22
+ * **Optional** `backend`: explicitly set backend instead of automatically selecting the best compatible
23
+
24
+ ## Tensor layouts
25
+
26
+ Imaginaire Attention only supports one tensor memory layout:
27
+ heads-last torch contiguous (`torch.contiguous_format`).
28
+
29
+ With this layout, input tensors `query`, `key`, and `value` are represented as rank-4 tensors, with
30
+ dimension 0 representing batch, dimension 1 representing sequence length, dimension 2 representing
31
+ attention heads, and dimension 3 representing head dimension.
32
+ This layout is also consistent with the `contiguous_format` memory layout in PyTorch, meaning the
33
+ right-most dimension (head dimension) is the major dimension (has stride 1), and tokens from
34
+ different heads are interleaved.
35
+
36
+ ```python
37
+ def verify_heads_last_contig_tensor(x: Tensor):
38
+ assert x.shape[0] == batch
39
+ assert x.shape[1] == seqlen
40
+ assert x.shape[2] == heads
41
+ assert x.shape[3] == head_dim
42
+
43
+ assert x.stride(3) == 1
44
+ assert x.stride(2) == head_dim
45
+ assert x.stride(1) == heads * head_dim
46
+ assert x.stride(0) == heads * head_dim * seqlen
47
+ ```
REGEN-main/cosmos_policy/_src/imaginaire/attention/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+
21
+ """
22
+
23
+ from cosmos_policy._src.imaginaire.attention.frontend import (
24
+ attention,
25
+ multi_dimensional_attention,
26
+ spatio_temporal_attention,
27
+ )
28
+
29
+ __all__ = ["attention", "multi_dimensional_attention", "spatio_temporal_attention"]
REGEN-main/cosmos_policy/_src/imaginaire/attention/backends.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Frontend APIs
21
+ """
22
+
23
+ from torch import Tensor
24
+
25
+ from cosmos_policy._src.imaginaire.attention.cudnn.checks import cudnn_attention_check
26
+ from cosmos_policy._src.imaginaire.attention.flash2.checks import flash2_attention_check
27
+ from cosmos_policy._src.imaginaire.attention.flash3.checks import flash3_attention_check
28
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
29
+ from cosmos_policy._src.imaginaire.attention.natten.checks import (
30
+ natten_attention_check,
31
+ natten_multi_dim_attention_check,
32
+ )
33
+ from cosmos_policy._src.imaginaire.attention.utils import get_arch_tag
34
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
35
+
36
+ BACKEND_CHECK_MAP = {
37
+ "cudnn": cudnn_attention_check,
38
+ "natten": natten_attention_check,
39
+ "flash2": flash2_attention_check,
40
+ "flash3": flash3_attention_check,
41
+ }
42
+
43
+ BACKEND_MULTI_DIM_CHECK_MAP = {
44
+ "natten": natten_multi_dim_attention_check,
45
+ }
46
+
47
+
48
+ def is_backend_compatible(
49
+ backend: str,
50
+ query: Tensor,
51
+ key: Tensor,
52
+ value: Tensor,
53
+ is_causal: bool,
54
+ causal_type: CausalType | None,
55
+ is_varlen: bool,
56
+ raise_error: bool = False,
57
+ ) -> bool:
58
+ """
59
+ Input validation function a specified backend.
60
+ Runs the common and backend-specific checks. Returns False if any checks fail, otherwise True.
61
+
62
+ Parameters:
63
+ backend (str): selected backend.
64
+
65
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
66
+ (`[batch, seqlen, heads, head_dim]`).
67
+
68
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
69
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
70
+
71
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
72
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
73
+
74
+ is_causal (bool): whether or not causal masking is enabled.
75
+
76
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
77
+ `CausalType.BottomRight`. Required when `is_causal = True`.
78
+
79
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
80
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
81
+ passed.
82
+
83
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
84
+ instead of just returning False. Default is False.
85
+
86
+ Returns:
87
+ success (bool): whether use case is compatible with the backend.
88
+
89
+ """
90
+ if backend is None:
91
+ raise ValueError("Cannot pass None backend to is_backend_compatible.")
92
+
93
+ if backend not in BACKEND_CHECK_MAP:
94
+ raise ValueError(f"Unrecognized backend name {backend}.")
95
+
96
+ return BACKEND_CHECK_MAP[backend](
97
+ query=query,
98
+ key=key,
99
+ value=value,
100
+ is_causal=is_causal,
101
+ causal_type=causal_type,
102
+ is_varlen=is_varlen,
103
+ raise_error=raise_error,
104
+ )
105
+
106
+
107
+ def get_backend_list(arch_tag: int) -> list[str]:
108
+ """
109
+ Returns list of supported backends according to arch tag (attention.utils.get_arch_tag).
110
+ Backends are ordered based on their known performance levels, so that the best-performing
111
+ compatible backend is selected.
112
+
113
+ Parameters:
114
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
115
+
116
+ Returns:
117
+ backend_list (list[str]): a list of backend names (string). Empty if device is not supported.
118
+
119
+ """
120
+
121
+ if arch_tag < 75:
122
+ log.debug(f"Minimum architecture supported for Attention is 75, got {arch_tag=}.")
123
+ return []
124
+
125
+ if arch_tag == 90:
126
+ return [
127
+ "flash3",
128
+ "cudnn",
129
+ "natten",
130
+ "flash2",
131
+ ]
132
+
133
+ if arch_tag in [100, 103]:
134
+ return [
135
+ # "flash4",
136
+ "cudnn",
137
+ "natten",
138
+ "flash2",
139
+ ]
140
+
141
+ if arch_tag >= 80:
142
+ return [
143
+ "flash2",
144
+ "cudnn",
145
+ "natten",
146
+ ]
147
+
148
+ return ["natten"]
149
+
150
+
151
+ def choose_backend(
152
+ query: Tensor,
153
+ key: Tensor,
154
+ value: Tensor,
155
+ is_causal: bool,
156
+ causal_type: CausalType | None,
157
+ is_varlen: bool,
158
+ backend: str | None = None,
159
+ raise_error: bool = True,
160
+ ) -> str | None:
161
+ """
162
+ Selects a compatible backend, unless one is already selected, which runs its corresponding
163
+ checks.
164
+
165
+ Parameters:
166
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
167
+ (`[batch, seqlen, heads, head_dim]`).
168
+
169
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
170
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
171
+
172
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
173
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
174
+
175
+ is_causal (bool): whether or not causal masking is enabled.
176
+
177
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
178
+ `CausalType.BottomRight`. Required when `is_causal = True`.
179
+
180
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
181
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
182
+ passed.
183
+
184
+ backend (str | None): selected backend, if any.
185
+
186
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
187
+ instead of just returning False. Default is **True**.
188
+
189
+ Returns:
190
+ backend (str | None): selected backend, or None if no backends are compatible.
191
+
192
+ """
193
+ if backend is not None:
194
+ if is_backend_compatible(
195
+ backend=backend,
196
+ query=query,
197
+ key=key,
198
+ value=value,
199
+ is_causal=is_causal,
200
+ causal_type=causal_type,
201
+ is_varlen=is_varlen,
202
+ raise_error=raise_error,
203
+ ):
204
+ return backend
205
+ return None
206
+
207
+ arch_tag = get_arch_tag(query.device)
208
+ backend_list = get_backend_list(arch_tag)
209
+ for backend in backend_list:
210
+ if is_backend_compatible(
211
+ backend=backend,
212
+ query=query,
213
+ key=key,
214
+ value=value,
215
+ is_causal=is_causal,
216
+ causal_type=causal_type,
217
+ is_varlen=is_varlen,
218
+ raise_error=False,
219
+ ):
220
+ return backend
221
+
222
+ if not raise_error:
223
+ return None
224
+
225
+ raise ValueError(
226
+ "Could not find a compatible Attention backend for this use case / device. "
227
+ "Try running with debug logs to find out why."
228
+ )
229
+
230
+
231
+ def is_multi_dim_backend_compatible(
232
+ backend: str,
233
+ query: Tensor,
234
+ key: Tensor,
235
+ value: Tensor,
236
+ raise_error: bool = False,
237
+ ) -> bool:
238
+ """
239
+ Input validation function a specified multi-dimensional backend.
240
+ Runs the common and backend-specific checks. Returns False if any checks fail, otherwise True.
241
+
242
+ Parameters:
243
+ backend (str): selected backend.
244
+
245
+ query (Tensor): 4-D, 5-D, or 6-D query tensor, with the heads-last contiguous layout
246
+ (`[batch, *token_layout_shape, heads, head_dim]`).
247
+
248
+ key (Tensor): 4-D, 5-D, or 6-D key tensor, with the heads-last contiguous layout
249
+ (`[batch, *token_layout_shape, heads_kv, head_dim]`).
250
+
251
+ value (Tensor): 4-D, 5-D, or 6-D value tensor, with heads-last contiguous layout
252
+ (`[batch, *token_layout_shape, heads_kv, head_dim_v]`).
253
+
254
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
255
+ instead of just returning False. Default is False.
256
+
257
+ Returns:
258
+ success (bool): whether use case is compatible with the backend.
259
+
260
+ """
261
+ if backend is None:
262
+ raise ValueError("Cannot pass None backend to is_backend_compatible.")
263
+
264
+ if backend not in BACKEND_MULTI_DIM_CHECK_MAP:
265
+ raise ValueError(f"Unrecognized backend name {backend}.")
266
+
267
+ return BACKEND_MULTI_DIM_CHECK_MAP[backend](
268
+ query=query,
269
+ key=key,
270
+ value=value,
271
+ raise_error=raise_error,
272
+ )
273
+
274
+
275
+ def get_multi_dim_backend_list(arch_tag: int) -> list[str]:
276
+ """
277
+ Returns list of supported multi-dimensional backends according to arch tag (attention.utils.get_arch_tag).
278
+ Backends are ordered based on their known performance levels, so that the best-performing
279
+ compatible backend is selected.
280
+
281
+ Parameters:
282
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
283
+
284
+ Returns:
285
+ backend_list (list[str]): a list of backend names (string). Empty if device is not supported.
286
+
287
+ """
288
+
289
+ if arch_tag < 75:
290
+ log.debug(f"Minimum architecture supported for Multi-Dimensional Attention is 75, got {arch_tag=}.")
291
+ return []
292
+
293
+ # NATTEN is the only supported backend for now
294
+ return ["natten"]
295
+
296
+
297
+ def choose_multi_dim_backend(
298
+ query: Tensor,
299
+ key: Tensor,
300
+ value: Tensor,
301
+ backend: str | None = None,
302
+ ) -> str:
303
+ """
304
+ Selects a compatible multi-dimensional backend, unless one is already selected, which runs its
305
+ corresponding checks.
306
+
307
+ Parameters:
308
+ query (Tensor): 4-D, 5-D, or 6-D query tensor, with the heads-last contiguous layout
309
+ (`[batch, *token_layout_shape, heads, head_dim]`).
310
+
311
+ key (Tensor): 4-D, 5-D, or 6-D key tensor, with the heads-last contiguous layout
312
+ (`[batch, *token_layout_shape, heads_kv, head_dim]`).
313
+
314
+ value (Tensor): 4-D, 5-D, or 6-D value tensor, with heads-last contiguous layout
315
+ (`[batch, *token_layout_shape, heads_kv, head_dim_v]`).
316
+
317
+ backend (str | None): selected backend, if any.
318
+
319
+ Returns:
320
+ backend (str): selected backend.
321
+
322
+ """
323
+ if backend is not None:
324
+ assert is_multi_dim_backend_compatible(
325
+ backend=backend,
326
+ query=query,
327
+ key=key,
328
+ value=value,
329
+ raise_error=True,
330
+ )
331
+ return backend
332
+
333
+ arch_tag = get_arch_tag(query.device)
334
+ backend_list = get_multi_dim_backend_list(arch_tag)
335
+ for backend in backend_list:
336
+ if is_multi_dim_backend_compatible(
337
+ backend=backend,
338
+ query=query,
339
+ key=key,
340
+ value=value,
341
+ raise_error=False,
342
+ ):
343
+ return backend
344
+
345
+ raise ValueError(
346
+ "Could not find a compatible Multi-Dimensional Attention backend for this use case / device. "
347
+ "Try running with debug logs to find out why."
348
+ )
REGEN-main/cosmos_policy/_src/imaginaire/attention/checks.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Common, op-specific, and backend-specific checks
21
+ """
22
+
23
+ from collections.abc import Sequence
24
+ from functools import partial
25
+ from typing import Any
26
+
27
+ import torch
28
+ from torch import Tensor
29
+
30
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
31
+ from cosmos_policy._src.imaginaire.attention.utils import log_or_raise_error
32
+ from cosmos_policy._src.imaginaire.attention.varlen import generate_varlen_parameters
33
+
34
+
35
+ def _universal_tensor_checks(query: Tensor, key: Tensor, value: Tensor, raise_error: bool = True) -> bool:
36
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
37
+
38
+ if query.is_sparse or key.is_sparse or value.is_sparse:
39
+ target_fn("This operation does not support sparse tensors.", exception=NotImplementedError)
40
+ return False
41
+
42
+ if query.is_nested or key.is_nested or value.is_nested:
43
+ target_fn("This operation does not support nested tensors.", exception=NotImplementedError)
44
+ return False
45
+
46
+ if query.device != key.device or query.device != value.device:
47
+ target_fn(
48
+ f"Query, key, and value must be on the same device, got {query.device=}, {key.device=}, {value.device=}.",
49
+ exception=ValueError,
50
+ )
51
+ return False
52
+
53
+ if query.dtype != key.dtype or query.dtype != value.dtype:
54
+ target_fn(
55
+ f"Query, key, and value must assume the same data type, got {query.dtype=}, {key.dtype=}, {value.dtype=}.",
56
+ exception=ValueError,
57
+ )
58
+ return False
59
+
60
+ return True
61
+
62
+
63
+ def _universal_attention_checks(
64
+ query: Tensor,
65
+ key: Tensor,
66
+ value: Tensor,
67
+ supported_dtypes_forward: list[torch.dtype] | None = None,
68
+ supported_dtypes_backward: list[torch.dtype] | None = None,
69
+ supports_mla: bool = True,
70
+ supports_gqa_mqa: bool = True,
71
+ raise_error: bool = True,
72
+ backend_name: str | None = None,
73
+ ) -> bool:
74
+ backend_name = backend_name or "Attention"
75
+ if not _universal_tensor_checks(query, key, value, raise_error=raise_error):
76
+ return False
77
+
78
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
79
+
80
+ if query.dim() != key.dim() or query.dim() != value.dim():
81
+ target_fn(
82
+ f"Q, K, and V must have the same rank, got {query.dim()=}, {key.dim()=}, {value.dim()=}.",
83
+ exception=ValueError,
84
+ )
85
+ return False
86
+
87
+ if query.shape[0] != key.shape[0] or query.shape[0] != value.shape[0]:
88
+ target_fn(
89
+ f"Q, K, and V must match in batch size, got {query.shape[0]=}, {key.shape[0]=}, {value.shape[0]=}.",
90
+ exception=ValueError,
91
+ )
92
+ return False
93
+
94
+ if query.shape[-1] != key.shape[-1]:
95
+ target_fn(
96
+ f"Q and K head dims must match, got {query.shape[-1]=}, {key.shape[-1]=}.",
97
+ exception=ValueError,
98
+ )
99
+ return False
100
+
101
+ if key.shape[-2] != value.shape[-2]:
102
+ target_fn(
103
+ f"K and V must always have the same number of heads, got {key.shape[2]=}, {value.shape[2]=}.",
104
+ exception=ValueError,
105
+ )
106
+ return False
107
+
108
+ if not supports_mla and query.shape[-1] != value.shape[-1]:
109
+ target_fn(
110
+ f"{backend_name} does not support different head dims for QK and V, got "
111
+ f"{query.shape[-1]=}, {value.shape[-1]=}.",
112
+ exception=ValueError,
113
+ )
114
+ return False
115
+
116
+ if not supports_gqa_mqa and (query.shape[-2] != key.shape[-2] or query.shape[-2] != value.shape[-2]):
117
+ target_fn(
118
+ f"{backend_name} does not support GQA/MQA, therefore number of heads in Q, K, and V "
119
+ f"must match, got {query.shape[-2]=}, {key.shape[-2]=}, {value.shape[-2]=}.",
120
+ exception=ValueError,
121
+ )
122
+ return False
123
+
124
+ if supports_gqa_mqa:
125
+ heads_q = query.shape[-2]
126
+ heads_kv = key.shape[-2]
127
+
128
+ if heads_q < heads_kv or heads_q % heads_kv != 0:
129
+ target_fn(
130
+ f"KV heads must evenly divide Q heads, got {heads_q=}, {heads_kv=}.",
131
+ exception=ValueError,
132
+ )
133
+ return False
134
+
135
+ # _universal_tensor_checks guarantees query.dtype == key.dtype == value.dtype
136
+ if supported_dtypes_forward is not None and query.dtype not in supported_dtypes_forward:
137
+ target_fn(
138
+ f"{backend_name} does not support forward pass (inference) with data type {query.dtype}; "
139
+ f"supported dtypes: {supported_dtypes_forward}.",
140
+ exception=ValueError,
141
+ )
142
+ return False
143
+
144
+ if supported_dtypes_backward is not None and query.requires_grad and query.dtype not in supported_dtypes_backward:
145
+ target_fn(
146
+ f"{backend_name} does not support backward pass (training) with data type {query.dtype}; "
147
+ f"supported dtypes: {supported_dtypes_backward}.",
148
+ exception=ValueError,
149
+ )
150
+ return False
151
+
152
+ return True
153
+
154
+
155
+ def attention_tensor_checks(
156
+ query: Tensor,
157
+ key: Tensor,
158
+ value: Tensor,
159
+ supported_dtypes_forward: list[torch.dtype] | None = None,
160
+ supported_dtypes_backward: list[torch.dtype] | None = None,
161
+ supports_mla: bool = True,
162
+ supports_gqa_mqa: bool = True,
163
+ raise_error: bool = True,
164
+ backend_name: str | None = None,
165
+ ) -> bool:
166
+ backend_name = backend_name or "Attention"
167
+ if not _universal_tensor_checks(query, key, value, raise_error=raise_error):
168
+ return False
169
+
170
+ if not _universal_attention_checks(
171
+ query=query,
172
+ key=key,
173
+ value=value,
174
+ supported_dtypes_forward=supported_dtypes_forward,
175
+ supported_dtypes_backward=supported_dtypes_backward,
176
+ supports_mla=supports_mla,
177
+ supports_gqa_mqa=supports_gqa_mqa,
178
+ raise_error=raise_error,
179
+ backend_name=backend_name,
180
+ ):
181
+ return False
182
+
183
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
184
+
185
+ if query.dim() != 4:
186
+ target_fn(
187
+ f"Attention expects 4-D tensors as inputs, got {query.dim()=}.",
188
+ exception=ValueError,
189
+ )
190
+ return False
191
+
192
+ if key.shape[1] != value.shape[1]:
193
+ target_fn(
194
+ f"K and V must match in sequence length, got {key.shape[1]=}, {value.shape[1]=}.",
195
+ exception=ValueError,
196
+ )
197
+ return False
198
+
199
+ return True
200
+
201
+
202
+ def varlen_tensor_checks(
203
+ query: Tensor,
204
+ key: Tensor,
205
+ value: Tensor,
206
+ seqlens_Q: Tensor | None = None,
207
+ seqlens_KV: Tensor | None = None,
208
+ cumulative_seqlen_Q: Tensor | None = None,
209
+ cumulative_seqlen_KV: Tensor | None = None,
210
+ max_seqlen_Q: int | None = None,
211
+ max_seqlen_KV: int | None = None,
212
+ ) -> tuple[None, None, int, int] | tuple[Tensor, Tensor, int, int]:
213
+ if query.shape[0] != key.shape[0] or query.shape[0] != value.shape[0]:
214
+ raise ValueError(
215
+ f"Q, K, and V must match in batch size, got {query.shape[0]=}, {key.shape[0]=}, {value.shape[0]=}."
216
+ )
217
+
218
+ if all(
219
+ x is None
220
+ for x in [
221
+ seqlens_Q,
222
+ seqlens_KV,
223
+ cumulative_seqlen_Q,
224
+ cumulative_seqlen_KV,
225
+ ]
226
+ ) and all(
227
+ x is None or x == 0
228
+ for x in [
229
+ max_seqlen_Q,
230
+ max_seqlen_KV,
231
+ ]
232
+ ):
233
+ # Not varlen
234
+ return None, None, 0, 0
235
+
236
+ if seqlens_Q is not None or seqlens_KV is not None:
237
+ # Generate cumulative_seqlen_{Q,KV}, max_seqlen_{Q,KV}, total_seqlen_{Q,KV}
238
+ # based on user input
239
+ return generate_varlen_parameters(
240
+ query=query,
241
+ key=key,
242
+ value=value,
243
+ seqlens_Q=seqlens_Q,
244
+ seqlens_KV=seqlens_KV,
245
+ )
246
+
247
+ # Validate user-input cumulative_seqlen_{Q,KV}, max_seqlen_{Q,KV}, total_seqlen_{Q,KV}
248
+ if any(
249
+ x is None
250
+ for x in [
251
+ cumulative_seqlen_Q,
252
+ cumulative_seqlen_KV,
253
+ max_seqlen_Q,
254
+ max_seqlen_KV,
255
+ ]
256
+ ) or any(
257
+ x == 0
258
+ for x in [
259
+ max_seqlen_Q,
260
+ max_seqlen_KV,
261
+ ]
262
+ ):
263
+ raise ValueError(
264
+ "Variable length Attention requires all 6 of "
265
+ "cumulative_seqlen_{Q,KV}, max_seqlen_{Q,KV}, total_seqlen_{Q,KV} to be set."
266
+ )
267
+
268
+ if query.shape[0] != 1:
269
+ raise ValueError(
270
+ f"Variable length Attention only supports sequence-packed memory layout (batch = 1), got {query.shape[0]=}."
271
+ )
272
+
273
+ assert cumulative_seqlen_Q is not None
274
+ assert cumulative_seqlen_KV is not None
275
+ assert max_seqlen_Q is not None
276
+ assert max_seqlen_KV is not None
277
+
278
+ if not isinstance(max_seqlen_Q, int) or not isinstance(max_seqlen_KV, int):
279
+ raise ValueError(
280
+ f"max_seqlen_Q and max_seqlen_KV must be ints, got {type(max_seqlen_Q)=}, {type(max_seqlen_KV)=}."
281
+ )
282
+
283
+ total_seqlen_Q = query.shape[1]
284
+ total_seqlen_KV = key.shape[1]
285
+ if max_seqlen_Q > total_seqlen_Q:
286
+ raise ValueError(f"Maximum sequence length cannot exceed total, got {max_seqlen_Q=}, {total_seqlen_Q=}.")
287
+
288
+ if max_seqlen_KV > total_seqlen_KV:
289
+ raise ValueError(f"Maximum sequence length cannot exceed total, got {max_seqlen_KV=}, {total_seqlen_KV=}.")
290
+
291
+ if max_seqlen_Q < 1 or max_seqlen_KV < 1:
292
+ raise ValueError(f"Maximum sequence length cannot be less than 1, got {max_seqlen_Q=}, {max_seqlen_KV=}.")
293
+
294
+ if not isinstance(cumulative_seqlen_Q, Tensor) or not isinstance(cumulative_seqlen_KV, Tensor):
295
+ raise ValueError("cumulative_seqlen_Q and cumulative_seqlen_KV must both be tensors.")
296
+
297
+ if cumulative_seqlen_Q.device != query.device or cumulative_seqlen_KV.device != query.device:
298
+ raise ValueError(
299
+ "cumulative_seqlen_Q and cumulative_seqlen_KV must be on the same device as QKV, but "
300
+ f"{cumulative_seqlen_Q.device=}, {cumulative_seqlen_KV.device=}, {query.device=}."
301
+ )
302
+
303
+ if cumulative_seqlen_Q.dtype != torch.int32 or cumulative_seqlen_KV.dtype != torch.int32:
304
+ raise ValueError(
305
+ "cumulative_seqlen_Q and cumulative_seqlen_KV must both be torch.int32 tensors, got "
306
+ f"{cumulative_seqlen_Q.dtype=}, {cumulative_seqlen_KV.dtype=}."
307
+ )
308
+
309
+ if cumulative_seqlen_Q.dim() != 1 or cumulative_seqlen_KV.dim() != 1:
310
+ raise ValueError(
311
+ "cumulative_seqlen_Q and cumulative_seqlen_KV must both be 1-D tensors, got "
312
+ f"{cumulative_seqlen_Q.dim()=}, {cumulative_seqlen_KV.dim()=}."
313
+ )
314
+
315
+ if cumulative_seqlen_Q.shape[0] != cumulative_seqlen_KV.shape[0]:
316
+ raise ValueError(
317
+ "cumulative_seqlen_Q and cumulative_seqlen_KV must match in size, got "
318
+ f"{cumulative_seqlen_Q.shape=}, {cumulative_seqlen_KV.shape=}."
319
+ )
320
+
321
+ if cumulative_seqlen_Q.shape[0] < 2:
322
+ raise ValueError(
323
+ "cumulative_seqlen_Q and cumulative_seqlen_KV must contain at least 2 elements, got "
324
+ f"{cumulative_seqlen_Q.shape=}, {cumulative_seqlen_KV.shape=}."
325
+ )
326
+
327
+ return (
328
+ cumulative_seqlen_Q,
329
+ cumulative_seqlen_KV,
330
+ max_seqlen_Q,
331
+ max_seqlen_KV,
332
+ )
333
+
334
+
335
+ def attention_param_checks(
336
+ query: Tensor,
337
+ key: Tensor,
338
+ value: Tensor,
339
+ is_causal: bool,
340
+ causal_type: CausalType,
341
+ ):
342
+ if is_causal and (causal_type is None or not isinstance(causal_type, CausalType)):
343
+ raise ValueError(
344
+ f"Argument causal_type must be specified as an enum instance of CausalType when is_causal=True, got {causal_type=}."
345
+ )
346
+
347
+ assert query.dim() == key.dim() == value.dim() == 4
348
+ assert key.shape[1] == value.shape[1]
349
+ if is_causal and causal_type == CausalType.DontCare and query.shape[1] != key.shape[1]:
350
+ raise ValueError(
351
+ "Causal mask type DontCare is only valid when seqlen_q == seqlen_kv, got "
352
+ f"{query.shape[1]=}, {key.shape[1]=}."
353
+ )
354
+
355
+
356
+ def multi_dim_attention_tensor_checks(
357
+ query: Tensor,
358
+ key: Tensor,
359
+ value: Tensor,
360
+ supported_dtypes_forward: list[torch.dtype] | None = None,
361
+ supported_dtypes_backward: list[torch.dtype] | None = None,
362
+ supports_mla: bool = True,
363
+ supports_gqa_mqa: bool = True,
364
+ raise_error: bool = True,
365
+ backend_name: str | None = None,
366
+ ) -> bool:
367
+ backend_name = backend_name or "Multi-Dimensional Attention"
368
+ if not _universal_tensor_checks(query, key, value, raise_error=raise_error):
369
+ return False
370
+
371
+ if not _universal_attention_checks(
372
+ query=query,
373
+ key=key,
374
+ value=value,
375
+ supported_dtypes_forward=supported_dtypes_forward,
376
+ supported_dtypes_backward=supported_dtypes_backward,
377
+ supports_mla=supports_mla,
378
+ supports_gqa_mqa=supports_gqa_mqa,
379
+ raise_error=raise_error,
380
+ backend_name=backend_name,
381
+ ):
382
+ return False
383
+
384
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
385
+
386
+ if query.dim() not in [4, 5, 6]:
387
+ target_fn(
388
+ f"Multi-Dimensional Attention supports 4-D, 5-D, or 6-D tensors as inputs, got {query.dim()=}.",
389
+ exception=ValueError,
390
+ )
391
+ return False
392
+
393
+ num_dims = query.dim() - 3 # minus batch, heads, head_dim
394
+
395
+ q_token_layout_shape = query.shape[1 : 1 + num_dims]
396
+ k_token_layout_shape = key.shape[1 : 1 + num_dims]
397
+ v_token_layout_shape = value.shape[1 : 1 + num_dims]
398
+
399
+ if q_token_layout_shape != k_token_layout_shape or q_token_layout_shape != v_token_layout_shape:
400
+ target_fn(
401
+ "Q, K and V must match in their token layout shapes in multi-dimensional attention, "
402
+ f"got {q_token_layout_shape=}, {k_token_layout_shape=}, {v_token_layout_shape=}.",
403
+ exception=ValueError,
404
+ )
405
+ return False
406
+
407
+ return True
408
+
409
+
410
+ def check_valid_tuple_or_element(param: Any, num_dims: int, typename: type) -> tuple | None:
411
+ if isinstance(param, typename):
412
+ return tuple(param for _ in range(num_dims))
413
+
414
+ if isinstance(param, Sequence) and len(param) == num_dims and all(isinstance(x, typename) for x in param):
415
+ return param
416
+
417
+ return None
418
+
419
+
420
+ def multi_dim_attention_param_filter(
421
+ query: Tensor,
422
+ window_size: tuple | int = -1,
423
+ stride: tuple | int = 1,
424
+ dilation: tuple | int = 1,
425
+ is_causal: tuple | bool = False,
426
+ ) -> tuple[tuple, tuple, tuple, tuple, tuple, tuple]:
427
+ """
428
+ Converts all multi-dimensional parameters to standard types.
429
+ """
430
+ assert query.dim() in [4, 5, 6]
431
+ num_dims = query.dim() - 3
432
+
433
+ token_layout_shape = tuple(s for s in query.shape[1 : 1 + num_dims])
434
+
435
+ window_size_ = check_valid_tuple_or_element(window_size, num_dims, int)
436
+ if window_size_ is None:
437
+ raise ValueError(
438
+ f"Parameter 'window_size' must be either an int or tuple of {num_dims} ints, got {window_size=}."
439
+ )
440
+
441
+ stride_ = check_valid_tuple_or_element(stride, num_dims, int)
442
+ if stride_ is None:
443
+ raise ValueError(f"Parameter 'stride' must be either an int or tuple of {num_dims} ints, got {stride=}.")
444
+
445
+ dilation_ = check_valid_tuple_or_element(dilation, num_dims, int)
446
+ if dilation_ is None:
447
+ raise ValueError(f"Parameter 'dilation' must be either an int or tuple of {num_dims} ints, got {dilation=}.")
448
+
449
+ is_causal_ = check_valid_tuple_or_element(is_causal, num_dims, bool)
450
+ if is_causal_ is None:
451
+ raise ValueError(
452
+ f"Parameter 'is_causal' must be either a boolean or tuple of {num_dims} booleans, got {is_causal=}."
453
+ )
454
+
455
+ # Map -1 windows to corresponding size in token layout
456
+ window_size_ = tuple(w if w != -1 else x for x, w in zip(token_layout_shape, window_size_))
457
+
458
+ return token_layout_shape, window_size_, stride_, dilation_, is_causal_
459
+
460
+
461
+ def multi_dim_attention_param_checks(
462
+ query: Tensor,
463
+ window_size: tuple,
464
+ stride: tuple,
465
+ dilation: tuple,
466
+ is_causal: tuple,
467
+ ):
468
+ """
469
+ Validates multi-dimensional parameters.
470
+ """
471
+ assert query.dim() in [4, 5, 6]
472
+ num_dims = query.dim() - 3
473
+
474
+ token_layout_shape = tuple(s for s in query.shape[1 : 1 + num_dims])
475
+
476
+ if any(x <= 1 for x in token_layout_shape):
477
+ raise ValueError(f"Token layout dimensions must all be >= 2, got {token_layout_shape=} ({query.shape=}).")
478
+
479
+ if any(w <= 1 for w in window_size):
480
+ raise ValueError(
481
+ "Parameter 'window_size' must be either -1 (no sparsity) or >= 2 along every dimension, "
482
+ f"got {window_size=}."
483
+ )
484
+
485
+ if any(w * d > x for x, w, d in zip(token_layout_shape, window_size, dilation)):
486
+ raise ValueError(
487
+ "The product of 'window_size' and 'dilation' cannot be greater than the input "
488
+ f"(token layout shape), got {window_size=}, {dilation=}, {token_layout_shape=} ({query.shape=})."
489
+ )
490
+
491
+ if any(s < 1 for s in stride):
492
+ raise ValueError(f"Parameter 'stride' allows positive integers only, got {stride=}.")
493
+
494
+ if any(s > w for w, s in zip(window_size, stride)):
495
+ raise ValueError(
496
+ f"Parameter 'stride' cannot be greater than window size along any dimension, got {window_size=}, {stride=}."
497
+ )
498
+
499
+ if any(d < 1 for d in dilation):
500
+ raise ValueError(f"Parameter 'dilation' allows positive integers only, got {dilation=}.")
REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ cuDNN Backend
21
+ """
22
+
23
+ import torch
24
+
25
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
26
+
27
+ # (ahassani) [11-20-2025] Banning cuDNN until reliability issues are resolved.
28
+ # Versions checked: 91300, 91400, 91500
29
+ # (ahassani) [12-01-2025]
30
+ # 91500 ran on both GB200 and H100 SXM.
31
+ CUDNN_DISALLOWED = True
32
+
33
+ CUDNN_MIN_BACKEND_VERSION = 91300
34
+ CUDNN_MIN_FRONTEND_VERSION = [1, 14, 0]
35
+
36
+
37
+ def cudnn_supported() -> bool:
38
+ """
39
+ Returns whether cuDNN Attention is supported in this environment.
40
+ Requirements are:
41
+ * Presence of CUDA Runtime (via PyTorch)
42
+ * Presence of cuDNN and its Python frontend, meeting minimum version requirements
43
+
44
+ This check guards imports / dependencies on the cuDNN package.
45
+ """
46
+ if not torch.cuda.is_available():
47
+ log.debug("cuDNN Attention is not supported because PyTorch did not detect CUDA runtime.")
48
+ return False
49
+
50
+ try:
51
+ import cudnn
52
+
53
+ except ImportError:
54
+ log.debug("cuDNN Attention is not supported because the frontend Python package was not found.")
55
+ return False
56
+ except Exception as e:
57
+ log.debug(f"cuDNN Attention is not supported because importing the frontend Python package failed: {e}")
58
+ return False
59
+
60
+ if cudnn.backend_version() < CUDNN_MIN_BACKEND_VERSION:
61
+ log.debug(
62
+ "cuDNN Attention is not supported due to insufficient cuDNN backend version "
63
+ f"{cudnn.backend_version()=}, expected at least {CUDNN_MIN_BACKEND_VERSION=}."
64
+ )
65
+ return False
66
+
67
+ cudnn_frontend_version_split = cudnn.__version__.split(".")
68
+ if len(cudnn_frontend_version_split) != 3:
69
+ log.debug(f"Unable to parse cuDNN frontend version {cudnn.__version__}.")
70
+ return False
71
+
72
+ try:
73
+ cudnn_frontend_version = [int(x) for x in cudnn_frontend_version_split]
74
+ except ValueError:
75
+ log.debug(f"Unable to parse cuDNN frontend version as an int list: {cudnn.__version__}.")
76
+ return False
77
+
78
+ if cudnn_frontend_version < CUDNN_MIN_FRONTEND_VERSION:
79
+ log.debug(
80
+ "cuDNN Attention is not supported due to insufficient cuDNN frontend version "
81
+ f"{cudnn_frontend_version=}, expected at least {CUDNN_MIN_FRONTEND_VERSION=}."
82
+ )
83
+ return False
84
+
85
+ return True
86
+
87
+
88
+ CUDNN_SUPPORTED = cudnn_supported()
89
+
90
+
91
+ if CUDNN_SUPPORTED:
92
+ from cosmos_policy._src.imaginaire.attention.cudnn.functions import cudnn_attention
93
+
94
+ else:
95
+ from cosmos_policy._src.imaginaire.attention.cudnn.stubs import cudnn_attention
96
+
97
+ __all__ = ["cudnn_attention", "CUDNN_SUPPORTED"]
REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/checks.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ cudNN backend checks
21
+ """
22
+
23
+ from functools import partial
24
+
25
+ from torch import Tensor
26
+
27
+ from cosmos_policy._src.imaginaire.attention.checks import attention_param_checks, attention_tensor_checks
28
+ from cosmos_policy._src.imaginaire.attention.cudnn import CUDNN_DISALLOWED, CUDNN_SUPPORTED
29
+ from cosmos_policy._src.imaginaire.attention.cudnn.meta import get_bwd_dtypes, get_fwd_dtypes
30
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
31
+ from cosmos_policy._src.imaginaire.attention.utils import get_arch_tag, is_torch_compiling, log_or_raise_error
32
+
33
+
34
+ def cudnn_attention_check(
35
+ query: Tensor,
36
+ key: Tensor,
37
+ value: Tensor,
38
+ is_causal: bool,
39
+ causal_type: CausalType,
40
+ is_varlen: bool,
41
+ raise_error: bool = False,
42
+ ) -> bool:
43
+ """
44
+ Input validation function for the cuDNN backend.
45
+ Runs the common and cuDNN-specific checks. Returns False if any checks fail, otherwise True.
46
+
47
+ Parameters:
48
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
49
+ (`[batch, seqlen, heads, head_dim]`).
50
+
51
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
52
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
53
+
54
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
55
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
56
+
57
+ is_causal (bool): whether or not causal masking is enabled.
58
+
59
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
60
+ `CausalType.BottomRight`. Required when `is_causal = True`.
61
+
62
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
63
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
64
+ passed.
65
+
66
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
67
+ instead of just returning False. Default is False.
68
+
69
+ Returns:
70
+ success (bool): whether use case is compatible with cuDNN backend.
71
+
72
+ """
73
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
74
+
75
+ if not CUDNN_SUPPORTED:
76
+ target_fn(
77
+ "cuDNN is not supported in this environment. Run with debug logs to find out why, or choose another backend.",
78
+ exception=RuntimeError,
79
+ )
80
+ return False
81
+
82
+ if CUDNN_DISALLOWED:
83
+ target_fn("cuDNN backend is disabled. Please choose another backend.", exception=RuntimeError)
84
+ return False
85
+
86
+ if is_torch_compiling():
87
+ target_fn(
88
+ "cuDNN backend does not support torch.compile yet.",
89
+ exception=RuntimeError,
90
+ )
91
+ return False
92
+
93
+ arch_tag = get_arch_tag(query.device)
94
+ fwd_dtypes = get_fwd_dtypes(arch_tag)
95
+ bwd_dtypes = get_bwd_dtypes(arch_tag)
96
+ if not attention_tensor_checks(
97
+ query=query,
98
+ key=key,
99
+ value=value,
100
+ supported_dtypes_forward=fwd_dtypes,
101
+ supported_dtypes_backward=bwd_dtypes,
102
+ supports_mla=False,
103
+ supports_gqa_mqa=False,
104
+ raise_error=raise_error,
105
+ backend_name="cuDNN Attention",
106
+ ):
107
+ target_fn("cuDNN does not support the given inputs.", exception=RuntimeError)
108
+ return False
109
+
110
+ if is_varlen:
111
+ target_fn("Varlen for cuDNN Attention is not integrated yet.", exception=RuntimeError)
112
+ return False
113
+
114
+ # Verifies causal_type is a CausalType instance when is_causal
115
+ # Verifies DontCare is not used unless seqlen_q == seqlen_kv
116
+ attention_param_checks(
117
+ query=query,
118
+ key=key,
119
+ value=value,
120
+ is_causal=is_causal,
121
+ causal_type=causal_type,
122
+ )
123
+
124
+ if is_causal and causal_type not in [CausalType.TopLeft, CausalType.DontCare]:
125
+ target_fn("cuDNN Attention only supports top-left causal masking for now.", exception=RuntimeError)
126
+ return False
127
+
128
+ return True
REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/cudnn_forward.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ cuDNN Backend: intermediate APIs
21
+ Only safe to import when CUDNN_SUPPORTED is True.
22
+ """
23
+
24
+ from functools import lru_cache
25
+ from typing import Callable
26
+
27
+ import cudnn
28
+ import torch
29
+ from torch import Size, Tensor
30
+
31
+ from cosmos_policy._src.imaginaire.attention.utils import get_arch_tag
32
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
33
+
34
+ # Force using padded mask as a potential workaround for failing use cases
35
+ FORCE_PADDED_MASK = False
36
+
37
+ CUDNN_GRAPH_CACHE_SIZE = 64
38
+
39
+ log.debug(f"cuDNN Attention graphs are cached using an LRU cache with capacity {CUDNN_GRAPH_CACHE_SIZE}.")
40
+ log.debug(f"cuDNN Attention {FORCE_PADDED_MASK=}.")
41
+
42
+
43
+ def get_dtype_choices(arch_tag: int) -> dict:
44
+ """
45
+ Returns data type choices according to arch tag (attention.utils.get_arch_tag).
46
+
47
+ Parameters:
48
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
49
+
50
+ Returns:
51
+ data_type_choices (dict): a map from PyTorch data types to cuDNN data types. Empty if device
52
+ is not supported.
53
+
54
+ """
55
+
56
+ if arch_tag < 80:
57
+ log.debug("cuDNN Attention is not supported because compute capability is below the minimum (8.0).")
58
+ return {}
59
+
60
+ ## NOTE (ahassani): As of version 91400 FP8 inference via the python frontend does
61
+ ## not seem to work.
62
+ # if arch_tag in [90, 100]:
63
+ # log.debug(f"cuDNN Attention supports FP8 for {arch_tag=}.")
64
+ # return {
65
+ # torch.float16: cudnn.data_type.HALF,
66
+ # torch.bfloat16: cudnn.data_type.BFLOAT16,
67
+ # torch.float8_e4m3fn: cudnn.data_type.FP8_E4M3,
68
+ # torch.float8_e5m2: cudnn.data_type.FP8_E5M2,
69
+ # }
70
+
71
+ log.debug(f"cuDNN Attention only supports FP16 and BF16 for {arch_tag=}.")
72
+ return {
73
+ torch.float16: cudnn.data_type.HALF,
74
+ torch.bfloat16: cudnn.data_type.BFLOAT16,
75
+ }
76
+
77
+
78
+ def cudnn_sdpa_fwd_generate_operands(
79
+ q: Tensor, k: Tensor, v: Tensor, num_heads: int, return_lse: bool = False
80
+ ) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor | None]:
81
+ """
82
+ Takes torch input operands (Q, K, V), validates them, and returns views compatible with cuDNN
83
+ APIs ("strided" view with heads-first logical layout but heads-last physical layout.
84
+
85
+ NOTE: this operation tries to specifically avoid memory copies and express everything as tensor
86
+ views, therefore it is crucial to not manipulate the outputs in __any way__ after this point,
87
+ and directly call cuDNN SDPA operations on it.
88
+ This is also what makes this operation very efficient and low in overhead, as there are no
89
+ device/CUDA operations or barriers with host/CPU.
90
+
91
+ Parameters:
92
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
93
+ (`[batch, seqlen, heads, head_dim]`)
94
+
95
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
96
+ (`[batch, seqlen_kv, heads_kv, head_dim]`)
97
+
98
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
99
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`)
100
+
101
+ num_heads (int): Number of attention heads. Used for layout validation.
102
+
103
+ Other Parameters:
104
+ return_lse (bool): Whether to store and return the logsumexp values. Default is False.
105
+
106
+ Returns:
107
+ query_cudnn_layout (Tensor): 4-D query tensor, with the cuDNN strided layout
108
+ (`[batch, heads, seqlen, head_dim]`).
109
+
110
+ key_cudnn_layout (Tensor): 4-D key tensor, with the cuDNN strided layout
111
+ (`[batch, heads_kv, seqlen_kv, head_dim]`).
112
+
113
+ value_cudnn_layout (Tensor): 4-D output tensor, with the cuDNN strided layout
114
+ (`[batch, heads_kv, seqlen_kv, head_dim_v]`).
115
+
116
+ output_cudnn_layout (Tensor): 4-D output tensor, with the cuDNN strided layout
117
+ (`[batch, heads, seqlen, head_dim_v]`).
118
+
119
+ logsumexp_cudnn_layout (Tensor | None): only returned when return_lse is True. logsumexp
120
+ tensor, with the cuDNN strided layout (`[batch, heads, seqlen, 1]`).
121
+ """
122
+
123
+ if q.shape[0] != k.shape[0] or q.shape[0] != v.shape[0]:
124
+ raise ValueError(
125
+ f"All attention operands must match in batch size, got {q.shape[0]=}, {k.shape[0]=}, {v.shape[0]=}."
126
+ )
127
+
128
+ if q.shape[-1] != k.shape[-1]:
129
+ raise ValueError(f"Query and key must match in head dim, got {q.shape[-1]=}, {k.shape[-1]=}.")
130
+
131
+ if q.shape[-2] != num_heads:
132
+ raise ValueError(
133
+ f"The heads-last layout considers q.shape[-2] as number of heads, got {q.shape[-2]=} but {num_heads=}."
134
+ )
135
+
136
+ if k.shape[-2] != num_heads:
137
+ raise ValueError(
138
+ f"The heads-last layout considers k.shape[-2] as number of heads, got {k.shape[-2]=} but {num_heads=}."
139
+ )
140
+
141
+ if v.shape[-2] != num_heads:
142
+ raise ValueError(
143
+ f"The heads-last layout considers v.shape[-2] as number of heads, got {v.shape[-2]=} but {num_heads=}."
144
+ )
145
+
146
+ if not q.is_contiguous() or not k.is_contiguous() or not v.is_contiguous():
147
+ raise ValueError(
148
+ "All attention operands must be contiguous, got "
149
+ f"{q.is_contiguous()=}, {k.is_contiguous()=}, {v.is_contiguous()=}."
150
+ )
151
+
152
+ if q.dtype != k.dtype or q.dtype != v.dtype:
153
+ raise ValueError(f"All attention operands must match in dtype, got {q.dtype=}, {k.dtype=}, {v.dtype=}.")
154
+
155
+ if q.device != k.device or q.device != v.device:
156
+ raise ValueError(
157
+ f"All attention operands must be on the same device, got {q.device=}, {k.device=}, {v.device=}."
158
+ )
159
+
160
+ dtype = q.dtype
161
+ device = q.device
162
+ arch_tag = get_arch_tag(device)
163
+ dtype_choices = get_dtype_choices(arch_tag)
164
+
165
+ if dtype not in dtype_choices:
166
+ raise ValueError(f"Data type {dtype} is not supported; choices are: {dtype_choices.keys()}.")
167
+
168
+ if arch_tag < 80:
169
+ raise NotImplementedError(f"cuDNN Attention only supports SM80 and later, but {device=} is SM{arch_tag}.")
170
+
171
+ batch, seqlen_q, _, head_dim_qk = q.shape
172
+ _, _, _, head_dim_v = v.shape
173
+
174
+ output = torch.empty([batch, seqlen_q, num_heads, head_dim_v], dtype=dtype, device=device)
175
+ lse = None
176
+ if return_lse:
177
+ lse = torch.empty([batch, seqlen_q, num_heads, 1], dtype=dtype, device=device)
178
+
179
+ q_cudnn_layout = q.permute(0, 2, 1, 3)
180
+ k_cudnn_layout = k.permute(0, 2, 1, 3)
181
+ v_cudnn_layout = v.permute(0, 2, 1, 3)
182
+ output_cudnn_layout = output.permute(0, 2, 1, 3)
183
+ lse_cudnn_layout = None
184
+ assert q_cudnn_layout.data_ptr() == q.data_ptr()
185
+ assert k_cudnn_layout.data_ptr() == k.data_ptr()
186
+ assert v_cudnn_layout.data_ptr() == v.data_ptr()
187
+ assert output_cudnn_layout.data_ptr() == output.data_ptr()
188
+
189
+ if return_lse:
190
+ lse_cudnn_layout = lse.permute(0, 2, 1, 3)
191
+ assert lse_cudnn_layout.data_ptr() == lse.data_ptr()
192
+
193
+ return q_cudnn_layout, k_cudnn_layout, v_cudnn_layout, output_cudnn_layout, lse_cudnn_layout
194
+
195
+
196
+ @lru_cache(maxsize=CUDNN_GRAPH_CACHE_SIZE)
197
+ def cudnn_sdpa_fwd_generate_op(
198
+ dtype: torch.dtype,
199
+ device: torch.device,
200
+ q_shape: Size,
201
+ q_stride: Size,
202
+ k_shape: Size,
203
+ k_stride: Size,
204
+ v_shape: Size,
205
+ v_stride: Size,
206
+ output_shape: Size,
207
+ output_stride: Size,
208
+ lse_shape: Size | None = None,
209
+ lse_stride: Size | None = None,
210
+ is_causal: bool = False,
211
+ attn_scale: float | None = None,
212
+ seqlen_Q: int | None = None,
213
+ seqlen_KV: int | None = None,
214
+ ) -> Callable:
215
+ """
216
+ Takes use case metadata that has been validated and generated by cudnn_sdpa_fwd_generate_operands
217
+ and returns a callable cuDNN SDPA forward operation.
218
+ This function does NOT perform attention and rather prepares and builds the cuDNN graph
219
+ responsible for doing so.
220
+
221
+ The final callable that it returns will take any q, k, v, output and (optionally) lse tensors
222
+ matching the same attributes (shape, device, dtype, etc) and call cuDNN SDPA forward on them.
223
+
224
+ Parameters:
225
+ dtype (torch.dtype): Tensor data type for Q, K, V, and output.
226
+
227
+ device (torch.device): Torch (CUDA) device where tensors are and where Attention will run.
228
+
229
+ q_shape (Size): The shape of the 4-D query tensor with the cuDNN strided layout
230
+ (`[batch, heads, seqlen, head_dim]`).
231
+
232
+ q_stride (Size): The stride of the 4-D query tensor with the cuDNN strided layout.
233
+
234
+ k_shape (Size): The shape of the 4-D key tensor with the cuDNN strided layout
235
+ (`[batch, heads_kv, seqlen_kv, head_dim]`).
236
+
237
+ k_stride (Size): The stride of the 4-D key tensor with the cuDNN strided layout.
238
+
239
+ v_shape (Size): The shape of the 4-D value tensor with the cuDNN strided layout
240
+ (`[batch, heads_kv, seqlen_kv, head_dim_v]`).
241
+
242
+ v_stride (Size): The stride of the 4-D value tensor with the cuDNN strided layout.
243
+
244
+ output_shape (Size): The shape of the 4-D output tensor with the cuDNN strided layout
245
+ (`[batch, heads, seqlen, head_dim_v]`).
246
+
247
+ output_stride (Size): The stride of the 4-D output tensor with the cuDNN strided layout.
248
+
249
+ lse_shape (Size | None): The shape of the 4-D logsumexp tensor with the cuDNN strided
250
+ layout (`[batch, heads, seqlen, 1]`).
251
+
252
+ lse_stride (Size | None): The stride of the 4-D logsumexp tensor with the cuDNN strided
253
+ layout.
254
+
255
+ Other Parameters:
256
+ is_causal (bool): whether or not causal masking is enabled. Default is False.
257
+
258
+ attn_scale (float | None): Dot product scale (attention scale). Defaults to
259
+ head_dim ** -0.5.
260
+
261
+ Returns:
262
+ cudnn_sdpa_forward_exec (Callable): Function executing the cuDNN graph with the SDPA
263
+ forward operation. Function signature:
264
+
265
+ query_cudnn_layout (Tensor): 4-D query tensor, with the cuDNN strided layout
266
+ (`[batch, heads, seqlen, head_dim]`).
267
+
268
+ key_cudnn_layout (Tensor): 4-D key tensor, with the cuDNN strided layout
269
+ (`[batch, heads_kv, seqlen_kv, head_dim]`).
270
+
271
+ value_cudnn_layout (Tensor): 4-D output tensor, with the cuDNN strided layout
272
+ (`[batch, heads_kv, seqlen_kv, head_dim_v]`).
273
+
274
+ output_cudnn_layout (Tensor): 4-D output tensor, with the cuDNN strided layout
275
+ (`[batch, heads, seqlen, head_dim_v]`).
276
+
277
+ logsumexp_cudnn_layout (Tensor | None): Optional logsumexp tensor, with the
278
+ cuDNN strided layout (`[batch, heads, seqlen, 1]`).
279
+ """
280
+
281
+ attn_scale = attn_scale if attn_scale is not None else q_shape[-1] ** -0.5
282
+
283
+ arch_tag = get_arch_tag(device)
284
+ dtype_choices = get_dtype_choices(arch_tag)
285
+
286
+ assert dtype in dtype_choices
287
+ cudnn_dtype = dtype_choices[dtype]
288
+
289
+ graph = cudnn.pygraph(
290
+ io_data_type=cudnn_dtype,
291
+ intermediate_data_type=cudnn.data_type.FLOAT,
292
+ compute_data_type=cudnn.data_type.FLOAT,
293
+ )
294
+
295
+ q_cudnn = graph.tensor(dim=q_shape, stride=q_stride, data_type=cudnn_dtype)
296
+ k_cudnn = graph.tensor(dim=k_shape, stride=k_stride, data_type=cudnn_dtype)
297
+ v_cudnn = graph.tensor(dim=v_shape, stride=v_stride, data_type=cudnn_dtype)
298
+
299
+ assert (lse_shape is None and lse_stride is None) or (lse_shape is not None and lse_stride is not None)
300
+ generate_stats = lse_shape is not None
301
+
302
+ seqlen_q_cudnn = None
303
+ seqlen_kv_cudnn = None
304
+ use_padding_mask = FORCE_PADDED_MASK or seqlen_Q is not None or seqlen_KV is not None
305
+ if use_padding_mask:
306
+ seqlen_Q = seqlen_Q if seqlen_Q is not None else q_shape[2]
307
+ seqlen_KV = seqlen_KV if seqlen_KV is not None else k_shape[2]
308
+
309
+ seqlen_q_cudnn = graph.tensor(dim=[q_shape[0], 1, 1, 1], stride=[1, 1, 1, 1], data_type=cudnn.data_type.INT32)
310
+ seqlen_kv_cudnn = graph.tensor(dim=[k_shape[0], 1, 1, 1], stride=[1, 1, 1, 1], data_type=cudnn.data_type.INT32)
311
+
312
+ o_cudnn, lse_cudnn = graph.sdpa(
313
+ q=q_cudnn,
314
+ k=k_cudnn,
315
+ v=v_cudnn,
316
+ generate_stats=generate_stats,
317
+ attn_scale=attn_scale,
318
+ use_causal_mask=is_causal,
319
+ use_padding_mask=use_padding_mask,
320
+ seq_len_q=seqlen_q_cudnn,
321
+ seq_len_kv=seqlen_kv_cudnn,
322
+ )
323
+
324
+ o_cudnn.set_output(True).set_data_type(cudnn_dtype).set_dim(output_shape).set_stride(output_stride)
325
+ if generate_stats:
326
+ lse_cudnn.set_output(True).set_dim(lse_shape).set_stride(lse_stride)
327
+
328
+ graph.validate()
329
+ graph.build_operation_graph()
330
+ graph.create_execution_plans([cudnn.heur_mode.A, cudnn.heur_mode.FALLBACK])
331
+ graph.check_support()
332
+ graph.build_plans()
333
+
334
+ workspace_size_bytes = graph.get_workspace_size()
335
+ log.debug(f"Generated cuDNN Attention graph. Scratch space required: {workspace_size_bytes} bytes.")
336
+
337
+ handle = cudnn.create_handle()
338
+
339
+ def cudnn_operation(q: Tensor, k: Tensor, v: Tensor, output: Tensor, lse: Tensor | None = None):
340
+ # NOTE: This is INCREDIBLY important to do -- this is what wasted days of my time
341
+ # with random NaNs and illegal memory accesses and things of that nature.
342
+ stream = torch.cuda.current_stream(q.device)
343
+ cudnn.set_stream(handle=handle, stream=stream.cuda_stream)
344
+
345
+ # caching allocator plays nicely with the LRU cache over this, but for now let's avoid
346
+ # premature optimization.
347
+ workspace = torch.zeros(workspace_size_bytes, device=device, dtype=torch.uint8)
348
+
349
+ variant_pack = {
350
+ q_cudnn: q,
351
+ k_cudnn: k,
352
+ v_cudnn: v,
353
+ o_cudnn: output,
354
+ }
355
+
356
+ if use_padding_mask:
357
+ batch = k.shape[0]
358
+ seqlen_q_cu = torch.tensor([seqlen_Q for _ in range(batch)]).to(device).reshape(batch, 1, 1, 1)
359
+ seqlen_kv_cu = torch.tensor([seqlen_KV for _ in range(batch)]).to(device).reshape(batch, 1, 1, 1)
360
+ log.debug(f"{q.shape=}, {k.shape=}, {seqlen_q_cu=}, {seqlen_kv_cu=}")
361
+ variant_pack[seqlen_q_cudnn] = seqlen_q_cu
362
+ variant_pack[seqlen_kv_cudnn] = seqlen_kv_cu
363
+
364
+ if generate_stats:
365
+ assert lse is not None
366
+ assert lse_cudnn is not None
367
+ variant_pack[lse_cudnn] = lse
368
+ else:
369
+ assert lse is None and lse_cudnn is None
370
+
371
+ log.debug("Generated cuDNN Attention graph executed")
372
+ return graph.execute(variant_pack, workspace, handle=handle)
373
+
374
+ return cudnn_operation
375
+
376
+
377
+ def cudnn_sdpa_fwd_post_process(
378
+ output_cudnn_layout: Tensor,
379
+ lse_cudnn_layout: Tensor | None = None,
380
+ ) -> tuple[Tensor, Tensor | None]:
381
+ """
382
+ Takes torch tensor views validated and generated by cudnn_sdpa_fwd_generate_operands and
383
+ maps back to torch contiguous layout (heads-last both logical and physical).
384
+ It should be called after the cuDNN operation.
385
+
386
+ Like cudnn_sdpa_fwd_generate_operands, this function is expected to be minimal overhead.
387
+
388
+ Parameters:
389
+ output_cudnn_layout (Tensor): 4-D output tensor, with the cuDNN strided layout
390
+ (`[batch, heads, seqlen, head_dim_v]`).
391
+
392
+ logsumexp_cudnn_layout (Tensor | None): Optional logsumexp tensor, with the cuDNN
393
+ strided layout (`[batch, heads, seqlen, 1]`).
394
+
395
+ Returns:
396
+ output (Tensor): 4-D output tensor, with the heads-last contiguous layout
397
+ (`[batch, seqlen, heads, head_dim_v]`).
398
+
399
+ logsumexp (Tensor | None): Optional logsumexp tensor, with the heads-last contiguous
400
+ layout (`[batch, seqlen, heads, 1]`).
401
+ """
402
+
403
+ output = output_cudnn_layout.permute(0, 2, 1, 3)
404
+ lse = None
405
+ assert output.data_ptr() == output_cudnn_layout.data_ptr()
406
+
407
+ if lse_cudnn_layout is not None:
408
+ lse = lse_cudnn_layout.permute(0, 2, 1, 3)
409
+ assert lse.data_ptr() == lse_cudnn_layout.data_ptr()
410
+
411
+ return output, lse
REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/functions.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ cuDNN Backend: intermediate APIs
21
+ Only safe to import when CUDNN_SUPPORTED is True.
22
+ """
23
+
24
+ import time
25
+ from functools import partial
26
+
27
+ import torch
28
+ from torch import Tensor
29
+ from torch.amp import custom_bwd, custom_fwd
30
+ from torch.autograd import Function
31
+
32
+ from cosmos_policy._src.imaginaire.attention.cudnn.checks import cudnn_attention_check
33
+ from cosmos_policy._src.imaginaire.attention.cudnn.cudnn_forward import (
34
+ cudnn_sdpa_fwd_generate_op,
35
+ cudnn_sdpa_fwd_generate_operands,
36
+ cudnn_sdpa_fwd_post_process,
37
+ )
38
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
39
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
40
+
41
+ amp_fwd = partial(custom_fwd, device_type="cuda")
42
+ amp_bwd = partial(custom_bwd, device_type="cuda")
43
+
44
+
45
+ CUDNN_PADDING_REQUIRED = False
46
+
47
+
48
+ class CudnnAttentionAutogradFn(Function):
49
+ @staticmethod
50
+ @amp_fwd
51
+ def forward(
52
+ ctx,
53
+ query: Tensor,
54
+ key: Tensor,
55
+ value: Tensor,
56
+ num_heads: int,
57
+ is_causal: bool,
58
+ scale: float,
59
+ ) -> tuple[Tensor, Tensor]:
60
+ query = query.contiguous()
61
+ key = key.contiguous()
62
+ value = value.contiguous()
63
+
64
+ seqlen_Q = None
65
+ seqlen_KV = None
66
+ padding_Q = 0
67
+ padding_KV = 0
68
+
69
+ # NOTE (ahassani): this may resolve some of the bugs caused by weird seqlens,
70
+ # but as of 11/12/2025 does not seem to fix any issues. Keeping here in case
71
+ # it ever comes back.
72
+ if CUDNN_PADDING_REQUIRED:
73
+ Q_multiplier = 256
74
+ KV_multiplier = 256
75
+
76
+ if query.shape[1] % Q_multiplier != 0:
77
+ seqlen_Q = query.shape[1]
78
+ padding_Q = Q_multiplier - (seqlen_Q % Q_multiplier)
79
+
80
+ old_shape = query.shape
81
+ query = torch.nn.functional.pad(query, (0, 0, 0, 0, 0, padding_Q), "constant", 0)
82
+ log.debug(f"cuDNN Attention: padded query from {old_shape} to {query.shape}.")
83
+
84
+ if key.shape[1] % KV_multiplier != 0:
85
+ seqlen_KV = key.shape[1]
86
+ padding_KV = KV_multiplier - (seqlen_KV % KV_multiplier)
87
+
88
+ old_shape = key.shape
89
+ key = torch.nn.functional.pad(key, (0, 0, 0, 0, 0, padding_KV), "constant", 0)
90
+ value = torch.nn.functional.pad(value, (0, 0, 0, 0, 0, padding_KV), "constant", 0)
91
+ log.debug(f"cuDNN Attention: padded KV from {old_shape} to {key.shape}.")
92
+
93
+ # Transform operands to cuDNN-compatible layouts, make output tensors
94
+ (q_cudnn_layout, k_cudnn_layout, v_cudnn_layout, output_cudnn_layout, lse_cudnn_layout) = (
95
+ cudnn_sdpa_fwd_generate_operands(q=query, k=key, v=value, num_heads=num_heads, return_lse=True)
96
+ )
97
+
98
+ # Construct graph
99
+ assert q_cudnn_layout.device == k_cudnn_layout.device == v_cudnn_layout.device == output_cudnn_layout.device
100
+ assert q_cudnn_layout.dtype == k_cudnn_layout.dtype == v_cudnn_layout.dtype == output_cudnn_layout.dtype
101
+ cudnn_graph_gen_start = time.time() * 1e3
102
+ cudnn_sdpa = cudnn_sdpa_fwd_generate_op(
103
+ dtype=q_cudnn_layout.dtype,
104
+ device=q_cudnn_layout.device,
105
+ q_shape=q_cudnn_layout.shape,
106
+ q_stride=q_cudnn_layout.stride(),
107
+ k_shape=k_cudnn_layout.shape,
108
+ k_stride=k_cudnn_layout.stride(),
109
+ v_shape=v_cudnn_layout.shape,
110
+ v_stride=v_cudnn_layout.stride(),
111
+ output_shape=output_cudnn_layout.shape,
112
+ output_stride=output_cudnn_layout.stride(),
113
+ lse_shape=None if lse_cudnn_layout is None else lse_cudnn_layout.shape,
114
+ lse_stride=None if lse_cudnn_layout is None else lse_cudnn_layout.stride(),
115
+ is_causal=is_causal,
116
+ attn_scale=scale,
117
+ seqlen_Q=seqlen_Q,
118
+ seqlen_KV=seqlen_KV,
119
+ )
120
+ cudnn_graph_gen_time = time.time() * 1e3 - cudnn_graph_gen_start
121
+ log.debug(f"cuDNN Attention forward graph generation took {cudnn_graph_gen_time:.1f} ms.")
122
+
123
+ # Execute graph
124
+ cudnn_sdpa(
125
+ q=q_cudnn_layout,
126
+ k=k_cudnn_layout,
127
+ v=v_cudnn_layout,
128
+ output=output_cudnn_layout,
129
+ lse=lse_cudnn_layout,
130
+ )
131
+
132
+ # Transform outputs back to torch contiguous layouts
133
+ output, logsumexp = cudnn_sdpa_fwd_post_process(
134
+ output_cudnn_layout=output_cudnn_layout,
135
+ lse_cudnn_layout=lse_cudnn_layout,
136
+ )
137
+
138
+ ctx.save_for_backward(q_cudnn_layout, k_cudnn_layout, v_cudnn_layout, lse_cudnn_layout, output_cudnn_layout)
139
+ ctx.num_heads = num_heads
140
+ ctx.scale = scale
141
+
142
+ if padding_Q > 0:
143
+ old_shape = output.shape
144
+ output = output[:, :seqlen_Q, :, :]
145
+ logsumexp = logsumexp[:, :seqlen_Q, :, :]
146
+ assert output.shape[1] == seqlen_Q
147
+ assert logsumexp.shape[1] == seqlen_Q
148
+ log.debug(f"cuDNN Attention: unpadded output from {old_shape} to {output.shape}.")
149
+
150
+ return output, logsumexp
151
+
152
+ @staticmethod
153
+ @amp_bwd
154
+ def backward(
155
+ ctx, grad_out: Tensor, grad_lse: Tensor
156
+ ) -> tuple[
157
+ Tensor,
158
+ Tensor,
159
+ Tensor,
160
+ None,
161
+ None,
162
+ None,
163
+ ]:
164
+ raise NotImplementedError()
165
+
166
+
167
+ def cudnn_attention(
168
+ query: Tensor,
169
+ key: Tensor,
170
+ value: Tensor,
171
+ is_causal: bool = False,
172
+ causal_type: CausalType | None = None,
173
+ scale: float | None = None,
174
+ cumulative_seqlen_Q: Tensor | None = None,
175
+ cumulative_seqlen_KV: Tensor | None = None,
176
+ max_seqlen_Q: int | None = None,
177
+ max_seqlen_KV: int | None = None,
178
+ return_lse: bool = False,
179
+ backend_kwargs: dict | None = None,
180
+ ) -> Tensor | tuple[Tensor, Tensor]:
181
+ """
182
+ Runs cuDNN Attention on given operands (Q, K, V) with the heads-last contiguous layout
183
+ (`[batch, seqlen, heads, head_dim]`).
184
+
185
+ Parameters:
186
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
187
+ (`[batch, seqlen, heads, head_dim]`)
188
+
189
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
190
+ (`[batch, seqlen_kv, heads_kv, head_dim]`)
191
+
192
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
193
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`)
194
+
195
+ is_causal (bool): whether or not causal masking is enabled. Default is False.
196
+
197
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
198
+ `CausalType.BottomRight`. Required when `is_causal = True`.
199
+
200
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
201
+
202
+ cumulative_seqlen_Q (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
203
+ indicating the cumulative sum of number of query tokens in each batch, with an
204
+ additional 0 element in the beginning. Must be passed together with
205
+ `cumulative_seqlen_KV` and `max_seqlen_{Q,KV}`.
206
+
207
+ cumulative_seqlen_KV (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
208
+ indicating the cumulative sum of number of key/value tokens in each batch, with an
209
+ additional 0 element in the beginning. Must be passed together with
210
+ `cumulative_seqlen_Q` and `max_seqlen_{Q,KV}`.
211
+
212
+ max_seqlen_Q (int | None): (varlen) Optional integer indicating the maximum query
213
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
214
+ and `max_seqlen_KV`.
215
+
216
+ max_seqlen_KV (int | None): (varlen) Optional integer indicating the maximum key/value
217
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
218
+ and `max_seqlen_Q`.
219
+
220
+ Other Parameters:
221
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
222
+
223
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to cuDNN's
224
+ attention operator, if any.
225
+
226
+ Returns:
227
+ output (Tensor): 4-D output tensor, with the heads-last contiguous layout
228
+ (`[batch, seqlen, heads, head_dim_v]`).
229
+
230
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
231
+ (`[batch, seqlen, heads, 1]`). Only returned when return_lse is True.
232
+ """
233
+
234
+ is_varlen = cumulative_seqlen_Q is not None
235
+ assert cudnn_attention_check(
236
+ query=query,
237
+ key=key,
238
+ value=value,
239
+ is_causal=is_causal,
240
+ causal_type=causal_type,
241
+ is_varlen=is_varlen,
242
+ raise_error=True,
243
+ )
244
+
245
+ assert not is_varlen # cudnn_attention_check should prevent this assertion failing
246
+
247
+ num_heads = query.shape[-2]
248
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
249
+
250
+ output, lse = CudnnAttentionAutogradFn.apply(
251
+ query,
252
+ key,
253
+ value,
254
+ num_heads,
255
+ is_causal,
256
+ scale,
257
+ )
258
+
259
+ if return_lse:
260
+ return output, lse
261
+
262
+ return output
REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/meta.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ cuDNN Backend: metadata
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ import torch
25
+
26
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
27
+
28
+
29
+ def get_fwd_dtypes(arch_tag: int) -> list[torch.dtype]:
30
+ """
31
+ Returns data type choices for forward pass according to arch tag (attention.utils.get_arch_tag).
32
+
33
+ Parameters:
34
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
35
+
36
+ Returns:
37
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
38
+
39
+ """
40
+
41
+ if arch_tag < 80:
42
+ log.debug("cuDNN Attention is not supported because compute capability is below the minimum (8.0).")
43
+ return []
44
+
45
+ ## NOTE (ahassani): As of version 91400 FP8 inference via the python frontend does
46
+ ## not seem to work.
47
+ log.debug(f"cuDNN Attention only supports FP16 and BF16 for {arch_tag=}.")
48
+ return [torch.float16, torch.bfloat16]
49
+
50
+
51
+ def get_bwd_dtypes(arch_tag: int) -> list[torch.dtype]:
52
+ """
53
+ Returns data type choices for backward pass according to arch tag (attention.utils.get_arch_tag).
54
+
55
+ Parameters:
56
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
57
+
58
+ Returns:
59
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
60
+
61
+ """
62
+
63
+ return []
REGEN-main/cosmos_policy/_src/imaginaire/attention/cudnn/stubs.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ cuDNN Backend: intermediate API stubs
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ from torch import Tensor
25
+
26
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
27
+
28
+
29
+ def cudnn_attention(
30
+ query: Tensor,
31
+ key: Tensor,
32
+ value: Tensor,
33
+ is_causal: bool = False,
34
+ causal_type: CausalType | None = None,
35
+ scale: float | None = None,
36
+ cumulative_seqlen_Q: Tensor | None = None,
37
+ cumulative_seqlen_KV: Tensor | None = None,
38
+ max_seqlen_Q: int | None = None,
39
+ max_seqlen_KV: int | None = None,
40
+ return_lse: bool = False,
41
+ backend_kwargs: dict | None = None,
42
+ ) -> Tensor | tuple[Tensor, Tensor]:
43
+ raise RuntimeError(
44
+ "Tried to run cuDNN attention, but it is not supported / available. "
45
+ "Try running with debug logs enabled to see why."
46
+ )
REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Imaginaire Attention Subpackage Docs
2
+
3
+ * [Basic API & Intro](../README.md)
4
+ * Docs (you are here)
5
+ * [Backends](backends.md)
6
+ * Features
7
+ * [Basic features](features.md)
8
+ * [Multi-dimensional Attention](multi-dim.md)
9
+ * [Spatio-Temporal Attention](multi-dim.md#spatio-temporal-attention)
10
+ * [APIs](apis.md)
REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/apis.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Imaginaire Attention Subpackage Docs > APIs
2
+
3
+ ## Attention
4
+
5
+ ::: cosmos_policy._src.imaginaire.attention
6
+ options:
7
+ heading_level: 3
8
+ show_object_full_path: true
9
+ members:
10
+ - attention
11
+
12
+ ## Multi-Dimensional Attention
13
+
14
+ ::: cosmos_policy._src.imaginaire.attention
15
+ options:
16
+ heading_level: 3
17
+ show_object_full_path: true
18
+ members:
19
+ - multi_dimensional_attention
20
+
21
+ ### Spatio-Temporal Attention
22
+
23
+ ::: cosmos_policy._src.imaginaire.attention
24
+ options:
25
+ heading_level: 3
26
+ show_object_full_path: true
27
+ members:
28
+ - spatio_temporal_attention
REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/backends.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Imaginaire Attention Subpackage Docs > Backends
2
+
3
+ The goal is to support as many stable and reliable backends as possible, both for feature coverage,
4
+ and for delivering the best performance.
5
+
6
+ ## NATTEN
7
+ [NATTEN](https://natten.org) ships standard Attention kernels in addition to sparse /
8
+ multi-dimensional kernels.
9
+
10
+ Minimum version required: `0.21.5.dev3`.
11
+
12
+ ### Feature coverage
13
+
14
+ | Feat/Backend | Ampere/RTX | Hopper | Blackwell |
15
+ |--------------|--------------------|--------|--------------------|
16
+ | Causal mask | :white_check_mark: | | :white_check_mark: |
17
+ | Varlen | :white_check_mark: | | :white_check_mark: |
18
+ | GQA/MQA | | | :white_check_mark: |
19
+ | MLA | :white_check_mark: | | |
20
+
21
+ This backend supports torch compile.
22
+
23
+ ## Flash Attention v2
24
+
25
+ Flash Attention v2 (original C++ kernels) are available under the `flash2` backend.
26
+ Requires the `flash_attn` package.
27
+
28
+ Minimum version required: `2.7.0`.
29
+ Maximum version supported: `2.7.4`.
30
+
31
+ This backend supports torch compile.
32
+
33
+ ### Feature coverage
34
+
35
+ | Feat/Backend | Ampere/RTX |
36
+ |--------------|--------------------|
37
+ | Causal mask | :white_check_mark: |
38
+ | Varlen | :white_check_mark: |
39
+ | GQA/MQA | :white_check_mark: |
40
+ | MLA | |
41
+
42
+ ## Flash Attention v3
43
+
44
+ Flash Attention v3 (original C++ kernels) are available under the `flash3` backend.
45
+ Requires the `flash_attn_3` package.
46
+
47
+ Version required: `3.0.0.b*`.
48
+
49
+ ### Feature coverage
50
+
51
+ | Feat/Backend | Ampere/RTX |
52
+ |--------------|--------------------|
53
+ | Causal mask | :white_check_mark: |
54
+ | Varlen | :white_check_mark: |
55
+ | GQA/MQA | :white_check_mark: |
56
+ | MLA | |
57
+
58
+ MLA is technically supported, but disabled due to an API bug in the backward pass.
59
+
60
+ Torch compile is NOT yet supported for this backend.
61
+
62
+ ## cuDNN
63
+
64
+ **NOTE**: due to numerical instability on Blackwell, this backend is not yet fully integrated, and
65
+ is banned for all use cases.
66
+
67
+ Minimum version required: python frontend: `1.14.0`, backend: `91300`.
68
+
69
+ Torch compile is NOT yet supported for this backend.
70
+
71
+ ## Future backends
72
+
73
+ We plan to add Flash Attention 4 (CuTeDSL kernels) and any other relevant backends.
REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/features.md ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Imaginaire Attention Subpackage Docs > Features
2
+
3
+ ## Causal mask
4
+
5
+ Causal masking requires explicit indication of causal mask type.
6
+ For example, simply passing `is_causal=True` will fail:
7
+
8
+ ```python
9
+ output = attention(
10
+ query=query,
11
+ key=key,
12
+ value=value,
13
+ is_causal=True
14
+ )
15
+ ```
16
+
17
+ Result:
18
+ ```
19
+ ValueError: Argument causal_type must be specified when is_causal=True.
20
+ ```
21
+
22
+ There are currently two types of causal masking that are supported, and many popular backends tend
23
+ to support only one. It's therefore critical to to choose the correct one for your application.
24
+
25
+
26
+ ```python
27
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
28
+
29
+ # Causal type choices:
30
+ # - CausalType.TopLeft
31
+ # - CausalType.BottomRight
32
+
33
+ output = attention(
34
+ query=query,
35
+ key=key,
36
+ value=value,
37
+ is_causal=True,
38
+ causal_type=CausalType.TopLeft,
39
+ )
40
+ ```
41
+
42
+ ### Top-left causal mask
43
+
44
+ Q sequence length = KV sequence length = 5
45
+
46
+ | | K1 | K2 | K3 | K4 | K5 |
47
+ |----|-----------|-----------|-----------|-----------|-----------|
48
+ | Q1 | &#x2713; | &#x2717; | &#x2717; | &#x2717; | &#x2717; |
49
+ | Q2 | &#x2713; | &#x2713; | &#x2717; | &#x2717; | &#x2717; |
50
+ | Q3 | &#x2713; | &#x2713; | &#x2713; | &#x2717; | &#x2717; |
51
+ | Q4 | &#x2713; | &#x2713; | &#x2713; | &#x2713; | &#x2717; |
52
+ | Q5 | &#x2713; | &#x2713; | &#x2713; | &#x2713; | &#x2713; |
53
+
54
+ Q sequence length = 2, KV sequence length = 5
55
+
56
+ | | K1 | K2 | K3 | K4 | K5 |
57
+ |----|-----------|-----------|-----------|-----------|-----------|
58
+ | Q1 | &#x2713; | &#x2717; | &#x2717; | &#x2717; | &#x2717; |
59
+ | Q2 | &#x2713; | &#x2713; | &#x2717; | &#x2717; | &#x2717; |
60
+
61
+ Q sequence length = 5, KV sequence length = 2
62
+
63
+ | | K1 | K2 |
64
+ |----|-----------|-----------|
65
+ | Q1 | &#x2713; | &#x2717; |
66
+ | Q2 | &#x2713; | &#x2713; |
67
+ | Q3 | &#x2713; | &#x2713; |
68
+ | Q4 | &#x2713; | &#x2713; |
69
+ | Q5 | &#x2713; | &#x2713; |
70
+
71
+ ### Bottom-right causal mask
72
+
73
+ Q sequence length = KV sequence length = 5
74
+
75
+ | | K1 | K2 | K3 | K4 | K5 |
76
+ |----|-----------|-----------|-----------|-----------|-----------|
77
+ | Q1 | &#x2713; | &#x2717; | &#x2717; | &#x2717; | &#x2717; |
78
+ | Q2 | &#x2713; | &#x2713; | &#x2717; | &#x2717; | &#x2717; |
79
+ | Q3 | &#x2713; | &#x2713; | &#x2713; | &#x2717; | &#x2717; |
80
+ | Q4 | &#x2713; | &#x2713; | &#x2713; | &#x2713; | &#x2717; |
81
+ | Q5 | &#x2713; | &#x2713; | &#x2713; | &#x2713; | &#x2713; |
82
+
83
+ (identical to top-left in this special case)
84
+
85
+ Q sequence length = 2, KV sequence length = 5
86
+
87
+ | | K1 | K2 | K3 | K4 | K5 |
88
+ |----|-----------|-----------|-----------|-----------|-----------|
89
+ | Q1 | &#x2713; | &#x2713; | &#x2713; | &#x2713; | &#x2717; |
90
+ | Q2 | &#x2713; | &#x2713; | &#x2713; | &#x2713; | &#x2713; |
91
+
92
+ Q sequence length = 5, KV sequence length = 2
93
+
94
+ | | K1 | K2 |
95
+ |----|-----------|-----------|
96
+ | Q1 | &#x2717; | &#x2717; |
97
+ | Q2 | &#x2717; | &#x2717; |
98
+ | Q3 | &#x2717; | &#x2717; |
99
+ | Q4 | &#x2713; | &#x2717; |
100
+ | Q5 | &#x2713; | &#x2713; |
101
+
102
+ ## GQA/MQA
103
+
104
+ Simply pass `key` and `value` without repeating attention heads.
105
+
106
+ **NOTE**: `key`/`value` heads must evenly divide `query` heads.
107
+
108
+ **NOTE**: the behavior is similar to `repeat_interleave`, not `repeat`.
109
+
110
+ ## Variable length
111
+
112
+ **(Less efficient option)** Pass sequence lengths directly:
113
+
114
+ ```python
115
+ output = attention(
116
+ query=query,
117
+ key=key,
118
+ value=value,
119
+ seqlens_Q=torch.tensor(sequence_length_list_Q, device=query.device),
120
+ seqlens_KV=torch.tensor(sequence_length_list_KV, device=query.device),
121
+ )
122
+ ```
123
+
124
+ This will manually compute the maximum sequence lengths, and cumulative sums (with the additional
125
+ padding).
126
+
127
+ **(More efficient option)** Compute cumulative sequence lengths and maximums once, and reuse it:
128
+
129
+ ```python
130
+ from cosmos_policy._src.imaginaire.attention.varlen import generate_varlen_parameters
131
+
132
+ # NOTE: query, key, and value are only used for verification, so it doesn't matter what model layer
133
+ # they correspond to.
134
+ (
135
+ cumulative_seqlen_Q,
136
+ cumulative_seqlen_KV,
137
+ max_seqlen_Q,
138
+ max_seqlen_KV,
139
+ ) = generate_varlen_parameters(query, key, value, seqlens_Q, seqlens_KV)
140
+
141
+ # in all attention layers that follow:
142
+ output = attention(
143
+ query=query,
144
+ key=key,
145
+ value=value,
146
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
147
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
148
+ max_seqlen_Q=max_seqlen_Q,
149
+ max_seqlen_KV=max_seqlen_KV,
150
+ )
151
+ ```
REGEN-main/cosmos_policy/_src/imaginaire/attention/docs/multi-dim.md ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Imaginaire Attention Subpackage Docs > Features > Multi-Dimensional Attention
2
+
3
+ Multi-Dimensional Attention is the primary API for handling various complex masks and sparsity
4
+ patterns, such as the spatio-temporal mask, and sliding window attention.
5
+
6
+ ## Basic API
7
+
8
+ ```python
9
+ from cosmos_policy._src.imaginaire.attention import multi_dimensional_attention
10
+
11
+ output = multi_dimensional_attention(
12
+ query=query,
13
+ key=key,
14
+ value=value,
15
+ )
16
+ ```
17
+
18
+ Sparsity parameters:
19
+ * **Optional** `window_size`: allows reducing the attention span by limiting each token's context to
20
+ a local sliding window. References:
21
+ * [Image Transformer](https://arxiv.org/abs/1802.05751)
22
+ * [Stand-alone self-attention](https://arxiv.org/abs/1906.05909)
23
+ * [Neighborhood attention transformer](https://arxiv.org/abs/2204.07143)
24
+ * **Optional** `dilation`: introduces gaps between the tokens within a sliding window, capturing
25
+ global context without more computation.
26
+ Reference: [Dilated neighborhood attention transformer](https://arxiv.org/abs/2209.15001)
27
+
28
+ Other masking parameters:
29
+ * **Optional** `stride`: introduces delays into the sliding window, for __potential__ efficiency
30
+ gains. Reference: [Generalized Neighborhood Attention](https://arxiv.org/abs/2504.16922).
31
+ * **Optional** `is_causal`: allows causally masking individual dimensions. This parameter can
32
+ implement the spatio-temporal mask (causal masking across temporal dimension, bi-directional
33
+ along space).
34
+
35
+ All sparsity / masking parameters can be specified **per dimension**.
36
+ The key feature of `multi_dimensional_attention` over the standard `attention` API is supporting
37
+ multi-dimensional layouts of tokens (i.e. multi-dimensional feature maps).
38
+
39
+ This means `query`, `key` and `value` are not necessarily 4-D tensors; they can be 4-D, 5-D, or 6-D,
40
+ representing 1-D, 2-D, and 3-D token layouts (see [Tensor layouts](#tensor-layouts)).
41
+
42
+ * **Optional** `scale`: attention (softmax/dot product) scale. Defaults to `head_dim ** -0.5`.
43
+ * **Optional** `return_lse`: returns logsumexp if `True`
44
+ * **Optional** `backend`: explicitly set backend instead of automatically selecting the best compatible
45
+
46
+ ## Tensor layouts
47
+
48
+ In addition to requiring the [contiguous heads-last tensor layout](../README.md#tensor-layouts),
49
+ Multi-Dimensional Attention also requires the "sequence length" dimension to be unrolled / unfolded
50
+ back into its original representation:
51
+
52
+ ```python
53
+ # 1-D case: language, audio
54
+ batch, X, heads, head_dim = query_1d.shape
55
+ # _
56
+ # ^
57
+ # |
58
+ # |-----> token layout shape
59
+
60
+ # 2-D case: images
61
+ batch, X, Y, heads, head_dim = query_2d.shape
62
+ # ____
63
+ # ^
64
+ # |
65
+ # |-----> token layout shape
66
+
67
+ # 3-D case: videos / 3-D images
68
+ batch, X, Y, Z, heads, head_dim = query_3d.shape
69
+ # _______
70
+ # ^
71
+ # |
72
+ # |------> token layout shape
73
+ ```
74
+
75
+ Multi-Dimensional Attention also requires the shapes of `query`, `key` and `value` to match along
76
+ those dimensions, henceforth called the **token layout shape**:
77
+
78
+ ```python
79
+ assert query_1d.shape[1:2] == key_1d.shape[1:2] == value_1d.shape[1:2]
80
+
81
+ assert query_2d.shape[1:3] == key_2d.shape[1:3] == value_2d.shape[1:3]
82
+
83
+ assert query_3d.shape[1:4] == key_3d.shape[1:4] == value_3d.shape[1:4]
84
+ ```
85
+
86
+ This is because of the large number of sparsity / masking features (and their combinations)
87
+ supported, which is mainly possible by making the assumption that query and context coordinate
88
+ spaces are the same, eliminating the requirement for a mapping between the two.
89
+
90
+ Problems with a different query and key/value token layout shape may be supported in the future.
91
+
92
+
93
+ ## Backends
94
+ The only backend supporting multi-dimensional attention for now is `natten`.
95
+
96
+ ## Spatio-Temporal Attention
97
+
98
+ Spatio-Temporal attention (causal masking across the time dimension, and no masking / bi-directional
99
+ across spatial dimensions) is a special case of Multi-Dimensional Attention.
100
+ You can either implement it by marking `is_causal` as expected in `multi_dimensional_attention`, or
101
+ directly use `spatio_temporal_attention`:
102
+
103
+ ```python
104
+ from cosmos_policy._src.imaginaire.attention import spatio_temporal_attention
105
+
106
+ output = spatio_temporal_attention(
107
+ query=query,
108
+ key=key,
109
+ value=value,
110
+ )
111
+ ```
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Causal Mask
2
+
3
+ NOTE: Flash only implements bottom-right-aligned causal mask, but the default
4
+ in SDPA, CUTLASS/NATTEN, cuDNN is top-left.
5
+ To get the same behavior, we __might__ be able to implement top-left-aligned with
6
+ the sliding window argument, but some of Flash's overrides prevent this...
7
+
8
+ ```python
9
+ seqlen_q = query.shape[1]
10
+ seqlen_k = key.shape[1]
11
+
12
+ # From Flash Attn readme:
13
+ # Query at position i will only attend to keys between
14
+ # [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive.
15
+ #
16
+ # so our window_size when doing top-left causal masking should satisfy:
17
+ # i + seqlen_k - seqlen_q - window_size[0] = 0
18
+ # i + seqlen_k - seqlen_q + window_size[1] = i
19
+ # =>
20
+ # seqlen_k - seqlen_q + window_size[1] = 0 ==>
21
+ # window_size[1] = seqlen_q - seqlen_k
22
+ #
23
+ # and:
24
+ #
25
+ # i + seqlen_k - seqlen_q = window_size[0]
26
+ #
27
+ # which has to be satisfied for all 0 <= i < seqlen_q:
28
+ # seqlen_k - seqlen_q = window_size[0]
29
+ #
30
+ # seqlen_q - 1 + seqlen_k - seqlen_q = window_size[0] ==>
31
+ # seqlen_k - 1 = window_size[0]
32
+ #
33
+ # which means ...
34
+ #
35
+ #
36
+ # Other Flash overrides:
37
+ # if (window_size_left >= seqlen_k) { window_size_left = -1; }
38
+ # if (window_size_right >= seqlen_k) { window_size_right = -1; }
39
+ #
40
+ # params.is_causal = window_size_left < 0 && window_size_right == 0;
41
+ #
42
+ # if (window_size_left < 0 && window_size_right >= 0) { window_size_left = seqlen_k; }
43
+ # if (window_size_left >= 0 && window_size_right < 0) { window_size_right = seqlen_k; }
44
+ # params.window_size_left = window_size_left;
45
+ # params.window_size_right = window_size_right;
46
+ #
47
+ # scheduler:
48
+ # n_block_min = max(0, (m_block * kBlockM + seqlen_k - seqlen_q - window_size_left) / kBlockN);
49
+ # n_block_max = min(n_block_max, ceil_div((m_block + 1) * kBlockM + seqlen_k - seqlen_q + window_size_right, kBlockN));
50
+ #
51
+
52
+ flash_causal = False
53
+ window_size = (-1, -1) if not is_causal else (seqlen_k, seqlen_q - seqlen_k)
54
+ if is_causal and seqlen_k < seqlen_q:
55
+ window_size = (-1, 0)
56
+
57
+ padding_KV = seqlen_q - seqlen_k
58
+ old_shape = key.shape
59
+ key = torch.nn.functional.pad(key, (0, 0, 0, 0, 0, padding_KV), "constant", 0)
60
+ value = torch.nn.functional.pad(value, (0, 0, 0, 0, 0, padding_KV), "constant", 0)
61
+ log.debug(f"Flash Attention: padded KV from {old_shape} to {key.shape}.")
62
+
63
+ print(f"{window_size=}")
64
+
65
+ #window_size = (-1, -1) if not is_causal else (-1, 0)
66
+ #window_size = (-1, -1) if not is_causal else (-1, seqlen_q - seqlen_k)
67
+
68
+ # seqlen_q=7688, seqlen_kv=2048, is_causal=True
69
+ # n_block_min = max(0, (q_start - 7688) / kBlockN);
70
+ # n_block_max = min(n_block_max, ceil_div(q_end, kBlockN));
71
+ ```
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/__init__.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v2 (flash2) Backend
21
+ """
22
+
23
+ import torch
24
+
25
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
26
+
27
+ # We lock to safe releases of Flash 2
28
+ # We will have a separate backend identifier for 2025 releases with CuTeDSL
29
+ # kernels.
30
+ FLASH_ATTENTION_V2_MIN_VERSION = [2, 7, 0]
31
+ FLASH_ATTENTION_V2_MAX_VERSION = [2, 7, 4]
32
+
33
+
34
+ def flash2_supported() -> bool:
35
+ """
36
+ Returns whether Flash Attention is supported in this environment.
37
+ Requirements are:
38
+ * Presence of CUDA Runtime (via PyTorch)
39
+ * Presence of Flash Attention, meeting minimum version requirements
40
+
41
+ This check guards imports / dependencies on the Flash Attention package.
42
+ """
43
+ if not torch.cuda.is_available():
44
+ log.debug("Flash Attention v2 is not supported because PyTorch did not detect CUDA runtime.")
45
+ return False
46
+
47
+ try:
48
+ import flash_attn
49
+
50
+ except ImportError:
51
+ log.debug("Flash Attention v2 is not supported because the Python package was not found.")
52
+ return False
53
+ except Exception as e:
54
+ log.debug(f"Flash Attention v2 is not supported because importing the Python package failed: {e}")
55
+ return False
56
+
57
+ flash2_version_str = None
58
+ if not hasattr(flash_attn, "__version__"):
59
+ from importlib.metadata import version
60
+
61
+ flash2_version_str = version("flash_attn")
62
+ else:
63
+ flash2_version_str = flash_attn.__version__
64
+
65
+ flash2_version_split = flash2_version_str.split(".")
66
+ if len(flash2_version_split) < 3:
67
+ log.debug(f"Unable to parse Flash Attention v2 version {flash2_version_str}.")
68
+ return False
69
+
70
+ try:
71
+ flash2_version = [int(x) for x in flash2_version_split[:3]]
72
+
73
+ except ValueError:
74
+ log.debug(f"Unable to parse Flash Attention v2 version as an int list: {flash2_version_str}.")
75
+ return False
76
+
77
+ if flash2_version > FLASH_ATTENTION_V2_MAX_VERSION or flash2_version < FLASH_ATTENTION_V2_MIN_VERSION:
78
+ log.debug(
79
+ "Flash Attention v2 build is not supported; this backend only supports versions "
80
+ f"{FLASH_ATTENTION_V2_MIN_VERSION} through {FLASH_ATTENTION_V2_MAX_VERSION}, got "
81
+ f"{flash2_version}."
82
+ )
83
+ return False
84
+
85
+ return True
86
+
87
+
88
+ FLASH2_SUPPORTED = flash2_supported()
89
+
90
+ if FLASH2_SUPPORTED:
91
+ from cosmos_policy._src.imaginaire.attention.flash2.functions import flash2_attention
92
+
93
+ else:
94
+ from cosmos_policy._src.imaginaire.attention.flash2.stubs import flash2_attention
95
+
96
+ __all__ = ["flash2_attention", "FLASH2_SUPPORTED"]
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/checks.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v2 (flash2) backend checks
21
+ """
22
+
23
+ from functools import partial
24
+
25
+ from torch import Tensor
26
+
27
+ from cosmos_policy._src.imaginaire.attention.checks import attention_param_checks, attention_tensor_checks
28
+ from cosmos_policy._src.imaginaire.attention.flash2 import FLASH2_SUPPORTED
29
+ from cosmos_policy._src.imaginaire.attention.flash2.meta import get_bwd_dtypes, get_fwd_dtypes
30
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
31
+ from cosmos_policy._src.imaginaire.attention.utils import get_arch_tag, log_or_raise_error
32
+
33
+
34
+ def flash2_attention_check(
35
+ query: Tensor,
36
+ key: Tensor,
37
+ value: Tensor,
38
+ is_causal: bool,
39
+ causal_type: CausalType,
40
+ is_varlen: bool,
41
+ raise_error: bool = False,
42
+ ) -> bool:
43
+ """
44
+ Input validation function for the flash2 backend.
45
+
46
+ Parameters:
47
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
48
+ (`[batch, seqlen, heads, head_dim]`).
49
+
50
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
51
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
52
+
53
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
54
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
55
+
56
+ is_causal (bool): whether or not causal masking is enabled.
57
+
58
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
59
+ `CausalType.BottomRight`. Required when `is_causal = True`.
60
+
61
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
62
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
63
+ passed.
64
+
65
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
66
+ instead of just returning False. Default is False.
67
+
68
+ Returns:
69
+ success (bool): whether use case is compatible with flash2 backend.
70
+
71
+ """
72
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
73
+
74
+ if not FLASH2_SUPPORTED:
75
+ target_fn(
76
+ "Flash Attention v2 (flash2) is not supported in this environment. Run with debug logs to find out why, or choose another backend.",
77
+ exception=RuntimeError,
78
+ )
79
+ return False
80
+
81
+ arch_tag = get_arch_tag(query.device)
82
+ fwd_dtypes = get_fwd_dtypes(arch_tag)
83
+ bwd_dtypes = get_bwd_dtypes(arch_tag)
84
+ if not attention_tensor_checks(
85
+ query=query,
86
+ key=key,
87
+ value=value,
88
+ supported_dtypes_forward=fwd_dtypes,
89
+ supported_dtypes_backward=bwd_dtypes,
90
+ supports_mla=False,
91
+ supports_gqa_mqa=True,
92
+ raise_error=raise_error,
93
+ backend_name="Flash Attention v2 (flash2)",
94
+ ):
95
+ target_fn("Flash Attention v2 (flash2) does not support the given inputs.", exception=RuntimeError)
96
+ return False
97
+
98
+ # Verifies causal_type is a CausalType instance when is_causal
99
+ # Verifies DontCare is not used unless seqlen_q == seqlen_kv
100
+ attention_param_checks(
101
+ query=query,
102
+ key=key,
103
+ value=value,
104
+ is_causal=is_causal,
105
+ causal_type=causal_type,
106
+ )
107
+
108
+ if is_causal and causal_type not in [CausalType.BottomRight, CausalType.DontCare]:
109
+ target_fn("Flash Attention only supports bottom-right causal masking.", exception=RuntimeError)
110
+ return False
111
+
112
+ return True
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/functions.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v2 (flash2) Backend: intermediate APIs
21
+ Only safe to import when FLASH2_SUPPORTED is True.
22
+ """
23
+
24
+ from flash_attn.flash_attn_interface import flash_attn_func, flash_attn_varlen_func
25
+ from torch import Tensor
26
+
27
+ from cosmos_policy._src.imaginaire.attention.flash2.checks import flash2_attention_check
28
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
29
+
30
+
31
+ def flash2_attention(
32
+ query: Tensor,
33
+ key: Tensor,
34
+ value: Tensor,
35
+ is_causal: bool = False,
36
+ causal_type: CausalType | None = None,
37
+ scale: float | None = None,
38
+ cumulative_seqlen_Q: Tensor | None = None,
39
+ cumulative_seqlen_KV: Tensor | None = None,
40
+ max_seqlen_Q: int | None = None,
41
+ max_seqlen_KV: int | None = None,
42
+ return_lse: bool = False,
43
+ backend_kwargs: dict | None = None,
44
+ ) -> Tensor | tuple[Tensor, Tensor]:
45
+ """
46
+ Runs Flash Attention v2 on given operands (Q, K, V) with the heads-last contiguous layout
47
+ (`[batch, seqlen, heads, head_dim]`).
48
+
49
+ Parameters:
50
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
51
+ (`[batch, seqlen, heads, head_dim]`)
52
+
53
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
54
+ (`[batch, seqlen_kv, heads_kv, head_dim]`)
55
+
56
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
57
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`)
58
+
59
+ is_causal (bool): whether or not causal masking is enabled. Default is False.
60
+
61
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
62
+ `CausalType.BottomRight`. Required when `is_causal = True`.
63
+
64
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
65
+
66
+ cumulative_seqlen_Q (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
67
+ indicating the cumulative sum of number of query tokens in each batch, with an
68
+ additional 0 element in the beginning. Must be passed together with
69
+ `cumulative_seqlen_KV` and `max_seqlen_{Q,KV}`.
70
+
71
+ cumulative_seqlen_KV (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
72
+ indicating the cumulative sum of number of key/value tokens in each batch, with an
73
+ additional 0 element in the beginning. Must be passed together with
74
+ `cumulative_seqlen_Q` and `max_seqlen_{Q,KV}`.
75
+
76
+ max_seqlen_Q (int | None): (varlen) Optional integer indicating the maximum query
77
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
78
+ and `max_seqlen_KV`.
79
+
80
+ max_seqlen_KV (int | None): (varlen) Optional integer indicating the maximum key/value
81
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
82
+ and `max_seqlen_Q`.
83
+
84
+ Other Parameters:
85
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
86
+
87
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to Flash's
88
+ attention operator, if any.
89
+
90
+ Returns:
91
+ output (Tensor): 4-D output tensor, with the heads-last contiguous layout
92
+ (`[batch, seqlen, heads, head_dim_v]`).
93
+
94
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
95
+ (`[batch, seqlen, heads, 1]`). Only returned when return_lse is True.
96
+ """
97
+
98
+ is_varlen = cumulative_seqlen_Q is not None
99
+ assert flash2_attention_check(
100
+ query=query,
101
+ key=key,
102
+ value=value,
103
+ is_causal=is_causal,
104
+ causal_type=causal_type,
105
+ is_varlen=is_varlen,
106
+ raise_error=True,
107
+ )
108
+
109
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
110
+
111
+ backend_kwargs = backend_kwargs if backend_kwargs is not None else {}
112
+
113
+ if is_varlen:
114
+ assert query.shape[0] == key.shape[0] == value.shape[0] == 1
115
+ q = query.squeeze(0)
116
+ k = key.squeeze(0)
117
+ v = value.squeeze(0)
118
+ assert q.dim() == k.dim() == v.dim() == 3
119
+ out, lse_, _ = flash_attn_varlen_func(
120
+ q=query.squeeze(0),
121
+ k=key.squeeze(0),
122
+ v=value.squeeze(0),
123
+ cu_seqlens_q=cumulative_seqlen_Q,
124
+ cu_seqlens_k=cumulative_seqlen_KV,
125
+ max_seqlen_q=max_seqlen_Q,
126
+ max_seqlen_k=max_seqlen_KV,
127
+ softmax_scale=scale,
128
+ causal=is_causal,
129
+ return_attn_probs=True,
130
+ **backend_kwargs,
131
+ # window_size=(-1, -1),
132
+ # dropout_p=0.0,
133
+ # softcap=0.0, # 0.0 means deactivated
134
+ # alibi_slopes=None,
135
+ # deterministic=False,
136
+ # block_table=None,
137
+ )
138
+ assert out.dim() == 3
139
+ assert lse_.dim() == 2
140
+
141
+ output = out.unsqueeze(0)
142
+ lse = lse_.unsqueeze(0)
143
+
144
+ else:
145
+ output, lse, _ = flash_attn_func(
146
+ q=query,
147
+ k=key,
148
+ v=value,
149
+ softmax_scale=scale,
150
+ causal=is_causal,
151
+ return_attn_probs=True,
152
+ **backend_kwargs,
153
+ # window_size=(-1, -1),
154
+ # dropout_p=0.0,
155
+ # softcap=0.0, # 0.0 means deactivated
156
+ # alibi_slopes=None,
157
+ # deterministic=False,
158
+ )
159
+
160
+ assert isinstance(output, Tensor)
161
+ assert isinstance(lse, Tensor)
162
+ assert output.dim() == 4
163
+ assert lse.dim() == 3
164
+
165
+ lse = lse.permute(0, 2, 1).contiguous() # [batch, seqlen, head_dim]
166
+
167
+ if return_lse:
168
+ return output, lse
169
+
170
+ return output
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/meta.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v2 (flash2) Backend: metadata
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ import torch
25
+
26
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
27
+
28
+
29
+ def get_fwd_dtypes(arch_tag: int) -> list[torch.dtype]:
30
+ """
31
+ Returns data type choices for forward pass according to arch tag (attention.utils.get_arch_tag).
32
+
33
+ Parameters:
34
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
35
+
36
+ Returns:
37
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
38
+
39
+ """
40
+
41
+ if arch_tag < 80:
42
+ log.debug("Flash Attention v2 (flash2) is not supported because compute capability is below the minimum (8.0).")
43
+ return []
44
+
45
+ return [torch.float16, torch.bfloat16]
46
+
47
+
48
+ def get_bwd_dtypes(arch_tag: int) -> list[torch.dtype]:
49
+ """
50
+ Returns data type choices for backward pass according to arch tag (attention.utils.get_arch_tag).
51
+
52
+ Parameters:
53
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
54
+
55
+ Returns:
56
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
57
+
58
+ """
59
+
60
+ if arch_tag < 80:
61
+ log.debug("Flash Attention v2 (flash2) is not supported because compute capability is below the minimum (8.0).")
62
+ return []
63
+
64
+ return [torch.float16, torch.bfloat16]
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash2/stubs.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v2 (flash2) Backend: intermediate API stubs
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ from torch import Tensor
25
+
26
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
27
+
28
+
29
+ def flash2_attention(
30
+ query: Tensor,
31
+ key: Tensor,
32
+ value: Tensor,
33
+ is_causal: bool = False,
34
+ causal_type: CausalType | None = None,
35
+ scale: float | None = None,
36
+ cumulative_seqlen_Q: Tensor | None = None,
37
+ cumulative_seqlen_KV: Tensor | None = None,
38
+ max_seqlen_Q: int | None = None,
39
+ max_seqlen_KV: int | None = None,
40
+ return_lse: bool = False,
41
+ backend_kwargs: dict | None = None,
42
+ ) -> Tensor | tuple[Tensor, Tensor]:
43
+ raise RuntimeError(
44
+ "Tried to run Flash Attention v2, but it is not supported / available. "
45
+ "Try running with debug logs enabled to see why."
46
+ )
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/__init__.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v3 (flash3) Backend
21
+ """
22
+
23
+ import torch
24
+
25
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
26
+
27
+ FLASH_ATTENTION_V3_MIN_VERSION = [3, 0, 0, 0]
28
+ FLASH_ATTENTION_V3_MAX_VERSION = [3, 0, 0, 1]
29
+
30
+
31
+ def flash3_supported() -> bool:
32
+ """
33
+ Returns whether Flash Attention is supported in this environment.
34
+ Requirements are:
35
+ * Presence of CUDA Runtime (via PyTorch)
36
+ * Presence of Flash Attention, meeting minimum version requirements
37
+
38
+ This check guards imports / dependencies on the Flash Attention package.
39
+ """
40
+ if not torch.cuda.is_available():
41
+ log.debug("Flash Attention v3 is not supported because PyTorch did not detect CUDA runtime.")
42
+ return False
43
+
44
+ try:
45
+ import flash_attn_3
46
+
47
+ except ImportError:
48
+ log.debug("Flash Attention v3 is not supported because the Python package was not found.")
49
+ return False
50
+ except Exception as e:
51
+ log.debug(f"Flash Attention v3 is not supported because importing the Python package failed: {e}")
52
+ return False
53
+
54
+ flash3_version_str = None
55
+ if not hasattr(flash_attn_3, "__version__"):
56
+ from importlib.metadata import version
57
+
58
+ flash3_version_str = version("flash_attn_3")
59
+ else:
60
+ flash3_version_str = flash_attn_3.__version__
61
+
62
+ flash3_version_split = flash3_version_str.replace("b", ".").split(".")
63
+ if len(flash3_version_split) != 4:
64
+ log.debug(f"Unable to parse Flash Attention v3 version {flash3_version_str}.")
65
+ return False
66
+
67
+ try:
68
+ flash3_version = [int(x) for x in flash3_version_split]
69
+
70
+ except ValueError:
71
+ log.debug(f"Unable to parse Flash Attention v3 version as an int list: {flash3_version_str}.")
72
+ return False
73
+
74
+ if flash3_version > FLASH_ATTENTION_V3_MAX_VERSION or flash3_version < FLASH_ATTENTION_V3_MIN_VERSION:
75
+ log.debug(
76
+ "Flash Attention v3 build is not supported; this backend only supports versions "
77
+ f"{FLASH_ATTENTION_V3_MIN_VERSION} through {FLASH_ATTENTION_V3_MAX_VERSION}, got "
78
+ f"{flash3_version}."
79
+ )
80
+ return False
81
+
82
+ return True
83
+
84
+
85
+ FLASH3_SUPPORTED = flash3_supported()
86
+
87
+
88
+ if FLASH3_SUPPORTED:
89
+ from cosmos_policy._src.imaginaire.attention.flash3.functions import flash3_attention
90
+
91
+ else:
92
+ from cosmos_policy._src.imaginaire.attention.flash3.stubs import flash3_attention
93
+
94
+ __all__ = ["flash3_attention", "FLASH3_SUPPORTED"]
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/checks.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v3 (flash3) backend checks
21
+ """
22
+
23
+ from functools import partial
24
+
25
+ from torch import Tensor
26
+
27
+ from cosmos_policy._src.imaginaire.attention.checks import attention_param_checks, attention_tensor_checks
28
+ from cosmos_policy._src.imaginaire.attention.flash3 import FLASH3_SUPPORTED
29
+ from cosmos_policy._src.imaginaire.attention.flash3.meta import get_bwd_dtypes, get_fwd_dtypes
30
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
31
+ from cosmos_policy._src.imaginaire.attention.utils import get_arch_tag, is_torch_compiling, log_or_raise_error
32
+
33
+
34
+ def flash3_attention_check(
35
+ query: Tensor,
36
+ key: Tensor,
37
+ value: Tensor,
38
+ is_causal: bool,
39
+ causal_type: CausalType,
40
+ is_varlen: bool,
41
+ raise_error: bool = False,
42
+ ) -> bool:
43
+ """
44
+ Input validation function for the flash3 backend.
45
+
46
+ Parameters:
47
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
48
+ (`[batch, seqlen, heads, head_dim]`).
49
+
50
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
51
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
52
+
53
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
54
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
55
+
56
+ is_causal (bool): whether or not causal masking is enabled.
57
+
58
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
59
+ `CausalType.BottomRight`. Required when `is_causal = True`.
60
+
61
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
62
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
63
+ passed.
64
+
65
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
66
+ instead of just returning False. Default is False.
67
+
68
+ Returns:
69
+ success (bool): whether use case is compatible with flash3 backend.
70
+
71
+ """
72
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
73
+
74
+ if not FLASH3_SUPPORTED:
75
+ target_fn(
76
+ "Flash Attention v3 (flash3) is not supported in this environment. Run with debug logs to find out why, or choose another backend.",
77
+ exception=RuntimeError,
78
+ )
79
+ return False
80
+
81
+ if is_torch_compiling():
82
+ target_fn(
83
+ "Flash Attention v3 (flash3) backend does not support torch.compile yet.",
84
+ exception=RuntimeError,
85
+ )
86
+ return False
87
+
88
+ arch_tag = get_arch_tag(query.device)
89
+ fwd_dtypes = get_fwd_dtypes(arch_tag)
90
+ bwd_dtypes = get_bwd_dtypes(arch_tag)
91
+ if not attention_tensor_checks(
92
+ query=query,
93
+ key=key,
94
+ value=value,
95
+ supported_dtypes_forward=fwd_dtypes,
96
+ supported_dtypes_backward=bwd_dtypes,
97
+ # flash3 supports MLA, unlike flash2, but with some constraints
98
+ # disabled for now due to API bug
99
+ supports_mla=False,
100
+ supports_gqa_mqa=True,
101
+ raise_error=raise_error,
102
+ backend_name="Flash Attention v3 (flash3)",
103
+ ):
104
+ target_fn("Flash Attention v3 (flash3) does not support the given inputs.", exception=RuntimeError)
105
+ return False
106
+
107
+ # MLA constraints
108
+ if query.shape[-1] != value.shape[-1]:
109
+ head_dim_q = query.shape[-1]
110
+ head_dim_v = value.shape[-1]
111
+ if not ((head_dim_q <= 64 and head_dim_v <= 512) or (128 <= head_dim_q <= 192 and 96 <= head_dim_v <= 128)):
112
+ target_fn(
113
+ "Flash Attention v3 (flash3) does not support this head dim combination. "
114
+ "Expected either head_dim_qk <= 64 and head_dim_v <= 512, or 128 <= head_dim_qk <= 192 "
115
+ f"and 96 <= head_dim_v <= 128, got {head_dim_q=}, {head_dim_v=}.",
116
+ exception=ValueError,
117
+ )
118
+ return False
119
+
120
+ # Verifies causal_type is a CausalType instance when is_causal
121
+ # Verifies DontCare is not used unless seqlen_q == seqlen_kv
122
+ attention_param_checks(
123
+ query=query,
124
+ key=key,
125
+ value=value,
126
+ is_causal=is_causal,
127
+ causal_type=causal_type,
128
+ )
129
+
130
+ if is_causal and causal_type not in [CausalType.BottomRight, CausalType.DontCare]:
131
+ target_fn("Flash Attention only supports bottom-right causal masking.", exception=ValueError)
132
+ return False
133
+
134
+ return True
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/functions.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v3 (flash3) Backend: intermediate APIs
21
+ Only safe to import when FLASH3_SUPPORTED is True.
22
+ """
23
+
24
+ import inspect
25
+
26
+ from flash_attn_3.flash_attn_interface import flash_attn_func, flash_attn_varlen_func
27
+ from torch import Tensor
28
+
29
+ # NOTE: older commits didn't have `return_attn_probs` as an argument, and there is no
30
+ # reflection of the commit hash in the version, so we have to manually inspect the signatures
31
+ HAS_RETURN_ATTN_PROBS = "return_attn_probs" in inspect.signature(flash_attn_func).parameters
32
+
33
+ from cosmos_policy._src.imaginaire.attention.flash3.checks import flash3_attention_check
34
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
35
+
36
+
37
+ def flash3_attention(
38
+ query: Tensor,
39
+ key: Tensor,
40
+ value: Tensor,
41
+ is_causal: bool = False,
42
+ causal_type: CausalType | None = None,
43
+ scale: float | None = None,
44
+ cumulative_seqlen_Q: Tensor | None = None,
45
+ cumulative_seqlen_KV: Tensor | None = None,
46
+ max_seqlen_Q: int | None = None,
47
+ max_seqlen_KV: int | None = None,
48
+ return_lse: bool = False,
49
+ backend_kwargs: dict | None = None,
50
+ ) -> Tensor | tuple[Tensor, Tensor]:
51
+ """
52
+ Runs Flash Attention v3 on given operands (Q, K, V) with the heads-last contiguous layout
53
+ (`[batch, seqlen, heads, head_dim]`).
54
+
55
+ Parameters:
56
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
57
+ (`[batch, seqlen, heads, head_dim]`)
58
+
59
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
60
+ (`[batch, seqlen_kv, heads_kv, head_dim]`)
61
+
62
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
63
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`)
64
+
65
+ is_causal (bool): whether or not causal masking is enabled. Default is False.
66
+
67
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
68
+ `CausalType.BottomRight`. Required when `is_causal = True`.
69
+
70
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
71
+
72
+ cumulative_seqlen_Q (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
73
+ indicating the cumulative sum of number of query tokens in each batch, with an
74
+ additional 0 element in the beginning. Must be passed together with
75
+ `cumulative_seqlen_KV` and `max_seqlen_{Q,KV}`.
76
+
77
+ cumulative_seqlen_KV (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
78
+ indicating the cumulative sum of number of key/value tokens in each batch, with an
79
+ additional 0 element in the beginning. Must be passed together with
80
+ `cumulative_seqlen_Q` and `max_seqlen_{Q,KV}`.
81
+
82
+ max_seqlen_Q (int | None): (varlen) Optional integer indicating the maximum query
83
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
84
+ and `max_seqlen_KV`.
85
+
86
+ max_seqlen_KV (int | None): (varlen) Optional integer indicating the maximum key/value
87
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
88
+ and `max_seqlen_Q`.
89
+
90
+ Other Parameters:
91
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
92
+
93
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to Flash's
94
+ attention operator, if any.
95
+
96
+ Returns:
97
+ output (Tensor): 4-D output tensor, with the heads-last contiguous layout
98
+ (`[batch, seqlen, heads, head_dim_v]`).
99
+
100
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
101
+ (`[batch, seqlen, heads, 1]`). Only returned when return_lse is True.
102
+ """
103
+
104
+ is_varlen = cumulative_seqlen_Q is not None
105
+ assert flash3_attention_check(
106
+ query=query,
107
+ key=key,
108
+ value=value,
109
+ is_causal=is_causal,
110
+ causal_type=causal_type,
111
+ is_varlen=is_varlen,
112
+ raise_error=True,
113
+ )
114
+
115
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
116
+
117
+ backend_kwargs = backend_kwargs if backend_kwargs is not None else {}
118
+
119
+ if HAS_RETURN_ATTN_PROBS:
120
+ backend_kwargs["return_attn_probs"] = True
121
+
122
+ if is_varlen:
123
+ assert query.shape[0] == key.shape[0] == value.shape[0] == 1
124
+ q = query.squeeze(0)
125
+ k = key.squeeze(0)
126
+ v = value.squeeze(0)
127
+ assert q.dim() == k.dim() == v.dim() == 3
128
+ out, lse_ = flash_attn_varlen_func(
129
+ q=query.squeeze(0),
130
+ k=key.squeeze(0),
131
+ v=value.squeeze(0),
132
+ cu_seqlens_q=cumulative_seqlen_Q,
133
+ cu_seqlens_k=cumulative_seqlen_KV,
134
+ max_seqlen_q=max_seqlen_Q,
135
+ max_seqlen_k=max_seqlen_KV,
136
+ softmax_scale=scale,
137
+ causal=is_causal,
138
+ **backend_kwargs,
139
+ # qv=None,
140
+ # q_descale=None, k_descale=None, v_descale=None,
141
+ # attention_chunk=0,
142
+ # num_splits=1,
143
+ # pack_gqa=None,
144
+ # sm_margin=0,
145
+ # window_size=(-1, -1),
146
+ # softcap=0.0, # 0.0 means deactivated
147
+ # deterministic=False,
148
+ )
149
+ assert out.dim() == 3
150
+ assert lse_.dim() == 2
151
+
152
+ output = out.unsqueeze(0)
153
+ lse = lse_.unsqueeze(0)
154
+
155
+ else:
156
+ output, lse = flash_attn_func(
157
+ q=query,
158
+ k=key,
159
+ v=value,
160
+ softmax_scale=scale,
161
+ causal=is_causal,
162
+ **backend_kwargs,
163
+ # qv=None,
164
+ # q_descale=None, k_descale=None, v_descale=None,
165
+ # attention_chunk=0,
166
+ # num_splits=1,
167
+ # pack_gqa=None,
168
+ # sm_margin=0,
169
+ # window_size=(-1, -1),
170
+ # softcap=0.0, # 0.0 means deactivated
171
+ # deterministic=False,
172
+ )
173
+
174
+ assert isinstance(output, Tensor)
175
+ assert isinstance(lse, Tensor)
176
+ assert output.dim() == 4
177
+ assert lse.dim() == 3
178
+
179
+ lse = lse.permute(0, 2, 1).contiguous() # [batch, seqlen, head_dim]
180
+
181
+ if return_lse:
182
+ return output, lse
183
+
184
+ return output
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/meta.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v3 (flash3) Backend: metadata
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ import torch
25
+
26
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
27
+
28
+
29
+ def get_fwd_dtypes(arch_tag: int) -> list[torch.dtype]:
30
+ """
31
+ Returns data type choices for forward pass according to arch tag (attention.utils.get_arch_tag).
32
+
33
+ Parameters:
34
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
35
+
36
+ Returns:
37
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
38
+
39
+ """
40
+
41
+ if arch_tag != 90:
42
+ log.debug("Flash Attention v3 (flash3) only supports compute capability 9.0 (Hopper).")
43
+ return []
44
+
45
+ return [torch.float16, torch.bfloat16]
46
+
47
+
48
+ def get_bwd_dtypes(arch_tag: int) -> list[torch.dtype]:
49
+ """
50
+ Returns data type choices for backward pass according to arch tag (attention.utils.get_arch_tag).
51
+
52
+ Parameters:
53
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
54
+
55
+ Returns:
56
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
57
+
58
+ """
59
+
60
+ if arch_tag != 90:
61
+ log.debug("Flash Attention v3 (flash3) only supports compute capability 9.0 (Hopper).")
62
+ return []
63
+
64
+ return [torch.float16, torch.bfloat16]
REGEN-main/cosmos_policy/_src/imaginaire/attention/flash3/stubs.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Flash Attention v3 (flash3) Backend: intermediate API stubs
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ from torch import Tensor
25
+
26
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
27
+
28
+
29
+ def flash3_attention(
30
+ query: Tensor,
31
+ key: Tensor,
32
+ value: Tensor,
33
+ is_causal: bool = False,
34
+ causal_type: CausalType | None = None,
35
+ scale: float | None = None,
36
+ cumulative_seqlen_Q: Tensor | None = None,
37
+ cumulative_seqlen_KV: Tensor | None = None,
38
+ max_seqlen_Q: int | None = None,
39
+ max_seqlen_KV: int | None = None,
40
+ return_lse: bool = False,
41
+ backend_kwargs: dict | None = None,
42
+ ) -> Tensor | tuple[Tensor, Tensor]:
43
+ raise RuntimeError(
44
+ "Tried to run Flash Attention v3, but it is not supported / available. "
45
+ "Try running with debug logs enabled to see why."
46
+ )
REGEN-main/cosmos_policy/_src/imaginaire/attention/frontend.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Frontend APIs
21
+ """
22
+
23
+ import torch
24
+ from torch import Tensor
25
+
26
+ from cosmos_policy._src.imaginaire.attention.backends import choose_backend, choose_multi_dim_backend
27
+ from cosmos_policy._src.imaginaire.attention.checks import (
28
+ attention_param_checks,
29
+ attention_tensor_checks,
30
+ multi_dim_attention_param_checks,
31
+ multi_dim_attention_param_filter,
32
+ multi_dim_attention_tensor_checks,
33
+ varlen_tensor_checks,
34
+ )
35
+ from cosmos_policy._src.imaginaire.attention.cudnn import cudnn_attention
36
+ from cosmos_policy._src.imaginaire.attention.flash2 import flash2_attention
37
+ from cosmos_policy._src.imaginaire.attention.flash3 import flash3_attention
38
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
39
+ from cosmos_policy._src.imaginaire.attention.natten import natten_attention, natten_multi_dim_attention
40
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
41
+
42
+ # Map backend names to their frontend attention API
43
+ BACKEND_MAP = {
44
+ "cudnn": cudnn_attention,
45
+ "natten": natten_attention,
46
+ "flash2": flash2_attention,
47
+ "flash3": flash3_attention,
48
+ }
49
+
50
+ MULTI_DIM_BACKEND_MAP = {
51
+ "natten": natten_multi_dim_attention,
52
+ }
53
+
54
+
55
+ def attention(
56
+ query: Tensor,
57
+ key: Tensor,
58
+ value: Tensor,
59
+ is_causal: bool = False,
60
+ causal_type: CausalType | None = None,
61
+ scale: float | None = None,
62
+ # varlen parameters
63
+ seqlens_Q: Tensor | None = None,
64
+ seqlens_KV: Tensor | None = None,
65
+ cumulative_seqlen_Q: Tensor | None = None,
66
+ cumulative_seqlen_KV: Tensor | None = None,
67
+ max_seqlen_Q: int | None = None,
68
+ max_seqlen_KV: int | None = None,
69
+ # backend & misc parameters
70
+ backend: str | None = None,
71
+ return_lse: bool = False,
72
+ backend_kwargs: dict | None = None,
73
+ ) -> Tensor | tuple[Tensor, Tensor]:
74
+ """
75
+ Runs Attention on given operands (Q, K, V) with the heads-last contiguous layout
76
+ (`[batch, seqlen, heads, head_dim]`).
77
+
78
+ Varlen Attention is only supported for the sequence-packed layout: QKV tensors have batch size
79
+ 1, and tokens from different batches are concatenated without any padding along the sequence
80
+ dimension. Sequence lengths for different batches can be provided in two ways:
81
+ 1. `seqlens_Q` and `seqlens_KV` (less efficient): only provide the sequence lengths as
82
+ integer tensors (must be on the same device as QKV), and cumulative and maximum sequence
83
+ lengths are recomputed on each call.
84
+ 2. `cumulative_seqlen_{Q,KV}` and `max_seqlen_{Q,KV}` (more efficient):
85
+ compute cumulative and maximum sequence lengths. `cumulative_seqlen_{Q,KV}` are integer
86
+ tensors on the same device as QKV containing the cumulative sum of `seqlens_{Q,KV}`,
87
+ with an additional `0` element in the beginning, therefore sized `batch+1`.
88
+ `max_seqlen_{Q,KV}` are integers (not Tensors) that represent the maximum sequence
89
+ lengths for Q and KV among all sequence batches.
90
+ You can use `generate_varlen_parameters` to generate these
91
+ parameters:
92
+ ```python3
93
+ from cosmos_policy._src.imaginaire.attention.varlen import generate_varlen_parameters
94
+ (
95
+ cumulative_seqlen_Q,
96
+ cumulative_seqlen_KV,
97
+ max_seqlen_Q,
98
+ max_seqlen_KV,
99
+ ) = generate_varlen_parameters(q, k, v, seqlens_Q, seqlens_KV)
100
+ ```
101
+
102
+ Parameters:
103
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
104
+ (`[batch, seqlen_q, heads, head_dim]`)
105
+
106
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
107
+ (`[batch, seqlen_kv, heads_kv, head_dim]`)
108
+
109
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
110
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`)
111
+
112
+ is_causal (bool): whether or not causal masking is enabled. Default is False.
113
+
114
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
115
+ `CausalType.BottomRight`, `CausalType.DontCare` (only valid when seqlen_q == seqlen_kv).
116
+ Required when `is_causal = True`.
117
+
118
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
119
+
120
+ seqlens_Q (Tensor | None): (varlen) Optional 1-D tensor with size `batch`
121
+ indicating the number of query tokens in each batch. Must be passed together with
122
+ `seqlens_KV`.
123
+
124
+ seqlens_KV (Tensor | None): (varlen) Optional 1-D tensor with size `batch`
125
+ indicating the number of key/value tokens in each batch. Must be passed together with
126
+ `seqlens_Q`.
127
+
128
+ cumulative_seqlen_Q (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
129
+ indicating the cumulative sum of number of query tokens in each batch, with an
130
+ additional 0 element in the beginning. Must be passed together with
131
+ `cumulative_seqlen_KV` and `max_seqlen_{Q,KV}`.
132
+
133
+ cumulative_seqlen_KV (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
134
+ indicating the cumulative sum of number of key/value tokens in each batch, with an
135
+ additional 0 element in the beginning. Must be passed together with
136
+ `cumulative_seqlen_Q` and `max_seqlen_{Q,KV}`.
137
+
138
+ max_seqlen_Q (int | None): (varlen) Optional integer indicating the maximum query
139
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
140
+ and `max_seqlen_KV`.
141
+
142
+ max_seqlen_KV (int | None): (varlen) Optional integer indicating the maximum key/value
143
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
144
+ and `max_seqlen_Q`.
145
+
146
+ Other Parameters:
147
+ backend (str | None): Backend to run with. If unspecified (default), it will try to
148
+ select the best available.
149
+
150
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
151
+
152
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to the backend's
153
+ attention operator, if any. Only valid when a specific backend is selected (backend is
154
+ not None).
155
+
156
+ Returns:
157
+ output (Tensor): 4-D output tensor, with the heads-last contiguous layout
158
+ (`[batch, seqlen_q, heads, head_dim_v]`).
159
+
160
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
161
+ (`[batch, seqlen_q, heads, 1]`). Only returned when return_lse is True.
162
+ """
163
+
164
+ assert attention_tensor_checks(query=query, key=key, value=value, raise_error=True)
165
+
166
+ attention_param_checks(
167
+ query=query,
168
+ key=key,
169
+ value=value,
170
+ is_causal=is_causal,
171
+ causal_type=causal_type,
172
+ )
173
+
174
+ (
175
+ cumulative_seqlen_Q,
176
+ cumulative_seqlen_KV,
177
+ max_seqlen_Q,
178
+ max_seqlen_KV,
179
+ ) = varlen_tensor_checks(
180
+ query=query,
181
+ key=key,
182
+ value=value,
183
+ seqlens_Q=seqlens_Q,
184
+ seqlens_KV=seqlens_KV,
185
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
186
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
187
+ max_seqlen_Q=max_seqlen_Q,
188
+ max_seqlen_KV=max_seqlen_KV,
189
+ )
190
+ is_varlen = cumulative_seqlen_Q is not None
191
+
192
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
193
+
194
+ if backend is None and backend_kwargs is not None:
195
+ backend_kwargs = None
196
+ log.debug("A backend was not specified, but got backend_kwargs. Ignoring... ")
197
+
198
+ if backend is not None and backend not in BACKEND_MAP:
199
+ raise ValueError(f"Selected {backend=}, but available choices are {BACKEND_MAP.keys()}. ")
200
+
201
+ compatible_backend = choose_backend(
202
+ query=query,
203
+ key=key,
204
+ value=value,
205
+ is_causal=is_causal,
206
+ causal_type=causal_type,
207
+ is_varlen=is_varlen,
208
+ backend=backend,
209
+ raise_error=False,
210
+ )
211
+
212
+ # Either incompatible backend specified by user, or no compatible backends found
213
+ # Try to see if we can handle it with graph transformations
214
+ # For now only handling GQA/MQA, but MLA, varlen, and some other features are also
215
+ # implementable with graph transformations, but we may need them even if not as efficient.
216
+ if compatible_backend is None:
217
+ is_gqa_mqa = query.shape[-2] != key.shape[-2] and query.shape[-2] > key.shape[-2]
218
+
219
+ # In practice this is the only reason why no backend would be selected,
220
+ # but moving forward we should represent support matrices for backends explicitly
221
+ # and rely on reasons to make the best decision when it comes to graph transformations.
222
+ if is_gqa_mqa:
223
+ heads = query.shape[-2]
224
+ heads_kv = key.shape[-2]
225
+ assert heads % heads_kv == 0
226
+ h_k = heads // heads_kv
227
+
228
+ query_t = query
229
+ key_t = torch.repeat_interleave(key, repeats=h_k, dim=-2, output_size=heads)
230
+ value_t = torch.repeat_interleave(value, repeats=h_k, dim=-2, output_size=heads)
231
+
232
+ log.debug("Backend incompatible with GQA/MQA use case. Trying again with graph transformation... ")
233
+ return attention(
234
+ query=query_t,
235
+ key=key_t,
236
+ value=value_t,
237
+ is_causal=is_causal,
238
+ causal_type=causal_type,
239
+ scale=scale,
240
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
241
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
242
+ max_seqlen_Q=max_seqlen_Q,
243
+ max_seqlen_KV=max_seqlen_KV,
244
+ return_lse=return_lse,
245
+ backend=backend,
246
+ backend_kwargs=backend_kwargs,
247
+ )
248
+
249
+ if backend is None:
250
+ raise ValueError(
251
+ "Could not find a compatible Attention backend for this use case / device. "
252
+ "Try running with debug logs to find out why."
253
+ )
254
+ else:
255
+ raise ValueError(
256
+ f"Selected Attention backend {backend} is incompatible with this use case / device. "
257
+ "Try running with debug logs to find out why."
258
+ )
259
+
260
+ assert compatible_backend in BACKEND_MAP
261
+ return BACKEND_MAP[compatible_backend](
262
+ query=query,
263
+ key=key,
264
+ value=value,
265
+ is_causal=is_causal,
266
+ causal_type=causal_type,
267
+ scale=scale,
268
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
269
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
270
+ max_seqlen_Q=max_seqlen_Q,
271
+ max_seqlen_KV=max_seqlen_KV,
272
+ return_lse=return_lse,
273
+ backend_kwargs=backend_kwargs,
274
+ )
275
+
276
+
277
+ def multi_dimensional_attention(
278
+ query: Tensor,
279
+ key: Tensor,
280
+ value: Tensor,
281
+ window_size: tuple | int = -1,
282
+ stride: tuple | int = 1,
283
+ dilation: tuple | int = 1,
284
+ is_causal: tuple | bool = False,
285
+ scale: float | None = None,
286
+ # backend & misc parameters
287
+ backend: str | None = None,
288
+ return_lse: bool = False,
289
+ backend_kwargs: dict | None = None,
290
+ ) -> Tensor | tuple[Tensor, Tensor]:
291
+ """
292
+ Runs Multi-Dimensional Attention on given operands (Q, K, V) with the heads-last contiguous
293
+ layout (`[batch, *, heads, head_dim]`). Supports up to and including 3 dimensions:
294
+ * 1-D: `[batch, X, heads, head_dim]`, with masking arguments expecting tuples of size 1.
295
+ * 2-D: `[batch, X, Y, heads, head_dim]`, with masking arguments expecting tuples of size 2.
296
+ * 3-D: `[batch, X, Y, Z, heads, head_dim]`, with masking arguments expecting tuples of size 3.
297
+
298
+ The dimensions here refer to the layout of tokens; that is the arrangement of tokens for each
299
+ batch/head, or the `[X]`, `[X, Y]`, `[X, Y, Z]` part of the input shape.
300
+ We refer to these as the "token layout shape".
301
+
302
+ For now, it is always expected that Q, K, and V match in the sizes of those dimensions.
303
+
304
+ Masking arguments, all of which can be set uniformly across all dimensions or per dimension, are:
305
+ * `window_size`: determines the sliding window size. -1 is interpreted as the maximum window
306
+ size. Must be either -1 or at least 2 and at most the token layout shape.
307
+ For example, if inputs are `[batch, X, Y, Z, heads_{q,kv}, head_dim_{qk,v}]`,
308
+ `window_size` must be either an integer == -1 or an integer <= `min(X, Y, Z)`,
309
+ or a tuple of size 3 corresponding to the three dimensions / axes, where:
310
+ * `window_size[0] == -1 or 2 <= window_size[0] <= X`
311
+ * `window_size[1] == -1 or 2 <= window_size[1] <= Y`
312
+ * `window_size[2] == -1 or 2 <= window_size[2] <= Z`
313
+ When `window_size` is set to the maximum for any dimension, we're effectively performing
314
+ self attention (no sparsity) along that dimension.
315
+ Default is -1 (self attention).
316
+
317
+ * `stride`: determines the step size of the sliding window. Only matters when the
318
+ corresponding `window_size` is not -1 / maximum (self attention).
319
+ Default is 1, indicating the smallest sliding window delay.
320
+ Larger values trade off translational equivariance for potentially improved efficiency.
321
+ Maximum value for `stride` along each dimension is the corresponding `window_size`.
322
+ If `stride == window_size` along any dimension, it is equivalent to blocked / windowed
323
+ attention (from works such as Swin Transformer, SAM, ViTDet, etc) along that dimension,
324
+ meaning no overlap between windows.
325
+ For more details, please refer to the GNA paper:
326
+ https://arxiv.org/abs/2504.16922
327
+
328
+ * `dilation`: introduces gaps between tokens in a sliding window, similarly to dilated
329
+ convolution.
330
+ Default is 1, indicating no gaps.
331
+ Maximum value is the largest positive integer that satisfies
332
+ `window_size * dilation <= token_layout_shape` along that dimension.
333
+ Higher dilation means more sparse and global context. Lower dilation means more
334
+ locality.
335
+ For more details, please refer to the DiNAT paper:
336
+ https://arxiv.org/abs/2209.15001
337
+
338
+ * `is_causal`: per-dimension causal mask.
339
+
340
+ Parameters:
341
+ query (Tensor): 4-D, 5-D, or 6-D query tensor, with the heads-last contiguous layout
342
+ (`[batch, *token_layout_shape, heads, head_dim]`)
343
+
344
+ key (Tensor): 4-D, 5-D, or 6-D key tensor, with the heads-last contiguous layout
345
+ (`[batch, *token_layout_shape, heads_kv, head_dim]`)
346
+
347
+ value (Tensor): 4-D, 5-D, or 6-D value tensor, with heads-last contiguous layout
348
+ (`[batch, *token_layout_shape, heads_kv, head_dim_v]`)
349
+
350
+ window_size (tuple | int): Attention window (kernel) size / shape. If an
351
+ integer, it will be repeated for all dimensions. For example `window_size=3`, when
352
+ `len(token_layout_shape) == 3`, is interpreted as `window_size=(3, 3, 3)`.
353
+ `-1`s are replaced with the corresponding `token_layout_shape`.
354
+ Final window size must satisfy `2 <= window_size <= token_layout_shape`.
355
+ Default is -1 (no sparsity).
356
+
357
+ stride (tuple | int): Sliding window step size/shape. If an integer, it will be repeated
358
+ for all dimensions. For example `stride=2`, when `len(token_layout_shape) == 3`, is
359
+ interpreted as `stride=(2, 2, 2)`.
360
+ Final stride must satisfy `1 <= stride <= window_size`.
361
+ Default is 1.
362
+
363
+ dilation (tuple | int): Dilation step size/shape. If an integer, it will be repeated for
364
+ all dimensions. For example `dilation=4`, when `len(token_layout_shape) == 3`, is
365
+ interpreted as `dilation=(4, 4, 4)`.
366
+ Final dilation must satisfy `2 <= dilation * window_size <= token_layout_shape`.
367
+ Default is 1.
368
+
369
+ is_causal (tuple | bool): Toggle causal masking. If a boolean, it will be repeated for all
370
+ dimensions. For example `is_causal=True`, when `len(token_layout_shape) == 3`, is
371
+ interpreted as `is_causal=(True, True, True)`.
372
+ Default is False.
373
+
374
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
375
+
376
+ Other Parameters:
377
+ backend (str | None): Backend to run with. If unspecified (default), it will try to
378
+ select the best available.
379
+
380
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
381
+
382
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to the backend's
383
+ multi-dim / sparse attention operator, if any. Only valid when a specific backend is
384
+ selected (backend is not None).
385
+
386
+ Returns:
387
+ output (Tensor): 4-D, 5-D, or 6-D output tensor, with the heads-last contiguous layout
388
+ (`[batch, *token_layout_shape, heads, head_dim_v]`).
389
+
390
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
391
+ (`[batch, *token_layout_shape, heads, 1]`). Only returned when return_lse is True.
392
+ """
393
+
394
+ assert multi_dim_attention_tensor_checks(query=query, key=key, value=value, raise_error=True)
395
+
396
+ token_layout_shape, window_size, stride, dilation, is_causal = multi_dim_attention_param_filter(
397
+ query,
398
+ window_size=window_size,
399
+ stride=stride,
400
+ dilation=dilation,
401
+ is_causal=is_causal,
402
+ )
403
+ num_dims = len(token_layout_shape)
404
+
405
+ # Automatic transformation for 1s in token layout
406
+ # I.e. Attention over a (1, 16, 32) token layout is identical to over a (16, 32)
407
+ # NOTE: assumes QKV token layouts match
408
+ token_layout_ones = [i for i in range(num_dims) if token_layout_shape[i] == 1]
409
+ if len(token_layout_ones) > 0:
410
+ token_layout_t = tuple(s for i, s in enumerate(token_layout_shape) if i not in token_layout_ones)
411
+ window_size_t = tuple(w for i, w in enumerate(window_size) if i not in token_layout_ones)
412
+ stride_t = tuple(s for i, s in enumerate(stride) if i not in token_layout_ones)
413
+ dilation_t = tuple(d for i, d in enumerate(dilation) if i not in token_layout_ones)
414
+ is_causal_t = tuple(c for i, c in enumerate(is_causal) if i not in token_layout_ones)
415
+
416
+ assert all(x >= 2 for x in token_layout_t)
417
+ assert all(w >= 2 for w in window_size_t)
418
+
419
+ query_t = query.reshape(query.shape[0], *token_layout_t, query.shape[-2], query.shape[-1])
420
+ key_t = key.reshape(key.shape[0], *token_layout_t, key.shape[-2], key.shape[-1])
421
+ value_t = key.reshape(value.shape[0], *token_layout_t, value.shape[-2], value.shape[-1])
422
+
423
+ log.debug(
424
+ "This Multi-Dimensional Attention problem has 1s in the token layout, which can be simplified from "
425
+ f"<{token_layout_shape=}, {window_size=}, {stride=}, {dilation=}, {is_causal=}> into "
426
+ f"<{token_layout_t=}, {window_size_t=}, {stride_t=}, {dilation_t=}, {is_causal_t=}>."
427
+ )
428
+
429
+ return multi_dimensional_attention(
430
+ query=query_t,
431
+ key=key_t,
432
+ value=value_t,
433
+ window_size=window_size_t,
434
+ stride=stride_t,
435
+ dilation=dilation_t,
436
+ is_causal=is_causal_t,
437
+ scale=scale,
438
+ backend=backend,
439
+ return_lse=return_lse,
440
+ backend_kwargs=backend_kwargs,
441
+ )
442
+
443
+ multi_dim_attention_param_checks(
444
+ query,
445
+ window_size=window_size,
446
+ stride=stride,
447
+ dilation=dilation,
448
+ is_causal=is_causal,
449
+ )
450
+
451
+ # Fast path for self attention problems
452
+ if all(x == w for x, w in zip(token_layout_shape, window_size)) and (
453
+ not any(c for c in is_causal) or num_dims == 1
454
+ ):
455
+ log.debug(
456
+ "This Multi-Dimensional Attention problem is implementable with standard Attention: "
457
+ f"{token_layout_shape=}, {window_size=}, {is_causal=}."
458
+ )
459
+ if backend is not None:
460
+ log.debug(f"Ignoring {backend=} and backend args...")
461
+
462
+ query_1d = query.flatten(1, num_dims)
463
+ key_1d = key.flatten(1, num_dims)
464
+ value_1d = value.flatten(1, num_dims)
465
+ is_causal_1d = is_causal[0]
466
+
467
+ return attention(
468
+ query_1d,
469
+ key_1d,
470
+ value_1d,
471
+ scale=scale,
472
+ is_causal=is_causal_1d,
473
+ causal_type=CausalType.DontCare,
474
+ return_lse=return_lse,
475
+ )
476
+
477
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
478
+
479
+ if backend is None and backend_kwargs is not None:
480
+ backend_kwargs = None
481
+ log.debug("A backend was not specified, but got backend_kwargs. Ignoring... ")
482
+
483
+ backend = choose_multi_dim_backend(
484
+ query=query,
485
+ key=key,
486
+ value=value,
487
+ backend=backend,
488
+ )
489
+
490
+ if backend not in MULTI_DIM_BACKEND_MAP:
491
+ raise ValueError(f"Selected {backend=}, but available choices are {MULTI_DIM_BACKEND_MAP.keys()}. ")
492
+
493
+ return MULTI_DIM_BACKEND_MAP[backend](
494
+ query=query,
495
+ key=key,
496
+ value=value,
497
+ window_size=window_size,
498
+ stride=stride,
499
+ dilation=dilation,
500
+ is_causal=is_causal,
501
+ scale=scale,
502
+ return_lse=return_lse,
503
+ backend_kwargs=backend_kwargs,
504
+ )
505
+
506
+
507
+ def spatio_temporal_attention(
508
+ query: Tensor,
509
+ key: Tensor,
510
+ value: Tensor,
511
+ window_size: tuple | int = -1,
512
+ stride: tuple | int = 1,
513
+ dilation: tuple | int = 1,
514
+ scale: float | None = None,
515
+ # backend & misc parameters
516
+ backend: str | None = None,
517
+ return_lse: bool = False,
518
+ backend_kwargs: dict | None = None,
519
+ ) -> Tensor | tuple[Tensor, Tensor]:
520
+ """
521
+ Runs Spatio-Temporal Attention on unflattened QKV with the heads-last contiguous layout
522
+ (`[batch, T, H, W, heads, head_dim]`).
523
+ For now, it is always expected that Q, K, and V match in their shapes.
524
+
525
+ Parameters:
526
+ query (Tensor): 6-D query tensor, with the heads-last contiguous layout
527
+ (`[batch, T, H, W, heads, head_dim]`)
528
+
529
+ key (Tensor): 6-D key tensor, with the heads-last contiguous layout
530
+ (`[batch, T, H, W, heads_kv, head_dim]`)
531
+
532
+ value (Tensor): 6-D value tensor, with heads-last contiguous layout
533
+ (`[batch, T, H, W, heads_kv, head_dim_v]`)
534
+
535
+ window_size (tuple | int): Attention window (kernel) size / shape. If an
536
+ integer, it will be repeated for all dimensions. For example `window_size=3` is
537
+ interpreted as `window_size=(3, 3, 3)`.
538
+ `-1`s are replaced with the corresponding value in `(T, H, W)`.
539
+ Default is -1 (no sparsity).
540
+
541
+ stride (tuple | int): Sliding window step size/shape. If an integer, it will be repeated
542
+ for all dimensions. For example `stride=2` is interpreted as `stride=(2, 2, 2)`.
543
+ Final stride must satisfy `1 <= stride <= window_size`.
544
+ Default is 1.
545
+
546
+ dilation (tuple | int): Dilation step size/shape. If an integer, it will be repeated for
547
+ all dimensions. For example `dilation=4` is interpreted as `dilation=(4, 4, 4)`.
548
+ Final dilation must satisfy `2 <= dilation * window_size <= (T, H, W)`.
549
+ Default is 1.
550
+
551
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
552
+
553
+ Other Parameters:
554
+ backend (str | None): Backend to run with. If unspecified (default), it will try to
555
+ select the best available.
556
+
557
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
558
+
559
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to the backend's
560
+ multi-dim / sparse attention operator, if any. Only valid when a specific backend is
561
+ selected (backend is not None).
562
+
563
+ Returns:
564
+ output (Tensor): 6-D output tensor, with the heads-last contiguous layout
565
+ (`[batch, T, H, W, heads, head_dim_v]`).
566
+
567
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
568
+ (`[batch, T, H, W, heads, 1]`). Only returned when return_lse is True.
569
+ """
570
+ if query.dim() != 6:
571
+ raise ValueError(
572
+ "Spatio-Temporal Attention requires 6-D input tensors ([batch, T, H, W, heads, head_dim]), "
573
+ f"got {query.shape=})."
574
+ )
575
+
576
+ return multi_dimensional_attention(
577
+ query=query,
578
+ key=key,
579
+ value=value,
580
+ window_size=window_size,
581
+ stride=stride,
582
+ dilation=dilation,
583
+ is_causal=(True, False, False),
584
+ scale=scale,
585
+ return_lse=return_lse,
586
+ backend_kwargs=backend_kwargs,
587
+ )
REGEN-main/cosmos_policy/_src/imaginaire/attention/masks.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Mask utilities
21
+ """
22
+
23
+ from enum import Enum
24
+
25
+
26
+ class CausalType(Enum):
27
+ """
28
+ Different types of causal masking supported by backends of interest.
29
+ """
30
+
31
+ # Top-Left: Simplified: mask if q_idx < kv_idx
32
+ # CUTLASS / NATTEN default
33
+ # Q = 2, KV = 5:
34
+ # O____
35
+ # OO___
36
+ #
37
+ # Q = 5, KV = 2:
38
+ # O_
39
+ # OO
40
+ # OO
41
+ # OO
42
+ # OO
43
+ TopLeft = 0
44
+
45
+ # Bottom-right: mask if q_idx + KV - Q < kv_idx
46
+ # Flash Attention default
47
+ # Q = 2, KV = 5:
48
+ # OOOO_
49
+ # OOOOO
50
+ #
51
+ # Q = 5, KV = 2:
52
+ # __
53
+ # __
54
+ # __
55
+ # O_
56
+ # OO
57
+ BottomRight = 1
58
+
59
+ # When seqlen_q == seqlen_kv, we don't care about the causal type
60
+ # because top-left and bottom-right are equivalent
61
+ DontCare = 2
REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/__init__.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ NATTEN Backend
21
+ """
22
+
23
+ import torch
24
+
25
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
26
+
27
+ NATTEN_MIN_RELEASE_VERSION = [0, 21, 5]
28
+ # 0.21.5.dev1 patches some varlen issues
29
+ # 0.21.5.dev2 adds torch compile support
30
+ # 0.21.5.dev3 fixes a few compat issues for older torch versions
31
+ NATTEN_MIN_DEV_VERSION = ([0, 21, 5], 3)
32
+
33
+
34
+ def natten_supported() -> bool:
35
+ """
36
+ Returns whether NATTEN is supported in this environment.
37
+ Requirements are:
38
+ * Presence of CUDA Runtime (via PyTorch)
39
+ * Presence of NATTEN, meeting minimum version requirements
40
+
41
+ This check guards imports / dependencies on the NATTEN package.
42
+ """
43
+ if not torch.cuda.is_available():
44
+ log.debug("NATTEN Attention is not supported because PyTorch did not detect CUDA runtime.")
45
+ return False
46
+
47
+ try:
48
+ import natten
49
+
50
+ except ImportError:
51
+ log.debug("NATTEN Attention is not supported because the Python package was not found.")
52
+ return False
53
+ except Exception as e:
54
+ log.debug(f"NATTEN Attention is not supported because importing the Python package failed: {e}")
55
+ return False
56
+
57
+ natten_version_split = natten.__version__.split(".")
58
+ if len(natten_version_split) < 3 or len(natten_version_split) > 4:
59
+ log.debug(f"Unable to parse NATTEN version {natten.__version__}.")
60
+ return False
61
+
62
+ try:
63
+ natten_version = [int(x) for x in natten_version_split[:3]]
64
+ natten_version_dev = None
65
+ if len(natten_version_split) >= 4 and natten_version_split[3].startswith("dev"):
66
+ natten_version_dev = int(natten_version_split[3].replace("dev", ""))
67
+
68
+ except ValueError:
69
+ log.debug(f"Unable to parse NATTEN version as an int list: {natten.__version__}.")
70
+ return False
71
+
72
+ if (natten_version_dev is None and natten_version >= NATTEN_MIN_RELEASE_VERSION) or (
73
+ natten_version_dev is not None
74
+ and natten_version >= NATTEN_MIN_DEV_VERSION[0]
75
+ and natten_version_dev >= NATTEN_MIN_DEV_VERSION[1]
76
+ ):
77
+ return True
78
+
79
+ log.debug(
80
+ "NATTEN Attention is not supported due to insufficient NATTEN version "
81
+ f"{natten.__version__=}, expected at least {NATTEN_MIN_RELEASE_VERSION=}, "
82
+ f"or {NATTEN_MIN_DEV_VERSION=}."
83
+ )
84
+ return False
85
+
86
+
87
+ NATTEN_SUPPORTED = natten_supported()
88
+
89
+ if NATTEN_SUPPORTED:
90
+ from cosmos_policy._src.imaginaire.attention.natten.functions import natten_attention, natten_multi_dim_attention
91
+
92
+ else:
93
+ from cosmos_policy._src.imaginaire.attention.natten.stubs import natten_attention, natten_multi_dim_attention
94
+
95
+ __all__ = ["natten_attention", "natten_multi_dim_attention", "NATTEN_SUPPORTED"]
REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/checks.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ NATTEN backend checks
21
+ """
22
+
23
+ from functools import partial
24
+
25
+ import torch
26
+ from torch import Tensor
27
+
28
+ from cosmos_policy._src.imaginaire.attention.checks import (
29
+ attention_param_checks,
30
+ attention_tensor_checks,
31
+ multi_dim_attention_tensor_checks,
32
+ )
33
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
34
+ from cosmos_policy._src.imaginaire.attention.natten import NATTEN_SUPPORTED
35
+ from cosmos_policy._src.imaginaire.attention.natten.meta import get_bwd_dtypes, get_fwd_dtypes
36
+ from cosmos_policy._src.imaginaire.attention.utils import get_arch_tag, log_or_raise_error
37
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
38
+
39
+
40
+ def dtype_supported(
41
+ dtype: torch.dtype, is_training: bool, dtypes_fwd: list[torch.dtype], dtypes_bwd: list[torch.dtype] | None = None
42
+ ) -> bool:
43
+ """
44
+ Helper determining whether dtype is supported with different sets of supported dtypes for
45
+ training and inference (forward+backward and forward).
46
+
47
+ Parameters:
48
+ dtype (torch.dtype): tensor element type.
49
+
50
+ is_training (bool): whether use case can be used to backpropagate (tensor.requires_grad).
51
+
52
+ dtypes_fwd (list[torch.dtype]): list of dtypes allowed for inference only (when not
53
+ tensor.requires_grad).
54
+
55
+ dtypes_bwd (list[torch.dtype] | None): Optional list of dtypes allowed for training only
56
+ (when tensor.requires_grad), if different from dtypes_fwd.
57
+
58
+ """
59
+ if is_training and dtypes_bwd is not None:
60
+ return dtype in dtypes_bwd
61
+ return dtype in dtypes_fwd
62
+
63
+
64
+ def choose_natten_backend(
65
+ query: Tensor, key: Tensor, value: Tensor, is_causal: bool, is_varlen: bool, raise_error: bool = False
66
+ ) -> str | None:
67
+ """
68
+ Chooses an FMHA backend in NATTEN (cutlass-fmha, hopper-fmha, blackwell-fmha) for the current
69
+ use case based on features needed and current GPU architecture.
70
+
71
+ Using tensor shapes, it infers whether MLA (head_dim_value != head_dim_qk) or
72
+ GQA/MQA (heads_kv != heads_q) are required.
73
+ Using tensor device, it infers GPU architecture and compatible backends.
74
+ Using arguments is_causal and is_varlen, and other inferred features, it picks the best
75
+ available backend.
76
+
77
+ It is possible for no backend to be selected, if the combination of features is not available in
78
+ any one of the NATTEN backends, in which case it will return None.
79
+
80
+ Parameters:
81
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
82
+ (`[batch, seqlen, heads, head_dim]`).
83
+
84
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
85
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
86
+
87
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
88
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
89
+
90
+ is_causal (bool): whether or not causal masking is enabled.
91
+
92
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
93
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
94
+ passed.
95
+
96
+ raise_error (bool): whether to raise an error if no backend is selected, instead of just
97
+ returning None. Default is False.
98
+
99
+ Returns:
100
+ backend (str | None): selected NATTEN backend, if any compatible.
101
+
102
+ """
103
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
104
+
105
+ # NOTE: assumes attention_tensor_checks have already been run once!
106
+ arch_tag = get_arch_tag(query.device)
107
+ dtype = query.dtype
108
+ is_training = query.requires_grad
109
+
110
+ is_mla = query.shape[-1] != value.shape[-1]
111
+ is_gqa_mqa = query.shape[-2] != key.shape[-2]
112
+
113
+ # banning devices not supported since CUDA 13.0 for simplicity
114
+ if arch_tag < 75:
115
+ log.debug("NATTEN is not supported because compute capability is below the minimum (7.5).")
116
+ return None
117
+
118
+ # blackwell-fmha: sm100 and sm103 only.
119
+ # limitations: no mla (TBD).
120
+ blackwell_fmha_fwd_dtypes = [torch.float16, torch.bfloat16, torch.float8_e5m2, torch.float8_e4m3fn]
121
+ blackwell_fmha_bwd_dtypes = [torch.float16, torch.bfloat16]
122
+ dtype_supported_blackwell = dtype_supported(
123
+ dtype=dtype, is_training=is_training, dtypes_fwd=blackwell_fmha_fwd_dtypes, dtypes_bwd=blackwell_fmha_bwd_dtypes
124
+ )
125
+ if arch_tag in [100, 103] and not is_mla and dtype_supported_blackwell:
126
+ return "blackwell-fmha"
127
+ else:
128
+ reason = ""
129
+ if arch_tag not in [100, 103]:
130
+ reason += f"Incompatible architecture ({arch_tag}, expected 100 or 103). "
131
+ if is_mla:
132
+ reason += "Use case is MLA (head_dim_qk != head_dim_value). "
133
+ if not dtype_supported_blackwell:
134
+ if is_training:
135
+ reason += (
136
+ f"Data type {dtype} is not in list of supported dtypes for training: {blackwell_fmha_bwd_dtypes}. "
137
+ )
138
+ else:
139
+ reason += (
140
+ f"Data type {dtype} is not in list of supported dtypes for inference: {blackwell_fmha_fwd_dtypes}. "
141
+ )
142
+ log.debug(f"NATTEN backend blackwell-fmha is not compatible. Reason: {reason}")
143
+
144
+ # hopper-fmha: sm90 only.
145
+ # limitations: no causal masking (TBD), no varlen, no gqa/mqa, no mla.
146
+ hopper_fmha_dtypes = [torch.float16, torch.bfloat16]
147
+ dtype_supported_hopper = dtype_supported(dtype=dtype, is_training=is_training, dtypes_fwd=hopper_fmha_dtypes)
148
+ if arch_tag == 90 and not is_causal and not is_varlen and not is_gqa_mqa and not is_mla and dtype_supported_hopper:
149
+ return "hopper-fmha"
150
+ else:
151
+ reason = ""
152
+ if arch_tag != 90:
153
+ reason += f"Incompatible architecture ({arch_tag}, expected 90). "
154
+ if is_causal:
155
+ reason += "Use case is causal. "
156
+ if is_varlen:
157
+ reason += "Use case is varlen. "
158
+ if is_gqa_mqa:
159
+ reason += "Use case is GQA/MQA. "
160
+ if is_mla:
161
+ reason += "Use case is MLA (head_dim_qk != head_dim_value). "
162
+ if not dtype_supported_hopper:
163
+ reason += f"Data type {dtype} is not in list of supported dtypes: {hopper_fmha_dtypes}. "
164
+ log.debug(f"NATTEN backend hopper-fmha is not compatible. Reason: {reason}")
165
+
166
+ # cutlass-fmha: targets sm50, sm70, sm75, sm80 (supports sm80+)
167
+ # limitations: no gqa/mqa.
168
+ cutlass_fmha_dtypes = [torch.float32, torch.float16, torch.bfloat16]
169
+ dtype_supported_cutlass = dtype_supported(dtype=dtype, is_training=is_training, dtypes_fwd=cutlass_fmha_dtypes)
170
+ if not is_gqa_mqa and dtype_supported_cutlass:
171
+ return "cutlass-fmha"
172
+ else:
173
+ reason = ""
174
+ if is_gqa_mqa:
175
+ reason += "Use case is GQA/MQA. "
176
+ if not dtype_supported_cutlass:
177
+ reason += f"Data type {dtype} is not in list of supported dtypes: {cutlass_fmha_dtypes}. "
178
+ log.debug(f"NATTEN backend cutlass-fmha is not compatible. Reason: {reason}")
179
+
180
+ target_fn(
181
+ f"Could not find a compatible NATTEN FMHA backend for {arch_tag=}, {is_causal=}, "
182
+ f"{is_varlen=}, {is_mla=}, {is_gqa_mqa=}.",
183
+ exception=RuntimeError,
184
+ )
185
+ return None
186
+
187
+
188
+ def natten_attention_check(
189
+ query: Tensor,
190
+ key: Tensor,
191
+ value: Tensor,
192
+ is_causal: bool,
193
+ causal_type: CausalType,
194
+ is_varlen: bool,
195
+ raise_error: bool = False,
196
+ ) -> bool:
197
+ """
198
+ Input validation function for the NATTEN backend.
199
+ Runs the common checks in addition to trying to find a compatible NATTEN backend. If any checks
200
+ fail, or no compatible backend is found in NATTEN, returns False.
201
+
202
+ Parameters:
203
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
204
+ (`[batch, seqlen, heads, head_dim]`).
205
+
206
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
207
+ (`[batch, seqlen_kv, heads_kv, head_dim]`).
208
+
209
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
210
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`).
211
+
212
+ is_causal (bool): whether or not causal masking is enabled.
213
+
214
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
215
+ `CausalType.BottomRight`. Required when `is_causal = True`.
216
+
217
+ is_varlen (bool): whether or not a variable length (varlen) use case. Must be inferred
218
+ beforehand based on arguments such as seqlens_{Q,KV} or cumulative_seqlen_{Q,KV} being
219
+ passed.
220
+
221
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
222
+ instead of just returning False. Default is False.
223
+
224
+ Returns:
225
+ success (bool): whether use case is compatible with NATTEN backend.
226
+
227
+ """
228
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
229
+
230
+ if not NATTEN_SUPPORTED:
231
+ target_fn(
232
+ "NATTEN is not supported in this environment. Run with debug logs to find out why, or choose another backend.",
233
+ exception=RuntimeError,
234
+ )
235
+ return False
236
+
237
+ arch_tag = get_arch_tag(query.device)
238
+ fwd_dtypes = get_fwd_dtypes(arch_tag)
239
+ bwd_dtypes = get_bwd_dtypes(arch_tag)
240
+ if not attention_tensor_checks(
241
+ query=query,
242
+ key=key,
243
+ value=value,
244
+ supported_dtypes_forward=fwd_dtypes,
245
+ supported_dtypes_backward=bwd_dtypes,
246
+ supports_mla=True,
247
+ supports_gqa_mqa=True,
248
+ raise_error=raise_error,
249
+ backend_name="NATTEN Attention",
250
+ ):
251
+ target_fn("NATTEN does not support the given inputs.", exception=RuntimeError)
252
+ return False
253
+
254
+ # Verifies causal_type is a CausalType instance when is_causal
255
+ # Verifies DontCare is not used unless seqlen_q == seqlen_kv
256
+ attention_param_checks(
257
+ query=query,
258
+ key=key,
259
+ value=value,
260
+ is_causal=is_causal,
261
+ causal_type=causal_type,
262
+ )
263
+
264
+ if is_causal and causal_type not in [CausalType.TopLeft, CausalType.DontCare]:
265
+ target_fn("NATTEN Attention only supports top-left causal masking for now.", exception=RuntimeError)
266
+ return False
267
+
268
+ natten_backend = choose_natten_backend(
269
+ query, key, value, is_causal=is_causal, is_varlen=is_varlen, raise_error=raise_error
270
+ )
271
+
272
+ if natten_backend is None:
273
+ return False
274
+
275
+ return True
276
+
277
+
278
+ def choose_natten_multi_dim_backend(query: Tensor, key: Tensor, value: Tensor, raise_error: bool = False) -> str | None:
279
+ """
280
+ Chooses an FNA backend in NATTEN (cutlass-fna, hopper-fna, blackwell-fna) for the current
281
+ use case based on features needed and current GPU architecture.
282
+
283
+ Using tensor shapes, it infers whether MLA (head_dim_value != head_dim_qk) or
284
+ GQA/MQA (heads_kv != heads_q) are required.
285
+ Using tensor device, it infers GPU architecture and compatible backends.
286
+ Using arguments is_causal and is_varlen, and other inferred features, it picks the best
287
+ available backend.
288
+
289
+ It is possible for no backend to be selected, if the combination of features is not available in
290
+ any one of the NATTEN backends, in which case it will return None.
291
+
292
+ Parameters:
293
+ query (Tensor): 4-D, 5-D, or 6-D query tensor, with the heads-last contiguous layout
294
+ (`[batch, *token_layout_shape, heads, head_dim]`).
295
+
296
+ key (Tensor): 4-D, 5-D, or 6-D key tensor, with the heads-last contiguous layout
297
+ (`[batch, *token_layout_shape, heads_kv, head_dim]`).
298
+
299
+ value (Tensor): 4-D, 5-D, or 6-D value tensor, with heads-last contiguous layout
300
+ (`[batch, *token_layout_shape, heads_kv, head_dim_v]`).
301
+
302
+ raise_error (bool): whether to raise an error if no backend is selected, instead of just
303
+ returning None. Default is False.
304
+
305
+ Returns:
306
+ backend (str | None): selected NATTEN backend, if any compatible.
307
+
308
+ """
309
+
310
+ # Reuse choose_natten_backend instead of duplicating code
311
+ # NATTEN specifically makes sure the FNA counterparts cover all the features the FMHA kernels
312
+ # do.
313
+ fmha_backend = choose_natten_backend(
314
+ query=query,
315
+ key=key,
316
+ value=value,
317
+ is_causal=False, # causal masking in supported across all multi-dim (FNA) backends
318
+ is_varlen=False, # varlen is undefined (so far) for multi-dim
319
+ raise_error=raise_error,
320
+ )
321
+
322
+ natten_fmha_backend_to_fna_backend = {
323
+ "cutlass-fmha": "cutlass-fna",
324
+ "hopper-fmha": "hopper-fna",
325
+ "blackwell-fmha": "blackwell-fna",
326
+ }
327
+
328
+ assert fmha_backend in natten_fmha_backend_to_fna_backend
329
+ return natten_fmha_backend_to_fna_backend[fmha_backend]
330
+
331
+
332
+ def natten_multi_dim_attention_check(
333
+ query: Tensor,
334
+ key: Tensor,
335
+ value: Tensor,
336
+ raise_error: bool = False,
337
+ ) -> bool:
338
+ """
339
+ Input validation function for the NATTEN multi-dimensional backend.
340
+ Runs the common checks in addition to trying to find a compatible NATTEN backend. If any checks
341
+ fail, or no compatible backend is found in NATTEN, returns False.
342
+
343
+ Parameters:
344
+ query (Tensor): 4-D, 5-D, or 6-D query tensor, with the heads-last contiguous layout
345
+ (`[batch, *token_layout_shape, heads, head_dim]`).
346
+
347
+ key (Tensor): 4-D, 5-D, or 6-D key tensor, with the heads-last contiguous layout
348
+ (`[batch, *token_layout_shape, heads_kv, head_dim]`).
349
+
350
+ value (Tensor): 4-D, 5-D, or 6-D value tensor, with heads-last contiguous layout
351
+ (`[batch, *token_layout_shape, heads_kv, head_dim_v]`).
352
+
353
+ raise_error (bool): whether to raise an error if any checks fail or no backend is selected,
354
+ instead of just returning False. Default is False.
355
+
356
+ Returns:
357
+ success (bool): whether use case is compatible with NATTEN backend.
358
+
359
+ """
360
+ target_fn = partial(log_or_raise_error, raise_error=raise_error)
361
+
362
+ if not NATTEN_SUPPORTED:
363
+ target_fn(
364
+ "NATTEN is not supported in this environment. Run with debug logs to find out why, or choose another backend.",
365
+ exception=RuntimeError,
366
+ )
367
+ return False
368
+
369
+ arch_tag = get_arch_tag(query.device)
370
+ fwd_dtypes = get_fwd_dtypes(arch_tag)
371
+ bwd_dtypes = get_bwd_dtypes(arch_tag)
372
+ if not multi_dim_attention_tensor_checks(
373
+ query=query,
374
+ key=key,
375
+ value=value,
376
+ supported_dtypes_forward=fwd_dtypes,
377
+ supported_dtypes_backward=bwd_dtypes,
378
+ supports_mla=True,
379
+ supports_gqa_mqa=False, # NATTEN's FNA ops don't support GQA/MQA yet
380
+ raise_error=raise_error,
381
+ backend_name="NATTEN Multi-Dimensional Attention",
382
+ ):
383
+ target_fn("NATTEN does not support the given inputs.", exception=RuntimeError)
384
+ return False
385
+
386
+ natten_backend = choose_natten_multi_dim_backend(query, key, value, raise_error=raise_error)
387
+
388
+ if natten_backend is None:
389
+ return False
390
+
391
+ return True
REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/functions.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ NATTEN Backend: intermediate APIs
21
+ Only safe to import when NATTEN_SUPPORTED is True.
22
+ """
23
+
24
+ from natten.context import set_memory_usage_preference, use_kv_parallelism_in_fused_na
25
+ from natten.functional import attention as _natten_attention
26
+ from natten.functional import neighborhood_attention_generic as _natten_multi_dim_attention
27
+ from torch import Tensor
28
+
29
+ from cosmos_policy._src.imaginaire.attention.checks import (
30
+ multi_dim_attention_param_checks,
31
+ multi_dim_attention_param_filter,
32
+ )
33
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
34
+ from cosmos_policy._src.imaginaire.attention.natten.checks import (
35
+ choose_natten_backend,
36
+ choose_natten_multi_dim_backend,
37
+ natten_attention_check,
38
+ natten_multi_dim_attention_check,
39
+ )
40
+
41
+ set_memory_usage_preference("unrestricted")
42
+ use_kv_parallelism_in_fused_na(True)
43
+
44
+
45
+ def natten_attention(
46
+ query: Tensor,
47
+ key: Tensor,
48
+ value: Tensor,
49
+ is_causal: bool = False,
50
+ causal_type: CausalType | None = None,
51
+ scale: float | None = None,
52
+ cumulative_seqlen_Q: Tensor | None = None,
53
+ cumulative_seqlen_KV: Tensor | None = None,
54
+ max_seqlen_Q: int | None = None,
55
+ max_seqlen_KV: int | None = None,
56
+ return_lse: bool = False,
57
+ backend_kwargs: dict | None = None,
58
+ ) -> Tensor | tuple[Tensor, Tensor]:
59
+ """
60
+ Runs NATTEN Attention on given operands (Q, K, V) with the heads-last contiguous layout
61
+ (`[batch, seqlen, heads, head_dim]`).
62
+
63
+ Parameters:
64
+ query (Tensor): 4-D query tensor, with the heads-last contiguous layout
65
+ (`[batch, seqlen, heads, head_dim]`)
66
+
67
+ key (Tensor): 4-D key tensor, with the heads-last contiguous layout
68
+ (`[batch, seqlen_kv, heads_kv, head_dim]`)
69
+
70
+ value (Tensor): 4-D value tensor, with heads-last contiguous layout
71
+ (`[batch, seqlen_kv, heads_kv, head_dim_v]`)
72
+
73
+ is_causal (bool): whether or not causal masking is enabled. Default is False.
74
+
75
+ causal_type (CausalType): causal masking mode. Choices: `CausalType.TopLeft`,
76
+ `CausalType.BottomRight`. Required when `is_causal = True`.
77
+
78
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
79
+
80
+ cumulative_seqlen_Q (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
81
+ indicating the cumulative sum of number of query tokens in each batch, with an
82
+ additional 0 element in the beginning. Must be passed together with
83
+ `cumulative_seqlen_KV` and `max_seqlen_{Q,KV}`.
84
+
85
+ cumulative_seqlen_KV (Tensor | None): (varlen) Optional 1-D tensor with size `batch + 1`
86
+ indicating the cumulative sum of number of key/value tokens in each batch, with an
87
+ additional 0 element in the beginning. Must be passed together with
88
+ `cumulative_seqlen_Q` and `max_seqlen_{Q,KV}`.
89
+
90
+ max_seqlen_Q (int | None): (varlen) Optional integer indicating the maximum query
91
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
92
+ and `max_seqlen_KV`.
93
+
94
+ max_seqlen_KV (int | None): (varlen) Optional integer indicating the maximum key/value
95
+ sequence length in all batches. Must be passed together with `cumulative_seqlen_{Q,KV}`
96
+ and `max_seqlen_Q`.
97
+
98
+ Other Parameters:
99
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
100
+
101
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to NATTEN's
102
+ attention operator, if any.
103
+
104
+ Returns:
105
+ output (Tensor): 4-D output tensor, with the heads-last contiguous layout
106
+ (`[batch, seqlen, heads, head_dim_v]`).
107
+
108
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
109
+ (`[batch, seqlen, heads, 1]`). Only returned when return_lse is True.
110
+ """
111
+
112
+ is_varlen = cumulative_seqlen_Q is not None
113
+ assert natten_attention_check(
114
+ query=query,
115
+ key=key,
116
+ value=value,
117
+ is_causal=is_causal,
118
+ causal_type=causal_type,
119
+ is_varlen=is_varlen,
120
+ raise_error=True,
121
+ )
122
+
123
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
124
+
125
+ backend_kwargs = backend_kwargs.copy() if backend_kwargs is not None else {}
126
+
127
+ natten_backend = None
128
+ if "backend" in backend_kwargs:
129
+ natten_backend = backend_kwargs["backend"]
130
+ del backend_kwargs["backend"]
131
+ else:
132
+ natten_backend = choose_natten_backend(
133
+ query, key, value, is_causal=is_causal, is_varlen=is_varlen, raise_error=True
134
+ )
135
+
136
+ assert natten_backend is not None
137
+
138
+ # Override NATTEN's default delta reduction method: using PyTorch
139
+ # is more accurate, but slightly slower.
140
+ # Only affects NATTEN's "cutlass-fmha" backend (Ampere kernels)
141
+ backward_use_pt_reduction = True
142
+ if "backward_use_pt_reduction" in backend_kwargs:
143
+ backward_use_pt_reduction = backend_kwargs["backward_use_pt_reduction"]
144
+ del backend_kwargs["backward_use_pt_reduction"]
145
+
146
+ return _natten_attention(
147
+ query=query,
148
+ key=key,
149
+ value=value,
150
+ is_causal=is_causal,
151
+ scale=scale,
152
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
153
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
154
+ max_seqlen_Q=max_seqlen_Q,
155
+ max_seqlen_KV=max_seqlen_KV,
156
+ return_lse=return_lse,
157
+ backend=natten_backend,
158
+ backward_use_pt_reduction=backward_use_pt_reduction,
159
+ **backend_kwargs,
160
+ )
161
+
162
+
163
+ def natten_multi_dim_attention(
164
+ query: Tensor,
165
+ key: Tensor,
166
+ value: Tensor,
167
+ window_size: tuple | int = -1,
168
+ stride: tuple | int = 1,
169
+ dilation: tuple | int = 1,
170
+ is_causal: tuple | bool = False,
171
+ scale: float | None = None,
172
+ return_lse: bool = False,
173
+ backend_kwargs: dict | None = None,
174
+ ) -> Tensor | tuple[Tensor, Tensor]:
175
+ """
176
+ Runs NATTEN's Multi-Dimensional Attention on given operands (Q, K, V) with the heads-last
177
+ contiguous layout (`[batch, *, heads, head_dim]`). Supports up to and including 3 dimensions:
178
+ * 1-D: `[batch, X, heads, head_dim]`, with masking arguments expecting tuples of size 1.
179
+ * 2-D: `[batch, X, Y, heads, head_dim]`, with masking arguments expecting tuples of size 2.
180
+ * 3-D: `[batch, X, Y, Z, heads, head_dim]`, with masking arguments expecting tuples of size 3.
181
+
182
+ Parameters:
183
+ query (Tensor): 4-D, 5-D, or 6-D query tensor, with the heads-last contiguous layout
184
+ (`[batch, *token_layout_shape, heads, head_dim]`)
185
+
186
+ key (Tensor): 4-D, 5-D, or 6-D key tensor, with the heads-last contiguous layout
187
+ (`[batch, *token_layout_shape, heads_kv, head_dim]`)
188
+
189
+ value (Tensor): 4-D, 5-D, or 6-D value tensor, with heads-last contiguous layout
190
+ (`[batch, *token_layout_shape, heads_kv, head_dim_v]`)
191
+
192
+ window_size (tuple | int): Attention window (kernel) size / shape. If an
193
+ integer, it will be repeated for all dimensions. For example `window_size=3`, when
194
+ `len(token_layout_shape) == 3`, is interpreted as `window_size=(3, 3, 3)`.
195
+ `-1`s are replaced with the corresponding `token_layout_shape`.
196
+ Final window size must satisfy `2 <= window_size <= token_layout_shape`.
197
+ Default is -1 (no sparsity).
198
+
199
+ stride (tuple | int): Sliding window step size/shape. If an integer, it will be repeated
200
+ for all dimensions. For example `stride=2`, when `len(token_layout_shape) == 3`, is
201
+ interpreted as `stride=(2, 2, 2)`.
202
+ Final stride must satisfy `1 <= stride <= window_size`.
203
+ Default is 1.
204
+
205
+ dilation (tuple | int): Dilation step size/shape. If an integer, it will be repeated for
206
+ all dimensions. For example `dilation=4`, when `len(token_layout_shape) == 3`, is
207
+ interpreted as `dilation=(4, 4, 4)`.
208
+ Final dilation must satisfy `2 <= dilation * window_size <= token_layout_shape`.
209
+ Default is 1.
210
+
211
+ is_causal (tuple | bool): Toggle causal masking. If a boolean, it will be repeated for all
212
+ dimensions. For example `is_causal=True`, when `len(token_layout_shape) == 3`, is
213
+ interpreted as `is_causal=(True, True, True)`.
214
+ Default is False.
215
+
216
+ scale (float | None): Dot product scale (attention scale). Defaults to head_dim ** -0.5.
217
+
218
+ Other Parameters:
219
+ return_lse (bool): Whether to return the logsumexp values. Default is False.
220
+
221
+ backend_kwargs (dict | None): Key-value pair for passing arguments specific to NATTEN's
222
+ multi-dim / sparse attention operator, if any.
223
+
224
+ Returns:
225
+ output (Tensor): 4-D, 5-D, or 6-D output tensor, with the heads-last contiguous layout
226
+ (`[batch, *token_layout_shape, heads, head_dim_v]`).
227
+
228
+ logsumexp (Tensor): logsumexp tensor, with the heads-last contiguous layout
229
+ (`[batch, *token_layout_shape, heads, 1]`). Only returned when return_lse is True.
230
+ """
231
+
232
+ assert natten_multi_dim_attention_check(
233
+ query=query,
234
+ key=key,
235
+ value=value,
236
+ raise_error=True,
237
+ )
238
+
239
+ token_layout, window_size, stride, dilation, is_causal = multi_dim_attention_param_filter(
240
+ query,
241
+ window_size=window_size,
242
+ stride=stride,
243
+ dilation=dilation,
244
+ is_causal=is_causal,
245
+ )
246
+
247
+ multi_dim_attention_param_checks(
248
+ query,
249
+ window_size=window_size,
250
+ stride=stride,
251
+ dilation=dilation,
252
+ is_causal=is_causal,
253
+ )
254
+
255
+ scale = scale if scale is not None else query.shape[-1] ** -0.5
256
+
257
+ backend_kwargs = backend_kwargs.copy() if backend_kwargs is not None else {}
258
+
259
+ natten_backend = None
260
+ if "backend" in backend_kwargs:
261
+ natten_backend = backend_kwargs["backend"]
262
+ del backend_kwargs["backend"]
263
+ else:
264
+ natten_backend = choose_natten_multi_dim_backend(query, key, value, raise_error=True)
265
+
266
+ assert natten_backend is not None
267
+
268
+ # Override NATTEN's default delta reduction method: using PyTorch
269
+ # is more accurate, but slightly slower.
270
+ # Only affects NATTEN's "cutlass-fmha" backend (Ampere kernels)
271
+ backward_use_pt_reduction = True
272
+ if "backward_use_pt_reduction" in backend_kwargs:
273
+ backward_use_pt_reduction = backend_kwargs["backward_use_pt_reduction"]
274
+ del backend_kwargs["backward_use_pt_reduction"]
275
+
276
+ output = _natten_multi_dim_attention(
277
+ query=query,
278
+ key=key,
279
+ value=value,
280
+ kernel_size=window_size,
281
+ stride=stride,
282
+ dilation=dilation,
283
+ is_causal=is_causal,
284
+ scale=scale,
285
+ backend=natten_backend,
286
+ backward_use_pt_reduction=backward_use_pt_reduction,
287
+ **backend_kwargs,
288
+ )
289
+
290
+ if return_lse:
291
+ raise NotImplementedError("NATTEN's Multi-Dimensional Attention does not support returning the logsumexp yet.")
292
+
293
+ return output
REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/meta.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ NATTEN Backend: metadata
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ import torch
25
+
26
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
27
+
28
+
29
+ def get_fwd_dtypes(arch_tag: int) -> list[torch.dtype]:
30
+ """
31
+ Returns data type choices for forward pass according to arch tag (attention.utils.get_arch_tag).
32
+
33
+ Parameters:
34
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
35
+
36
+ Returns:
37
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
38
+
39
+ """
40
+
41
+ if arch_tag < 75:
42
+ log.debug("NATTEN is not supported because compute capability is below the minimum (7.5).")
43
+ return []
44
+
45
+ if arch_tag in [100, 103]:
46
+ return [torch.float32, torch.float16, torch.bfloat16, torch.float8_e5m2, torch.float8_e4m3fn]
47
+
48
+ return [torch.float32, torch.float16, torch.bfloat16]
49
+
50
+
51
+ def get_bwd_dtypes(arch_tag: int) -> list[torch.dtype]:
52
+ """
53
+ Returns data type choices for backward pass according to arch tag (attention.utils.get_arch_tag).
54
+
55
+ Parameters:
56
+ arch_tag (int): Arch tag for the current CUDA device. Example: 80 for A100, 90 for H100.
57
+
58
+ Returns:
59
+ data_type_choices (list): a list of PyTorch data types. Empty if device is not supported.
60
+
61
+ """
62
+
63
+ if arch_tag < 75:
64
+ log.debug("NATTEN is not supported because compute capability is below the minimum (7.5).")
65
+ return []
66
+
67
+ return [torch.float32, torch.float16, torch.bfloat16]
REGEN-main/cosmos_policy/_src/imaginaire/attention/natten/stubs.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ NATTEN Backend: intermediate API stubs
21
+ Always safe to import (as long as torch is available.)
22
+ """
23
+
24
+ from torch import Tensor
25
+
26
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
27
+
28
+
29
+ def natten_attention(
30
+ query: Tensor,
31
+ key: Tensor,
32
+ value: Tensor,
33
+ is_causal: bool = False,
34
+ causal_type: CausalType | None = None,
35
+ scale: float | None = None,
36
+ cumulative_seqlen_Q: Tensor | None = None,
37
+ cumulative_seqlen_KV: Tensor | None = None,
38
+ max_seqlen_Q: int | None = None,
39
+ max_seqlen_KV: int | None = None,
40
+ return_lse: bool = False,
41
+ backend_kwargs: dict | None = None,
42
+ ) -> Tensor | tuple[Tensor, Tensor]:
43
+ raise RuntimeError(
44
+ "Tried to run NATTEN attention, but it is not supported / available. "
45
+ "Try running with debug logs enabled to see why."
46
+ )
47
+
48
+
49
+ def natten_multi_dim_attention(
50
+ query: Tensor,
51
+ key: Tensor,
52
+ value: Tensor,
53
+ window_size: tuple | int = -1,
54
+ stride: tuple | int = 1,
55
+ dilation: tuple | int = 1,
56
+ is_causal: tuple | bool = False,
57
+ scale: float | None = None,
58
+ return_lse: bool = False,
59
+ backend_kwargs: dict | None = None,
60
+ ) -> Tensor | tuple[Tensor, Tensor]:
61
+ raise RuntimeError(
62
+ "Tried to run NATTEN's Multi-Dimensional attention, but it is not supported / available. "
63
+ "Try running with debug logs enabled to see why."
64
+ )
REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/multi_dim_test.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Multi-Dimensional Attention unit tests.
21
+ """
22
+
23
+ import math
24
+ import random
25
+ import unittest
26
+ from functools import partial
27
+ from itertools import product
28
+ from typing import Callable
29
+
30
+ import pytest
31
+ import torch
32
+ from torch import Tensor
33
+
34
+ from cosmos_policy._src.imaginaire.attention import multi_dimensional_attention
35
+ from cosmos_policy._src.imaginaire.attention.natten import NATTEN_SUPPORTED
36
+ from cosmos_policy._src.imaginaire.attention.utils import is_blackwell_dc, is_fp8
37
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
38
+
39
+ RAND_SWEEP_TESTS = 1000
40
+
41
+ skip_if_natten_not_supported = partial(
42
+ pytest.mark.skipif,
43
+ not NATTEN_SUPPORTED,
44
+ reason="NATTEN is disabled, not available, or too old in this environment.",
45
+ )
46
+
47
+
48
+ def _reset_everything():
49
+ torch.manual_seed(42)
50
+ torch.cuda.empty_cache()
51
+
52
+
53
+ class MultiDimTester:
54
+ def __init__(
55
+ self,
56
+ reference_fn: Callable,
57
+ batch: int,
58
+ heads: int,
59
+ token_layout_shape: tuple,
60
+ head_dim: int,
61
+ window_size: tuple,
62
+ stride: tuple,
63
+ dilation: tuple,
64
+ is_causal: tuple,
65
+ test_backward: bool = True,
66
+ scale: float | None = None,
67
+ dtype: torch.dtype = torch.float32,
68
+ device: torch.device = "cuda",
69
+ heads_kv: int | None = None,
70
+ head_dim_v: int | None = None,
71
+ ):
72
+ self.batch = batch
73
+ self.heads = heads
74
+ self.heads_kv = heads_kv or heads
75
+ self.token_layout_shape = token_layout_shape
76
+ self.head_dim = head_dim
77
+ self.head_dim_v = head_dim_v or head_dim
78
+ self.test_backward = test_backward
79
+ self.scale = scale if scale is not None else head_dim**-0.5
80
+ self.dtype = dtype
81
+ self.device = device
82
+
83
+ self.window_size = window_size
84
+ self.stride = stride
85
+ self.dilation = dilation
86
+ self.is_causal = is_causal
87
+
88
+ # Initialize input tensors
89
+ self.q = torch.randn(
90
+ self.batch,
91
+ *self.token_layout_shape,
92
+ self.heads,
93
+ self.head_dim,
94
+ dtype=dtype,
95
+ device=device,
96
+ requires_grad=test_backward,
97
+ )
98
+ self.k = torch.randn(
99
+ self.batch,
100
+ *self.token_layout_shape,
101
+ self.heads_kv,
102
+ self.head_dim,
103
+ dtype=dtype,
104
+ device=device,
105
+ requires_grad=test_backward,
106
+ )
107
+ self.v = torch.randn(
108
+ self.batch,
109
+ *self.token_layout_shape,
110
+ self.heads_kv,
111
+ self.head_dim_v,
112
+ dtype=dtype,
113
+ device=device,
114
+ requires_grad=test_backward,
115
+ )
116
+ self.d_output = (
117
+ torch.randn(self.batch, *self.token_layout_shape, self.heads, self.head_dim_v, dtype=dtype, device=device)
118
+ if test_backward
119
+ else None
120
+ )
121
+
122
+ # Run reference implementation
123
+ q_ref = self.q.clone().detach().requires_grad_(self.test_backward)
124
+ k_ref = self.k.clone().detach().requires_grad_(self.test_backward)
125
+ v_ref = self.v.clone().detach().requires_grad_(self.test_backward)
126
+
127
+ output_ref = reference_fn(
128
+ query=q_ref,
129
+ key=k_ref,
130
+ value=v_ref,
131
+ scale=self.scale,
132
+ window_size=self.window_size,
133
+ stride=self.stride,
134
+ dilation=self.dilation,
135
+ is_causal=self.is_causal,
136
+ )
137
+
138
+ self.output_ref = output_ref.detach().to(torch.float32)
139
+
140
+ # Reference backward pass
141
+ if self.test_backward:
142
+ d_output = self.d_output.clone().detach()
143
+ output_ref.backward(d_output)
144
+ self.dq_ref = q_ref.grad.detach().to(torch.float32)
145
+ self.dk_ref = k_ref.grad.detach().to(torch.float32)
146
+ self.dv_ref = v_ref.grad.detach().to(torch.float32)
147
+
148
+ def test(
149
+ self,
150
+ target_fn: Callable,
151
+ dtype: torch.dtype,
152
+ atol_fwd: float,
153
+ atol_bwd: tuple[float, float, float] | None = None,
154
+ rtol_fwd: float = 0.0,
155
+ rtol_bwd: float = 0.0,
156
+ test_backward: bool | None = None,
157
+ ):
158
+ test_backward = self.test_backward if test_backward is None else test_backward
159
+
160
+ q = self.q.clone().detach().to(dtype).requires_grad_(test_backward)
161
+ k = self.k.clone().detach().to(dtype).requires_grad_(test_backward)
162
+ v = self.v.clone().detach().to(dtype).requires_grad_(test_backward)
163
+
164
+ output = target_fn(
165
+ query=q,
166
+ key=k,
167
+ value=v,
168
+ scale=self.scale,
169
+ window_size=self.window_size,
170
+ stride=self.stride,
171
+ dilation=self.dilation,
172
+ is_causal=self.is_causal,
173
+ )
174
+
175
+ torch.testing.assert_close(output.to(torch.float32), self.output_ref, atol=atol_fwd, rtol=rtol_fwd)
176
+
177
+ # Backward pass
178
+ if test_backward:
179
+ assert atol_bwd is not None
180
+ assert rtol_bwd is not None
181
+ atol_dq, atol_dk, atol_dv = atol_bwd
182
+
183
+ d_output = self.d_output.clone().detach().to(dtype)
184
+ output.backward(d_output)
185
+
186
+ dq = q.grad.detach().to(torch.float32)
187
+ dk = k.grad.detach().to(torch.float32)
188
+ dv = v.grad.detach().to(torch.float32)
189
+
190
+ torch.testing.assert_close(dq, self.dq_ref, atol=atol_dq, rtol=rtol_bwd)
191
+ torch.testing.assert_close(dk, self.dk_ref, atol=atol_dk, rtol=rtol_bwd)
192
+ torch.testing.assert_close(dv, self.dv_ref, atol=atol_dv, rtol=rtol_bwd)
193
+
194
+
195
+ def idx2crd(index, shape) -> tuple:
196
+ rank = len(shape)
197
+ coord = []
198
+ residual = index
199
+ for i in range(rank - 1, -1, -1):
200
+ coord.append(residual % shape[i])
201
+ residual = residual // shape[i]
202
+
203
+ # assert residual == 0
204
+ return tuple(coord[::-1])
205
+
206
+
207
+ def multi_dim_mask(
208
+ q_idx: int,
209
+ kv_idx: int,
210
+ token_layout_shape: tuple,
211
+ window_size: tuple,
212
+ stride: tuple,
213
+ dilation: tuple,
214
+ is_causal: tuple,
215
+ ) -> bool:
216
+ assert len(token_layout_shape) == len(window_size) == len(stride) == len(dilation) == len(is_causal)
217
+
218
+ # Reconstruct global Q and KV coordinates
219
+ q_crd = idx2crd(q_idx, token_layout_shape)
220
+ kv_crd = idx2crd(kv_idx, token_layout_shape)
221
+
222
+ masks = []
223
+ for q, kv, x, w, s, d, c in zip(q_crd, kv_crd, token_layout_shape, window_size, stride, dilation, is_causal):
224
+ # Coordinates within dilation group
225
+ q_crd_di = q // d
226
+ kv_crd_di = kv // d
227
+
228
+ # Dilation group coordinates
229
+ q_dilation_group_crd = q % d
230
+ kv_dilation_group_crd = kv % d
231
+
232
+ # Fixup input shape according to dilation group
233
+ dilation_group_padding = 1 - ((q_dilation_group_crd + (d - (x % d))) // d)
234
+ qkv_shape_corrected = (x // d) + dilation_group_padding
235
+
236
+ if c:
237
+ # Leader is the last (right-most) query in the stride group.
238
+ stride_group_leader = min(
239
+ (q_crd_di // s) * s + s - 1,
240
+ qkv_shape_corrected - 1,
241
+ )
242
+
243
+ if not (
244
+ (q_crd_di - kv_crd_di >= 0) # window still ends at query index
245
+ and (stride_group_leader - kv_crd_di < w)
246
+ and (q_dilation_group_crd == kv_dilation_group_crd)
247
+ ):
248
+ return False
249
+
250
+ else:
251
+ # Window size left and right (non-causal only)
252
+ window_size_left = w // 2
253
+ window_size_right = w // 2 + (w % 2 - 1)
254
+
255
+ # Leader is the center-most query in the stride group.
256
+ # If stride is even, choose the right hand side center query.
257
+ stride_group_leader = min(
258
+ (q_crd_di // s) * s + (s // 2),
259
+ qkv_shape_corrected - 1,
260
+ )
261
+
262
+ window_center = min(max(stride_group_leader, window_size_left), qkv_shape_corrected - 1 - window_size_right)
263
+ w0 = window_center - kv_crd_di
264
+ w1 = kv_crd_di - window_center
265
+ if not (
266
+ (((0 <= w0) and (w0 <= window_size_left)) or ((0 <= w1) and (w1 <= window_size_right)))
267
+ and (q_dilation_group_crd == kv_dilation_group_crd)
268
+ ):
269
+ return False
270
+
271
+ return True
272
+
273
+
274
+ def multi_dim_reference(
275
+ query: Tensor,
276
+ key: Tensor,
277
+ value: Tensor,
278
+ window_size: tuple,
279
+ stride: tuple,
280
+ dilation: tuple,
281
+ is_causal: tuple,
282
+ scale: float,
283
+ ):
284
+ assert query.dim() in [4, 5, 6]
285
+ B, *token_layout_shape, H, D = query.shape
286
+ H_kv, _ = key.shape[-2:]
287
+ D_v = value.shape[-1]
288
+ seqlen = math.prod(token_layout_shape)
289
+
290
+ # cast from torch shape to tuple
291
+ token_layout_shape = tuple(x for x in token_layout_shape)
292
+
293
+ num_dims = len(token_layout_shape)
294
+
295
+ assert H % H_kv == 0
296
+ h_k = H // H_kv
297
+
298
+ query_t = query.flatten(1, num_dims).transpose(1, 2)
299
+ key_t = key.flatten(1, num_dims).transpose(1, 2)
300
+ value_t = value.flatten(1, num_dims).transpose(1, 2)
301
+
302
+ assert query_t.dim() == key_t.dim() == value_t.dim() == 4
303
+ assert query_t.shape[2] == key_t.shape[2] == value_t.shape[2] == seqlen
304
+
305
+ # Decomposed GQA/MQA implementation
306
+ if h_k > 1:
307
+ key_t = torch.repeat_interleave(key_t, repeats=h_k, dim=1, output_size=H)
308
+ value_t = torch.repeat_interleave(value_t, repeats=h_k, dim=1, output_size=H)
309
+
310
+ attn_scores = torch.matmul(query_t, key_t.transpose(-2, -1)) * scale
311
+
312
+ mask = torch.zeros((seqlen, seqlen), dtype=torch.bool)
313
+ is_valid = partial(
314
+ multi_dim_mask,
315
+ token_layout_shape=token_layout_shape,
316
+ window_size=window_size,
317
+ stride=stride,
318
+ dilation=dilation,
319
+ is_causal=is_causal,
320
+ )
321
+ for q, kv in product(range(mask.shape[0]), range(mask.shape[1])):
322
+ mask[q, kv] = not is_valid(q, kv)
323
+
324
+ mask_cu = mask.unsqueeze(0).unsqueeze(0).to(attn_scores.device)
325
+ attn_scores = attn_scores.masked_fill(mask_cu, float("-inf"))
326
+
327
+ attn_weights = attn_scores.softmax(dim=-1)
328
+
329
+ out = torch.matmul(attn_weights, value_t)
330
+
331
+ out = out.transpose(1, 2)
332
+
333
+ out = out.reshape(B, *token_layout_shape, H, D_v)
334
+
335
+ return out
336
+
337
+
338
+ class MultiDimTest(unittest.TestCase):
339
+ def setUp(self):
340
+ _reset_everything()
341
+
342
+ def tearDown(self):
343
+ _reset_everything()
344
+
345
+ def _test_against_bmm_reference(
346
+ self,
347
+ batch: int,
348
+ heads: int,
349
+ token_layout_shape: tuple,
350
+ head_dim: int,
351
+ window_size: tuple,
352
+ stride: tuple,
353
+ dilation: tuple,
354
+ is_causal: tuple,
355
+ test_backward: bool,
356
+ backend: str,
357
+ scale: float | None = None,
358
+ heads_kv: int | None = None,
359
+ head_dim_v: int | None = None,
360
+ ):
361
+ reference_dtype = torch.float16
362
+ device = "cuda"
363
+ attention_fn = partial(multi_dimensional_attention, backend=backend)
364
+
365
+ log.debug(
366
+ "Running reference Multi-Dimensional Attention on: "
367
+ f"{batch=}, {heads=}, {heads_kv=}, {head_dim=}, {head_dim_v=}, "
368
+ f"{token_layout_shape=}, {window_size=}, {stride=}, {dilation=}, {is_causal=}."
369
+ )
370
+ tester = MultiDimTester(
371
+ reference_fn=multi_dim_reference,
372
+ batch=batch,
373
+ heads=heads,
374
+ heads_kv=heads_kv,
375
+ token_layout_shape=token_layout_shape,
376
+ head_dim=head_dim,
377
+ head_dim_v=head_dim_v,
378
+ window_size=window_size,
379
+ stride=stride,
380
+ dilation=dilation,
381
+ is_causal=is_causal,
382
+ dtype=reference_dtype,
383
+ test_backward=test_backward,
384
+ scale=scale,
385
+ device=device,
386
+ )
387
+
388
+ ALLOWED_DTYPES = [
389
+ # dtype, atol_out, (atol_dq, atol_dk, atol_dv), rtol_fwd, rtol_bwd
390
+ (torch.float16, 1e-2, (4e-2, 4e-2, 4e-2), 0, 0),
391
+ (torch.bfloat16, 1e-1, (2e-1, 2e-1, 2e-1), 0, 0),
392
+ ]
393
+ if backend == "natten" and is_blackwell_dc():
394
+ ALLOWED_DTYPES += [
395
+ (torch.float8_e4m3fn, 4e-1, None, 1e-1, 0),
396
+ (torch.float8_e5m2, 8e-1, None, 5e-1, 0),
397
+ ]
398
+
399
+ for dtype, atol_fwd, atol_bwd, rtol_fwd, rtol_bwd in ALLOWED_DTYPES:
400
+ test_backward_ = test_backward and not is_fp8(dtype)
401
+ log.debug(
402
+ f"Testing Multi-Dimensional Attention ({backend}): {batch=}, {heads=}, {heads_kv=}, {head_dim=}, {head_dim_v=}, "
403
+ f"{token_layout_shape=}, {window_size=}, {stride=}, {dilation=}, "
404
+ f"{is_causal=}, {dtype=}, {test_backward_=}."
405
+ )
406
+ tester.test(
407
+ target_fn=attention_fn,
408
+ dtype=dtype,
409
+ atol_fwd=atol_fwd,
410
+ atol_bwd=atol_bwd,
411
+ rtol_fwd=rtol_fwd,
412
+ rtol_bwd=rtol_bwd,
413
+ test_backward=test_backward_,
414
+ )
415
+
416
+ def _test_randsweep(self, num_dims: int, backend: str, max_tests: int = 1000, max_seqlen: int = 2**17):
417
+ random.seed(42)
418
+
419
+ for i in range(max_tests):
420
+ batch = random.choice(range(1, 2))
421
+
422
+ supports_mla = False
423
+ supports_gqa_mqa = False
424
+ if backend == "natten":
425
+ head_dim_choices = [32, 64, 128]
426
+ heads_choices = range(1, 4 + 1)
427
+ # GQA/MQA is not supported in FNA ops yet
428
+ supports_gqa_mqa = False
429
+
430
+ # Enable MLA when supported in hopper or blackwell
431
+ head_dim = random.choice(head_dim_choices)
432
+ head_dim_v = None
433
+ # head_dim_v = random.choice(head_dim_choices)
434
+
435
+ else:
436
+ raise NotImplementedError()
437
+
438
+ heads = random.choice(heads_choices)
439
+ heads_kv = (
440
+ heads
441
+ if not supports_gqa_mqa
442
+ else random.choice([1] + [i for i in range(1, heads + 1) if heads % i == 0])
443
+ )
444
+ assert heads >= heads_kv and heads % heads_kv == 0
445
+
446
+ token_layout_shape = []
447
+ for j in range(num_dims):
448
+ max_size = (
449
+ min(max_seqlen, 16384)
450
+ if j == 0
451
+ else min(16384, max(10, max_seqlen - math.prod(token_layout_shape)))
452
+ )
453
+ token_layout_shape.append(random.choice(range(4, max_size)))
454
+
455
+ while math.prod(token_layout_shape) > max_seqlen:
456
+ dim_to_cut = random.choice(range(num_dims))
457
+ token_layout_shape[dim_to_cut] = max(4, int(token_layout_shape[dim_to_cut] * 0.1))
458
+
459
+ token_layout_shape = tuple(token_layout_shape)
460
+ window_size = tuple(random.choice(range(2, x + 1)) for x in token_layout_shape)
461
+ stride = tuple(random.choice(range(1, k + 1)) for k in window_size)
462
+ dilation = tuple(random.choice(range(1, x // k + 1)) for x, k in zip(token_layout_shape, window_size))
463
+ is_causal = tuple(random.choice([False, True]) for _ in range(num_dims))
464
+
465
+ self._test_against_bmm_reference(
466
+ batch=batch,
467
+ heads=heads,
468
+ heads_kv=heads_kv,
469
+ head_dim=head_dim,
470
+ head_dim_v=head_dim_v,
471
+ token_layout_shape=token_layout_shape,
472
+ window_size=window_size,
473
+ stride=stride,
474
+ dilation=dilation,
475
+ is_causal=is_causal,
476
+ backend=backend,
477
+ test_backward=True,
478
+ )
479
+
480
+ @pytest.mark.L1
481
+ @skip_if_natten_not_supported()
482
+ def test_natten_fast(self):
483
+ random.seed(83)
484
+ torch.manual_seed(83)
485
+ self._test_randsweep(num_dims=1, backend="natten", max_tests=10, max_seqlen=2**10)
486
+ self._test_randsweep(num_dims=2, backend="natten", max_tests=10, max_seqlen=2**10)
487
+ self._test_randsweep(num_dims=3, backend="natten", max_tests=10, max_seqlen=2**10)
488
+
489
+ @pytest.mark.L1
490
+ @pytest.mark.skip("Extended rand sweep is disabled until we have a faster reference for multi-dim")
491
+ @skip_if_natten_not_supported()
492
+ def test_natten_randsweep(self):
493
+ random.seed(84)
494
+ torch.manual_seed(84)
495
+ self._test_randsweep(num_dims=1, backend="natten", max_tests=RAND_SWEEP_TESTS // 3, max_seqlen=2**11)
496
+ self._test_randsweep(num_dims=2, backend="natten", max_tests=RAND_SWEEP_TESTS // 3, max_seqlen=2**11)
497
+ self._test_randsweep(num_dims=3, backend="natten", max_tests=RAND_SWEEP_TESTS // 3, max_seqlen=2**11)
498
+
499
+
500
+ if __name__ == "__main__":
501
+ random.seed(42)
502
+ torch.manual_seed(42)
503
+ unittest.main()
REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/sdpa_test.py ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ SDPA unit tests.
21
+ """
22
+
23
+ import random
24
+ import unittest
25
+ from functools import partial
26
+ from typing import Callable
27
+
28
+ import pytest
29
+ import torch
30
+ from torch import Tensor
31
+
32
+ from cosmos_policy._src.imaginaire.attention import attention as i4_attention
33
+ from cosmos_policy._src.imaginaire.attention.cudnn import CUDNN_DISALLOWED, CUDNN_SUPPORTED
34
+ from cosmos_policy._src.imaginaire.attention.flash2 import FLASH2_SUPPORTED
35
+ from cosmos_policy._src.imaginaire.attention.flash3 import FLASH3_SUPPORTED
36
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
37
+ from cosmos_policy._src.imaginaire.attention.natten import NATTEN_SUPPORTED
38
+ from cosmos_policy._src.imaginaire.attention.utils import is_blackwell_dc, is_fp8, is_hopper
39
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
40
+
41
+ RAND_SWEEP_TESTS = 1000
42
+
43
+ skip_if_cudnn_not_supported = partial(
44
+ pytest.mark.skipif,
45
+ CUDNN_DISALLOWED or not CUDNN_SUPPORTED,
46
+ reason="cuDNN is disabled, not available, or too old in this environment.",
47
+ )
48
+
49
+ skip_if_natten_not_supported = partial(
50
+ pytest.mark.skipif,
51
+ not NATTEN_SUPPORTED,
52
+ reason="NATTEN is disabled, not available, or too old in this environment.",
53
+ )
54
+
55
+ skip_if_flash2_not_supported = partial(
56
+ pytest.mark.skipif,
57
+ not FLASH2_SUPPORTED,
58
+ reason="Flash2 is disabled, not available, or too old in this environment.",
59
+ )
60
+
61
+ skip_if_flash3_not_supported = partial(
62
+ pytest.mark.skipif,
63
+ not FLASH3_SUPPORTED,
64
+ reason="Flash3 is disabled, not available, or too old in this environment.",
65
+ )
66
+
67
+ # Tests are only enabled on Hopper and Blackwell DC-class for now.
68
+ # Will extend to other arches as we integrate more backends.
69
+ skip_if_not_supported = partial(
70
+ pytest.mark.skipif,
71
+ not is_blackwell_dc() and not is_hopper(),
72
+ reason="SDPA tests are only allowed for Hopper and Blackwell DC-class GPUs for now.",
73
+ )
74
+
75
+ skip_if_not_blackwell = partial(
76
+ pytest.mark.skipif, not is_blackwell_dc(), reason="This test is only allowed for Blackwell DC-class GPUs."
77
+ )
78
+
79
+ skip_if_not_hopper = partial(pytest.mark.skipif, not is_hopper(), reason="This test is only allowed for Hopper GPUs.")
80
+
81
+
82
+ def _reset_everything():
83
+ torch.manual_seed(42)
84
+ torch.cuda.empty_cache()
85
+
86
+
87
+ class SdpaTester:
88
+ def __init__(
89
+ self,
90
+ reference_fn: Callable,
91
+ batch: int,
92
+ heads: int,
93
+ seqlen_q: int,
94
+ seqlen_kv: int,
95
+ head_dim: int,
96
+ test_backward: bool = True,
97
+ scale: float | None = None,
98
+ is_causal: bool = False,
99
+ causal_type: CausalType | None = None,
100
+ dtype: torch.dtype = torch.float32,
101
+ device: torch.device = "cuda",
102
+ heads_kv: int | None = None,
103
+ head_dim_v: int | None = None,
104
+ ):
105
+ self.batch = batch
106
+ self.heads = heads
107
+ self.heads_kv = heads_kv or heads
108
+ self.seqlen_q = seqlen_q
109
+ self.seqlen_kv = seqlen_kv
110
+ self.head_dim = head_dim
111
+ self.head_dim_v = head_dim_v or head_dim
112
+ self.test_backward = test_backward
113
+ self.scale = scale if scale is not None else head_dim**-0.5
114
+ self.is_causal = is_causal
115
+ self.causal_type = causal_type
116
+ self.dtype = dtype
117
+ self.device = device
118
+
119
+ # Initialize input tensors
120
+ self.q = torch.randn(
121
+ self.batch,
122
+ self.seqlen_q,
123
+ self.heads,
124
+ self.head_dim,
125
+ dtype=dtype,
126
+ device=device,
127
+ requires_grad=test_backward,
128
+ )
129
+ self.k = torch.randn(
130
+ self.batch,
131
+ self.seqlen_kv,
132
+ self.heads_kv,
133
+ self.head_dim,
134
+ dtype=dtype,
135
+ device=device,
136
+ requires_grad=test_backward,
137
+ )
138
+ self.v = torch.randn(
139
+ self.batch,
140
+ self.seqlen_kv,
141
+ self.heads_kv,
142
+ self.head_dim_v,
143
+ dtype=dtype,
144
+ device=device,
145
+ requires_grad=test_backward,
146
+ )
147
+ self.d_output = (
148
+ torch.randn(self.batch, self.seqlen_q, self.heads, self.head_dim_v, dtype=dtype, device=device)
149
+ if test_backward
150
+ else None
151
+ )
152
+
153
+ # Run reference implementation
154
+ q_ref = self.q.clone().detach().requires_grad_(self.test_backward)
155
+ k_ref = self.k.clone().detach().requires_grad_(self.test_backward)
156
+ v_ref = self.v.clone().detach().requires_grad_(self.test_backward)
157
+
158
+ output_ref = reference_fn(
159
+ query=q_ref,
160
+ key=k_ref,
161
+ value=v_ref,
162
+ scale=self.scale,
163
+ is_causal=self.is_causal,
164
+ causal_type=self.causal_type,
165
+ )
166
+
167
+ self.output_ref = output_ref.detach().to(torch.float32)
168
+
169
+ # Reference backward pass
170
+ if self.test_backward:
171
+ d_output = self.d_output.clone().detach()
172
+ output_ref.backward(d_output)
173
+ self.dq_ref = q_ref.grad.detach().to(torch.float32)
174
+ self.dk_ref = k_ref.grad.detach().to(torch.float32)
175
+ self.dv_ref = v_ref.grad.detach().to(torch.float32)
176
+
177
+ def test(
178
+ self,
179
+ target_fn: Callable,
180
+ dtype: torch.dtype,
181
+ atol_fwd: float,
182
+ atol_bwd: tuple[float, float, float] | None = None,
183
+ rtol_fwd: float = 0.0,
184
+ rtol_bwd: float = 0.0,
185
+ test_backward: bool | None = None,
186
+ ):
187
+ test_backward = self.test_backward if test_backward is None else test_backward
188
+
189
+ q = self.q.clone().detach().to(dtype).requires_grad_(test_backward)
190
+ k = self.k.clone().detach().to(dtype).requires_grad_(test_backward)
191
+ v = self.v.clone().detach().to(dtype).requires_grad_(test_backward)
192
+
193
+ output = target_fn(
194
+ query=q, key=k, value=v, scale=self.scale, is_causal=self.is_causal, causal_type=self.causal_type
195
+ )
196
+
197
+ torch.testing.assert_close(output.to(torch.float32), self.output_ref, atol=atol_fwd, rtol=rtol_fwd)
198
+
199
+ # Backward pass
200
+ if test_backward:
201
+ assert atol_bwd is not None
202
+ assert rtol_bwd is not None
203
+ atol_dq, atol_dk, atol_dv = atol_bwd
204
+
205
+ d_output = self.d_output.clone().detach().to(dtype)
206
+ output.backward(d_output)
207
+
208
+ dq = q.grad.detach().to(torch.float32)
209
+ dk = k.grad.detach().to(torch.float32)
210
+ dv = v.grad.detach().to(torch.float32)
211
+
212
+ torch.testing.assert_close(dq, self.dq_ref, atol=atol_dq, rtol=rtol_bwd)
213
+ torch.testing.assert_close(dk, self.dk_ref, atol=atol_dk, rtol=rtol_bwd)
214
+ torch.testing.assert_close(dv, self.dv_ref, atol=atol_dv, rtol=rtol_bwd)
215
+
216
+
217
+ def torch_sdpa_reference(
218
+ query: Tensor,
219
+ key: Tensor,
220
+ value: Tensor,
221
+ scale: float,
222
+ is_causal: bool,
223
+ causal_type: CausalType,
224
+ ):
225
+ heads = query.shape[2]
226
+ heads_kv = key.shape[2]
227
+ assert heads % heads_kv == 0
228
+ h_k = heads // heads_kv
229
+
230
+ assert not is_causal or causal_type == CausalType.TopLeft, "Torch SDPA only supports top-left causal mask."
231
+
232
+ # Torch requires heads-first layout
233
+ query = query.permute(0, 2, 1, 3).contiguous()
234
+ key = key.permute(0, 2, 1, 3).contiguous()
235
+ value = value.permute(0, 2, 1, 3).contiguous()
236
+
237
+ k_final, v_final = key, value
238
+ # Decomposed GQA/MQA implementation for torch SDPA via explicit repeats
239
+ if h_k > 1:
240
+ k_final = torch.repeat_interleave(key, repeats=h_k, dim=1, output_size=heads)
241
+ v_final = torch.repeat_interleave(value, repeats=h_k, dim=1, output_size=heads)
242
+
243
+ assert k_final.shape[:2] == query.shape[:2]
244
+ assert v_final.shape[:2] == query.shape[:2]
245
+ assert k_final.shape[-1] == query.shape[-1]
246
+ assert v_final.shape[-1] == query.shape[-1]
247
+
248
+ with torch.nn.attention.sdpa_kernel(backends=[torch.nn.attention.SDPBackend.EFFICIENT_ATTENTION]):
249
+ out = torch.nn.functional.scaled_dot_product_attention(
250
+ query, k_final, v_final, is_causal=is_causal, scale=scale
251
+ )
252
+
253
+ out = out.permute(0, 2, 1, 3).contiguous()
254
+ return out
255
+
256
+
257
+ # NOTE: Use ONLY when seqlen_{q,kv} are small!
258
+ # Supports MLA and bottom-right causal mask, unlike SDPA
259
+ def bmm_sdpa_reference(
260
+ query: Tensor,
261
+ key: Tensor,
262
+ value: Tensor,
263
+ scale: float,
264
+ is_causal: bool,
265
+ causal_type: CausalType,
266
+ MAX_QK: int = 16384**2,
267
+ ):
268
+ B, S_q, H, D = query.shape
269
+ _, S_kv, H_kv, _ = key.shape
270
+
271
+ assert H % H_kv == 0
272
+ h_k = H // H_kv
273
+
274
+ if S_q * S_kv > MAX_QK:
275
+ raise ValueError(f"Query-key matmul too large: {S_q}*{S_kv} > MAX_QK={MAX_QK}")
276
+
277
+ query_t = query.transpose(1, 2)
278
+ key_t = key.transpose(1, 2)
279
+ value_t = value.transpose(1, 2)
280
+
281
+ # Decomposed GQA/MQA implementation
282
+ if h_k > 1:
283
+ key_t = torch.repeat_interleave(key_t, repeats=h_k, dim=1, output_size=H)
284
+ value_t = torch.repeat_interleave(value_t, repeats=h_k, dim=1, output_size=H)
285
+
286
+ attn_scores = torch.matmul(query_t, key_t.transpose(-2, -1)) * scale
287
+
288
+ if is_causal:
289
+ if causal_type == CausalType.TopLeft:
290
+ diagonal_offset = 1
291
+ elif causal_type == CausalType.BottomRight:
292
+ diagonal_offset = S_kv - S_q + 1
293
+ else:
294
+ raise NotImplementedError()
295
+ mask = torch.triu(torch.ones(S_q, S_kv, device=query.device, dtype=torch.bool), diagonal=diagonal_offset)
296
+ attn_scores = attn_scores.masked_fill(mask, float("-inf"))
297
+
298
+ attn_weights = attn_scores.softmax(dim=-1)
299
+
300
+ # We can have entirely masked rows (queries) with this mask
301
+ if causal_type == CausalType.BottomRight:
302
+ attn_weights = torch.nan_to_num(attn_weights, nan=0.0)
303
+
304
+ out = torch.matmul(attn_weights, value_t)
305
+
306
+ out = out.transpose(1, 2)
307
+
308
+ return out
309
+
310
+
311
+ class SdpaTest(unittest.TestCase):
312
+ def setUp(self):
313
+ _reset_everything()
314
+
315
+ def tearDown(self):
316
+ _reset_everything()
317
+
318
+ def _test_against_torch_sdpa(
319
+ self,
320
+ batch: int,
321
+ heads: int,
322
+ head_dim: int,
323
+ seqlen_q: int,
324
+ seqlen_kv: int,
325
+ is_causal: bool,
326
+ causal_type: CausalType,
327
+ test_backward: bool,
328
+ backend: str,
329
+ scale: float | None = None,
330
+ heads_kv: int | None = None,
331
+ head_dim_v: int | None = None,
332
+ ):
333
+ reference_dtype = torch.float16
334
+ device = "cuda"
335
+ attention_fn = partial(i4_attention, backend=backend)
336
+
337
+ reference_fn = torch_sdpa_reference
338
+ if (is_causal and causal_type == CausalType.BottomRight) or (head_dim_v is not None and head_dim_v != head_dim):
339
+ reference_fn = bmm_sdpa_reference
340
+
341
+ tester = SdpaTester(
342
+ reference_fn=reference_fn,
343
+ batch=batch,
344
+ heads=heads,
345
+ heads_kv=heads_kv,
346
+ head_dim=head_dim,
347
+ head_dim_v=head_dim_v,
348
+ seqlen_q=seqlen_q,
349
+ seqlen_kv=seqlen_kv,
350
+ dtype=reference_dtype,
351
+ test_backward=test_backward,
352
+ scale=scale,
353
+ is_causal=is_causal,
354
+ causal_type=causal_type,
355
+ device=device,
356
+ )
357
+
358
+ ALLOWED_DTYPES = [
359
+ # dtype, atol_out, (atol_dq, atol_dk, atol_dv), rtol_fwd, rtol_bwd
360
+ (torch.float16, 1e-2, (4e-2, 4e-2, 4e-2), 0, 0),
361
+ (torch.bfloat16, 1e-1, (2e-1, 2e-1, 2e-1), 0, 0),
362
+ ]
363
+ if backend == "natten" and is_blackwell_dc():
364
+ ALLOWED_DTYPES += [
365
+ (torch.float8_e4m3fn, 4e-1, None, 1e-1, 0),
366
+ (torch.float8_e5m2, 8e-1, None, 5e-1, 0),
367
+ ]
368
+
369
+ for dtype, atol_fwd, atol_bwd, rtol_fwd, rtol_bwd in ALLOWED_DTYPES:
370
+ test_backward_ = test_backward and not is_fp8(dtype)
371
+ log.debug(
372
+ f"Testing SDPA ({backend}) vs torch SDPA: {batch=}, {heads=}, {heads_kv=}, {head_dim=}, {head_dim_v=}, "
373
+ f"{seqlen_q=}, {seqlen_kv=}, {is_causal=}, {causal_type=}, {dtype=}, {test_backward_=}"
374
+ )
375
+ tester.test(
376
+ target_fn=attention_fn,
377
+ dtype=dtype,
378
+ atol_fwd=atol_fwd,
379
+ atol_bwd=atol_bwd,
380
+ rtol_fwd=rtol_fwd,
381
+ rtol_bwd=rtol_bwd,
382
+ test_backward=test_backward_,
383
+ )
384
+
385
+ def _test_backend_against_torch_sdpa(
386
+ self,
387
+ batch: int,
388
+ heads: int,
389
+ head_dim: int,
390
+ seqlen_q: int,
391
+ seqlen_kv: int,
392
+ is_causal: bool,
393
+ backend: str,
394
+ scale: float | None = None,
395
+ heads_kv: int | None = None,
396
+ head_dim_v: int | None = None,
397
+ ):
398
+ assert backend in ["natten", "flash2", "flash3", "cudnn"]
399
+ self._test_against_torch_sdpa(
400
+ batch=batch,
401
+ heads=heads,
402
+ heads_kv=heads_kv,
403
+ head_dim=head_dim,
404
+ head_dim_v=head_dim_v,
405
+ seqlen_q=seqlen_q,
406
+ seqlen_kv=seqlen_kv,
407
+ is_causal=is_causal,
408
+ causal_type=CausalType.TopLeft if backend not in ["flash2", "flash3"] else CausalType.BottomRight,
409
+ scale=scale,
410
+ test_backward=backend != "cudnn",
411
+ backend=backend,
412
+ )
413
+
414
+ def _test_randsweep_against_torch_sdpa(self, backend: str, max_tests: int = 1000):
415
+ random.seed(42)
416
+
417
+ max_qk = 2**21
418
+ for i in range(max_tests):
419
+ batch = random.choice(range(1, 4))
420
+
421
+ supports_mla = False
422
+ supports_gqa_mqa = False
423
+ if backend == "natten":
424
+ head_dim_choices = [32, 64, 128]
425
+ heads_choices = range(1, 8 + 1)
426
+ # GQA/MQA is only supported in NATTEN's Blackwell FMHA backend for now
427
+ supports_gqa_mqa = is_blackwell_dc()
428
+
429
+ # Enable MLA when supported in hopper or blackwell
430
+ head_dim = random.choice(head_dim_choices)
431
+ head_dim_v = None
432
+ # head_dim_v = random.choice(head_dim_choices)
433
+
434
+ elif backend in ["flash2", "flash3"]:
435
+ head_dim_choices = range(16, 256 + 1, 8)
436
+ heads_choices = range(1, 8 + 1)
437
+ supports_gqa_mqa = True
438
+
439
+ # NOTE: Flash 3 MLA fails a static check in bwd, seems like an FA bug
440
+ ## Flash 3 supports MLA, but with some extra constraints
441
+ # if backend == "flash3" and random.choice([True, False]):
442
+ # # Either head_dim_qk <= 64 and head_dim_v <= 512, or
443
+ # # 128 <= head_dim_qk <= 192 and 96 <= head_dim_v <= 128
444
+ # if random.choice([True, False]):
445
+ # head_dim = random.choice(range(16, 64 + 1, 8))
446
+ # head_dim_v = random.choice(head_dim_choices)
447
+ # else:
448
+ # head_dim = random.choice(range(128, 192 + 1, 8))
449
+ # head_dim_v = random.choice(range(96, 128 + 1, 8))
450
+
451
+ # else:
452
+ head_dim = random.choice(head_dim_choices)
453
+ head_dim_v = None
454
+
455
+ elif backend == "cudnn":
456
+ head_dim_choices = [32, 64, 128]
457
+ heads_choices = range(1, 4)
458
+
459
+ # Enable MLA when verified
460
+ head_dim = random.choice(head_dim_choices)
461
+ head_dim_v = None
462
+ # head_dim_v = random.choice(head_dim_choices)
463
+
464
+ else:
465
+ raise NotImplementedError()
466
+
467
+ heads = random.choice(heads_choices)
468
+ heads_kv = (
469
+ heads
470
+ if not supports_gqa_mqa
471
+ else random.choice([1] + [i for i in range(1, heads + 1) if heads % i == 0])
472
+ )
473
+ assert heads >= heads_kv and heads % heads_kv == 0
474
+
475
+ seqlen_q = random.choice(range(16, 2**14, 1))
476
+ seqlen_kv = random.choice(range(16, 2**14, 1))
477
+
478
+ is_causal = random.choice([True, False])
479
+
480
+ while seqlen_q * seqlen_kv > max_qk:
481
+ cut_kv = random.choice([True, False])
482
+ if cut_kv:
483
+ seqlen_kv = int(seqlen_kv * 0.75)
484
+ else:
485
+ seqlen_q = int(seqlen_q * 0.75)
486
+
487
+ self._test_backend_against_torch_sdpa(
488
+ batch=batch,
489
+ heads=heads,
490
+ heads_kv=heads_kv,
491
+ head_dim=head_dim,
492
+ head_dim_v=head_dim_v,
493
+ seqlen_q=seqlen_q,
494
+ seqlen_kv=seqlen_kv,
495
+ is_causal=is_causal,
496
+ backend=backend,
497
+ )
498
+
499
+ @pytest.mark.L1
500
+ @skip_if_cudnn_not_supported()
501
+ @skip_if_not_blackwell()
502
+ def test_cudnn_fast(self):
503
+ problem_sizes = [
504
+ #### fp16 NaN??!!
505
+ #### batch=1, heads=13, head_dim=128, seqlen_q=7688, seqlen_kv=256, is_causal=False, dtype=torch.float16
506
+ (1, 8, 128, 16384, 16384),
507
+ (1, 13, 128, 7688, 256),
508
+ #### illegal mem access -- seems intermittent
509
+ ## batch=6, heads=2, head_dim=128, seqlen_q=12244, seqlen_kv=123, is_causal=False, dtype=torch.float16
510
+ (6, 2, 128, 12244, 123),
511
+ #####
512
+ (2, 1, 128, 2048, 2048),
513
+ (2, 1, 64, 2048, 2048),
514
+ (4, 1, 64, 2048, 2048),
515
+ ### Failing FP16 case:
516
+ ### batch=2, heads=1, head_dim=64, seqlen_q=1411, seqlen_kv=1375, is_causal=False, dtype=torch.float16
517
+ (1, 1, 64, 1411, 1375),
518
+ (2, 1, 64, 1536, 1280),
519
+ (2, 1, 64, 1536, 1536),
520
+ (2, 1, 64, 1536, 1376),
521
+ (2, 1, 64, 1416, 1376),
522
+ (2, 1, 64, 1411, 1375),
523
+ ### NaN case
524
+ ### batch=3, heads=3, head_dim=64, seqlen_q=9197, seqlen_kv=166,
525
+ (1, 1, 64, 10240, 512),
526
+ (2, 1, 64, 10240, 512),
527
+ (4, 1, 64, 10240, 512),
528
+ (8, 1, 64, 10240, 512),
529
+ #####
530
+ (3, 1, 64, 10240, 512),
531
+ (4, 1, 64, 10240, 512),
532
+ (5, 1, 64, 10240, 512),
533
+ (6, 1, 64, 10240, 512),
534
+ (7, 1, 64, 10240, 512),
535
+ (8, 1, 64, 10240, 512),
536
+ (3, 3, 64, 10240, 512),
537
+ (3, 3, 64, 9216, 512),
538
+ (3, 3, 64, 9200, 512),
539
+ (3, 3, 64, 9200, 512),
540
+ (3, 3, 64, 9200, 512),
541
+ (3, 3, 64, 9200, 512),
542
+ (3, 3, 64, 9198, 512),
543
+ (3, 3, 64, 9197, 512),
544
+ #
545
+ (3, 1, 64, 10240, 256),
546
+ (4, 1, 64, 10240, 256),
547
+ (5, 1, 64, 10240, 256),
548
+ (6, 1, 64, 10240, 256),
549
+ (7, 1, 64, 10240, 256),
550
+ (8, 1, 64, 10240, 256),
551
+ (3, 3, 64, 10240, 256),
552
+ (3, 3, 64, 9216, 256),
553
+ (3, 3, 64, 9200, 256),
554
+ (3, 3, 64, 9200, 192),
555
+ (3, 3, 64, 9200, 168),
556
+ (3, 3, 64, 9200, 166),
557
+ (3, 3, 64, 9198, 166),
558
+ (3, 3, 64, 9197, 166),
559
+ # Passing:
560
+ (4, 1, 64, 10240, 10240),
561
+ (4, 1, 64, 10240, 1024),
562
+ (1, 1, 64, 9197, 166),
563
+ (3, 3, 64, 2560, 256),
564
+ #
565
+ (1, 1, 128, 128, 128),
566
+ (2, 1, 128, 128, 128),
567
+ (1, 2, 128, 128, 128),
568
+ (2, 2, 128, 128, 128),
569
+ (2, 2, 64, 128, 128),
570
+ (1, 1, 32, 32, 32),
571
+ (1, 1, 32, 128, 128),
572
+ (1, 1, 32, 128, 128),
573
+ (1, 1, 128, 128, 64),
574
+ (1, 1, 32, 128, 258),
575
+ (1, 2, 64, 128, 15),
576
+ (1, 1, 32, 8, 17),
577
+ (1, 1, 64, 17, 49),
578
+ (2, 4, 32, 128, 237),
579
+ (4, 3, 64, 256, 33),
580
+ (1, 1, 128, 128, 75),
581
+ (1, 1, 32, 125, 444),
582
+ (1, 2, 64, 125, 231),
583
+ (1, 1, 128, 256, 10240),
584
+ (1, 1, 32, 128, 4096),
585
+ (1, 1, 128, 3584, 381),
586
+ (1, 1, 128, 12072, 1680),
587
+ ]
588
+ for (
589
+ batch,
590
+ heads,
591
+ head_dim,
592
+ seqlen_q,
593
+ seqlen_kv,
594
+ ) in problem_sizes:
595
+ for is_causal in [False, True]:
596
+ self._test_backend_against_torch_sdpa(
597
+ batch=batch,
598
+ heads=heads,
599
+ head_dim=head_dim,
600
+ seqlen_q=seqlen_q,
601
+ seqlen_kv=seqlen_kv,
602
+ is_causal=is_causal,
603
+ backend="cudnn",
604
+ )
605
+
606
+ @pytest.mark.L1
607
+ @skip_if_cudnn_not_supported()
608
+ @skip_if_not_blackwell()
609
+ def test_cudnn_randsweep(self):
610
+ self._test_randsweep_against_torch_sdpa(backend="cudnn", max_tests=RAND_SWEEP_TESTS)
611
+
612
+ @pytest.mark.L1
613
+ @skip_if_natten_not_supported()
614
+ @skip_if_not_blackwell()
615
+ def test_natten_blackwell_fast(self):
616
+ problem_sizes = [
617
+ (1, 8, 8, 128, 16384, 16384),
618
+ (1, 8, 4, 128, 16384, 16384),
619
+ (1, 8, 2, 128, 16384, 16384),
620
+ (1, 8, 1, 128, 16384, 16384),
621
+ (1, 12, 12, 128, 7688, 256),
622
+ (1, 12, 6, 128, 7688, 256),
623
+ (1, 12, 4, 128, 7688, 256),
624
+ (1, 12, 3, 128, 7688, 256),
625
+ (1, 12, 2, 128, 7688, 256),
626
+ (1, 12, 1, 128, 7688, 256),
627
+ (6, 2, 2, 128, 12244, 123),
628
+ (6, 2, 1, 128, 12244, 123),
629
+ (2, 1, 1, 128, 2048, 2048),
630
+ (2, 1, 1, 64, 2048, 2048),
631
+ (4, 1, 1, 64, 2048, 2048),
632
+ (1, 1, 1, 64, 1411, 1375),
633
+ (2, 1, 1, 64, 1536, 1280),
634
+ (2, 1, 1, 64, 1536, 1536),
635
+ (2, 1, 1, 64, 1536, 1376),
636
+ (2, 1, 1, 64, 1416, 1376),
637
+ (2, 1, 1, 64, 1411, 1375),
638
+ (1, 1, 1, 64, 10240, 512),
639
+ (2, 1, 1, 64, 10240, 512),
640
+ (4, 1, 1, 64, 10240, 512),
641
+ (8, 1, 1, 64, 10240, 512),
642
+ (3, 1, 1, 64, 10240, 512),
643
+ (4, 1, 1, 64, 10240, 512),
644
+ (5, 1, 1, 64, 10240, 512),
645
+ (6, 1, 1, 64, 10240, 512),
646
+ (7, 1, 1, 64, 10240, 512),
647
+ (8, 1, 1, 64, 10240, 512),
648
+ (3, 3, 3, 64, 9197, 512),
649
+ (3, 3, 1, 64, 9197, 512),
650
+ (7, 1, 1, 64, 10240, 256),
651
+ (3, 3, 3, 64, 10240, 256),
652
+ (3, 3, 3, 64, 9216, 256),
653
+ (3, 3, 3, 64, 9200, 256),
654
+ (3, 3, 3, 64, 9200, 192),
655
+ (3, 3, 3, 64, 9200, 168),
656
+ (3, 3, 3, 64, 9200, 166),
657
+ (3, 3, 3, 64, 9198, 166),
658
+ (3, 3, 3, 64, 9197, 166),
659
+ (4, 1, 1, 64, 10240, 10240),
660
+ (4, 1, 1, 64, 10240, 1024),
661
+ (1, 1, 1, 64, 9197, 166),
662
+ (3, 3, 3, 64, 2560, 256),
663
+ (1, 1, 1, 128, 128, 128),
664
+ (2, 1, 1, 128, 128, 128),
665
+ (1, 2, 2, 128, 128, 128),
666
+ (2, 2, 2, 128, 128, 128),
667
+ (2, 2, 2, 64, 128, 128),
668
+ (1, 1, 1, 32, 32, 32),
669
+ (1, 1, 1, 32, 128, 128),
670
+ (1, 1, 1, 32, 128, 128),
671
+ (1, 1, 1, 128, 128, 64),
672
+ (1, 1, 1, 32, 128, 258),
673
+ (1, 2, 2, 64, 128, 15),
674
+ (1, 1, 1, 32, 8, 17),
675
+ (1, 1, 1, 64, 17, 49),
676
+ (2, 4, 4, 32, 128, 237),
677
+ (2, 4, 2, 32, 128, 237),
678
+ (2, 4, 1, 32, 128, 237),
679
+ (4, 3, 3, 64, 256, 33),
680
+ (4, 3, 1, 64, 256, 33),
681
+ (1, 1, 1, 128, 128, 75),
682
+ (1, 1, 1, 32, 125, 444),
683
+ (1, 2, 2, 64, 125, 231),
684
+ (1, 2, 1, 64, 125, 231),
685
+ (1, 1, 1, 128, 256, 10240),
686
+ (1, 1, 1, 32, 128, 4096),
687
+ (1, 1, 1, 128, 3584, 381),
688
+ (1, 1, 1, 128, 12072, 1680),
689
+ ]
690
+ for (
691
+ batch,
692
+ heads,
693
+ heads_kv,
694
+ head_dim,
695
+ seqlen_q,
696
+ seqlen_kv,
697
+ ) in problem_sizes:
698
+ for is_causal in [False, True]:
699
+ self._test_backend_against_torch_sdpa(
700
+ batch=batch,
701
+ heads=heads,
702
+ heads_kv=heads_kv,
703
+ head_dim=head_dim,
704
+ seqlen_q=seqlen_q,
705
+ seqlen_kv=seqlen_kv,
706
+ is_causal=is_causal,
707
+ backend="natten",
708
+ )
709
+
710
+ @pytest.mark.L1
711
+ @skip_if_natten_not_supported()
712
+ @skip_if_not_hopper()
713
+ def test_natten_hopper_fast(self):
714
+ # No GQA/MQA
715
+ # No MLA (except when using Ampere kernels)
716
+ # No causal masking (except when using Ampere kernels)
717
+ problem_sizes = [
718
+ (1, 8, 8, 128, 16384, 16384),
719
+ (1, 12, 12, 128, 7688, 256),
720
+ (6, 2, 2, 128, 12244, 123),
721
+ (2, 1, 1, 128, 2048, 2048),
722
+ (2, 1, 1, 64, 2048, 2048),
723
+ (4, 1, 1, 64, 2048, 2048),
724
+ (1, 1, 1, 64, 1411, 1375),
725
+ (2, 1, 1, 64, 1536, 1280),
726
+ (2, 1, 1, 64, 1536, 1536),
727
+ (2, 1, 1, 64, 1536, 1376),
728
+ (2, 1, 1, 64, 1416, 1376),
729
+ (2, 1, 1, 64, 1411, 1375),
730
+ (1, 1, 1, 64, 10240, 512),
731
+ (2, 1, 1, 64, 10240, 512),
732
+ (4, 1, 1, 64, 10240, 512),
733
+ (8, 1, 1, 64, 10240, 512),
734
+ (3, 1, 1, 64, 10240, 512),
735
+ (4, 1, 1, 64, 10240, 512),
736
+ (5, 1, 1, 64, 10240, 512),
737
+ (6, 1, 1, 64, 10240, 512),
738
+ (7, 1, 1, 64, 10240, 512),
739
+ (8, 1, 1, 64, 10240, 512),
740
+ (3, 3, 3, 64, 9197, 512),
741
+ (7, 1, 1, 64, 10240, 256),
742
+ (3, 3, 3, 64, 10240, 256),
743
+ (3, 3, 3, 64, 9216, 256),
744
+ (3, 3, 3, 64, 9200, 256),
745
+ (3, 3, 3, 64, 9200, 192),
746
+ (3, 3, 3, 64, 9200, 168),
747
+ (3, 3, 3, 64, 9200, 166),
748
+ (3, 3, 3, 64, 9198, 166),
749
+ (3, 3, 3, 64, 9197, 166),
750
+ (4, 1, 1, 64, 10240, 10240),
751
+ (4, 1, 1, 64, 10240, 1024),
752
+ (1, 1, 1, 64, 9197, 166),
753
+ (3, 3, 3, 64, 2560, 256),
754
+ (1, 1, 1, 128, 128, 128),
755
+ (2, 1, 1, 128, 128, 128),
756
+ (1, 2, 2, 128, 128, 128),
757
+ (2, 2, 2, 128, 128, 128),
758
+ (2, 2, 2, 64, 128, 128),
759
+ (1, 1, 1, 32, 32, 32),
760
+ (1, 1, 1, 32, 128, 128),
761
+ (1, 1, 1, 32, 128, 128),
762
+ (1, 1, 1, 128, 128, 64),
763
+ (1, 1, 1, 32, 128, 258),
764
+ (1, 2, 2, 64, 128, 15),
765
+ (1, 1, 1, 32, 8, 17),
766
+ (1, 1, 1, 64, 17, 49),
767
+ (2, 4, 4, 32, 128, 237),
768
+ (4, 3, 3, 64, 256, 33),
769
+ (1, 1, 1, 128, 128, 75),
770
+ (1, 1, 1, 32, 125, 444),
771
+ (1, 2, 2, 64, 125, 231),
772
+ (1, 1, 1, 128, 256, 10240),
773
+ (1, 1, 1, 32, 128, 4096),
774
+ (1, 1, 1, 128, 3584, 381),
775
+ (1, 1, 1, 128, 12072, 1680),
776
+ ]
777
+ for (
778
+ batch,
779
+ heads,
780
+ heads_kv,
781
+ head_dim,
782
+ seqlen_q,
783
+ seqlen_kv,
784
+ ) in problem_sizes:
785
+ for is_causal in [False, True]:
786
+ self._test_backend_against_torch_sdpa(
787
+ batch=batch,
788
+ heads=heads,
789
+ heads_kv=heads_kv,
790
+ head_dim=head_dim,
791
+ seqlen_q=seqlen_q,
792
+ seqlen_kv=seqlen_kv,
793
+ is_causal=is_causal,
794
+ backend="natten",
795
+ )
796
+
797
+ @pytest.mark.L1
798
+ @skip_if_natten_not_supported()
799
+ @skip_if_not_supported()
800
+ def test_natten_randsweep(self):
801
+ self._test_randsweep_against_torch_sdpa(backend="natten", max_tests=RAND_SWEEP_TESTS)
802
+
803
+ @pytest.mark.L1
804
+ @skip_if_flash2_not_supported()
805
+ @skip_if_not_supported()
806
+ def test_flash2_fast(self):
807
+ problem_sizes = [
808
+ (1, 8, 8, 128, 16384, 16384),
809
+ (1, 8, 4, 128, 16384, 16384),
810
+ (1, 8, 2, 128, 16384, 16384),
811
+ (1, 8, 1, 128, 16384, 16384),
812
+ (1, 12, 12, 128, 7688, 256),
813
+ (1, 12, 6, 128, 7688, 256),
814
+ (1, 12, 4, 128, 7688, 256),
815
+ (1, 12, 3, 128, 7688, 256),
816
+ (1, 12, 2, 128, 7688, 256),
817
+ (1, 12, 1, 128, 7688, 256),
818
+ (6, 2, 2, 128, 12244, 123),
819
+ (6, 2, 1, 128, 12244, 123),
820
+ (2, 1, 1, 128, 2048, 2048),
821
+ (2, 1, 1, 64, 2048, 2048),
822
+ (4, 1, 1, 64, 2048, 2048),
823
+ (1, 1, 1, 64, 1411, 1375),
824
+ (2, 1, 1, 64, 1536, 1280),
825
+ (2, 1, 1, 64, 1536, 1536),
826
+ (2, 1, 1, 64, 1536, 1376),
827
+ (2, 1, 1, 64, 1416, 1376),
828
+ (2, 1, 1, 64, 1411, 1375),
829
+ (1, 1, 1, 64, 10240, 512),
830
+ (2, 1, 1, 64, 10240, 512),
831
+ (4, 1, 1, 64, 10240, 512),
832
+ (8, 1, 1, 64, 10240, 512),
833
+ (3, 1, 1, 64, 10240, 512),
834
+ (4, 1, 1, 64, 10240, 512),
835
+ (5, 1, 1, 64, 10240, 512),
836
+ (6, 1, 1, 64, 10240, 512),
837
+ (7, 1, 1, 64, 10240, 512),
838
+ (8, 1, 1, 64, 10240, 512),
839
+ (3, 3, 3, 64, 9197, 512),
840
+ (3, 3, 1, 64, 9197, 512),
841
+ (7, 1, 1, 64, 10240, 256),
842
+ (3, 3, 3, 64, 10240, 256),
843
+ (3, 3, 3, 64, 9216, 256),
844
+ (3, 3, 3, 64, 9200, 256),
845
+ (3, 3, 3, 64, 9200, 192),
846
+ (3, 3, 3, 64, 9200, 168),
847
+ (3, 3, 3, 64, 9200, 166),
848
+ (3, 3, 3, 64, 9198, 166),
849
+ (3, 3, 3, 64, 9197, 166),
850
+ (4, 1, 1, 64, 10240, 10240),
851
+ (4, 1, 1, 64, 10240, 1024),
852
+ (1, 1, 1, 64, 9197, 166),
853
+ (3, 3, 3, 64, 2560, 256),
854
+ (1, 1, 1, 128, 128, 128),
855
+ (2, 1, 1, 128, 128, 128),
856
+ (1, 2, 2, 128, 128, 128),
857
+ (2, 2, 2, 128, 128, 128),
858
+ (2, 2, 2, 64, 128, 128),
859
+ (1, 1, 1, 32, 32, 32),
860
+ (1, 1, 1, 32, 128, 128),
861
+ (1, 1, 1, 32, 128, 128),
862
+ (1, 1, 1, 128, 128, 64),
863
+ (1, 1, 1, 32, 128, 258),
864
+ (1, 2, 2, 64, 128, 15),
865
+ (1, 1, 1, 32, 8, 17),
866
+ (1, 1, 1, 64, 17, 49),
867
+ (2, 4, 4, 32, 128, 237),
868
+ (2, 4, 2, 32, 128, 237),
869
+ (2, 4, 1, 32, 128, 237),
870
+ (4, 3, 3, 64, 256, 33),
871
+ (4, 3, 1, 64, 256, 33),
872
+ (1, 1, 1, 128, 128, 75),
873
+ (1, 1, 1, 32, 125, 444),
874
+ (1, 2, 2, 64, 125, 231),
875
+ (1, 2, 1, 64, 125, 231),
876
+ (1, 1, 1, 128, 256, 10240),
877
+ (1, 1, 1, 32, 128, 4096),
878
+ (1, 1, 1, 128, 3584, 381),
879
+ (1, 1, 1, 128, 12072, 1680),
880
+ ]
881
+ for (
882
+ batch,
883
+ heads,
884
+ heads_kv,
885
+ head_dim,
886
+ seqlen_q,
887
+ seqlen_kv,
888
+ ) in problem_sizes:
889
+ for is_causal in [False, True]:
890
+ self._test_backend_against_torch_sdpa(
891
+ batch=batch,
892
+ heads=heads,
893
+ heads_kv=heads_kv,
894
+ head_dim=head_dim,
895
+ seqlen_q=seqlen_q,
896
+ seqlen_kv=seqlen_kv,
897
+ is_causal=is_causal,
898
+ backend="flash2",
899
+ )
900
+
901
+ @pytest.mark.L1
902
+ @skip_if_flash2_not_supported()
903
+ @skip_if_not_supported()
904
+ def test_flash2_randsweep(self):
905
+ self._test_randsweep_against_torch_sdpa(backend="flash2", max_tests=RAND_SWEEP_TESTS)
906
+
907
+ @pytest.mark.L1
908
+ @skip_if_flash3_not_supported()
909
+ @skip_if_not_supported()
910
+ def test_flash3_fast(self):
911
+ problem_sizes = [
912
+ (1, 8, 8, 128, 16384, 16384),
913
+ (1, 8, 4, 128, 16384, 16384),
914
+ (1, 8, 2, 128, 16384, 16384),
915
+ (1, 8, 1, 128, 16384, 16384),
916
+ (1, 12, 12, 128, 7688, 256),
917
+ (1, 12, 6, 128, 7688, 256),
918
+ (1, 12, 4, 128, 7688, 256),
919
+ (1, 12, 3, 128, 7688, 256),
920
+ (1, 12, 2, 128, 7688, 256),
921
+ (1, 12, 1, 128, 7688, 256),
922
+ (6, 2, 2, 128, 12244, 123),
923
+ (6, 2, 1, 128, 12244, 123),
924
+ (2, 1, 1, 128, 2048, 2048),
925
+ (2, 1, 1, 64, 2048, 2048),
926
+ (4, 1, 1, 64, 2048, 2048),
927
+ (1, 1, 1, 64, 1411, 1375),
928
+ (2, 1, 1, 64, 1536, 1280),
929
+ (2, 1, 1, 64, 1536, 1536),
930
+ (2, 1, 1, 64, 1536, 1376),
931
+ (2, 1, 1, 64, 1416, 1376),
932
+ (2, 1, 1, 64, 1411, 1375),
933
+ (1, 1, 1, 64, 10240, 512),
934
+ (2, 1, 1, 64, 10240, 512),
935
+ (4, 1, 1, 64, 10240, 512),
936
+ (8, 1, 1, 64, 10240, 512),
937
+ (3, 1, 1, 64, 10240, 512),
938
+ (4, 1, 1, 64, 10240, 512),
939
+ (5, 1, 1, 64, 10240, 512),
940
+ (6, 1, 1, 64, 10240, 512),
941
+ (7, 1, 1, 64, 10240, 512),
942
+ (8, 1, 1, 64, 10240, 512),
943
+ (3, 3, 3, 64, 9197, 512),
944
+ (3, 3, 1, 64, 9197, 512),
945
+ (7, 1, 1, 64, 10240, 256),
946
+ (3, 3, 3, 64, 10240, 256),
947
+ (3, 3, 3, 64, 9216, 256),
948
+ (3, 3, 3, 64, 9200, 256),
949
+ (3, 3, 3, 64, 9200, 192),
950
+ (3, 3, 3, 64, 9200, 168),
951
+ (3, 3, 3, 64, 9200, 166),
952
+ (3, 3, 3, 64, 9198, 166),
953
+ (3, 3, 3, 64, 9197, 166),
954
+ (4, 1, 1, 64, 10240, 10240),
955
+ (4, 1, 1, 64, 10240, 1024),
956
+ (1, 1, 1, 64, 9197, 166),
957
+ (3, 3, 3, 64, 2560, 256),
958
+ (1, 1, 1, 128, 128, 128),
959
+ (2, 1, 1, 128, 128, 128),
960
+ (1, 2, 2, 128, 128, 128),
961
+ (2, 2, 2, 128, 128, 128),
962
+ (2, 2, 2, 64, 128, 128),
963
+ (1, 1, 1, 32, 32, 32),
964
+ (1, 1, 1, 32, 128, 128),
965
+ (1, 1, 1, 32, 128, 128),
966
+ (1, 1, 1, 128, 128, 64),
967
+ (1, 1, 1, 32, 128, 258),
968
+ (1, 2, 2, 64, 128, 15),
969
+ (1, 1, 1, 32, 8, 17),
970
+ (1, 1, 1, 64, 17, 49),
971
+ (2, 4, 4, 32, 128, 237),
972
+ (2, 4, 2, 32, 128, 237),
973
+ (2, 4, 1, 32, 128, 237),
974
+ (4, 3, 3, 64, 256, 33),
975
+ (4, 3, 1, 64, 256, 33),
976
+ (1, 1, 1, 128, 128, 75),
977
+ (1, 1, 1, 32, 125, 444),
978
+ (1, 2, 2, 64, 125, 231),
979
+ (1, 2, 1, 64, 125, 231),
980
+ (1, 1, 1, 128, 256, 10240),
981
+ (1, 1, 1, 32, 128, 4096),
982
+ (1, 1, 1, 128, 3584, 381),
983
+ (1, 1, 1, 128, 12072, 1680),
984
+ ]
985
+ for (
986
+ batch,
987
+ heads,
988
+ heads_kv,
989
+ head_dim,
990
+ seqlen_q,
991
+ seqlen_kv,
992
+ ) in problem_sizes:
993
+ for is_causal in [False, True]:
994
+ self._test_backend_against_torch_sdpa(
995
+ batch=batch,
996
+ heads=heads,
997
+ heads_kv=heads_kv,
998
+ head_dim=head_dim,
999
+ seqlen_q=seqlen_q,
1000
+ seqlen_kv=seqlen_kv,
1001
+ is_causal=is_causal,
1002
+ backend="flash3",
1003
+ )
1004
+
1005
+ @pytest.mark.L1
1006
+ @skip_if_flash3_not_supported()
1007
+ @skip_if_not_hopper()
1008
+ def test_flash3_randsweep(self):
1009
+ self._test_randsweep_against_torch_sdpa(backend="flash3", max_tests=RAND_SWEEP_TESTS)
1010
+
1011
+
1012
+ if __name__ == "__main__":
1013
+ random.seed(42)
1014
+ torch.manual_seed(42)
1015
+ unittest.main()
REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/torch_compile_test.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #################################################################################################
2
+ # Copyright (c) 2022-2025 Ali Hassani.
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ # of this software and associated documentation files (the "Software"), to deal
6
+ # in the Software without restriction, including without limitation the rights
7
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ # copies of the Software, and to permit persons to whom the Software is
9
+ # furnished to do so, subject to the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be included in all
12
+ # copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ # SOFTWARE.
21
+ #
22
+ #################################################################################################
23
+
24
+ import unittest
25
+ from functools import partial
26
+
27
+ import pytest
28
+ import torch
29
+ from torch import nn
30
+
31
+ from cosmos_policy._src.imaginaire.attention import attention as i4_attention
32
+ from cosmos_policy._src.imaginaire.attention.flash2 import FLASH2_SUPPORTED
33
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
34
+ from cosmos_policy._src.imaginaire.attention.natten import NATTEN_SUPPORTED
35
+ from cosmos_policy._src.imaginaire.attention.utils import is_blackwell_dc, is_hopper
36
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
37
+ from cosmos_policy._src.imaginaire.attention.varlen import generate_varlen_parameters
38
+
39
+ skip_if_natten_not_supported = partial(
40
+ pytest.mark.skipif,
41
+ not NATTEN_SUPPORTED,
42
+ reason="NATTEN is disabled, not available, or too old in this environment.",
43
+ )
44
+
45
+ skip_if_flash2_not_supported = partial(
46
+ pytest.mark.skipif,
47
+ not FLASH2_SUPPORTED,
48
+ reason="Flash2 is disabled, not available, or too old in this environment.",
49
+ )
50
+
51
+ # Tests are only enabled on Hopper and Blackwell DC-class for now.
52
+ # Will extend to other arches as we integrate more backends.
53
+ skip_if_not_supported = partial(
54
+ pytest.mark.skipif,
55
+ not is_blackwell_dc() and not is_hopper(),
56
+ reason="Attention tests are only allowed for Hopper and Blackwell DC-class GPUs for now.",
57
+ )
58
+
59
+ skip_if_not_blackwell = partial(
60
+ pytest.mark.skipif, not is_blackwell_dc(), reason="This test is only allowed for Blackwell DC-class GPUs."
61
+ )
62
+
63
+ skip_if_not_hopper = partial(pytest.mark.skipif, not is_hopper(), reason="This test is only allowed for Hopper GPUs.")
64
+
65
+
66
+ def reset_torch_compile(cache_size_limit):
67
+ # Torch compile reset and sensible settings for unit testing
68
+ log.debug(f"Resetting torch compile cache. New cache size limit: {cache_size_limit}")
69
+ torch.compiler.reset()
70
+ torch._dynamo.config.cache_size_limit = cache_size_limit
71
+ torch._dynamo.config.accumulated_recompile_limit = cache_size_limit * 4
72
+ torch._dynamo.config.fail_on_recompile_limit_hit = True
73
+
74
+
75
+ def _reset_everything():
76
+ torch.manual_seed(42)
77
+ reset_torch_compile(1024)
78
+ torch.cuda.empty_cache()
79
+
80
+
81
+ class Block(nn.Module):
82
+ def __init__(
83
+ self,
84
+ embed_dim: int,
85
+ num_heads: int,
86
+ mlp_ratio: int,
87
+ qkv_bias: bool = True,
88
+ ):
89
+ super().__init__()
90
+
91
+ self.embed_dim = embed_dim
92
+ self.mlp_ratio = mlp_ratio
93
+ self.mlp_dim = int(self.embed_dim * self.mlp_ratio)
94
+ self.num_heads = num_heads
95
+ self.head_dim = self.embed_dim // self.num_heads
96
+ self.scale = self.head_dim**-0.5
97
+
98
+ self.q = nn.Linear(self.embed_dim, self.embed_dim, bias=qkv_bias)
99
+ self.kv = nn.Linear(self.embed_dim, self.embed_dim * 2, bias=qkv_bias)
100
+ self.proj = nn.Linear(self.embed_dim, self.embed_dim)
101
+
102
+ self.mlp = nn.Sequential(
103
+ nn.Linear(self.embed_dim, self.mlp_dim),
104
+ nn.GELU(),
105
+ nn.Linear(self.mlp_dim, embed_dim),
106
+ )
107
+
108
+ def forward(self, x: torch.Tensor, c: torch.Tensor, *args, **kwargs):
109
+ B, sQ, D = x.shape
110
+ B, sK, D = c.shape
111
+ q = self.q(x).reshape(B, sQ, self.num_heads, self.head_dim)
112
+ k, v = self.kv(c).reshape(B, sK, 2, self.num_heads, self.head_dim).permute(2, 0, 1, 3, 4)
113
+
114
+ x0 = i4_attention(q, k, v, *args, **kwargs)
115
+ assert isinstance(x0, torch.Tensor)
116
+ x0 = x0.reshape(B, sQ, D)
117
+
118
+ return self.mlp(x0)
119
+
120
+
121
+ class TorchCompileTests(unittest.TestCase):
122
+ def setUp(self):
123
+ _reset_everything()
124
+
125
+ def tearDown(self):
126
+ _reset_everything()
127
+
128
+ def _test_module(
129
+ self,
130
+ batch: int,
131
+ seqlens_Q: list[int],
132
+ seqlens_KV: list[int],
133
+ num_heads: int,
134
+ head_dim: int,
135
+ is_causal: bool,
136
+ causal_type: CausalType,
137
+ atol: float,
138
+ backend: str,
139
+ device: str = "cuda",
140
+ dtype: torch.dtype = torch.float16,
141
+ ):
142
+ embed_dim = num_heads * head_dim
143
+
144
+ assert len(seqlens_Q) == len(seqlens_KV)
145
+ assert len(seqlens_Q) >= 1
146
+ assert len(seqlens_Q) == 1 or batch == len(seqlens_Q)
147
+
148
+ seqlen_q = sum(seqlens_Q)
149
+ seqlen_kv = sum(seqlens_KV)
150
+ is_varlen = len(seqlens_Q) > 1
151
+
152
+ batch_ = 1 if is_varlen else batch
153
+ seqlens_Q_ = torch.tensor(seqlens_Q, device=device, dtype=torch.int32) if is_varlen else None
154
+ seqlens_KV_ = torch.tensor(seqlens_KV, device=device, dtype=torch.int32) if is_varlen else None
155
+
156
+ dummy_q = torch.randn(
157
+ (batch_, seqlen_q, num_heads, head_dim),
158
+ dtype=dtype,
159
+ device=device,
160
+ requires_grad=True,
161
+ )
162
+ dummy_kv = torch.randn(
163
+ (batch_, seqlen_kv, num_heads, head_dim),
164
+ dtype=dtype,
165
+ device=device,
166
+ requires_grad=True,
167
+ )
168
+
169
+ # seq maxes MUST be computed ahead of time when using torch compile
170
+ # because need to be copied to host
171
+ (
172
+ cumulative_seqlen_Q,
173
+ cumulative_seqlen_KV,
174
+ max_seqlen_Q,
175
+ max_seqlen_KV,
176
+ ) = generate_varlen_parameters(
177
+ query=dummy_q,
178
+ key=dummy_kv,
179
+ value=dummy_kv,
180
+ seqlens_Q=seqlens_Q_,
181
+ seqlens_KV=seqlens_KV_,
182
+ )
183
+
184
+ _reset_everything()
185
+
186
+ log.debug(
187
+ f"Testing torch compile on Attention module with input shapes: "
188
+ f"{batch=}, {num_heads=}, {head_dim=}, {seqlens_Q=}, {seqlens_KV=}, "
189
+ f"{is_causal=}, {causal_type=}, {dtype=}, {device=}, {backend=}."
190
+ )
191
+
192
+ model_eager = (
193
+ Block(
194
+ embed_dim=embed_dim,
195
+ mlp_ratio=2,
196
+ num_heads=num_heads,
197
+ )
198
+ .to(dtype)
199
+ .to(device)
200
+ )
201
+
202
+ model_compiled = torch.compile(model_eager, fullgraph=True, backend="inductor")
203
+
204
+ x = torch.randn((batch_, seqlen_q, embed_dim), dtype=dtype, device=device)
205
+ c = torch.randn((batch_, seqlen_kv, embed_dim), dtype=dtype, device=device)
206
+ dy = torch.randn((batch_, seqlen_q, embed_dim), dtype=dtype, device=device) * 0.1
207
+
208
+ x_ref = x.clone().requires_grad_(True)
209
+ c_ref = c.clone().requires_grad_(True)
210
+ dy_ref = dy.clone()
211
+
212
+ # eager
213
+ y_ref = model_eager(
214
+ x_ref,
215
+ c_ref,
216
+ is_causal=is_causal,
217
+ causal_type=causal_type,
218
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
219
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
220
+ max_seqlen_Q=max_seqlen_Q,
221
+ max_seqlen_KV=max_seqlen_KV,
222
+ backend=backend,
223
+ )
224
+ y_ref.backward(dy_ref)
225
+ dx_ref = x_ref.grad
226
+ dc_ref = c_ref.grad
227
+
228
+ # compile on first attempt
229
+ x = x.requires_grad_(True)
230
+ c = c.requires_grad_(True)
231
+ y = model_compiled(
232
+ x,
233
+ c,
234
+ is_causal=is_causal,
235
+ causal_type=causal_type,
236
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
237
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
238
+ max_seqlen_Q=max_seqlen_Q,
239
+ max_seqlen_KV=max_seqlen_KV,
240
+ backend=backend,
241
+ )
242
+ y.backward(dy)
243
+ dx = x.grad
244
+ dc = c.grad
245
+
246
+ torch.testing.assert_close(y, y_ref, atol=atol, rtol=0)
247
+ torch.testing.assert_close(dx, dx_ref, atol=atol, rtol=0)
248
+ torch.testing.assert_close(dc, dc_ref, atol=atol, rtol=0)
249
+
250
+ # Second run, just to make sure it doesn't crash
251
+ y = model_compiled(
252
+ x,
253
+ c,
254
+ is_causal=is_causal,
255
+ causal_type=causal_type,
256
+ cumulative_seqlen_Q=cumulative_seqlen_Q,
257
+ cumulative_seqlen_KV=cumulative_seqlen_KV,
258
+ max_seqlen_Q=max_seqlen_Q,
259
+ max_seqlen_KV=max_seqlen_KV,
260
+ backend=backend,
261
+ )
262
+ y.backward(dy)
263
+ dx = x.grad
264
+ dc = c.grad
265
+
266
+ @pytest.mark.L1
267
+ @skip_if_natten_not_supported()
268
+ @skip_if_not_supported()
269
+ def test_compiled_natten(self):
270
+ problem_sizes = [
271
+ (1, 4, 128, [128], [128]),
272
+ (1, 1, 128, [128], [1024]),
273
+ (1, 1, 128, [128], [13568]),
274
+ (1, 1, 128, [128], [13496]),
275
+ (1, 1, 32, [128], [13496]),
276
+ (1, 1, 32, [32], [13496]),
277
+ (3, 1, 32, [77], [8504]),
278
+ (1, 1, 32, [77], [8504]),
279
+ (1, 1, 64, [40], [12296]),
280
+ (1, 2, 64, [40], [12296]),
281
+ (1, 2, 64, [40], [12296]),
282
+ (1, 1, 128, [128], [128]),
283
+ (6, 1, 128, [128, 128, 135, 121, 128, 128], [128, 128, 135, 121, 128, 128]),
284
+ (5, 1, 128, [128, 128, 135, 128, 128], [128, 128, 135, 128, 128]),
285
+ (2, 1, 128, [135, 200], [128, 768]),
286
+ (2, 1, 128, [1024, 200], [128, 768]),
287
+ (2, 1, 128, [135, 200], [135, 768]),
288
+ (2, 1, 128, [1024, 200], [135, 768]),
289
+ (2, 1, 128, [1024, 256], [128, 768]),
290
+ (4, 1, 128, [1024, 8, 17, 2048], [10, 20, 512, 16]),
291
+ (3, 2, 128, [268, 1584, 1571], [2448, 4088, 1925]),
292
+ (2, 1, 128, [1024, 256], [512, 768]),
293
+ ]
294
+ for (
295
+ batch,
296
+ num_heads,
297
+ head_dim,
298
+ seqlens_Q,
299
+ seqlens_KV,
300
+ ) in problem_sizes:
301
+ for is_causal in [False, True]:
302
+ self._test_module(
303
+ batch=batch,
304
+ seqlens_Q=seqlens_Q,
305
+ seqlens_KV=seqlens_KV,
306
+ num_heads=num_heads,
307
+ head_dim=head_dim,
308
+ is_causal=is_causal,
309
+ causal_type=CausalType.TopLeft,
310
+ atol=1e-3,
311
+ backend="natten",
312
+ )
313
+
314
+ @pytest.mark.L1
315
+ @skip_if_flash2_not_supported()
316
+ @skip_if_not_supported()
317
+ def test_compiled_flash2(self):
318
+ problem_sizes = [
319
+ (1, 4, 128, [128], [128]),
320
+ (1, 1, 128, [128], [1024]),
321
+ (1, 1, 128, [128], [13568]),
322
+ (1, 1, 128, [128], [13496]),
323
+ (1, 1, 32, [128], [13496]),
324
+ (1, 1, 32, [32], [13496]),
325
+ (3, 1, 32, [77], [8504]),
326
+ (1, 1, 32, [77], [8504]),
327
+ (1, 1, 64, [40], [12296]),
328
+ (1, 2, 64, [40], [12296]),
329
+ (1, 2, 64, [40], [12296]),
330
+ (1, 1, 128, [128], [128]),
331
+ (6, 1, 128, [128, 128, 135, 121, 128, 128], [128, 128, 135, 121, 128, 128]),
332
+ (5, 1, 128, [128, 128, 135, 128, 128], [128, 128, 135, 128, 128]),
333
+ (2, 1, 128, [135, 200], [128, 768]),
334
+ (2, 1, 128, [1024, 200], [128, 768]),
335
+ (2, 1, 128, [135, 200], [135, 768]),
336
+ (2, 1, 128, [1024, 200], [135, 768]),
337
+ (2, 1, 128, [1024, 256], [128, 768]),
338
+ (4, 1, 128, [1024, 8, 17, 2048], [10, 20, 512, 16]),
339
+ (3, 2, 128, [268, 1584, 1571], [2448, 4088, 1925]),
340
+ (2, 1, 128, [1024, 256], [512, 768]),
341
+ ]
342
+ for (
343
+ batch,
344
+ num_heads,
345
+ head_dim,
346
+ seqlens_Q,
347
+ seqlens_KV,
348
+ ) in problem_sizes:
349
+ for is_causal in [False, True]:
350
+ self._test_module(
351
+ batch=batch,
352
+ seqlens_Q=seqlens_Q,
353
+ seqlens_KV=seqlens_KV,
354
+ num_heads=num_heads,
355
+ head_dim=head_dim,
356
+ is_causal=is_causal,
357
+ causal_type=CausalType.BottomRight,
358
+ atol=1e-3,
359
+ backend="flash2",
360
+ )
361
+
362
+
363
+ if __name__ == "__main__":
364
+ torch.manual_seed(42)
365
+ unittest.main()
REGEN-main/cosmos_policy/_src/imaginaire/attention/tests/varlen_test.py ADDED
@@ -0,0 +1,711 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ SDPA unit tests.
21
+ """
22
+
23
+ import random
24
+ import unittest
25
+ from functools import partial
26
+
27
+ import pytest
28
+ import torch
29
+
30
+ from cosmos_policy._src.imaginaire.attention import attention as i4_attention
31
+ from cosmos_policy._src.imaginaire.attention.flash2 import FLASH2_SUPPORTED
32
+ from cosmos_policy._src.imaginaire.attention.flash3 import FLASH3_SUPPORTED
33
+ from cosmos_policy._src.imaginaire.attention.masks import CausalType
34
+ from cosmos_policy._src.imaginaire.attention.natten import NATTEN_SUPPORTED
35
+ from cosmos_policy._src.imaginaire.attention.utils import is_blackwell_dc, is_fp8, is_hopper
36
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
37
+
38
+ RAND_SWEEP_TESTS = 1000
39
+
40
+ skip_if_natten_not_supported = partial(
41
+ pytest.mark.skipif,
42
+ not NATTEN_SUPPORTED,
43
+ reason="NATTEN is disabled, not available, or too old in this environment.",
44
+ )
45
+
46
+ skip_if_flash2_not_supported = partial(
47
+ pytest.mark.skipif,
48
+ not FLASH2_SUPPORTED,
49
+ reason="Flash2 is disabled, not available, or too old in this environment.",
50
+ )
51
+
52
+ skip_if_flash3_not_supported = partial(
53
+ pytest.mark.skipif,
54
+ not FLASH3_SUPPORTED,
55
+ reason="Flash3 is disabled, not available, or too old in this environment.",
56
+ )
57
+
58
+ # Tests are only enabled on Hopper and Blackwell DC-class for now.
59
+ # Will extend to other arches as we integrate more backends.
60
+ skip_if_not_supported = partial(
61
+ pytest.mark.skipif,
62
+ not is_blackwell_dc() and not is_hopper(),
63
+ reason="SDPA tests are only allowed for Hopper and Blackwell DC-class GPUs for now.",
64
+ )
65
+
66
+ skip_if_not_blackwell = partial(
67
+ pytest.mark.skipif, not is_blackwell_dc(), reason="This test is only allowed for Blackwell DC-class GPUs."
68
+ )
69
+
70
+ skip_if_not_hopper = partial(pytest.mark.skipif, not is_hopper(), reason="This test is only allowed for Hopper GPUs.")
71
+
72
+
73
+ def _reset_everything():
74
+ torch.manual_seed(42)
75
+ torch.cuda.empty_cache()
76
+
77
+
78
+ # Computes varlen by breaking up into individual attention calls
79
+ def compute_split_reference(
80
+ batch: int,
81
+ heads: int,
82
+ head_dim: int,
83
+ seqlens_Q_list: list[int],
84
+ seqlens_KV_list: list[int],
85
+ is_causal: bool,
86
+ causal_type: CausalType | None,
87
+ backend: str,
88
+ test_backward: bool,
89
+ dtype: torch.dtype = torch.float32,
90
+ heads_kv: int | None = None,
91
+ head_dim_v: int | None = None,
92
+ backend_kwargs: dict | None = None,
93
+ ):
94
+ heads_kv = heads_kv or heads
95
+ head_dim_v = head_dim_v or head_dim
96
+
97
+ assert len(seqlens_Q_list) == len(seqlens_KV_list) == batch
98
+
99
+ seqlen_q_total = sum(seqlens_Q_list)
100
+ seqlen_kv_total = sum(seqlens_KV_list)
101
+ dtype_safe = torch.float16
102
+ with torch.no_grad():
103
+ q_ref, k_ref, v_ref, d_out_ref = (
104
+ torch.randn((1, seqlen_q_total, heads, head_dim), device="cuda", dtype=dtype_safe).to(dtype),
105
+ torch.randn(
106
+ (1, seqlen_kv_total, heads_kv, head_dim),
107
+ device="cuda",
108
+ dtype=dtype_safe,
109
+ ).to(dtype),
110
+ torch.randn(
111
+ (1, seqlen_kv_total, heads_kv, head_dim_v),
112
+ device="cuda",
113
+ dtype=dtype_safe,
114
+ ).to(dtype),
115
+ torch.randn((1, seqlen_q_total, heads, head_dim_v), device="cuda", dtype=dtype_safe).to(dtype),
116
+ )
117
+ q, k, v, d_out = (
118
+ q_ref.clone(),
119
+ k_ref.clone(),
120
+ v_ref.clone(),
121
+ d_out_ref.clone(),
122
+ )
123
+
124
+ out_list = []
125
+ lse_list = []
126
+ d_q_list = []
127
+ d_k_list = []
128
+ d_v_list = []
129
+
130
+ q_start, kv_start = 0, 0
131
+ for b in range(batch):
132
+ seqlen_q = seqlens_Q_list[b]
133
+ seqlen_kv = seqlens_KV_list[b]
134
+
135
+ q_ = q_ref[:, q_start : q_start + seqlen_q, :, :].clone()
136
+ k_ = k_ref[:, kv_start : kv_start + seqlen_kv, :, :].clone()
137
+ v_ = v_ref[:, kv_start : kv_start + seqlen_kv, :, :].clone()
138
+
139
+ if test_backward:
140
+ q_ = q_.requires_grad_(True)
141
+ k_ = k_.requires_grad_(True)
142
+ v_ = v_.requires_grad_(True)
143
+ d_out_ = d_out_ref[:, q_start : q_start + seqlen_q, :, :].clone().requires_grad_(True)
144
+
145
+ out_, lse_ = i4_attention(
146
+ q_,
147
+ k_,
148
+ v_,
149
+ is_causal=is_causal,
150
+ causal_type=causal_type,
151
+ backend=backend,
152
+ backend_kwargs=backend_kwargs,
153
+ return_lse=True,
154
+ )
155
+
156
+ if test_backward:
157
+ out_.backward(d_out_)
158
+
159
+ with torch.no_grad():
160
+ out_list.append(out_.data.clone().float())
161
+ lse_list.append(lse_.data.clone().float())
162
+ if test_backward:
163
+ assert q_.grad is not None
164
+ assert k_.grad is not None
165
+ assert v_.grad is not None
166
+ d_q_list.append(q_.grad.clone().float())
167
+ d_k_list.append(k_.grad.clone().float())
168
+ d_v_list.append(v_.grad.clone().float())
169
+
170
+ q_start += seqlen_q
171
+ kv_start += seqlen_kv
172
+
173
+ assert q_start == seqlen_q_total
174
+ assert kv_start == seqlen_kv_total
175
+
176
+ out_ref = torch.cat(out_list, dim=1)
177
+ lse_ref = torch.cat(lse_list, dim=1)
178
+ assert out_ref.shape[:3] == q_ref.shape[:3]
179
+ dq_ref = None
180
+ dk_ref = None
181
+ dv_ref = None
182
+ if test_backward:
183
+ dq_ref = torch.cat(d_q_list, dim=1)
184
+ dk_ref = torch.cat(d_k_list, dim=1)
185
+ dv_ref = torch.cat(d_v_list, dim=1)
186
+
187
+ assert dq_ref.shape == q_ref.shape
188
+ assert dk_ref.shape == k_ref.shape
189
+ assert dv_ref.shape == v_ref.shape
190
+
191
+ return (q, k, v, d_out), (out_ref, lse_ref, dq_ref, dk_ref, dv_ref)
192
+
193
+
194
+ class VarlenTest(unittest.TestCase):
195
+ def setUp(self):
196
+ _reset_everything()
197
+
198
+ def tearDown(self):
199
+ _reset_everything()
200
+
201
+ def _test_against_manual_varlen(
202
+ self,
203
+ batch: int,
204
+ heads: int,
205
+ head_dim: int,
206
+ seqlens_Q_list: list[int],
207
+ seqlens_KV_list: list[int],
208
+ is_causal: bool,
209
+ causal_type: CausalType | None,
210
+ dtype: torch.dtype,
211
+ atol_fwd: tuple[float, float],
212
+ atol_bwd: tuple[float, float, float] | None,
213
+ backend: str,
214
+ reference_backend: str,
215
+ test_backward: bool,
216
+ heads_kv: int | None = None,
217
+ head_dim_v: int | None = None,
218
+ reference_backend_kwargs: dict | None = None,
219
+ backend_kwargs: dict | None = None,
220
+ ):
221
+ heads_kv = heads_kv or heads
222
+ head_dim_v = head_dim_v or head_dim
223
+
224
+ log.debug(
225
+ f"Testing varlen ({backend}) against manual varlen ({reference_backend}): "
226
+ f"{batch=}, {heads=}, {heads_kv=}, {head_dim=}, {head_dim_v=}, "
227
+ f"{seqlens_Q_list=}, {seqlens_KV_list=}, {is_causal=}, {causal_type=}, {dtype=}."
228
+ )
229
+
230
+ inputs, reference = compute_split_reference(
231
+ batch=batch,
232
+ heads=heads,
233
+ heads_kv=heads_kv,
234
+ head_dim=head_dim,
235
+ head_dim_v=head_dim_v,
236
+ seqlens_Q_list=seqlens_Q_list,
237
+ seqlens_KV_list=seqlens_KV_list,
238
+ is_causal=is_causal,
239
+ causal_type=causal_type,
240
+ dtype=dtype,
241
+ backend=reference_backend,
242
+ backend_kwargs=reference_backend_kwargs,
243
+ test_backward=test_backward,
244
+ )
245
+
246
+ q, k, v, d_out = inputs
247
+ out_ref, lse_ref, dq_ref, dk_ref, dv_ref = reference
248
+ q = q.to(dtype)
249
+ k = k.to(dtype)
250
+ v = v.to(dtype)
251
+ d_out = d_out.to(dtype)
252
+
253
+ # Run target
254
+ if test_backward:
255
+ q.requires_grad_(test_backward)
256
+ k.requires_grad_(test_backward)
257
+ v.requires_grad_(test_backward)
258
+ d_out.requires_grad_(test_backward)
259
+
260
+ seqlens_Q = torch.tensor(seqlens_Q_list, dtype=torch.int32, device=q.device)
261
+ seqlens_KV = torch.tensor(seqlens_KV_list, dtype=torch.int32, device=q.device)
262
+
263
+ out_, lse_ = i4_attention(
264
+ q,
265
+ k,
266
+ v,
267
+ is_causal=is_causal,
268
+ causal_type=causal_type,
269
+ backend=backend,
270
+ return_lse=True,
271
+ seqlens_Q=seqlens_Q,
272
+ seqlens_KV=seqlens_KV,
273
+ backend_kwargs=backend_kwargs,
274
+ )
275
+ out = out_.float()
276
+ lse = lse_.float()
277
+
278
+ if test_backward:
279
+ dq, dk, dv = None, None, None
280
+ out_.backward(d_out)
281
+ with torch.no_grad():
282
+ dq, dk, dv = (
283
+ q.grad.clone().float(),
284
+ k.grad.clone().float(),
285
+ v.grad.clone().float(),
286
+ )
287
+
288
+ atol_out, atol_lse = atol_fwd
289
+ assert out.shape == out_ref.shape
290
+
291
+ torch.testing.assert_close(out, out_ref, atol=atol_out, rtol=0)
292
+ torch.testing.assert_close(lse, lse_ref, atol=atol_lse, rtol=0)
293
+
294
+ if test_backward:
295
+ assert atol_bwd is not None
296
+ atol_dq, atol_dk, atol_dv = atol_bwd
297
+ torch.testing.assert_close(dq, dq_ref, atol=atol_dq, rtol=0)
298
+ torch.testing.assert_close(dk, dk_ref, atol=atol_dk, rtol=0)
299
+ torch.testing.assert_close(dv, dv_ref, atol=atol_dv, rtol=0)
300
+
301
+ def _test_natten_varlen(
302
+ self,
303
+ batch: int,
304
+ heads: int,
305
+ head_dim: int,
306
+ seqlens_Q_list: list[int],
307
+ seqlens_KV_list: list[int],
308
+ is_causal: bool,
309
+ head_dim_v: int | None = None,
310
+ heads_kv: int | None = None,
311
+ ):
312
+ torch.set_default_device("cuda")
313
+
314
+ # We're testing against the same backend and same dtype,
315
+ # but with varlen implemented as multiple kernel calls, so
316
+ # error thresholds should be much smaller here.
317
+ # This is therefore only a test of the varlen functionality.
318
+ # Correctness per dtype is expected to be verified in the main
319
+ # fmha tests.
320
+ # dQ still needs a more relaxed threshold because of the non-determinism
321
+ ALLOWED_DTYPES = [
322
+ # dtype, (atol_out, atol_lse), (atol_dq, atol_dk, atol_dv)
323
+ (torch.float16, (1e-6, 1e-6), (1e-2, 1e-6, 1e-6)),
324
+ (torch.bfloat16, (1e-6, 1e-6), (1e-2, 1e-6, 1e-6)),
325
+ ]
326
+
327
+ if is_blackwell_dc():
328
+ ALLOWED_DTYPES += [
329
+ (torch.float8_e4m3fn, (1e-6, 1e-6), None),
330
+ (torch.float8_e5m2, (1e-6, 1e-6), None),
331
+ ]
332
+
333
+ # NOTE: Hopper FMHA does not support varlen, so natten falls back
334
+ # to cutlass-fmha, which means the reference may target hopper-fmha,
335
+ # while the varlen target is cutlass-fmha, and this will throw off the
336
+ # error limits.
337
+ backend_kwargs = None
338
+ if is_hopper():
339
+ backend_kwargs = {"backend": "cutlass-fmha"}
340
+
341
+ for dtype, atol_fwd, atol_bwd in ALLOWED_DTYPES:
342
+ self._test_against_manual_varlen(
343
+ batch=batch,
344
+ heads=heads,
345
+ heads_kv=heads_kv,
346
+ head_dim=head_dim,
347
+ head_dim_v=head_dim_v,
348
+ seqlens_Q_list=seqlens_Q_list,
349
+ seqlens_KV_list=seqlens_KV_list,
350
+ is_causal=is_causal,
351
+ causal_type=CausalType.TopLeft, # Top-left is the only supported mask in natten (for now)
352
+ dtype=dtype,
353
+ atol_fwd=atol_fwd,
354
+ atol_bwd=atol_bwd,
355
+ backend="natten",
356
+ reference_backend="natten",
357
+ backend_kwargs=backend_kwargs,
358
+ reference_backend_kwargs=backend_kwargs,
359
+ test_backward=not is_fp8(dtype),
360
+ )
361
+
362
+ def _test_flash2_varlen(
363
+ self,
364
+ batch: int,
365
+ heads: int,
366
+ head_dim: int,
367
+ seqlens_Q_list: list[int],
368
+ seqlens_KV_list: list[int],
369
+ is_causal: bool,
370
+ head_dim_v: int | None = None,
371
+ heads_kv: int | None = None,
372
+ ):
373
+ torch.set_default_device("cuda")
374
+
375
+ # we can't quite pull the same trick as in natten -- apparently the kernel
376
+ # configs for varlen and non-varlen cases are very different.
377
+ # Setting deterministic=True doesn't seem to help either
378
+ backend_kwargs = None
379
+ # backend_kwargs = {"deterministic": True}
380
+ ALLOWED_DTYPES = [
381
+ # dtype, (atol_out, atol_lse), (atol_dq, atol_dk, atol_dv)
382
+ (torch.float16, (1e-2, 1e-2), (1e-1, 1e-2, 1e-2)),
383
+ (torch.bfloat16, (1e-1, 1e-2), (1e-1, 1e-1, 1e-1)),
384
+ ]
385
+
386
+ for dtype, atol_fwd, atol_bwd in ALLOWED_DTYPES:
387
+ self._test_against_manual_varlen(
388
+ batch=batch,
389
+ heads=heads,
390
+ heads_kv=heads_kv,
391
+ head_dim=head_dim,
392
+ head_dim_v=head_dim_v,
393
+ seqlens_Q_list=seqlens_Q_list,
394
+ seqlens_KV_list=seqlens_KV_list,
395
+ is_causal=is_causal,
396
+ causal_type=CausalType.BottomRight, # Bottom-right is the only supported mask in flash2
397
+ dtype=dtype,
398
+ atol_fwd=atol_fwd,
399
+ atol_bwd=atol_bwd,
400
+ backend="flash2",
401
+ reference_backend="flash2",
402
+ backend_kwargs=backend_kwargs,
403
+ reference_backend_kwargs=backend_kwargs,
404
+ test_backward=True,
405
+ )
406
+
407
+ def _test_flash3_varlen(
408
+ self,
409
+ batch: int,
410
+ heads: int,
411
+ head_dim: int,
412
+ seqlens_Q_list: list[int],
413
+ seqlens_KV_list: list[int],
414
+ is_causal: bool,
415
+ head_dim_v: int | None = None,
416
+ heads_kv: int | None = None,
417
+ ):
418
+ torch.set_default_device("cuda")
419
+
420
+ # We're testing against the same backend and same dtype,
421
+ # but with varlen implemented as multiple kernel calls, so
422
+ # error thresholds should be much smaller here.
423
+ # This is therefore only a test of the varlen functionality.
424
+ # Correctness per dtype is expected to be verified in the main
425
+ # fmha tests.
426
+ # dQ still needs a more relaxed threshold because of the non-determinism
427
+ ALLOWED_DTYPES = [
428
+ # dtype, (atol_out, atol_lse), (atol_dq, atol_dk, atol_dv)
429
+ (torch.float16, (1e-6, 1e-6), (1e-2, 1e-6, 1e-6)),
430
+ (torch.bfloat16, (1e-6, 1e-6), (1e-2, 1e-6, 1e-6)),
431
+ ]
432
+ backend_kwargs = None
433
+
434
+ # GQA/MQA introduce some extra non determinism (possibly due to extra reduction step?)
435
+ if heads_kv is not None and heads != heads_kv:
436
+ ALLOWED_DTYPES = [
437
+ # dtype, (atol_out, atol_lse), (atol_dq, atol_dk, atol_dv)
438
+ (torch.float16, (1e-6, 1e-6), (1e-2, 1e-1, 1e-1)),
439
+ (torch.bfloat16, (1e-6, 1e-6), (1e-2, 1e-1, 1e-1)),
440
+ ]
441
+ backend_kwargs = {"deterministic": True}
442
+
443
+ for dtype, atol_fwd, atol_bwd in ALLOWED_DTYPES:
444
+ self._test_against_manual_varlen(
445
+ batch=batch,
446
+ heads=heads,
447
+ heads_kv=heads_kv,
448
+ head_dim=head_dim,
449
+ head_dim_v=head_dim_v,
450
+ seqlens_Q_list=seqlens_Q_list,
451
+ seqlens_KV_list=seqlens_KV_list,
452
+ is_causal=is_causal,
453
+ causal_type=CausalType.BottomRight, # Bottom-right is the only supported mask in flash3
454
+ dtype=dtype,
455
+ atol_fwd=atol_fwd,
456
+ atol_bwd=atol_bwd,
457
+ backend="flash3",
458
+ reference_backend="flash3",
459
+ backend_kwargs=backend_kwargs,
460
+ reference_backend_kwargs=backend_kwargs,
461
+ test_backward=True,
462
+ )
463
+
464
+ def _test_varlen(
465
+ self,
466
+ batch: int,
467
+ heads: int,
468
+ head_dim: int,
469
+ seqlens_Q_list: list[int],
470
+ seqlens_KV_list: list[int],
471
+ is_causal: bool,
472
+ backend: str,
473
+ head_dim_v: int | None = None,
474
+ heads_kv: int | None = None,
475
+ ):
476
+ if backend == "natten":
477
+ self._test_natten_varlen(
478
+ batch=batch,
479
+ heads=heads,
480
+ heads_kv=heads_kv,
481
+ head_dim=head_dim,
482
+ head_dim_v=head_dim_v,
483
+ seqlens_Q_list=seqlens_Q_list,
484
+ seqlens_KV_list=seqlens_KV_list,
485
+ is_causal=is_causal,
486
+ )
487
+ elif backend == "flash2":
488
+ self._test_flash2_varlen(
489
+ batch=batch,
490
+ heads=heads,
491
+ heads_kv=heads_kv,
492
+ head_dim=head_dim,
493
+ head_dim_v=head_dim_v,
494
+ seqlens_Q_list=seqlens_Q_list,
495
+ seqlens_KV_list=seqlens_KV_list,
496
+ is_causal=is_causal,
497
+ )
498
+ elif backend == "flash3":
499
+ self._test_flash3_varlen(
500
+ batch=batch,
501
+ heads=heads,
502
+ heads_kv=heads_kv,
503
+ head_dim=head_dim,
504
+ head_dim_v=head_dim_v,
505
+ seqlens_Q_list=seqlens_Q_list,
506
+ seqlens_KV_list=seqlens_KV_list,
507
+ is_causal=is_causal,
508
+ )
509
+ else:
510
+ raise NotImplementedError()
511
+
512
+ def _test_varlen_randsweep(self, backend: str, max_tests: int = 1000):
513
+ random.seed(42)
514
+
515
+ max_seqlen = 2**17
516
+ for i in range(max_tests):
517
+ batch = random.choice(range(1, 12))
518
+
519
+ supports_gqa_mqa = False
520
+ if backend == "natten":
521
+ head_dim_choices = [32, 64, 128]
522
+ heads_choices = range(1, 8 + 1)
523
+ # GQA/MQA is only supported in NATTEN's Blackwell FMHA backend for now
524
+ supports_gqa_mqa = is_blackwell_dc()
525
+ elif backend in ["flash2", "flash3"]:
526
+ head_dim_choices = range(16, 256 + 1, 8)
527
+ heads_choices = range(1, 8 + 1)
528
+ supports_gqa_mqa = True
529
+ else:
530
+ raise NotImplementedError()
531
+
532
+ heads = random.choice(heads_choices)
533
+ heads_kv = (
534
+ heads
535
+ if not supports_gqa_mqa
536
+ else random.choice([1] + [i for i in range(1, heads + 1) if heads % i == 0])
537
+ )
538
+ assert heads >= heads_kv and heads % heads_kv == 0
539
+
540
+ head_dim = random.choice(head_dim_choices)
541
+ head_dim_v = None
542
+
543
+ seqlens_Q_list = []
544
+ seqlens_KV_list = []
545
+ for i in range(batch):
546
+ max_q = min(2**12, max(max_seqlen - sum(seqlens_Q_list), 24))
547
+ max_k = min(2**12, max(max_seqlen - sum(seqlens_KV_list), 24))
548
+ new_q = random.choice(range(8, max_q, 1))
549
+ new_k = random.choice(range(8, max_k, 1))
550
+ seqlens_Q_list.append(new_q)
551
+ seqlens_KV_list.append(new_k)
552
+
553
+ for is_causal in [False, True]:
554
+ self._test_varlen(
555
+ batch=batch,
556
+ heads=heads,
557
+ heads_kv=heads_kv,
558
+ head_dim=head_dim,
559
+ head_dim_v=head_dim_v,
560
+ seqlens_Q_list=seqlens_Q_list,
561
+ seqlens_KV_list=seqlens_KV_list,
562
+ is_causal=is_causal,
563
+ backend=backend,
564
+ )
565
+
566
+ @pytest.mark.L1
567
+ @skip_if_natten_not_supported()
568
+ @skip_if_not_supported()
569
+ def test_natten_varlen_fast(self):
570
+ problem_sizes = [
571
+ (
572
+ 9,
573
+ 4,
574
+ 128,
575
+ [2669, 2240, 910, 2421, 3323, 34, 3308, 2867, 1401],
576
+ [2880, 1726, 1847, 1147, 3568, 3116, 661, 1739, 1146],
577
+ ),
578
+ (6, 1, 128, [128, 128, 135, 121, 128, 128], [128, 128, 135, 121, 128, 128]),
579
+ (5, 1, 128, [128, 128, 135, 128, 128], [128, 128, 135, 128, 128]),
580
+ (2, 1, 128, [135, 200], [128, 768]),
581
+ (2, 1, 128, [1024, 200], [128, 768]),
582
+ (2, 1, 128, [135, 200], [135, 768]),
583
+ (2, 1, 128, [1024, 200], [135, 768]),
584
+ (2, 1, 128, [1024, 256], [128, 768]),
585
+ (4, 1, 128, [1024, 8, 17, 2048], [10, 20, 512, 16]),
586
+ (3, 2, 128, [268, 1584, 1571], [2448, 4088, 1925]),
587
+ (2, 1, 128, [1024, 256], [512, 768]),
588
+ ]
589
+ for (
590
+ batch,
591
+ heads,
592
+ head_dim,
593
+ seqlens_Q_list,
594
+ seqlens_KV_list,
595
+ ) in problem_sizes:
596
+ for is_causal in [False, True]:
597
+ self._test_varlen(
598
+ batch=batch,
599
+ heads=heads,
600
+ head_dim=head_dim,
601
+ seqlens_Q_list=seqlens_Q_list,
602
+ seqlens_KV_list=seqlens_KV_list,
603
+ is_causal=is_causal,
604
+ backend="natten",
605
+ )
606
+
607
+ @pytest.mark.L1
608
+ @skip_if_natten_not_supported()
609
+ @skip_if_not_supported()
610
+ def test_natten_varlen_randsweep(self):
611
+ self._test_varlen_randsweep(backend="natten", max_tests=RAND_SWEEP_TESTS)
612
+
613
+ @pytest.mark.L1
614
+ @skip_if_flash2_not_supported()
615
+ @skip_if_not_supported()
616
+ def test_flash2_varlen_fast(self):
617
+ problem_sizes = [
618
+ (
619
+ 9,
620
+ 4,
621
+ 128,
622
+ [2669, 2240, 910, 2421, 3323, 34, 3308, 2867, 1401],
623
+ [2880, 1726, 1847, 1147, 3568, 3116, 661, 1739, 1146],
624
+ ),
625
+ (6, 1, 128, [128, 128, 135, 121, 128, 128], [128, 128, 135, 121, 128, 128]),
626
+ (5, 1, 128, [128, 128, 135, 128, 128], [128, 128, 135, 128, 128]),
627
+ (2, 1, 128, [135, 200], [128, 768]),
628
+ (2, 1, 128, [1024, 200], [128, 768]),
629
+ (2, 1, 128, [135, 200], [135, 768]),
630
+ (2, 1, 128, [1024, 200], [135, 768]),
631
+ (2, 1, 128, [1024, 256], [128, 768]),
632
+ (4, 1, 128, [1024, 8, 17, 2048], [10, 20, 512, 16]),
633
+ (3, 2, 128, [268, 1584, 1571], [2448, 4088, 1925]),
634
+ (2, 1, 128, [1024, 256], [512, 768]),
635
+ ]
636
+ for (
637
+ batch,
638
+ heads,
639
+ head_dim,
640
+ seqlens_Q_list,
641
+ seqlens_KV_list,
642
+ ) in problem_sizes:
643
+ for is_causal in [False, True]:
644
+ self._test_varlen(
645
+ batch=batch,
646
+ heads=heads,
647
+ head_dim=head_dim,
648
+ seqlens_Q_list=seqlens_Q_list,
649
+ seqlens_KV_list=seqlens_KV_list,
650
+ is_causal=is_causal,
651
+ backend="flash2",
652
+ )
653
+
654
+ @pytest.mark.L1
655
+ @skip_if_flash2_not_supported()
656
+ @skip_if_not_supported()
657
+ def test_flash2_varlen_randsweep(self):
658
+ self._test_varlen_randsweep(backend="flash2", max_tests=RAND_SWEEP_TESTS)
659
+
660
+ @pytest.mark.L1
661
+ @skip_if_flash3_not_supported()
662
+ @skip_if_not_hopper()
663
+ def test_flash3_varlen_fast(self):
664
+ problem_sizes = [
665
+ (
666
+ 9,
667
+ 4,
668
+ 128,
669
+ [2669, 2240, 910, 2421, 3323, 34, 3308, 2867, 1401],
670
+ [2880, 1726, 1847, 1147, 3568, 3116, 661, 1739, 1146],
671
+ ),
672
+ (6, 1, 128, [128, 128, 135, 121, 128, 128], [128, 128, 135, 121, 128, 128]),
673
+ (5, 1, 128, [128, 128, 135, 128, 128], [128, 128, 135, 128, 128]),
674
+ (2, 1, 128, [135, 200], [128, 768]),
675
+ (2, 1, 128, [1024, 200], [128, 768]),
676
+ (2, 1, 128, [135, 200], [135, 768]),
677
+ (2, 1, 128, [1024, 200], [135, 768]),
678
+ (2, 1, 128, [1024, 256], [128, 768]),
679
+ (4, 1, 128, [1024, 8, 17, 2048], [10, 20, 512, 16]),
680
+ (3, 2, 128, [268, 1584, 1571], [2448, 4088, 1925]),
681
+ (2, 1, 128, [1024, 256], [512, 768]),
682
+ ]
683
+ for (
684
+ batch,
685
+ heads,
686
+ head_dim,
687
+ seqlens_Q_list,
688
+ seqlens_KV_list,
689
+ ) in problem_sizes:
690
+ for is_causal in [False, True]:
691
+ self._test_varlen(
692
+ batch=batch,
693
+ heads=heads,
694
+ head_dim=head_dim,
695
+ seqlens_Q_list=seqlens_Q_list,
696
+ seqlens_KV_list=seqlens_KV_list,
697
+ is_causal=is_causal,
698
+ backend="flash3",
699
+ )
700
+
701
+ @pytest.mark.L1
702
+ @skip_if_flash3_not_supported()
703
+ @skip_if_not_hopper()
704
+ def test_flash3_varlen_randsweep(self):
705
+ self._test_varlen_randsweep(backend="flash3", max_tests=RAND_SWEEP_TESTS)
706
+
707
+
708
+ if __name__ == "__main__":
709
+ random.seed(42)
710
+ torch.manual_seed(42)
711
+ unittest.main()
REGEN-main/cosmos_policy/_src/imaginaire/attention/utils/__init__.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Utilities: compute capability detection, helpers, and more.
21
+ """
22
+
23
+ from typing import Any
24
+
25
+ import torch
26
+
27
+ from cosmos_policy._src.imaginaire.attention.utils import safe_log as log
28
+ from cosmos_policy._src.imaginaire.attention.utils.environment import is_torch_compiling
29
+
30
+
31
+ def get_arch_tag(device: torch.device | None = None) -> int:
32
+ """
33
+ Returns the compute capability of a given torch device if it's a CUDA device, otherwise returns 0.
34
+
35
+ Args:
36
+ device (torch.device | None): torch device. Uses default device if None.
37
+
38
+ Returns:
39
+ device_cc (int): compute capability in the SmXXX format (i.e. 90 for Hopper).
40
+ """
41
+ if torch.cuda.is_available() and torch.version.cuda and (device is None or device.type == "cuda"):
42
+ major, minor = torch.cuda.get_device_capability(device)
43
+ return major * 10 + minor
44
+ return 0
45
+
46
+
47
+ def log_or_raise_error(msg: str, raise_error: bool = False, exception: Any = RuntimeError):
48
+ if raise_error:
49
+ raise exception(msg)
50
+ else:
51
+ log.debug(msg)
52
+
53
+
54
+ def is_full(dtype: torch.dtype) -> bool:
55
+ return dtype == torch.float32
56
+
57
+
58
+ def is_half(dtype: torch.dtype) -> bool:
59
+ return dtype in [torch.float16, torch.bfloat16]
60
+
61
+
62
+ def is_fp8(dtype: torch.dtype) -> bool:
63
+ return dtype in [torch.float8_e5m2, torch.float8_e4m3fn]
64
+
65
+
66
+ def is_hopper(device: torch.device | None = None) -> bool:
67
+ return get_arch_tag(device) == 90
68
+
69
+
70
+ def is_blackwell_dc(device: torch.device | None = None) -> bool:
71
+ return get_arch_tag(device) in [100, 103]
72
+
73
+
74
+ __all__ = [
75
+ "get_arch_tag",
76
+ "log_or_raise_error",
77
+ "is_full",
78
+ "is_half",
79
+ "is_fp8",
80
+ "is_hopper",
81
+ "is_blackwell_dc",
82
+ "is_torch_compiling",
83
+ ]
REGEN-main/cosmos_policy/_src/imaginaire/attention/utils/environment.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Environment-related utilities.
21
+ """
22
+
23
+ import torch
24
+
25
+ from cosmos_policy._src.imaginaire.utils import log
26
+
27
+
28
+ # Controls all regions guarded against torch compile
29
+ # Logs, and certain assertions cause graph breaks.
30
+ def is_torch_compiling() -> bool:
31
+ try:
32
+ return torch.compiler.is_compiling()
33
+ except Exception as e:
34
+ log.exception(f"Exception occurred checking whether in torch compiled region: {e}")
35
+ # Assume too old to support torch compile
36
+ return False
REGEN-main/cosmos_policy/_src/imaginaire/attention/utils/safe_log.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Safe logging utilities: logging should be disabled when in a torch.compiled
21
+ region.
22
+ """
23
+
24
+ from cosmos_policy._src.imaginaire.attention.utils.environment import is_torch_compiling
25
+ from cosmos_policy._src.imaginaire.utils import log
26
+
27
+
28
+ def trace(message: str, rank0_only: bool = True) -> None:
29
+ if not is_torch_compiling():
30
+ log.trace(message=message, rank0_only=rank0_only)
31
+
32
+
33
+ def debug(message: str, rank0_only: bool = True) -> None:
34
+ if not is_torch_compiling():
35
+ log.debug(message=message, rank0_only=rank0_only)
36
+
37
+
38
+ def info(message: str, rank0_only: bool = True) -> None:
39
+ if not is_torch_compiling():
40
+ log.info(message=message, rank0_only=rank0_only)
41
+
42
+
43
+ def success(message: str, rank0_only: bool = True) -> None:
44
+ if not is_torch_compiling():
45
+ log.success(message=message, rank0_only=rank0_only)
46
+
47
+
48
+ def warning(message: str, rank0_only: bool = True) -> None:
49
+ if not is_torch_compiling():
50
+ log.warning(message=message, rank0_only=rank0_only)
51
+
52
+
53
+ def error(message: str, rank0_only: bool = True) -> None:
54
+ if not is_torch_compiling():
55
+ log.critical(message=message, rank0_only=rank0_only)
56
+
57
+
58
+ def critical(message: str, rank0_only: bool = True) -> None:
59
+ if not is_torch_compiling():
60
+ log.critical(message=message, rank0_only=rank0_only)
61
+
62
+
63
+ def exception(message: str, rank0_only: bool = True) -> None:
64
+ if not is_torch_compiling():
65
+ log.exception(message=message, rank0_only=rank0_only)
REGEN-main/cosmos_policy/_src/imaginaire/attention/varlen.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ Imaginaire4 Attention Subpackage:
18
+ Unified implementation for all Attention implementations.
19
+
20
+ Varlen utilities
21
+ """
22
+
23
+ import torch
24
+ from torch import Tensor
25
+
26
+ from cosmos_policy._src.imaginaire.attention.utils import is_torch_compiling
27
+
28
+
29
+ def generate_varlen_parameters(
30
+ query: Tensor,
31
+ key: Tensor,
32
+ value: Tensor,
33
+ seqlens_Q: Tensor | None = None,
34
+ seqlens_KV: Tensor | None = None,
35
+ ) -> tuple[None, None, int, int] | tuple[Tensor, Tensor, int, int]:
36
+ # NOTE: max_seqlen_{Q,KV} require a device-host sync, since they're expected to be ints (with
37
+ # which we launch the varlen kernel) and not device tensors.
38
+ # .item() introduces control flow and breaks the graph.
39
+ # It is also inefficient to repeat this per-op, and mostly there for convenience.
40
+ # generate_varlen_parameters should ideally always be called by the user ahead of model
41
+ # forward / backward.
42
+ if is_torch_compiling():
43
+ raise RuntimeError(
44
+ "Running 'generate_varlen_parameters' in a torch-compiled region is disallowed as it "
45
+ "results in graph breaks. Please consider calling ahead of time and pass "
46
+ "'cumulative_seqlen_{Q,KV}' and 'max_seqlen_{Q,KV}' instead of 'seqlens_{Q,KV}' to "
47
+ "'attention'. "
48
+ )
49
+
50
+ if query.shape[0] != key.shape[0] or query.shape[0] != value.shape[0]:
51
+ raise ValueError(
52
+ f"Q, K, and V must match in batch size, got {query.shape[0]=}, {key.shape[0]=}, {value.shape[0]=}."
53
+ )
54
+
55
+ if (seqlens_Q is None) ^ (seqlens_KV is None):
56
+ raise ValueError(
57
+ "Variable length Attention requires both of seqlens_Q and seqlens_KV to be set, got "
58
+ f"{seqlens_Q=}, {seqlens_KV=}."
59
+ )
60
+
61
+ if seqlens_Q is None and seqlens_KV is None:
62
+ # Not varlen
63
+ return None, None, 0, 0
64
+
65
+ assert seqlens_Q is not None
66
+ assert seqlens_KV is not None
67
+
68
+ if not isinstance(seqlens_Q, Tensor) or not isinstance(seqlens_KV, Tensor):
69
+ raise ValueError("seqlens_Q and seqlens_KV must both be tensors.")
70
+
71
+ if seqlens_Q.device != query.device or seqlens_KV.device != query.device:
72
+ raise ValueError(
73
+ "seqlens_Q and seqlens_KV must be on the same device as QKV, but "
74
+ f"{seqlens_Q.device=}, {seqlens_KV.device=}, {query.device=}."
75
+ )
76
+
77
+ if seqlens_Q.dtype != torch.int32 or seqlens_KV.dtype != torch.int32:
78
+ raise ValueError(
79
+ f"seqlens_Q and seqlens_KV must both be torch.int32 tensors, got {seqlens_Q.dtype=}, {seqlens_KV.dtype=}."
80
+ )
81
+
82
+ if seqlens_Q.dim() != 1 or seqlens_KV.dim() != 1:
83
+ raise ValueError(
84
+ f"seqlens_Q and seqlens_KV must both be 1-D tensors, got {seqlens_Q.dim()=}, {seqlens_KV.dim()=}."
85
+ )
86
+
87
+ if seqlens_Q.shape[0] != seqlens_KV.shape[0]:
88
+ raise ValueError(f"seqlens_Q and seqlens_KV must match in size, got {seqlens_Q.shape=}, {seqlens_KV.shape=}.")
89
+
90
+ if seqlens_Q.shape[0] < 1:
91
+ raise ValueError(
92
+ f"seqlens_Q and seqlens_KV must contain at least one element, got {seqlens_Q.shape=}, {seqlens_KV.shape=}."
93
+ )
94
+
95
+ if query.shape[0] != 1:
96
+ raise ValueError(
97
+ f"Variable length attention only supports sequence-packed memory layout (batch = 1), got {query.shape[0]=}."
98
+ )
99
+
100
+ assert seqlens_Q.dim() == seqlens_KV.dim() == 1
101
+ assert seqlens_Q.shape[0] == seqlens_KV.shape[0] >= 1
102
+ assert seqlens_Q.dtype == seqlens_KV.dtype == torch.int32
103
+
104
+ max_seqlen_Q = seqlens_Q.max().item() # type: ignore
105
+ max_seqlen_KV = seqlens_KV.max().item() # type: ignore
106
+
107
+ # NOTE: we have to prepend with 0 manually :(
108
+ z = torch.tensor([0], dtype=torch.int32, device=seqlens_Q.device)
109
+ cumulative_seqlen_Q = torch.cat([z, seqlens_Q.cumsum(0).to(torch.int32)], dim=0)
110
+ cumulative_seqlen_KV = torch.cat([z, seqlens_KV.cumsum(0).to(torch.int32)], dim=0)
111
+
112
+ assert isinstance(max_seqlen_Q, int)
113
+ assert isinstance(max_seqlen_KV, int)
114
+
115
+ return (
116
+ cumulative_seqlen_Q,
117
+ cumulative_seqlen_KV,
118
+ max_seqlen_Q,
119
+ max_seqlen_KV,
120
+ )
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/blocklist.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import os
18
+ import re
19
+ import string
20
+ from difflib import SequenceMatcher
21
+
22
+ import nltk
23
+ from better_profanity import profanity
24
+
25
+ from cosmos_policy._src.imaginaire.auxiliary.guardrail.blocklist.utils import read_keyword_list_from_dir, to_ascii
26
+ from cosmos_policy._src.imaginaire.auxiliary.guardrail.common.core import (
27
+ GUARDRAIL1_CHECKPOINT_DIR,
28
+ ContentSafetyGuardrail,
29
+ GuardrailRunner,
30
+ )
31
+ from cosmos_policy._src.imaginaire.utils import log, misc
32
+
33
+ CENSOR = misc.Color.red("*")
34
+
35
+
36
+ class Blocklist(ContentSafetyGuardrail):
37
+ def __init__(
38
+ self,
39
+ guardrail_partial_match_min_chars: int = 6,
40
+ guardrail_partial_match_letter_count: float = 0.4,
41
+ ) -> None:
42
+ """Blocklist model for text filtering safety check.
43
+
44
+ Args:
45
+ checkpoint_dir (str): Path to the checkpoint directory.
46
+ guardrail_partial_match_min_chars (int, optional): Minimum number of characters in a word to check for partial match. Defaults to 6.
47
+ guardrail_partial_match_letter_count (float, optional): Maximum allowed difference in characters for partial match. Defaults to 0.4.
48
+ """
49
+ self.checkpoint_dir = os.path.join(GUARDRAIL1_CHECKPOINT_DIR, "blocklist")
50
+ nltk.data.path.append(os.path.join(self.checkpoint_dir, "nltk_data"))
51
+ self.lemmatizer = nltk.WordNetLemmatizer()
52
+ self.profanity = profanity
53
+ self.guardrail_partial_match_min_chars = guardrail_partial_match_min_chars
54
+ self.guardrail_partial_match_letter_count = guardrail_partial_match_letter_count
55
+
56
+ # Load blocklist and whitelist keywords
57
+ self.blocklist_words = read_keyword_list_from_dir(os.path.join(self.checkpoint_dir, "custom"))
58
+ self.whitelist_words = read_keyword_list_from_dir(os.path.join(self.checkpoint_dir, "whitelist"))
59
+ self.exact_match_words = read_keyword_list_from_dir(os.path.join(self.checkpoint_dir, "exact_match"))
60
+
61
+ self.profanity.load_censor_words(custom_words=self.blocklist_words, whitelist_words=self.whitelist_words)
62
+ log.debug(f"Loaded {len(self.blocklist_words)} words/phrases from blocklist")
63
+ log.debug(f"Whitelisted {len(self.whitelist_words)} words/phrases from whitelist")
64
+ log.debug(f"Loaded {len(self.exact_match_words)} exact match words/phrases from blocklist")
65
+
66
+ def uncensor_whitelist(self, input_prompt: str, censored_prompt: str) -> str:
67
+ """Explicitly uncensor words that are in the whitelist."""
68
+ input_words = input_prompt.split()
69
+ censored_words = censored_prompt.split()
70
+ whitelist_words = set(self.whitelist_words)
71
+ for i, token in enumerate(input_words):
72
+ if token.strip(string.punctuation).lower() in whitelist_words:
73
+ censored_words[i] = token
74
+ censored_prompt = " ".join(censored_words)
75
+ return censored_prompt
76
+
77
+ def censor_prompt(self, input_prompt: str) -> tuple[bool, str]:
78
+ """Censor the prompt using the blocklist with better-profanity fuzzy matching.
79
+
80
+ Args:
81
+ input_prompt: input prompt to censor
82
+
83
+ Returns:
84
+ bool: True if the prompt is blocked, False otherwise
85
+ str: A message indicating why the prompt was blocked
86
+ """
87
+ censored_prompt = self.profanity.censor(input_prompt, censor_char=CENSOR)
88
+ # Uncensor whitelisted words that were censored from blocklist fuzzy matching
89
+ censored_prompt = self.uncensor_whitelist(input_prompt, censored_prompt)
90
+ if CENSOR in censored_prompt:
91
+ return True, f"Prompt blocked by censorship: Censored Prompt: {censored_prompt}"
92
+ return False, ""
93
+
94
+ @staticmethod
95
+ def check_partial_match(
96
+ normalized_prompt: str, normalized_word: str, guardrail_partial_match_letter_count: float
97
+ ) -> tuple[bool, str]:
98
+ """
99
+ Check robustly if normalized word and the matching target have a difference of up to guardrail_partial_match_letter_count characters.
100
+
101
+ Args:
102
+ normalized_prompt: a string with many words
103
+ normalized_word: a string with one or multiple words, its length is smaller than normalized_prompt
104
+ guardrail_partial_match_letter_count: maximum allowed difference in characters (float to allow partial characters)
105
+
106
+ Returns:
107
+ bool: True if a match is found, False otherwise
108
+ str: A message indicating why the prompt was blocked
109
+ """
110
+ prompt_words = normalized_prompt.split()
111
+ word_length = len(normalized_word.split())
112
+ max_similarity_ratio = (len(normalized_word) - float(guardrail_partial_match_letter_count)) / float(
113
+ len(normalized_word)
114
+ )
115
+
116
+ seq_matcher = SequenceMatcher(None)
117
+ seq_matcher.set_seq2(normalized_word)
118
+
119
+ for i in range(len(prompt_words) - word_length + 1):
120
+ # Extract a substring from the prompt with the same number of words as the normalized_word
121
+ substring = " ".join(prompt_words[i : i + word_length])
122
+ seq_matcher.set_seq1(substring)
123
+
124
+ # real_quick_ratio and quick_ratio are faster than ratio and both serve as upper bound for similarity ratio.
125
+ # If they are less than max_similarity_ratio, it means that also the ratio will be less than max_similarity_ratio and we can skip the expensive ratio computation.
126
+ # This saves a lot of time because in practice the tested words are usually dissimilar.
127
+ # For details see: https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher
128
+ if (
129
+ seq_matcher.real_quick_ratio() < max_similarity_ratio
130
+ or seq_matcher.quick_ratio() < max_similarity_ratio
131
+ ):
132
+ continue
133
+
134
+ similarity_ratio = seq_matcher.ratio()
135
+ if similarity_ratio >= max_similarity_ratio:
136
+ return (
137
+ True,
138
+ f"Prompt blocked by partial match blocklist: Prompt: {normalized_prompt}, Partial Match Word: {normalized_word}",
139
+ )
140
+
141
+ return False, ""
142
+
143
+ @staticmethod
144
+ def check_against_whole_word_blocklist(
145
+ prompt: str,
146
+ blocklist: list[str],
147
+ guardrail_partial_match_min_chars: int = 6,
148
+ guardrail_partial_match_letter_count: float = 0.4,
149
+ ) -> tuple[bool, str]:
150
+ """
151
+ Check if the prompt contains any whole words from the blocklist.
152
+ The match is case insensitive and robust to multiple spaces between words.
153
+
154
+ Args:
155
+ prompt: input prompt to check
156
+ blocklist: list of words to check against
157
+ guardrail_partial_match_min_chars: minimum number of characters in a word to check for partial match
158
+ guardrail_partial_match_letter_count: maximum allowed difference in characters for partial match
159
+
160
+ Returns:
161
+ tuple[bool, str]: (True if a match is found, False otherwise), message indicating why the prompt was blocked
162
+ """
163
+ # Normalize spaces and convert to lowercase
164
+ normalized_prompt = re.sub(r"\s+", " ", prompt).strip().lower()
165
+
166
+ normalized_words_cache = set()
167
+
168
+ for word in blocklist:
169
+ # Normalize spaces and convert to lowercase for each blocklist word
170
+ normalized_word = re.sub(r"\s+", " ", word).strip().lower()
171
+
172
+ if normalized_word in normalized_words_cache:
173
+ continue
174
+
175
+ normalized_words_cache.add(normalized_word)
176
+
177
+ # Use word boundaries to ensure whole word match
178
+ if re.search(r"\b" + re.escape(normalized_word) + r"\b", normalized_prompt):
179
+ return True, f"Prompt blocked by exact match blocklist: Prompt: {prompt}, Exact Match Word: {word}"
180
+
181
+ # Roughly 3/4 of the time this function requires is spent on partial matching.
182
+ # We could use just one for loop to check both exact and partial matches but doing it in two loops is faster in practice
183
+ # because it delays the partial matching as long as possible with a chance of early exit due to exact match.
184
+ # Above we cache the normalized words and here we reuse them in the second loop for partial matching.
185
+
186
+ for normalized_word in normalized_words_cache:
187
+ # Check for partial match if the word is long enough
188
+ if len(normalized_word) >= guardrail_partial_match_min_chars:
189
+ match, message = Blocklist.check_partial_match(
190
+ normalized_prompt, normalized_word, guardrail_partial_match_letter_count
191
+ )
192
+ if match:
193
+ return True, message
194
+
195
+ return False, ""
196
+
197
+ def is_safe(self, input_prompt: str = "") -> tuple[bool, str]:
198
+ """Check if the input prompt is safe using the blocklist."""
199
+ # Check if the input is empty
200
+ if not input_prompt:
201
+ return False, "Input is empty"
202
+ input_prompt = to_ascii(input_prompt)
203
+
204
+ # Check full sentence for censored words
205
+ censored, message = self.censor_prompt(input_prompt)
206
+ if censored:
207
+ return False, message
208
+
209
+ # Check lemmatized words for censored words
210
+ tokens = nltk.word_tokenize(input_prompt)
211
+ lemmas = [self.lemmatizer.lemmatize(token) for token in tokens]
212
+ lemmatized_prompt = " ".join(lemmas)
213
+ censored, message = self.censor_prompt(lemmatized_prompt)
214
+ if censored:
215
+ return False, message
216
+
217
+ # Check for exact match blocklist words
218
+ censored, message = self.check_against_whole_word_blocklist(
219
+ input_prompt,
220
+ self.exact_match_words,
221
+ self.guardrail_partial_match_min_chars,
222
+ self.guardrail_partial_match_letter_count,
223
+ )
224
+ if censored:
225
+ return False, message
226
+
227
+ # If all these checks pass, the input is safe
228
+ return True, "Input is safe"
229
+
230
+
231
+ def parse_args():
232
+ parser = argparse.ArgumentParser()
233
+ parser.add_argument("--prompt", type=str, required=True, help="Input prompt")
234
+ return parser.parse_args()
235
+
236
+
237
+ def main(args):
238
+ blocklist = Blocklist()
239
+ runner = GuardrailRunner(safety_models=[blocklist])
240
+ with misc.timer("blocklist safety check"):
241
+ safety, message = runner.run_safety_check(args.prompt)
242
+ log.info(f"Input is: {'SAFE' if safety else 'UNSAFE'}")
243
+ log.info(f"Message: {message}") if not safety else None
244
+
245
+
246
+ if __name__ == "__main__":
247
+ args = parse_args()
248
+ main(args)
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/blocklist_test.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import pytest
17
+
18
+ from cosmos_policy._src.imaginaire.auxiliary.guardrail.blocklist.blocklist import Blocklist
19
+
20
+
21
+ @pytest.mark.L1
22
+ def test_exact_match():
23
+ """Test exact word matching."""
24
+ prompt = "this contains badword in the middle"
25
+ word = "badword"
26
+
27
+ match, message = Blocklist.check_partial_match(prompt, word, 0.4)
28
+
29
+ assert match is True
30
+ assert "badword" in message
31
+
32
+
33
+ @pytest.mark.L1
34
+ def test_no_match():
35
+ """Test when there's no match."""
36
+ prompt = "this is a clean prompt"
37
+ word = "badword"
38
+
39
+ match, message = Blocklist.check_partial_match(prompt, word, 0.4)
40
+
41
+ assert match is False
42
+ assert message == ""
43
+
44
+
45
+ @pytest.mark.L1
46
+ def test_partial_match_with_threshold():
47
+ """Test partial matching with character difference threshold."""
48
+ prompt = "this contains badw0rd here" # One character different
49
+ word = "badword"
50
+
51
+ # With threshold of 1.0 character difference, should match
52
+ match, _ = Blocklist.check_partial_match(prompt, word, 1.0)
53
+ assert match is True
54
+
55
+ # With threshold of 0.5 character difference, should not match
56
+ match, _ = Blocklist.check_partial_match(prompt, word, 0.5)
57
+ assert match is False
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/profile_blocklist.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import time
17
+
18
+ from cosmos_policy._src.imaginaire.auxiliary.guardrail.blocklist.blocklist import Blocklist
19
+ from cosmos_policy._src.imaginaire.auxiliary.guardrail.common.core import GuardrailRunner
20
+
21
+ # Test prompts
22
+ prompts = [
23
+ "Create a beautiful landscape",
24
+ "Generate a detailed cinematic scene of a bustling medieval marketplace with merchants selling colorful spices, fabrics hanging from wooden stalls, cobblestone streets filled with people in period clothing, warm golden hour lighting filtering through ancient stone buildings, and smoke rising from food vendors cooking over open fires",
25
+ "Create an image of Adele",
26
+ "lot of words" * 100 + "Create an image of Adele",
27
+ "lot of words" * 100 + "Create an image of Adeele",
28
+ "Make an image of someone getting hurt badly",
29
+ "Generate a disturbing scene with graphic violence showing people fighting brutally with weapons, blood splattered everywhere, gruesome injuries visible in high detail, screaming faces contorted in pain and terror, dark atmosphere with dramatic lighting emphasizing the carnage and destruction, bodies lying motionless on the ground surrounded by pools of crimson liquid",
30
+ "Show me a peaceful garden with flowers blooming in spring sunlight",
31
+ "Design a futuristic space station orbiting Earth with advanced technology, sleek metallic surfaces reflecting starlight, astronauts in cutting-edge spacesuits conducting research, multiple docking bays with various spacecraft, solar panels gleaming in the cosmic void, and Earth's blue marble visible in the background through massive observation windows",
32
+ ]
33
+
34
+ checkpoint_dir = "/path/to/your/checkpoint/dir" # Change this path
35
+
36
+ # Initialize
37
+ blocklist = Blocklist(checkpoint_dir=checkpoint_dir)
38
+ runner = GuardrailRunner(safety_models=[blocklist])
39
+
40
+ # Warm up
41
+ _ = runner.run_safety_check(prompts[0])
42
+
43
+
44
+ times = []
45
+ for prompt in prompts:
46
+ start = time.time()
47
+ safe, message = runner.run_safety_check(prompt)
48
+ end = time.time()
49
+
50
+ elapsed = end - start
51
+ times.append(elapsed)
52
+
53
+ print(f"Prompt: '{prompt[:50]}...'")
54
+ print(f"Safe: {safe}, Time: {elapsed:.4f}s")
55
+ if message:
56
+ print(f"Message: {message}")
57
+ print("-" * 40)
58
+
59
+ print(f"\nAverage time: {sum(times) / len(times):.4f}s")
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/blocklist/utils.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ import re
18
+
19
+ from cosmos_policy._src.imaginaire.utils import log
20
+
21
+
22
+ def read_keyword_list_from_dir(folder_path: str) -> list[str]:
23
+ """Read keyword list from all files in a folder."""
24
+ output_list = []
25
+ file_list = []
26
+ # Get list of files in the folder
27
+ for file in os.listdir(folder_path):
28
+ if os.path.isfile(os.path.join(folder_path, file)):
29
+ file_list.append(file)
30
+
31
+ # Process each file
32
+ for file in file_list:
33
+ file_path = os.path.join(folder_path, file)
34
+ try:
35
+ with open(file_path) as f:
36
+ output_list.extend([line.strip() for line in f.readlines()])
37
+ except Exception as e:
38
+ log.error(f"Error reading file {file}: {e!s}")
39
+
40
+ return output_list
41
+
42
+
43
+ def to_ascii(prompt: str) -> str:
44
+ """Convert prompt to ASCII."""
45
+ return re.sub(r"[^\x00-\x7F]+", " ", prompt)
REGEN-main/cosmos_policy/_src/imaginaire/auxiliary/guardrail/common/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.