liger-kernel 0.6.0__py3-none-any.whl → 0.6.1__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/ops/fused_add_rms_norm.py +412 -0
- liger_kernel/ops/layer_norm.py +126 -89
- liger_kernel/ops/rms_norm.py +2 -2
- liger_kernel/ops/rope.py +1 -1
- liger_kernel/transformers/__init__.py +5 -0
- liger_kernel/transformers/functional.py +5 -0
- liger_kernel/transformers/fused_add_rms_norm.py +39 -0
- liger_kernel/transformers/model/gemma3.py +1 -1
- liger_kernel/transformers/model/smollm3.py +189 -0
- liger_kernel/transformers/monkey_patch.py +85 -12
- {liger_kernel-0.6.0.dist-info → liger_kernel-0.6.1.dist-info}/METADATA +11 -13
- {liger_kernel-0.6.0.dist-info → liger_kernel-0.6.1.dist-info}/RECORD +16 -13
- {liger_kernel-0.6.0.dist-info → liger_kernel-0.6.1.dist-info}/WHEEL +0 -0
- {liger_kernel-0.6.0.dist-info → liger_kernel-0.6.1.dist-info}/licenses/LICENSE +0 -0
- {liger_kernel-0.6.0.dist-info → liger_kernel-0.6.1.dist-info}/licenses/NOTICE +0 -0
- {liger_kernel-0.6.0.dist-info → liger_kernel-0.6.1.dist-info}/top_level.txt +0 -0
liger_kernel/ops/layer_norm.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import math
|
|
2
1
|
import operator
|
|
3
2
|
|
|
4
3
|
import torch
|
|
@@ -43,30 +42,45 @@ def _layer_norm_forward_kernel(
|
|
|
43
42
|
https://arxiv.org/abs/1607.06450
|
|
44
43
|
https://github.com/karpathy/llm.c/blob/master/doc/layernorm/layernorm.md
|
|
45
44
|
"""
|
|
46
|
-
row_idx = tl.program_id(0)
|
|
45
|
+
row_idx = tl.program_id(0).to(tl.int64)
|
|
47
46
|
col_offsets = tl.arange(0, BLOCK_SIZE)
|
|
48
47
|
mask = col_offsets < n_cols
|
|
49
48
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
49
|
+
# Pre-load weights and bias in fp32 to avoid repeated conversions
|
|
50
|
+
W_row = tl.load(W_ptr + col_offsets, mask=mask, other=0.0)
|
|
51
|
+
B_row = tl.load(B_ptr + col_offsets, mask=mask, other=0.0)
|
|
52
|
+
W_f32 = W_row.to(tl.float32)
|
|
53
|
+
B_f32 = B_row.to(tl.float32)
|
|
54
|
+
|
|
55
|
+
# Calculate pointers for this row
|
|
56
|
+
row_X_ptr = X_ptr + row_idx * X_row_stride
|
|
57
|
+
row_Y_ptr = Y_ptr + row_idx * Y_row_stride
|
|
58
|
+
row_Mean_ptr = Mean_ptr + row_idx * Mean_row_stride
|
|
59
|
+
row_RSTD_ptr = RSTD_ptr + row_idx * RSTD_row_stride
|
|
60
|
+
|
|
61
|
+
# Load input data and convert to fp32 for numerical stability
|
|
62
|
+
X_row = tl.load(row_X_ptr + col_offsets, mask=mask, other=0.0)
|
|
63
|
+
X_f32 = X_row.to(tl.float32)
|
|
64
|
+
|
|
65
|
+
# Compute statistics in fp32 for numerical stability
|
|
66
|
+
n_cols_f32 = n_cols.to(tl.float32)
|
|
67
|
+
mean = tl.sum(X_f32, axis=0) / n_cols_f32
|
|
68
|
+
X_centered = X_f32 - mean
|
|
69
|
+
# Apply mask to variance calculation to exclude contributions from masked elements
|
|
70
|
+
X_centered_masked = tl.where(mask, X_centered, 0.0)
|
|
71
|
+
var = tl.sum(X_centered_masked * X_centered_masked, axis=0) / n_cols_f32
|
|
62
72
|
rstd = rsqrt(var + eps)
|
|
63
73
|
|
|
64
|
-
|
|
65
|
-
tl.store(
|
|
74
|
+
# Store statistics (convert back to original dtype only once)
|
|
75
|
+
tl.store(row_Mean_ptr, mean.to(X_row.dtype))
|
|
76
|
+
tl.store(row_RSTD_ptr, rstd.to(X_row.dtype))
|
|
66
77
|
|
|
67
|
-
|
|
78
|
+
# Fused normalization and affine transformation
|
|
79
|
+
# Y = (X - mean) * rstd * W + B = X_centered * rstd * W + B
|
|
80
|
+
Y_f32 = X_centered * rstd * W_f32 + B_f32
|
|
68
81
|
|
|
69
|
-
|
|
82
|
+
# Store output (single conversion back to original dtype)
|
|
83
|
+
tl.store(row_Y_ptr + col_offsets, Y_f32.to(X_row.dtype), mask=mask)
|
|
70
84
|
|
|
71
85
|
|
|
72
86
|
@triton.jit
|
|
@@ -81,73 +95,87 @@ def _layer_norm_backward_kernel(
|
|
|
81
95
|
DY_ptr, # pointer to output grad, shape (n_rows, n_cols)
|
|
82
96
|
stride_x, # stride of each row in input
|
|
83
97
|
stride_dx, # stride of each row in input grad
|
|
84
|
-
stride_dw, # stride of each row in weights grad
|
|
85
|
-
stride_db, # stride of each row in bias grad
|
|
86
98
|
stride_dy, # stride of each row in output grad
|
|
87
|
-
n_rows,
|
|
88
99
|
n_cols,
|
|
89
|
-
rows_per_program: tl.constexpr,
|
|
90
100
|
BLOCK_SIZE: tl.constexpr,
|
|
91
101
|
dtype: tl.constexpr,
|
|
102
|
+
atomic_dtype: tl.constexpr,
|
|
92
103
|
):
|
|
93
104
|
"""
|
|
94
105
|
References:
|
|
95
106
|
https://arxiv.org/abs/1607.06450
|
|
96
107
|
https://github.com/karpathy/llm.c/blob/master/doc/layernorm/layernorm.md
|
|
97
|
-
https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
|
|
98
|
-
https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/ops/triton/layer_norm.py
|
|
99
108
|
"""
|
|
100
|
-
|
|
101
|
-
row_start = row_block_id * rows_per_program
|
|
102
|
-
row_end = min((row_block_id + 1) * rows_per_program, n_rows)
|
|
109
|
+
row_idx = tl.program_id(0).to(tl.int64)
|
|
103
110
|
cols = tl.arange(0, BLOCK_SIZE)
|
|
104
111
|
mask = cols < n_cols
|
|
105
112
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
tl.store(
|
|
139
|
-
|
|
113
|
+
# Pre-load weights once (same optimization as forward pass)
|
|
114
|
+
w = tl.load(W_ptr + cols, mask=mask, other=0.0)
|
|
115
|
+
w_f32 = w.to(tl.float32)
|
|
116
|
+
n_cols_f32 = n_cols.to(tl.float32)
|
|
117
|
+
|
|
118
|
+
# Calculate pointers for this specific row
|
|
119
|
+
row_X_ptr = X_ptr + row_idx * stride_x
|
|
120
|
+
row_DX_ptr = DX_ptr + row_idx * stride_dx
|
|
121
|
+
row_DY_ptr = DY_ptr + row_idx * stride_dy
|
|
122
|
+
row_Mean_ptr = Mean_ptr + row_idx
|
|
123
|
+
row_RSTD_ptr = RSTD_ptr + row_idx
|
|
124
|
+
|
|
125
|
+
# Load data for this row
|
|
126
|
+
x = tl.load(row_X_ptr + cols, mask=mask, other=0.0)
|
|
127
|
+
dy = tl.load(row_DY_ptr + cols, mask=mask, other=0.0)
|
|
128
|
+
mean = tl.load(row_Mean_ptr)
|
|
129
|
+
rstd = tl.load(row_RSTD_ptr)
|
|
130
|
+
|
|
131
|
+
# Convert to fp32 for numerical stability
|
|
132
|
+
x_f32 = x.to(tl.float32)
|
|
133
|
+
dy_f32 = dy.to(tl.float32)
|
|
134
|
+
mean_f32 = mean.to(tl.float32)
|
|
135
|
+
rstd_f32 = rstd.to(tl.float32)
|
|
136
|
+
|
|
137
|
+
# Compute backward pass for this row
|
|
138
|
+
x_hat = (x_f32 - mean_f32) * rstd_f32
|
|
139
|
+
wdy = w_f32 * dy_f32
|
|
140
|
+
c1 = tl.sum(x_hat * wdy, axis=0) / n_cols_f32
|
|
141
|
+
c2 = tl.sum(wdy, axis=0) / n_cols_f32
|
|
142
|
+
dx = (wdy - (x_hat * c1 + c2)) * rstd_f32
|
|
143
|
+
|
|
144
|
+
# Store input gradient
|
|
145
|
+
tl.store(row_DX_ptr + cols, dx.to(dtype), mask=mask)
|
|
146
|
+
|
|
147
|
+
# Accumulate weight and bias gradients using atomic operations
|
|
148
|
+
dw = dy_f32 * x_hat
|
|
149
|
+
db = dy_f32
|
|
150
|
+
tl.atomic_add(DW_ptr + cols, dw.to(atomic_dtype), mask=mask)
|
|
151
|
+
tl.atomic_add(DB_ptr + cols, db.to(atomic_dtype), mask=mask)
|
|
140
152
|
|
|
141
153
|
|
|
142
154
|
def layer_norm_forward(X, W, B, eps):
|
|
155
|
+
"""
|
|
156
|
+
Args:
|
|
157
|
+
X: Input tensor of shape (..., hidden_size)
|
|
158
|
+
W: Weight tensor of shape (hidden_size,)
|
|
159
|
+
B: Bias tensor of shape (hidden_size,)
|
|
160
|
+
eps: Small constant for numerical stability
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
Tuple of (output, input, mean, rstd, block_size, num_warps)
|
|
164
|
+
"""
|
|
143
165
|
shape = X.shape
|
|
144
166
|
dim = shape[-1]
|
|
145
167
|
X = X.view(-1, dim)
|
|
146
168
|
n_rows, n_cols = X.shape
|
|
169
|
+
|
|
170
|
+
# Calculate optimal block size and warp configuration
|
|
147
171
|
BLOCK_SIZE, num_warps = calculate_settings(n_cols)
|
|
172
|
+
|
|
173
|
+
# Allocate output tensors
|
|
148
174
|
Y = torch.empty((n_rows, n_cols), dtype=X.dtype, device=X.device)
|
|
149
175
|
Mean = torch.empty(n_rows, dtype=X.dtype, device=X.device)
|
|
150
176
|
RSTD = torch.empty(n_rows, dtype=X.dtype, device=X.device)
|
|
177
|
+
|
|
178
|
+
# Validate input dimensions
|
|
151
179
|
if X.shape[1] != W.shape[0]:
|
|
152
180
|
raise ValueError(
|
|
153
181
|
f"Incompatible dimensions: input feature size (X.shape[1]={X.shape[1]}) "
|
|
@@ -159,7 +187,9 @@ def layer_norm_forward(X, W, B, eps):
|
|
|
159
187
|
if X.device.type == "xpu":
|
|
160
188
|
kernel_args["grf_mode"] = "large"
|
|
161
189
|
|
|
162
|
-
|
|
190
|
+
# Launch kernel with one thread block per row for optimal performance
|
|
191
|
+
grid = (n_rows,)
|
|
192
|
+
_layer_norm_forward_kernel[grid](
|
|
163
193
|
Y,
|
|
164
194
|
Y.stride(0),
|
|
165
195
|
X,
|
|
@@ -176,35 +206,43 @@ def layer_norm_forward(X, W, B, eps):
|
|
|
176
206
|
eps,
|
|
177
207
|
BLOCK_SIZE=BLOCK_SIZE,
|
|
178
208
|
num_warps=num_warps,
|
|
179
|
-
**kernel_args,
|
|
209
|
+
**kernel_args,
|
|
180
210
|
)
|
|
211
|
+
|
|
181
212
|
return Y.view(*shape), X, Mean, RSTD, BLOCK_SIZE, num_warps
|
|
182
213
|
|
|
183
214
|
|
|
184
215
|
def layer_norm_backward(dY, X, W, B, Mean, RSTD):
|
|
216
|
+
"""
|
|
217
|
+
Args:
|
|
218
|
+
dY: Gradient of output
|
|
219
|
+
X: Input tensor
|
|
220
|
+
W: Weight tensor
|
|
221
|
+
B: Bias tensor
|
|
222
|
+
Mean: Pre-computed mean
|
|
223
|
+
RSTD: Pre-computed reciprocal standard deviation
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
Tuple of (input_grad, weight_grad, bias_grad)
|
|
227
|
+
"""
|
|
185
228
|
shape = dY.shape
|
|
186
229
|
dim = shape[-1]
|
|
187
230
|
dY = dY.view(-1, dim)
|
|
188
231
|
n_rows, n_cols = dY.shape
|
|
189
232
|
|
|
190
|
-
|
|
191
|
-
if X.device.type == "cuda":
|
|
192
|
-
sm_count = torch.cuda.get_device_properties(X.device).multi_processor_count
|
|
193
|
-
elif X.device.type == "xpu":
|
|
194
|
-
sm_count = torch.xpu.get_device_properties(X.device).gpu_eu_count
|
|
195
|
-
|
|
233
|
+
# Allocate gradient tensors
|
|
196
234
|
DX = torch.empty((n_rows, n_cols), dtype=X.dtype, device=X.device)
|
|
197
|
-
|
|
198
|
-
|
|
235
|
+
# Use float32 for weight/bias gradients if bfloat16 (due to atomic_add limitation)
|
|
236
|
+
grad_dtype = torch.float32 if W.dtype == torch.bfloat16 else W.dtype
|
|
237
|
+
DW = torch.zeros(n_cols, dtype=grad_dtype, device=W.device)
|
|
238
|
+
DB = torch.zeros(n_cols, dtype=grad_dtype, device=W.device)
|
|
199
239
|
|
|
240
|
+
# Calculate optimal block size and warp configuration
|
|
200
241
|
BLOCK_SIZE, num_warps = calculate_settings(n_cols)
|
|
201
242
|
if n_cols > BLOCK_SIZE:
|
|
202
|
-
raise RuntimeError(
|
|
203
|
-
f"Feature dimension {n_cols} exceeds maximum supported size of {BLOCK_SIZE}. Consider using a smaller feature dimension."
|
|
204
|
-
)
|
|
243
|
+
raise RuntimeError(f"Feature dimension {n_cols} exceeds maximum supported size of {BLOCK_SIZE}.")
|
|
205
244
|
|
|
206
|
-
|
|
207
|
-
grid = (sm_count,)
|
|
245
|
+
# Determine dtype for triton operations
|
|
208
246
|
triton_dtype = (
|
|
209
247
|
tl.float32
|
|
210
248
|
if X.dtype == torch.float32
|
|
@@ -212,41 +250,40 @@ def layer_norm_backward(dY, X, W, B, Mean, RSTD):
|
|
|
212
250
|
if X.dtype == torch.bfloat16
|
|
213
251
|
else tl.float16
|
|
214
252
|
if X.dtype == torch.float16
|
|
215
|
-
else tl.float32 # fallback
|
|
253
|
+
else tl.float32 # fallback
|
|
216
254
|
)
|
|
217
255
|
|
|
256
|
+
# Use float32 for atomic operations if bfloat16 is not supported
|
|
257
|
+
atomic_dtype = tl.float32 if triton_dtype == tl.bfloat16 else triton_dtype
|
|
258
|
+
|
|
259
|
+
kernel_args = {"num_warps": num_warps}
|
|
218
260
|
# XPU-specific optimization
|
|
219
|
-
kernel_args = {}
|
|
220
261
|
if X.device.type == "xpu":
|
|
221
262
|
kernel_args.update({"grf_mode": "large", "num_warps": 32, "num_stages": 4})
|
|
222
263
|
|
|
264
|
+
# Launch kernel with one thread block per row for optimal performance
|
|
265
|
+
grid = (n_rows,)
|
|
223
266
|
_layer_norm_backward_kernel[grid](
|
|
224
267
|
X,
|
|
225
268
|
W,
|
|
226
269
|
Mean,
|
|
227
270
|
RSTD,
|
|
228
271
|
DX,
|
|
229
|
-
|
|
230
|
-
|
|
272
|
+
DW,
|
|
273
|
+
DB,
|
|
231
274
|
dY,
|
|
232
275
|
X.stride(0),
|
|
233
276
|
DX.stride(0),
|
|
234
|
-
_DW.stride(0),
|
|
235
|
-
_DB.stride(0),
|
|
236
277
|
dY.stride(0),
|
|
237
|
-
n_rows,
|
|
238
278
|
n_cols,
|
|
239
|
-
rows_per_program,
|
|
240
279
|
BLOCK_SIZE=BLOCK_SIZE,
|
|
241
280
|
dtype=triton_dtype,
|
|
242
|
-
|
|
281
|
+
atomic_dtype=atomic_dtype,
|
|
282
|
+
**kernel_args,
|
|
243
283
|
)
|
|
244
284
|
|
|
245
|
-
DW = _DW.sum(dim=0).to(W.dtype)
|
|
246
|
-
DB = _DB.sum(dim=0).to(W.dtype)
|
|
247
|
-
|
|
248
285
|
DX = DX.view(*shape)
|
|
249
|
-
return DX, DW, DB
|
|
286
|
+
return DX, DW.to(W.dtype), DB.to(W.dtype)
|
|
250
287
|
|
|
251
288
|
|
|
252
289
|
class LigerLayerNormFunction(torch.autograd.Function):
|
liger_kernel/ops/rms_norm.py
CHANGED
|
@@ -63,7 +63,7 @@ def _rms_norm_forward_kernel(
|
|
|
63
63
|
3. https://arxiv.org/pdf/1910.07467
|
|
64
64
|
"""
|
|
65
65
|
|
|
66
|
-
row_idx = tl.program_id(0)
|
|
66
|
+
row_idx = tl.program_id(0).to(tl.int64)
|
|
67
67
|
col_offsets = tl.arange(0, BLOCK_SIZE)
|
|
68
68
|
mask = col_offsets < n_cols
|
|
69
69
|
|
|
@@ -137,7 +137,7 @@ def _rms_norm_backward_kernel(
|
|
|
137
137
|
dw = sum(dy * (x / RMS)). summation over BxT dimension
|
|
138
138
|
"""
|
|
139
139
|
|
|
140
|
-
row_block_id = tl.program_id(0)
|
|
140
|
+
row_block_id = tl.program_id(0).to(tl.int64)
|
|
141
141
|
row_start = row_block_id * rows_per_program
|
|
142
142
|
row_end = min((row_block_id + 1) * rows_per_program, n_rows)
|
|
143
143
|
col_offsets = tl.arange(0, BLOCK_SIZE)
|
liger_kernel/ops/rope.py
CHANGED
|
@@ -32,7 +32,7 @@ def _triton_rope(
|
|
|
32
32
|
|
|
33
33
|
# cos size: (1, seq_len, head_dim) or (bsz, seq_len, head_dim)
|
|
34
34
|
# stride: (seq_len * head_dim, head_dim, 1)
|
|
35
|
-
pid = tl.program_id(0)
|
|
35
|
+
pid = tl.program_id(0).to(tl.int64)
|
|
36
36
|
|
|
37
37
|
# locate start address
|
|
38
38
|
q_ptr = q_ptr + pid * q_row_stride
|
|
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING
|
|
|
5
5
|
# Always-safe imports (independent of 'transformers')
|
|
6
6
|
from liger_kernel.transformers.cross_entropy import LigerCrossEntropyLoss # noqa: F401
|
|
7
7
|
from liger_kernel.transformers.dyt import LigerDyT # noqa: F401
|
|
8
|
+
from liger_kernel.transformers.fused_add_rms_norm import LigerFusedAddRMSNorm # noqa: F401
|
|
8
9
|
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss # noqa: F401
|
|
9
10
|
from liger_kernel.transformers.fused_linear_jsd import LigerFusedLinearJSD # noqa: F401
|
|
10
11
|
from liger_kernel.transformers.geglu import LigerGEGLUMLP # noqa: F401
|
|
@@ -43,6 +44,7 @@ if TYPE_CHECKING:
|
|
|
43
44
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_vl # noqa: F401
|
|
44
45
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3 # noqa: F401
|
|
45
46
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3_moe # noqa: F401
|
|
47
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_smollm3 # noqa: F401
|
|
46
48
|
|
|
47
49
|
|
|
48
50
|
# Check if 'transformers' is installed
|
|
@@ -100,6 +102,7 @@ def __getattr__(name: str):
|
|
|
100
102
|
"apply_liger_kernel_to_qwen2_vl",
|
|
101
103
|
"apply_liger_kernel_to_qwen3",
|
|
102
104
|
"apply_liger_kernel_to_qwen3_moe",
|
|
105
|
+
"apply_liger_kernel_to_smollm3",
|
|
103
106
|
}
|
|
104
107
|
|
|
105
108
|
if name in monkey_patch_symbols:
|
|
@@ -119,6 +122,7 @@ __all__ = [
|
|
|
119
122
|
"LigerGEGLUMLP",
|
|
120
123
|
"LigerJSD",
|
|
121
124
|
"LigerLayerNorm",
|
|
125
|
+
"LigerFusedAddRMSNorm",
|
|
122
126
|
"LigerRMSNorm",
|
|
123
127
|
"liger_rotary_pos_emb",
|
|
124
128
|
"LigerBlockSparseTop2MLP",
|
|
@@ -155,5 +159,6 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
155
159
|
"apply_liger_kernel_to_qwen2_vl",
|
|
156
160
|
"apply_liger_kernel_to_qwen3",
|
|
157
161
|
"apply_liger_kernel_to_qwen3_moe",
|
|
162
|
+
"apply_liger_kernel_to_smollm3",
|
|
158
163
|
]
|
|
159
164
|
)
|
|
@@ -2,6 +2,7 @@ from typing import Optional
|
|
|
2
2
|
|
|
3
3
|
from liger_kernel.ops.cross_entropy import LigerCrossEntropyFunction
|
|
4
4
|
from liger_kernel.ops.dyt import LigerDyTFunction
|
|
5
|
+
from liger_kernel.ops.fused_add_rms_norm import LigerFusedAddRMSNormFunction
|
|
5
6
|
from liger_kernel.ops.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyFunction
|
|
6
7
|
from liger_kernel.ops.fused_linear_jsd import LigerFusedLinearJSDFunction
|
|
7
8
|
from liger_kernel.ops.fused_neighborhood_attention import LigerFusedNeighborhoodAttentionFunction
|
|
@@ -253,6 +254,10 @@ def liger_rms_norm(X, W, eps, offset: float = 0.0, casting_mode: str = "llama",
|
|
|
253
254
|
return LigerRMSNormFunction.apply(X, W, eps, offset, casting_mode, in_place)
|
|
254
255
|
|
|
255
256
|
|
|
257
|
+
def liger_fused_add_rms_norm(X, R, W, eps, offset: float = 0.0, casting_mode: str = "llama", in_place: bool = True):
|
|
258
|
+
return LigerFusedAddRMSNormFunction.apply(X, R, W, eps, offset, casting_mode, in_place)
|
|
259
|
+
|
|
260
|
+
|
|
256
261
|
def liger_rope(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
|
257
262
|
return LigerRopeFunction.apply(q, k, cos, sin, position_ids, unsqueeze_dim)
|
|
258
263
|
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
|
|
4
|
+
from liger_kernel.ops.fused_add_rms_norm import LigerFusedAddRMSNormFunction
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LigerFusedAddRMSNorm(nn.Module):
|
|
8
|
+
def __init__(
|
|
9
|
+
self,
|
|
10
|
+
hidden_size,
|
|
11
|
+
eps=1e-6,
|
|
12
|
+
offset=0.0,
|
|
13
|
+
casting_mode="llama",
|
|
14
|
+
init_fn="ones",
|
|
15
|
+
in_place=False,
|
|
16
|
+
):
|
|
17
|
+
super().__init__()
|
|
18
|
+
assert init_fn in [
|
|
19
|
+
"ones",
|
|
20
|
+
"zeros",
|
|
21
|
+
], f"init_fn must be either 'ones' or 'zeros', got {init_fn}"
|
|
22
|
+
self.weight = nn.Parameter(torch.ones(hidden_size) if init_fn == "ones" else torch.zeros(hidden_size))
|
|
23
|
+
self.variance_epsilon, self.offset, self.casting_mode, self.in_place = (eps, offset, casting_mode, in_place)
|
|
24
|
+
|
|
25
|
+
def forward(self, hidden_states, residual):
|
|
26
|
+
return LigerFusedAddRMSNormFunction.apply(
|
|
27
|
+
hidden_states,
|
|
28
|
+
residual,
|
|
29
|
+
self.weight,
|
|
30
|
+
self.variance_epsilon,
|
|
31
|
+
self.offset,
|
|
32
|
+
self.casting_mode,
|
|
33
|
+
self.in_place,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def extra_repr(self):
|
|
37
|
+
return (
|
|
38
|
+
f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}, offset={self.offset}, in_place={self.in_place}"
|
|
39
|
+
)
|
|
@@ -255,7 +255,7 @@ def multimodal_forward(
|
|
|
255
255
|
shift_labels = shift_labels.view(-1).to(hidden_device)
|
|
256
256
|
|
|
257
257
|
lce = LigerFusedLinearCrossEntropyLoss()
|
|
258
|
-
loss = lce(self.
|
|
258
|
+
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
259
259
|
else:
|
|
260
260
|
logits = self.lm_head(kept_hidden_states)
|
|
261
261
|
if labels is not None:
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
from typing import List
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from typing import Tuple
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from torch.distributed.fsdp import FullyShardedDataParallel
|
|
10
|
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
11
|
+
from transformers.utils.deprecation import deprecate_kwarg
|
|
12
|
+
|
|
13
|
+
from liger_kernel.transformers.fsdp import _FSDPForwardRedirection
|
|
14
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
15
|
+
from liger_kernel.utils import PEFT_AVAILABLE
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from transformers.cache_utils import Cache
|
|
19
|
+
|
|
20
|
+
if PEFT_AVAILABLE:
|
|
21
|
+
from peft.utils.other import ModulesToSaveWrapper
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
25
|
+
def lce_forward(
|
|
26
|
+
self,
|
|
27
|
+
input_ids: torch.LongTensor = None,
|
|
28
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
29
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
30
|
+
past_key_values: Optional[Union["Cache", List[torch.FloatTensor]]] = None,
|
|
31
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
32
|
+
labels: Optional[torch.LongTensor] = None,
|
|
33
|
+
use_cache: Optional[bool] = None,
|
|
34
|
+
output_attentions: Optional[bool] = None,
|
|
35
|
+
output_hidden_states: Optional[bool] = None,
|
|
36
|
+
return_dict: Optional[bool] = None,
|
|
37
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
38
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
39
|
+
skip_logits: Optional[bool] = None,
|
|
40
|
+
**kwargs,
|
|
41
|
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
42
|
+
r"""
|
|
43
|
+
Args:
|
|
44
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
45
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
46
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
47
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
48
|
+
|
|
49
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
50
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
51
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
52
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
53
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
54
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
|
|
58
|
+
Example:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
>>> from transformers import AutoTokenizer, Smollm3ForCausalLM
|
|
62
|
+
|
|
63
|
+
>>> model = Smollm3ForCausalLM.from_pretrained("HuggingFaceTB/SmolLM3-3B")
|
|
64
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM3-3B")
|
|
65
|
+
|
|
66
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
67
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
68
|
+
|
|
69
|
+
>>> # Generate
|
|
70
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
71
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
72
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
73
|
+
```"""
|
|
74
|
+
|
|
75
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
76
|
+
output_hidden_states = (
|
|
77
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
78
|
+
)
|
|
79
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
80
|
+
|
|
81
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
82
|
+
outputs = self.model(
|
|
83
|
+
input_ids=input_ids,
|
|
84
|
+
attention_mask=attention_mask,
|
|
85
|
+
position_ids=position_ids,
|
|
86
|
+
past_key_values=past_key_values,
|
|
87
|
+
inputs_embeds=inputs_embeds,
|
|
88
|
+
use_cache=use_cache,
|
|
89
|
+
output_attentions=output_attentions,
|
|
90
|
+
output_hidden_states=output_hidden_states,
|
|
91
|
+
return_dict=return_dict,
|
|
92
|
+
cache_position=cache_position,
|
|
93
|
+
**kwargs,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
hidden_states = outputs[0]
|
|
97
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
98
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
99
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
100
|
+
|
|
101
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
102
|
+
logits = None
|
|
103
|
+
loss = None
|
|
104
|
+
# if in training mode, don't materialize logits
|
|
105
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
106
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
107
|
+
|
|
108
|
+
if skip_logits is None:
|
|
109
|
+
# By default, if in training mode, don't materialize logits
|
|
110
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
111
|
+
|
|
112
|
+
if skip_logits:
|
|
113
|
+
loss = lce_maybe_trainable_lm_head(
|
|
114
|
+
self,
|
|
115
|
+
hidden_states=kept_hidden_states,
|
|
116
|
+
hidden_size=self.config.hidden_size,
|
|
117
|
+
labels=labels,
|
|
118
|
+
shift_labels=shift_labels,
|
|
119
|
+
**kwargs,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
else:
|
|
123
|
+
logits = self.lm_head(kept_hidden_states)
|
|
124
|
+
if labels is not None:
|
|
125
|
+
loss = self.loss_function(
|
|
126
|
+
logits=logits,
|
|
127
|
+
labels=labels,
|
|
128
|
+
vocab_size=self.config.vocab_size,
|
|
129
|
+
**kwargs,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
if not return_dict:
|
|
133
|
+
output = (logits,) + outputs[1:]
|
|
134
|
+
return (loss,) + output if loss is not None else output
|
|
135
|
+
|
|
136
|
+
return CausalLMOutputWithPast(
|
|
137
|
+
loss=loss,
|
|
138
|
+
logits=logits,
|
|
139
|
+
past_key_values=outputs.past_key_values,
|
|
140
|
+
hidden_states=outputs.hidden_states,
|
|
141
|
+
attentions=outputs.attentions,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def lce_maybe_trainable_lm_head(self, hidden_states, hidden_size, labels, shift_labels, **loss_kwargs):
|
|
146
|
+
lm_head = self.lm_head
|
|
147
|
+
|
|
148
|
+
# Unwrap the module if lm_head has been added as trainable module in PEFT LoRA configuration,
|
|
149
|
+
# i.e. listed in the modules_to_save field of LoraConfig, so the lm_head weights are read
|
|
150
|
+
# from the unwrapped module.
|
|
151
|
+
# See https://huggingface.co/docs/peft/package_reference/lora for reference.
|
|
152
|
+
if PEFT_AVAILABLE and isinstance(lm_head, ModulesToSaveWrapper):
|
|
153
|
+
lm_head = lm_head.modules_to_save.default
|
|
154
|
+
|
|
155
|
+
# If FSDP is used and lm_head is trainable, e.g., during full fine-tuning or with LoRA,
|
|
156
|
+
# reading the lm_head module weights and calling the kernel must be done within FSDP forward pass
|
|
157
|
+
# so the module entire parameters are summoned and kept in memory during the kernel execution.
|
|
158
|
+
if isinstance(lm_head, FullyShardedDataParallel):
|
|
159
|
+
return _FSDPForwardRedirection()(
|
|
160
|
+
lm_head,
|
|
161
|
+
_liger_for_causal_lm_loss,
|
|
162
|
+
lm_head.module,
|
|
163
|
+
hidden_states,
|
|
164
|
+
hidden_size,
|
|
165
|
+
labels,
|
|
166
|
+
shift_labels,
|
|
167
|
+
**loss_kwargs,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# FSDP is not used so we can read the lm_head weights and call the kernel directly
|
|
171
|
+
return _liger_for_causal_lm_loss(
|
|
172
|
+
lm_head=self.lm_head,
|
|
173
|
+
hidden_states=hidden_states,
|
|
174
|
+
hidden_size=hidden_size,
|
|
175
|
+
labels=labels,
|
|
176
|
+
shift_labels=shift_labels,
|
|
177
|
+
**loss_kwargs,
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _liger_for_causal_lm_loss(lm_head, hidden_states, hidden_size, labels, shift_labels, **loss_kwargs):
|
|
182
|
+
return LigerForCausalLMLoss(
|
|
183
|
+
hidden_states=hidden_states,
|
|
184
|
+
lm_head_weight=lm_head.weight,
|
|
185
|
+
labels=labels,
|
|
186
|
+
hidden_size=hidden_size,
|
|
187
|
+
shift_labels=shift_labels,
|
|
188
|
+
**loss_kwargs,
|
|
189
|
+
)
|