-
Notifications
You must be signed in to change notification settings - Fork 201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add TVD Loss Kernel #324
Open
saurabhkoshatwar
wants to merge
7
commits into
linkedin:main
Choose a base branch
from
saurabhkoshatwar:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+498
−0
Open
Add TVD Loss Kernel #324
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
da24657
Feature/tvd loss fused (#1)
saurabhkoshatwar 7736e32
Add TVD to README.md
saurabhkoshatwar a45f6ce
checkstyle fixes
saurabhkoshatwar bc906d8
Merge branch 'main' into main
saurabhkoshatwar 0097d15
Merge branch 'main' into main
lancerts bd5f976
Merge branch 'main' into main
saurabhkoshatwar 18fa8b7
init and backward pass reduction
saurabhkoshatwar File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
import torch | ||
import triton | ||
from utils import ( | ||
QUANTILES, | ||
SingleBenchmarkRunInput, | ||
SingleBenchmarkRunOutput, | ||
_test_memory, | ||
parse_benchmark_script_args, | ||
run_benchmarks, | ||
) | ||
|
||
from liger_kernel.transformers.tvd import LigerTVDLoss | ||
|
||
|
||
class TorchTVDLoss(torch.nn.Module): | ||
def __init__(self, reduction="batchmean"): | ||
super(TorchTVDLoss, self).__init__() | ||
self.reduction = reduction | ||
|
||
def forward(self, p, q): | ||
tvd = torch.abs(p - q) / 2.0 | ||
if self.reduction == "mean": | ||
return torch.sum(tvd) / (p.size(0) * p.size(1)) | ||
elif self.reduction == "sum": | ||
return torch.sum(tvd) | ||
elif self.reduction == "none": | ||
return tvd | ||
elif self.reduction == "batchmean": | ||
return torch.sum(tvd) / p.size(0) | ||
else: | ||
raise ValueError("Invalid reduction type.") | ||
|
||
|
||
S, E = 12, 18 | ||
|
||
|
||
def bench_speed_tvd(input: SingleBenchmarkRunInput) -> SingleBenchmarkRunOutput: | ||
reduction = "batchmean" | ||
V = input.x | ||
B, T = input.extra_benchmark_config["B"], input.extra_benchmark_config["T"] | ||
torch_tvd = TorchTVDLoss(reduction=reduction) | ||
liger_tvd = LigerTVDLoss(reduction=reduction) | ||
|
||
_input = torch.randn(B * T, V, requires_grad=True, device="cuda").softmax(dim=-1) | ||
target = torch.randn(B * T, V, device="cuda").softmax(dim=-1) | ||
|
||
def fwd(): | ||
if input.kernel_provider == "liger": | ||
return liger_tvd(_input, target) | ||
else: | ||
return torch_tvd(_input, target) | ||
|
||
if input.kernel_operation_mode == "forward": | ||
ms_50, ms_20, ms_80 = triton.testing.do_bench(fwd, quantiles=QUANTILES, rep=100) | ||
elif input.kernel_operation_mode == "backward": | ||
y = fwd() | ||
|
||
ms_50, ms_20, ms_80 = triton.testing.do_bench( | ||
lambda: y.backward(retain_graph=True), | ||
quantiles=QUANTILES, | ||
grad_to_none=[_input], | ||
rep=100, | ||
) | ||
elif input.kernel_operation_mode == "full": | ||
|
||
def full(): | ||
y = fwd() | ||
y.backward(retain_graph=True) | ||
|
||
ms_50, ms_20, ms_80 = triton.testing.do_bench( | ||
full, quantiles=QUANTILES, rep=100 | ||
) | ||
return SingleBenchmarkRunOutput( | ||
y_20=ms_20, | ||
y_50=ms_50, | ||
y_80=ms_80, | ||
) | ||
|
||
|
||
def bench_memory_tvd(input: SingleBenchmarkRunInput) -> SingleBenchmarkRunOutput: | ||
reduction = "batchmean" | ||
torch_tvd = TorchTVDLoss(reduction=reduction) | ||
liger_tvd = LigerTVDLoss(reduction=reduction) | ||
|
||
V = input.x | ||
B, T = input.extra_benchmark_config["B"], input.extra_benchmark_config["T"] | ||
|
||
_input = torch.randn(B * T, V, requires_grad=True, device="cuda").softmax(dim=-1) | ||
target = torch.randn(B * T, V, device="cuda").softmax(dim=-1) | ||
|
||
def fwd(): | ||
if input.kernel_provider == "liger": | ||
return liger_tvd(_input, target) | ||
else: | ||
return torch_tvd(_input, target) | ||
|
||
def full(): | ||
y = fwd() | ||
y.backward(retain_graph=True) | ||
|
||
mem_50, mem_20, mem_80 = _test_memory(full, quantiles=QUANTILES) | ||
|
||
return SingleBenchmarkRunOutput( | ||
y_20=mem_20, | ||
y_50=mem_50, | ||
y_80=mem_80, | ||
) | ||
|
||
|
||
if __name__ == "__main__": | ||
args = parse_benchmark_script_args() | ||
common_args = { | ||
"kernel_name": "tvd", | ||
"x_name": "V", | ||
"x_label": "vocab size", | ||
"x_values": [2**i for i in range(12, 18)], | ||
"kernel_providers": ["liger", "torch"], | ||
"extra_benchmark_configs": [{"B": 8, "T": 2048}], | ||
"overwrite": args.overwrite, | ||
} | ||
|
||
run_benchmarks( | ||
bench_test_fn=bench_memory_tvd, | ||
kernel_operation_modes=["full"], | ||
metric_name="memory", | ||
metric_unit="MB", | ||
**common_args, | ||
) | ||
|
||
run_benchmarks( | ||
bench_test_fn=bench_speed_tvd, | ||
kernel_operation_modes=["forward", "full"], | ||
metric_name="speed", | ||
metric_unit="ms", | ||
**common_args, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,183 @@ | ||
from typing import Literal | ||
|
||
import torch | ||
import triton | ||
import triton.language as tl | ||
|
||
from liger_kernel.ops.utils import ensure_contiguous | ||
|
||
MAX_FUSED_SIZE = 65536 // 4 | ||
|
||
REDUCTION_LITERAL = Literal["none", "sum", "mean", "batchmean"] | ||
|
||
_REDUCTION_MODE_NONE = tl.constexpr(0) | ||
_REDUCTION_MODE_SUM = tl.constexpr(1) | ||
_REDUCTION_MODE_MEAN = tl.constexpr(2) | ||
_REDUCTION_MODE_BATCHMEAN = tl.constexpr(3) | ||
|
||
_str_to_reduction_mode = { | ||
"none": _REDUCTION_MODE_NONE.value, | ||
"sum": _REDUCTION_MODE_SUM.value, | ||
"mean": _REDUCTION_MODE_MEAN.value, | ||
"batchmean": _REDUCTION_MODE_BATCHMEAN.value, | ||
} | ||
|
||
|
||
def get_num_warps(BLOCK_SIZE): | ||
num_warps = 4 | ||
if BLOCK_SIZE >= 32768: | ||
num_warps = 32 | ||
elif BLOCK_SIZE >= 8192: | ||
num_warps = 16 | ||
elif BLOCK_SIZE >= 2048: | ||
num_warps = 8 | ||
|
||
return num_warps | ||
|
||
|
||
@triton.jit | ||
def _tv_distance_kernel( | ||
p_ptr, | ||
p_stride, | ||
q_ptr, | ||
q_stride, | ||
loss_ptr, | ||
loss_stride, | ||
grads_ptr, | ||
grads_stride, | ||
n_cols, | ||
BLOCK_SIZE: tl.constexpr, | ||
reduction: tl.constexpr = _REDUCTION_MODE_BATCHMEAN, | ||
): | ||
pid = tl.program_id(0).to(tl.int64) | ||
p_ptr += pid * p_stride | ||
q_ptr += pid * q_stride | ||
loss_ptr += pid * loss_stride | ||
grads_ptr += pid * grads_stride | ||
|
||
base_offsets = tl.arange(0, BLOCK_SIZE) | ||
|
||
loss_sum = 0.0 | ||
for i in range(0, n_cols, BLOCK_SIZE): | ||
offsets = i + base_offsets | ||
mask = offsets < n_cols | ||
|
||
p = tl.load(p_ptr + offsets, mask=mask, other=0.0) | ||
q = tl.load(q_ptr + offsets, mask=mask, other=0.0) | ||
|
||
# TVD(P || Q) = 0.5 * |P - Q| | ||
tv_loss = 0.5 * tl.abs(p - q) | ||
|
||
grad_res = tl.where(p > q, 0.5, -0.5) | ||
|
||
tl.store(grads_ptr + offsets, grad_res, mask=mask) | ||
|
||
if reduction == _REDUCTION_MODE_NONE: | ||
tl.store(loss_ptr + offsets, tv_loss, mask=mask) | ||
else: | ||
loss_sum += tl.sum(tv_loss, axis=0) | ||
|
||
if reduction != _REDUCTION_MODE_NONE: | ||
tl.store(loss_ptr, loss_sum) | ||
|
||
|
||
def tv_distance_forward_triton(p, q, reduction): | ||
BT, V = p.shape | ||
|
||
BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(V)) | ||
num_warps = get_num_warps(BLOCK_SIZE) | ||
|
||
grid = (BT,) | ||
|
||
reduction = _str_to_reduction_mode[reduction] | ||
|
||
out_size = (BT, V) if reduction == _REDUCTION_MODE_NONE.value else (BT,) | ||
output_tensor = torch.zeros(out_size, device=p.device, dtype=torch.float32) | ||
grads = torch.empty_like(p) | ||
|
||
_tv_distance_kernel[grid]( | ||
p, | ||
p.stride(0), | ||
q, | ||
q.stride(0), | ||
output_tensor, | ||
output_tensor.stride(0), | ||
grads, | ||
grads.stride(0), | ||
V, | ||
BLOCK_SIZE=BLOCK_SIZE, | ||
num_warps=num_warps, | ||
reduction=reduction, | ||
) | ||
|
||
if reduction == _REDUCTION_MODE_BATCHMEAN.value: | ||
return output_tensor.sum() / BT, grads | ||
elif reduction == _REDUCTION_MODE_SUM.value: | ||
return output_tensor.sum(dim=0), grads | ||
elif reduction == _REDUCTION_MODE_MEAN.value: | ||
return output_tensor.sum() / (BT * V), grads | ||
else: | ||
return output_tensor, grads | ||
|
||
|
||
def tvd_backward_triton(grad_output, grads): | ||
|
||
# If cross entropy is the last layer, grad_output is 1.0. Skip the mul then. | ||
if torch.equal(grad_output, torch.tensor(1.0, device=grad_output.device)): | ||
return grads | ||
|
||
return grads * grad_output | ||
|
||
|
||
class LigerTVDLossFunction(torch.autograd.Function): | ||
""" | ||
Class implementing the forward and backward pass for the Total Variation Distance Loss using Triton. | ||
""" | ||
|
||
@staticmethod | ||
@ensure_contiguous | ||
def forward( | ||
ctx, | ||
p: torch.Tensor, | ||
q: torch.Tensor, | ||
reduction: REDUCTION_LITERAL = "batchmean", | ||
) -> torch.Tensor: | ||
"""A forward pass for the Total Variation Distance Loss. | ||
|
||
Args: | ||
ctx: Torch autograd context | ||
p (torch.Tensor): A tensor of shape (BT, V) containing the first distribution. | ||
q (torch.Tensor): A tensor of shape (BT, V) containing the second distribution. | ||
reduction (REDUCTION_LITERAL, optional): The reduction method to be applied. Defaults to "batchmean". | ||
|
||
Returns: | ||
torch.Tensor: The computed Total Variation Distance Loss. | ||
""" | ||
loss, grads = tv_distance_forward_triton(p, q, reduction) | ||
ctx.save_for_backward(grads) | ||
ctx.reduction = reduction | ||
return loss | ||
|
||
@staticmethod | ||
@ensure_contiguous | ||
def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor: | ||
"""A backward pass for the Total Variation Distance Loss. | ||
|
||
Args: | ||
ctx: Torch autograd context | ||
grad_output (torch.Tensor): The gradient of the loss with respect to the output. | ||
|
||
Returns: | ||
tuple[torch.Tensor, None, None]: The gradient of the loss with respect to the inputs. | ||
""" | ||
(grads,) = ctx.saved_tensors | ||
BT, V = grads.shape | ||
|
||
grads = tvd_backward_triton(grad_output, grads) | ||
|
||
if ctx.reduction == "batchmean": | ||
grads /= BT | ||
elif ctx.reduction == "mean": | ||
grads /= BT * V | ||
|
||
return grads, None, None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
since we're doing gradients calculation in forward pass already, we can divide gradients by BT (BT * V) based on the reduction mode here to avoid extra calculations in backward pass and saving reduction mode in ctx