liger-kernel-nightly 0.4.1.dev20241113011623__py3-none-any.whl → 0.4.1.dev20241114041219__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.

Potentially problematic release.


This version of liger-kernel-nightly might be problematic. Click here for more details.

File without changes
@@ -0,0 +1,107 @@
1
+ import torch
2
+
3
+
4
+ class LigerFusedLinearPreferenceBase(torch.autograd.Function):
5
+ @staticmethod
6
+ def forward(
7
+ ctx,
8
+ _input,
9
+ weight,
10
+ target,
11
+ bias=None,
12
+ loss_fn=None,
13
+ chunk_size=1,
14
+ compiled=True,
15
+ ):
16
+ """
17
+ Base class for fused linear layer with preference loss.
18
+ Expects _input to be stacked with chosen and rejected inputs on the batch dimension.
19
+
20
+ Args:
21
+ _input (torch.Tensor): Input tensor. Shape: (batch_size, seq_len, hidden_size).
22
+ weight (torch.Tensor): Weight tensor. Shape: (vocab_size, hidden_size).
23
+ target (torch.Tensor): Target tensor. Shape: (batch_size, seq_len).
24
+ bias (torch.Tensor, optional): Bias tensor. Shape: (vocab_size,).
25
+ loss_fn (callable): Loss function to compute the loss on a chunk of input/target.
26
+ chunk_size (int): Size of a chunk (# of batches of stacked chosen and rejected inputs).
27
+ compiled (bool): Whether to use torch compile for chunk accumulation.
28
+ """
29
+ # TODO: Tune CHUNK_SIZE to fully utilize the GPU
30
+ CHUNK_SIZE = chunk_size
31
+
32
+ grad_weight = torch.zeros_like(weight)
33
+ grad_chosen_inputs = []
34
+ grad_rejected_inputs = []
35
+ grad_bias = torch.zeros_like(bias) if bias is not None else None
36
+ loss_acc = torch.zeros((), device=_input.device)
37
+
38
+ chunks = max(1, _input.shape[0] // (2 * CHUNK_SIZE))
39
+
40
+ def accumulate_chunk(input_chunk, target_chunk):
41
+ if bias is not None:
42
+ (chunk_grad_input, chunk_grad_weight, chunk_grad_bias), (
43
+ chunk_loss,
44
+ (chunk_or_loss, chunk_chosen_logps, chunk_rejected_logps),
45
+ ) = torch.func.grad_and_value(loss_fn, argnums=(0, 1, 3), has_aux=True)(
46
+ input_chunk, weight, target_chunk, bias
47
+ )
48
+ grad_bias.add_(chunk_grad_bias)
49
+ else:
50
+ (chunk_grad_input, chunk_grad_weight), (
51
+ chunk_loss,
52
+ (chunk_or_loss, chunk_chosen_logps, chunk_rejected_logps),
53
+ ) = torch.func.grad_and_value(loss_fn, argnums=(0, 1), has_aux=True)(
54
+ input_chunk, weight, target_chunk
55
+ )
56
+ grad_weight.add_(chunk_grad_weight)
57
+ loss_acc.add_(chunk_loss)
58
+ return chunk_grad_input
59
+
60
+ len_chosen = target.shape[0] // 2
61
+ _chosen_input_chunks = torch.chunk(_input[:len_chosen], chunks=chunks, dim=0)
62
+ _chosen_target_chunks = torch.chunk(target[:len_chosen], chunks=chunks, dim=0)
63
+ _rejected_input_chunks = torch.chunk(_input[len_chosen:], chunks=chunks, dim=0)
64
+ _rejected_target_chunks = torch.chunk(target[len_chosen:], chunks=chunks, dim=0)
65
+
66
+ for (
67
+ chosen_input_chunk,
68
+ rejected_input_chunk,
69
+ chosen_target_chunk,
70
+ rejected_target_chunk,
71
+ ) in zip(
72
+ _chosen_input_chunks,
73
+ _rejected_input_chunks,
74
+ _chosen_target_chunks,
75
+ _rejected_target_chunks,
76
+ ):
77
+ input_chunk = torch.cat([chosen_input_chunk, rejected_input_chunk], dim=0)
78
+ target_chunk = torch.cat(
79
+ [chosen_target_chunk, rejected_target_chunk], dim=0
80
+ )
81
+
82
+ if compiled:
83
+ accumulate_chunk = torch.compile(accumulate_chunk)
84
+ grad_input = accumulate_chunk(input_chunk, target_chunk)
85
+
86
+ grad_chosen_inputs.append(grad_input[: chosen_target_chunk.shape[0]])
87
+ grad_rejected_inputs.append(grad_input[chosen_target_chunk.shape[0] :])
88
+
89
+ # combine grad_chosen_inputs and grad_rejected_inputs
90
+ grad_inputs = grad_chosen_inputs + grad_rejected_inputs
91
+
92
+ ctx.save_for_backward(
93
+ torch.cat(grad_inputs, dim=0),
94
+ grad_weight,
95
+ grad_bias,
96
+ )
97
+ return loss_acc
98
+
99
+ @staticmethod
100
+ def backward(ctx, grad_output):
101
+ grad_input, grad_weight, grad_bias = ctx.saved_tensors
102
+ if torch.ne(grad_output, torch.tensor(1.0, device=grad_output.device)):
103
+ grad_input = grad_input * grad_output
104
+ grad_weight = grad_weight * grad_output
105
+ grad_bias = grad_bias * grad_output if grad_bias is not None else None
106
+
107
+ return grad_input, grad_weight, None, grad_bias, None, None, None
@@ -0,0 +1,117 @@
1
+ from functools import partial
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ from liger_kernel.chunked_loss.fused_linear_preference import (
7
+ LigerFusedLinearPreferenceBase,
8
+ )
9
+
10
+
11
+ def odds_ratio_loss(chosen_logps, rejected_logps, beta=0.1):
12
+ """
13
+ Compute odds-ratio loss.
14
+ Args:
15
+ chosen_logps (torch.Tensor): Avg log probabilities of chosen tokens. Shape: (batch_size,).
16
+ rejected_logps (torch.Tensor): Avg log probabilities of rejected tokens. Shape: (batch_size,).
17
+ beta (float): Weight for the odds ratio loss.
18
+ """
19
+ log_odds = (chosen_logps - rejected_logps) - (
20
+ torch.log1p(-torch.exp(chosen_logps)) - torch.log1p(-torch.exp(rejected_logps))
21
+ )
22
+ ratio = F.logsigmoid(log_odds)
23
+ return beta * ratio.sum()
24
+
25
+
26
+ def _compute_orpo_loss(
27
+ input_chunk,
28
+ weight,
29
+ target_chunk,
30
+ bias=None,
31
+ full_target=None,
32
+ ignore_index=-100,
33
+ beta=0.1,
34
+ compute_nll_loss=True,
35
+ ):
36
+ """
37
+ Compute ORPO loss for a chunk of input and target.
38
+ Args:
39
+ input_chunk (torch.Tensor): Chunk of input tensor. Shape: (2 * chunk_size, sequence_length, hidden_size).
40
+ weight (torch.Tensor): Weight tensor. Shape: (vocab_size, hidden_size).
41
+ target_chunk (torch.Tensor): Chunk of target tensor. Shape: (2 * chunk_size, sequence_length).
42
+ bias (torch.Tensor, optional): Bias tensor. Shape: (vocab_size,).
43
+ full_target (torch.Tensor): Full target tensor. Shape: (batch_size, sequence_length).
44
+ ignore_index (int): Index to ignore for loss computation.
45
+ beta (float): Weight for the odds ratio loss.
46
+ """
47
+ len_chosen_chunk = target_chunk.shape[0] // 2
48
+
49
+ logits_chunk = input_chunk @ weight.t() # chunk_size x V
50
+ if bias is not None:
51
+ logits_chunk = logits_chunk + bias
52
+ log_probs_chunk = F.log_softmax(logits_chunk.float(), dim=-1)
53
+
54
+ chosen_nll_loss = 0.0
55
+ if compute_nll_loss:
56
+ chosen_nll_loss = F.nll_loss(
57
+ log_probs_chunk[:len_chosen_chunk].view(-1, log_probs_chunk.shape[-1]),
58
+ target_chunk[:len_chosen_chunk].view(-1),
59
+ reduction="sum",
60
+ ignore_index=ignore_index,
61
+ )
62
+ chosen_nll_loss = (
63
+ chosen_nll_loss
64
+ / (full_target[: full_target.shape[0] // 2] != ignore_index).sum()
65
+ )
66
+
67
+ loss_mask = target_chunk != ignore_index
68
+ label_chunk = torch.where(loss_mask, target_chunk, 0)
69
+
70
+ per_token_logps = log_probs_chunk.gather(-1, label_chunk.unsqueeze(-1)).squeeze(-1)
71
+ average_log_prob = (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
72
+
73
+ chosen_logps = average_log_prob[:len_chosen_chunk]
74
+ rejected_logps = average_log_prob[len_chosen_chunk:]
75
+
76
+ or_loss = odds_ratio_loss(chosen_logps, rejected_logps, beta=beta)
77
+ or_loss = or_loss / (full_target.shape[0] // 2)
78
+
79
+ loss = chosen_nll_loss - or_loss
80
+ return loss, (or_loss, chosen_logps, rejected_logps)
81
+
82
+
83
+ class LigerFusedLinearORPOFunction(LigerFusedLinearPreferenceBase):
84
+ @staticmethod
85
+ def forward(
86
+ ctx,
87
+ _input,
88
+ weight,
89
+ target,
90
+ bias=None,
91
+ ignore_index=-100,
92
+ beta=0.1,
93
+ compute_nll_loss=True,
94
+ compiled=True,
95
+ ):
96
+ """
97
+ Fused linear layer with ORPO (Odds-Ratio Preference Optimization) loss.
98
+ Handles both the forward and backward pass of the final linear layer with ORPO loss.
99
+ Inspired from LigerFusedLinearCrossEntropyFunction (https://arxiv.org/abs/2410.10989) which fuses final linear layer and CE loss.
100
+ """
101
+ orpo_loss_fn = partial(
102
+ _compute_orpo_loss,
103
+ full_target=target,
104
+ ignore_index=ignore_index,
105
+ beta=beta,
106
+ compute_nll_loss=compute_nll_loss,
107
+ )
108
+ return LigerFusedLinearPreferenceBase.forward(
109
+ ctx, _input, weight, target, bias, loss_fn=orpo_loss_fn
110
+ )
111
+
112
+ @staticmethod
113
+ def backward(ctx, grad_output):
114
+ # Get gradients for _input, weight, bias, and target from the base class
115
+ grads = LigerFusedLinearPreferenceBase.backward(ctx, grad_output)[:4]
116
+ # Return these gradients, followed by None for the remaining inputs
117
+ return *grads, None, None, None, None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: liger_kernel_nightly
3
- Version: 0.4.1.dev20241113011623
3
+ Version: 0.4.1.dev20241114041219
4
4
  Summary: Efficient Triton kernels for LLM Training
5
5
  License: BSD 2-CLAUSE LICENSE
6
6
  Copyright 2024 LinkedIn Corporation
@@ -1,4 +1,7 @@
1
1
  liger_kernel/env_report.py,sha256=jye8RvUkmhqaIshdeIpoUABoAu7FPKJUib4FnAfvkpw,1132
2
+ liger_kernel/chunked_loss/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ liger_kernel/chunked_loss/fused_linear_preference.py,sha256=WYsIW3t_DEPeC2VkKACimMI0LhZwOciLluDhKnaMmWE,4416
4
+ liger_kernel/chunked_loss/orpo_loss.py,sha256=HgiWjS1ueVpi63ZGVveqwXkXY7EePfSzfbW-bbZlDxE,4220
2
5
  liger_kernel/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
6
  liger_kernel/ops/cross_entropy.py,sha256=sfUb7-jIZp0EKXjg1DYy2Wdzw_Mg-mHmGoR5bpdm4tw,15526
4
7
  liger_kernel/ops/fused_linear_cross_entropy.py,sha256=JPiQ0TgPjtQ-3F5ovC0b5ZnBk067XUmzyNuGO3KZv44,9963
@@ -43,9 +46,9 @@ liger_kernel/transformers/model/qwen2.py,sha256=EyhSSzQOskGjSnCsKMZpd1s5IAIlHd5P
43
46
  liger_kernel/transformers/model/qwen2_vl.py,sha256=j6xAhp9AG195dsZK5f8dFYVM9uKtWApZrggT5Y08jn4,7055
44
47
  liger_kernel/triton/__init__.py,sha256=yfRe0zMb47QnqjecZWG7LnanfCTzeku7SgWRAwNVmzU,101
45
48
  liger_kernel/triton/monkey_patch.py,sha256=5BcGKTtdqeYchypBIBopGIWPx1-cFALz7sOKoEsqXJ0,1584
46
- liger_kernel_nightly-0.4.1.dev20241113011623.dist-info/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
47
- liger_kernel_nightly-0.4.1.dev20241113011623.dist-info/METADATA,sha256=5XnD8ZeAAXku-4RiHLuQKYt2t_v8Pe20QVi_fK8glxY,21556
48
- liger_kernel_nightly-0.4.1.dev20241113011623.dist-info/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
49
- liger_kernel_nightly-0.4.1.dev20241113011623.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
50
- liger_kernel_nightly-0.4.1.dev20241113011623.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
51
- liger_kernel_nightly-0.4.1.dev20241113011623.dist-info/RECORD,,
49
+ liger_kernel_nightly-0.4.1.dev20241114041219.dist-info/LICENSE,sha256=OhzLDHJ0to4a8sodVLELZiCFylZ1NAAYLs-HrjPy0ag,1312
50
+ liger_kernel_nightly-0.4.1.dev20241114041219.dist-info/METADATA,sha256=o4-CpcoMQuNzIpWwfEGDLui8edp-sWcFlXXZFDSHmlw,21556
51
+ liger_kernel_nightly-0.4.1.dev20241114041219.dist-info/NOTICE,sha256=njwnoPZLh9AN8SJQzxvCGLHi-8X__AvWRze6joNXIY8,2066
52
+ liger_kernel_nightly-0.4.1.dev20241114041219.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
53
+ liger_kernel_nightly-0.4.1.dev20241114041219.dist-info/top_level.txt,sha256=2eghu4hA3LnkM7ElW92tQ8zegWKgSbeo-k-aGe1YnvY,13
54
+ liger_kernel_nightly-0.4.1.dev20241114041219.dist-info/RECORD,,