liger-kernel-nightly 0.6.1.dev20250805235815__py3-none-any.whl → 0.6.1.dev20250809233744__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.
@@ -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
@@ -11,6 +11,8 @@ from liger_kernel.transformers.fused_linear_jsd import LigerFusedLinearJSD # no
11
11
  from liger_kernel.transformers.geglu import LigerGEGLUMLP # noqa: F401
12
12
  from liger_kernel.transformers.jsd import LigerJSD # noqa: F401
13
13
  from liger_kernel.transformers.layer_norm import LigerLayerNorm # noqa: F401
14
+ from liger_kernel.transformers.llama4_rope import liger_llama4_text_rotary_pos_emb # noqa: F401
15
+ from liger_kernel.transformers.llama4_rope import liger_llama4_vision_rotary_pos_emb # noqa: F401
14
16
  from liger_kernel.transformers.rms_norm import LigerRMSNorm # noqa: F401
15
17
  from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
16
18
  from liger_kernel.transformers.swiglu import LigerBlockSparseTop2MLP # noqa: F401
@@ -125,6 +127,8 @@ __all__ = [
125
127
  "LigerFusedAddRMSNorm",
126
128
  "LigerRMSNorm",
127
129
  "liger_rotary_pos_emb",
130
+ "liger_llama4_text_rotary_pos_emb",
131
+ "liger_llama4_vision_rotary_pos_emb",
128
132
  "LigerBlockSparseTop2MLP",
129
133
  "LigerPhi3SwiGLUMLP",
130
134
  "LigerQwen3MoeSwiGLUMLP",
@@ -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
@@ -5,131 +5,12 @@ from typing import Union
5
5
 
6
6
  import torch
7
7
 
8
- from torch.nn import CrossEntropyLoss
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,36 +29,21 @@ 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("microsoft/phi-3-mini-4k-instruct")
172
- >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
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 = "This is an example script ."
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
- 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
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
49
  output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
@@ -186,21 +52,18 @@ def lce_forward(
186
52
  )
187
53
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
188
54
 
189
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
190
- outputs = self.model(
55
+ outputs: BaseModelOutputWithPast = self.model(
191
56
  input_ids=input_ids,
192
57
  attention_mask=attention_mask,
193
58
  position_ids=position_ids,
194
59
  past_key_values=past_key_values,
195
60
  inputs_embeds=inputs_embeds,
196
61
  use_cache=use_cache,
197
- output_attentions=output_attentions,
198
- output_hidden_states=output_hidden_states,
199
- return_dict=return_dict,
62
+ cache_position=cache_position,
200
63
  **kwargs,
201
64
  )
202
65
 
203
- hidden_states = outputs[0]
66
+ hidden_states = outputs.last_hidden_state
204
67
  # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
205
68
  slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
206
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 = False,
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
- raise NotImplementedError("liger_rotary_pos_emb is not available for Llama4 models.")
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
- if transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
1679
- from transformers.loss.loss_utils import nn
1679
+ from transformers.loss.loss_utils import nn
1680
1680
 
1681
- nn.functional.cross_entropy = liger_cross_entropy
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 transformer_version >= version.parse(SUPPORTED_TRANSFORMER_VERSION):
1687
- if model is not None:
1688
- model.forward = MethodType(phi3_lce_forward, model)
1689
- else:
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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: liger_kernel_nightly
3
- Version: 0.6.1.dev20250805235815
3
+ Version: 0.6.1.dev20250809233744
4
4
  Summary: Efficient Triton kernels for LLM Training
5
5
  License: BSD 2-CLAUSE LICENSE
6
6
  Copyright 2024 LinkedIn Corporation
@@ -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,7 +41,7 @@ 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=VoHQp5emsAJAouql37RuvtGFeZCoMIHgoIxfsyYMTc8,7564
44
+ liger_kernel/transformers/__init__.py,sha256=YQ3ffAaZWLy266snmFFHHfoz4EX1AhcSfojXZhOs6h0,7842
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
@@ -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/monkey_patch.py,sha256=tXKo4EKVp3szpdqPh051oLZFrlg_hCbWRv0RpSX_kfY,89238
60
+ liger_kernel/transformers/llama4_rope.py,sha256=kS6PSHEwf3dS7hD7C7p8S0geugx2EMCiP0h0F7LsUoY,3639
61
+ liger_kernel/transformers/monkey_patch.py,sha256=zeYj1XhI1at_gWdKnvZqazT53uBy_YOV36ZuQfnhf20,88545
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
@@ -81,7 +83,7 @@ liger_kernel/transformers/model/mixtral.py,sha256=VY-y73IyjcCyWyI7ahxXLw0fJrhgjY
81
83
  liger_kernel/transformers/model/mllama.py,sha256=my29NXk-p6ckQaP8qDIN8e318yI_9mQZHt38MV3SqLY,11280
82
84
  liger_kernel/transformers/model/olmo2.py,sha256=6L_bo-ZUgO1lYppdJneOtYxNIylQKS6BiGp13g7Uq9E,5259
83
85
  liger_kernel/transformers/model/paligemma.py,sha256=xuIx3oOwTgftU3jqLfWOxUxgCLBNJh0yNC21an9qDjo,18773
84
- liger_kernel/transformers/model/phi3.py,sha256=aOl1Pz2rp5jSahRKUHKFPgkdkgG28fnHPpOW2ZVnMPg,10124
86
+ liger_kernel/transformers/model/phi3.py,sha256=AwScxUe3LjmHHyQg4gW9bMoUI7uA6fUEMXJ3YhBiHtQ,4046
85
87
  liger_kernel/transformers/model/qwen2.py,sha256=3fpOTEOkniQmkCfN1KUa3KhseHJVzhj2Ht9FdYPUy-E,9962
86
88
  liger_kernel/transformers/model/qwen2_5_vl.py,sha256=zEVVwotCXnAm3RRc8-1Nc8uitSWrwW4B9dYY2uOZDwg,6331
87
89
  liger_kernel/transformers/model/qwen2_vl.py,sha256=5vK-vtCDpKZ2w33xYp2BS8kQYWUbKMqaiKvQcI27Mss,5884
@@ -92,9 +94,9 @@ liger_kernel/transformers/trainer/__init__.py,sha256=p7yQfklV8-467qSz_ZMimkbDF7H
92
94
  liger_kernel/transformers/trainer/orpo_trainer.py,sha256=tX0h63aOFe3rNqTmk6JpMf75UPo981yzEa6TghnjS0Q,5370
93
95
  liger_kernel/triton/__init__.py,sha256=qCiCamzCRv6lpV8IqpAc9YMdNKC7GKurClWceQPnlis,92
94
96
  liger_kernel/triton/monkey_patch.py,sha256=Rd0hUHAzDkFfHvnX7-PBaNK5EKnZhtfM_h-fgQH9HPY,1568
95
- liger_kernel_nightly-0.6.1.dev20250805235815.dist-info/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
96
- liger_kernel_nightly-0.6.1.dev20250805235815.dist-info/METADATA,sha256=CS11ODzzuxnxvqj1e-waNYiUcvwS5gwkrtGEwYnTkn0,24504
97
- liger_kernel_nightly-0.6.1.dev20250805235815.dist-info/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
98
- liger_kernel_nightly-0.6.1.dev20250805235815.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
99
- liger_kernel_nightly-0.6.1.dev20250805235815.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
100
- liger_kernel_nightly-0.6.1.dev20250805235815.dist-info/RECORD,,
97
+ liger_kernel_nightly-0.6.1.dev20250809233744.dist-info/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
98
+ liger_kernel_nightly-0.6.1.dev20250809233744.dist-info/METADATA,sha256=nClPzQutLCx1b5T1KZGIsCPMTAaYbSw6PVkt9EJjhVw,24504
99
+ liger_kernel_nightly-0.6.1.dev20250809233744.dist-info/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
100
+ liger_kernel_nightly-0.6.1.dev20250809233744.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
101
+ liger_kernel_nightly-0.6.1.dev20250809233744.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
102
+ liger_kernel_nightly-0.6.1.dev20250809233744.dist-info/RECORD,,