liger-kernel 0.3.1__py3-none-any.whl → 0.4.1__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/env_report.py +2 -0
- liger_kernel/ops/cross_entropy.py +144 -65
- liger_kernel/ops/experimental/mm_int8int2.py +355 -0
- liger_kernel/ops/fused_linear_cross_entropy.py +31 -11
- liger_kernel/ops/fused_linear_jsd.py +245 -0
- liger_kernel/ops/geglu.py +2 -2
- liger_kernel/ops/group_norm.py +322 -0
- liger_kernel/ops/jsd.py +176 -0
- liger_kernel/ops/kl_div.py +2 -2
- liger_kernel/ops/rms_norm.py +92 -46
- liger_kernel/ops/swiglu.py +2 -2
- liger_kernel/ops/utils.py +62 -1
- liger_kernel/transformers/__init__.py +3 -0
- liger_kernel/transformers/cross_entropy.py +44 -12
- liger_kernel/transformers/functional.py +38 -1
- liger_kernel/transformers/fused_linear_cross_entropy.py +31 -4
- liger_kernel/transformers/fused_linear_jsd.py +98 -0
- liger_kernel/transformers/group_norm.py +56 -0
- liger_kernel/transformers/jsd.py +75 -0
- liger_kernel/transformers/model/gemma.py +124 -1
- liger_kernel/transformers/model/gemma2.py +277 -0
- liger_kernel/transformers/model/llama.py +135 -4
- liger_kernel/transformers/model/mistral.py +3 -0
- liger_kernel/transformers/model/mixtral.py +153 -2
- liger_kernel/transformers/model/mllama.py +274 -0
- liger_kernel/transformers/model/phi3.py +140 -2
- liger_kernel/transformers/model/qwen2.py +123 -2
- liger_kernel/transformers/model/qwen2_vl.py +8 -1
- liger_kernel/transformers/monkey_patch.py +258 -68
- liger_kernel/transformers/rms_norm.py +11 -3
- {liger_kernel-0.3.1.dist-info → liger_kernel-0.4.1.dist-info}/METADATA +63 -29
- liger_kernel-0.4.1.dist-info/NOTICE +58 -0
- liger_kernel-0.4.1.dist-info/RECORD +51 -0
- {liger_kernel-0.3.1.dist-info → liger_kernel-0.4.1.dist-info}/WHEEL +1 -1
- liger_kernel-0.3.1.dist-info/NOTICE +0 -4
- liger_kernel-0.3.1.dist-info/RECORD +0 -42
- {liger_kernel-0.3.1.dist-info → liger_kernel-0.4.1.dist-info}/LICENSE +0 -0
- {liger_kernel-0.3.1.dist-info → liger_kernel-0.4.1.dist-info}/top_level.txt +0 -0
|
@@ -1,13 +1,38 @@
|
|
|
1
|
-
from
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import torch
|
|
2
4
|
|
|
3
5
|
from liger_kernel.ops.fused_linear_cross_entropy import (
|
|
4
6
|
LigerFusedLinearCrossEntropyFunction,
|
|
5
7
|
)
|
|
6
8
|
|
|
7
9
|
|
|
8
|
-
class LigerFusedLinearCrossEntropyLoss(
|
|
9
|
-
def __init__(
|
|
10
|
-
|
|
10
|
+
class LigerFusedLinearCrossEntropyLoss(torch.nn.Module):
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
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
|
+
):
|
|
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}"
|
|
23
|
+
assert reduction in {
|
|
24
|
+
"mean",
|
|
25
|
+
"sum",
|
|
26
|
+
"none",
|
|
27
|
+
}, f"reduction must be one of 'mean', 'sum', or 'none'. Got: {reduction}"
|
|
28
|
+
assert (
|
|
29
|
+
softcap is None or softcap > 0
|
|
30
|
+
), f"softcap must greater than 0.0 or None. Got: {softcap}"
|
|
31
|
+
self.ignore_index = ignore_index
|
|
32
|
+
self.lse_square_scale = lse_square_scale
|
|
33
|
+
self.label_smoothing = label_smoothing
|
|
34
|
+
self.reduction = reduction
|
|
35
|
+
self.softcap = softcap
|
|
11
36
|
|
|
12
37
|
def forward(self, lin_weight, _input, target, bias=None):
|
|
13
38
|
return LigerFusedLinearCrossEntropyFunction.apply(
|
|
@@ -16,6 +41,8 @@ class LigerFusedLinearCrossEntropyLoss(CrossEntropyLoss):
|
|
|
16
41
|
target,
|
|
17
42
|
bias,
|
|
18
43
|
self.ignore_index,
|
|
44
|
+
self.lse_square_scale,
|
|
19
45
|
self.label_smoothing,
|
|
20
46
|
self.reduction,
|
|
47
|
+
self.softcap,
|
|
21
48
|
)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
from liger_kernel.ops.fused_linear_jsd 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 open interval (0, 1). 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 (
|
|
74
|
+
jsd_beta > 0 and jsd_beta < 1
|
|
75
|
+
), f"beta must be greater than 0 and less than 1. Got: {jsd_beta}"
|
|
76
|
+
assert temperature != 0, "temperature cannot be 0."
|
|
77
|
+
self.jsd_beta = jsd_beta
|
|
78
|
+
self.temperature = temperature
|
|
79
|
+
self.ignore_index = ignore_index
|
|
80
|
+
|
|
81
|
+
def forward(
|
|
82
|
+
self,
|
|
83
|
+
student_input: torch.Tensor,
|
|
84
|
+
student_weight: torch.Tensor,
|
|
85
|
+
teacher_input: torch.Tensor,
|
|
86
|
+
teacher_weight: torch.Tensor,
|
|
87
|
+
shift_labels: Optional[torch.LongTensor],
|
|
88
|
+
):
|
|
89
|
+
return LigerFusedLinearJSDFunction.apply(
|
|
90
|
+
student_input,
|
|
91
|
+
student_weight,
|
|
92
|
+
teacher_input,
|
|
93
|
+
teacher_weight,
|
|
94
|
+
shift_labels,
|
|
95
|
+
self.jsd_beta,
|
|
96
|
+
self.ignore_index,
|
|
97
|
+
self.temperature,
|
|
98
|
+
)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
|
|
4
|
+
from liger_kernel.ops.group_norm import LigerGroupNormFunction
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LigerGroupNorm(nn.Module):
|
|
8
|
+
def __init__(self, num_channels, num_groups, eps=1e-6, bias=False, init_fn="ones"):
|
|
9
|
+
"""
|
|
10
|
+
A Group Normalization layer.
|
|
11
|
+
Args:
|
|
12
|
+
num_channels (int): Number of channels in the input tensor.
|
|
13
|
+
num_groups (int): Number of groups to divide the channels into.
|
|
14
|
+
eps (float, optional): A value added to the denominator for numerical stability. Default: 1e-6.
|
|
15
|
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``False``.
|
|
16
|
+
init_fn (str, optional): Initialization function for the learnable parameters. Default: "ones".
|
|
17
|
+
"""
|
|
18
|
+
super().__init__()
|
|
19
|
+
assert init_fn in [
|
|
20
|
+
"ones",
|
|
21
|
+
"zeros",
|
|
22
|
+
], f"init_fn must be either 'ones' or 'zeros', got {init_fn}"
|
|
23
|
+
|
|
24
|
+
assert (
|
|
25
|
+
num_channels % num_groups == 0
|
|
26
|
+
), f"Number of channels {num_channels} must be divisible by num_groups {num_groups}"
|
|
27
|
+
self.num_channels = num_channels
|
|
28
|
+
self.num_groups = num_groups
|
|
29
|
+
self.eps = eps
|
|
30
|
+
self.weight = nn.Parameter(
|
|
31
|
+
torch.ones(num_channels) if init_fn == "ones" else torch.zeros(num_channels)
|
|
32
|
+
)
|
|
33
|
+
self.bias = nn.Parameter(
|
|
34
|
+
torch.randn(num_channels) if bias else torch.zeros(num_channels)
|
|
35
|
+
)
|
|
36
|
+
self.variance_epsilon = eps
|
|
37
|
+
|
|
38
|
+
def forward(self, hidden_states):
|
|
39
|
+
# hidden_states: (batch_size, num_channels, *)
|
|
40
|
+
assert (
|
|
41
|
+
hidden_states.dim() >= 3
|
|
42
|
+
), f"Input must have atleast 3 dimensions, got {hidden_states.dim()}"
|
|
43
|
+
assert (
|
|
44
|
+
hidden_states.size(1) == self.num_channels
|
|
45
|
+
), f"Input tensor must have {self.num_channels} channels, got {hidden_states.size(1)}"
|
|
46
|
+
return LigerGroupNormFunction.apply(
|
|
47
|
+
hidden_states,
|
|
48
|
+
self.weight,
|
|
49
|
+
self.bias,
|
|
50
|
+
self.num_channels,
|
|
51
|
+
self.num_groups,
|
|
52
|
+
self.variance_epsilon,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def extra_repr(self):
|
|
56
|
+
return f"{self.hidden_size}, num_channels={self.num_channels}, num_groups={self.num_groups}, eps={self.eps}"
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
from liger_kernel.ops.jsd import LigerJSDFunction
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LigerJSD(torch.nn.Module):
|
|
9
|
+
r"""The generalized Jensen-Shannon Divergence.
|
|
10
|
+
.. math::
|
|
11
|
+
JSD(\beta)(P || Q)
|
|
12
|
+
= \beta * KLDiv(P || (\beta * P + (1 - \beta) * Q)) + (1 - \beta) * KLDiv(Q || (\beta * P + (1 - \beta) * Q))
|
|
13
|
+
.. note::
|
|
14
|
+
As all the other losses in PyTorch, this function expects the first argument,
|
|
15
|
+
:attr:`log_q`, to be the predictions, the output of the student model in log-space,
|
|
16
|
+
and the second, :attr:`log_p`, to be the observations, the output of the teacher model in log-space.
|
|
17
|
+
This differs from the standard mathematical notation :math:`JSD(P || Q)` where
|
|
18
|
+
:math:`P` denotes the teacher model and :math:`Q` denotes the student model.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
beta (float): coefficient beta of generalized JSD in the open interval (0, 1). Default: `0.5`
|
|
22
|
+
ignore_index (int): The index to ignore in the target. Default: `-100`
|
|
23
|
+
|
|
24
|
+
Shape:
|
|
25
|
+
- Input: :math:`(BT, V)`, where B is batch size, T is sequence length, V is vocab size.
|
|
26
|
+
- Target: :math:`(BT, V)`, same shape as the input.
|
|
27
|
+
- shift_labels (Optional): :math:`(BT,)`
|
|
28
|
+
- Output: a scalar.
|
|
29
|
+
|
|
30
|
+
Examples:
|
|
31
|
+
```python
|
|
32
|
+
>>> (B, T, V) = (2, 2, 5)
|
|
33
|
+
>>> jsd = LigerJSD(beta=0.1)
|
|
34
|
+
>>> # input should be a distribution in the log space
|
|
35
|
+
>>> input = torch.randn(B * T, V, requires_grad=True).log_softmax(dim=-1)
|
|
36
|
+
>>> target = torch.randn(B * T, V).log_softmax(dim=-1)
|
|
37
|
+
>>> output = jsd(input, target)
|
|
38
|
+
>>>
|
|
39
|
+
>>> # Example with labels for supervised fine-tuning (SFT) context
|
|
40
|
+
>>> # Assume logits and corresponding labels are given
|
|
41
|
+
>>> student_logits = torch.randn(B * T, V, requires_grad=True).log_softmax(dim=-1)
|
|
42
|
+
>>> teacher_logits = torch.randn(B * T, V).log_softmax(dim=-1)
|
|
43
|
+
>>> labels = torch.randint(0, V, (B * T,), torch.long)
|
|
44
|
+
>>> # Shift so that tokens < n predict n
|
|
45
|
+
>>> shift_student_logits = student_logits[..., :-1, :].contiguous()
|
|
46
|
+
>>> shift_teacher_logits = teacher_logits[..., :-1, :].contiguous()
|
|
47
|
+
>>> shift_labels = labels[..., 1:].contiguous()
|
|
48
|
+
>>> # Flatten tokens
|
|
49
|
+
>>> shift_student_logits = shift_student_logits.view(-1, V)
|
|
50
|
+
>>> shift_teacher_logits = shift_teacher_logits.view(-1, V)
|
|
51
|
+
>>> shift_labels = shift_labels.view(-1)
|
|
52
|
+
>>> # Calculate loss
|
|
53
|
+
>>> loss_fct = LigerJSD(beta=0.1)
|
|
54
|
+
>>> loss = loss_fct(shift_studetn_logits, shift_teacher_logits, shift_labels)
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, beta: float = 0.5, ignore_index: int = -100):
|
|
60
|
+
super().__init__()
|
|
61
|
+
assert (
|
|
62
|
+
beta > 0 and beta < 1
|
|
63
|
+
), f"beta must be greater than 0 and less than 1. Got: {beta}"
|
|
64
|
+
self.beta = beta
|
|
65
|
+
self.ignore_index = ignore_index
|
|
66
|
+
|
|
67
|
+
def forward(
|
|
68
|
+
self,
|
|
69
|
+
log_q: torch.Tensor,
|
|
70
|
+
log_p: torch.Tensor,
|
|
71
|
+
shift_labels: Optional[torch.LongTensor] = None,
|
|
72
|
+
):
|
|
73
|
+
return LigerJSDFunction.apply(
|
|
74
|
+
log_q, log_p, shift_labels, self.beta, self.ignore_index
|
|
75
|
+
)
|
|
@@ -22,7 +22,7 @@ from liger_kernel.transformers.fused_linear_cross_entropy import (
|
|
|
22
22
|
@replace_return_docstrings(
|
|
23
23
|
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
|
24
24
|
)
|
|
25
|
-
def
|
|
25
|
+
def lce_forward_deprecated(
|
|
26
26
|
self,
|
|
27
27
|
input_ids: torch.LongTensor = None,
|
|
28
28
|
attention_mask: Optional[torch.Tensor] = None,
|
|
@@ -136,3 +136,126 @@ def lce_forward(
|
|
|
136
136
|
hidden_states=outputs.hidden_states,
|
|
137
137
|
attentions=outputs.attentions,
|
|
138
138
|
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
|
|
142
|
+
@replace_return_docstrings(
|
|
143
|
+
output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
|
|
144
|
+
)
|
|
145
|
+
def lce_forward(
|
|
146
|
+
self,
|
|
147
|
+
input_ids: torch.LongTensor = None,
|
|
148
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
149
|
+
position_ids: Optional[torch.LongTensor] = None,
|
|
150
|
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
|
151
|
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
|
152
|
+
labels: Optional[torch.LongTensor] = None,
|
|
153
|
+
use_cache: Optional[bool] = None,
|
|
154
|
+
output_attentions: Optional[bool] = None,
|
|
155
|
+
output_hidden_states: Optional[bool] = None,
|
|
156
|
+
return_dict: Optional[bool] = None,
|
|
157
|
+
cache_position: Optional[torch.LongTensor] = None,
|
|
158
|
+
num_logits_to_keep: int = 0,
|
|
159
|
+
**loss_kwargs,
|
|
160
|
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
|
161
|
+
r"""
|
|
162
|
+
Args:
|
|
163
|
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
|
164
|
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
|
165
|
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
|
166
|
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
|
167
|
+
|
|
168
|
+
num_logits_to_keep (`int`, *optional*):
|
|
169
|
+
Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
|
|
170
|
+
`input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
|
|
171
|
+
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
|
|
175
|
+
Example:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
>>> from transformers import AutoTokenizer, GemmaForCausalLM
|
|
179
|
+
|
|
180
|
+
>>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
|
|
181
|
+
>>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
|
|
182
|
+
|
|
183
|
+
>>> prompt = "What is your favorite condiment?"
|
|
184
|
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
|
185
|
+
|
|
186
|
+
>>> # Generate
|
|
187
|
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
|
188
|
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
189
|
+
"What is your favorite condiment?"
|
|
190
|
+
```"""
|
|
191
|
+
output_attentions = (
|
|
192
|
+
output_attentions
|
|
193
|
+
if output_attentions is not None
|
|
194
|
+
else self.config.output_attentions
|
|
195
|
+
)
|
|
196
|
+
output_hidden_states = (
|
|
197
|
+
output_hidden_states
|
|
198
|
+
if output_hidden_states is not None
|
|
199
|
+
else self.config.output_hidden_states
|
|
200
|
+
)
|
|
201
|
+
return_dict = (
|
|
202
|
+
return_dict if return_dict is not None else self.config.use_return_dict
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
|
206
|
+
outputs = self.model(
|
|
207
|
+
input_ids=input_ids,
|
|
208
|
+
attention_mask=attention_mask,
|
|
209
|
+
position_ids=position_ids,
|
|
210
|
+
past_key_values=past_key_values,
|
|
211
|
+
inputs_embeds=inputs_embeds,
|
|
212
|
+
use_cache=use_cache,
|
|
213
|
+
output_attentions=output_attentions,
|
|
214
|
+
output_hidden_states=output_hidden_states,
|
|
215
|
+
return_dict=return_dict,
|
|
216
|
+
cache_position=cache_position,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
hidden_states = outputs[0]
|
|
220
|
+
|
|
221
|
+
logits = None
|
|
222
|
+
loss = None
|
|
223
|
+
# if in training mode, don't materialize logits
|
|
224
|
+
if self.training and (labels is not None):
|
|
225
|
+
# We do the same thing as ForCausalLMLoss but using Liger FLCE
|
|
226
|
+
|
|
227
|
+
shift_hidden_states = hidden_states[..., :-1, :].contiguous()
|
|
228
|
+
shift_labels = labels[..., 1:].contiguous()
|
|
229
|
+
|
|
230
|
+
# flatten tokens
|
|
231
|
+
shift_hidden_states = shift_hidden_states.view(-1, self.config.hidden_size)
|
|
232
|
+
shift_labels = shift_labels.view(-1)
|
|
233
|
+
|
|
234
|
+
reduction = "sum" if "num_items_in_batch" in loss_kwargs else "mean"
|
|
235
|
+
lce = LigerFusedLinearCrossEntropyLoss(reduction=reduction)
|
|
236
|
+
|
|
237
|
+
loss = lce(self.lm_head.weight, shift_hidden_states, shift_labels)
|
|
238
|
+
if reduction == "sum":
|
|
239
|
+
loss /= loss_kwargs["num_items_in_batch"]
|
|
240
|
+
|
|
241
|
+
else: # if in inference mode materialize logits
|
|
242
|
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
|
243
|
+
if labels is not None:
|
|
244
|
+
loss = self.loss_function(
|
|
245
|
+
logits=logits,
|
|
246
|
+
labels=labels,
|
|
247
|
+
vocab_size=self.config.vocab_size,
|
|
248
|
+
**loss_kwargs,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
if not return_dict:
|
|
252
|
+
output = (logits,) + outputs[1:]
|
|
253
|
+
return (loss,) + output if loss is not None else output
|
|
254
|
+
|
|
255
|
+
return CausalLMOutputWithPast(
|
|
256
|
+
loss=loss,
|
|
257
|
+
logits=logits,
|
|
258
|
+
past_key_values=outputs.past_key_values,
|
|
259
|
+
hidden_states=outputs.hidden_states,
|
|
260
|
+
attentions=outputs.attentions,
|
|
261
|
+
)
|