liger-kernel 0.6.1__py3-none-any.whl → 0.6.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.
- liger_kernel/chunked_loss/dpo_loss.py +54 -3
- liger_kernel/ops/fused_linear_cross_entropy.py +21 -13
- liger_kernel/ops/llama4_rope.py +225 -0
- liger_kernel/transformers/__init__.py +15 -0
- liger_kernel/transformers/experimental/__init__.py +5 -0
- liger_kernel/transformers/functional.py +2 -0
- liger_kernel/transformers/fused_linear_cross_entropy.py +3 -0
- liger_kernel/transformers/llama4_rope.py +93 -0
- liger_kernel/transformers/model/glm4v.py +150 -0
- liger_kernel/transformers/model/loss_utils.py +2 -0
- liger_kernel/transformers/model/mllama.py +4 -2
- liger_kernel/transformers/model/phi3.py +8 -159
- liger_kernel/transformers/monkey_patch.py +100 -20
- {liger_kernel-0.6.1.dist-info → liger_kernel-0.6.2.dist-info}/METADATA +2 -2
- {liger_kernel-0.6.1.dist-info → liger_kernel-0.6.2.dist-info}/RECORD +19 -15
- {liger_kernel-0.6.1.dist-info → liger_kernel-0.6.2.dist-info}/WHEEL +0 -0
- {liger_kernel-0.6.1.dist-info → liger_kernel-0.6.2.dist-info}/licenses/LICENSE +0 -0
- {liger_kernel-0.6.1.dist-info → liger_kernel-0.6.2.dist-info}/licenses/NOTICE +0 -0
- {liger_kernel-0.6.1.dist-info → liger_kernel-0.6.2.dist-info}/top_level.txt +0 -0
|
@@ -13,6 +13,7 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
|
|
|
13
13
|
ref_chosen_logps=None,
|
|
14
14
|
ref_rejected_logps=None,
|
|
15
15
|
beta=0.1,
|
|
16
|
+
loss_type="sigmoid",
|
|
16
17
|
):
|
|
17
18
|
"""
|
|
18
19
|
Paper: https://arxiv.org/pdf/2305.18290
|
|
@@ -48,8 +49,50 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
|
|
|
48
49
|
chosen_rewards = beta * chosen_logratios
|
|
49
50
|
rejected_rewards = beta * rejected_logratios
|
|
50
51
|
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
if loss_type == "sigmoid":
|
|
53
|
+
logits_diff = beta * (chosen_logratios - rejected_logratios)
|
|
54
|
+
loss = -F.logsigmoid(logits_diff).sum() / (full_target.shape[0] // 2)
|
|
55
|
+
|
|
56
|
+
elif loss_type == "apo_zero":
|
|
57
|
+
# Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
|
|
58
|
+
# Use this loss when you believe the chosen outputs are better than your model's default output
|
|
59
|
+
losses_chosen = 1 - F.sigmoid(beta * chosen_logratios) # Increase chosen likelihood
|
|
60
|
+
losses_rejected = F.sigmoid(beta * rejected_logratios)
|
|
61
|
+
losses = losses_chosen + losses_rejected
|
|
62
|
+
loss = losses.sum() / (full_target.shape[0] // 2)
|
|
63
|
+
|
|
64
|
+
elif loss_type == "apo_down":
|
|
65
|
+
# Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266)
|
|
66
|
+
# Use this loss when you believe the chosen outputs are worse than your model's default output.
|
|
67
|
+
# Decrease chosen likelihood and decrease rejected likelihood more
|
|
68
|
+
losses_chosen = F.sigmoid(beta * chosen_logratios)
|
|
69
|
+
losses_rejected = 1 - F.sigmoid(beta * (chosen_logratios - rejected_logratios))
|
|
70
|
+
losses = losses_chosen + losses_rejected
|
|
71
|
+
loss = losses.sum() / (full_target.shape[0] // 2)
|
|
72
|
+
|
|
73
|
+
elif loss_type == "sppo_hard":
|
|
74
|
+
# In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach,
|
|
75
|
+
# estimated using the PairRM score. The probability calculation is conducted outside of the trainer class.
|
|
76
|
+
# The version described here is the hard probability version, where P in Equation (4.7) of Algorithm 1 is
|
|
77
|
+
# set to 1 for the winner and 0 for the loser.
|
|
78
|
+
a = chosen_logps - ref_chosen_logps
|
|
79
|
+
b = rejected_logps - ref_rejected_logps
|
|
80
|
+
losses = (a - 0.5 / beta) ** 2 + (b + 0.5 / beta) ** 2
|
|
81
|
+
loss = losses.sum() / (full_target.shape[0] // 2)
|
|
82
|
+
|
|
83
|
+
elif loss_type == "nca_pair":
|
|
84
|
+
losses = (
|
|
85
|
+
-F.logsigmoid(chosen_rewards)
|
|
86
|
+
- 0.5 * F.logsigmoid(-chosen_rewards)
|
|
87
|
+
- 0.5 * F.logsigmoid(-rejected_rewards)
|
|
88
|
+
)
|
|
89
|
+
loss = losses.sum() / (full_target.shape[0] // 2)
|
|
90
|
+
|
|
91
|
+
else:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
f"Unsupported loss_type: {loss_type}. Supported types are: sigmoid, apo_zero, apo_down, sppo_hard, nca_pair"
|
|
94
|
+
)
|
|
95
|
+
|
|
53
96
|
return loss, chosen_rewards, rejected_rewards
|
|
54
97
|
|
|
55
98
|
@classmethod
|
|
@@ -70,6 +113,7 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
|
|
|
70
113
|
use_ref_model=True,
|
|
71
114
|
average_log_prob=False,
|
|
72
115
|
chunk_size=1,
|
|
116
|
+
loss_type="sigmoid",
|
|
73
117
|
):
|
|
74
118
|
"""
|
|
75
119
|
Fused linear layer with DPO loss.
|
|
@@ -108,12 +152,13 @@ class LigerFusedLinearDPOFunction(LigerFusedLinearPreferenceBase):
|
|
|
108
152
|
ref_bias=ref_bias,
|
|
109
153
|
average_log_prob=average_log_prob,
|
|
110
154
|
chunk_size=chunk_size,
|
|
155
|
+
loss_type=loss_type,
|
|
111
156
|
)
|
|
112
157
|
|
|
113
158
|
@staticmethod
|
|
114
159
|
def backward(ctx, *grad_output):
|
|
115
160
|
grads = LigerFusedLinearPreferenceBase.backward(ctx, grad_output)[:4]
|
|
116
|
-
return *grads, None, None, None, None, None, None, None, None, None, None
|
|
161
|
+
return *grads, None, None, None, None, None, None, None, None, None, None, None
|
|
117
162
|
|
|
118
163
|
|
|
119
164
|
class LigerFusedLinearDPOLoss(torch.nn.Module):
|
|
@@ -130,6 +175,7 @@ class LigerFusedLinearDPOLoss(torch.nn.Module):
|
|
|
130
175
|
use_ref_model: bool = True,
|
|
131
176
|
average_log_prob: bool = False,
|
|
132
177
|
chunk_size: int = 1,
|
|
178
|
+
loss_type: str = "sigmoid",
|
|
133
179
|
):
|
|
134
180
|
"""
|
|
135
181
|
Args:
|
|
@@ -149,6 +195,10 @@ class LigerFusedLinearDPOLoss(torch.nn.Module):
|
|
|
149
195
|
self.use_ref_model = use_ref_model
|
|
150
196
|
self.average_log_prob = average_log_prob
|
|
151
197
|
self.chunk_size = chunk_size
|
|
198
|
+
self.loss_type = loss_type
|
|
199
|
+
supported_loss_types = {"sigmoid", "apo_zero", "apo_down", "sppo_hard", "nca_pair"}
|
|
200
|
+
if self.loss_type not in supported_loss_types:
|
|
201
|
+
raise ValueError(f"Unsupported loss_type: {self.loss_type}. Supported types are: {supported_loss_types}")
|
|
152
202
|
|
|
153
203
|
def forward(
|
|
154
204
|
self,
|
|
@@ -175,4 +225,5 @@ class LigerFusedLinearDPOLoss(torch.nn.Module):
|
|
|
175
225
|
self.use_ref_model,
|
|
176
226
|
self.average_log_prob,
|
|
177
227
|
self.chunk_size,
|
|
228
|
+
self.loss_type,
|
|
178
229
|
)
|
|
@@ -25,6 +25,7 @@ def fused_linear_cross_entropy_forward(
|
|
|
25
25
|
reduction="mean",
|
|
26
26
|
softcap=None,
|
|
27
27
|
return_z_loss=False,
|
|
28
|
+
accum_dtype=None,
|
|
28
29
|
):
|
|
29
30
|
assert isinstance(return_z_loss, bool), f"return_z_loss must be True or False. Got: {return_z_loss}"
|
|
30
31
|
device = _input.device
|
|
@@ -44,10 +45,16 @@ def fused_linear_cross_entropy_forward(
|
|
|
44
45
|
chunk_size = triton.next_power_of_2(triton.cdiv(BT, inc_factor)) # (BT + inc_factor - 1) // inc_factor
|
|
45
46
|
num_chunks = triton.cdiv(BT, chunk_size) # (BT + chunk_size - 1) // chunk_size
|
|
46
47
|
|
|
47
|
-
grad_weight = torch.zeros_like(weight, device=device) if weight.requires_grad else None
|
|
48
48
|
grad_input = torch.zeros_like(_input, device=device)
|
|
49
|
-
|
|
50
|
-
# we use fp32 for loss accumulator
|
|
49
|
+
|
|
50
|
+
# we use fp32 for loss and gradients accumulator
|
|
51
|
+
if accum_dtype is None:
|
|
52
|
+
grad_weight = torch.zeros_like(weight, device=device) if weight.requires_grad else None
|
|
53
|
+
grad_bias = torch.zeros_like(bias, device=device) if bias is not None else None
|
|
54
|
+
else:
|
|
55
|
+
grad_weight = torch.zeros_like(weight, dtype=accum_dtype, device=device) if weight.requires_grad else None
|
|
56
|
+
grad_bias = torch.zeros_like(bias, dtype=accum_dtype, device=device) if bias is not None else None
|
|
57
|
+
|
|
51
58
|
loss_1d = torch.zeros(BT, dtype=torch.float32, device=device)
|
|
52
59
|
z_loss_1d = torch.zeros(BT, dtype=_input.dtype, device=_input.device) if return_z_loss else None
|
|
53
60
|
|
|
@@ -124,16 +131,7 @@ def fused_linear_cross_entropy_forward(
|
|
|
124
131
|
grad_input[start_idx:end_idx] = grad_logits_chunk @ weight
|
|
125
132
|
|
|
126
133
|
if grad_weight is not None:
|
|
127
|
-
torch.
|
|
128
|
-
input=grad_weight,
|
|
129
|
-
mat1=logits_chunk.t().to(
|
|
130
|
-
_input_chunk.dtype
|
|
131
|
-
), # In an autocast scenario without bias, differing logits_chunk data types will cause an addmm operation error.
|
|
132
|
-
mat2=_input_chunk,
|
|
133
|
-
out=grad_weight,
|
|
134
|
-
alpha=1.0,
|
|
135
|
-
beta=1.0,
|
|
136
|
-
)
|
|
134
|
+
grad_weight += torch.mm(grad_logits_chunk.t(), _input_chunk).float()
|
|
137
135
|
|
|
138
136
|
if bias is not None:
|
|
139
137
|
torch.add(
|
|
@@ -151,6 +149,11 @@ def fused_linear_cross_entropy_forward(
|
|
|
151
149
|
else:
|
|
152
150
|
loss = torch.sum(loss_1d)
|
|
153
151
|
z_loss = torch.sum(z_loss_1d) if return_z_loss else None
|
|
152
|
+
|
|
153
|
+
# Cast back to original dtype
|
|
154
|
+
grad_weight = grad_weight.to(weight.dtype) if grad_weight is not None else None
|
|
155
|
+
grad_bias = grad_bias.to(bias.dtype) if grad_bias is not None else None
|
|
156
|
+
|
|
154
157
|
return loss, z_loss, grad_input, grad_weight, grad_bias
|
|
155
158
|
|
|
156
159
|
|
|
@@ -217,6 +220,7 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
|
|
|
217
220
|
reduction="mean",
|
|
218
221
|
softcap=None,
|
|
219
222
|
return_z_loss: bool = False,
|
|
223
|
+
accum_dtype=None,
|
|
220
224
|
):
|
|
221
225
|
"""
|
|
222
226
|
Fusing the last linear layer with cross-entropy loss
|
|
@@ -235,6 +239,8 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
|
|
|
235
239
|
ignore_index: the index to ignore in the target
|
|
236
240
|
label_smoothing (float): The amount of smoothing when computing the loss, where 0.0 means no smoothing.
|
|
237
241
|
reduction: reduction to apply
|
|
242
|
+
accum_dtype (torch.dtype): the dtype of intermediate result buffers for weight and bias gradient accumulations.
|
|
243
|
+
Recommended to set `accum_dtype` to higher precision, e.g. `torch.float32`, if the training is unstable with original dtype. Default: `None`, performing accumulations in original dtype
|
|
238
244
|
"""
|
|
239
245
|
|
|
240
246
|
loss, z_loss, grad_input, grad_weight, grad_bias = fused_linear_cross_entropy_forward(
|
|
@@ -249,6 +255,7 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
|
|
|
249
255
|
reduction=reduction,
|
|
250
256
|
softcap=softcap,
|
|
251
257
|
return_z_loss=return_z_loss,
|
|
258
|
+
accum_dtype=accum_dtype,
|
|
252
259
|
)
|
|
253
260
|
# downcast to dtype and store for backward
|
|
254
261
|
ctx.save_for_backward(
|
|
@@ -280,4 +287,5 @@ class LigerFusedLinearCrossEntropyFunction(torch.autograd.Function):
|
|
|
280
287
|
None,
|
|
281
288
|
None,
|
|
282
289
|
None,
|
|
290
|
+
None,
|
|
283
291
|
)
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import triton
|
|
3
|
+
import triton.language as tl
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _prepare_freqs(freqs_cis: torch.Tensor, seq_len: int, head_dim_half: int):
|
|
7
|
+
# Split or unpack complex frequencies into real and imag parts
|
|
8
|
+
if freqs_cis.is_complex():
|
|
9
|
+
freqs_real = freqs_cis.real
|
|
10
|
+
freqs_imag = freqs_cis.imag
|
|
11
|
+
else:
|
|
12
|
+
# Already split: last dim should be 2*head_dim_half
|
|
13
|
+
if freqs_cis.shape[-1] == 2 * head_dim_half:
|
|
14
|
+
freqs_real = freqs_cis[..., :head_dim_half]
|
|
15
|
+
freqs_imag = freqs_cis[..., head_dim_half:]
|
|
16
|
+
else:
|
|
17
|
+
raise ValueError(
|
|
18
|
+
f"Unexpected freqs_cis shape for non-complex input: {freqs_cis.shape}, expected last dim = {2 * head_dim_half}"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# Canonicalize to shape (seq_len, head_dim_half):
|
|
22
|
+
# 1) Ensure the last dimension is head_dim_half
|
|
23
|
+
if freqs_real.shape[-1] != head_dim_half:
|
|
24
|
+
raise ValueError(f"Unexpected last dim for freqs: {freqs_real.shape[-1]} (expected {head_dim_half})")
|
|
25
|
+
# 2) Flatten all leading dims to a single row dimension
|
|
26
|
+
freqs_real = freqs_real.reshape(-1, head_dim_half)
|
|
27
|
+
freqs_imag = freqs_imag.reshape(-1, head_dim_half)
|
|
28
|
+
# 3) If we have fewer rows than seq_len, allow broadcasting when single row
|
|
29
|
+
if freqs_real.shape[0] < seq_len:
|
|
30
|
+
if freqs_real.shape[0] == 1:
|
|
31
|
+
freqs_real = freqs_real.expand(seq_len, -1)
|
|
32
|
+
freqs_imag = freqs_imag.expand(seq_len, -1)
|
|
33
|
+
else:
|
|
34
|
+
raise ValueError(f"Insufficient rows in freqs: {freqs_real.shape[0]} < seq_len={seq_len}")
|
|
35
|
+
# 4) If we have more rows than seq_len (e.g., batch present), take the first seq_len rows
|
|
36
|
+
elif freqs_real.shape[0] > seq_len:
|
|
37
|
+
freqs_real = freqs_real[:seq_len]
|
|
38
|
+
freqs_imag = freqs_imag[:seq_len]
|
|
39
|
+
|
|
40
|
+
return freqs_real, freqs_imag
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _maybe_to_dtype(t: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
|
|
44
|
+
return t if t.dtype == dtype else t.to(dtype)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _maybe_contiguous(t: torch.Tensor) -> torch.Tensor:
|
|
48
|
+
return t if t.is_contiguous() else t.contiguous()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _cast_and_contiguous(q, k, freqs_real, freqs_imag):
|
|
52
|
+
# Choose compute dtype: use fp32 only when inputs are fp32; otherwise keep input dtype for performance
|
|
53
|
+
compute_dtype = torch.float32 if q.dtype == torch.float32 else q.dtype
|
|
54
|
+
|
|
55
|
+
# Make sure q/k share the same dtype before casting to compute dtype
|
|
56
|
+
if k.dtype != q.dtype:
|
|
57
|
+
k = k.to(q.dtype)
|
|
58
|
+
|
|
59
|
+
q = _maybe_contiguous(_maybe_to_dtype(q, compute_dtype))
|
|
60
|
+
k = _maybe_contiguous(_maybe_to_dtype(k, compute_dtype))
|
|
61
|
+
freqs_real = _maybe_contiguous(_maybe_to_dtype(freqs_real, compute_dtype))
|
|
62
|
+
freqs_imag = _maybe_contiguous(_maybe_to_dtype(freqs_imag, compute_dtype))
|
|
63
|
+
return q, k, freqs_real, freqs_imag
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@triton.jit
|
|
67
|
+
def _llama4_rope_kernel(
|
|
68
|
+
q_ptr,
|
|
69
|
+
k_ptr,
|
|
70
|
+
freqs_real_ptr,
|
|
71
|
+
freqs_imag_ptr,
|
|
72
|
+
q_row_stride,
|
|
73
|
+
k_row_stride,
|
|
74
|
+
q_head_stride,
|
|
75
|
+
k_head_stride,
|
|
76
|
+
freqs_row_stride,
|
|
77
|
+
seq_len,
|
|
78
|
+
batch_size,
|
|
79
|
+
imag_sign,
|
|
80
|
+
head_dim_half: tl.constexpr,
|
|
81
|
+
n_q_heads: tl.constexpr,
|
|
82
|
+
n_k_heads: tl.constexpr,
|
|
83
|
+
BLOCK_SIZE: tl.constexpr,
|
|
84
|
+
):
|
|
85
|
+
"""
|
|
86
|
+
H100-optimized RoPE kernel with improved parallelization across heads and dimensions.
|
|
87
|
+
Grid: (batch*seq, head)
|
|
88
|
+
"""
|
|
89
|
+
# 2D grid
|
|
90
|
+
pid_bs = tl.program_id(0) # over batch*seq
|
|
91
|
+
pid_h = tl.program_id(1) # over heads
|
|
92
|
+
|
|
93
|
+
batch_idx = pid_bs // seq_len
|
|
94
|
+
seq_idx = pid_bs % seq_len
|
|
95
|
+
|
|
96
|
+
# Bounds check
|
|
97
|
+
if batch_idx >= batch_size or seq_idx >= seq_len:
|
|
98
|
+
return
|
|
99
|
+
|
|
100
|
+
# Base pointers for this (batch, seq) position
|
|
101
|
+
base_offset = batch_idx * seq_len + seq_idx
|
|
102
|
+
q_base = q_ptr + base_offset * q_row_stride
|
|
103
|
+
k_base = k_ptr + base_offset * k_row_stride
|
|
104
|
+
|
|
105
|
+
# Tiling over dim/2
|
|
106
|
+
for d_start in tl.static_range(0, head_dim_half, BLOCK_SIZE):
|
|
107
|
+
d_indices = d_start + tl.arange(0, BLOCK_SIZE)
|
|
108
|
+
mask_d = d_indices < head_dim_half
|
|
109
|
+
|
|
110
|
+
# Load frequencies once per tile (freqs layout: [seq_len, head_dim_half])
|
|
111
|
+
freq_idx = d_indices
|
|
112
|
+
freqs_real = tl.load(freqs_real_ptr + seq_idx * freqs_row_stride + freq_idx, mask=mask_d, other=0.0)
|
|
113
|
+
freqs_imag = tl.load(freqs_imag_ptr + seq_idx * freqs_row_stride + freq_idx, mask=mask_d, other=0.0)
|
|
114
|
+
freqs_imag = freqs_imag * imag_sign
|
|
115
|
+
|
|
116
|
+
# Process one query head per program in pid_h
|
|
117
|
+
if pid_h < n_q_heads:
|
|
118
|
+
q_head_ptr = q_base + pid_h * q_head_stride
|
|
119
|
+
q_real = tl.load(q_head_ptr + d_indices * 2, mask=mask_d, other=0.0)
|
|
120
|
+
q_imag = tl.load(q_head_ptr + d_indices * 2 + 1, mask=mask_d, other=0.0)
|
|
121
|
+
|
|
122
|
+
# Complex multiply with FMAs: (a+ib)*(c+i d) = (a*c - b*d) + i(a*d + b*c)
|
|
123
|
+
new_q_real = tl.math.fma(q_real, freqs_real, -(q_imag * freqs_imag))
|
|
124
|
+
new_q_imag = tl.math.fma(q_real, freqs_imag, q_imag * freqs_real)
|
|
125
|
+
|
|
126
|
+
tl.store(q_head_ptr + d_indices * 2, new_q_real, mask=mask_d)
|
|
127
|
+
tl.store(q_head_ptr + d_indices * 2 + 1, new_q_imag, mask=mask_d)
|
|
128
|
+
|
|
129
|
+
# Process one key head per program in pid_h
|
|
130
|
+
if pid_h < n_k_heads:
|
|
131
|
+
k_head_ptr = k_base + pid_h * k_head_stride
|
|
132
|
+
k_real = tl.load(k_head_ptr + d_indices * 2, mask=mask_d, other=0.0)
|
|
133
|
+
k_imag = tl.load(k_head_ptr + d_indices * 2 + 1, mask=mask_d, other=0.0)
|
|
134
|
+
|
|
135
|
+
new_k_real = tl.math.fma(k_real, freqs_real, -(k_imag * freqs_imag))
|
|
136
|
+
new_k_imag = tl.math.fma(k_real, freqs_imag, k_imag * freqs_real)
|
|
137
|
+
|
|
138
|
+
tl.store(k_head_ptr + d_indices * 2, new_k_real, mask=mask_d)
|
|
139
|
+
tl.store(k_head_ptr + d_indices * 2 + 1, new_k_imag, mask=mask_d)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _select_kernel_meta(head_dim_half: int):
|
|
143
|
+
# Heuristic tuning for block size and num_warps
|
|
144
|
+
if head_dim_half >= 256:
|
|
145
|
+
return 128, 8
|
|
146
|
+
if head_dim_half >= 96:
|
|
147
|
+
return 128, 4
|
|
148
|
+
if head_dim_half >= 48:
|
|
149
|
+
return 64, 4
|
|
150
|
+
if head_dim_half >= 24:
|
|
151
|
+
return 32, 2
|
|
152
|
+
return 16, 2
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def llama4_rope_forward(q, k, freqs_cis, BLOCK_SIZE: int = None, imag_sign: float = 1.0):
|
|
156
|
+
# Save original dtype for casting back
|
|
157
|
+
original_dtype = q.dtype
|
|
158
|
+
|
|
159
|
+
batch_size, seq_len, n_q_heads, head_dim = q.shape
|
|
160
|
+
_, _, n_k_heads, _ = k.shape
|
|
161
|
+
head_dim_half = head_dim // 2
|
|
162
|
+
|
|
163
|
+
# Prepare frequencies
|
|
164
|
+
freqs_real, freqs_imag = _prepare_freqs(freqs_cis, seq_len, head_dim_half)
|
|
165
|
+
|
|
166
|
+
# Cast to appropriate dtype and make contiguous only when needed
|
|
167
|
+
q, k, freqs_real, freqs_imag = _cast_and_contiguous(q, k, freqs_real, freqs_imag)
|
|
168
|
+
|
|
169
|
+
# H100-optimized meta-params
|
|
170
|
+
if BLOCK_SIZE is None:
|
|
171
|
+
BLOCK_SIZE, num_warps = _select_kernel_meta(head_dim_half)
|
|
172
|
+
else:
|
|
173
|
+
# Provide a default num_warps if caller pins BLOCK_SIZE
|
|
174
|
+
_, num_warps = _select_kernel_meta(head_dim_half)
|
|
175
|
+
|
|
176
|
+
# 2D grid: one program per (batch, seq, head)
|
|
177
|
+
n_heads_max = max(n_q_heads, n_k_heads)
|
|
178
|
+
grid = (batch_size * seq_len, n_heads_max)
|
|
179
|
+
|
|
180
|
+
# Launch kernel
|
|
181
|
+
_llama4_rope_kernel[grid](
|
|
182
|
+
q,
|
|
183
|
+
k,
|
|
184
|
+
freqs_real,
|
|
185
|
+
freqs_imag,
|
|
186
|
+
q.stride(1),
|
|
187
|
+
k.stride(1),
|
|
188
|
+
q.stride(2),
|
|
189
|
+
k.stride(2),
|
|
190
|
+
freqs_real.stride(0),
|
|
191
|
+
seq_len,
|
|
192
|
+
batch_size,
|
|
193
|
+
imag_sign,
|
|
194
|
+
head_dim_half,
|
|
195
|
+
n_q_heads,
|
|
196
|
+
n_k_heads,
|
|
197
|
+
BLOCK_SIZE,
|
|
198
|
+
num_warps=num_warps,
|
|
199
|
+
num_stages=2,
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Cast back to original dtype only if it differs from compute dtype
|
|
203
|
+
if q.dtype != original_dtype:
|
|
204
|
+
q = q.to(original_dtype)
|
|
205
|
+
if k.dtype != original_dtype:
|
|
206
|
+
k = k.to(original_dtype)
|
|
207
|
+
|
|
208
|
+
return q, k
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class LigerLlama4RopeFunction(torch.autograd.Function):
|
|
212
|
+
@staticmethod
|
|
213
|
+
def forward(ctx, q, k, freqs_cis, BLOCK_SIZE: int = None):
|
|
214
|
+
q_out, k_out = llama4_rope_forward(q, k, freqs_cis, BLOCK_SIZE, imag_sign=1.0)
|
|
215
|
+
ctx.save_for_backward(freqs_cis.detach() if isinstance(freqs_cis, torch.Tensor) else freqs_cis)
|
|
216
|
+
ctx.BLOCK_SIZE = BLOCK_SIZE
|
|
217
|
+
return q_out, k_out
|
|
218
|
+
|
|
219
|
+
@staticmethod
|
|
220
|
+
def backward(ctx, dq, dk):
|
|
221
|
+
(freqs_cis,) = ctx.saved_tensors
|
|
222
|
+
BLOCK_SIZE = getattr(ctx, "BLOCK_SIZE", None)
|
|
223
|
+
# Use imag_sign=-1.0 for conjugate without materializing a new tensor
|
|
224
|
+
dq_out, dk_out = llama4_rope_forward(dq, dk, freqs_cis, BLOCK_SIZE, imag_sign=-1.0)
|
|
225
|
+
return dq_out, dk_out, None
|
|
@@ -10,9 +10,15 @@ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinea
|
|
|
10
10
|
from liger_kernel.transformers.fused_linear_jsd import LigerFusedLinearJSD # noqa: F401
|
|
11
11
|
from liger_kernel.transformers.geglu import LigerGEGLUMLP # noqa: F401
|
|
12
12
|
from liger_kernel.transformers.jsd import LigerJSD # noqa: F401
|
|
13
|
+
from liger_kernel.transformers.kl_div import LigerKLDIVLoss # noqa: F401
|
|
13
14
|
from liger_kernel.transformers.layer_norm import LigerLayerNorm # noqa: F401
|
|
15
|
+
from liger_kernel.transformers.llama4_rope import liger_llama4_text_rotary_pos_emb # noqa: F401
|
|
16
|
+
from liger_kernel.transformers.llama4_rope import liger_llama4_vision_rotary_pos_emb # noqa: F401
|
|
17
|
+
from liger_kernel.transformers.multi_token_attention import LigerMultiTokenAttention # noqa: F401
|
|
14
18
|
from liger_kernel.transformers.rms_norm import LigerRMSNorm # noqa: F401
|
|
15
19
|
from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
|
|
20
|
+
from liger_kernel.transformers.softmax import LigerSoftmax # noqa: F401
|
|
21
|
+
from liger_kernel.transformers.sparsemax import LigerSparsemax # noqa: F401
|
|
16
22
|
from liger_kernel.transformers.swiglu import LigerBlockSparseTop2MLP # noqa: F401
|
|
17
23
|
from liger_kernel.transformers.swiglu import LigerPhi3SwiGLUMLP # noqa: F401
|
|
18
24
|
from liger_kernel.transformers.swiglu import LigerQwen3MoeSwiGLUMLP # noqa: F401
|
|
@@ -29,6 +35,7 @@ if TYPE_CHECKING:
|
|
|
29
35
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma3 # noqa: F401
|
|
30
36
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma3_text # noqa: F401
|
|
31
37
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_glm4 # noqa: F401
|
|
38
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_glm4v # noqa: F401
|
|
32
39
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_granite # noqa: F401
|
|
33
40
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama # noqa: F401
|
|
34
41
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama4 # noqa: F401
|
|
@@ -87,6 +94,7 @@ def __getattr__(name: str):
|
|
|
87
94
|
"apply_liger_kernel_to_gemma3",
|
|
88
95
|
"apply_liger_kernel_to_gemma3_text",
|
|
89
96
|
"apply_liger_kernel_to_glm4",
|
|
97
|
+
"apply_liger_kernel_to_glm4v",
|
|
90
98
|
"apply_liger_kernel_to_granite",
|
|
91
99
|
"apply_liger_kernel_to_llama",
|
|
92
100
|
"apply_liger_kernel_to_llava",
|
|
@@ -125,11 +133,17 @@ __all__ = [
|
|
|
125
133
|
"LigerFusedAddRMSNorm",
|
|
126
134
|
"LigerRMSNorm",
|
|
127
135
|
"liger_rotary_pos_emb",
|
|
136
|
+
"liger_llama4_text_rotary_pos_emb",
|
|
137
|
+
"liger_llama4_vision_rotary_pos_emb",
|
|
128
138
|
"LigerBlockSparseTop2MLP",
|
|
129
139
|
"LigerPhi3SwiGLUMLP",
|
|
130
140
|
"LigerQwen3MoeSwiGLUMLP",
|
|
131
141
|
"LigerSwiGLUMLP",
|
|
132
142
|
"LigerTVDLoss",
|
|
143
|
+
"LigerKLDIVLoss",
|
|
144
|
+
"LigerMultiTokenAttention",
|
|
145
|
+
"LigerSoftmax",
|
|
146
|
+
"LigerSparsemax",
|
|
133
147
|
]
|
|
134
148
|
|
|
135
149
|
# Add transformer-dependent symbols only if available
|
|
@@ -144,6 +158,7 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
144
158
|
"apply_liger_kernel_to_gemma3",
|
|
145
159
|
"apply_liger_kernel_to_gemma3_text",
|
|
146
160
|
"apply_liger_kernel_to_glm4",
|
|
161
|
+
"apply_liger_kernel_to_glm4v",
|
|
147
162
|
"apply_liger_kernel_to_granite",
|
|
148
163
|
"apply_liger_kernel_to_llama",
|
|
149
164
|
"apply_liger_kernel_to_llava",
|
|
@@ -64,6 +64,7 @@ def liger_fused_linear_cross_entropy(
|
|
|
64
64
|
reduction: str = "mean",
|
|
65
65
|
softcap: Optional[float] = None,
|
|
66
66
|
return_z_loss: bool = False,
|
|
67
|
+
accum_dtype=None,
|
|
67
68
|
):
|
|
68
69
|
loss, z_loss = LigerFusedLinearCrossEntropyFunction.apply(
|
|
69
70
|
input,
|
|
@@ -77,6 +78,7 @@ def liger_fused_linear_cross_entropy(
|
|
|
77
78
|
reduction,
|
|
78
79
|
softcap,
|
|
79
80
|
return_z_loss,
|
|
81
|
+
accum_dtype,
|
|
80
82
|
)
|
|
81
83
|
if not return_z_loss:
|
|
82
84
|
return loss
|
|
@@ -15,6 +15,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
15
15
|
reduction: str = "mean",
|
|
16
16
|
softcap: Optional[float] = None,
|
|
17
17
|
return_z_loss: bool = False,
|
|
18
|
+
accum_dtype: Optional[torch.dtype] = None,
|
|
18
19
|
):
|
|
19
20
|
super().__init__()
|
|
20
21
|
assert (label_smoothing >= 0) and (label_smoothing <= 1), (
|
|
@@ -32,6 +33,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
32
33
|
self.reduction = reduction
|
|
33
34
|
self.softcap = softcap
|
|
34
35
|
self.return_z_loss = return_z_loss
|
|
36
|
+
self.accum_dtype = accum_dtype
|
|
35
37
|
|
|
36
38
|
def forward(self, lin_weight, _input, target, bias=None):
|
|
37
39
|
loss, z_loss = LigerFusedLinearCrossEntropyFunction.apply(
|
|
@@ -46,6 +48,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
46
48
|
self.reduction,
|
|
47
49
|
self.softcap,
|
|
48
50
|
self.return_z_loss,
|
|
51
|
+
self.accum_dtype,
|
|
49
52
|
)
|
|
50
53
|
if not self.return_z_loss:
|
|
51
54
|
return loss
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Liger Kernel implementation of Llama4 Rotary Position Embedding (RoPE).
|
|
3
|
+
Supports both text and vision RoPE variants with fused operations for optimal performance.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from liger_kernel.ops.llama4_rope import LigerLlama4RopeFunction
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def liger_llama4_text_rotary_pos_emb(
|
|
12
|
+
xq: torch.Tensor,
|
|
13
|
+
xk: torch.Tensor,
|
|
14
|
+
freqs_cis: torch.Tensor,
|
|
15
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
16
|
+
"""
|
|
17
|
+
Liger-optimized implementation of Llama4 text rotary position embedding.
|
|
18
|
+
|
|
19
|
+
This implementation uses a fused Triton kernel for complex multiplication,
|
|
20
|
+
providing significant performance improvements over the original PyTorch implementation.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
xq (torch.Tensor): Query tensor of shape (batch_size, seq_len, num_heads, head_dim)
|
|
24
|
+
xk (torch.Tensor): Key tensor of shape (batch_size, seq_len, num_heads, head_dim)
|
|
25
|
+
freqs_cis (torch.Tensor): Complex frequency tensor from Llama4TextRotaryEmbedding
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
Tuple[torch.Tensor, torch.Tensor]: Rotated query and key tensors
|
|
29
|
+
"""
|
|
30
|
+
# Use fused Triton kernel for complex RoPE
|
|
31
|
+
return LigerLlama4RopeFunction.apply(xq, xk, freqs_cis)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def liger_llama4_vision_rotary_pos_emb(
|
|
35
|
+
query: torch.Tensor,
|
|
36
|
+
key: torch.Tensor,
|
|
37
|
+
freqs_ci: torch.Tensor,
|
|
38
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
39
|
+
"""
|
|
40
|
+
Liger-optimized implementation of Llama4 vision rotary position embedding.
|
|
41
|
+
|
|
42
|
+
This implementation uses the same fused Triton kernel as text RoPE,
|
|
43
|
+
providing performance improvements for vision transformer attention.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
query (torch.Tensor): Query tensor of shape (batch_size, seq_len, num_heads, head_dim)
|
|
47
|
+
key (torch.Tensor): Key tensor of shape (batch_size, seq_len, num_heads, head_dim)
|
|
48
|
+
freqs_ci (torch.Tensor): Complex frequency tensor for 2D positions
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Tuple[torch.Tensor, torch.Tensor]: Rotated query and key tensors
|
|
52
|
+
"""
|
|
53
|
+
# Handle broadcasting for vision RoPE
|
|
54
|
+
if freqs_ci.dim() == 3:
|
|
55
|
+
try:
|
|
56
|
+
# Try the regular 3D expansion
|
|
57
|
+
freqs_ci = freqs_ci.unsqueeze(0).expand(query.shape[0], -1, -1)
|
|
58
|
+
except RuntimeError as e:
|
|
59
|
+
if "expand" in str(e) and "4" in str(e):
|
|
60
|
+
# The tensor is actually 4D internally, handle it differently
|
|
61
|
+
freqs_ci = freqs_ci.squeeze(1) # Remove the middle dimension
|
|
62
|
+
freqs_ci = freqs_ci.unsqueeze(0).expand(query.shape[0], -1, -1)
|
|
63
|
+
else:
|
|
64
|
+
raise e
|
|
65
|
+
elif freqs_ci.dim() == 4: # (1, seq_len, 1, head_dim//2) - already properly shaped
|
|
66
|
+
# Squeeze the middle dimension to get (1, seq_len, head_dim//2)
|
|
67
|
+
freqs_ci = freqs_ci.squeeze(2)
|
|
68
|
+
elif freqs_ci.dim() == 2: # (seq_len, head_dim//2) - needs expansion
|
|
69
|
+
freqs_ci = freqs_ci.unsqueeze(0).expand(query.shape[0], -1, -1)
|
|
70
|
+
else:
|
|
71
|
+
raise ValueError(f"Unexpected freqs_ci shape: {freqs_ci.shape}")
|
|
72
|
+
|
|
73
|
+
# Use the same fused kernel as text RoPE
|
|
74
|
+
return LigerLlama4RopeFunction.apply(query, key, freqs_ci)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Note: We only patch the functions, not the classes
|
|
78
|
+
# The original Llama4TextRotaryEmbedding and Llama4VisionRotaryEmbedding classes remain unchanged
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# Convenience functions for monkey patching
|
|
82
|
+
def apply_liger_llama4_rope_full(modeling_module):
|
|
83
|
+
"""
|
|
84
|
+
Apply Liger optimizations to Llama4 RoPE functions.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
modeling_module: The transformers modeling module to patch
|
|
88
|
+
"""
|
|
89
|
+
# Replace the text RoPE function
|
|
90
|
+
modeling_module.apply_rotary_emb = liger_llama4_text_rotary_pos_emb
|
|
91
|
+
|
|
92
|
+
# Replace the vision RoPE function
|
|
93
|
+
modeling_module.vision_apply_rotary_emb = liger_llama4_vision_rotary_pos_emb
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
from typing import Optional
|
|
3
|
+
from typing import Tuple
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
9
|
+
from transformers.utils.deprecation import deprecate_kwarg
|
|
10
|
+
|
|
11
|
+
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
15
|
+
def lce_forward(
|
|
16
|
+
self,
|
|
17
|
+
input_ids: torch.LongTensor = None,
|
|
18
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
19
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
20
|
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
21
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
22
|
+
labels: Optional[torch.LongTensor] = None,
|
|
23
|
+
use_cache: Optional[bool] = None,
|
|
24
|
+
output_attentions: Optional[bool] = None,
|
|
25
|
+
output_hidden_states: Optional[bool] = None,
|
|
26
|
+
return_dict: Optional[bool] = None,
|
|
27
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
28
|
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
|
29
|
+
skip_logits: Optional[bool] = None,
|
|
30
|
+
**kwargs,
|
|
31
|
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
32
|
+
r"""
|
|
33
|
+
Args:
|
|
34
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
35
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
36
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
37
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
38
|
+
|
|
39
|
+
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
40
|
+
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
41
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
42
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
43
|
+
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
44
|
+
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
>>> from PIL import Image
|
|
52
|
+
>>> from transformers import AutoTokenizer, Glm4vForConditionalGeneration
|
|
53
|
+
|
|
54
|
+
>>> MODEL_PATH = "THUDM/GLM-4.1V-9B-Thinking"
|
|
55
|
+
>>> messages = [
|
|
56
|
+
{
|
|
57
|
+
"role": "user",
|
|
58
|
+
"content": [
|
|
59
|
+
{
|
|
60
|
+
"type": "image",
|
|
61
|
+
"url": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Grayscale_8bits_palette_sample_image.png"
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
"type": "text",
|
|
65
|
+
"text": "describe this image"
|
|
66
|
+
}
|
|
67
|
+
],
|
|
68
|
+
}
|
|
69
|
+
]
|
|
70
|
+
>>> processor = AutoProcessor.from_pretrained(MODEL_PATH, use_fast=True)
|
|
71
|
+
>>> model = Glm4vForConditionalGeneration.from_pretrained(
|
|
72
|
+
pretrained_model_name_or_path=MODEL_PATH,
|
|
73
|
+
torch_dtype=torch.bfloat16,
|
|
74
|
+
device_map="auto",
|
|
75
|
+
)
|
|
76
|
+
>>> inputs = processor.apply_chat_template(
|
|
77
|
+
messages,
|
|
78
|
+
tokenize=True,
|
|
79
|
+
add_generation_prompt=True,
|
|
80
|
+
return_dict=True,
|
|
81
|
+
return_tensors="pt"
|
|
82
|
+
).to(model.device)
|
|
83
|
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=8192)
|
|
84
|
+
output_text = processor.decode(generated_ids[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False)
|
|
85
|
+
<think>Got it, let's describe the image. First, there's a vintage car, specifically a Volkswagen Beetle
|
|
86
|
+
```"""
|
|
87
|
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
88
|
+
output_hidden_states = (
|
|
89
|
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
90
|
+
)
|
|
91
|
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
92
|
+
|
|
93
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
94
|
+
outputs = self.model(
|
|
95
|
+
input_ids=input_ids,
|
|
96
|
+
attention_mask=attention_mask,
|
|
97
|
+
position_ids=position_ids,
|
|
98
|
+
past_key_values=past_key_values,
|
|
99
|
+
inputs_embeds=inputs_embeds,
|
|
100
|
+
use_cache=use_cache,
|
|
101
|
+
output_attentions=output_attentions,
|
|
102
|
+
output_hidden_states=output_hidden_states,
|
|
103
|
+
return_dict=return_dict,
|
|
104
|
+
cache_position=cache_position,
|
|
105
|
+
**kwargs,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
hidden_states = outputs[0]
|
|
109
|
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
110
|
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
111
|
+
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
112
|
+
|
|
113
|
+
shift_labels = kwargs.pop("shift_labels", None)
|
|
114
|
+
logits = None
|
|
115
|
+
loss = None
|
|
116
|
+
|
|
117
|
+
if skip_logits and labels is None and shift_labels is None:
|
|
118
|
+
raise ValueError("skip_logits is True, but labels and shift_labels are None")
|
|
119
|
+
|
|
120
|
+
if skip_logits is None:
|
|
121
|
+
# By default, if in training mode, don't materialize logits
|
|
122
|
+
skip_logits = self.training and (labels is not None or shift_labels is not None)
|
|
123
|
+
|
|
124
|
+
if skip_logits:
|
|
125
|
+
loss = LigerForCausalLMLoss(
|
|
126
|
+
hidden_states=kept_hidden_states,
|
|
127
|
+
lm_head_weight=self.lm_head.weight,
|
|
128
|
+
labels=labels,
|
|
129
|
+
shift_labels=shift_labels,
|
|
130
|
+
hidden_size=self.config.hidden_size,
|
|
131
|
+
**kwargs,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
else:
|
|
135
|
+
logits = self.lm_head(kept_hidden_states)
|
|
136
|
+
if labels is not None:
|
|
137
|
+
loss = self.loss_function(
|
|
138
|
+
logits=logits,
|
|
139
|
+
labels=labels,
|
|
140
|
+
vocab_size=self.config.vocab_size,
|
|
141
|
+
**kwargs,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
return CausalLMOutputWithPast(
|
|
145
|
+
loss=loss,
|
|
146
|
+
logits=logits,
|
|
147
|
+
past_key_values=outputs.past_key_values,
|
|
148
|
+
hidden_states=outputs.hidden_states,
|
|
149
|
+
attentions=outputs.attentions,
|
|
150
|
+
)
|
|
@@ -13,6 +13,7 @@ def fixed_fused_linear_cross_entropy(
|
|
|
13
13
|
num_items_in_batch: Optional[int] = None,
|
|
14
14
|
ignore_index: int = -100,
|
|
15
15
|
final_logit_softcapping: Optional[float] = None,
|
|
16
|
+
accum_dtype: Optional[torch.dtype] = None,
|
|
16
17
|
**kwargs,
|
|
17
18
|
):
|
|
18
19
|
reduction = "sum" if num_items_in_batch is not None else "mean"
|
|
@@ -23,6 +24,7 @@ def fixed_fused_linear_cross_entropy(
|
|
|
23
24
|
reduction=reduction,
|
|
24
25
|
ignore_index=ignore_index,
|
|
25
26
|
softcap=final_logit_softcapping,
|
|
27
|
+
accum_dtype=accum_dtype,
|
|
26
28
|
)
|
|
27
29
|
if reduction == "sum":
|
|
28
30
|
loss = loss / num_items_in_batch
|
|
@@ -190,7 +190,9 @@ def lce_forward(
|
|
|
190
190
|
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
191
191
|
)
|
|
192
192
|
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
193
|
-
|
|
193
|
+
# Filter out accum_dtype from kwargs for model call as MllamaTextModel doesn't accept it in transformers 4.49.0
|
|
194
|
+
# but preserve it for loss function calls
|
|
195
|
+
model_kwargs = {k: v for k, v in kwargs.items() if k != "accum_dtype"}
|
|
194
196
|
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
195
197
|
outputs = self.model(
|
|
196
198
|
input_ids=input_ids,
|
|
@@ -206,7 +208,7 @@ def lce_forward(
|
|
|
206
208
|
output_hidden_states=output_hidden_states,
|
|
207
209
|
return_dict=return_dict,
|
|
208
210
|
cache_position=cache_position,
|
|
209
|
-
**
|
|
211
|
+
**model_kwargs,
|
|
210
212
|
)
|
|
211
213
|
|
|
212
214
|
hidden_states = outputs[0]
|
|
@@ -5,131 +5,12 @@ from typing import Union
|
|
|
5
5
|
|
|
6
6
|
import torch
|
|
7
7
|
|
|
8
|
-
from
|
|
8
|
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
|
9
9
|
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
10
|
-
from transformers.utils.deprecation import deprecate_kwarg
|
|
11
10
|
|
|
12
|
-
from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
|
|
13
11
|
from liger_kernel.transformers.model.loss_utils import LigerForCausalLMLoss
|
|
14
12
|
|
|
15
13
|
|
|
16
|
-
def lce_forward_deprecated(
|
|
17
|
-
self,
|
|
18
|
-
input_ids: torch.LongTensor = None,
|
|
19
|
-
attention_mask: Optional[torch.Tensor] = None,
|
|
20
|
-
position_ids: Optional[torch.LongTensor] = None,
|
|
21
|
-
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
|
22
|
-
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
23
|
-
labels: Optional[torch.LongTensor] = None,
|
|
24
|
-
use_cache: Optional[bool] = None,
|
|
25
|
-
output_attentions: Optional[bool] = None,
|
|
26
|
-
output_hidden_states: Optional[bool] = None,
|
|
27
|
-
return_dict: Optional[bool] = None,
|
|
28
|
-
cache_position: Optional[torch.LongTensor] = None,
|
|
29
|
-
skip_logits: Optional[bool] = None,
|
|
30
|
-
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
31
|
-
r"""
|
|
32
|
-
Copy paste phi3 forward from transfomers v4.44.2 but replace torch cross entropy with liger fused linear cross entropy
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
Args:
|
|
36
|
-
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
37
|
-
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
38
|
-
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
39
|
-
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
40
|
-
|
|
41
|
-
Returns:
|
|
42
|
-
|
|
43
|
-
Example:
|
|
44
|
-
|
|
45
|
-
```python
|
|
46
|
-
>>> from transformers import AutoTokenizer, Phi3ForCausalLM
|
|
47
|
-
|
|
48
|
-
>>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
|
|
49
|
-
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
|
|
50
|
-
|
|
51
|
-
>>> prompt = "This is an example script ."
|
|
52
|
-
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
53
|
-
|
|
54
|
-
>>> # Generate
|
|
55
|
-
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
56
|
-
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
57
|
-
'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
|
|
58
|
-
```"""
|
|
59
|
-
|
|
60
|
-
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
61
|
-
output_hidden_states = (
|
|
62
|
-
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
63
|
-
)
|
|
64
|
-
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
65
|
-
|
|
66
|
-
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
67
|
-
outputs = self.model(
|
|
68
|
-
input_ids=input_ids,
|
|
69
|
-
attention_mask=attention_mask,
|
|
70
|
-
position_ids=position_ids,
|
|
71
|
-
past_key_values=past_key_values,
|
|
72
|
-
inputs_embeds=inputs_embeds,
|
|
73
|
-
use_cache=use_cache,
|
|
74
|
-
output_attentions=output_attentions,
|
|
75
|
-
output_hidden_states=output_hidden_states,
|
|
76
|
-
return_dict=return_dict,
|
|
77
|
-
)
|
|
78
|
-
|
|
79
|
-
hidden_states = outputs[0]
|
|
80
|
-
|
|
81
|
-
loss = None
|
|
82
|
-
logits = None
|
|
83
|
-
|
|
84
|
-
if skip_logits and labels is None:
|
|
85
|
-
raise ValueError("skip_logits is True, but labels is None")
|
|
86
|
-
|
|
87
|
-
if skip_logits is None:
|
|
88
|
-
# By default, if in training mode, don't materialize logits
|
|
89
|
-
skip_logits = self.training and labels is not None
|
|
90
|
-
|
|
91
|
-
if skip_logits:
|
|
92
|
-
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
93
|
-
shift_labels = labels[..., 1:].contiguous()
|
|
94
|
-
|
|
95
|
-
# flatten tokens
|
|
96
|
-
shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
|
|
97
|
-
shift_labels = shift_labels.view(-1)
|
|
98
|
-
|
|
99
|
-
lce = LigerFusedLinearCrossEntropyLoss()
|
|
100
|
-
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
101
|
-
else:
|
|
102
|
-
logits = self.lm_head(hidden_states)
|
|
103
|
-
|
|
104
|
-
loss = None
|
|
105
|
-
if labels is not None:
|
|
106
|
-
# Upcast to float if we need to compute the loss to avoid potential precision issues
|
|
107
|
-
logits = logits.float()
|
|
108
|
-
# Shift so that tokens < n predict n
|
|
109
|
-
shift_logits = logits[..., :-1, :].contiguous()
|
|
110
|
-
shift_labels = labels[..., 1:].contiguous()
|
|
111
|
-
# Flatten the tokens
|
|
112
|
-
loss_fct = CrossEntropyLoss()
|
|
113
|
-
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
|
114
|
-
shift_labels = shift_labels.view(-1)
|
|
115
|
-
# Enable model parallelism
|
|
116
|
-
shift_labels = shift_labels.to(shift_logits.device)
|
|
117
|
-
loss = loss_fct(shift_logits, shift_labels)
|
|
118
|
-
|
|
119
|
-
if not return_dict:
|
|
120
|
-
output = (logits,) + outputs[1:]
|
|
121
|
-
return (loss,) + output if loss is not None else output
|
|
122
|
-
|
|
123
|
-
return CausalLMOutputWithPast(
|
|
124
|
-
loss=loss,
|
|
125
|
-
logits=logits,
|
|
126
|
-
past_key_values=outputs.past_key_values,
|
|
127
|
-
hidden_states=outputs.hidden_states,
|
|
128
|
-
attentions=outputs.attentions,
|
|
129
|
-
)
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
@deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
|
|
133
14
|
def lce_forward(
|
|
134
15
|
self,
|
|
135
16
|
input_ids: torch.LongTensor = None,
|
|
@@ -148,73 +29,41 @@ def lce_forward(
|
|
|
148
29
|
**kwargs,
|
|
149
30
|
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
150
31
|
r"""
|
|
151
|
-
Args:
|
|
152
|
-
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
153
|
-
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
154
|
-
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
155
|
-
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
156
|
-
|
|
157
|
-
logits_to_keep (`int` or `torch.Tensor`, *optional*):
|
|
158
|
-
If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
|
|
159
|
-
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
160
|
-
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
161
|
-
If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
|
|
162
|
-
This is useful when using packed tensor format (single dimension for batch and sequence length).
|
|
163
|
-
|
|
164
|
-
Returns:
|
|
165
|
-
|
|
166
32
|
Example:
|
|
167
33
|
|
|
168
34
|
```python
|
|
169
35
|
>>> from transformers import AutoTokenizer, Phi3ForCausalLM
|
|
170
36
|
|
|
171
|
-
>>> model = Phi3ForCausalLM.from_pretrained("
|
|
172
|
-
>>> tokenizer = AutoTokenizer.from_pretrained("
|
|
37
|
+
>>> model = Phi3ForCausalLM.from_pretrained("meta-phi3/Phi3-2-7b-hf")
|
|
38
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-phi3/Phi3-2-7b-hf")
|
|
173
39
|
|
|
174
|
-
>>> prompt = "
|
|
40
|
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
|
175
41
|
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
176
42
|
|
|
177
43
|
>>> # Generate
|
|
178
44
|
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
179
45
|
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
180
|
-
|
|
46
|
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
|
181
47
|
```"""
|
|
182
48
|
|
|
183
|
-
from transformers.models.phi3.modeling_phi3 import logging
|
|
184
|
-
|
|
185
|
-
logger = logging.get_logger(__name__)
|
|
186
|
-
|
|
187
|
-
if (
|
|
188
|
-
use_cache
|
|
189
|
-
and self.config.rope_scaling
|
|
190
|
-
and cache_position is not None
|
|
191
|
-
and cache_position[0] == self.config.original_max_position_embeddings
|
|
192
|
-
):
|
|
193
|
-
logger.warning(
|
|
194
|
-
f"If you are not using the generate method, you may encounter nonsensical outputs after the {self.config.original_max_position_embeddings}th token, as the KV cache needs to be recomputed."
|
|
195
|
-
)
|
|
196
|
-
|
|
197
49
|
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
|
198
50
|
output_hidden_states = (
|
|
199
51
|
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
|
200
52
|
)
|
|
201
53
|
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
|
202
54
|
|
|
203
|
-
|
|
204
|
-
outputs = self.model(
|
|
55
|
+
outputs: BaseModelOutputWithPast = self.model(
|
|
205
56
|
input_ids=input_ids,
|
|
206
57
|
attention_mask=attention_mask,
|
|
207
58
|
position_ids=position_ids,
|
|
208
59
|
past_key_values=past_key_values,
|
|
209
60
|
inputs_embeds=inputs_embeds,
|
|
210
61
|
use_cache=use_cache,
|
|
211
|
-
|
|
212
|
-
output_hidden_states=output_hidden_states,
|
|
213
|
-
return_dict=return_dict,
|
|
62
|
+
cache_position=cache_position,
|
|
214
63
|
**kwargs,
|
|
215
64
|
)
|
|
216
65
|
|
|
217
|
-
hidden_states = outputs
|
|
66
|
+
hidden_states = outputs.last_hidden_state
|
|
218
67
|
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
|
219
68
|
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
|
220
69
|
kept_hidden_states = hidden_states[:, slice_indices, :]
|
|
@@ -26,7 +26,6 @@ from liger_kernel.transformers.model.mistral import lce_forward as mistral_lce_f
|
|
|
26
26
|
from liger_kernel.transformers.model.mixtral import lce_forward as mixtral_lce_forward
|
|
27
27
|
from liger_kernel.transformers.model.mixtral import lce_forward_deprecated as mixtral_lce_forward_deprecated
|
|
28
28
|
from liger_kernel.transformers.model.phi3 import lce_forward as phi3_lce_forward
|
|
29
|
-
from liger_kernel.transformers.model.phi3 import lce_forward_deprecated as phi3_lce_forward_deprecated
|
|
30
29
|
from liger_kernel.transformers.model.qwen2 import lce_forward as qwen2_lce_forward
|
|
31
30
|
from liger_kernel.transformers.model.qwen2 import lce_forward_deprecated as qwen2_lce_forward_deprecated
|
|
32
31
|
from liger_kernel.transformers.model.smollm3 import lce_forward as smollm3_lce_forward
|
|
@@ -449,7 +448,7 @@ def apply_liger_kernel_to_llava(
|
|
|
449
448
|
|
|
450
449
|
|
|
451
450
|
def apply_liger_kernel_to_llama4(
|
|
452
|
-
rope: bool =
|
|
451
|
+
rope: bool = True,
|
|
453
452
|
cross_entropy: bool = False,
|
|
454
453
|
fused_linear_cross_entropy: bool = True,
|
|
455
454
|
rms_norm: bool = True,
|
|
@@ -485,7 +484,9 @@ def apply_liger_kernel_to_llama4(
|
|
|
485
484
|
from liger_kernel.transformers.model.llama4 import lce_forward as llama4_lce_forward
|
|
486
485
|
|
|
487
486
|
if rope:
|
|
488
|
-
|
|
487
|
+
from liger_kernel.transformers.llama4_rope import apply_liger_llama4_rope_full
|
|
488
|
+
|
|
489
|
+
apply_liger_llama4_rope_full(modeling_llama4)
|
|
489
490
|
if rms_norm:
|
|
490
491
|
modeling_llama4.Llama4TextRMSNorm = LigerRMSNorm
|
|
491
492
|
if swiglu:
|
|
@@ -1675,25 +1676,14 @@ def apply_liger_kernel_to_phi3(
|
|
|
1675
1676
|
if swiglu:
|
|
1676
1677
|
modeling_phi3.Phi3MLP = LigerPhi3SwiGLUMLP
|
|
1677
1678
|
if cross_entropy:
|
|
1678
|
-
|
|
1679
|
-
from transformers.loss.loss_utils import nn
|
|
1679
|
+
from transformers.loss.loss_utils import nn
|
|
1680
1680
|
|
|
1681
|
-
|
|
1682
|
-
else:
|
|
1683
|
-
logger.warning(TRANSFORMER_DEPRECATION_WARNING)
|
|
1684
|
-
modeling_phi3.CrossEntropyLoss = LigerCrossEntropyLoss
|
|
1681
|
+
nn.functional.cross_entropy = liger_cross_entropy
|
|
1685
1682
|
if fused_linear_cross_entropy:
|
|
1686
|
-
if
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
modeling_phi3.Phi3ForCausalLM.forward = phi3_lce_forward
|
|
1691
|
-
else: # if version < 4.46.1
|
|
1692
|
-
logger.warning(TRANSFORMER_DEPRECATION_WARNING)
|
|
1693
|
-
if model is not None:
|
|
1694
|
-
model.forward = MethodType(phi3_lce_forward_deprecated, model)
|
|
1695
|
-
else:
|
|
1696
|
-
modeling_phi3.Phi3ForCausalLM.forward = phi3_lce_forward_deprecated
|
|
1683
|
+
if model is not None:
|
|
1684
|
+
model.forward = MethodType(phi3_lce_forward, model)
|
|
1685
|
+
else:
|
|
1686
|
+
modeling_phi3.Phi3ForCausalLM.forward = phi3_lce_forward
|
|
1697
1687
|
|
|
1698
1688
|
if model is not None:
|
|
1699
1689
|
# The model instance already exists, so we need to additionally patch the
|
|
@@ -1849,6 +1839,95 @@ def apply_liger_kernel_to_glm4(
|
|
|
1849
1839
|
_patch_rms_norm_module(decoder_layer.post_mlp_layernorm, in_place=False)
|
|
1850
1840
|
|
|
1851
1841
|
|
|
1842
|
+
def apply_liger_kernel_to_glm4v(
|
|
1843
|
+
rope: bool = False,
|
|
1844
|
+
cross_entropy: bool = False,
|
|
1845
|
+
fused_linear_cross_entropy: bool = True,
|
|
1846
|
+
rms_norm: bool = True,
|
|
1847
|
+
swiglu: bool = True,
|
|
1848
|
+
model: PreTrainedModel = None,
|
|
1849
|
+
) -> None:
|
|
1850
|
+
"""
|
|
1851
|
+
Apply Liger kernels to replace original implementation in HuggingFace GLM-4v models.
|
|
1852
|
+
|
|
1853
|
+
Args:
|
|
1854
|
+
rope (bool): Whether to apply Liger's rotary position embedding. Default is False.
|
|
1855
|
+
cross_entropy (bool): Whether to apply Liger's cross entropy loss. Default is False.
|
|
1856
|
+
fused_linear_cross_entropy (bool):
|
|
1857
|
+
Whether to apply Liger's fused linear cross entropy loss. Default is True.
|
|
1858
|
+
`cross_entropy` and `fused_linear_cross_entropy` cannot both be True.
|
|
1859
|
+
If `fused_linear_cross_entropy` is True, the logits will not be materialized but more memory efficient.
|
|
1860
|
+
rms_norm (bool): Whether to apply Liger's RMSNorm. Default is True.
|
|
1861
|
+
swiglu (bool): Whether to apply Liger's SwiGLU Glm4MLP. Default is True.
|
|
1862
|
+
model (PreTrainedModel): The model instance to apply Liger kernels to, if the model has already been
|
|
1863
|
+
loaded. Default is None.
|
|
1864
|
+
"""
|
|
1865
|
+
assert not (cross_entropy and fused_linear_cross_entropy), (
|
|
1866
|
+
"cross_entropy and fused_linear_cross_entropy cannot both be True."
|
|
1867
|
+
)
|
|
1868
|
+
|
|
1869
|
+
from transformers.models.glm4v import modeling_glm4v
|
|
1870
|
+
from transformers.models.glm4v.modeling_glm4v import Glm4vForConditionalGeneration
|
|
1871
|
+
from transformers.models.glm4v.modeling_glm4v import Glm4vModel
|
|
1872
|
+
from transformers.models.glm4v.modeling_glm4v import Glm4vTextModel
|
|
1873
|
+
from transformers.models.glm4v.modeling_glm4v import Glm4vVisionModel
|
|
1874
|
+
|
|
1875
|
+
from liger_kernel.transformers.model.glm4v import lce_forward as glm4v_lce_forward
|
|
1876
|
+
from liger_kernel.transformers.rms_norm import LigerRMSNormForGlm4
|
|
1877
|
+
|
|
1878
|
+
if rope:
|
|
1879
|
+
raise NotImplementedError("liger_rotary_pos_emb is not available for Glm4 models.")
|
|
1880
|
+
if rms_norm:
|
|
1881
|
+
modeling_glm4v.Glm4vRMSNorm = LigerRMSNormForGlm4
|
|
1882
|
+
if cross_entropy:
|
|
1883
|
+
from transformers.loss.loss_utils import nn
|
|
1884
|
+
|
|
1885
|
+
nn.functional.cross_entropy = liger_cross_entropy
|
|
1886
|
+
if fused_linear_cross_entropy:
|
|
1887
|
+
if model is not None:
|
|
1888
|
+
model.forward = MethodType(glm4v_lce_forward, model)
|
|
1889
|
+
else:
|
|
1890
|
+
modeling_glm4v.Glm4vForConditionalGeneration.forward = glm4v_lce_forward
|
|
1891
|
+
|
|
1892
|
+
if model is not None:
|
|
1893
|
+
# The model instance already exists, so we need to additionally patch the
|
|
1894
|
+
# instance variables that reference already-instantiated modules
|
|
1895
|
+
if isinstance(model, (Glm4vForConditionalGeneration, Glm4vModel)):
|
|
1896
|
+
# Note: language_model and visual properties can be accessed throught conditional class for BC.
|
|
1897
|
+
# Not sure if it is subject to changes in the future.
|
|
1898
|
+
# Reference: https://github.com/huggingface/transformers/blob/main/src/transformers/models/glm4v/modeling_glm4v.py#L1305
|
|
1899
|
+
text_model: Glm4vTextModel = model.language_model
|
|
1900
|
+
vision_model: Glm4vVisionModel = model.visual
|
|
1901
|
+
elif isinstance(model, Glm4vTextModel):
|
|
1902
|
+
text_model: Glm4vTextModel = model
|
|
1903
|
+
vision_model = None
|
|
1904
|
+
else:
|
|
1905
|
+
# Note: Currently there's no support for patching vision model only. Feel free to raise an issue if needed.
|
|
1906
|
+
raise TypeError(
|
|
1907
|
+
f"Unsupported glm4.1v model type. `model` must be `Glm4VLForConditionalGeneration`, `Glm4vVisionModel` or `Glm4vTextModel`. Got: {type(model)}"
|
|
1908
|
+
)
|
|
1909
|
+
|
|
1910
|
+
if vision_model is not None:
|
|
1911
|
+
for vision_block in vision_model.blocks:
|
|
1912
|
+
if rms_norm:
|
|
1913
|
+
_patch_rms_norm_module(vision_block.norm1)
|
|
1914
|
+
_patch_rms_norm_module(vision_block.norm2)
|
|
1915
|
+
if swiglu:
|
|
1916
|
+
_patch_swiglu_module(vision_block.mlp, LigerSwiGLUMLP)
|
|
1917
|
+
|
|
1918
|
+
if text_model is not None:
|
|
1919
|
+
if rms_norm:
|
|
1920
|
+
_patch_rms_norm_module(text_model.norm)
|
|
1921
|
+
for decoder_layer in text_model.layers:
|
|
1922
|
+
if swiglu:
|
|
1923
|
+
_patch_swiglu_module(decoder_layer.mlp, LigerPhi3SwiGLUMLP)
|
|
1924
|
+
if rms_norm:
|
|
1925
|
+
_patch_rms_norm_module(decoder_layer.input_layernorm)
|
|
1926
|
+
_patch_rms_norm_module(decoder_layer.post_attention_layernorm)
|
|
1927
|
+
_patch_rms_norm_module(decoder_layer.post_self_attn_layernorm)
|
|
1928
|
+
_patch_rms_norm_module(decoder_layer.post_mlp_layernorm)
|
|
1929
|
+
|
|
1930
|
+
|
|
1852
1931
|
# Model type corresponds to the keys defined in transformers/models/auto/modeling_auto.py
|
|
1853
1932
|
MODEL_TYPE_TO_APPLY_LIGER_FN = {
|
|
1854
1933
|
"gemma": apply_liger_kernel_to_gemma,
|
|
@@ -1856,6 +1935,7 @@ MODEL_TYPE_TO_APPLY_LIGER_FN = {
|
|
|
1856
1935
|
"gemma3_text": apply_liger_kernel_to_gemma3_text,
|
|
1857
1936
|
"gemma3": apply_liger_kernel_to_gemma3,
|
|
1858
1937
|
"glm4": apply_liger_kernel_to_glm4,
|
|
1938
|
+
"glm4v": apply_liger_kernel_to_glm4v,
|
|
1859
1939
|
"llama": apply_liger_kernel_to_llama,
|
|
1860
1940
|
"llama4_text": apply_liger_kernel_to_llama4,
|
|
1861
1941
|
"llama4": apply_liger_kernel_to_llama4,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: liger_kernel
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.2
|
|
4
4
|
Summary: Efficient Triton kernels for LLM Training
|
|
5
5
|
License: BSD 2-CLAUSE LICENSE
|
|
6
6
|
Copyright 2024 LinkedIn Corporation
|
|
@@ -400,7 +400,7 @@ loss.backward()
|
|
|
400
400
|
</a>
|
|
401
401
|
</div>
|
|
402
402
|
<div style="display: block;">
|
|
403
|
-
<a href="https://github.com/linkedin/Liger-Kernel/actions/workflows/
|
|
403
|
+
<a href="https://github.com/linkedin/Liger-Kernel/actions/workflows/intel-ci.yml">
|
|
404
404
|
<img src="https://github.com/linkedin/Liger-Kernel/actions/workflows/intel-ci.yml/badge.svg?event=schedule" alt="Build">
|
|
405
405
|
</a>
|
|
406
406
|
</div>
|
|
@@ -5,7 +5,7 @@ liger_kernel/chunked_loss/README.md,sha256=0FmkFC3hKBqyoDT5uTlIYmrvRkF-EOCR1y-EB
|
|
|
5
5
|
liger_kernel/chunked_loss/__init__.py,sha256=J5_jNnzZ4gZmA38W5f_4oab7xMoNk1Xy-yh3X_Xlf-s,714
|
|
6
6
|
liger_kernel/chunked_loss/cosine_similarity_loss.py,sha256=pZ07OQ6RI-c8uk96tDRlUXdt31-da7yWhfwircZlKRw,4198
|
|
7
7
|
liger_kernel/chunked_loss/cpo_loss.py,sha256=Gzz1eU4kgcbdubFVRy55e8A1Cr-r45UgNicXwZIjmBU,5454
|
|
8
|
-
liger_kernel/chunked_loss/dpo_loss.py,sha256=
|
|
8
|
+
liger_kernel/chunked_loss/dpo_loss.py,sha256=I83khNs3QQjuhr8U3NIOAACkbse6DNiBV-TulPZ0lXw,9006
|
|
9
9
|
liger_kernel/chunked_loss/functional.py,sha256=-XPDbLml9dHmvoSU2VNTUrBDFehuzvuAGPikVetBMtI,1132
|
|
10
10
|
liger_kernel/chunked_loss/fused_linear_distillation.py,sha256=ooR-qnZCyWJN935oHCSWLaKKKyaYERyhNczRGi1VOiw,11935
|
|
11
11
|
liger_kernel/chunked_loss/fused_linear_ppo.py,sha256=AA19cpv6D8mo5RbSK5GRCcZoOSnpxV_Z1eJlAsC5eic,13434
|
|
@@ -20,7 +20,7 @@ liger_kernel/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,
|
|
|
20
20
|
liger_kernel/ops/cross_entropy.py,sha256=e8THGnhOcy_0SbOLABx67HEM7-B8a8pG7nDKbCRpQKM,19123
|
|
21
21
|
liger_kernel/ops/dyt.py,sha256=gCLz4S8aul8SY9nvIGaoK67aGb7U9MJRQdo3ONqmQYs,5417
|
|
22
22
|
liger_kernel/ops/fused_add_rms_norm.py,sha256=UBqmlqFCmhSAIpkNKd8rrfXatX7Z4J9bp2dX9A0lrJQ,14017
|
|
23
|
-
liger_kernel/ops/fused_linear_cross_entropy.py,sha256=
|
|
23
|
+
liger_kernel/ops/fused_linear_cross_entropy.py,sha256=YFPXUOIZpM_4r7AlfjkwOgDhAE_0H2mFjdKtx8cv-T4,11594
|
|
24
24
|
liger_kernel/ops/fused_linear_jsd.py,sha256=CSoprxb-YcJy-YUKiTcYkxN8sb9h2kdk_iHuncvSV5c,9683
|
|
25
25
|
liger_kernel/ops/fused_neighborhood_attention.py,sha256=vPi5xbnh6wxyZehaqo6Tuilqo2fN5SGDiONjnNmIKqs,35556
|
|
26
26
|
liger_kernel/ops/geglu.py,sha256=r0WSq9E93zzynL44Wh8femzOWK07_SseBM_pJUyxT3s,4144
|
|
@@ -29,6 +29,7 @@ liger_kernel/ops/grpo_loss.py,sha256=anRnv7k1-AV3pCC6_TqP0GMg78YYUfRAJrbpx6PVhl0
|
|
|
29
29
|
liger_kernel/ops/jsd.py,sha256=onHp5T3MbvJaVz5Vup7Ww6EQp_HTaZeayTjJk6FgQMY,7042
|
|
30
30
|
liger_kernel/ops/kl_div.py,sha256=ZjGdDLKWksHT9dZ0xF_TDgAkj5cuMTwwT5tr9E-_24o,8734
|
|
31
31
|
liger_kernel/ops/layer_norm.py,sha256=BHPDuaogMTfIJkBJdqLZbOQouNWTf3fJVyOQOD7blCE,9901
|
|
32
|
+
liger_kernel/ops/llama4_rope.py,sha256=-aqdZzllklTN8b9--e-TsWY_ntGCN8-tyseT4x0bd8s,8223
|
|
32
33
|
liger_kernel/ops/multi_token_attention.py,sha256=Oz_RXDp-OSS_R_HuGmaETHdAJ7Toda_70OfE7TXMUlY,7645
|
|
33
34
|
liger_kernel/ops/qwen2vl_mrope.py,sha256=3GExhYpLgB4VUtyZyjRk8XjEur3W4EWF6HQ67ML5vBU,8481
|
|
34
35
|
liger_kernel/ops/rms_norm.py,sha256=DtvsWN5YktFAoc0JYSAwVeoZfryBFJlX-ipU7ooP01A,18891
|
|
@@ -40,14 +41,14 @@ liger_kernel/ops/tvd.py,sha256=FHJtLQI95ijqgg9UtaHpMAjSCiPxB6CduPwPMcGxelc,6405
|
|
|
40
41
|
liger_kernel/ops/utils.py,sha256=uoFKQqo-34N2TWQNvXMFywqGiOMMXNEVBxVojzlUAa0,3836
|
|
41
42
|
liger_kernel/ops/experimental/embedding.py,sha256=tolj3tItkzpSb30zWqDN2_yX4ectflaQ8HMyKyFIQc8,4172
|
|
42
43
|
liger_kernel/ops/experimental/mm_int8int2.py,sha256=TrS9lpwekrik_w5qE7AhMJD1bcq-OidjtbsW80oZ6IM,13314
|
|
43
|
-
liger_kernel/transformers/__init__.py,sha256=
|
|
44
|
+
liger_kernel/transformers/__init__.py,sha256=jkokP69dbCzUDTz-H6QowB5xNEflmgQ7Zv-_4MVuxpY,8440
|
|
44
45
|
liger_kernel/transformers/auto_model.py,sha256=0qCTRZt280Bj_LcFdzo9hlaR-BWNazawXOGgoCZjgEg,1545
|
|
45
46
|
liger_kernel/transformers/cross_entropy.py,sha256=z3KTWQnFxr_IZaVjtYt0ZNEWQdDdYThN35xWkHlDGH0,1683
|
|
46
47
|
liger_kernel/transformers/dyt.py,sha256=i-4GPaMrl-jab9TVI5qN0-H9qycn_mCbV82ozU4nbmU,723
|
|
47
48
|
liger_kernel/transformers/fsdp.py,sha256=CUiyjTmjkjY7pLXQv8ly9rnzgXw6529csd9pvtJNMYc,3096
|
|
48
|
-
liger_kernel/transformers/functional.py,sha256=
|
|
49
|
+
liger_kernel/transformers/functional.py,sha256=XkYk_zb8xsRMtZtouYmlX_Tyyr-QA3WigSPF36DECYk,7777
|
|
49
50
|
liger_kernel/transformers/fused_add_rms_norm.py,sha256=7_Bzg-x6lLe6W1qG2DtjDALhEpNZlC6N5GppEs9cTYY,1199
|
|
50
|
-
liger_kernel/transformers/fused_linear_cross_entropy.py,sha256=
|
|
51
|
+
liger_kernel/transformers/fused_linear_cross_entropy.py,sha256=_5AaQT2mcUEO2T7JGJYQafz6A1Efn9d3-Z3xFO_Xe0o,1862
|
|
51
52
|
liger_kernel/transformers/fused_linear_jsd.py,sha256=bZ4otCvWBuOnA5XdQL-FzZVItJlDt-ht9e_pG7PG93E,3999
|
|
52
53
|
liger_kernel/transformers/fused_neighborhood_attention.py,sha256=TxYDUAt9B6WSP14aJP66C_2Mbds2sSIPGnamhUSTrC8,7957
|
|
53
54
|
liger_kernel/transformers/geglu.py,sha256=mrgqzIUVd6lN7fkDKLkw5YaESDxDtFgbot430WwPVOQ,1107
|
|
@@ -56,7 +57,8 @@ liger_kernel/transformers/grpo_loss.py,sha256=uAkUNKSnUGEOqa82L9w2e6AI1kcmG8K45-
|
|
|
56
57
|
liger_kernel/transformers/jsd.py,sha256=DGqRnxIZxsvxo0_tbbxX3b-sDbDjC_yKufyRIHCcScY,2979
|
|
57
58
|
liger_kernel/transformers/kl_div.py,sha256=WLffFbh1EExD2Eb1F7lN11fo9JJC-0751WJjZAF1Fj8,409
|
|
58
59
|
liger_kernel/transformers/layer_norm.py,sha256=c9pk3PEasOKYR0rhe5e5nNrnYKVCEW4VC8S6LpCq9EQ,906
|
|
59
|
-
liger_kernel/transformers/
|
|
60
|
+
liger_kernel/transformers/llama4_rope.py,sha256=kS6PSHEwf3dS7hD7C7p8S0geugx2EMCiP0h0F7LsUoY,3639
|
|
61
|
+
liger_kernel/transformers/monkey_patch.py,sha256=pG3Yf0fMg4_0pAncc2wLtpdfXvmC5CROpNJ43-MmElM,93075
|
|
60
62
|
liger_kernel/transformers/multi_token_attention.py,sha256=l9VDICK0dfmifUDW668hGscP8AHq2rYcM2oGUa3baRQ,1751
|
|
61
63
|
liger_kernel/transformers/qwen2vl_mrope.py,sha256=5EwSqrMdsL9MYspeBMXBsNJKvH0MOmRrtJXAJlnnlOI,1047
|
|
62
64
|
liger_kernel/transformers/rms_norm.py,sha256=vkekcvTeWY8vL4H6hg3t0XeY0Ew_3OFMPHuzqlxPPVw,2719
|
|
@@ -66,22 +68,24 @@ liger_kernel/transformers/sparsemax.py,sha256=0lQA0UEOs4mu8CMruZ3VLhImxQVXJWhPsA
|
|
|
66
68
|
liger_kernel/transformers/swiglu.py,sha256=LZ8YeLIdv2k46JleZMjzubGk98smt6t780kSgcVLsQk,3454
|
|
67
69
|
liger_kernel/transformers/trainer_integration.py,sha256=W3ON51O5GkyzNJsItz0y5rKx-uy2f2cFfveZpqbUdhw,123
|
|
68
70
|
liger_kernel/transformers/tvd.py,sha256=XrRfyJIqN6HFxXk8MYyFVZM1OLz3mtSbRZvWfZ_JerQ,450
|
|
71
|
+
liger_kernel/transformers/experimental/__init__.py,sha256=oQqk-f32JYgWEP9DJCj6ty6bbJSGrdXsFDQFwGeX6vI,127
|
|
69
72
|
liger_kernel/transformers/experimental/embedding.py,sha256=2P0QYdlFyFrG5OqTzTa1wcRgDSyjBMv5i1a7BrDPDQw,881
|
|
70
73
|
liger_kernel/transformers/model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
71
74
|
liger_kernel/transformers/model/gemma.py,sha256=mNX-mIwV6jI4zfbrUHp0C468pOmjzsL7mjXipGt-eS0,10007
|
|
72
75
|
liger_kernel/transformers/model/gemma2.py,sha256=R_JFPyWTk7RyA7D05ZiIaNO5pX8gWcvfWf-6rdCRMxs,11296
|
|
73
76
|
liger_kernel/transformers/model/gemma3.py,sha256=FKO4j3t4W_5uECRA1lhVnXC-It2GhirHm4tpCf9ApAc,12785
|
|
74
77
|
liger_kernel/transformers/model/glm4.py,sha256=GlnEhdGJuDIqp2R9qC54biY3HwV1tWmfpJm6ijoAsrM,5257
|
|
78
|
+
liger_kernel/transformers/model/glm4v.py,sha256=zbV3agptEYpGAD0eeCRwIpJAhJUviTT5xQbbLlgpVnc,5957
|
|
75
79
|
liger_kernel/transformers/model/llama.py,sha256=i8jJgyZsMKWQ-zKloETLugtwFpUOdaWxLDceciFXKd4,12832
|
|
76
80
|
liger_kernel/transformers/model/llama4.py,sha256=IgbB8sTh3dlETQnaNNy1bZLuXy-Nt7qmeAjF27ydGpg,4210
|
|
77
81
|
liger_kernel/transformers/model/llava.py,sha256=bLCioday_SOm69ogMDBhy_4UsVkH2-BSl93-EXY6-7I,15076
|
|
78
|
-
liger_kernel/transformers/model/loss_utils.py,sha256=
|
|
82
|
+
liger_kernel/transformers/model/loss_utils.py,sha256=YiYsmRHIuoRnFjGpwyIM18DCsrPPmO32YWMWqkEm1UQ,1867
|
|
79
83
|
liger_kernel/transformers/model/mistral.py,sha256=syYNL8dLThX2-4uC13Lu0krEZ5zw3InviDUR3AJmc-I,5500
|
|
80
84
|
liger_kernel/transformers/model/mixtral.py,sha256=VY-y73IyjcCyWyI7ahxXLw0fJrhgjYfr1xwRYtsHX0o,11396
|
|
81
|
-
liger_kernel/transformers/model/mllama.py,sha256=
|
|
85
|
+
liger_kernel/transformers/model/mllama.py,sha256=NhJtlXiuszJHo5YSJOvSGYH47ly7Hse8r-5BKznBg9s,11522
|
|
82
86
|
liger_kernel/transformers/model/olmo2.py,sha256=6L_bo-ZUgO1lYppdJneOtYxNIylQKS6BiGp13g7Uq9E,5259
|
|
83
87
|
liger_kernel/transformers/model/paligemma.py,sha256=xuIx3oOwTgftU3jqLfWOxUxgCLBNJh0yNC21an9qDjo,18773
|
|
84
|
-
liger_kernel/transformers/model/phi3.py,sha256=
|
|
88
|
+
liger_kernel/transformers/model/phi3.py,sha256=AwScxUe3LjmHHyQg4gW9bMoUI7uA6fUEMXJ3YhBiHtQ,4046
|
|
85
89
|
liger_kernel/transformers/model/qwen2.py,sha256=3fpOTEOkniQmkCfN1KUa3KhseHJVzhj2Ht9FdYPUy-E,9962
|
|
86
90
|
liger_kernel/transformers/model/qwen2_5_vl.py,sha256=zEVVwotCXnAm3RRc8-1Nc8uitSWrwW4B9dYY2uOZDwg,6331
|
|
87
91
|
liger_kernel/transformers/model/qwen2_vl.py,sha256=5vK-vtCDpKZ2w33xYp2BS8kQYWUbKMqaiKvQcI27Mss,5884
|
|
@@ -92,9 +96,9 @@ liger_kernel/transformers/trainer/__init__.py,sha256=p7yQfklV8-467qSz_ZMimkbDF7H
|
|
|
92
96
|
liger_kernel/transformers/trainer/orpo_trainer.py,sha256=tX0h63aOFe3rNqTmk6JpMf75UPo981yzEa6TghnjS0Q,5370
|
|
93
97
|
liger_kernel/triton/__init__.py,sha256=qCiCamzCRv6lpV8IqpAc9YMdNKC7GKurClWceQPnlis,92
|
|
94
98
|
liger_kernel/triton/monkey_patch.py,sha256=Rd0hUHAzDkFfHvnX7-PBaNK5EKnZhtfM_h-fgQH9HPY,1568
|
|
95
|
-
liger_kernel-0.6.
|
|
96
|
-
liger_kernel-0.6.
|
|
97
|
-
liger_kernel-0.6.
|
|
98
|
-
liger_kernel-0.6.
|
|
99
|
-
liger_kernel-0.6.
|
|
100
|
-
liger_kernel-0.6.
|
|
99
|
+
liger_kernel-0.6.2.dist-info/licenses/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
|
|
100
|
+
liger_kernel-0.6.2.dist-info/licenses/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
|
|
101
|
+
liger_kernel-0.6.2.dist-info/METADATA,sha256=vW1xVHcl4MfLYAF86zLMpZM_OVtBALaNsD4mZTRI0N8,24547
|
|
102
|
+
liger_kernel-0.6.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
103
|
+
liger_kernel-0.6.2.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
|
|
104
|
+
liger_kernel-0.6.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|