fla-core 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fla/__init__.py +4 -0
- fla/modules/__init__.py +33 -0
- fla/modules/activations.py +548 -0
- fla/modules/convolution.py +1143 -0
- fla/modules/feature_map.py +300 -0
- fla/modules/fused_bitlinear.py +632 -0
- fla/modules/fused_cross_entropy.py +419 -0
- fla/modules/fused_kl_div.py +324 -0
- fla/modules/fused_linear_cross_entropy.py +620 -0
- fla/modules/fused_norm_gate.py +1253 -0
- fla/modules/grpo.py +411 -0
- fla/modules/l2norm.py +285 -0
- fla/modules/l2warp.py +38 -0
- fla/modules/layernorm.py +1433 -0
- fla/modules/layernorm_gated.py +528 -0
- fla/modules/mlp.py +132 -0
- fla/modules/parallel.py +42 -0
- fla/modules/rotary.py +500 -0
- fla/modules/token_shift.py +543 -0
- fla/ops/__init__.py +53 -0
- fla/ops/abc/__init__.py +7 -0
- fla/ops/abc/chunk.py +1117 -0
- fla/ops/abc/naive.py +96 -0
- fla/ops/attn/__init__.py +7 -0
- fla/ops/attn/decoding.py +182 -0
- fla/ops/attn/parallel.py +730 -0
- fla/ops/based/__init__.py +9 -0
- fla/ops/based/fused_chunk.py +373 -0
- fla/ops/based/naive.py +72 -0
- fla/ops/based/parallel.py +408 -0
- fla/ops/comba/__init__.py +7 -0
- fla/ops/comba/chunk.py +342 -0
- fla/ops/comba/fused_recurrent.py +332 -0
- fla/ops/comba/utils.py +172 -0
- fla/ops/comba/wy_fast.py +423 -0
- fla/ops/common/__init__.py +1 -0
- fla/ops/common/chunk_delta_h.py +527 -0
- fla/ops/common/chunk_h.py +384 -0
- fla/ops/common/chunk_h_parallel.py +551 -0
- fla/ops/common/chunk_h_split.py +596 -0
- fla/ops/common/chunk_o.py +681 -0
- fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
- fla/ops/common/fused_chunk.py +629 -0
- fla/ops/common/fused_recurrent.py +567 -0
- fla/ops/delta_rule/__init__.py +11 -0
- fla/ops/delta_rule/chunk.py +311 -0
- fla/ops/delta_rule/fused_chunk.py +6 -0
- fla/ops/delta_rule/fused_recurrent.py +535 -0
- fla/ops/delta_rule/naive.py +120 -0
- fla/ops/delta_rule/parallel.py +403 -0
- fla/ops/delta_rule/wy_fast.py +294 -0
- fla/ops/forgetting_attn/__init__.py +7 -0
- fla/ops/forgetting_attn/parallel.py +64 -0
- fla/ops/gated_delta_product/__init__.py +5 -0
- fla/ops/gated_delta_product/chunk.py +305 -0
- fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
- fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
- fla/ops/gated_delta_product/chunk_ref.py +68 -0
- fla/ops/gated_delta_product/naive.py +36 -0
- fla/ops/gated_delta_rule/__init__.py +7 -0
- fla/ops/gated_delta_rule/chunk.py +340 -0
- fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
- fla/ops/gated_delta_rule/wy_fast.py +296 -0
- fla/ops/generalized_delta_rule/__init__.py +9 -0
- fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
- fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
- fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
- fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
- fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
- fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
- fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
- fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
- fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
- fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
- fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
- fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
- fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
- fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
- fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
- fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
- fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
- fla/ops/gla/__init__.py +11 -0
- fla/ops/gla/chunk.py +1298 -0
- fla/ops/gla/fused_chunk.py +642 -0
- fla/ops/gla/fused_recurrent.py +111 -0
- fla/ops/gla/naive.py +41 -0
- fla/ops/gsa/__init__.py +9 -0
- fla/ops/gsa/chunk.py +1133 -0
- fla/ops/gsa/fused_recurrent.py +536 -0
- fla/ops/gsa/naive.py +69 -0
- fla/ops/hgrn/__init__.py +9 -0
- fla/ops/hgrn/chunk.py +282 -0
- fla/ops/hgrn/fused_recurrent.py +308 -0
- fla/ops/hgrn/naive.py +63 -0
- fla/ops/lightning_attn/__init__.py +9 -0
- fla/ops/lightning_attn/chunk.py +84 -0
- fla/ops/lightning_attn/fused_recurrent.py +84 -0
- fla/ops/linear_attn/__init__.py +11 -0
- fla/ops/linear_attn/chunk.py +76 -0
- fla/ops/linear_attn/fused_chunk.py +61 -0
- fla/ops/linear_attn/fused_recurrent.py +35 -0
- fla/ops/linear_attn/naive.py +64 -0
- fla/ops/linear_attn/utils.py +10 -0
- fla/ops/log_linear_attn/__init__.py +7 -0
- fla/ops/log_linear_attn/chunk.py +1904 -0
- fla/ops/log_linear_attn/naive.py +50 -0
- fla/ops/mesa_net/__init__.py +5 -0
- fla/ops/mesa_net/chunk.py +371 -0
- fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
- fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
- fla/ops/mesa_net/chunk_h_fwd.py +170 -0
- fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
- fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
- fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
- fla/ops/mesa_net/decoding_one_step.py +175 -0
- fla/ops/mesa_net/naive.py +131 -0
- fla/ops/nsa/__init__.py +9 -0
- fla/ops/nsa/compression.py +536 -0
- fla/ops/nsa/naive.py +103 -0
- fla/ops/nsa/parallel.py +879 -0
- fla/ops/nsa/utils.py +92 -0
- fla/ops/path_attn/__init__.py +7 -0
- fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
- fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
- fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
- fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
- fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
- fla/ops/path_attn/parallel.py +270 -0
- fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
- fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
- fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
- fla/ops/path_attn/parallel_path_fwd.py +195 -0
- fla/ops/path_attn/prepare_k_cache.py +74 -0
- fla/ops/path_attn/transform_q.py +108 -0
- fla/ops/rebased/__init__.py +7 -0
- fla/ops/rebased/naive.py +27 -0
- fla/ops/rebased/parallel.py +464 -0
- fla/ops/retention/__init__.py +13 -0
- fla/ops/retention/chunk.py +77 -0
- fla/ops/retention/fused_chunk.py +78 -0
- fla/ops/retention/fused_recurrent.py +33 -0
- fla/ops/retention/naive.py +15 -0
- fla/ops/retention/parallel.py +71 -0
- fla/ops/rwkv4/__init__.py +7 -0
- fla/ops/rwkv4/fused_recurrent.py +472 -0
- fla/ops/rwkv6/__init__.py +9 -0
- fla/ops/rwkv6/chunk.py +1300 -0
- fla/ops/rwkv6/chunk_naive.py +43 -0
- fla/ops/rwkv6/fused_recurrent.py +673 -0
- fla/ops/rwkv6/recurrent_naive.py +103 -0
- fla/ops/rwkv7/__init__.py +10 -0
- fla/ops/rwkv7/channel_mixing.py +323 -0
- fla/ops/rwkv7/chunk.py +78 -0
- fla/ops/rwkv7/fused_addcmul.py +293 -0
- fla/ops/rwkv7/fused_k_update.py +346 -0
- fla/ops/rwkv7/fused_recurrent.py +334 -0
- fla/ops/rwkv7/gate_output_correction.py +244 -0
- fla/ops/simple_gla/__init__.py +13 -0
- fla/ops/simple_gla/chunk.py +303 -0
- fla/ops/simple_gla/fused_chunk.py +108 -0
- fla/ops/simple_gla/fused_recurrent.py +112 -0
- fla/ops/simple_gla/naive.py +114 -0
- fla/ops/simple_gla/parallel.py +722 -0
- fla/ops/titans/__init__.py +7 -0
- fla/ops/titans/log_impl.py +153 -0
- fla/ops/titans/naive.py +375 -0
- fla/ops/ttt/__init__.py +9 -0
- fla/ops/ttt/chunk.py +1441 -0
- fla/ops/ttt/fused_chunk.py +831 -0
- fla/ops/ttt/naive.py +126 -0
- fla/ops/utils/__init__.py +58 -0
- fla/ops/utils/constant.py +6 -0
- fla/ops/utils/cumsum.py +465 -0
- fla/ops/utils/index.py +133 -0
- fla/ops/utils/logcumsumexp.py +52 -0
- fla/ops/utils/logsumexp.py +80 -0
- fla/ops/utils/matmul.py +245 -0
- fla/ops/utils/op.py +62 -0
- fla/ops/utils/pack.py +208 -0
- fla/ops/utils/pooling.py +207 -0
- fla/ops/utils/softmax.py +106 -0
- fla/ops/utils/solve_tril.py +381 -0
- fla/utils.py +462 -0
- fla_core-0.3.2.dist-info/METADATA +575 -0
- fla_core-0.3.2.dist-info/RECORD +188 -0
- fla_core-0.3.2.dist-info/WHEEL +5 -0
- fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
- fla_core-0.3.2.dist-info/top_level.txt +1 -0
fla/utils.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import functools
|
|
5
|
+
import inspect
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import warnings
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
import triton
|
|
16
|
+
from packaging import version
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from fla import __version__
|
|
22
|
+
|
|
23
|
+
FLA_CI_ENV = os.getenv("FLA_CI_ENV") == "1"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@lru_cache(maxsize=1)
|
|
27
|
+
def check_environments():
|
|
28
|
+
"""
|
|
29
|
+
Checks the current operating system, Triton version, and Python version,
|
|
30
|
+
issuing warnings if they don't meet recommendations.
|
|
31
|
+
This function's body only runs once due to lru_cache.
|
|
32
|
+
"""
|
|
33
|
+
# Check Operating System
|
|
34
|
+
if sys.platform == 'win32':
|
|
35
|
+
logger.warning(
|
|
36
|
+
"Detected Windows operating system. Triton does not have an official Windows release, "
|
|
37
|
+
"thus FLA will not be adapted for Windows, and any potential errors will not be fixed. "
|
|
38
|
+
"Please consider using a Linux environment for compatibility."
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
triton_version = version.parse(triton.__version__)
|
|
42
|
+
required_triton_version = version.parse("3.2.0")
|
|
43
|
+
|
|
44
|
+
if triton_version < required_triton_version:
|
|
45
|
+
logger.warning(
|
|
46
|
+
f"Current Triton version {triton_version} is below the recommended 3.2.0 version. "
|
|
47
|
+
"Errors may occur and these issues will not be fixed. "
|
|
48
|
+
"Please consider upgrading Triton."
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Check Python version
|
|
52
|
+
py_version = version.parse(f"{sys.version_info.major}.{sys.version_info.minor}")
|
|
53
|
+
required_py_version = version.parse("3.11")
|
|
54
|
+
|
|
55
|
+
if py_version < required_py_version:
|
|
56
|
+
logger.warning(
|
|
57
|
+
f"Current Python version {py_version} is below the recommended 3.11 version. "
|
|
58
|
+
"It is recommended to upgrade to Python 3.11 or higher for the best experience."
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
check_environments()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_abs_err(x, y):
|
|
68
|
+
return (x.detach()-y.detach()).flatten().abs().max().item()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def get_err_ratio(x, y):
|
|
72
|
+
err = (x.detach()-y.detach()).flatten().square().mean().sqrt().item()
|
|
73
|
+
base = (x.detach()).flatten().square().mean().sqrt().item()
|
|
74
|
+
return err / (base + 1e-8)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def assert_close(prefix, ref, tri, ratio, warning=False, err_atol=1e-6):
|
|
78
|
+
abs_atol = get_abs_err(ref, tri)
|
|
79
|
+
msg = f"{prefix:>16} diff: {abs_atol:.6f} ratio: {get_err_ratio(ref, tri):.6f}"
|
|
80
|
+
logger.info(msg)
|
|
81
|
+
error_rate = get_err_ratio(ref, tri)
|
|
82
|
+
if abs_atol <= err_atol:
|
|
83
|
+
return
|
|
84
|
+
if warning or (FLA_CI_ENV and (error_rate < 0.01 or abs_atol <= 0.3)):
|
|
85
|
+
if error_rate > ratio:
|
|
86
|
+
warnings.warn(msg)
|
|
87
|
+
else:
|
|
88
|
+
assert error_rate < ratio, msg
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def tensor_cache(
|
|
92
|
+
fn: Callable[..., torch.Tensor]
|
|
93
|
+
) -> Callable[..., torch.Tensor]:
|
|
94
|
+
"""
|
|
95
|
+
A decorator that caches the most recent result of a function with tensor inputs.
|
|
96
|
+
|
|
97
|
+
This decorator will store the output of the decorated function for the most recent set of input tensors.
|
|
98
|
+
If the function is called again with the same input tensors, it will return the cached result.
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
fn (Callable[..., torch.Tensor]):
|
|
103
|
+
The function to be decorated. It should take tensor inputs and return tensor outputs.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
Callable[..., torch.Tensor]:
|
|
107
|
+
A wrapped version of the input function with single-entry caching.
|
|
108
|
+
"""
|
|
109
|
+
last_args: Optional[Tuple] = None
|
|
110
|
+
last_kwargs: Optional[Dict] = None
|
|
111
|
+
last_result: Any = None
|
|
112
|
+
|
|
113
|
+
@functools.wraps(fn)
|
|
114
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
115
|
+
nonlocal last_args, last_kwargs, last_result
|
|
116
|
+
|
|
117
|
+
if last_args is not None and last_kwargs is not None:
|
|
118
|
+
if len(args) == len(last_args) and len(kwargs) == len(last_kwargs):
|
|
119
|
+
if all(a is b for a, b in zip(args, last_args)) and \
|
|
120
|
+
all(k in last_kwargs and v is last_kwargs[k] for k, v in kwargs.items()):
|
|
121
|
+
return last_result
|
|
122
|
+
|
|
123
|
+
result = fn(*args, **kwargs)
|
|
124
|
+
last_args, last_kwargs, last_result = args, kwargs, result
|
|
125
|
+
return result
|
|
126
|
+
|
|
127
|
+
return wrapper
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def input_guard(
|
|
131
|
+
fn: Callable[..., torch.Tensor]
|
|
132
|
+
) -> Callable[..., torch.Tensor]:
|
|
133
|
+
"""
|
|
134
|
+
A decorator to make sure all input tensors are contiguous and set the device based on input tensors.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
@functools.wraps(fn)
|
|
138
|
+
def wrapper(*args, **kwargs):
|
|
139
|
+
contiguous_args = (i if not isinstance(i, torch.Tensor) else i.contiguous() for i in args)
|
|
140
|
+
contiguous_kwargs = {k: (v if not isinstance(v, torch.Tensor) else v.contiguous()) for k, v in kwargs.items()}
|
|
141
|
+
|
|
142
|
+
tensor = None
|
|
143
|
+
for arg in args:
|
|
144
|
+
if isinstance(arg, torch.Tensor):
|
|
145
|
+
tensor = arg
|
|
146
|
+
break
|
|
147
|
+
if tensor is None:
|
|
148
|
+
for value in kwargs.values():
|
|
149
|
+
if isinstance(value, torch.Tensor):
|
|
150
|
+
tensor = value
|
|
151
|
+
break
|
|
152
|
+
|
|
153
|
+
if tensor is not None:
|
|
154
|
+
ctx = custom_device_ctx(tensor.device.index)
|
|
155
|
+
else:
|
|
156
|
+
ctx = contextlib.nullcontext()
|
|
157
|
+
|
|
158
|
+
with ctx:
|
|
159
|
+
return fn(*contiguous_args, **contiguous_kwargs)
|
|
160
|
+
|
|
161
|
+
return wrapper
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
contiguous = input_guard
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def require_version(version, hint):
|
|
168
|
+
"""
|
|
169
|
+
Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
|
|
170
|
+
"""
|
|
171
|
+
def decorator(fn):
|
|
172
|
+
@functools.wraps(fn)
|
|
173
|
+
def wrapper(ctx, *args, **kwargs):
|
|
174
|
+
from transformers.utils.versions import require_version
|
|
175
|
+
require_version(version, hint)
|
|
176
|
+
return fn(ctx,
|
|
177
|
+
*(i if not isinstance(i, torch.Tensor) else i.contiguous() for i in args),
|
|
178
|
+
**{k: (v if not isinstance(v, torch.Tensor) else v.contiguous()) for k, v in kwargs.items()})
|
|
179
|
+
return wrapper
|
|
180
|
+
return decorator
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class Action(Enum):
|
|
184
|
+
NONE = "none"
|
|
185
|
+
NOTIFY = "notify"
|
|
186
|
+
NOTIFY_ALWAYS = "notify_always"
|
|
187
|
+
RAISE = "raise"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def deprecate_kwarg(
|
|
191
|
+
old_name: str,
|
|
192
|
+
version: str,
|
|
193
|
+
new_name: Optional[str] = None,
|
|
194
|
+
warn_if_greater_or_equal_version: bool = False,
|
|
195
|
+
raise_if_greater_or_equal_version: bool = False,
|
|
196
|
+
raise_if_both_names: bool = False,
|
|
197
|
+
additional_message: Optional[str] = None,
|
|
198
|
+
):
|
|
199
|
+
"""
|
|
200
|
+
Decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified.
|
|
201
|
+
|
|
202
|
+
This decorator allows you to:
|
|
203
|
+
- Notify users when a keyword argument is deprecated.
|
|
204
|
+
- Automatically replace deprecated keyword arguments with new ones.
|
|
205
|
+
- Raise an error if deprecated arguments are used, depending on the specified conditions.
|
|
206
|
+
|
|
207
|
+
By default, the decorator notifies the user about the deprecated argument while the `fla.__version__` < specified `version`
|
|
208
|
+
in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
old_name (`str`):
|
|
212
|
+
Name of the deprecated keyword argument.
|
|
213
|
+
version (`str`):
|
|
214
|
+
The version in which the keyword argument was (or will be) deprecated.
|
|
215
|
+
new_name (`Optional[str]`, *optional*):
|
|
216
|
+
The new name for the deprecated keyword argument.
|
|
217
|
+
If specified, the deprecated keyword argument will be replaced with this new name.
|
|
218
|
+
warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
|
|
219
|
+
Whether to show warning if current `fla` version is greater or equal to the deprecated version.
|
|
220
|
+
raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
|
|
221
|
+
Whether to raise `ValueError` if current `fla` version is greater or equal to the deprecated version.
|
|
222
|
+
raise_if_both_names (`bool`, *optional*, defaults to `False`):
|
|
223
|
+
Whether to raise `ValueError` if both deprecated and new keyword arguments are set.
|
|
224
|
+
additional_message (`Optional[str]`, *optional*):
|
|
225
|
+
An additional message to append to the default deprecation message.
|
|
226
|
+
|
|
227
|
+
Raises:
|
|
228
|
+
ValueError:
|
|
229
|
+
If `raise_if_greater_or_equal_version` is `True` and the current version >= the deprecated one,
|
|
230
|
+
or if `raise_if_both_names` is `True` and both old and new keyword arguments are provided.
|
|
231
|
+
|
|
232
|
+
Returns:
|
|
233
|
+
Callable:
|
|
234
|
+
A wrapped function that handles the deprecated keyword arguments according to the specified parameters.
|
|
235
|
+
|
|
236
|
+
Example usage with renaming argument:
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
@deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0")
|
|
240
|
+
def my_function(do_reduce_labels):
|
|
241
|
+
print(do_reduce_labels)
|
|
242
|
+
|
|
243
|
+
my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Example usage without renaming argument:
|
|
247
|
+
|
|
248
|
+
```python
|
|
249
|
+
@deprecate_kwarg("max_size", version="6.0.0")
|
|
250
|
+
def my_function(max_size):
|
|
251
|
+
print(max_size)
|
|
252
|
+
|
|
253
|
+
my_function(max_size=1333) # Will show a deprecation warning
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
"""
|
|
257
|
+
deprecated_version = version.parse(version)
|
|
258
|
+
current_version = version.parse(__version__)
|
|
259
|
+
is_greater_or_equal_version = current_version >= deprecated_version
|
|
260
|
+
|
|
261
|
+
if is_greater_or_equal_version:
|
|
262
|
+
version_message = f"and removed starting from version {version}"
|
|
263
|
+
else:
|
|
264
|
+
version_message = f"and will be removed in version {version}"
|
|
265
|
+
|
|
266
|
+
def wrapper(func):
|
|
267
|
+
# Required for better warning message
|
|
268
|
+
sig = inspect.signature(func)
|
|
269
|
+
function_named_args = set(sig.parameters.keys())
|
|
270
|
+
is_instance_method = "self" in function_named_args
|
|
271
|
+
is_class_method = "cls" in function_named_args
|
|
272
|
+
|
|
273
|
+
@functools.wraps(func)
|
|
274
|
+
def wrapped_func(*args, **kwargs):
|
|
275
|
+
# Get class + function name (just for better warning message)
|
|
276
|
+
func_name = func.__name__
|
|
277
|
+
if is_instance_method:
|
|
278
|
+
func_name = f"{args[0].__class__.__name__}.{func_name}"
|
|
279
|
+
elif is_class_method:
|
|
280
|
+
func_name = f"{args[0].__name__}.{func_name}"
|
|
281
|
+
|
|
282
|
+
minimum_action = Action.NONE
|
|
283
|
+
message = None
|
|
284
|
+
|
|
285
|
+
# deprecated kwarg and its new version are set for function call -> replace it with new name
|
|
286
|
+
if old_name in kwargs and new_name in kwargs:
|
|
287
|
+
minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS
|
|
288
|
+
message = (
|
|
289
|
+
f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. "
|
|
290
|
+
f"Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`."
|
|
291
|
+
)
|
|
292
|
+
kwargs.pop(old_name)
|
|
293
|
+
|
|
294
|
+
# only deprecated kwarg is set for function call -> replace it with new name
|
|
295
|
+
elif old_name in kwargs and new_name is not None and new_name not in kwargs:
|
|
296
|
+
minimum_action = Action.NOTIFY
|
|
297
|
+
message = (
|
|
298
|
+
f"`{old_name}` is deprecated {version_message} for `{func_name}`. "
|
|
299
|
+
f"Use `{new_name}` instead."
|
|
300
|
+
)
|
|
301
|
+
kwargs[new_name] = kwargs.pop(old_name)
|
|
302
|
+
|
|
303
|
+
# deprecated kwarg is not set for function call and new name is not specified -> just notify
|
|
304
|
+
elif old_name in kwargs:
|
|
305
|
+
minimum_action = Action.NOTIFY
|
|
306
|
+
message = f"`{old_name}` is deprecated {version_message} for `{func_name}`."
|
|
307
|
+
|
|
308
|
+
if message is not None and additional_message is not None:
|
|
309
|
+
message = f"{message} {additional_message}"
|
|
310
|
+
|
|
311
|
+
# update minimum_action if argument is ALREADY deprecated (current version >= deprecated version)
|
|
312
|
+
if is_greater_or_equal_version:
|
|
313
|
+
# change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified
|
|
314
|
+
# in case we want to raise error for already deprecated arguments
|
|
315
|
+
if raise_if_greater_or_equal_version and minimum_action != Action.NONE:
|
|
316
|
+
minimum_action = Action.RAISE
|
|
317
|
+
|
|
318
|
+
# change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE)
|
|
319
|
+
# in case we want to ignore notifications for already deprecated arguments
|
|
320
|
+
elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY:
|
|
321
|
+
minimum_action = Action.NONE
|
|
322
|
+
|
|
323
|
+
# raise error or notify user
|
|
324
|
+
if minimum_action == Action.RAISE:
|
|
325
|
+
raise ValueError(message)
|
|
326
|
+
elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS):
|
|
327
|
+
# DeprecationWarning is ignored by default, so we use FutureWarning instead
|
|
328
|
+
warnings.warn(message, FutureWarning, stacklevel=2)
|
|
329
|
+
|
|
330
|
+
return func(*args, **kwargs)
|
|
331
|
+
|
|
332
|
+
return wrapped_func
|
|
333
|
+
|
|
334
|
+
return wrapper
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def checkpoint(fn):
|
|
338
|
+
def wrapper(*args, **kwargs):
|
|
339
|
+
return torch.utils.checkpoint.checkpoint(fn, *args, **kwargs)
|
|
340
|
+
return wrapper
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@lru_cache(maxsize=None)
|
|
344
|
+
def check_pytorch_version(version_s: str = '2.4') -> bool:
|
|
345
|
+
return version.parse(torch.__version__) >= version.parse(version_s)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _cpu_device_warning():
|
|
349
|
+
warnings.warn(('Triton is not supported on current platform, roll back to CPU.'), stacklevel=1)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@lru_cache(maxsize=None)
|
|
353
|
+
def get_multiprocessor_count(tensor_idx: int = 0) -> int:
|
|
354
|
+
try:
|
|
355
|
+
return triton.runtime.driver.active.utils.get_device_properties(tensor_idx)['multiprocessor_count']
|
|
356
|
+
except BaseException:
|
|
357
|
+
# Maybe we use a NPU device.
|
|
358
|
+
if triton.runtime.driver.active.get_current_target().backend == 'npu':
|
|
359
|
+
return triton.runtime.driver.active.utils.get_device_properties(tensor_idx)['num_vectorcore']
|
|
360
|
+
else:
|
|
361
|
+
return 1
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
@lru_cache(maxsize=None)
|
|
365
|
+
def get_available_device() -> str:
|
|
366
|
+
try:
|
|
367
|
+
return triton.runtime.driver.active.get_current_target().backend
|
|
368
|
+
except BaseException:
|
|
369
|
+
_cpu_device_warning()
|
|
370
|
+
return 'cpu'
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def map_triton_backend_to_torch_device() -> str:
|
|
374
|
+
backend = get_available_device() # 'cuda' | 'hip' | 'xpu' | 'cpu' | ...
|
|
375
|
+
return {'cuda': 'cuda', 'hip': 'cuda', 'xpu': 'xpu'}.get(backend, backend)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
# For AMD GPUs, the triton backend is 'hip', while for Nvidia GPUs, the triton backend is 'cuda'.
|
|
379
|
+
# However, the torch backend is 'cuda' for both Nvidia and AMD GPUs.
|
|
380
|
+
# Therefore, we need to check the triton backend to determine the actual GPU vendor.
|
|
381
|
+
device = get_available_device() if get_available_device() != 'hip' else 'cuda'
|
|
382
|
+
device_torch_lib = getattr(torch, device)
|
|
383
|
+
device_platform = get_available_device()
|
|
384
|
+
device_name = map_triton_backend_to_torch_device()
|
|
385
|
+
|
|
386
|
+
is_amd = (device_platform == 'hip')
|
|
387
|
+
is_intel = (device_platform == 'xpu')
|
|
388
|
+
is_nvidia = (device_platform == 'cuda')
|
|
389
|
+
is_intel_alchemist = (is_intel and 'Intel(R) Arc(TM) A' in torch.xpu.get_device_name(0))
|
|
390
|
+
is_nvidia_hopper = (is_nvidia and ('NVIDIA H' in torch.cuda.get_device_name(0) or torch.cuda.get_device_capability()[0] >= 9))
|
|
391
|
+
use_cuda_graph = (is_nvidia and os.environ.get('FLA_USE_CUDA_GRAPH', '0') == '1')
|
|
392
|
+
|
|
393
|
+
# Nvidia Ampere or newer, haven't check AMD and intel yet.
|
|
394
|
+
is_tf32_supported = (is_nvidia and torch.cuda.get_device_capability(0)[0] >= 8)
|
|
395
|
+
is_gather_supported = hasattr(triton.language, 'gather')
|
|
396
|
+
is_tma_supported = (is_nvidia and torch.cuda.get_device_capability(0)[0] >= 9) \
|
|
397
|
+
and os.environ.get('FLA_NO_USE_TMA', '0') != '1' and \
|
|
398
|
+
(hasattr(triton.language, '_experimental_make_tensor_descriptor') or hasattr(triton.language, 'make_tensor_descriptor'))
|
|
399
|
+
|
|
400
|
+
if is_nvidia and not is_tf32_supported:
|
|
401
|
+
# Make old card happy, since triton will use tf32 by default.
|
|
402
|
+
# This is a workaround for old nvidia card.
|
|
403
|
+
os.environ['TRITON_F32_DEFAULT'] = 'ieee'
|
|
404
|
+
|
|
405
|
+
if is_tma_supported:
|
|
406
|
+
logger.info('TMA is supported, using TMA by default.')
|
|
407
|
+
|
|
408
|
+
def alloc_fn(size: int, alignment: int, stream: Optional[int]):
|
|
409
|
+
return torch.empty(size, device=torch.device(device_name, device_torch_lib.current_device()), dtype=torch.int8)
|
|
410
|
+
|
|
411
|
+
triton.set_allocator(alloc_fn)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def get_all_max_shared_mem():
|
|
415
|
+
try:
|
|
416
|
+
return [
|
|
417
|
+
triton.runtime.driver.active.utils.get_device_properties(i)['max_shared_mem']
|
|
418
|
+
for i in range(device_torch_lib.device_count())
|
|
419
|
+
]
|
|
420
|
+
except BaseException:
|
|
421
|
+
_cpu_device_warning()
|
|
422
|
+
return [-1]
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
class Backend(Enum):
|
|
426
|
+
ADA = 101376 # RTX 4090
|
|
427
|
+
AMPERE = 166912 # A100
|
|
428
|
+
HOPPER = 232448 # H100
|
|
429
|
+
DEFAULT = 102400 # Default
|
|
430
|
+
|
|
431
|
+
@classmethod
|
|
432
|
+
def get_shared_memory(cls, arch: str) -> int:
|
|
433
|
+
try:
|
|
434
|
+
return cls[arch.upper()].value
|
|
435
|
+
except KeyError:
|
|
436
|
+
return cls.DEFAULT.value
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
@lru_cache(maxsize=None)
|
|
440
|
+
def check_shared_mem(arch: str = "none", tensor_idx: int = 0) -> bool:
|
|
441
|
+
try:
|
|
442
|
+
device_shared_mem_list = get_all_max_shared_mem()
|
|
443
|
+
max_shared_memory = device_shared_mem_list[tensor_idx]
|
|
444
|
+
return max_shared_memory >= Backend.get_shared_memory(arch)
|
|
445
|
+
except Exception:
|
|
446
|
+
return False
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
if check_pytorch_version('2.4'):
|
|
450
|
+
device = 'cuda' if device == 'cpu' else device
|
|
451
|
+
autocast_custom_fwd = functools.partial(torch.amp.custom_fwd, device_type=device)
|
|
452
|
+
autocast_custom_bwd = functools.partial(torch.amp.custom_bwd, device_type=device)
|
|
453
|
+
|
|
454
|
+
def custom_device_ctx(index: int):
|
|
455
|
+
return device_torch_lib.device(index)
|
|
456
|
+
else:
|
|
457
|
+
assert device == 'cuda', 'Only cuda device is supported for PyTorch version < 2.4.0.'
|
|
458
|
+
autocast_custom_fwd = device_torch_lib.amp.custom_fwd
|
|
459
|
+
autocast_custom_bwd = device_torch_lib.amp.custom_bwd
|
|
460
|
+
|
|
461
|
+
def custom_device_ctx(index: int):
|
|
462
|
+
return torch.cuda.device(index)
|