FlashRWKV2 0.2.0a1__tar.gz → 0.2.0a2__tar.gz
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.
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/FlashRWKV2.egg-info/PKG-INFO +13 -1
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/FlashRWKV2.egg-info/SOURCES.txt +1 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/PKG-INFO +13 -1
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/README.md +12 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/_internal/linear.py +36 -23
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/_internal/state.py +9 -1
- flashrwkv2-0.2.0a2/flashrwkv2/cmix/__init__.py +129 -0
- flashrwkv2-0.2.0a2/flashrwkv2/mtp/__init__.py +194 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/tokenshift/__init__.py +55 -31
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/tokenshift/tilelang.py +50 -16
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/wkv7/__init__.py +18 -6
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/wkv7/pretrain.py +2 -6
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/wkv7/tilelang.py +68 -22
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/wkv_prepare/tilelang.py +1 -1
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/pyproject.toml +1 -1
- flashrwkv2-0.2.0a1/flashrwkv2/cmix/__init__.py +0 -309
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/FlashRWKV2.egg-info/dependency_links.txt +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/FlashRWKV2.egg-info/not-zip-safe +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/FlashRWKV2.egg-info/requires.txt +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/FlashRWKV2.egg-info/top_level.txt +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/LICENSE +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/LICENSES/Apache-2.0.txt +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/MANIFEST.in +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/NOTICE +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/bindings.cpp +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/bindings.h +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/registration.cpp +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/sm80/sampling/infer_fp32_forward_varlen.cpp +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/sm80/sampling/infer_fp32_forward_varlen.cu +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/validation/recurrent_metadata.cpp +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/validation/recurrent_metadata.cu +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/validation.cpp +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/csrc/validation.h +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/_internal/elementwise.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/_internal/execution.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/_internal/logprob.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/compile.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/embedding/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/head/ce/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/head/ce/tilelang.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/head/l2wrap_ce/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/head/linear/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/loss/l2wrap_ce/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/loss/l2wrap_ce/tilelang.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/post_norm/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/post_norm/tilelang.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/sampling/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/kk_pre/tilelang.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/readout/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/readout/pretrain.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/readout/tilelang.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/vres_gate/tilelang.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/flashrwkv2/tmix/wkv_prepare/__init__.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/setup.cfg +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/setup.py +0 -0
- {flashrwkv2-0.2.0a1 → flashrwkv2-0.2.0a2}/tests/test_runtime.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: FlashRWKV2
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.0a2
|
|
4
4
|
Summary: TileLang RWKV-7 operators with shared BF16 training and inference
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Project-URL: Repository, https://github.com/rwkv-rs/FlashRWKV2
|
|
@@ -99,6 +99,12 @@ then restore state and gradients before capture. Dense and packed training
|
|
|
99
99
|
accept optional FP32 initial state and can return final state for the next
|
|
100
100
|
chunk. See the [training contract](docs/kernel_api.md#training).
|
|
101
101
|
|
|
102
|
+
Speculative decoding can export per-token WKV checkpoints and normalized TMix
|
|
103
|
+
and CMix shift states from the verifier. The optional
|
|
104
|
+
`flashrwkv2.mtp.DraftLoop` runs a single-request LightMTP block eagerly or in
|
|
105
|
+
a CUDA Graph. See the [state export and DraftLoop contracts](docs/kernel_api.md#state-and-packed-metadata)
|
|
106
|
+
and the [original TileRWKV changes by Joluck](https://github.com/Joluck/tilerwkv/commit/409b492e952086a61d89817d8032375a851b51da).
|
|
107
|
+
|
|
102
108
|
## Tests
|
|
103
109
|
|
|
104
110
|
```bash
|
|
@@ -144,6 +150,12 @@ and checks the public digests.
|
|
|
144
150
|
|
|
145
151
|
## Benchmarks
|
|
146
152
|
|
|
153
|
+
Run the LightMTP comparison at the RWKV-7 G1k 7.2B draft shape with:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
PYTHONPATH=benchmarks timeout 10m .venv/bin/python benchmarks/mtp/bench.py --depth 4
|
|
157
|
+
```
|
|
158
|
+
|
|
147
159
|
Operator benchmarks live in [`benchmarks/`](benchmarks/). The WKV matrix covers
|
|
148
160
|
batch size, sequence length, and head dimensions:
|
|
149
161
|
|
|
@@ -35,6 +35,7 @@ flashrwkv2/head/l2wrap_ce/__init__.py
|
|
|
35
35
|
flashrwkv2/head/linear/__init__.py
|
|
36
36
|
flashrwkv2/loss/l2wrap_ce/__init__.py
|
|
37
37
|
flashrwkv2/loss/l2wrap_ce/tilelang.py
|
|
38
|
+
flashrwkv2/mtp/__init__.py
|
|
38
39
|
flashrwkv2/post_norm/__init__.py
|
|
39
40
|
flashrwkv2/post_norm/tilelang.py
|
|
40
41
|
flashrwkv2/sampling/__init__.py
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: FlashRWKV2
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.0a2
|
|
4
4
|
Summary: TileLang RWKV-7 operators with shared BF16 training and inference
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Project-URL: Repository, https://github.com/rwkv-rs/FlashRWKV2
|
|
@@ -99,6 +99,12 @@ then restore state and gradients before capture. Dense and packed training
|
|
|
99
99
|
accept optional FP32 initial state and can return final state for the next
|
|
100
100
|
chunk. See the [training contract](docs/kernel_api.md#training).
|
|
101
101
|
|
|
102
|
+
Speculative decoding can export per-token WKV checkpoints and normalized TMix
|
|
103
|
+
and CMix shift states from the verifier. The optional
|
|
104
|
+
`flashrwkv2.mtp.DraftLoop` runs a single-request LightMTP block eagerly or in
|
|
105
|
+
a CUDA Graph. See the [state export and DraftLoop contracts](docs/kernel_api.md#state-and-packed-metadata)
|
|
106
|
+
and the [original TileRWKV changes by Joluck](https://github.com/Joluck/tilerwkv/commit/409b492e952086a61d89817d8032375a851b51da).
|
|
107
|
+
|
|
102
108
|
## Tests
|
|
103
109
|
|
|
104
110
|
```bash
|
|
@@ -144,6 +150,12 @@ and checks the public digests.
|
|
|
144
150
|
|
|
145
151
|
## Benchmarks
|
|
146
152
|
|
|
153
|
+
Run the LightMTP comparison at the RWKV-7 G1k 7.2B draft shape with:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
PYTHONPATH=benchmarks timeout 10m .venv/bin/python benchmarks/mtp/bench.py --depth 4
|
|
157
|
+
```
|
|
158
|
+
|
|
147
159
|
Operator benchmarks live in [`benchmarks/`](benchmarks/). The WKV matrix covers
|
|
148
160
|
batch size, sequence length, and head dimensions:
|
|
149
161
|
|
|
@@ -85,6 +85,12 @@ then restore state and gradients before capture. Dense and packed training
|
|
|
85
85
|
accept optional FP32 initial state and can return final state for the next
|
|
86
86
|
chunk. See the [training contract](docs/kernel_api.md#training).
|
|
87
87
|
|
|
88
|
+
Speculative decoding can export per-token WKV checkpoints and normalized TMix
|
|
89
|
+
and CMix shift states from the verifier. The optional
|
|
90
|
+
`flashrwkv2.mtp.DraftLoop` runs a single-request LightMTP block eagerly or in
|
|
91
|
+
a CUDA Graph. See the [state export and DraftLoop contracts](docs/kernel_api.md#state-and-packed-metadata)
|
|
92
|
+
and the [original TileRWKV changes by Joluck](https://github.com/Joluck/tilerwkv/commit/409b492e952086a61d89817d8032375a851b51da).
|
|
93
|
+
|
|
88
94
|
## Tests
|
|
89
95
|
|
|
90
96
|
```bash
|
|
@@ -130,6 +136,12 @@ and checks the public digests.
|
|
|
130
136
|
|
|
131
137
|
## Benchmarks
|
|
132
138
|
|
|
139
|
+
Run the LightMTP comparison at the RWKV-7 G1k 7.2B draft shape with:
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
PYTHONPATH=benchmarks timeout 10m .venv/bin/python benchmarks/mtp/bench.py --depth 4
|
|
143
|
+
```
|
|
144
|
+
|
|
133
145
|
Operator benchmarks live in [`benchmarks/`](benchmarks/). The WKV matrix covers
|
|
134
146
|
batch size, sequence length, and head dimensions:
|
|
135
147
|
|
|
@@ -152,7 +152,7 @@ def _compile_spec(
|
|
|
152
152
|
),
|
|
153
153
|
{
|
|
154
154
|
"out_idx": [3],
|
|
155
|
-
"target": {"kind": "cuda", "arch": f"sm_{arch}"},
|
|
155
|
+
"target": {"kind": "cuda", "arch": f"sm_{arch}a" if arch == 90 else f"sm_{arch}"},
|
|
156
156
|
"pass_configs": pass_configs,
|
|
157
157
|
},
|
|
158
158
|
)
|
|
@@ -422,7 +422,7 @@ def _adapter_kernel(outputs, dtype, scale, arch):
|
|
|
422
422
|
return tilelang.compile(
|
|
423
423
|
epilogue,
|
|
424
424
|
out_idx=[2],
|
|
425
|
-
target={"kind": "cuda", "arch": f"sm_{arch}"},
|
|
425
|
+
target={"kind": "cuda", "arch": f"sm_{arch}a" if arch == 90 else f"sm_{arch}"},
|
|
426
426
|
pass_configs=_PASS_CONFIG,
|
|
427
427
|
)
|
|
428
428
|
|
|
@@ -501,7 +501,7 @@ def _nora_kernel(rank, channels, dtype, strides, backward, arch):
|
|
|
501
501
|
|
|
502
502
|
return tilelang.compile(
|
|
503
503
|
normalize,
|
|
504
|
-
target={"kind": "cuda", "arch": f"sm_{arch}"},
|
|
504
|
+
target={"kind": "cuda", "arch": f"sm_{arch}a" if arch == 90 else f"sm_{arch}"},
|
|
505
505
|
pass_configs=_PASS_CONFIG,
|
|
506
506
|
)
|
|
507
507
|
|
|
@@ -616,8 +616,7 @@ def linear(x, weight, bias=None, output_dtype=None):
|
|
|
616
616
|
raise ValueError(
|
|
617
617
|
"linear expects x [...,in_features], weight [out_features,in_features]"
|
|
618
618
|
)
|
|
619
|
-
|
|
620
|
-
if output_dtype not in (torch.bfloat16, torch.float32):
|
|
619
|
+
if output_dtype not in (None, torch.bfloat16, torch.float32):
|
|
621
620
|
raise ValueError("linear output_dtype must be bfloat16 or float32")
|
|
622
621
|
if bias is not None and (
|
|
623
622
|
bias.shape != (weight.shape[0],)
|
|
@@ -625,6 +624,11 @@ def linear(x, weight, bias=None, output_dtype=None):
|
|
|
625
624
|
or bias.dtype not in (torch.bfloat16, torch.float32)
|
|
626
625
|
):
|
|
627
626
|
raise ValueError("linear bias must be [out_features], BF16/FP32, on x's device")
|
|
627
|
+
return _linear(x, weight, bias, output_dtype)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _linear(x, weight, bias=None, output_dtype=None):
|
|
631
|
+
output_dtype = torch.bfloat16 if output_dtype is None else output_dtype
|
|
628
632
|
operation = _compiled_linear if torch.compiler.is_compiling() else _Linear.apply
|
|
629
633
|
result = operation(
|
|
630
634
|
x.reshape(-1, x.shape[-1]).contiguous(),
|
|
@@ -645,6 +649,25 @@ def check_adapter_scale(scale):
|
|
|
645
649
|
return value
|
|
646
650
|
|
|
647
651
|
|
|
652
|
+
def check_adapter_parameters(a, b, scale, weight, device):
|
|
653
|
+
if (a is None) != (b is None):
|
|
654
|
+
raise ValueError("adapter A and B must be provided together")
|
|
655
|
+
if a is None:
|
|
656
|
+
return scale
|
|
657
|
+
if (
|
|
658
|
+
a.ndim != 2
|
|
659
|
+
or a.shape[0] == 0
|
|
660
|
+
or a.shape[1] != weight.shape[1]
|
|
661
|
+
or b.shape != (weight.shape[0], a.shape[0])
|
|
662
|
+
or a.device != device
|
|
663
|
+
or b.device != device
|
|
664
|
+
or a.dtype not in (torch.bfloat16, torch.float32)
|
|
665
|
+
or b.dtype not in (torch.bfloat16, torch.float32)
|
|
666
|
+
):
|
|
667
|
+
raise ValueError("adapter expects A [rank,in], B [out,rank], CUDA BF16/FP32")
|
|
668
|
+
return check_adapter_scale(scale)
|
|
669
|
+
|
|
670
|
+
|
|
648
671
|
def adapter_linear(
|
|
649
672
|
x,
|
|
650
673
|
weight,
|
|
@@ -655,6 +678,7 @@ def adapter_linear(
|
|
|
655
678
|
output_dtype=None,
|
|
656
679
|
*,
|
|
657
680
|
base_result=None,
|
|
681
|
+
_validated=False,
|
|
658
682
|
):
|
|
659
683
|
"""Project through a base weight and differentiable LoRA/NoRA parameters.
|
|
660
684
|
|
|
@@ -662,28 +686,17 @@ def adapter_linear(
|
|
|
662
686
|
training contract. Both modes round A/B and the intermediate features to
|
|
663
687
|
BF16. The adapter's second projection, scaling and addition use FP32.
|
|
664
688
|
"""
|
|
665
|
-
|
|
666
|
-
|
|
689
|
+
project = _linear if _validated else linear
|
|
690
|
+
if not _validated:
|
|
691
|
+
scale = check_adapter_parameters(a, b, scale, weight, x.device)
|
|
667
692
|
if a is None:
|
|
668
693
|
return (
|
|
669
|
-
|
|
694
|
+
project(x, weight, output_dtype=output_dtype)
|
|
670
695
|
if base_result is None
|
|
671
696
|
else base_result
|
|
672
697
|
)
|
|
673
|
-
if (
|
|
674
|
-
a.ndim != 2
|
|
675
|
-
or b.ndim != 2
|
|
676
|
-
or a.shape[1] != weight.shape[1]
|
|
677
|
-
or b.shape != (weight.shape[0], a.shape[0])
|
|
678
|
-
or a.device != x.device
|
|
679
|
-
or b.device != x.device
|
|
680
|
-
or a.dtype not in (torch.bfloat16, torch.float32)
|
|
681
|
-
or b.dtype not in (torch.bfloat16, torch.float32)
|
|
682
|
-
):
|
|
683
|
-
raise ValueError("adapter expects A [rank,in], B [out,rank], CUDA BF16/FP32")
|
|
684
|
-
scale = check_adapter_scale(scale)
|
|
685
698
|
result = (
|
|
686
|
-
|
|
699
|
+
project(x, weight, output_dtype=output_dtype)
|
|
687
700
|
if base_result is None
|
|
688
701
|
else base_result
|
|
689
702
|
)
|
|
@@ -691,7 +704,7 @@ def adapter_linear(
|
|
|
691
704
|
normalized = _compiled_nora(a)[0] if torch.compiler.is_compiling() else _NoRA.apply(a)
|
|
692
705
|
else:
|
|
693
706
|
normalized = a.to(torch.bfloat16)
|
|
694
|
-
features =
|
|
695
|
-
update =
|
|
707
|
+
features = project(x, normalized)
|
|
708
|
+
update = project(features, b.to(torch.bfloat16), output_dtype=torch.float32)
|
|
696
709
|
operation = _compiled_adapter_add if torch.compiler.is_compiling() else _AdapterAdd.apply
|
|
697
710
|
return operation(result, update, scale)
|
|
@@ -6,7 +6,6 @@ import tilelang.language as T
|
|
|
6
6
|
import torch
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
|
|
10
9
|
def check_cuda_condition(condition, message):
|
|
11
10
|
"""Validate device metadata without host reads in compiled/captured calls."""
|
|
12
11
|
if torch.compiler.is_compiling() or torch.cuda.is_current_stream_capturing():
|
|
@@ -15,6 +14,15 @@ def check_cuda_condition(condition, message):
|
|
|
15
14
|
raise ValueError(message)
|
|
16
15
|
|
|
17
16
|
|
|
17
|
+
def check_cu_seqlens(cu_seqlens, total_tokens):
|
|
18
|
+
"""Assert packed boundaries on the device before launching a training kernel."""
|
|
19
|
+
torch._assert_async(
|
|
20
|
+
(cu_seqlens[0] == 0) & (cu_seqlens[-1] == total_tokens)
|
|
21
|
+
& (cu_seqlens[1:] >= cu_seqlens[:-1]).all(),
|
|
22
|
+
"cu_seqlens must be nondecreasing and span [0,N]",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
18
26
|
@tilelang.jit(pass_configs={"tl.enable_fast_math": False})
|
|
19
27
|
def _transfer(channels: int, dtype: str, write: bool):
|
|
20
28
|
slots, batch = T.dynamic("slots, batch")
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""ChannelMix with one BF16 forward for training and packed inference."""
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _check_projection(x, key_weight, value_weight, adapters):
|
|
8
|
+
from .._internal.linear import check_adapter_parameters
|
|
9
|
+
|
|
10
|
+
if x.ndim != 2 or x.numel() == 0:
|
|
11
|
+
raise ValueError("CMix projection input must have nonempty shape [rows,C]")
|
|
12
|
+
channels = x.shape[1]
|
|
13
|
+
if (
|
|
14
|
+
key_weight.ndim != 2
|
|
15
|
+
or key_weight.shape[1] != channels
|
|
16
|
+
or key_weight.shape[0] == 0
|
|
17
|
+
or value_weight.shape != (channels, key_weight.shape[0])
|
|
18
|
+
):
|
|
19
|
+
raise ValueError("CMix projection requires key_weight [F,C] and value_weight [C,F]")
|
|
20
|
+
if any(t.dtype != torch.bfloat16 or t.device != x.device for t in (key_weight, value_weight)):
|
|
21
|
+
raise ValueError("CMix weights must be bfloat16 and share x's device")
|
|
22
|
+
return tuple(
|
|
23
|
+
(a, b, check_adapter_parameters(a, b, scale, weight, x.device), use_nora)
|
|
24
|
+
for weight, (a, b, scale, use_nora) in zip((key_weight, value_weight), adapters, strict=True)
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _project(mixed, key_weight, value_weight, adapters):
|
|
29
|
+
from .._internal.elementwise import activation
|
|
30
|
+
from .._internal.linear import adapter_linear
|
|
31
|
+
|
|
32
|
+
key_adapter, value_adapter = adapters
|
|
33
|
+
features = adapter_linear(mixed, key_weight, *key_adapter, _validated=True)
|
|
34
|
+
return adapter_linear(activation(features, "relu2"), value_weight, *value_adapter, _validated=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def infer_cmix_forward_varlen(
|
|
38
|
+
x,
|
|
39
|
+
res,
|
|
40
|
+
weight,
|
|
41
|
+
bias,
|
|
42
|
+
x_k,
|
|
43
|
+
key_weight,
|
|
44
|
+
value_weight,
|
|
45
|
+
*,
|
|
46
|
+
shift_state_pool,
|
|
47
|
+
cu_seqlens,
|
|
48
|
+
state_indices,
|
|
49
|
+
max_seqlen=None,
|
|
50
|
+
eps=1.0e-5,
|
|
51
|
+
validated_metadata=None,
|
|
52
|
+
deterministic=False,
|
|
53
|
+
key_lora_a=None,
|
|
54
|
+
key_lora_b=None,
|
|
55
|
+
value_lora_a=None,
|
|
56
|
+
value_lora_b=None,
|
|
57
|
+
key_lora_scale=1.0,
|
|
58
|
+
value_lora_scale=1.0,
|
|
59
|
+
key_use_nora=False,
|
|
60
|
+
value_use_nora=False,
|
|
61
|
+
save_normalized: torch.Tensor | None = None,
|
|
62
|
+
):
|
|
63
|
+
"""Apply res/ln, TokenShift, ReLU² and projection to packed rows.
|
|
64
|
+
|
|
65
|
+
The inference value weight retains its runtime [F,C] layout. A transpose
|
|
66
|
+
view feeds the same projection as the training [C,F] weight.
|
|
67
|
+
``save_normalized`` optionally receives the BF16 shift state of each
|
|
68
|
+
active input row.
|
|
69
|
+
"""
|
|
70
|
+
from ..tmix.tokenshift import _postnorm_tokenshift_varlen
|
|
71
|
+
|
|
72
|
+
value_weight = value_weight.t()
|
|
73
|
+
adapters = _check_projection(
|
|
74
|
+
x, key_weight, value_weight,
|
|
75
|
+
adapters=(
|
|
76
|
+
(key_lora_a, key_lora_b, key_lora_scale, key_use_nora),
|
|
77
|
+
(value_lora_a, value_lora_b, value_lora_scale, value_use_nora),
|
|
78
|
+
),
|
|
79
|
+
)
|
|
80
|
+
return _postnorm_tokenshift_varlen(
|
|
81
|
+
x, res, weight, bias, (x_k,), shift_state_pool, cu_seqlens, state_indices,
|
|
82
|
+
max_seqlen, eps, validated_metadata, save_normalized=save_normalized,
|
|
83
|
+
save_inputs=(key_weight, value_weight, key_lora_a, key_lora_b, value_lora_a, value_lora_b),
|
|
84
|
+
project=lambda mixed: _project(mixed[0], key_weight, value_weight, adapters),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def pretrain_cmix_bf16(
|
|
89
|
+
x,
|
|
90
|
+
x_k,
|
|
91
|
+
key_weight,
|
|
92
|
+
value_weight,
|
|
93
|
+
*,
|
|
94
|
+
initial_shift=None,
|
|
95
|
+
cu_seqlens: torch.Tensor | None = None,
|
|
96
|
+
return_final_state=False,
|
|
97
|
+
key_lora_a=None,
|
|
98
|
+
key_lora_b=None,
|
|
99
|
+
value_lora_a=None,
|
|
100
|
+
value_lora_b=None,
|
|
101
|
+
key_lora_scale=1.0,
|
|
102
|
+
value_lora_scale=1.0,
|
|
103
|
+
key_use_nora=False,
|
|
104
|
+
value_use_nora=False,
|
|
105
|
+
):
|
|
106
|
+
"""Apply ChannelMix to dense [B,T,C] or packed [N,C] rows with differentiable shift state."""
|
|
107
|
+
from ..tmix.tokenshift.tilelang import tokenshift
|
|
108
|
+
|
|
109
|
+
packed = cu_seqlens is not None
|
|
110
|
+
rows = x
|
|
111
|
+
if cu_seqlens is None:
|
|
112
|
+
if x.ndim != 3:
|
|
113
|
+
raise ValueError("CMix training input must have shape [B,T,C]")
|
|
114
|
+
batch, tokens, _ = x.shape
|
|
115
|
+
cu_seqlens = torch.arange(batch + 1, device=x.device, dtype=torch.int32) * tokens
|
|
116
|
+
rows = x.flatten(0, -2)
|
|
117
|
+
adapters = _check_projection(
|
|
118
|
+
rows, key_weight, value_weight,
|
|
119
|
+
adapters=(
|
|
120
|
+
(key_lora_a, key_lora_b, key_lora_scale, key_use_nora),
|
|
121
|
+
(value_lora_a, value_lora_b, value_lora_scale, value_use_nora),
|
|
122
|
+
),
|
|
123
|
+
)
|
|
124
|
+
(mixed,), final = tokenshift(rows, (x_k,), cu_seqlens, initial_shift, _check_cu=packed)
|
|
125
|
+
output = _project(mixed, key_weight, value_weight, adapters).view_as(x)
|
|
126
|
+
return (output, final) if return_final_state else output
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
__all__ = ["infer_cmix_forward_varlen", "pretrain_cmix_bf16"]
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
"""Single-request LightMTP drafting with reusable CUDA Graph inputs and outputs."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn.functional as F
|
|
11
|
+
from torch import nn
|
|
12
|
+
|
|
13
|
+
from .._internal.linear import linear
|
|
14
|
+
from ..head.linear import infer_head_linear_all_forward_varlen
|
|
15
|
+
|
|
16
|
+
_NORMS = ("norm_e", "norm_h", "norm_mlp", "norm_out")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DraftLoop(nn.Module):
|
|
20
|
+
"""Run a shared LightMTP block and an FP32 LM head for each draft token.
|
|
21
|
+
|
|
22
|
+
The embedding callable accepts CUDA int64 `[1]` and produces CUDA BF16
|
|
23
|
+
`[1,C]` on the loop's device. Each call returns the same `[1,depth]` output
|
|
24
|
+
buffer. Clone it when results must survive another call on this instance.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
state: Mapping[str, torch.Tensor],
|
|
30
|
+
lm_head_weight: torch.Tensor,
|
|
31
|
+
*,
|
|
32
|
+
depth: int,
|
|
33
|
+
eps: float = 1e-5,
|
|
34
|
+
) -> None:
|
|
35
|
+
super().__init__()
|
|
36
|
+
if not isinstance(depth, int) or isinstance(depth, bool) or depth <= 0:
|
|
37
|
+
raise ValueError("depth must be a positive integer")
|
|
38
|
+
if not math.isfinite(eps) or eps <= 0:
|
|
39
|
+
raise ValueError("eps must be finite and positive")
|
|
40
|
+
if (
|
|
41
|
+
not isinstance(lm_head_weight, torch.Tensor) or lm_head_weight.ndim != 2
|
|
42
|
+
or lm_head_weight.numel() == 0 or not lm_head_weight.is_floating_point()
|
|
43
|
+
):
|
|
44
|
+
raise ValueError("lm_head_weight must be a nonempty floating-point [V,C] tensor")
|
|
45
|
+
|
|
46
|
+
channels = lm_head_weight.shape[1]
|
|
47
|
+
device = lm_head_weight.device
|
|
48
|
+
gate = state.get("block.gate.weight")
|
|
49
|
+
if not isinstance(gate, torch.Tensor) or gate.ndim != 2 or gate.shape[0] == 0:
|
|
50
|
+
raise ValueError("block.gate.weight must be a nonempty [F,C] tensor")
|
|
51
|
+
features = gate.shape[0]
|
|
52
|
+
shapes = {
|
|
53
|
+
"proj.weight": (channels, 2 * channels),
|
|
54
|
+
"gate.weight": (features, channels),
|
|
55
|
+
"up.weight": (features, channels),
|
|
56
|
+
"down.weight": (channels, features),
|
|
57
|
+
}
|
|
58
|
+
for name in _NORMS:
|
|
59
|
+
shapes[f"{name}.weight"] = shapes[f"{name}.bias"] = (channels,)
|
|
60
|
+
|
|
61
|
+
weights = {}
|
|
62
|
+
for name, shape in shapes.items():
|
|
63
|
+
key = f"block.{name}"
|
|
64
|
+
weight = state.get(key)
|
|
65
|
+
if (
|
|
66
|
+
not isinstance(weight, torch.Tensor) or weight.shape != shape
|
|
67
|
+
or not weight.is_floating_point()
|
|
68
|
+
):
|
|
69
|
+
raise ValueError(f"{key} must be a floating-point tensor with shape {shape}")
|
|
70
|
+
weights[name.replace(".", "_")] = nn.Parameter(
|
|
71
|
+
weight.detach().to(device=device, dtype=torch.bfloat16).contiguous(),
|
|
72
|
+
requires_grad=False,
|
|
73
|
+
)
|
|
74
|
+
self._weights = nn.ParameterDict(weights)
|
|
75
|
+
self.lm_head = nn.Parameter(
|
|
76
|
+
lm_head_weight.detach().to(dtype=torch.bfloat16).contiguous(), requires_grad=False,
|
|
77
|
+
)
|
|
78
|
+
self.hidden_size = channels
|
|
79
|
+
self.depth = depth
|
|
80
|
+
self.eps = float(eps)
|
|
81
|
+
self._buffers_for_draft: tuple[torch.Tensor, ...] | None = None
|
|
82
|
+
self._captured: tuple[torch.cuda.CUDAGraph, Callable] | None = None
|
|
83
|
+
|
|
84
|
+
@classmethod
|
|
85
|
+
def from_state_dict(
|
|
86
|
+
cls,
|
|
87
|
+
state: Mapping[str, torch.Tensor],
|
|
88
|
+
lm_head_weight: torch.Tensor,
|
|
89
|
+
*,
|
|
90
|
+
depth: int,
|
|
91
|
+
eps: float = 1e-5,
|
|
92
|
+
) -> DraftLoop:
|
|
93
|
+
"""Build from the sidecar's `block.*` weight mapping."""
|
|
94
|
+
return cls(state, lm_head_weight, depth=depth, eps=eps)
|
|
95
|
+
|
|
96
|
+
def _apply(self, fn, recurse=True):
|
|
97
|
+
self._captured = None
|
|
98
|
+
self._buffers_for_draft = None
|
|
99
|
+
return super()._apply(fn, recurse=recurse)
|
|
100
|
+
|
|
101
|
+
def _load_from_state_dict(self, *args, **kwargs):
|
|
102
|
+
self._captured = None
|
|
103
|
+
self._buffers_for_draft = None
|
|
104
|
+
super()._load_from_state_dict(*args, **kwargs)
|
|
105
|
+
|
|
106
|
+
def _workspace(self):
|
|
107
|
+
if self._buffers_for_draft is None:
|
|
108
|
+
if not self.lm_head.is_cuda or self.lm_head.dtype != torch.bfloat16:
|
|
109
|
+
raise ValueError("DraftLoop weights must be CUDA bfloat16 before execution")
|
|
110
|
+
self._buffers_for_draft = (
|
|
111
|
+
self.lm_head.new_zeros((1, self.hidden_size)),
|
|
112
|
+
self.lm_head.new_zeros((1,), dtype=torch.int64),
|
|
113
|
+
self.lm_head.new_empty((1, 2 * self.hidden_size)),
|
|
114
|
+
self.lm_head.new_empty((1, self.depth), dtype=torch.int64),
|
|
115
|
+
)
|
|
116
|
+
return self._buffers_for_draft
|
|
117
|
+
|
|
118
|
+
def _load_inputs(self, hidden, token_ids, workspace):
|
|
119
|
+
device = self.lm_head.device
|
|
120
|
+
if (hidden.shape not in ((self.hidden_size,), (1, self.hidden_size))
|
|
121
|
+
or hidden.device != device or hidden.dtype != torch.bfloat16):
|
|
122
|
+
raise ValueError("hidden must be CUDA bfloat16 [1,C] or [C] on the loop device")
|
|
123
|
+
if token_ids.shape not in ((), (1,)) or token_ids.device != device or token_ids.dtype != torch.int64:
|
|
124
|
+
raise ValueError("token_ids must be a CUDA int64 scalar or [1] on the loop device")
|
|
125
|
+
workspace[0].copy_(hidden.reshape(1, self.hidden_size))
|
|
126
|
+
workspace[1].copy_(token_ids.reshape(1))
|
|
127
|
+
|
|
128
|
+
def _draft(self, embed, workspace):
|
|
129
|
+
from ..post_norm.tilelang import norm
|
|
130
|
+
|
|
131
|
+
hidden, token, joined, drafts = workspace
|
|
132
|
+
weights = self._weights
|
|
133
|
+
channels = self.hidden_size
|
|
134
|
+
|
|
135
|
+
def normalize(x, name):
|
|
136
|
+
return norm(x, weights[f"{name}_weight"], weights[f"{name}_bias"], self.eps)
|
|
137
|
+
|
|
138
|
+
for step in range(self.depth):
|
|
139
|
+
joined[:, :channels].copy_(normalize(embed(token), "norm_e"))
|
|
140
|
+
joined[:, channels:].copy_(normalize(hidden, "norm_h"))
|
|
141
|
+
x = hidden + linear(joined, weights["proj_weight"])
|
|
142
|
+
mlp = normalize(x, "norm_mlp")
|
|
143
|
+
gate = linear(mlp, weights["gate_weight"])
|
|
144
|
+
up = linear(mlp, weights["up_weight"])
|
|
145
|
+
hidden = x + linear(F.silu(gate) * up, weights["down_weight"])
|
|
146
|
+
logits = infer_head_linear_all_forward_varlen(normalize(hidden, "norm_out"), self.lm_head)
|
|
147
|
+
torch.argmax(logits, dim=-1, out=token)
|
|
148
|
+
drafts[:, step].copy_(token)
|
|
149
|
+
return drafts
|
|
150
|
+
|
|
151
|
+
@torch.no_grad()
|
|
152
|
+
def forward(
|
|
153
|
+
self, hidden: torch.Tensor, token_ids: torch.Tensor, embed: Callable,
|
|
154
|
+
) -> torch.Tensor:
|
|
155
|
+
"""Run the draft loop eagerly."""
|
|
156
|
+
workspace = self._workspace()
|
|
157
|
+
self._load_inputs(hidden, token_ids, workspace)
|
|
158
|
+
return self._draft(embed, workspace)
|
|
159
|
+
|
|
160
|
+
@torch.no_grad()
|
|
161
|
+
def capture(self, embed: Callable) -> None:
|
|
162
|
+
"""Warm and capture the draft loop for this embedding and device."""
|
|
163
|
+
if self._captured is not None:
|
|
164
|
+
if embed is not self._captured[1]:
|
|
165
|
+
raise ValueError("this DraftLoop is already captured with a different embedding")
|
|
166
|
+
return
|
|
167
|
+
workspace = self._workspace()
|
|
168
|
+
device = self.lm_head.device
|
|
169
|
+
with torch.cuda.device(device):
|
|
170
|
+
current = torch.cuda.current_stream()
|
|
171
|
+
side = torch.cuda.Stream()
|
|
172
|
+
side.wait_stream(current)
|
|
173
|
+
with torch.cuda.stream(side):
|
|
174
|
+
workspace[0].zero_()
|
|
175
|
+
workspace[1].zero_()
|
|
176
|
+
self._draft(embed, workspace)
|
|
177
|
+
current.wait_stream(side)
|
|
178
|
+
graph = torch.cuda.CUDAGraph()
|
|
179
|
+
with torch.cuda.graph(graph, stream=side):
|
|
180
|
+
self._draft(embed, workspace)
|
|
181
|
+
self._captured = (graph, embed)
|
|
182
|
+
|
|
183
|
+
@torch.no_grad()
|
|
184
|
+
def replay(self, hidden: torch.Tensor, token_ids: torch.Tensor) -> torch.Tensor:
|
|
185
|
+
"""Replay on the current stream using staged device inputs."""
|
|
186
|
+
if self._captured is None:
|
|
187
|
+
raise RuntimeError("capture() must run before replay()")
|
|
188
|
+
workspace = self._workspace()
|
|
189
|
+
self._load_inputs(hidden, token_ids, workspace)
|
|
190
|
+
self._captured[0].replay()
|
|
191
|
+
return workspace[3]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
__all__ = ["DraftLoop"]
|