liger-kernel 0.5.9__py3-none-any.whl → 0.6.0__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.
- liger_kernel/chunked_loss/__init__.py +1 -0
- liger_kernel/chunked_loss/cosine_similarity_loss.py +127 -0
- liger_kernel/chunked_loss/dpo_loss.py +1 -1
- liger_kernel/chunked_loss/functional.py +2 -0
- liger_kernel/chunked_loss/fused_linear_preference.py +0 -1
- liger_kernel/chunked_loss/jsd_loss.py +2 -2
- liger_kernel/ops/dyt.py +111 -179
- liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
- liger_kernel/ops/geglu.py +1 -1
- liger_kernel/ops/grpo_loss.py +310 -0
- liger_kernel/ops/multi_token_attention.py +207 -0
- liger_kernel/ops/rms_norm.py +265 -54
- liger_kernel/ops/softmax.py +201 -0
- liger_kernel/ops/sparsemax.py +179 -0
- liger_kernel/ops/swiglu.py +1 -1
- liger_kernel/transformers/__init__.py +8 -0
- liger_kernel/transformers/dyt.py +5 -3
- liger_kernel/transformers/fsdp.py +55 -0
- liger_kernel/transformers/functional.py +70 -0
- liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
- liger_kernel/transformers/grpo_loss.py +98 -0
- liger_kernel/transformers/model/gemma.py +25 -16
- liger_kernel/transformers/model/gemma2.py +27 -14
- liger_kernel/transformers/model/gemma3.py +62 -106
- liger_kernel/transformers/model/glm4.py +16 -13
- liger_kernel/transformers/model/llama.py +81 -18
- liger_kernel/transformers/model/llama4.py +108 -0
- liger_kernel/transformers/model/llava.py +95 -132
- liger_kernel/transformers/model/mistral.py +13 -14
- liger_kernel/transformers/model/mixtral.py +16 -15
- liger_kernel/transformers/model/mllama.py +16 -14
- liger_kernel/transformers/model/olmo2.py +16 -13
- liger_kernel/transformers/model/paligemma.py +8 -9
- liger_kernel/transformers/model/phi3.py +25 -16
- liger_kernel/transformers/model/qwen2.py +24 -15
- liger_kernel/transformers/model/qwen2_5_vl.py +41 -97
- liger_kernel/transformers/model/qwen2_vl.py +38 -106
- liger_kernel/transformers/model/qwen3.py +11 -9
- liger_kernel/transformers/model/qwen3_moe.py +132 -0
- liger_kernel/transformers/monkey_patch.py +424 -81
- liger_kernel/transformers/multi_token_attention.py +64 -0
- liger_kernel/transformers/rms_norm.py +40 -4
- liger_kernel/transformers/softmax.py +12 -0
- liger_kernel/transformers/sparsemax.py +16 -0
- liger_kernel/transformers/swiglu.py +21 -0
- liger_kernel/transformers/trainer/orpo_trainer.py +1 -53
- liger_kernel/utils.py +11 -0
- {liger_kernel-0.5.9.dist-info → liger_kernel-0.6.0.dist-info}/METADATA +41 -21
- liger_kernel-0.6.0.dist-info/RECORD +97 -0
- {liger_kernel-0.5.9.dist-info → liger_kernel-0.6.0.dist-info}/WHEEL +1 -1
- liger_kernel/transformers/gema3_rms.py +0 -8
- liger_kernel-0.5.9.dist-info/RECORD +0 -84
- {liger_kernel-0.5.9.dist-info → liger_kernel-0.6.0.dist-info}/licenses/LICENSE +0 -0
- {liger_kernel-0.5.9.dist-info → liger_kernel-0.6.0.dist-info}/licenses/NOTICE +0 -0
- {liger_kernel-0.5.9.dist-info → liger_kernel-0.6.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
from typing import Tuple
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
import triton
|
|
5
|
+
import triton.language as tl
|
|
6
|
+
|
|
7
|
+
from liger_kernel.ops.utils import calculate_settings
|
|
8
|
+
from liger_kernel.ops.utils import ensure_contiguous
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@triton.jit
|
|
12
|
+
def _sparsemax_forward_kernel(
|
|
13
|
+
x_ptr,
|
|
14
|
+
x_stride_row,
|
|
15
|
+
sorted_x_ptr,
|
|
16
|
+
sorted_x_stride_row,
|
|
17
|
+
o_ptr,
|
|
18
|
+
o_stride_row,
|
|
19
|
+
n_cols,
|
|
20
|
+
BLOCK_SIZE: tl.constexpr,
|
|
21
|
+
num_warps: tl.constexpr,
|
|
22
|
+
):
|
|
23
|
+
pid_row = tl.program_id(0)
|
|
24
|
+
ptr_x_data_row = x_ptr + pid_row * x_stride_row
|
|
25
|
+
ptr_sorted_x_data_row = sorted_x_ptr + pid_row * sorted_x_stride_row
|
|
26
|
+
ptr_output_row = o_ptr + pid_row * o_stride_row
|
|
27
|
+
|
|
28
|
+
offs = tl.arange(0, BLOCK_SIZE)
|
|
29
|
+
mask = offs < n_cols
|
|
30
|
+
|
|
31
|
+
z_sorted_block = tl.load(
|
|
32
|
+
ptr_sorted_x_data_row + offs,
|
|
33
|
+
mask=mask,
|
|
34
|
+
other=-float("inf"),
|
|
35
|
+
cache_modifier=".ca",
|
|
36
|
+
).to(tl.float32)
|
|
37
|
+
|
|
38
|
+
z_valid = tl.where(mask, z_sorted_block, 0.0)
|
|
39
|
+
cssv = tl.cumsum(z_valid, 0)
|
|
40
|
+
|
|
41
|
+
r = (offs + 1).to(tl.float32)
|
|
42
|
+
safe_r = tl.where(mask, r, 1.0)
|
|
43
|
+
|
|
44
|
+
t_vec = (cssv - 1.0) / safe_r
|
|
45
|
+
|
|
46
|
+
support = (z_sorted_block > t_vec) & mask
|
|
47
|
+
|
|
48
|
+
k_int = tl.sum(support.to(tl.int32), 0)
|
|
49
|
+
k_clamped_int = tl.maximum(k_int, 1)
|
|
50
|
+
k = k_clamped_int.to(tl.float32)
|
|
51
|
+
|
|
52
|
+
s = tl.sum(tl.where(support, z_sorted_block, 0.0), 0)
|
|
53
|
+
|
|
54
|
+
tau = (s - 1.0) / k
|
|
55
|
+
|
|
56
|
+
x_block = tl.load(
|
|
57
|
+
ptr_x_data_row + offs,
|
|
58
|
+
mask=mask,
|
|
59
|
+
other=0.0,
|
|
60
|
+
cache_modifier=".ca",
|
|
61
|
+
).to(tl.float32)
|
|
62
|
+
|
|
63
|
+
y = tl.maximum(x_block - tau, 0.0)
|
|
64
|
+
|
|
65
|
+
tl.store(
|
|
66
|
+
ptr_output_row + offs,
|
|
67
|
+
y.to(ptr_output_row.dtype.element_ty),
|
|
68
|
+
mask=mask,
|
|
69
|
+
cache_modifier=".cs",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@triton.jit
|
|
74
|
+
def _sparsemax_backward_kernel(
|
|
75
|
+
o_ptr, go_ptr, gi_ptr, stride, n_cols, BLOCK_SIZE: tl.constexpr, num_warps: tl.constexpr
|
|
76
|
+
):
|
|
77
|
+
row = tl.program_id(0)
|
|
78
|
+
o_row = o_ptr + row * stride
|
|
79
|
+
go_row = go_ptr + row * stride
|
|
80
|
+
gi_row = gi_ptr + row * stride
|
|
81
|
+
|
|
82
|
+
offs = tl.arange(0, BLOCK_SIZE)
|
|
83
|
+
|
|
84
|
+
supp_cnt = tl.zeros((), tl.float32)
|
|
85
|
+
go_sum = tl.zeros((), tl.float32)
|
|
86
|
+
|
|
87
|
+
for i in tl.range(0, tl.cdiv(n_cols, BLOCK_SIZE)):
|
|
88
|
+
offs_iter = i * BLOCK_SIZE + offs
|
|
89
|
+
mask_iter = offs_iter < n_cols
|
|
90
|
+
o_val = tl.load(o_row + offs_iter, mask=mask_iter, other=0.0, cache_modifier=".ca").to(tl.float32)
|
|
91
|
+
go_val = tl.load(go_row + offs_iter, mask=mask_iter, other=0.0).to(tl.float32)
|
|
92
|
+
supp = o_val > 0.0
|
|
93
|
+
go_sum += tl.sum(tl.where(supp, go_val, 0.0))
|
|
94
|
+
supp_cnt += tl.sum(supp.to(tl.float32))
|
|
95
|
+
|
|
96
|
+
for i in tl.range(0, tl.cdiv(n_cols, BLOCK_SIZE)):
|
|
97
|
+
offs_iter = i * BLOCK_SIZE + offs
|
|
98
|
+
mask_iter = offs_iter < n_cols
|
|
99
|
+
o_val = tl.load(o_row + offs_iter, mask=mask_iter, other=0.0, cache_modifier=".ca").to(tl.float32)
|
|
100
|
+
go_val = tl.load(go_row + offs_iter, mask=mask_iter, other=0.0).to(tl.float32)
|
|
101
|
+
supp = o_val > 0.0
|
|
102
|
+
gi_val = tl.where(
|
|
103
|
+
supp,
|
|
104
|
+
go_val - tl.cast(go_sum / tl.maximum(supp_cnt, 1e-6), gi_row.dtype.element_ty).to(tl.float32),
|
|
105
|
+
0.0,
|
|
106
|
+
)
|
|
107
|
+
tl.store(gi_row + offs_iter, gi_val.to(gi_row.dtype.element_ty), mask=mask_iter, cache_modifier=".wb")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _sparsemax_forward(x: torch.Tensor, dim: int) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
111
|
+
if dim < 0:
|
|
112
|
+
dim += x.dim()
|
|
113
|
+
x_sw = x.transpose(dim, -1).contiguous()
|
|
114
|
+
n_cols = x_sw.size(-1)
|
|
115
|
+
n_rows = x_sw.numel() // n_cols
|
|
116
|
+
x_flat = x_sw.view(n_rows, n_cols)
|
|
117
|
+
x_sorted_flat = torch.sort(x_flat.float(), dim=-1, descending=True).values
|
|
118
|
+
|
|
119
|
+
BLOCK_SIZE, num_warps = calculate_settings(n_cols)
|
|
120
|
+
out_flat = torch.empty_like(x_flat)
|
|
121
|
+
grid = (n_rows,)
|
|
122
|
+
_sparsemax_forward_kernel[grid](
|
|
123
|
+
x_flat,
|
|
124
|
+
x_flat.stride(0),
|
|
125
|
+
x_sorted_flat,
|
|
126
|
+
x_sorted_flat.stride(0),
|
|
127
|
+
out_flat,
|
|
128
|
+
out_flat.stride(0),
|
|
129
|
+
n_cols,
|
|
130
|
+
BLOCK_SIZE=BLOCK_SIZE,
|
|
131
|
+
num_warps=num_warps,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
y = out_flat.view_as(x_sw).transpose(dim, -1)
|
|
135
|
+
return y, out_flat
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _sparsemax_backward(
|
|
139
|
+
grad_out: torch.Tensor,
|
|
140
|
+
out_flat: torch.Tensor,
|
|
141
|
+
dim: int,
|
|
142
|
+
) -> torch.Tensor:
|
|
143
|
+
grad_sw = grad_out.transpose(dim, -1).contiguous()
|
|
144
|
+
n_cols = grad_sw.size(-1)
|
|
145
|
+
n_rows = grad_sw.numel() // n_cols
|
|
146
|
+
go_flat = grad_sw.view(n_rows, n_cols)
|
|
147
|
+
|
|
148
|
+
BLOCK_SIZE, num_warps = calculate_settings(n_cols)
|
|
149
|
+
dx_flat = torch.empty_like(go_flat)
|
|
150
|
+
grid = (n_rows,)
|
|
151
|
+
_sparsemax_backward_kernel[grid](
|
|
152
|
+
out_flat,
|
|
153
|
+
go_flat,
|
|
154
|
+
dx_flat,
|
|
155
|
+
out_flat.stride(0),
|
|
156
|
+
n_cols,
|
|
157
|
+
BLOCK_SIZE=BLOCK_SIZE,
|
|
158
|
+
num_warps=num_warps,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
dx = dx_flat.view_as(grad_sw).transpose(dim, -1)
|
|
162
|
+
return dx
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class LigerSparsemaxFunction(torch.autograd.Function):
|
|
166
|
+
@staticmethod
|
|
167
|
+
@ensure_contiguous
|
|
168
|
+
def forward(ctx, x: torch.Tensor, dim: int):
|
|
169
|
+
y, out_flat = _sparsemax_forward(x, dim)
|
|
170
|
+
ctx.save_for_backward(out_flat)
|
|
171
|
+
ctx.dim = dim
|
|
172
|
+
return y
|
|
173
|
+
|
|
174
|
+
@staticmethod
|
|
175
|
+
@ensure_contiguous
|
|
176
|
+
def backward(ctx, grad_out: torch.Tensor):
|
|
177
|
+
(out_flat,) = ctx.saved_tensors
|
|
178
|
+
dx = _sparsemax_backward(grad_out, out_flat, ctx.dim)
|
|
179
|
+
return dx, None
|
liger_kernel/ops/swiglu.py
CHANGED
|
@@ -26,7 +26,7 @@ def _swiglu_forward_kernel(a_ptr, b_ptr, c_ptr, stride, n_cols: tl.constexpr, BL
|
|
|
26
26
|
# sigmoid requires type float32
|
|
27
27
|
a_row = tl.load(a_ptr + col_offsets, mask=mask, other=0).to(tl.float32)
|
|
28
28
|
b_row = tl.load(b_ptr + col_offsets, mask=mask, other=0)
|
|
29
|
-
c_row = silu(a_row) * b_row
|
|
29
|
+
c_row = silu(a_row).cast(b_row.dtype) * b_row
|
|
30
30
|
tl.store(c_ptr + col_offsets, c_row, mask=mask)
|
|
31
31
|
|
|
32
32
|
|
|
@@ -14,6 +14,7 @@ from liger_kernel.transformers.rms_norm import LigerRMSNorm # noqa: F401
|
|
|
14
14
|
from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
|
|
15
15
|
from liger_kernel.transformers.swiglu import LigerBlockSparseTop2MLP # noqa: F401
|
|
16
16
|
from liger_kernel.transformers.swiglu import LigerPhi3SwiGLUMLP # noqa: F401
|
|
17
|
+
from liger_kernel.transformers.swiglu import LigerQwen3MoeSwiGLUMLP # noqa: F401
|
|
17
18
|
from liger_kernel.transformers.swiglu import LigerSwiGLUMLP # noqa: F401
|
|
18
19
|
from liger_kernel.transformers.tvd import LigerTVDLoss # noqa: F401
|
|
19
20
|
|
|
@@ -29,6 +30,7 @@ if TYPE_CHECKING:
|
|
|
29
30
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_glm4 # noqa: F401
|
|
30
31
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_granite # noqa: F401
|
|
31
32
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama # noqa: F401
|
|
33
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama4 # noqa: F401
|
|
32
34
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llava # noqa: F401
|
|
33
35
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mistral # noqa: F401
|
|
34
36
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mixtral # noqa: F401
|
|
@@ -40,6 +42,7 @@ if TYPE_CHECKING:
|
|
|
40
42
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_5_vl # noqa: F401
|
|
41
43
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_vl # noqa: F401
|
|
42
44
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3 # noqa: F401
|
|
45
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3_moe # noqa: F401
|
|
43
46
|
|
|
44
47
|
|
|
45
48
|
# Check if 'transformers' is installed
|
|
@@ -85,6 +88,7 @@ def __getattr__(name: str):
|
|
|
85
88
|
"apply_liger_kernel_to_granite",
|
|
86
89
|
"apply_liger_kernel_to_llama",
|
|
87
90
|
"apply_liger_kernel_to_llava",
|
|
91
|
+
"apply_liger_kernel_to_llama4",
|
|
88
92
|
"apply_liger_kernel_to_mistral",
|
|
89
93
|
"apply_liger_kernel_to_mixtral",
|
|
90
94
|
"apply_liger_kernel_to_mllama",
|
|
@@ -95,6 +99,7 @@ def __getattr__(name: str):
|
|
|
95
99
|
"apply_liger_kernel_to_qwen2_5_vl",
|
|
96
100
|
"apply_liger_kernel_to_qwen2_vl",
|
|
97
101
|
"apply_liger_kernel_to_qwen3",
|
|
102
|
+
"apply_liger_kernel_to_qwen3_moe",
|
|
98
103
|
}
|
|
99
104
|
|
|
100
105
|
if name in monkey_patch_symbols:
|
|
@@ -118,6 +123,7 @@ __all__ = [
|
|
|
118
123
|
"liger_rotary_pos_emb",
|
|
119
124
|
"LigerBlockSparseTop2MLP",
|
|
120
125
|
"LigerPhi3SwiGLUMLP",
|
|
126
|
+
"LigerQwen3MoeSwiGLUMLP",
|
|
121
127
|
"LigerSwiGLUMLP",
|
|
122
128
|
"LigerTVDLoss",
|
|
123
129
|
]
|
|
@@ -137,6 +143,7 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
137
143
|
"apply_liger_kernel_to_granite",
|
|
138
144
|
"apply_liger_kernel_to_llama",
|
|
139
145
|
"apply_liger_kernel_to_llava",
|
|
146
|
+
"apply_liger_kernel_to_llama4",
|
|
140
147
|
"apply_liger_kernel_to_mistral",
|
|
141
148
|
"apply_liger_kernel_to_mixtral",
|
|
142
149
|
"apply_liger_kernel_to_mllama",
|
|
@@ -147,5 +154,6 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
147
154
|
"apply_liger_kernel_to_qwen2_5_vl",
|
|
148
155
|
"apply_liger_kernel_to_qwen2_vl",
|
|
149
156
|
"apply_liger_kernel_to_qwen3",
|
|
157
|
+
"apply_liger_kernel_to_qwen3_moe",
|
|
150
158
|
]
|
|
151
159
|
)
|
liger_kernel/transformers/dyt.py
CHANGED
|
@@ -5,16 +5,18 @@ from liger_kernel.ops.dyt import LigerDyTFunction
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
class LigerDyT(nn.Module):
|
|
8
|
-
def __init__(self, hidden_size, init_alpha=0.5):
|
|
8
|
+
def __init__(self, hidden_size, beta=True, init_alpha=0.5):
|
|
9
9
|
super().__init__()
|
|
10
10
|
self.hidden_size = hidden_size
|
|
11
11
|
self.init_alpha = init_alpha
|
|
12
12
|
self.alpha = nn.Parameter(torch.ones(1) * init_alpha)
|
|
13
13
|
self.gamma = nn.Parameter(torch.ones(hidden_size))
|
|
14
|
-
self.beta =
|
|
14
|
+
self.beta = None
|
|
15
|
+
if beta:
|
|
16
|
+
self.beta = nn.Parameter(torch.zeros(hidden_size))
|
|
15
17
|
|
|
16
18
|
def forward(self, x):
|
|
17
19
|
return LigerDyTFunction.apply(x, self.alpha, self.gamma, self.beta)
|
|
18
20
|
|
|
19
21
|
def extra_repr(self):
|
|
20
|
-
return f"{self.hidden_size}, init_alpha={self.init_alpha}"
|
|
22
|
+
return f"{self.hidden_size}, init_alpha={self.init_alpha}, beta={self.beta}"
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
from typing import Callable
|
|
3
|
+
|
|
4
|
+
from torch.distributed.fsdp import FullyShardedDataParallel
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _FSDPForwardRedirection:
|
|
8
|
+
"""
|
|
9
|
+
Modified based on
|
|
10
|
+
https://github.com/Lightning-AI/pytorch-lightning/blob/d3f9c83d6efa4f1def36aa6c199600946cdb9117/src/lightning/pytorch/strategies/strategy.py#L601-L648
|
|
11
|
+
Redirect a method call through FullyShardedDataParallel.forward so that the FSDP module's root pre-forward and
|
|
12
|
+
post-forward can be properly executed around the method call.
|
|
13
|
+
This is needed in cases where we call a submodule of a FSDP module. For instance, when we want to call only
|
|
14
|
+
the `LlamaModel` part out of a FSDP-wrapped `LlamaForCausalLM` to get the hidden states without involving
|
|
15
|
+
GPU-memory-heavy `lm_head` and cross entropy computation, doing this directly (i.e. `model.model.forward()`)
|
|
16
|
+
will not work because the first `nn.Embedding` layer is not independently wrapped as a FSDP module (because of
|
|
17
|
+
the transformer-based wrapping policy), and not calling it through FSDP root module forward will not all-gather
|
|
18
|
+
its parameter, thus resulting in "RuntimeError: 'weight' must be 2-D" error. Similarly, if we want to call just
|
|
19
|
+
the `lm_head` part of a model, we need this trick too to properly get its params all-gathered.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __call__(
|
|
23
|
+
self,
|
|
24
|
+
wrapper_module: FullyShardedDataParallel,
|
|
25
|
+
method: Callable,
|
|
26
|
+
*args: Any,
|
|
27
|
+
**kwargs: Any,
|
|
28
|
+
):
|
|
29
|
+
"""Reroutes a method call through the `wrapper_module`'s `forward` method.
|
|
30
|
+
Args:
|
|
31
|
+
wrapper_module: The module that has `original_module` wrapped.
|
|
32
|
+
original_module: The module that was wrapped inside `wrapper_module`.
|
|
33
|
+
method_name: The name of the method that should be called on the `original_module` after inputs get
|
|
34
|
+
redirected through the `wrapper_module`'s `forward` method.
|
|
35
|
+
*args: The positional arguments to the method `method_name`. They will get passed to a patched
|
|
36
|
+
`forward` method instead.
|
|
37
|
+
**kwargs: The keyword arguments to the method `method_name`. They will get passed to a patched
|
|
38
|
+
`forward` method instead.
|
|
39
|
+
"""
|
|
40
|
+
assert isinstance(wrapper_module, FullyShardedDataParallel)
|
|
41
|
+
original_module = wrapper_module._fsdp_wrapped_module
|
|
42
|
+
original_forward = original_module.forward
|
|
43
|
+
|
|
44
|
+
def wrapped_forward(*_args: Any, **_kwargs: Any) -> Any:
|
|
45
|
+
# Unpatch ourselves immediately before calling the method `method_name`
|
|
46
|
+
# because itself may want to call the real `forward`
|
|
47
|
+
original_module.forward = original_forward # type: ignore[method-assign]
|
|
48
|
+
# Call the actual method e.g. `.training_step(...)`
|
|
49
|
+
out = method(*_args, **_kwargs)
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
# Patch the original_module's forward so we can redirect the arguments back to the real method
|
|
53
|
+
original_module.forward = wrapped_forward # type: ignore[method-assign]
|
|
54
|
+
wrapper_output = wrapper_module(*args, **kwargs)
|
|
55
|
+
return wrapper_output
|
|
@@ -4,14 +4,18 @@ from liger_kernel.ops.cross_entropy import LigerCrossEntropyFunction
|
|
|
4
4
|
from liger_kernel.ops.dyt import LigerDyTFunction
|
|
5
5
|
from liger_kernel.ops.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyFunction
|
|
6
6
|
from liger_kernel.ops.fused_linear_jsd import LigerFusedLinearJSDFunction
|
|
7
|
+
from liger_kernel.ops.fused_neighborhood_attention import LigerFusedNeighborhoodAttentionFunction
|
|
7
8
|
from liger_kernel.ops.geglu import LigerGELUMulFunction
|
|
8
9
|
from liger_kernel.ops.group_norm import LigerGroupNormFunction
|
|
9
10
|
from liger_kernel.ops.jsd import LigerJSDFunction
|
|
10
11
|
from liger_kernel.ops.kl_div import LigerKLDivLossFunction
|
|
11
12
|
from liger_kernel.ops.layer_norm import LigerLayerNormFunction
|
|
13
|
+
from liger_kernel.ops.multi_token_attention import LigerMultiTokenAttentionFunction
|
|
12
14
|
from liger_kernel.ops.qwen2vl_mrope import LigerQwen2VLMRopeFunction
|
|
13
15
|
from liger_kernel.ops.rms_norm import LigerRMSNormFunction
|
|
14
16
|
from liger_kernel.ops.rope import LigerRopeFunction
|
|
17
|
+
from liger_kernel.ops.softmax import LigerSoftmaxFunction
|
|
18
|
+
from liger_kernel.ops.sparsemax import LigerSparsemaxFunction
|
|
15
19
|
from liger_kernel.ops.swiglu import LigerSiLUMulFunction
|
|
16
20
|
from liger_kernel.ops.tvd import LigerTVDLossFunction
|
|
17
21
|
|
|
@@ -159,6 +163,68 @@ def liger_kl_div(
|
|
|
159
163
|
)
|
|
160
164
|
|
|
161
165
|
|
|
166
|
+
def liger_sparsemax(
|
|
167
|
+
input,
|
|
168
|
+
dim: int = -1,
|
|
169
|
+
):
|
|
170
|
+
return LigerSparsemaxFunction.apply(input, dim)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def liger_multi_token_attention(
|
|
174
|
+
scores,
|
|
175
|
+
weight,
|
|
176
|
+
bias=None,
|
|
177
|
+
stride: int = 1,
|
|
178
|
+
padding: int = 0,
|
|
179
|
+
dilation: int = 1,
|
|
180
|
+
groups: int = 1,
|
|
181
|
+
sparse: bool = False,
|
|
182
|
+
):
|
|
183
|
+
"""
|
|
184
|
+
Functional interface for multi-token attention.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
scores: Input tensor of shape (B, C_in, L, L)
|
|
188
|
+
weight: Convolution weight tensor of shape (C_out, C_in // groups, K, K)
|
|
189
|
+
bias: Optional bias tensor of shape (C_out,)
|
|
190
|
+
stride: Stride for the convolution (default: 1)
|
|
191
|
+
padding: Padding for the convolution (default: 0)
|
|
192
|
+
dilation: Dilation factor for the convolution (default: 1)
|
|
193
|
+
groups: Number of groups for the convolution (default: 1)
|
|
194
|
+
sparse: Specifies if input tensors are expected to be sparse (default: False)
|
|
195
|
+
Returns:
|
|
196
|
+
Output tensor after applying multi-token attention.
|
|
197
|
+
"""
|
|
198
|
+
return LigerMultiTokenAttentionFunction.apply(scores, weight, bias, stride, padding, dilation, groups, sparse)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def liger_fused_neighborhood_attention(
|
|
202
|
+
query,
|
|
203
|
+
key,
|
|
204
|
+
value,
|
|
205
|
+
kernel_size: int = 7,
|
|
206
|
+
dilation: int = 1,
|
|
207
|
+
scale: float = None,
|
|
208
|
+
):
|
|
209
|
+
"""
|
|
210
|
+
Liger fused neighborhood attention.
|
|
211
|
+
|
|
212
|
+
paper: https://arxiv.org/pdf/2504.16922
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
query: Query tensor of shape [batch_size, num_heads, seq_len, head_dim]
|
|
216
|
+
key: Key tensor of shape [batch_size, num_heads, seq_len, head_dim]
|
|
217
|
+
value: Value tensor of shape [batch_size, num_heads, seq_len, head_dim]
|
|
218
|
+
kernel_size: Size of the neighborhood window (default: 7)
|
|
219
|
+
dilation: Dilation factor for the neighborhood (default: 1)
|
|
220
|
+
scale: Scaling factor for attention scores (default: rsqrt(head_dim))
|
|
221
|
+
|
|
222
|
+
Returns:
|
|
223
|
+
Output tensor of shape [batch_size, num_heads, seq_len, head_dim]
|
|
224
|
+
"""
|
|
225
|
+
return LigerFusedNeighborhoodAttentionFunction.apply(query, key, value, kernel_size, dilation, scale)
|
|
226
|
+
|
|
227
|
+
|
|
162
228
|
def liger_tvd(
|
|
163
229
|
input,
|
|
164
230
|
target,
|
|
@@ -195,5 +261,9 @@ def liger_swiglu(a, b):
|
|
|
195
261
|
return LigerSiLUMulFunction.apply(a, b)
|
|
196
262
|
|
|
197
263
|
|
|
264
|
+
def liger_softmax(x):
|
|
265
|
+
return LigerSoftmaxFunction.apply(x)
|
|
266
|
+
|
|
267
|
+
|
|
198
268
|
def liger_dyt(x, alpha, gamma, beta):
|
|
199
269
|
return LigerDyTFunction.apply(x, alpha, gamma, beta)
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
import torch
|
|
6
|
+
import torch.nn as nn
|
|
7
|
+
|
|
8
|
+
from liger_kernel.ops.fused_neighborhood_attention import LigerFusedNeighborhoodAttentionFunction
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LigerFusedNeighborhoodAttention(nn.Module):
|
|
12
|
+
"""
|
|
13
|
+
Liger Fused Neighborhood Attention Module.
|
|
14
|
+
|
|
15
|
+
Paper: https://arxiv.org/pdf/2504.16922
|
|
16
|
+
|
|
17
|
+
Fused Neighborhood attention restricts the attention mechanism to a local neighborhood
|
|
18
|
+
around each position, reducing computational complexity from O(n²) to O(n*k)
|
|
19
|
+
where k is the neighborhood size.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
hidden_size (int): The hidden dimension size
|
|
23
|
+
num_heads (int): Number of attention heads
|
|
24
|
+
kernel_size (int): Size of the neighborhood window (default: 7)
|
|
25
|
+
dilation (int): Dilation factor for the neighborhood (default: 1)
|
|
26
|
+
bias (bool): Whether to use bias in linear projections (default: True)
|
|
27
|
+
dropout (float): Dropout probability (default: 0.0)
|
|
28
|
+
scale (Optional[float]): Scaling factor for attention scores.
|
|
29
|
+
If None, uses 1/sqrt(head_dim) (default: None)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
hidden_size: int,
|
|
35
|
+
num_heads: int,
|
|
36
|
+
kernel_size: int = 7,
|
|
37
|
+
dilation: int = 1,
|
|
38
|
+
bias: bool = True,
|
|
39
|
+
dropout: float = 0.0,
|
|
40
|
+
scale: Optional[float] = None,
|
|
41
|
+
):
|
|
42
|
+
super().__init__()
|
|
43
|
+
|
|
44
|
+
if hidden_size % num_heads != 0:
|
|
45
|
+
raise ValueError(f"hidden_size ({hidden_size}) must be divisible by num_heads ({num_heads})")
|
|
46
|
+
|
|
47
|
+
if kernel_size <= 0:
|
|
48
|
+
raise ValueError(f"kernel_size ({kernel_size}) must be positive")
|
|
49
|
+
|
|
50
|
+
if kernel_size % 2 == 0:
|
|
51
|
+
raise ValueError(f"kernel_size ({kernel_size}) must be odd")
|
|
52
|
+
|
|
53
|
+
if dilation < 1:
|
|
54
|
+
raise ValueError(f"dilation ({dilation}) must be positive")
|
|
55
|
+
|
|
56
|
+
self.hidden_size = hidden_size
|
|
57
|
+
self.num_heads = num_heads
|
|
58
|
+
self.head_dim = hidden_size // num_heads
|
|
59
|
+
self.kernel_size = kernel_size
|
|
60
|
+
self.dilation = dilation
|
|
61
|
+
self.scale = scale if scale is not None else 1.0 / math.sqrt(self.head_dim)
|
|
62
|
+
self.dropout_p = dropout
|
|
63
|
+
|
|
64
|
+
self.q_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
|
|
65
|
+
self.k_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
|
|
66
|
+
self.v_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
|
|
67
|
+
|
|
68
|
+
self.out_proj = nn.Linear(hidden_size, hidden_size, bias=bias)
|
|
69
|
+
|
|
70
|
+
if dropout > 0.0:
|
|
71
|
+
self.dropout = nn.Dropout(dropout)
|
|
72
|
+
else:
|
|
73
|
+
self.dropout = None
|
|
74
|
+
|
|
75
|
+
def forward(
|
|
76
|
+
self,
|
|
77
|
+
hidden_states: torch.Tensor,
|
|
78
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
79
|
+
) -> torch.Tensor:
|
|
80
|
+
"""
|
|
81
|
+
Forward pass of the fused neighborhood attention module.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
hidden_states (torch.Tensor): Input tensor of shape [batch_size, seq_len, hidden_size]
|
|
85
|
+
attention_mask (Optional[torch.Tensor]): Attention mask (currently not supported)
|
|
86
|
+
|
|
87
|
+
Returns:
|
|
88
|
+
torch.Tensor: Output tensor of shape [batch_size, seq_len, hidden_size]
|
|
89
|
+
"""
|
|
90
|
+
if attention_mask is not None:
|
|
91
|
+
raise NotImplementedError("Attention mask is not yet supported in LigerFusedNeighborhoodAttention")
|
|
92
|
+
|
|
93
|
+
batch_size, seq_len, hidden_size = hidden_states.shape
|
|
94
|
+
|
|
95
|
+
query = self.q_proj(hidden_states)
|
|
96
|
+
key = self.k_proj(hidden_states)
|
|
97
|
+
value = self.v_proj(hidden_states)
|
|
98
|
+
|
|
99
|
+
query = query.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
|
100
|
+
key = key.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
|
101
|
+
value = value.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
|
|
102
|
+
|
|
103
|
+
attn_output = LigerFusedNeighborhoodAttentionFunction.apply(
|
|
104
|
+
query, key, value, self.kernel_size, self.dilation, self.scale
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, hidden_size)
|
|
108
|
+
|
|
109
|
+
if self.dropout is not None:
|
|
110
|
+
attn_output = self.dropout(attn_output)
|
|
111
|
+
|
|
112
|
+
output = self.out_proj(attn_output)
|
|
113
|
+
|
|
114
|
+
return output
|
|
115
|
+
|
|
116
|
+
def extra_repr(self) -> str:
|
|
117
|
+
return (
|
|
118
|
+
f"hidden_size={self.hidden_size}, num_heads={self.num_heads}, "
|
|
119
|
+
f"head_dim={self.head_dim}, kernel_size={self.kernel_size}, "
|
|
120
|
+
f"dilation={self.dilation}, scale={self.scale}, dropout={self.dropout_p}"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class LigerFusedNeighborhoodAttentionLayer(nn.Module):
|
|
125
|
+
"""
|
|
126
|
+
A complete neighborhood attention layer with layer norm and residual connection.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
hidden_size (int): The hidden dimension size
|
|
130
|
+
num_heads (int): Number of attention heads
|
|
131
|
+
kernel_size (int): Size of the neighborhood window (default: 7)
|
|
132
|
+
dilation (int): Dilation factor for the neighborhood (default: 1)
|
|
133
|
+
bias (bool): Whether to use bias in linear projections (default: True)
|
|
134
|
+
dropout (float): Dropout probability (default: 0.0)
|
|
135
|
+
layer_norm_eps (float): Epsilon for layer normalization (default: 1e-5)
|
|
136
|
+
scale (Optional[float]): Scaling factor for attention scores (default: None)
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
hidden_size: int,
|
|
142
|
+
num_heads: int,
|
|
143
|
+
kernel_size: int = 7,
|
|
144
|
+
dilation: int = 1,
|
|
145
|
+
bias: bool = True,
|
|
146
|
+
dropout: float = 0.0,
|
|
147
|
+
layer_norm_eps: float = 1e-5,
|
|
148
|
+
scale: Optional[float] = None,
|
|
149
|
+
):
|
|
150
|
+
super().__init__()
|
|
151
|
+
|
|
152
|
+
self.attention = LigerFusedNeighborhoodAttention(
|
|
153
|
+
hidden_size=hidden_size,
|
|
154
|
+
num_heads=num_heads,
|
|
155
|
+
kernel_size=kernel_size,
|
|
156
|
+
dilation=dilation,
|
|
157
|
+
bias=bias,
|
|
158
|
+
dropout=dropout,
|
|
159
|
+
scale=scale,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
self.layer_norm = nn.LayerNorm(hidden_size, eps=layer_norm_eps)
|
|
163
|
+
|
|
164
|
+
if dropout > 0.0:
|
|
165
|
+
self.dropout = nn.Dropout(dropout)
|
|
166
|
+
else:
|
|
167
|
+
self.dropout = None
|
|
168
|
+
|
|
169
|
+
def forward(
|
|
170
|
+
self,
|
|
171
|
+
hidden_states: torch.Tensor,
|
|
172
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
173
|
+
) -> torch.Tensor:
|
|
174
|
+
"""
|
|
175
|
+
Forward pass with residual connection and layer normalization.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
hidden_states (torch.Tensor): Input tensor of shape [batch_size, seq_len, hidden_size]
|
|
179
|
+
attention_mask (Optional[torch.Tensor]): Attention mask (currently not supported)
|
|
180
|
+
|
|
181
|
+
Returns:
|
|
182
|
+
torch.Tensor: Output tensor of shape [batch_size, seq_len, hidden_size]
|
|
183
|
+
"""
|
|
184
|
+
normed_hidden_states = self.layer_norm(hidden_states)
|
|
185
|
+
|
|
186
|
+
attn_output = self.attention(normed_hidden_states, attention_mask)
|
|
187
|
+
|
|
188
|
+
if self.dropout is not None:
|
|
189
|
+
attn_output = self.dropout(attn_output)
|
|
190
|
+
|
|
191
|
+
output = hidden_states + attn_output
|
|
192
|
+
|
|
193
|
+
return output
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class LigerFusedNeighborhoodAttentionConfig:
|
|
197
|
+
"""
|
|
198
|
+
Configuration class for Fused Neighborhood Attention.
|
|
199
|
+
|
|
200
|
+
This can be used to easily configure neighborhood attention parameters
|
|
201
|
+
for different model architectures.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
hidden_size: int = 768,
|
|
207
|
+
num_heads: int = 12,
|
|
208
|
+
kernel_size: int = 7,
|
|
209
|
+
dilation: int = 1,
|
|
210
|
+
bias: bool = True,
|
|
211
|
+
dropout: float = 0.0,
|
|
212
|
+
layer_norm_eps: float = 1e-5,
|
|
213
|
+
scale: Optional[float] = None,
|
|
214
|
+
):
|
|
215
|
+
self.hidden_size = hidden_size
|
|
216
|
+
self.num_heads = num_heads
|
|
217
|
+
self.kernel_size = kernel_size
|
|
218
|
+
self.dilation = dilation
|
|
219
|
+
self.bias = bias
|
|
220
|
+
self.dropout = dropout
|
|
221
|
+
self.layer_norm_eps = layer_norm_eps
|
|
222
|
+
self.scale = scale
|
|
223
|
+
|
|
224
|
+
def to_dict(self):
|
|
225
|
+
return {
|
|
226
|
+
"hidden_size": self.hidden_size,
|
|
227
|
+
"num_heads": self.num_heads,
|
|
228
|
+
"kernel_size": self.kernel_size,
|
|
229
|
+
"dilation": self.dilation,
|
|
230
|
+
"bias": self.bias,
|
|
231
|
+
"dropout": self.dropout,
|
|
232
|
+
"layer_norm_eps": self.layer_norm_eps,
|
|
233
|
+
"scale": self.scale,
|
|
234
|
+
}
|