liger-kernel 0.5.3__py3-none-any.whl → 0.5.4__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,207 @@
1
+ from typing import Literal
2
+ from typing import Optional
3
+
4
+ import torch
5
+ import triton
6
+ import triton.language as tl
7
+
8
+ from liger_kernel.ops.utils import ensure_contiguous
9
+
10
+ MAX_FUSED_SIZE = 65536 // 4
11
+
12
+ REDUCTION_LITERAL = Literal["none", "sum", "mean", "batchmean"]
13
+
14
+ _REDUCTION_MODE_NONE = tl.constexpr(0)
15
+ _REDUCTION_MODE_SUM = tl.constexpr(1)
16
+ _REDUCTION_MODE_MEAN = tl.constexpr(2)
17
+ _REDUCTION_MODE_BATCHMEAN = tl.constexpr(3)
18
+
19
+ _str_to_reduction_mode = {
20
+ "none": _REDUCTION_MODE_NONE.value,
21
+ "sum": _REDUCTION_MODE_SUM.value,
22
+ "mean": _REDUCTION_MODE_MEAN.value,
23
+ "batchmean": _REDUCTION_MODE_BATCHMEAN.value,
24
+ }
25
+
26
+
27
+ def get_num_warps(BLOCK_SIZE):
28
+ num_warps = 4
29
+ if BLOCK_SIZE >= 32768:
30
+ num_warps = 32
31
+ elif BLOCK_SIZE >= 8192:
32
+ num_warps = 16
33
+ elif BLOCK_SIZE >= 2048:
34
+ num_warps = 8
35
+
36
+ return num_warps
37
+
38
+
39
+ @triton.jit
40
+ def _tv_distance_kernel(
41
+ p_ptr,
42
+ p_stride,
43
+ q_ptr,
44
+ q_stride,
45
+ loss_ptr,
46
+ loss_stride,
47
+ grads_ptr,
48
+ grads_stride,
49
+ label_ptr,
50
+ ignore_index: tl.constexpr,
51
+ n_cols,
52
+ BLOCK_SIZE: tl.constexpr,
53
+ HAS_LABEL: tl.constexpr,
54
+ reduction: tl.constexpr = _REDUCTION_MODE_BATCHMEAN,
55
+ ):
56
+ pid = tl.program_id(0).to(tl.int64)
57
+ p_ptr += pid * p_stride
58
+ q_ptr += pid * q_stride
59
+ loss_ptr += pid * loss_stride
60
+ grads_ptr += pid * grads_stride
61
+ label_ptr += pid
62
+
63
+ base_offsets = tl.arange(0, BLOCK_SIZE)
64
+
65
+ if HAS_LABEL:
66
+ label = tl.load(label_ptr)
67
+ if label == ignore_index:
68
+ for i in range(0, n_cols, BLOCK_SIZE):
69
+ offsets = i + base_offsets
70
+ mask = offsets < n_cols
71
+ tl.store(grads_ptr + offsets, 0.0, mask=mask)
72
+ if reduction == _REDUCTION_MODE_NONE:
73
+ tl.store(loss_ptr + offsets, 0.0, mask=mask)
74
+ return
75
+
76
+ loss_sum = 0.0
77
+ for i in range(0, n_cols, BLOCK_SIZE):
78
+ offsets = i + base_offsets
79
+ mask = offsets < n_cols
80
+
81
+ p = tl.load(p_ptr + offsets, mask=mask, other=0.0)
82
+ q = tl.load(q_ptr + offsets, mask=mask, other=0.0)
83
+
84
+ # TVD(P || Q) = 0.5 * |P - Q|
85
+ tv_loss = 0.5 * tl.abs(p - q)
86
+
87
+ grad_res = tl.where(p > q, 0.5, -0.5)
88
+
89
+ tl.store(grads_ptr + offsets, grad_res, mask=mask)
90
+
91
+ if reduction == _REDUCTION_MODE_NONE:
92
+ tl.store(loss_ptr + offsets, tv_loss, mask=mask)
93
+ else:
94
+ loss_sum += tl.sum(tv_loss, axis=0)
95
+
96
+ if reduction != _REDUCTION_MODE_NONE:
97
+ tl.store(loss_ptr, loss_sum)
98
+
99
+
100
+ def tv_distance_forward_triton(p, q, shift_labels, reduction, ignore_index, has_label):
101
+ BT, V = p.shape
102
+
103
+ BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(V))
104
+ num_warps = get_num_warps(BLOCK_SIZE)
105
+
106
+ grid = (BT,)
107
+
108
+ reduction = _str_to_reduction_mode[reduction]
109
+
110
+ out_size = (BT, V) if reduction == _REDUCTION_MODE_NONE.value else (BT,)
111
+ output_tensor = torch.zeros(out_size, device=p.device, dtype=torch.float32)
112
+ grads = torch.empty_like(p)
113
+
114
+ n_non_ignore = (shift_labels != ignore_index).sum().item() if has_label else BT
115
+
116
+ _tv_distance_kernel[grid](
117
+ p,
118
+ p.stride(0),
119
+ q,
120
+ q.stride(0),
121
+ output_tensor,
122
+ output_tensor.stride(0),
123
+ grads,
124
+ grads.stride(0),
125
+ shift_labels if has_label else torch.empty(1, device=p.device),
126
+ ignore_index,
127
+ V,
128
+ BLOCK_SIZE=BLOCK_SIZE,
129
+ HAS_LABEL=has_label,
130
+ num_warps=num_warps,
131
+ reduction=reduction,
132
+ )
133
+
134
+ if reduction == _REDUCTION_MODE_BATCHMEAN.value:
135
+ return output_tensor.sum() / n_non_ignore, grads / n_non_ignore
136
+ elif reduction == _REDUCTION_MODE_SUM.value:
137
+ return output_tensor.sum(dim=0), grads
138
+ elif reduction == _REDUCTION_MODE_MEAN.value:
139
+ return output_tensor.sum() / (n_non_ignore * V), grads / (n_non_ignore * V)
140
+ else:
141
+ return output_tensor, grads
142
+
143
+
144
+ def tvd_backward_triton(grad_output, grads):
145
+ # If cross entropy is the last layer, grad_output is 1.0. Skip the mul then.
146
+ if torch.equal(grad_output, torch.tensor(1.0, device=grad_output.device)):
147
+ return grads
148
+
149
+ return grads * grad_output
150
+
151
+
152
+ class LigerTVDLossFunction(torch.autograd.Function):
153
+ """
154
+ Class implementing the forward and backward pass for the Total Variation Distance Loss using Triton.
155
+ """
156
+
157
+ @staticmethod
158
+ @ensure_contiguous
159
+ def forward(
160
+ ctx,
161
+ p: torch.Tensor,
162
+ q: torch.Tensor,
163
+ shift_labels: Optional[torch.Tensor] = None,
164
+ reduction: REDUCTION_LITERAL = "batchmean",
165
+ ignore_index: int = -100,
166
+ ) -> torch.Tensor:
167
+ """A forward pass for the Total Variation Distance Loss.
168
+
169
+ Args:
170
+ ctx: Torch autograd context
171
+ p (torch.Tensor): A tensor of shape (BT, V) containing the first distribution.
172
+ q (torch.Tensor): A tensor of shape (BT, V) containing the second distribution.
173
+ shift_labels (Optional[torch.Tensor]): A tensor of shape (BT,) containing the labels.
174
+ reduction (REDUCTION_LITERAL, optional): The reduction method to be applied. Defaults to "batchmean".
175
+ ignore_index (int, optional): The index to ignore during loss calculation. Defaults to -100.
176
+
177
+ Returns:
178
+ torch.Tensor: The computed Total Variation Distance Loss.
179
+ """
180
+ has_label = False
181
+ if shift_labels is not None:
182
+ assert shift_labels.shape == (p.shape[0],), (
183
+ f"the shape of shift_labels must be (BT,). Got: {shift_labels.shape}"
184
+ )
185
+ shift_labels = shift_labels.contiguous()
186
+ has_label = True
187
+
188
+ loss, grads = tv_distance_forward_triton(p, q, shift_labels, reduction, ignore_index, has_label)
189
+ ctx.save_for_backward(grads)
190
+ return loss
191
+
192
+ @staticmethod
193
+ @ensure_contiguous
194
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
195
+ """A backward pass for the Total Variation Distance Loss.
196
+
197
+ Args:
198
+ ctx: Torch autograd context
199
+ grad_output (torch.Tensor): The gradient of the loss with respect to the output.
200
+
201
+ Returns:
202
+ tuple[torch.Tensor, None, None, None, None]: The gradient of the loss with respect to the inputs.
203
+ """
204
+ (grads,) = ctx.saved_tensors
205
+ grads = tvd_backward_triton(grad_output, grads)
206
+
207
+ return grads, None, None, None, None
liger_kernel/ops/utils.py CHANGED
@@ -49,8 +49,7 @@ def calculate_settings(n):
49
49
  BLOCK_SIZE = triton.next_power_of_2(n)
50
50
  if BLOCK_SIZE > MAX_FUSED_SIZE:
51
51
  raise RuntimeError(
52
- f"Cannot launch Triton kernel since n = {n} exceeds "
53
- f"the recommended Triton blocksize = {MAX_FUSED_SIZE}."
52
+ f"Cannot launch Triton kernel since n = {n} exceeds the recommended Triton blocksize = {MAX_FUSED_SIZE}."
54
53
  )
55
54
 
56
55
  num_warps = 4
@@ -9,10 +9,12 @@ from liger_kernel.transformers.monkey_patch import _apply_liger_kernel # noqa:
9
9
  from liger_kernel.transformers.monkey_patch import _apply_liger_kernel_to_instance # noqa: F401
10
10
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma # noqa: F401
11
11
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma2 # noqa: F401
12
+ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_granite # noqa: F401
12
13
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama # noqa: F401
13
14
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mistral # noqa: F401
14
15
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mixtral # noqa: F401
15
16
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mllama # noqa: F401
17
+ from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_olmo2 # noqa: F401
16
18
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_phi3 # noqa: F401
17
19
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2 # noqa: F401
18
20
  from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2_vl # noqa: F401
@@ -21,3 +23,4 @@ from liger_kernel.transformers.rope import liger_rotary_pos_emb # noqa: F401
21
23
  from liger_kernel.transformers.swiglu import LigerBlockSparseTop2MLP # noqa: F401
22
24
  from liger_kernel.transformers.swiglu import LigerPhi3SwiGLUMLP # noqa: F401
23
25
  from liger_kernel.transformers.swiglu import LigerSwiGLUMLP # noqa: F401
26
+ from liger_kernel.transformers.tvd import LigerTVDLoss # noqa: F401
@@ -17,9 +17,9 @@ class LigerCrossEntropyLoss(torch.nn.Module):
17
17
  return_z_loss: bool = False,
18
18
  ):
19
19
  super().__init__()
20
- assert (label_smoothing >= 0) and (
21
- label_smoothing <= 1
22
- ), f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
20
+ assert (label_smoothing >= 0) and (label_smoothing <= 1), (
21
+ f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
22
+ )
23
23
  assert reduction in {
24
24
  "mean",
25
25
  "sum",
@@ -12,6 +12,7 @@ from liger_kernel.ops.qwen2vl_mrope import LigerQwen2VLMRopeFunction
12
12
  from liger_kernel.ops.rms_norm import LigerRMSNormFunction
13
13
  from liger_kernel.ops.rope import LigerRopeFunction
14
14
  from liger_kernel.ops.swiglu import LigerSiLUMulFunction
15
+ from liger_kernel.ops.tvd import LigerTVDLossFunction
15
16
 
16
17
 
17
18
  # conform to the function signature in https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html
@@ -157,6 +158,22 @@ def liger_kl_div(
157
158
  )
158
159
 
159
160
 
161
+ def liger_tvd(
162
+ input,
163
+ target,
164
+ shift_labels=None,
165
+ reduction: str = "mean",
166
+ ignore_index: int = -100,
167
+ ):
168
+ return LigerTVDLossFunction.apply(
169
+ input,
170
+ target,
171
+ shift_labels,
172
+ reduction,
173
+ ignore_index,
174
+ )
175
+
176
+
160
177
  def liger_layer_norm(X, W, B, eps):
161
178
  return LigerLayerNormFunction.apply(X, W, B, eps)
162
179
 
@@ -17,9 +17,9 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
17
17
  return_z_loss: bool = False,
18
18
  ):
19
19
  super().__init__()
20
- assert (label_smoothing >= 0) and (
21
- label_smoothing <= 1
22
- ), f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
20
+ assert (label_smoothing >= 0) and (label_smoothing <= 1), (
21
+ f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
22
+ )
23
23
  assert reduction in {
24
24
  "mean",
25
25
  "sum",
@@ -21,9 +21,9 @@ class LigerGroupNorm(nn.Module):
21
21
  "zeros",
22
22
  ], f"init_fn must be either 'ones' or 'zeros', got {init_fn}"
23
23
 
24
- assert (
25
- num_channels % num_groups == 0
26
- ), f"Number of channels {num_channels} must be divisible by num_groups {num_groups}"
24
+ assert num_channels % num_groups == 0, (
25
+ f"Number of channels {num_channels} must be divisible by num_groups {num_groups}"
26
+ )
27
27
  self.num_channels = num_channels
28
28
  self.num_groups = num_groups
29
29
  self.eps = eps
@@ -34,9 +34,9 @@ class LigerGroupNorm(nn.Module):
34
34
  def forward(self, hidden_states):
35
35
  # hidden_states: (batch_size, num_channels, *)
36
36
  assert hidden_states.dim() >= 3, f"Input must have atleast 3 dimensions, got {hidden_states.dim()}"
37
- assert (
38
- hidden_states.size(1) == self.num_channels
39
- ), f"Input tensor must have {self.num_channels} channels, got {hidden_states.size(1)}"
37
+ assert hidden_states.size(1) == self.num_channels, (
38
+ f"Input tensor must have {self.num_channels} channels, got {hidden_states.size(1)}"
39
+ )
40
40
  return LigerGroupNormFunction.apply(
41
41
  hidden_states,
42
42
  self.weight,
@@ -0,0 +1,124 @@
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.models.olmo2.modeling_olmo2 import _CONFIG_FOR_DOC
10
+ from transformers.models.olmo2.modeling_olmo2 import OLMO2_INPUTS_DOCSTRING
11
+ from transformers.utils import add_start_docstrings_to_model_forward
12
+ from transformers.utils import replace_return_docstrings
13
+
14
+ from liger_kernel.transformers.fused_linear_cross_entropy import LigerFusedLinearCrossEntropyLoss
15
+
16
+
17
+ @add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING)
18
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
19
+ def lce_forward(
20
+ self,
21
+ input_ids: torch.LongTensor = None,
22
+ attention_mask: Optional[torch.Tensor] = None,
23
+ position_ids: Optional[torch.LongTensor] = None,
24
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
25
+ inputs_embeds: Optional[torch.FloatTensor] = None,
26
+ labels: Optional[torch.LongTensor] = None,
27
+ use_cache: Optional[bool] = None,
28
+ output_attentions: Optional[bool] = None,
29
+ output_hidden_states: Optional[bool] = None,
30
+ return_dict: Optional[bool] = None,
31
+ cache_position: Optional[torch.LongTensor] = None,
32
+ num_logits_to_keep: int = 0,
33
+ **loss_kwargs,
34
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
35
+ r"""
36
+ Args:
37
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
38
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
39
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
40
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
41
+
42
+ num_logits_to_keep (`int`, *optional*):
43
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
44
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
45
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
46
+
47
+ Returns:
48
+
49
+ Example:
50
+
51
+ ```python
52
+ >>> from transformers import AutoTokenizer, Olmo2ForCausalLM
53
+
54
+ >>> model = Olmo2ForCausalLM.from_pretrained("allenai/Olmo2-1B-hf")
55
+ >>> tokenizer = AutoTokenizer.from_pretrained("allenai/Olmo2-1B-hf")
56
+
57
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
58
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
59
+
60
+ >>> # Generate
61
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
62
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
63
+ 'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
64
+ ```
65
+ """
66
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
67
+ output_hidden_states = (
68
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
69
+ )
70
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
71
+
72
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
73
+ outputs = self.model(
74
+ input_ids=input_ids,
75
+ attention_mask=attention_mask,
76
+ position_ids=position_ids,
77
+ past_key_values=past_key_values,
78
+ inputs_embeds=inputs_embeds,
79
+ use_cache=use_cache,
80
+ output_attentions=output_attentions,
81
+ output_hidden_states=output_hidden_states,
82
+ return_dict=return_dict,
83
+ cache_position=cache_position,
84
+ )
85
+
86
+ hidden_states = outputs[0]
87
+
88
+ logits = None
89
+ loss = None
90
+ # if in training mode, don't materialize logits
91
+ if self.training and (labels is not None):
92
+ # We do the same thing as ForCausalLMLoss but using Liger FLCE
93
+
94
+ shift_hidden_states = hidden_states[..., :-1, :].contiguous()
95
+ shift_labels = labels[..., 1:].contiguous()
96
+
97
+ # flatten tokens
98
+ shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
99
+ shift_labels = shift_labels.view(-1)
100
+
101
+ reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
102
+ lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
103
+
104
+ loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
105
+ if reduction == "sum":
106
+ loss /= loss_kwargs["num_items_in_batch"]
107
+
108
+ else: # if in inference mode materialize logits
109
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
110
+ if labels is not None:
111
+ loss = self.loss_function(
112
+ logits=logits,
113
+ labels=labels,
114
+ vocab_size=self.config.vocab_size,
115
+ **loss_kwargs,
116
+ )
117
+
118
+ return CausalLMOutputWithPast(
119
+ loss=loss,
120
+ logits=logits,
121
+ past_key_values=outputs.past_key_values,
122
+ hidden_states=outputs.hidden_states,
123
+ attentions=outputs.attentions,
124
+ )