liger-kernel 0.6.3__py3-none-any.whl → 0.6.5__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/cosine_similarity_loss.py +20 -5
- liger_kernel/chunked_loss/fused_linear_distillation.py +23 -5
- liger_kernel/chunked_loss/fused_linear_ppo.py +21 -5
- liger_kernel/chunked_loss/grpo_loss.py +8 -5
- liger_kernel/chunked_loss/jsd_loss.py +39 -11
- liger_kernel/ops/__init__.py +141 -0
- liger_kernel/ops/backends/README.md +151 -0
- liger_kernel/ops/backends/__init__.py +13 -0
- liger_kernel/ops/backends/_ascend/__init__.py +5 -0
- liger_kernel/ops/backends/_ascend/ascend-ub-manager-design.md +492 -0
- liger_kernel/ops/backends/_ascend/ops/__init__.py +61 -0
- liger_kernel/ops/backends/_ascend/ops/embedding.py +214 -0
- liger_kernel/ops/backends/_ascend/ops/geglu.py +191 -0
- liger_kernel/ops/backends/_ascend/ops/llama4_rope.py +298 -0
- liger_kernel/ops/backends/_ascend/ops/qwen2vl_mrope.py +275 -0
- liger_kernel/ops/backends/_ascend/ops/rope.py +265 -0
- liger_kernel/ops/backends/_ascend/ops/swiglu.py +142 -0
- liger_kernel/ops/backends/_ascend/ops/tvd.py +223 -0
- liger_kernel/ops/backends/_ascend/ub_manager.py +367 -0
- liger_kernel/ops/backends/registry.py +61 -0
- liger_kernel/ops/cross_entropy.py +71 -11
- liger_kernel/ops/dyt.py +5 -2
- liger_kernel/ops/fused_add_rms_norm.py +21 -23
- liger_kernel/ops/fused_linear_cross_entropy.py +32 -5
- liger_kernel/ops/geglu.py +5 -3
- liger_kernel/ops/group_norm.py +12 -8
- liger_kernel/ops/grpo_loss.py +3 -1
- liger_kernel/ops/kl_div.py +8 -11
- liger_kernel/ops/layer_norm.py +89 -69
- liger_kernel/ops/poly_norm.py +19 -21
- liger_kernel/ops/rms_norm.py +149 -71
- liger_kernel/ops/tiled_mlp.py +136 -0
- liger_kernel/ops/utils.py +25 -0
- liger_kernel/transformers/__init__.py +25 -0
- liger_kernel/transformers/auto_model.py +21 -0
- liger_kernel/transformers/cross_entropy.py +9 -4
- liger_kernel/transformers/dyt.py +1 -1
- liger_kernel/transformers/experimental/embedding.py +1 -1
- liger_kernel/transformers/functional.py +44 -26
- liger_kernel/transformers/fused_add_rms_norm.py +1 -1
- liger_kernel/transformers/fused_linear_cross_entropy.py +9 -4
- liger_kernel/transformers/fused_linear_jsd.py +1 -1
- liger_kernel/transformers/fused_neighborhood_attention.py +1 -1
- liger_kernel/transformers/geglu.py +1 -1
- liger_kernel/transformers/group_norm.py +1 -1
- liger_kernel/transformers/grpo_loss.py +57 -2
- liger_kernel/transformers/jsd.py +1 -1
- liger_kernel/transformers/kl_div.py +1 -1
- liger_kernel/transformers/layer_norm.py +1 -1
- liger_kernel/transformers/llama4_rope.py +1 -1
- liger_kernel/transformers/model/exaone4.py +136 -0
- liger_kernel/transformers/model/falcon_h1.py +19 -5
- liger_kernel/transformers/model/gemma.py +17 -6
- liger_kernel/transformers/model/gemma2.py +17 -8
- liger_kernel/transformers/model/gemma3.py +35 -16
- liger_kernel/transformers/model/glm4.py +16 -4
- liger_kernel/transformers/model/glm4v.py +16 -4
- liger_kernel/transformers/model/glm4v_moe.py +23 -4
- liger_kernel/transformers/model/gpt_oss.py +211 -0
- liger_kernel/transformers/model/hunyuan_v1.py +134 -0
- liger_kernel/transformers/model/internvl.py +12 -5
- liger_kernel/transformers/model/llama.py +14 -5
- liger_kernel/transformers/model/llama4.py +16 -4
- liger_kernel/transformers/model/llava.py +12 -4
- liger_kernel/transformers/model/loss_utils.py +37 -3
- liger_kernel/transformers/model/mistral.py +15 -6
- liger_kernel/transformers/model/mixtral.py +16 -7
- liger_kernel/transformers/model/mllama.py +12 -4
- liger_kernel/transformers/model/olmo2.py +16 -4
- liger_kernel/transformers/model/olmo3.py +142 -0
- liger_kernel/transformers/model/output_classes.py +147 -0
- liger_kernel/transformers/model/paligemma.py +23 -5
- liger_kernel/transformers/model/phi3.py +14 -7
- liger_kernel/transformers/model/qwen2.py +16 -3
- liger_kernel/transformers/model/qwen2_5_vl.py +14 -6
- liger_kernel/transformers/model/qwen2_vl.py +16 -4
- liger_kernel/transformers/model/qwen3.py +20 -5
- liger_kernel/transformers/model/qwen3_moe.py +19 -5
- liger_kernel/transformers/model/qwen3_next.py +17 -5
- liger_kernel/transformers/model/qwen3_vl.py +150 -0
- liger_kernel/transformers/model/qwen3_vl_moe.py +126 -0
- liger_kernel/transformers/model/smollm3.py +15 -6
- liger_kernel/transformers/monkey_patch.py +584 -49
- liger_kernel/transformers/multi_token_attention.py +1 -1
- liger_kernel/transformers/poly_norm.py +1 -1
- liger_kernel/transformers/qwen2vl_mrope.py +1 -1
- liger_kernel/transformers/rms_norm.py +8 -3
- liger_kernel/transformers/rope.py +45 -1
- liger_kernel/transformers/softmax.py +1 -1
- liger_kernel/transformers/sparsemax.py +1 -1
- liger_kernel/transformers/swiglu.py +18 -1
- liger_kernel/transformers/tiled_mlp.py +125 -0
- liger_kernel/transformers/tvd.py +1 -1
- liger_kernel/utils.py +54 -0
- {liger_kernel-0.6.3.dist-info → liger_kernel-0.6.5.dist-info}/METADATA +14 -4
- liger_kernel-0.6.5.dist-info/RECORD +134 -0
- {liger_kernel-0.6.3.dist-info → liger_kernel-0.6.5.dist-info}/WHEEL +1 -1
- liger_kernel-0.6.3.dist-info/RECORD +0 -111
- {liger_kernel-0.6.3.dist-info → liger_kernel-0.6.5.dist-info}/licenses/LICENSE +0 -0
- {liger_kernel-0.6.3.dist-info → liger_kernel-0.6.5.dist-info}/licenses/NOTICE +0 -0
- {liger_kernel-0.6.3.dist-info → liger_kernel-0.6.5.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
from typing import Callable
|
|
4
|
+
from typing import List
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from liger_kernel.ops.utils import ensure_contiguous
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LigerTiledMLPFunction(torch.autograd.Function):
|
|
13
|
+
"""
|
|
14
|
+
Based on DeepSpeed's TiledMLP:
|
|
15
|
+
https://github.com/deepspeedai/DeepSpeed/blob/v0.18.2/deepspeed/runtime/sequence_parallel/ulysses_sp.py#L838
|
|
16
|
+
|
|
17
|
+
Perform a tiled MLP computation to massively reduce memory usage needed to compute MLP
|
|
18
|
+
when using very long sequence lengths.
|
|
19
|
+
|
|
20
|
+
This module re-computes `forward` in the `backward`. So the `forward` occurs twice each iteration.
|
|
21
|
+
And if you're using activation checkpointing it then occurs thrice.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
fn: the function to call on sharded inputs (e.g., mlp.forward)
|
|
25
|
+
mlp_module: the MLP nn.Module object
|
|
26
|
+
x: the input to MLP.forward (hidden_states)
|
|
27
|
+
shards: how many shards to use
|
|
28
|
+
compute_params: a list of weights engaged in the compute
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
the computed hidden_states
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
@staticmethod
|
|
35
|
+
@ensure_contiguous
|
|
36
|
+
def forward(
|
|
37
|
+
ctx,
|
|
38
|
+
fn: Callable,
|
|
39
|
+
mlp_module: torch.nn.Module,
|
|
40
|
+
x: torch.Tensor,
|
|
41
|
+
shards: int,
|
|
42
|
+
compute_params: Optional[List[torch.nn.Parameter]] = None,
|
|
43
|
+
) -> torch.Tensor:
|
|
44
|
+
ctx.fn = fn
|
|
45
|
+
ctx.mlp_module = mlp_module
|
|
46
|
+
ctx.shards = shards
|
|
47
|
+
ctx.save_for_backward(x)
|
|
48
|
+
|
|
49
|
+
# x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts)
|
|
50
|
+
x_shards = list(torch.chunk(x, chunks=shards, dim=-2))
|
|
51
|
+
with torch.no_grad():
|
|
52
|
+
output_shards = [fn(mlp_module, x_shard) for x_shard in x_shards]
|
|
53
|
+
output_unsharded = torch.cat(output_shards, dim=-2)
|
|
54
|
+
|
|
55
|
+
return output_unsharded
|
|
56
|
+
|
|
57
|
+
@staticmethod
|
|
58
|
+
@ensure_contiguous
|
|
59
|
+
def backward(ctx, *grads) -> tuple:
|
|
60
|
+
fn = ctx.fn
|
|
61
|
+
(x,) = ctx.saved_tensors
|
|
62
|
+
mlp_module = ctx.mlp_module
|
|
63
|
+
shards = ctx.shards
|
|
64
|
+
|
|
65
|
+
x_requires_grad = x.requires_grad
|
|
66
|
+
x = x.detach()
|
|
67
|
+
# detach() unsets x.requires_grad, so restore it
|
|
68
|
+
x.requires_grad_(x_requires_grad)
|
|
69
|
+
|
|
70
|
+
# x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts)
|
|
71
|
+
hidden_size = x.shape[-1]
|
|
72
|
+
x_shape_orig = x.shape
|
|
73
|
+
|
|
74
|
+
# flatten bs+seqlen to avoid having stride issues when narrowing into seqlen w/ bs>1
|
|
75
|
+
x = x.view(-1, hidden_size)
|
|
76
|
+
incoming_grad = grads[0].view(-1, hidden_size)
|
|
77
|
+
x_grad = torch.zeros_like(x)
|
|
78
|
+
|
|
79
|
+
x_shards = list(torch.chunk(x, chunks=shards, dim=0))
|
|
80
|
+
|
|
81
|
+
for i, x_shard in enumerate(x_shards):
|
|
82
|
+
x_shard.requires_grad_(x_requires_grad)
|
|
83
|
+
|
|
84
|
+
# if seqlen is not exactly divisible by shards the last step will be shorter than shard_step
|
|
85
|
+
shard_step = x_shards[i].shape[0]
|
|
86
|
+
shard_offset = i * x_shards[0].shape[0]
|
|
87
|
+
|
|
88
|
+
x_shard.grad = x_grad.narrow(0, shard_offset, shard_step).view_as(x_shard)
|
|
89
|
+
incoming_grad_shard = incoming_grad.narrow(0, shard_offset, shard_step).view_as(x_shard)
|
|
90
|
+
|
|
91
|
+
with torch.enable_grad():
|
|
92
|
+
output = fn(mlp_module, x_shard)
|
|
93
|
+
torch.autograd.backward(output, incoming_grad_shard)
|
|
94
|
+
|
|
95
|
+
# unflatten
|
|
96
|
+
x_grad = x_grad.view(x_shape_orig)
|
|
97
|
+
|
|
98
|
+
return (None, None, x_grad, None, None)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def apply_tiled_mlp(
|
|
102
|
+
fn: Callable,
|
|
103
|
+
mlp_module: torch.nn.Module,
|
|
104
|
+
x: torch.Tensor,
|
|
105
|
+
num_shards: Optional[int] = None,
|
|
106
|
+
compute_params: Optional[List[torch.nn.Parameter]] = None,
|
|
107
|
+
) -> torch.Tensor:
|
|
108
|
+
"""
|
|
109
|
+
Apply tiled MLP computation for memory efficiency.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
fn: the function to call on sharded inputs (e.g., lambda module, x: module(x))
|
|
113
|
+
mlp_module: the MLP nn.Module object
|
|
114
|
+
x: the input tensor with shape [bs, seqlen, hidden_size] or [seqlen, hidden_size]
|
|
115
|
+
num_shards: number of shards to use. If None, automatically calculated as ceil(seqlen / hidden_size)
|
|
116
|
+
compute_params: list of parameters for DeepSpeed ZeRO optimization
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
output tensor with the same shape as input
|
|
120
|
+
"""
|
|
121
|
+
if num_shards is None:
|
|
122
|
+
# x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size]
|
|
123
|
+
hidden_size = x.shape[-1]
|
|
124
|
+
seqlen = x.shape[-2]
|
|
125
|
+
num_shards = math.ceil(seqlen / hidden_size)
|
|
126
|
+
|
|
127
|
+
# Ensure num_shards is at least 1
|
|
128
|
+
num_shards = max(1, num_shards)
|
|
129
|
+
|
|
130
|
+
return LigerTiledMLPFunction.apply(
|
|
131
|
+
fn,
|
|
132
|
+
mlp_module,
|
|
133
|
+
x,
|
|
134
|
+
num_shards,
|
|
135
|
+
compute_params,
|
|
136
|
+
)
|
liger_kernel/ops/utils.py
CHANGED
|
@@ -78,6 +78,8 @@ def get_amp_custom_fwd_bwd() -> Callable:
|
|
|
78
78
|
functools.partial(torch.amp.custom_fwd, device_type=device),
|
|
79
79
|
functools.partial(torch.amp.custom_bwd, device_type=device),
|
|
80
80
|
)
|
|
81
|
+
if hasattr(torch, "npu") and getattr(torch.npu, "amp", None) is not None:
|
|
82
|
+
return torch.npu.amp.custom_fwd, torch.npu.amp.custom_bwd
|
|
81
83
|
return torch.cuda.amp.custom_fwd, torch.cuda.amp.custom_bwd
|
|
82
84
|
|
|
83
85
|
|
|
@@ -125,3 +127,26 @@ def element_mul_kernel(
|
|
|
125
127
|
X_offsets = i + tl.arange(0, BLOCK_SIZE)
|
|
126
128
|
X_block = tl.load(X_ptr + X_offsets, mask=X_offsets < n_cols)
|
|
127
129
|
tl.store(X_ptr + X_offsets, X_block * grad_output, mask=X_offsets < n_cols)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def get_npu_core_count(default: int = 20) -> int:
|
|
133
|
+
"""Return NPU vector core count.
|
|
134
|
+
Fallback to `default` if Triton runtime or NPU device is unavailable.
|
|
135
|
+
"""
|
|
136
|
+
try:
|
|
137
|
+
utils = triton.runtime.driver.active.utils
|
|
138
|
+
props = utils.get_device_properties(0)
|
|
139
|
+
return int(props.get("num_vectorcore", default))
|
|
140
|
+
except Exception:
|
|
141
|
+
return default
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def set_large_grf_mode(kernel_args: dict):
|
|
145
|
+
"""Set large GRF mode for XPU devices."""
|
|
146
|
+
# On XPU triton installed along with pytorch-xpu will be called `pytorch-triton-xpu`,
|
|
147
|
+
# triton XPU installed from source will be called `triton`.
|
|
148
|
+
if compare_version("pytorch-triton-xpu", operator.ge, "3.6.0") or compare_version("triton", operator.ge, "3.6.0"):
|
|
149
|
+
kernel_args["grf_mode"] = "256"
|
|
150
|
+
else:
|
|
151
|
+
# API was changed in https://github.com/intel/intel-xpu-backend-for-triton/pull/5430
|
|
152
|
+
kernel_args["grf_mode"] = "large"
|
|
@@ -24,6 +24,8 @@ from liger_kernel.transformers.swiglu import LigerBlockSparseTop2MLP # noqa: F4
|
|
|
24
24
|
from liger_kernel.transformers.swiglu import LigerPhi3SwiGLUMLP # noqa: F401
|
|
25
25
|
from liger_kernel.transformers.swiglu import LigerQwen3MoeSwiGLUMLP # noqa: F401
|
|
26
26
|
from liger_kernel.transformers.swiglu import LigerSwiGLUMLP # noqa: F401
|
|
27
|
+
from liger_kernel.transformers.tiled_mlp import LigerTiledGEGLUMLP # noqa: F401
|
|
28
|
+
from liger_kernel.transformers.tiled_mlp import LigerTiledSwiGLUMLP # noqa: F401
|
|
27
29
|
from liger_kernel.transformers.tvd import LigerTVDLoss # noqa: F401
|
|
28
30
|
|
|
29
31
|
# Static-only imports for IDEs and type checkers
|
|
@@ -31,6 +33,7 @@ if TYPE_CHECKING:
|
|
|
31
33
|
from liger_kernel.transformers.auto_model import AutoLigerKernelForCausalLM # noqa: F401
|
|
32
34
|
from liger_kernel.transformers.monkey_patch import _apply_liger_kernel # noqa: F401
|
|
33
35
|
from liger_kernel.transformers.monkey_patch import _apply_liger_kernel_to_instance # noqa: F401
|
|
36
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_exaone4 # noqa: F401
|
|
34
37
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_falcon_h1 # noqa: F401
|
|
35
38
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma # noqa: F401
|
|
36
39
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gemma2 # noqa: F401
|
|
@@ -39,7 +42,10 @@ if TYPE_CHECKING:
|
|
|
39
42
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_glm4 # noqa: F401
|
|
40
43
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_glm4v # noqa: F401
|
|
41
44
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_glm4v_moe # noqa: F401
|
|
45
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_gpt_oss # noqa: F401
|
|
42
46
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_granite # noqa: F401
|
|
47
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_hunyuan_v1_dense # noqa: F401
|
|
48
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_hunyuan_v1_moe # noqa: F401
|
|
43
49
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_internvl # noqa: F401
|
|
44
50
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama # noqa: F401
|
|
45
51
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_llama4 # noqa: F401
|
|
@@ -48,6 +54,7 @@ if TYPE_CHECKING:
|
|
|
48
54
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mixtral # noqa: F401
|
|
49
55
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_mllama # noqa: F401
|
|
50
56
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_olmo2 # noqa: F401
|
|
57
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_olmo3 # noqa: F401
|
|
51
58
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_paligemma # noqa: F401
|
|
52
59
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_phi3 # noqa: F401
|
|
53
60
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen2 # noqa: F401
|
|
@@ -56,6 +63,8 @@ if TYPE_CHECKING:
|
|
|
56
63
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3 # noqa: F401
|
|
57
64
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3_moe # noqa: F401
|
|
58
65
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3_next # noqa: F401
|
|
66
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3_vl # noqa: F401
|
|
67
|
+
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_qwen3_vl_moe # noqa: F401
|
|
59
68
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_smollm3 # noqa: F401
|
|
60
69
|
from liger_kernel.transformers.monkey_patch import apply_liger_kernel_to_smolvlm # noqa: F401
|
|
61
70
|
|
|
@@ -103,6 +112,7 @@ def __getattr__(name: str):
|
|
|
103
112
|
"apply_liger_kernel_to_glm4",
|
|
104
113
|
"apply_liger_kernel_to_glm4v",
|
|
105
114
|
"apply_liger_kernel_to_glm4v_moe",
|
|
115
|
+
"apply_liger_kernel_to_gpt_oss",
|
|
106
116
|
"apply_liger_kernel_to_granite",
|
|
107
117
|
"apply_liger_kernel_to_internvl",
|
|
108
118
|
"apply_liger_kernel_to_llama",
|
|
@@ -112,6 +122,7 @@ def __getattr__(name: str):
|
|
|
112
122
|
"apply_liger_kernel_to_mixtral",
|
|
113
123
|
"apply_liger_kernel_to_mllama",
|
|
114
124
|
"apply_liger_kernel_to_olmo2",
|
|
125
|
+
"apply_liger_kernel_to_olmo3",
|
|
115
126
|
"apply_liger_kernel_to_paligemma",
|
|
116
127
|
"apply_liger_kernel_to_phi3",
|
|
117
128
|
"apply_liger_kernel_to_qwen2",
|
|
@@ -120,8 +131,13 @@ def __getattr__(name: str):
|
|
|
120
131
|
"apply_liger_kernel_to_qwen3",
|
|
121
132
|
"apply_liger_kernel_to_qwen3_moe",
|
|
122
133
|
"apply_liger_kernel_to_qwen3_next",
|
|
134
|
+
"apply_liger_kernel_to_qwen3_vl",
|
|
135
|
+
"apply_liger_kernel_to_qwen3_vl_moe",
|
|
123
136
|
"apply_liger_kernel_to_smollm3",
|
|
124
137
|
"apply_liger_kernel_to_smolvlm",
|
|
138
|
+
"apply_liger_kernel_to_hunyuan_v1_dense",
|
|
139
|
+
"apply_liger_kernel_to_hunyuan_v1_moe",
|
|
140
|
+
"apply_liger_kernel_to_exaone4",
|
|
125
141
|
}
|
|
126
142
|
|
|
127
143
|
if name in monkey_patch_symbols:
|
|
@@ -151,6 +167,8 @@ __all__ = [
|
|
|
151
167
|
"LigerPhi3SwiGLUMLP",
|
|
152
168
|
"LigerQwen3MoeSwiGLUMLP",
|
|
153
169
|
"LigerSwiGLUMLP",
|
|
170
|
+
"LigerTiledGEGLUMLP",
|
|
171
|
+
"LigerTiledSwiGLUMLP",
|
|
154
172
|
"LigerTVDLoss",
|
|
155
173
|
"LigerKLDIVLoss",
|
|
156
174
|
"LigerMultiTokenAttention",
|
|
@@ -173,6 +191,7 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
173
191
|
"apply_liger_kernel_to_glm4",
|
|
174
192
|
"apply_liger_kernel_to_glm4v",
|
|
175
193
|
"apply_liger_kernel_to_glm4v_moe",
|
|
194
|
+
"apply_liger_kernel_to_gpt_oss",
|
|
176
195
|
"apply_liger_kernel_to_granite",
|
|
177
196
|
"apply_liger_kernel_to_internvl",
|
|
178
197
|
"apply_liger_kernel_to_llama",
|
|
@@ -182,6 +201,7 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
182
201
|
"apply_liger_kernel_to_mixtral",
|
|
183
202
|
"apply_liger_kernel_to_mllama",
|
|
184
203
|
"apply_liger_kernel_to_olmo2",
|
|
204
|
+
"apply_liger_kernel_to_olmo3",
|
|
185
205
|
"apply_liger_kernel_to_paligemma",
|
|
186
206
|
"apply_liger_kernel_to_phi3",
|
|
187
207
|
"apply_liger_kernel_to_qwen2",
|
|
@@ -190,7 +210,12 @@ if _TRANSFORMERS_AVAILABLE:
|
|
|
190
210
|
"apply_liger_kernel_to_qwen3",
|
|
191
211
|
"apply_liger_kernel_to_qwen3_moe",
|
|
192
212
|
"apply_liger_kernel_to_qwen3_next",
|
|
213
|
+
"apply_liger_kernel_to_qwen3_vl",
|
|
214
|
+
"apply_liger_kernel_to_qwen3_vl_moe",
|
|
193
215
|
"apply_liger_kernel_to_smollm3",
|
|
194
216
|
"apply_liger_kernel_to_smolvlm",
|
|
217
|
+
"apply_liger_kernel_to_hunyuan_v1_dense",
|
|
218
|
+
"apply_liger_kernel_to_hunyuan_v1_moe",
|
|
219
|
+
"apply_liger_kernel_to_exaone4",
|
|
195
220
|
]
|
|
196
221
|
)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import inspect
|
|
2
|
+
import logging
|
|
2
3
|
|
|
3
4
|
from transformers import AutoConfig
|
|
4
5
|
from transformers import AutoModelForCausalLM
|
|
@@ -6,6 +7,8 @@ from transformers import AutoModelForCausalLM
|
|
|
6
7
|
from liger_kernel.transformers.monkey_patch import MODEL_TYPE_TO_APPLY_LIGER_FN
|
|
7
8
|
from liger_kernel.transformers.monkey_patch import _apply_liger_kernel
|
|
8
9
|
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
9
12
|
|
|
10
13
|
def _get_model_config(model_dir, **model_init_kwargs):
|
|
11
14
|
config = AutoConfig.from_pretrained(model_dir, **model_init_kwargs)
|
|
@@ -36,3 +39,21 @@ class AutoLigerKernelForCausalLM(AutoModelForCausalLM):
|
|
|
36
39
|
applicable_kwargs = {key: value for key, value in kwargs.items() if key not in apply_fn_signature.parameters}
|
|
37
40
|
|
|
38
41
|
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **applicable_kwargs)
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_config(cls, config, **kwargs):
|
|
45
|
+
model_type = getattr(config, "model_type", None)
|
|
46
|
+
if not model_type:
|
|
47
|
+
logger.info("Model type could not be determined from model config. No Liger kernels will be applied.")
|
|
48
|
+
return
|
|
49
|
+
model_type = config.model_type
|
|
50
|
+
|
|
51
|
+
_apply_liger_kernel(model_type, **kwargs)
|
|
52
|
+
|
|
53
|
+
# Filter out kwargs that were passed to the apply_liger_* function, which will cause
|
|
54
|
+
# model initialization errors otherwise
|
|
55
|
+
apply_fn = MODEL_TYPE_TO_APPLY_LIGER_FN[model_type]
|
|
56
|
+
apply_fn_signature = inspect.signature(apply_fn)
|
|
57
|
+
applicable_kwargs = {key: value for key, value in kwargs.items() if key not in apply_fn_signature.parameters}
|
|
58
|
+
|
|
59
|
+
return super().from_config(config, **applicable_kwargs)
|
|
@@ -2,7 +2,8 @@ from typing import Optional
|
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
4
|
|
|
5
|
-
from liger_kernel.ops
|
|
5
|
+
from liger_kernel.ops import LigerCrossEntropyFunction
|
|
6
|
+
from liger_kernel.transformers.functional import CrossEntropyOutput
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
class LigerCrossEntropyLoss(torch.nn.Module):
|
|
@@ -15,6 +16,7 @@ class LigerCrossEntropyLoss(torch.nn.Module):
|
|
|
15
16
|
reduction: str = "mean",
|
|
16
17
|
softcap: Optional[float] = None,
|
|
17
18
|
return_z_loss: bool = False,
|
|
19
|
+
return_token_accuracy: bool = False,
|
|
18
20
|
):
|
|
19
21
|
super().__init__()
|
|
20
22
|
assert (label_smoothing >= 0) and (label_smoothing <= 1), (
|
|
@@ -33,9 +35,10 @@ class LigerCrossEntropyLoss(torch.nn.Module):
|
|
|
33
35
|
self.reduction = reduction
|
|
34
36
|
self.softcap = softcap
|
|
35
37
|
self.return_z_loss = return_z_loss
|
|
38
|
+
self.return_token_accuracy = return_token_accuracy
|
|
36
39
|
|
|
37
40
|
def forward(self, _input: torch.Tensor, target: torch.Tensor):
|
|
38
|
-
loss, z_loss = LigerCrossEntropyFunction.apply(
|
|
41
|
+
loss, z_loss, token_accuracy = LigerCrossEntropyFunction.apply(
|
|
39
42
|
_input,
|
|
40
43
|
target,
|
|
41
44
|
self.weight,
|
|
@@ -45,7 +48,9 @@ class LigerCrossEntropyLoss(torch.nn.Module):
|
|
|
45
48
|
self.reduction,
|
|
46
49
|
self.softcap,
|
|
47
50
|
self.return_z_loss,
|
|
51
|
+
self.return_token_accuracy,
|
|
48
52
|
)
|
|
49
|
-
if not self.return_z_loss:
|
|
53
|
+
if not self.return_z_loss and not self.return_token_accuracy:
|
|
50
54
|
return loss
|
|
51
|
-
|
|
55
|
+
|
|
56
|
+
return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
|
liger_kernel/transformers/dyt.py
CHANGED
|
@@ -1,25 +1,35 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
1
2
|
from typing import Optional
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
from liger_kernel.ops
|
|
6
|
-
from liger_kernel.ops
|
|
7
|
-
from liger_kernel.ops
|
|
8
|
-
from liger_kernel.ops
|
|
9
|
-
from liger_kernel.ops
|
|
10
|
-
from liger_kernel.ops
|
|
11
|
-
from liger_kernel.ops
|
|
12
|
-
from liger_kernel.ops
|
|
13
|
-
from liger_kernel.ops
|
|
14
|
-
from liger_kernel.ops
|
|
15
|
-
from liger_kernel.ops
|
|
16
|
-
from liger_kernel.ops
|
|
17
|
-
from liger_kernel.ops
|
|
18
|
-
from liger_kernel.ops
|
|
19
|
-
from liger_kernel.ops
|
|
20
|
-
from liger_kernel.ops
|
|
21
|
-
from liger_kernel.ops
|
|
22
|
-
from liger_kernel.ops
|
|
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
|
|
23
33
|
|
|
24
34
|
|
|
25
35
|
# conform to the function signature in https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html
|
|
@@ -36,8 +46,9 @@ def liger_cross_entropy(
|
|
|
36
46
|
lse_square_scale: float = 0.0,
|
|
37
47
|
softcap: Optional[float] = None,
|
|
38
48
|
return_z_loss: bool = False,
|
|
49
|
+
return_token_accuracy: bool = False,
|
|
39
50
|
):
|
|
40
|
-
loss, z_loss = LigerCrossEntropyFunction.apply(
|
|
51
|
+
loss, z_loss, token_accuracy = LigerCrossEntropyFunction.apply(
|
|
41
52
|
input,
|
|
42
53
|
target,
|
|
43
54
|
weight,
|
|
@@ -47,10 +58,13 @@ def liger_cross_entropy(
|
|
|
47
58
|
reduction,
|
|
48
59
|
softcap,
|
|
49
60
|
return_z_loss,
|
|
61
|
+
return_token_accuracy,
|
|
50
62
|
)
|
|
51
|
-
|
|
63
|
+
|
|
64
|
+
if not return_z_loss and not return_token_accuracy:
|
|
52
65
|
return loss
|
|
53
|
-
|
|
66
|
+
|
|
67
|
+
return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
|
|
54
68
|
|
|
55
69
|
|
|
56
70
|
def liger_fused_linear_cross_entropy(
|
|
@@ -67,8 +81,9 @@ def liger_fused_linear_cross_entropy(
|
|
|
67
81
|
return_z_loss: bool = False,
|
|
68
82
|
accum_dtype=None,
|
|
69
83
|
use_token_scaling: bool = False,
|
|
84
|
+
return_token_accuracy: bool = False,
|
|
70
85
|
):
|
|
71
|
-
loss, z_loss = LigerFusedLinearCrossEntropyFunction.apply(
|
|
86
|
+
loss, z_loss, token_accuracy = LigerFusedLinearCrossEntropyFunction.apply(
|
|
72
87
|
input,
|
|
73
88
|
weight,
|
|
74
89
|
target,
|
|
@@ -82,10 +97,13 @@ def liger_fused_linear_cross_entropy(
|
|
|
82
97
|
return_z_loss,
|
|
83
98
|
accum_dtype,
|
|
84
99
|
use_token_scaling,
|
|
100
|
+
return_token_accuracy,
|
|
85
101
|
)
|
|
86
|
-
|
|
102
|
+
|
|
103
|
+
if not return_z_loss and not return_token_accuracy:
|
|
87
104
|
return loss
|
|
88
|
-
|
|
105
|
+
|
|
106
|
+
return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
|
|
89
107
|
|
|
90
108
|
|
|
91
109
|
def liger_fused_linear_jsd(
|
|
@@ -2,7 +2,8 @@ from typing import Optional
|
|
|
2
2
|
|
|
3
3
|
import torch
|
|
4
4
|
|
|
5
|
-
from liger_kernel.ops
|
|
5
|
+
from liger_kernel.ops import LigerFusedLinearCrossEntropyFunction
|
|
6
|
+
from liger_kernel.transformers.functional import CrossEntropyOutput
|
|
6
7
|
|
|
7
8
|
|
|
8
9
|
class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
@@ -17,6 +18,7 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
17
18
|
return_z_loss: bool = False,
|
|
18
19
|
accum_dtype: Optional[torch.dtype] = None,
|
|
19
20
|
use_token_scaling: bool = False,
|
|
21
|
+
return_token_accuracy: bool = False,
|
|
20
22
|
):
|
|
21
23
|
super().__init__()
|
|
22
24
|
assert (label_smoothing >= 0) and (label_smoothing <= 1), (
|
|
@@ -37,9 +39,10 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
37
39
|
self.return_z_loss = return_z_loss
|
|
38
40
|
self.accum_dtype = accum_dtype
|
|
39
41
|
self.use_token_scaling = use_token_scaling
|
|
42
|
+
self.return_token_accuracy = return_token_accuracy
|
|
40
43
|
|
|
41
44
|
def forward(self, lin_weight, _input, target, bias=None):
|
|
42
|
-
loss, z_loss = LigerFusedLinearCrossEntropyFunction.apply(
|
|
45
|
+
loss, z_loss, token_accuracy = LigerFusedLinearCrossEntropyFunction.apply(
|
|
43
46
|
_input,
|
|
44
47
|
lin_weight,
|
|
45
48
|
target,
|
|
@@ -53,7 +56,9 @@ class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
|
53
56
|
self.return_z_loss,
|
|
54
57
|
self.accum_dtype,
|
|
55
58
|
self.use_token_scaling,
|
|
59
|
+
self.return_token_accuracy,
|
|
56
60
|
)
|
|
57
|
-
if not self.return_z_loss:
|
|
61
|
+
if not self.return_z_loss and not self.return_token_accuracy:
|
|
58
62
|
return loss
|
|
59
|
-
|
|
63
|
+
|
|
64
|
+
return CrossEntropyOutput(loss=loss, z_loss=z_loss, token_accuracy=token_accuracy)
|
|
@@ -5,7 +5,7 @@ from typing import Optional
|
|
|
5
5
|
import torch
|
|
6
6
|
import torch.nn as nn
|
|
7
7
|
|
|
8
|
-
from liger_kernel.ops
|
|
8
|
+
from liger_kernel.ops import LigerFusedNeighborhoodAttentionFunction
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class LigerFusedNeighborhoodAttention(nn.Module):
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
import torch
|
|
2
|
+
|
|
3
|
+
from liger_kernel.chunked_loss.fused_linear_ppo import LigerFusedLinearPPOBase
|
|
4
|
+
from liger_kernel.ops import GrpoLossFunction
|
|
2
5
|
|
|
3
6
|
|
|
4
7
|
def triton_grpo_loss(
|
|
@@ -13,12 +16,20 @@ def triton_grpo_loss(
|
|
|
13
16
|
eps_low=0.2,
|
|
14
17
|
eps_high=0.4,
|
|
15
18
|
inplace=True,
|
|
19
|
+
loss_type="dapo",
|
|
20
|
+
max_completion_length=None,
|
|
21
|
+
importance_sampling_level="token",
|
|
22
|
+
reduce=False,
|
|
16
23
|
):
|
|
17
24
|
assert logits is not None and completion_ids is not None and advantages is not None, (
|
|
18
25
|
"must provide logits、completion_ids and advantages"
|
|
19
26
|
)
|
|
27
|
+
if importance_sampling_level != "token":
|
|
28
|
+
raise ValueError(
|
|
29
|
+
f"Triton GRPO loss only supports token-level importance sampling. Got {importance_sampling_level}."
|
|
30
|
+
)
|
|
20
31
|
|
|
21
|
-
|
|
32
|
+
per_token_loss, per_token_kl, is_clipped = GrpoLossFunction.apply(
|
|
22
33
|
logits,
|
|
23
34
|
old_logp,
|
|
24
35
|
ref_logp,
|
|
@@ -31,6 +42,50 @@ def triton_grpo_loss(
|
|
|
31
42
|
eps_high,
|
|
32
43
|
inplace,
|
|
33
44
|
)
|
|
45
|
+
if not reduce:
|
|
46
|
+
return per_token_loss, per_token_kl, is_clipped
|
|
47
|
+
|
|
48
|
+
loss = _reduce_grpo_loss(
|
|
49
|
+
per_token_loss,
|
|
50
|
+
completion_mask,
|
|
51
|
+
loss_type=loss_type,
|
|
52
|
+
max_completion_length=max_completion_length,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
metrics = []
|
|
56
|
+
if beta != 0.0 and per_token_kl is not None:
|
|
57
|
+
metrics.append(_masked_mean(per_token_kl, completion_mask))
|
|
58
|
+
metrics.append(_masked_mean(is_clipped.float(), completion_mask))
|
|
59
|
+
return loss, metrics
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _reduce_grpo_loss(per_token_loss, completion_mask, loss_type, max_completion_length):
|
|
63
|
+
mask = completion_mask
|
|
64
|
+
if mask is None:
|
|
65
|
+
mask = torch.ones_like(per_token_loss, dtype=per_token_loss.dtype, device=per_token_loss.device)
|
|
66
|
+
mask = mask.to(per_token_loss.dtype)
|
|
67
|
+
|
|
68
|
+
if loss_type == "grpo":
|
|
69
|
+
per_seq = (per_token_loss * mask).sum(-1) / mask.sum(-1).clamp(min=1.0)
|
|
70
|
+
return per_seq.mean()
|
|
71
|
+
if loss_type == "bnpo":
|
|
72
|
+
return (per_token_loss * mask).sum() / mask.sum().clamp(min=1.0)
|
|
73
|
+
if loss_type == "dr_grpo":
|
|
74
|
+
if max_completion_length is None:
|
|
75
|
+
raise ValueError("max_completion_length must be provided when using loss_type='dr_grpo'")
|
|
76
|
+
batch = per_token_loss.shape[0]
|
|
77
|
+
return (per_token_loss * mask).sum() / (batch * max_completion_length)
|
|
78
|
+
if loss_type == "dapo":
|
|
79
|
+
normalizer = LigerFusedLinearPPOBase._compute_dapo_normalizer(mask)
|
|
80
|
+
return (per_token_loss * mask).sum() / normalizer
|
|
81
|
+
raise ValueError(f"Unsupported loss_type '{loss_type}' for Triton GRPO loss.")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _masked_mean(values, mask):
|
|
85
|
+
if mask is None:
|
|
86
|
+
mask = torch.ones_like(values, dtype=values.dtype, device=values.device)
|
|
87
|
+
mask = mask.to(values.dtype)
|
|
88
|
+
return (values * mask).sum() / mask.sum().clamp(min=1.0)
|
|
34
89
|
|
|
35
90
|
|
|
36
91
|
# This is a demo how to use grpo_loss in GRPOTrainer. The Trl version must be 0.16
|