File size: 42,353 Bytes
b66f552 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 | # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import warnings
import torch
import triton
import triton.language as tl
from fla.ops.common.chunk_h import chunk_fwd_h
from fla.ops.gla.chunk import chunk_gla_bwd_dA, chunk_gla_bwd_dv, chunk_gla_fwd_o_gk
from fla.ops.utils import prepare_chunk_indices, prepare_chunk_offsets
from fla.ops.utils.op import exp
from fla.utils import (
autocast_custom_bwd,
autocast_custom_fwd,
autotune_cache_kwargs,
check_shared_mem,
input_guard,
use_cuda_graph,
)
BK_LIST = [32, 64] if check_shared_mem() else [16, 32]
BV_LIST = [32, 64] if check_shared_mem() else [16, 32]
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({'BS': BS}, num_warps=num_warps, num_stages=num_stages)
for BS in [16, 32, 64]
for num_warps in [4, 8, 16]
for num_stages in [2, 3, 4]
],
key=['S', 'BT'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_fwd_cumsum_kernel(
s,
oi,
oe,
cu_seqlens,
chunk_indices,
T,
H: tl.constexpr,
S: tl.constexpr,
BT: tl.constexpr,
BS: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_s, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
else:
bos, eos = i_b * T, i_b * T + T
o_i = tl.arange(0, BT)
m_i = tl.where(o_i[:, None] >= o_i[None, :], 1., 0.).to(tl.float32)
m_e = tl.where(o_i[:, None] > o_i[None, :], 1., 0.).to(tl.float32)
p_s = tl.make_block_ptr(s + (bos * H + i_h) * S, (T, S), (H*S, 1), (i_t * BT, i_s * BS), (BT, BS), (1, 0))
p_oi = tl.make_block_ptr(oi + (bos * H + i_h) * S, (T, S), (H*S, 1), (i_t * BT, i_s * BS), (BT, BS), (1, 0))
p_oe = tl.make_block_ptr(oe + (bos * H + i_h) * S, (T, S), (H*S, 1), (i_t * BT, i_s * BS), (BT, BS), (1, 0))
# [BT, BS]
b_s = tl.load(p_s, boundary_check=(0, 1)).to(tl.float32)
b_oi = tl.dot(m_i, b_s)
b_oe = tl.dot(m_e, b_s)
tl.store(p_oi, b_oi.to(p_oi.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
tl.store(p_oe, b_oe.to(p_oe.dtype.element_ty, fp_downcast_rounding="rtne"), boundary_check=(0, 1))
def chunk_rwkv6_fwd_cumsum(
g: torch.Tensor,
chunk_size: int,
cu_seqlens: torch.Tensor | None = None,
) -> torch.Tensor:
B, T, H, S = g.shape
BT = chunk_size
chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
gi, ge = torch.empty_like(g, dtype=torch.float), torch.empty_like(g, dtype=torch.float)
def grid(meta): return (triton.cdiv(meta['S'], meta['BS']), NT, B * H)
# keep cummulative normalizer in fp32
chunk_rwkv6_fwd_cumsum_kernel[grid](
g,
gi,
ge,
cu_seqlens,
chunk_indices,
T=T,
H=H,
S=S,
BT=BT,
)
return gi, ge
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({'BK': BK}, num_warps=num_warps, num_stages=num_stages)
for BK in [32, 64]
for num_warps in [1, 2, 4, 8]
for num_stages in [2, 3, 4]
],
key=['BC'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_fwd_A_kernel_intra_sub_inter(
q,
k,
gi, # cumulative decay inclusive
ge, # cumulative decay exclusive
A,
cu_seqlens,
chunk_indices,
scale,
T,
H: tl.constexpr,
K: tl.constexpr,
BT: tl.constexpr,
BC: tl.constexpr,
BK: tl.constexpr,
NC: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_t, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
i_i, i_j = i_c // NC, i_c % NC
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
else:
bos, eos = i_b * T, i_b * T + T
if i_t * BT + i_i * BC >= T:
return
if i_i <= i_j:
return
m_i = i_t * BT + i_i * BC + tl.arange(0, BC) < T
b_A = tl.zeros([BC, BC], dtype=tl.float32)
for i_k in range(tl.cdiv(K, BK)):
o_k = i_k * BK + tl.arange(0, BK)
m_k = o_k < K
p_q = tl.make_block_ptr(q + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
p_gq = tl.make_block_ptr(ge + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
p_k = tl.make_block_ptr(k + (bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT + i_j * BC), (BK, BC), (0, 1))
p_gk = tl.make_block_ptr(gi + (bos*H+i_h)*K, (K, T), (1, H*K), (i_k * BK, i_t * BT + i_j * BC), (BK, BC), (0, 1))
p_gn = gi + (bos + i_t * BT + i_i * BC - 1) * H*K + i_h * K + o_k
# [BK,]
b_gn = tl.load(p_gn, mask=m_k, other=0)
# [BC, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
b_gq = tl.where(m_i[:, None] & m_k, tl.load(p_gq, boundary_check=(0, 1)), float('-inf'))
b_qg = b_q * exp(b_gq - b_gn[None, :]) * scale
# [BK, BC]
b_k = tl.load(p_k, boundary_check=(0, 1))
b_gk = tl.load(p_gk, boundary_check=(0, 1))
b_kg = b_k * exp(b_gn[:, None] - b_gk)
# [BC, BC] using tf32 to improve precision here.
b_A += tl.dot(b_qg, b_kg)
p_A = tl.make_block_ptr(A + (bos*H + i_h)*BT, (T, BT), (H*BT, 1), (i_t * BT + i_i * BC, i_j * BC), (BC, BC), (1, 0))
tl.store(p_A, b_A.to(A.dtype.element_ty), boundary_check=(0, 1))
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=num_warps)
for num_warps in [1, 2, 4, 8]
],
key=['BK', 'BT'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_fwd_A_kernel_intra_sub_intra(
q,
k,
gi,
ge,
u,
A,
cu_seqlens,
chunk_indices,
scale,
T,
H: tl.constexpr,
K: tl.constexpr,
BT: tl.constexpr,
BC: tl.constexpr,
BK: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_t, i_i, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
i_j = i_i
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
else:
bos, eos = i_b * T, i_b * T + T
if i_t * BT + i_i * BC >= T:
return
o_i = tl.arange(0, BC)
o_k = tl.arange(0, BK)
m_k = o_k < K
m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
o_A = (bos + i_t * BT + i_i * BC + tl.arange(0, BC)) * H*BT + i_h * BT + i_j * BC
p_q = tl.make_block_ptr(q + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, 0), (BC, BK), (1, 0))
p_g = tl.make_block_ptr(ge + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, 0), (BC, BK), (1, 0))
p_qj = q + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
p_kj = k + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
p_gk = gi + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
b_q = tl.load(p_q, boundary_check=(0, 1))
b_g = tl.load(p_g, boundary_check=(0, 1))
p_u = tl.make_block_ptr(u + i_h * K, (K,), (1,), (0,), (BK,), (0,))
b_u = tl.load(p_u, boundary_check=(0,))
for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
b_qj = tl.load(p_qj, mask=m_k, other=0).to(tl.float32)
b_kj = tl.load(p_kj, mask=m_k, other=0).to(tl.float32)
b_gk = tl.load(p_gk, mask=m_k, other=0).to(tl.float32)
b_A = tl.sum(b_q * b_kj[None, :] * exp(b_g - b_gk[None, :]), 1)
b_A = tl.where(o_i > j, b_A * scale, 0.)
b_A = tl.where(o_i != j, b_A, tl.sum(b_qj * b_kj * b_u * scale))
tl.store(A + o_A + j, b_A, mask=m_A)
p_qj += H*K
p_kj += H*K
p_gk += H*K
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=1),
triton.Config({}, num_warps=2),
triton.Config({}, num_warps=4),
triton.Config({}, num_warps=8),
],
key=['BC', 'BK'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_fwd_A_kernel_intra_sub_intra_split(
q,
k,
gi,
ge,
u,
A,
cu_seqlens,
chunk_indices,
scale,
B: tl.constexpr,
T,
H: tl.constexpr,
K: tl.constexpr,
BT: tl.constexpr,
BC: tl.constexpr,
BK: tl.constexpr,
NC: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_k, i_tc, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
i_t, i_i = i_tc // NC, i_tc % NC
i_j = i_i
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
all = T
T = eos - bos
else:
bos, eos = i_b * T, i_b * T + T
all = B * T
if i_t * BT + i_i * BC >= T:
return
o_i = tl.arange(0, BC)
o_k = i_k * BK + tl.arange(0, BK)
m_k = o_k < K
m_A = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
o_A = (i_k * all + bos + i_t * BT + i_i * BC + tl.arange(0, BC)) * H*BC + i_h * BC
p_q = tl.make_block_ptr(q + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
p_g = tl.make_block_ptr(ge + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
p_qj = q + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
p_kj = k + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
p_gk = gi + (bos + i_t * BT + i_j * BC) * H*K + i_h * K + o_k
b_q = tl.load(p_q, boundary_check=(0, 1))
b_g = tl.load(p_g, boundary_check=(0, 1))
p_u = tl.make_block_ptr(u + i_h * K, (K,), (1,), (i_k * BK), (BK,), (0,))
b_u = tl.load(p_u, boundary_check=(0,))
for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
b_qj = tl.load(p_qj, mask=m_k, other=0).to(tl.float32)
b_kj = tl.load(p_kj, mask=m_k, other=0).to(tl.float32)
b_gk = tl.load(p_gk, mask=m_k, other=0).to(tl.float32)
b_A = tl.sum(b_q * b_kj[None, :] * exp(b_g - b_gk[None, :]), 1)
b_A = tl.where(o_i > j, b_A * scale, 0.)
b_A = tl.where(o_i != j, b_A, tl.sum(b_qj * b_kj * b_u * scale))
tl.store(A + o_A + j, b_A, mask=m_A)
p_qj += H*K
p_kj += H*K
p_gk += H*K
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=1),
triton.Config({}, num_warps=2),
triton.Config({}, num_warps=4),
triton.Config({}, num_warps=8),
],
key=['BC'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_fwd_A_kernel_intra_sub_intra_merge(
A,
A2,
cu_seqlens,
chunk_indices,
T,
B: tl.constexpr,
H: tl.constexpr,
BT: tl.constexpr,
BC: tl.constexpr,
NK: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_t, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
all = T
T = eos - bos
else:
bos, eos = i_b * T, i_b * T + T
all = B * T
if i_t * BT + i_c * BC >= T:
return
b_A = tl.zeros([BC, BC], dtype=tl.float32)
for i_k in range(0, NK):
p_A = tl.make_block_ptr(A + (i_k*all+bos)*H*BC+i_h*BC, (T, BC), (H*BC, 1), (i_t*BT + i_c*BC, 0), (BC, BC), (1, 0))
b_A += tl.load(p_A, boundary_check=(0, 1))
p_A2 = tl.make_block_ptr(A2 + (bos*H+i_h)*BT, (T, BT), (H*BT, 1), (i_t * BT + i_c * BC, i_c * BC), (BC, BC), (1, 0))
tl.store(p_A2, b_A.to(A2.dtype.element_ty), boundary_check=(0, 1))
@triton.heuristics({
'STORE_INITIAL_STATE_GRADIENT': lambda args: args['dh0'] is not None,
'USE_FINAL_STATE_GRADIENT': lambda args: args['dht'] is not None,
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps, num_stages=num_stages)
for BK in BK_LIST
for BV in BV_LIST
for num_warps in [1, 2, 4, 8]
for num_stages in [2, 3, 4]
],
key=['BT'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_bwd_kernel_dh(
q,
gi,
ge,
do,
dh,
dht,
dh0,
cu_seqlens,
chunk_offsets,
scale,
T,
HQ: tl.constexpr,
H: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
NG: tl.constexpr,
STORE_INITIAL_STATE_GRADIENT: tl.constexpr,
USE_FINAL_STATE_GRADIENT: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_k, i_v, i_nh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_n, i_hq = i_nh // HQ, i_nh % HQ
i_h = i_hq // NG
if IS_VARLEN:
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
NT = tl.cdiv(T, BT)
boh = tl.load(chunk_offsets + i_n).to(tl.int32)
else:
bos, eos = i_n * T, i_n * T + T
NT = tl.cdiv(T, BT)
boh = i_n * NT
# [BK, BV]
b_dh = tl.zeros([BK, BV], dtype=tl.float32)
if USE_FINAL_STATE_GRADIENT:
p_dht = tl.make_block_ptr(dht + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
b_dh += tl.load(p_dht, boundary_check=(0, 1)).to(tl.float32)
for i_t in range(NT - 1, -1, -1):
p_dh = tl.make_block_ptr(dh + ((boh+i_t) * H + i_h) * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
tl.store(p_dh, b_dh.to(p_dh.dtype.element_ty), boundary_check=(0, 1))
last_idx = min(i_t * BT + BT, T) - 1
# [BK, BT]
p_q = tl.make_block_ptr(q + (bos*HQ + i_hq) * K, (K, T), (1, HQ*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
p_do = tl.make_block_ptr(do + (bos*HQ + i_hq) * V, (T, V), (HQ*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
b_q = tl.load(p_q, boundary_check=(0, 1))
# [BT, BV]
b_do = tl.load(p_do, boundary_check=(0, 1))
p_gk = tl.make_block_ptr(ge + (bos*H + i_h) * K, (K, T), (1, H*K), (i_k * BK, i_t * BT), (BK, BT), (0, 1))
p_gk_last = gi + (bos + last_idx) * H*K + i_h * K + i_k * BK + tl.arange(0, BK)
b_gk = tl.load(p_gk, boundary_check=(0, 1))
b_q = (b_q * exp(b_gk) * scale).to(b_q.dtype)
b_gk_last = tl.load(p_gk_last, mask=(i_k * BK + tl.arange(0, BK) < K), other=0.)
b_dh *= exp(b_gk_last)[:, None]
b_dh += tl.dot(b_q, b_do)
if STORE_INITIAL_STATE_GRADIENT:
p_dh0 = tl.make_block_ptr(dh0 + i_nh * K*V, (K, V), (V, 1), (i_k * BK, i_v * BV), (BK, BV), (1, 0))
tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), boundary_check=(0, 1))
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({}, num_warps=num_warps)
for num_warps in [1, 2, 4, 8]
],
key=['BK', 'NC', 'BT'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_bwd_kernel_intra(
q,
k,
gi,
ge,
dA,
dq,
dk,
cu_seqlens,
chunk_indices,
T,
H: tl.constexpr,
K: tl.constexpr,
BT: tl.constexpr,
BC: tl.constexpr,
BK: tl.constexpr,
NC: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_k, i_c, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
i_t, i_i = i_c // NC, i_c % NC
if IS_VARLEN:
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
else:
bos, eos = i_b * T, i_b * T + T
T = eos - bos
if i_t * BT + i_i * BC >= T:
return
o_k = i_k * BK + tl.arange(0, BK)
m_k = o_k < K
p_ge = tl.make_block_ptr(ge + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
# [BC, BK]
b_ge = tl.load(p_ge, boundary_check=(0, 1))
b_dq = tl.zeros([BC, BK], dtype=tl.float32)
if i_i > 0:
p_gn = gi + (bos + i_t * BT + i_i * BC - 1) * H*K + i_h*K + o_k
# [BK,]
b_gn = tl.load(p_gn, mask=m_k, other=0)
for i_j in range(0, i_i):
p_k = tl.make_block_ptr(k+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT+i_j*BC, i_k * BK), (BC, BK), (1, 0))
p_gk = tl.make_block_ptr(gi+(bos*H+i_h)*K, (T, K), (H*K, 1), (i_t*BT+i_j*BC, i_k * BK), (BC, BK), (1, 0))
p_dA = tl.make_block_ptr(dA+(bos*H+i_h)*BT, (T, BT), (H*BT, 1), (i_t*BT+i_i*BC, i_j * BC), (BC, BC), (1, 0))
# [BC, BK]
b_k = tl.load(p_k, boundary_check=(0, 1))
b_gk = tl.load(p_gk, boundary_check=(0, 1))
b_kg = b_k * exp(b_gn[None, :] - b_gk)
# [BC, BC]
b_dA = tl.load(p_dA, boundary_check=(0, 1))
# [BC, BK]
b_dq += tl.dot(b_dA, b_kg)
b_dq *= exp(b_ge - b_gn[None, :])
o_i = tl.arange(0, BC)
m_dA = (i_t * BT + i_i * BC + tl.arange(0, BC)) < T
o_dA = bos*H*BT + (i_t * BT + i_i * BC + tl.arange(0, BC)) * H*BT + i_h * BT + i_i * BC
p_kj = k + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
p_gkj = gi + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
p_dq = tl.make_block_ptr(dq + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
# [BC,]
b_dA = tl.load(dA + o_dA + j, mask=m_dA, other=0)
# [BK,]
b_kj = tl.load(p_kj, mask=m_k, other=0).to(tl.float32)
b_gkj = tl.load(p_gkj, mask=m_k, other=0).to(tl.float32)
# [BC, BK]
m_i = o_i[:, None] > j
# [BC, BK]
# (SY 09/17) important to not use bf16 here to have a good precision.
b_dq += tl.where(m_i, b_dA[:, None] * b_kj[None, :] * exp(b_ge - b_gkj[None, :]), 0.)
p_kj += H*K
p_gkj += H*K
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
tl.debug_barrier()
p_k = tl.make_block_ptr(k + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
p_gk = tl.make_block_ptr(gi + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
# [BC, BK]
b_k = tl.load(p_k, boundary_check=(0, 1))
b_gk = tl.load(p_gk, boundary_check=(0, 1))
b_dk = tl.zeros([BC, BK], dtype=tl.float32)
NC = min(NC, tl.cdiv(T - i_t * BT, BC))
if i_i < NC - 1:
p_gn = gi + (bos + min(i_t * BT + i_i * BC + BC, T) - 1) * H*K + i_h*K + o_k
# [BK,]
b_gn = tl.load(p_gn, mask=m_k, other=0)
for i_j in range(i_i + 1, NC):
m_j = (i_t * BT + i_j * BC + tl.arange(0, BC)) < T
p_q = tl.make_block_ptr(q + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_j * BC, i_k*BK), (BC, BK), (1, 0))
p_gq = tl.make_block_ptr(ge + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_j * BC, i_k*BK), (BC, BK), (1, 0))
p_dA = tl.make_block_ptr(dA + (bos*H+i_h)*BT, (BT, T), (1, H*BT), (i_i*BC, i_t*BT + i_j*BC), (BC, BC), (0, 1))
# [BC, BK]
b_q = tl.load(p_q, boundary_check=(0, 1))
b_gq = tl.where(m_j[:, None] & m_k, tl.load(p_gq, boundary_check=(0, 1)), float('-inf'))
b_qg = b_q * exp(b_gq - b_gn[None, :])
# [BC, BC]
b_dA = tl.load(p_dA, boundary_check=(0, 1))
# [BC, BK]
# (SY 09/17) important to not use bf16 here to have a good precision.
b_dk += tl.dot(b_dA, b_qg)
b_dk *= exp(b_gn[None, :] - b_gk)
o_dA = bos*H*BT + (i_t * BT + i_i * BC) * H*BT + i_h * BT + i_i * BC + tl.arange(0, BC)
p_qj = q + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
p_gqj = ge + (bos + i_t * BT + i_i * BC) * H*K + i_h * K + o_k
p_dk = tl.make_block_ptr(dk + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT + i_i * BC, i_k * BK), (BC, BK), (1, 0))
for j in range(0, min(BC, T - i_t * BT - i_i * BC)):
# [BC,]
b_dA = tl.load(dA + o_dA + j * H*BT)
# [BK,]
b_qj = tl.load(p_qj, mask=m_k, other=0).to(tl.float32)
b_gqj = tl.load(p_gqj, mask=m_k, other=0).to(tl.float32)
# [BC, BK]
m_i = o_i[:, None] < j
b_dk += tl.where(m_i, b_dA[:, None] * b_qj[None, :] * exp(b_gqj[None, :] - b_gk), 0.)
p_qj += H*K
p_gqj += H*K
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
@triton.heuristics({
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
})
@triton.autotune(
configs=[
triton.Config({'BK': BK, 'BV': BV}, num_warps=num_warps)
for BK in BK_LIST
for BV in BV_LIST
for num_warps in [2, 4, 8]
],
key=['BT'],
use_cuda_graph=use_cuda_graph,
**autotune_cache_kwargs,
)
@triton.jit(do_not_specialize=['T'])
def chunk_rwkv6_bwd_kernel_inter(
q,
k,
v,
h,
gi,
ge,
u,
do,
dh,
dA,
dq,
dk,
dq2,
dk2,
dg,
du,
cu_seqlens,
chunk_indices,
scale,
T,
H: tl.constexpr,
K: tl.constexpr,
V: tl.constexpr,
BT: tl.constexpr,
BK: tl.constexpr,
BV: tl.constexpr,
IS_VARLEN: tl.constexpr,
):
i_k, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
i_b, i_h = i_bh // H, i_bh % H
if IS_VARLEN:
i_tg = i_t
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
T = eos - bos
NT = tl.cdiv(T, BT)
else:
NT = tl.cdiv(T, BT)
i_tg = i_b * NT + i_t
bos, eos = i_b * T, i_b * T + T
o_k = i_k * BK + tl.arange(0, BK)
m_k = o_k < K
p_gk = tl.make_block_ptr(ge + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_gi = tl.make_block_ptr(gi + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_gn = gi + (bos + min(T, i_t * BT + BT)-1) * H*K + i_h * K + o_k
b_gn = tl.load(p_gn, mask=m_k, other=0)
b_dq = tl.zeros([BT, BK], dtype=tl.float32)
b_dk = tl.zeros([BT, BK], dtype=tl.float32)
b_dgk = tl.zeros([BK], dtype=tl.float32)
for i_v in range(tl.cdiv(V, BV)):
p_v = tl.make_block_ptr(v + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_do = tl.make_block_ptr(do + (bos*H + i_h) * V, (T, V), (H*V, 1), (i_t * BT, i_v * BV), (BT, BV), (1, 0))
p_h = tl.make_block_ptr(h + (i_tg * H + i_h) * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
p_dh = tl.make_block_ptr(dh + (i_tg * H + i_h) * K*V, (V, K), (1, V), (i_v * BV, i_k * BK), (BV, BK), (0, 1))
# [BT, BV]
b_v = tl.load(p_v, boundary_check=(0, 1))
b_do = tl.load(p_do, boundary_check=(0, 1))
# [BV, BK]
b_h = tl.load(p_h, boundary_check=(0, 1))
b_dh = tl.load(p_dh, boundary_check=(0, 1))
# [BK]
b_dgk += tl.sum(b_h * b_dh, axis=0)
# [BT, BK]
b_dq += tl.dot(b_do, b_h.to(b_do.dtype))
b_dk += tl.dot(b_v, b_dh.to(b_v.dtype))
b_dgk *= exp(b_gn)
b_dq *= scale
b_gk = tl.load(p_gk, boundary_check=(0, 1))
b_gi = tl.load(p_gi, boundary_check=(0, 1))
b_dq = b_dq * exp(b_gk)
b_dk = b_dk * exp(b_gn[None, :] - b_gi)
o_i = tl.arange(0, BT)
p_q = tl.make_block_ptr(q + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_k = tl.make_block_ptr(k + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_dq = tl.make_block_ptr(dq + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_dk = tl.make_block_ptr(dk + (bos*H+i_h)*K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_dA_dig = dA + ((bos + i_t * BT + o_i) * H + i_h) * BT + o_i
b_q = tl.load(p_q, boundary_check=(0, 1))
b_k = tl.load(p_k, boundary_check=(0, 1))
b_dgk += tl.sum(b_dk * b_k, axis=0)
b_dq += tl.load(p_dq, boundary_check=(0, 1))
b_dk += tl.load(p_dk, boundary_check=(0, 1))
b_dg = b_q * b_dq - b_k * b_dk
b_dg = b_dg - tl.cumsum(b_dg, axis=0) + tl.sum(b_dg, axis=0)[None, :] + b_dgk[None, :] - b_q * b_dq
# [BT,]
b_dA_dig = tl.load(p_dA_dig, mask=(i_t * BT + o_i) < T, other=0)
p_u = tl.make_block_ptr(u + i_h * K, (K,), (1,), (i_k * BK,), (BK,), (0,))
b_u = tl.load(p_u, boundary_check=(0,))
# scale is already applied to b_dA_diag
b_dq += (b_dA_dig[:, None] * b_u[None, :] * b_k)
b_dk += (b_dA_dig[:, None] * b_u[None, :] * b_q)
b_du = tl.sum(b_dA_dig[:, None] * b_q * b_k, axis=0)
p_du = tl.make_block_ptr(du + (i_tg * H + i_h) * K, (K,), (1,), (i_k * BK,), (BK,), (0,))
tl.store(p_du, b_du, boundary_check=(0,))
p_dq = tl.make_block_ptr(dq2 + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_dk = tl.make_block_ptr(dk2 + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
p_dg = tl.make_block_ptr(dg + (bos * H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), boundary_check=(0, 1))
tl.store(p_dg, b_dg.to(p_dg.dtype.element_ty), boundary_check=(0, 1))
def chunk_rwkv6_fwd_intra(
q: torch.Tensor,
k: torch.Tensor,
gi: torch.Tensor,
ge: torch.Tensor,
u: torch.Tensor,
scale: float,
cu_seqlens: torch.LongTensor | None = None,
chunk_size: int = 64,
):
B, T, H, K = k.shape
BT = chunk_size
chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
BC = min(16, BT)
NC = triton.cdiv(BT, BC)
A = q.new_empty(B, T, H, BT, dtype=torch.float)
grid = (NT, NC * NC, B * H)
chunk_rwkv6_fwd_A_kernel_intra_sub_inter[grid](
q,
k,
gi,
ge,
A,
cu_seqlens,
chunk_indices,
scale,
T=T,
H=H,
K=K,
BT=BT,
BC=BC,
NC=NC,
)
grid = (NT, NC, B * H)
# load the entire [BC, K] blocks into SRAM at once
if K <= 256:
BK = max(triton.next_power_of_2(K), 16)
chunk_rwkv6_fwd_A_kernel_intra_sub_intra[grid](
q,
k,
gi,
ge,
u,
A,
cu_seqlens,
chunk_indices,
scale,
T=T,
H=H,
K=K,
BT=BT,
BC=BC,
BK=BK,
)
# split then merge
else:
BK = min(128, triton.next_power_of_2(K))
NK = triton.cdiv(K, BK)
A_intra = q.new_empty(NK, B, T, H, BC, dtype=torch.float)
grid = (NK, NT * NC, B * H)
chunk_rwkv6_fwd_A_kernel_intra_sub_intra_split[grid](
q,
k,
gi,
ge,
u,
A_intra,
cu_seqlens,
chunk_indices,
scale,
B=B,
T=T,
H=H,
K=K,
BT=BT,
BC=BC,
BK=BK,
NC=NC,
)
grid = (NT, NC, B * H)
chunk_rwkv6_fwd_A_kernel_intra_sub_intra_merge[grid](
A_intra,
A,
cu_seqlens,
chunk_indices,
B=B,
T=T,
H=H,
BT=BT,
BC=BC,
NK=NK,
)
return A
def chunk_rwkv6_bwd_dh(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
gi: torch.Tensor,
ge: torch.Tensor,
do: torch.Tensor,
h0: torch.Tensor,
dht: torch.Tensor,
scale: float,
cu_seqlens: torch.Tensor | None = None,
chunk_size: int = 64,
states_in_fp32: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
B, T, H, K, V = *k.shape, v.shape[-1]
HQ = q.shape[2]
BT = chunk_size
# N: the actual number of sequences in the batch with either equal or variable lengths
# NG: number of groups in GQA
chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
if cu_seqlens is None:
N, NT, chunk_offsets = B, triton.cdiv(T, BT), None
else:
N, NT = len(cu_seqlens) - 1, len(chunk_indices)
chunk_offsets = prepare_chunk_offsets(cu_seqlens, BT)
NG = HQ // H
dh = k.new_empty(B, NT, HQ, K, V, dtype=k.dtype if not states_in_fp32 else torch.float)
dh0 = torch.empty_like(h0, dtype=torch.float) if h0 is not None else None
def grid(meta): return (triton.cdiv(K, meta['BK']), triton.cdiv(V, meta['BV']), N * H)
chunk_rwkv6_bwd_kernel_dh[grid](
q=q,
gi=gi,
ge=ge,
do=do,
dh=dh,
dht=dht,
dh0=dh0,
cu_seqlens=cu_seqlens,
chunk_offsets=chunk_offsets,
scale=scale,
T=T,
HQ=HQ,
H=H,
K=K,
V=V,
BT=BT,
NG=NG,
)
return dh, dh0
def chunk_rwkv6_bwd_dqk_intra(
q: torch.Tensor,
k: torch.Tensor,
gi: torch.Tensor,
ge: torch.Tensor,
dA: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
chunk_size: int = 64,
):
B, T, H, K = q.shape
BT = chunk_size
BC = min(16, BT)
BK = min(64, triton.next_power_of_2(K))
chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
NC = triton.cdiv(BT, BC)
NK = triton.cdiv(K, BK)
dq = torch.empty_like(q, dtype=torch.float)
dk = torch.empty_like(k, dtype=torch.float)
grid = (NK, NT * NC, B * H)
chunk_rwkv6_bwd_kernel_intra[grid](
q,
k,
gi,
ge,
dA,
dq,
dk,
cu_seqlens,
chunk_indices,
T=T,
H=H,
K=K,
BT=BT,
BC=BC,
BK=BK,
NC=NC,
)
return dq, dk
def chunk_rwkv6_bwd_dqkgu(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
h: torch.Tensor,
g: torch.Tensor,
gi: torch.Tensor,
ge: torch.Tensor,
u: torch.Tensor,
do: torch.Tensor,
dh: torch.Tensor,
dA: torch.Tensor,
dq: torch.Tensor,
dk: torch.Tensor,
scale: float,
cu_seqlens: torch.LongTensor | None = None,
chunk_size: int = 64,
):
B, T, H, K, V = *k.shape, v.shape[-1]
BT = chunk_size
chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size) if cu_seqlens is not None else None
NT = triton.cdiv(T, BT) if cu_seqlens is None else len(chunk_indices)
dq2 = torch.empty_like(dq)
dk2 = torch.empty_like(dk)
dg = torch.empty_like(g)
du = u.new_empty(B * NT, H, K, dtype=torch.float)
def grid(meta): return (triton.cdiv(K, meta['BK']), NT, B * H)
chunk_rwkv6_bwd_kernel_inter[grid](
q,
k,
v,
h,
gi,
ge,
u,
do,
dh,
dA,
dq,
dk,
dq2,
dk2,
dg,
du,
cu_seqlens,
chunk_indices,
scale,
T=T,
H=H,
K=K,
V=V,
BT=BT,
)
du = du.sum(0)
return dq2, dk2, dg, du
def chunk_rwkv6_fwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g: torch.Tensor,
u: torch.Tensor,
scale: float,
initial_state: torch.Tensor,
output_final_state: bool,
cu_seqlens: torch.LongTensor | None = None,
chunk_size: int = 64,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
gi, ge = chunk_rwkv6_fwd_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens)
h, ht = chunk_fwd_h(
k=k,
v=v,
g=None,
gk=gi,
gv=None,
h0=initial_state,
output_final_state=output_final_state,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
states_in_fp32=True,
)
# the intra A is kept in fp32
# the computation has very marginal effect on the entire throughput
A = chunk_rwkv6_fwd_intra(
q=q,
k=k,
gi=gi,
ge=ge,
u=u,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
o = chunk_gla_fwd_o_gk(
q=q,
v=v,
g=ge,
A=A,
h=h,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
return A, h, ht, o
def chunk_rwkv6_bwd(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
g: torch.Tensor,
u: torch.Tensor,
scale: float,
initial_state: torch.Tensor,
A: torch.Tensor,
do: torch.Tensor,
dht: torch.Tensor,
cu_seqlens: torch.LongTensor | None = None,
chunk_size: int = 64,
):
gi, ge = chunk_rwkv6_fwd_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens)
h, _ = chunk_fwd_h(
k=k,
v=v,
g=None,
gk=gi,
gv=None,
h0=initial_state,
output_final_state=False,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
states_in_fp32=True,
)
dh, dh0 = chunk_rwkv6_bwd_dh(
q=q,
k=k,
v=v,
gi=gi,
ge=ge,
do=do,
h0=initial_state,
dht=dht,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
states_in_fp32=True,
)
# dq dk in fp32
dA = chunk_gla_bwd_dA(
v=v,
do=do,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
dv = chunk_gla_bwd_dv(
k=k,
g=gi,
A=A,
do=do,
dh=dh,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
dq, dk = chunk_rwkv6_bwd_dqk_intra(
q=q,
k=k,
gi=gi,
ge=ge,
dA=dA,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
dq, dk, dg, du = chunk_rwkv6_bwd_dqkgu(
q=q,
k=k,
v=v,
h=h,
g=g,
gi=gi,
ge=ge,
u=u,
do=do,
dh=dh,
dA=dA,
dq=dq,
dk=dk,
scale=scale,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
return dq, dk, dv, dg, du, dh0
class ChunkRWKV6Function(torch.autograd.Function):
@staticmethod
@input_guard
@autocast_custom_fwd
def forward(
ctx,
q,
k,
v,
g,
u,
scale,
initial_state,
output_final_state,
cu_seqlens,
):
T = q.shape[1]
if check_shared_mem():
chunk_size = min(32, max(32, triton.next_power_of_2(T)))
else:
chunk_size = min(64, max(32, triton.next_power_of_2(T)))
A, h, ht, o = chunk_rwkv6_fwd(
q=q,
k=k,
v=v,
g=g,
u=u,
scale=scale,
initial_state=initial_state,
output_final_state=output_final_state,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
ctx.save_for_backward(q, k, v, g, initial_state, A, u)
ctx.chunk_size = chunk_size
ctx.scale = scale
ctx.cu_seqlens = cu_seqlens
return o, ht
@staticmethod
@input_guard
@autocast_custom_bwd
def backward(ctx, do, dht):
q, k, v, g, initial_state, A, u = ctx.saved_tensors
chunk_size, scale, cu_seqlens = ctx.chunk_size, ctx.scale, ctx.cu_seqlens
dq, dk, dv, dg, du, dh0 = chunk_rwkv6_bwd(
q=q,
k=k,
v=v,
g=g,
u=u,
scale=scale,
initial_state=initial_state,
A=A,
do=do,
dht=dht,
cu_seqlens=cu_seqlens,
chunk_size=chunk_size,
)
return dq.to(q), dk.to(k), dv.to(v), dg.to(g), du.to(u), None, dh0, None, None
@torch.compiler.disable
def chunk_rwkv6(
r: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
w: torch.Tensor,
u: torch.Tensor,
scale: int | None = None,
initial_state: torch.Tensor = None,
output_final_state: bool = False,
cu_seqlens: torch.LongTensor | None = None,
head_first: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
r"""
Args:
r (torch.Tensor):
queries of shape `[B, T, H, K]`.
k (torch.Tensor):
keys of shape `[B, T, H, K]`.
v (torch.Tensor):
values of shape `[B, T, H, V]`.
w (torch.Tensor):
Forget gates of shape `[B, T, H, K]`. applied to keys.
u (torch.Tensor):
bonus representations of shape `[H]`.
scale (Optional[float]):
Scale factor for the attention scores.
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
initial_state (Optional[torch.Tensor]):
Initial state of shape `[N, H, K, V]` for `N` input sequences.
For equal-length input sequences, `N` equals the batch size `B`.
Default: `None`.
output_final_state (Optional[bool]):
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
cu_seqlens (torch.LongTensor):
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
consistent with the FlashAttention API.
head_first (Optional[bool]):
Whether the inputs are in the head-first format. Default: `False`.
This argument has been deprecated.
Returns:
o (torch.Tensor):
Outputs of shape `[B, T, H, V]`.
final_state (Optional[torch.Tensor]):
Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
Examples::
>>> import torch
>>> import torch.nn.functional as F
>>> from einops import rearrange
>>> from fla.ops.rwkv6 import chunk_rwkv6
# inputs with equal lengths
>>> B, T, H, K, V = 4, 2048, 4, 512, 512
>>> r = torch.randn(B, T, H, K, device='cuda')
>>> k = torch.randn(B, T, H, K, device='cuda')
>>> v = torch.randn(B, T, H, V, device='cuda')
>>> w = F.logsigmoid(torch.randn(B, T, H, K, device='cuda'))
>>> u = torch.randn(H, K, device='cuda')
>>> h0 = torch.randn(B, H, K, V, device='cuda')
>>> o, ht = chunk_rwkv6(
r, k, v, w, u,
initial_state=h0,
output_final_state=True
)
# for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
>>> r, k, v, w = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (r, k, v, w))
# for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
>>> cu_seqlens = r.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
>>> o_var, ht_var = chunk_rwkv6(
r, k, v, w, u,
initial_state=h0,
output_final_state=True,
cu_seqlens=cu_seqlens
)
>>> assert o.allclose(o_var.view(o.shape))
>>> assert ht.allclose(ht_var)
"""
if head_first:
raise DeprecationWarning(
"head_first is deprecated and will be removed in a future version. "
"Please use head_first=False for now instead.",
)
if not head_first and r.shape[1] < r.shape[2]:
warnings.warn(
f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
"when head_first=False was specified. "
"Please verify your input tensor format matches the expected shape [B, T, H, ...].",
)
if cu_seqlens is not None:
if r.shape[0] != 1:
raise ValueError(
f"The batch size is expected to be 1 rather than {r.shape[0]} when using `cu_seqlens`."
f"Please flatten variable-length inputs before processing.",
)
if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
raise ValueError(
f"The number of initial states is expected to be equal to the number of input sequences, "
f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}.",
)
if scale is None:
scale = r.shape[-1] ** -0.5
o, final_state = ChunkRWKV6Function.apply(
r,
k,
v,
w,
u,
scale,
initial_state,
output_final_state,
cu_seqlens,
)
return o, final_state
|