liger-kernel-nightly 0.0.1.dev20240819184814__py3-none-any.whl → 0.6.4.dev20251212103629__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.
Files changed (126) hide show
  1. liger_kernel/__init__.py +0 -0
  2. liger_kernel/chunked_loss/README.md +25 -0
  3. liger_kernel/chunked_loss/__init__.py +8 -0
  4. liger_kernel/chunked_loss/cosine_similarity_loss.py +136 -0
  5. liger_kernel/chunked_loss/cpo_loss.py +157 -0
  6. liger_kernel/chunked_loss/dpo_loss.py +229 -0
  7. liger_kernel/chunked_loss/functional.py +17 -0
  8. liger_kernel/chunked_loss/fused_linear_distillation.py +292 -0
  9. liger_kernel/chunked_loss/fused_linear_ppo.py +366 -0
  10. liger_kernel/chunked_loss/fused_linear_preference.py +433 -0
  11. liger_kernel/chunked_loss/fused_linear_unpaired_preference.py +341 -0
  12. liger_kernel/chunked_loss/grpo_loss.py +307 -0
  13. liger_kernel/chunked_loss/jsd_loss.py +200 -0
  14. liger_kernel/chunked_loss/kto_loss.py +210 -0
  15. liger_kernel/chunked_loss/orpo_loss.py +144 -0
  16. liger_kernel/chunked_loss/simpo_loss.py +165 -0
  17. liger_kernel/env_report.py +63 -0
  18. liger_kernel/ops/__init__.py +141 -0
  19. liger_kernel/ops/backends/README.md +151 -0
  20. liger_kernel/ops/backends/__init__.py +13 -0
  21. liger_kernel/ops/backends/_ascend/__init__.py +5 -0
  22. liger_kernel/ops/backends/_ascend/ops/__init__.py +15 -0
  23. liger_kernel/ops/backends/registry.py +61 -0
  24. liger_kernel/ops/cross_entropy.py +383 -114
  25. liger_kernel/ops/dyt.py +160 -0
  26. liger_kernel/ops/experimental/embedding.py +141 -0
  27. liger_kernel/ops/experimental/mm_int8int2.py +349 -0
  28. liger_kernel/ops/fused_add_rms_norm.py +416 -0
  29. liger_kernel/ops/fused_linear_cross_entropy.py +346 -132
  30. liger_kernel/ops/fused_linear_jsd.py +228 -0
  31. liger_kernel/ops/fused_neighborhood_attention.py +1022 -0
  32. liger_kernel/ops/geglu.py +66 -64
  33. liger_kernel/ops/group_norm.py +306 -0
  34. liger_kernel/ops/grpo_loss.py +312 -0
  35. liger_kernel/ops/jsd.py +201 -0
  36. liger_kernel/ops/kl_div.py +262 -0
  37. liger_kernel/ops/layer_norm.py +320 -0
  38. liger_kernel/ops/llama4_rope.py +225 -0
  39. liger_kernel/ops/multi_token_attention.py +207 -0
  40. liger_kernel/ops/poly_norm.py +390 -0
  41. liger_kernel/ops/qwen2vl_mrope.py +222 -0
  42. liger_kernel/ops/rms_norm.py +484 -88
  43. liger_kernel/ops/rope.py +122 -117
  44. liger_kernel/ops/softmax.py +201 -0
  45. liger_kernel/ops/sparsemax.py +179 -0
  46. liger_kernel/ops/swiglu.py +68 -65
  47. liger_kernel/ops/tiled_mlp.py +136 -0
  48. liger_kernel/ops/tvd.py +207 -0
  49. liger_kernel/ops/utils.py +82 -3
  50. liger_kernel/transformers/__init__.py +218 -6
  51. liger_kernel/transformers/auto_model.py +38 -0
  52. liger_kernel/transformers/cross_entropy.py +52 -7
  53. liger_kernel/transformers/dyt.py +22 -0
  54. liger_kernel/transformers/experimental/__init__.py +5 -0
  55. liger_kernel/transformers/experimental/embedding.py +26 -0
  56. liger_kernel/transformers/fsdp.py +55 -0
  57. liger_kernel/transformers/functional.py +301 -0
  58. liger_kernel/transformers/fused_add_rms_norm.py +39 -0
  59. liger_kernel/transformers/fused_linear_cross_entropy.py +59 -10
  60. liger_kernel/transformers/fused_linear_jsd.py +95 -0
  61. liger_kernel/transformers/fused_neighborhood_attention.py +234 -0
  62. liger_kernel/transformers/geglu.py +6 -7
  63. liger_kernel/transformers/group_norm.py +50 -0
  64. liger_kernel/transformers/grpo_loss.py +153 -0
  65. liger_kernel/transformers/jsd.py +70 -0
  66. liger_kernel/transformers/kl_div.py +12 -0
  67. liger_kernel/transformers/layer_norm.py +24 -0
  68. liger_kernel/transformers/llama4_rope.py +93 -0
  69. liger_kernel/transformers/model/falcon_h1.py +122 -0
  70. liger_kernel/transformers/model/gemma.py +261 -0
  71. liger_kernel/transformers/model/gemma2.py +283 -0
  72. liger_kernel/transformers/model/gemma3.py +332 -0
  73. liger_kernel/transformers/model/glm4.py +141 -0
  74. liger_kernel/transformers/model/glm4v.py +163 -0
  75. liger_kernel/transformers/model/glm4v_moe.py +172 -0
  76. liger_kernel/transformers/model/gpt_oss.py +211 -0
  77. liger_kernel/transformers/model/hunyuan_v1.py +134 -0
  78. liger_kernel/transformers/model/internvl.py +157 -0
  79. liger_kernel/transformers/model/llama.py +221 -41
  80. liger_kernel/transformers/model/llama4.py +121 -0
  81. liger_kernel/transformers/model/llava.py +344 -0
  82. liger_kernel/transformers/model/loss_utils.py +95 -0
  83. liger_kernel/transformers/model/mistral.py +145 -0
  84. liger_kernel/transformers/model/mixtral.py +293 -0
  85. liger_kernel/transformers/model/mllama.py +269 -0
  86. liger_kernel/transformers/model/olmo2.py +141 -0
  87. liger_kernel/transformers/model/olmo3.py +142 -0
  88. liger_kernel/transformers/model/output_classes.py +147 -0
  89. liger_kernel/transformers/model/paligemma.py +433 -0
  90. liger_kernel/transformers/model/phi3.py +120 -0
  91. liger_kernel/transformers/model/qwen2.py +259 -0
  92. liger_kernel/transformers/model/qwen2_5_vl.py +163 -0
  93. liger_kernel/transformers/model/qwen2_vl.py +159 -0
  94. liger_kernel/transformers/model/qwen3.py +136 -0
  95. liger_kernel/transformers/model/qwen3_moe.py +152 -0
  96. liger_kernel/transformers/model/qwen3_next.py +146 -0
  97. liger_kernel/transformers/model/qwen3_vl.py +150 -0
  98. liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
  99. liger_kernel/transformers/model/smollm3.py +199 -0
  100. liger_kernel/transformers/model/smolvlm.py +158 -0
  101. liger_kernel/transformers/monkey_patch.py +2816 -21
  102. liger_kernel/transformers/multi_token_attention.py +64 -0
  103. liger_kernel/transformers/poly_norm.py +42 -0
  104. liger_kernel/transformers/qwen2vl_mrope.py +20 -0
  105. liger_kernel/transformers/rms_norm.py +75 -5
  106. liger_kernel/transformers/rope.py +47 -3
  107. liger_kernel/transformers/softmax.py +12 -0
  108. liger_kernel/transformers/sparsemax.py +16 -0
  109. liger_kernel/transformers/swiglu.py +62 -6
  110. liger_kernel/transformers/tiled_mlp.py +133 -0
  111. liger_kernel/transformers/trainer/__init__.py +4 -0
  112. liger_kernel/transformers/trainer/orpo_trainer.py +130 -0
  113. liger_kernel/transformers/trainer_integration.py +2 -45
  114. liger_kernel/transformers/tvd.py +13 -0
  115. liger_kernel/triton/__init__.py +1 -3
  116. liger_kernel/triton/monkey_patch.py +1 -5
  117. liger_kernel/utils.py +96 -0
  118. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/METADATA +447 -0
  119. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/NOTICE +58 -0
  120. liger_kernel_nightly-0.6.4.dev20251212103629.dist-info/RECORD +124 -0
  121. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/WHEEL +1 -1
  122. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/METADATA +0 -21
  123. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/NOTICE +0 -4
  124. liger_kernel_nightly-0.0.1.dev20240819184814.dist-info/RECORD +0 -27
  125. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/LICENSE +0 -0
  126. {liger_kernel_nightly-0.0.1.dev20240819184814.dist-info → liger_kernel_nightly-0.6.4.dev20251212103629.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,301 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+ from liger_kernel.ops import LigerCrossEntropyFunction
7
+ from liger_kernel.ops import LigerDyTFunction
8
+ from liger_kernel.ops import LigerFusedAddRMSNormFunction
9
+ from liger_kernel.ops import LigerFusedLinearCrossEntropyFunction
10
+ from liger_kernel.ops import LigerFusedLinearJSDFunction
11
+ from liger_kernel.ops import LigerFusedNeighborhoodAttentionFunction
12
+ from liger_kernel.ops import LigerGELUMulFunction
13
+ from liger_kernel.ops import LigerGroupNormFunction
14
+ from liger_kernel.ops import LigerJSDFunction
15
+ from liger_kernel.ops import LigerKLDivLossFunction
16
+ from liger_kernel.ops import LigerLayerNormFunction
17
+ from liger_kernel.ops import LigerMultiTokenAttentionFunction
18
+ from liger_kernel.ops import LigerPolyNormFunction
19
+ from liger_kernel.ops import LigerQwen2VLMRopeFunction
20
+ from liger_kernel.ops import LigerRMSNormFunction
21
+ from liger_kernel.ops import LigerRopeFunction
22
+ from liger_kernel.ops import LigerSiLUMulFunction
23
+ from liger_kernel.ops import LigerSoftmaxFunction
24
+ from liger_kernel.ops import LigerSparsemaxFunction
25
+ from liger_kernel.ops import LigerTVDLossFunction
26
+
27
+
28
+ @dataclass
29
+ class CrossEntropyOutput:
30
+ loss: torch.Tensor
31
+ z_loss: Optional[torch.Tensor] = None
32
+ token_accuracy: Optional[torch.Tensor] = None
33
+
34
+
35
+ # conform to the function signature in https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html
36
+ # `weight` and `size_average` are placeholders and not implemented yet
37
+ def liger_cross_entropy(
38
+ input,
39
+ target,
40
+ weight=None,
41
+ size_average=None,
42
+ ignore_index: int = -100,
43
+ reduce=None,
44
+ reduction: str = "mean",
45
+ label_smoothing: float = 0.0,
46
+ lse_square_scale: float = 0.0,
47
+ softcap: Optional[float] = None,
48
+ return_z_loss: bool = False,
49
+ return_token_accuracy: bool = False,
50
+ ):
51
+ loss, z_loss, token_accuracy = LigerCrossEntropyFunction.apply(
52
+ input,
53
+ target,
54
+ weight,
55
+ ignore_index,
56
+ lse_square_scale,
57
+ label_smoothing,
58
+ reduction,
59
+ softcap,
60
+ return_z_loss,
61
+ return_token_accuracy,
62
+ )
63
+
64
+ if not return_z_loss and not return_token_accuracy:
65
+ return loss
66
+
67
+ return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
68
+
69
+
70
+ def liger_fused_linear_cross_entropy(
71
+ input,
72
+ weight,
73
+ target,
74
+ bias=None,
75
+ ce_weight=None,
76
+ ignore_index: int = -100,
77
+ lse_square_scale: float = 0.0,
78
+ label_smoothing: float = 0.0,
79
+ reduction: str = "mean",
80
+ softcap: Optional[float] = None,
81
+ return_z_loss: bool = False,
82
+ accum_dtype=None,
83
+ use_token_scaling: bool = False,
84
+ return_token_accuracy: bool = False,
85
+ ):
86
+ loss, z_loss, token_accuracy = LigerFusedLinearCrossEntropyFunction.apply(
87
+ input,
88
+ weight,
89
+ target,
90
+ bias,
91
+ ce_weight,
92
+ ignore_index,
93
+ lse_square_scale,
94
+ label_smoothing,
95
+ reduction,
96
+ softcap,
97
+ return_z_loss,
98
+ accum_dtype,
99
+ use_token_scaling,
100
+ return_token_accuracy,
101
+ )
102
+
103
+ if not return_z_loss and not return_token_accuracy:
104
+ return loss
105
+
106
+ return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
107
+
108
+
109
+ def liger_fused_linear_jsd(
110
+ student_input,
111
+ student_weight,
112
+ teacher_input,
113
+ teacher_weight,
114
+ shift_labels=None,
115
+ jsd_beta: float = 0.5,
116
+ ignore_index: int = -100,
117
+ temperature: float = 1.0,
118
+ ):
119
+ return LigerFusedLinearJSDFunction.apply(
120
+ student_input,
121
+ student_weight,
122
+ teacher_input,
123
+ teacher_weight,
124
+ shift_labels,
125
+ jsd_beta,
126
+ ignore_index,
127
+ temperature,
128
+ )
129
+
130
+
131
+ def liger_geglu(a, b):
132
+ return LigerGELUMulFunction.apply(a, b)
133
+
134
+
135
+ def liger_group_norm(
136
+ X,
137
+ affine_scaling_weight,
138
+ affine_shifting_bias,
139
+ num_channels,
140
+ num_groups,
141
+ eps,
142
+ ):
143
+ return LigerGroupNormFunction.apply(
144
+ X,
145
+ affine_scaling_weight,
146
+ affine_shifting_bias,
147
+ num_channels,
148
+ num_groups,
149
+ eps,
150
+ )
151
+
152
+
153
+ def liger_jsd(
154
+ input,
155
+ target,
156
+ shift_labels=None,
157
+ beta: float = 0.5,
158
+ ignore_index: int = -100,
159
+ ):
160
+ return LigerJSDFunction.apply(
161
+ input,
162
+ target,
163
+ shift_labels,
164
+ beta,
165
+ ignore_index,
166
+ )
167
+
168
+
169
+ # conform to the function signature in https://pytorch.org/docs/stable/generated/torch.nn.functional.kl_div.html#torch.nn.functional.kl_div
170
+ # `size_average` and `mean` are being deprecated in torch API and are placeholders here
171
+ def liger_kl_div(
172
+ input,
173
+ target,
174
+ size_average: bool = True,
175
+ reduce: bool = True,
176
+ reduction: str = "mean",
177
+ log_target: bool = False,
178
+ eps: float = 1e-10,
179
+ ):
180
+ # Note: the default reduction in torch is `mean`, but being `batchmean` in Liger
181
+ return LigerKLDivLossFunction.apply(
182
+ input,
183
+ target,
184
+ reduction,
185
+ log_target,
186
+ eps,
187
+ )
188
+
189
+
190
+ def liger_sparsemax(
191
+ input,
192
+ dim: int = -1,
193
+ ):
194
+ return LigerSparsemaxFunction.apply(input, dim)
195
+
196
+
197
+ def liger_multi_token_attention(
198
+ scores,
199
+ weight,
200
+ bias=None,
201
+ stride: int = 1,
202
+ padding: int = 0,
203
+ dilation: int = 1,
204
+ groups: int = 1,
205
+ sparse: bool = False,
206
+ ):
207
+ """
208
+ Functional interface for multi-token attention.
209
+
210
+ Args:
211
+ scores: Input tensor of shape (B, C_in, L, L)
212
+ weight: Convolution weight tensor of shape (C_out, C_in // groups, K, K)
213
+ bias: Optional bias tensor of shape (C_out,)
214
+ stride: Stride for the convolution (default: 1)
215
+ padding: Padding for the convolution (default: 0)
216
+ dilation: Dilation factor for the convolution (default: 1)
217
+ groups: Number of groups for the convolution (default: 1)
218
+ sparse: Specifies if input tensors are expected to be sparse (default: False)
219
+ Returns:
220
+ Output tensor after applying multi-token attention.
221
+ """
222
+ return LigerMultiTokenAttentionFunction.apply(scores, weight, bias, stride, padding, dilation, groups, sparse)
223
+
224
+
225
+ def liger_fused_neighborhood_attention(
226
+ query,
227
+ key,
228
+ value,
229
+ kernel_size: int = 7,
230
+ dilation: int = 1,
231
+ scale: float = None,
232
+ ):
233
+ """
234
+ Liger fused neighborhood attention.
235
+
236
+ paper: https://arxiv.org/pdf/2504.16922
237
+
238
+ Args:
239
+ query: Query tensor of shape [batch_size, num_heads, seq_len, head_dim]
240
+ key: Key tensor of shape [batch_size, num_heads, seq_len, head_dim]
241
+ value: Value tensor of shape [batch_size, num_heads, seq_len, head_dim]
242
+ kernel_size: Size of the neighborhood window (default: 7)
243
+ dilation: Dilation factor for the neighborhood (default: 1)
244
+ scale: Scaling factor for attention scores (default: rsqrt(head_dim))
245
+
246
+ Returns:
247
+ Output tensor of shape [batch_size, num_heads, seq_len, head_dim]
248
+ """
249
+ return LigerFusedNeighborhoodAttentionFunction.apply(query, key, value, kernel_size, dilation, scale)
250
+
251
+
252
+ def liger_tvd(
253
+ input,
254
+ target,
255
+ shift_labels=None,
256
+ reduction: str = "mean",
257
+ ignore_index: int = -100,
258
+ ):
259
+ return LigerTVDLossFunction.apply(
260
+ input,
261
+ target,
262
+ shift_labels,
263
+ reduction,
264
+ ignore_index,
265
+ )
266
+
267
+
268
+ def liger_layer_norm(X, W, B, eps):
269
+ return LigerLayerNormFunction.apply(X, W, B, eps)
270
+
271
+
272
+ def liger_qwen2vl_mrope(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
273
+ return LigerQwen2VLMRopeFunction.apply(q, k, cos, sin, mrope_section, unsqueeze_dim)
274
+
275
+
276
+ def liger_rms_norm(X, W, eps, offset: float = 0.0, casting_mode: str = "llama", in_place: bool = True):
277
+ return LigerRMSNormFunction.apply(X, W, eps, offset, casting_mode, in_place)
278
+
279
+
280
+ def liger_poly_norm(X, W, B, eps=1e-6, in_place=True):
281
+ return LigerPolyNormFunction.apply(X, W, B, eps, in_place)
282
+
283
+
284
+ def liger_fused_add_rms_norm(X, R, W, eps, offset: float = 0.0, casting_mode: str = "llama", in_place: bool = True):
285
+ return LigerFusedAddRMSNormFunction.apply(X, R, W, eps, offset, casting_mode, in_place)
286
+
287
+
288
+ def liger_rope(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
289
+ return LigerRopeFunction.apply(q, k, cos, sin, position_ids, unsqueeze_dim)
290
+
291
+
292
+ def liger_swiglu(a, b):
293
+ return LigerSiLUMulFunction.apply(a, b)
294
+
295
+
296
+ def liger_softmax(x):
297
+ return LigerSoftmaxFunction.apply(x)
298
+
299
+
300
+ def liger_dyt(x, alpha, gamma, beta):
301
+ return LigerDyTFunction.apply(x, alpha, gamma, beta)
@@ -0,0 +1,39 @@
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from liger_kernel.ops import LigerFusedAddRMSNormFunction
5
+
6
+
7
+ class LigerFusedAddRMSNorm(nn.Module):
8
+ def __init__(
9
+ self,
10
+ hidden_size,
11
+ eps=1e-6,
12
+ offset=0.0,
13
+ casting_mode="llama",
14
+ init_fn="ones",
15
+ in_place=False,
16
+ ):
17
+ super().__init__()
18
+ assert init_fn in [
19
+ "ones",
20
+ "zeros",
21
+ ], f"init_fn must be either 'ones' or 'zeros', got {init_fn}"
22
+ self.weight = nn.Parameter(torch.ones(hidden_size) if init_fn == "ones" else torch.zeros(hidden_size))
23
+ self.variance_epsilon, self.offset, self.casting_mode, self.in_place = (eps, offset, casting_mode, in_place)
24
+
25
+ def forward(self, hidden_states, residual):
26
+ return LigerFusedAddRMSNormFunction.apply(
27
+ hidden_states,
28
+ residual,
29
+ self.weight,
30
+ self.variance_epsilon,
31
+ self.offset,
32
+ self.casting_mode,
33
+ self.in_place,
34
+ )
35
+
36
+ def extra_repr(self):
37
+ return (
38
+ f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}, offset={self.offset}, in_place={self.in_place}"
39
+ )
@@ -1,15 +1,64 @@
1
- from torch.nn import CrossEntropyLoss
1
+ from typing import Optional
2
2
 
3
- from liger_kernel.ops.fused_linear_cross_entropy import (
4
- LigerFusedLinearCrossEntropyFunction,
5
- )
3
+ import torch
6
4
 
5
+ from liger_kernel.ops import LigerFusedLinearCrossEntropyFunction
6
+ from liger_kernel.transformers.functional import CrossEntropyOutput
7
7
 
8
- class LigerFusedLinearCrossEntropyLoss(CrossEntropyLoss):
9
- def __init__(self, *args, **kwargs):
10
- super(LigerFusedLinearCrossEntropyLoss, self).__init__(*args, **kwargs)
11
8
 
12
- def forward(self, lin_weight, _input, target):
13
- return LigerFusedLinearCrossEntropyFunction.apply(
14
- _input, lin_weight, target, self.ignore_index
9
+ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
10
+ def __init__(
11
+ self,
12
+ ce_weight: Optional[torch.FloatTensor] = None,
13
+ ignore_index: int = -100,
14
+ lse_square_scale: float = 0.0,
15
+ label_smoothing: float = 0.0,
16
+ reduction: str = "mean",
17
+ softcap: Optional[float] = None,
18
+ return_z_loss: bool = False,
19
+ accum_dtype: Optional[torch.dtype] = None,
20
+ use_token_scaling: bool = False,
21
+ return_token_accuracy: bool = False,
22
+ ):
23
+ super().__init__()
24
+ assert (label_smoothing >= 0) and (label_smoothing <= 1), (
25
+ f"label_smoothing must be between 0.0 and 1.0. Got: {label_smoothing}"
15
26
  )
27
+ assert reduction in {
28
+ "mean",
29
+ "sum",
30
+ "none",
31
+ }, f"reduction must be 'mean' or 'sum' or 'none'. Got: {reduction}"
32
+ assert softcap is None or softcap > 0, f"softcap must greater than 0.0 or None. Got: {softcap}"
33
+ self.ce_weight = ce_weight
34
+ self.ignore_index = ignore_index
35
+ self.lse_square_scale = lse_square_scale
36
+ self.label_smoothing = label_smoothing
37
+ self.reduction = reduction
38
+ self.softcap = softcap
39
+ self.return_z_loss = return_z_loss
40
+ self.accum_dtype = accum_dtype
41
+ self.use_token_scaling = use_token_scaling
42
+ self.return_token_accuracy = return_token_accuracy
43
+
44
+ def forward(self, lin_weight, _input, target, bias=None):
45
+ loss, z_loss, token_accuracy = LigerFusedLinearCrossEntropyFunction.apply(
46
+ _input,
47
+ lin_weight,
48
+ target,
49
+ bias,
50
+ self.ce_weight,
51
+ self.ignore_index,
52
+ self.lse_square_scale,
53
+ self.label_smoothing,
54
+ self.reduction,
55
+ self.softcap,
56
+ self.return_z_loss,
57
+ self.accum_dtype,
58
+ self.use_token_scaling,
59
+ self.return_token_accuracy,
60
+ )
61
+ if not self.return_z_loss and not self.return_token_accuracy:
62
+ return loss
63
+
64
+ return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
@@ -0,0 +1,95 @@
1
+ from typing import Optional
2
+
3
+ import torch
4
+
5
+ from liger_kernel.ops import LigerFusedLinearJSDFunction
6
+
7
+
8
+ class LigerFusedLinearJSD(torch.nn.Module):
9
+ r"""Fusing the last linear layer with generalized JSD
10
+
11
+ Handle the forward and backward pass of the final linear layer via JSD by avoiding
12
+ the materialization of the large logits tensor.
13
+
14
+ Args:
15
+ jsd_beta (float): coefficient beta of generalized JSD in the interval [0, 1]. It implements forward/reverse KL when beta equals 0 and 1 respectively. Default: `0.5`
16
+ ignore_index (int): The index to ignore in the target. Default: `-100`
17
+ temperature (float): temperature in softmax function to control the output probability distribution. Default: `1.0`
18
+
19
+ Shape:
20
+ - student_input: :math:`(BT, H)`, where B is batch size, T is sequence length, H is hidden dimension.
21
+ - student_weight: :math:`(V, H)`, where V is vocab size.
22
+ - teacher_input: :math:`(BT, H')`, where H' is hidden dimension of the teacher model.
23
+ - teacher_weight: :math:`(V, H')`, where hidden size H and H' can be different.
24
+ - shift_labels: :math:`(BT,)`
25
+ - Output: a scalar.
26
+
27
+ Examples:
28
+ ```python
29
+ >>> (B, T, H_s, H_t, V) = (2, 2, 3, 5, 10)
30
+ >>> fused_jsd = LigerFusedLinearJSD(jsd_beta=0.1, temperature=2.0)
31
+ >>> # generate inputs and weights
32
+ >>> student_input = torch.rand(B * T, H_s, device="cuda", requires_grad=True)
33
+ >>> student_lin = torch.nn.Linear(H_s, V, bias=False, device="cuda")
34
+ >>> # teacher input doesn't require grad, hidden_dim can be different from student's
35
+ >>> teacher_input = torch.rand(B * T, H_t, device="cuda")
36
+ >>> teacher_lin = torch.nn.Linear(H_t, V, bias=False, device="cuda")
37
+ >>> output = fused_jsd(student_input, student_lin.weight, teacher_input, teacher_lin.weight)
38
+ >>> output.backward()
39
+ >>>
40
+ >>> # Example with labels for supervised fine-tuning (SFT) context:
41
+ >>>
42
+ >>> # Assume hidden_states, lm_heads and corresponding labels are given
43
+ >>> student_lm_head = torch.nn.Linear(H_s, V, bias=False)
44
+ >>> student_hidden_states = torch.randn(B * T, H_s, requires_grad=True).log_softmax(dim=-1)
45
+ >>> teacher_lm_head = torch.nn.Linear(H_t, V, bias=False)
46
+ >>> teacher_hidden_states = torch.randn(B * T, H_t).log_softmax(dim=-1)
47
+ >>> labels = torch.randint(0, V, (B * T,), torch.long)
48
+ >>>
49
+ >>> # Shift so that tokens < n predict n
50
+ >>> shift_student_hidden_states = student_hidden_states[..., :-1, :].contiguous()
51
+ >>> shift_teacher_hidden_states = teacher_hidden_states[..., :-1, :].contiguous()
52
+ >>> shift_labels = labels[..., 1:].contiguous()
53
+ >>>
54
+ >>> # Flatten tokens
55
+ >>> shift_student_hidden_states = shift_student_hidden_states.view(-1, V)
56
+ >>> shift_teacher_hidden_states = shift_teacher_hidden_states.view(-1, V)
57
+ >>> shift_labels = shift_labels.view(-1)
58
+ >>>
59
+ >>> # Calculate loss
60
+ >>> loss_fct = LigerJSD(beta=0.1)
61
+ >>> loss = loss_fct(
62
+ >>> shift_studetn_hidden_states,
63
+ >>> student_lm_head.weight,
64
+ >>> shift_teacher_hidden_states,
65
+ >>> teacher_lm_head.weight,
66
+ >>> shift_labels
67
+ >>> )
68
+ ```
69
+ """
70
+
71
+ def __init__(self, jsd_beta=0.5, ignore_index=-100, temperature=1.0):
72
+ super().__init__()
73
+ assert temperature != 0, "temperature cannot be 0."
74
+ self.jsd_beta = jsd_beta
75
+ self.temperature = temperature
76
+ self.ignore_index = ignore_index
77
+
78
+ def forward(
79
+ self,
80
+ student_input: torch.Tensor,
81
+ student_weight: torch.Tensor,
82
+ teacher_input: torch.Tensor,
83
+ teacher_weight: torch.Tensor,
84
+ shift_labels: Optional[torch.LongTensor],
85
+ ):
86
+ return LigerFusedLinearJSDFunction.apply(
87
+ student_input,
88
+ student_weight,
89
+ teacher_input,
90
+ teacher_weight,
91
+ shift_labels,
92
+ self.jsd_beta,
93
+ self.ignore_index,
94
+ self.temperature,
95
+ )