Text Generation
Transformers
English
multilingual
inkling2_loop
image-text-to-text
prime-quant
2-bit
4-bit precision
Mixture of Experts
inkling-2
inkling-2-mini
looped-transformer
triton
rocm
cuda
quantization
coding
openai-compatible
conversational
Instructions to use batteryphil/Inkling-2-Mini-PRIME-Quant with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="batteryphil/Inkling-2-Mini-PRIME-Quant") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("batteryphil/Inkling-2-Mini-PRIME-Quant") model = AutoModelForMultimodalLM.from_pretrained("batteryphil/Inkling-2-Mini-PRIME-Quant", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "batteryphil/Inkling-2-Mini-PRIME-Quant" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "batteryphil/Inkling-2-Mini-PRIME-Quant", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/batteryphil/Inkling-2-Mini-PRIME-Quant
- SGLang
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "batteryphil/Inkling-2-Mini-PRIME-Quant" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "batteryphil/Inkling-2-Mini-PRIME-Quant", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "batteryphil/Inkling-2-Mini-PRIME-Quant" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "batteryphil/Inkling-2-Mini-PRIME-Quant", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use batteryphil/Inkling-2-Mini-PRIME-Quant with Docker Model Runner:
docker model run hf.co/batteryphil/Inkling-2-Mini-PRIME-Quant
File size: 52,524 Bytes
53ce2f5 | 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 | # Copyright (c) 2026 Philip Bartsch (@batteryphil).
# Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE).
"""
True In-VRAM Compressed PyTorch + Triton Runtime (`PrimeLiveModule`)
====================================================================
Keeps weights permanently compressed in GPU VRAM (`2.50 bpw` `Q2_G32` / `P2_G32` or `4.50 bpw` `P4_G32`)
and dequantizes on-the-fly per layer forward pass with zero persistent `FP16`/`BF16` weight copy!
Supports `linear`, `embedding`, `conv2d`, and `conv3d`, plus `<1.5s` `torch.device("meta")`
SafeTensors v2 serialization and loading.
"""
from __future__ import annotations
import os
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors import safe_open
P2_LUT_LIST: List[float] = [-23.0, -7.0, 5.0, 17.0]
P4_LUT_LIST: List[float] = [
-127.0, -101.0, -80.0, -62.0, -46.0, -33.0, -21.0, -10.0,
0.0, 10.0, 21.0, 33.0, 46.0, 62.0, 80.0, 101.0,
]
_BYTE_LUT_CACHE: Dict[Tuple[torch.device, torch.dtype, str], torch.Tensor] = {}
_TRITON_LUT_CACHE: Dict[Tuple[torch.device, str], torch.Tensor] = {}
try:
import triton as _triton
import triton.language as _tl
@_triton.jit
def _unpack_p4_g32_triton(
qp_ptr,
df_ptr,
lut_ptr,
out_ptr,
n_blocks,
BLOCK_B: _tl.constexpr,
):
pid = _tl.program_id(0)
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
b_mask = b < n_blocks
scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
offs16 = _tl.arange(0, 16)
byte_idx = b[:, None] * 16 + offs16[None, :]
packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32)
v_lo = _tl.load(lut_ptr + (packed & 0x0F)) * scale[:, None]
v_hi = _tl.load(lut_ptr + ((packed >> 4) & 0x0F)) * scale[:, None]
v_full = _tl.interleave(v_lo, v_hi).to(out_ptr.dtype.element_ty)
offs32 = _tl.arange(0, 32)
out_idx = b[:, None] * 32 + offs32[None, :]
_tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None])
@_triton.jit
def _unpack_q2_g32_triton(
qp_ptr,
df_ptr,
out_ptr,
n_blocks,
BLOCK_B: _tl.constexpr,
):
pid = _tl.program_id(0)
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
b_mask = b < n_blocks
scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
offs8 = _tl.arange(0, 8)
byte_idx = b[:, None] * 8 + offs8[None, :]
packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32)
c0 = ((packed & 0x03) - 2).to(_tl.float32) * scale[:, None]
c1 = (((packed >> 2) & 0x03) - 2).to(_tl.float32) * scale[:, None]
c2 = (((packed >> 4) & 0x03) - 2).to(_tl.float32) * scale[:, None]
c3 = (((packed >> 6) & 0x03) - 2).to(_tl.float32) * scale[:, None]
ce = _tl.interleave(c0, c2)
co = _tl.interleave(c1, c3)
v_full = _tl.interleave(ce, co).to(out_ptr.dtype.element_ty)
offs32 = _tl.arange(0, 32)
out_idx = b[:, None] * 32 + offs32[None, :]
_tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None])
@_triton.jit
def _unpack_p2_g32_triton(
qp_ptr,
df_ptr,
lut_ptr,
out_ptr,
n_blocks,
BLOCK_B: _tl.constexpr,
):
pid = _tl.program_id(0)
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
b_mask = b < n_blocks
scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
offs8 = _tl.arange(0, 8)
byte_idx = b[:, None] * 8 + offs8[None, :]
packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32)
c0 = _tl.load(lut_ptr + (packed & 0x03)) * scale[:, None]
c1 = _tl.load(lut_ptr + ((packed >> 2) & 0x03)) * scale[:, None]
c2 = _tl.load(lut_ptr + ((packed >> 4) & 0x03)) * scale[:, None]
c3 = _tl.load(lut_ptr + ((packed >> 6) & 0x03)) * scale[:, None]
ce = _tl.interleave(c0, c2)
co = _tl.interleave(c1, c3)
v_full = _tl.interleave(ce, co).to(out_ptr.dtype.element_ty)
offs32 = _tl.arange(0, 32)
out_idx = b[:, None] * 32 + offs32[None, :]
_tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None])
@_triton.jit
def _dequant_p4_i8_triton(
q_ptr,
d_ptr,
lut_ptr,
out_ptr,
n_blocks,
BLOCK_B: _tl.constexpr,
):
pid = _tl.program_id(0)
b = pid * BLOCK_B + _tl.arange(0, BLOCK_B)
b_mask = b < n_blocks
scale = _tl.load(d_ptr + b, mask=b_mask, other=0.0).to(_tl.float32)
offs32 = _tl.arange(0, 32)
idx = b[:, None] * 32 + offs32[None, :]
qi = _tl.load(q_ptr + idx, mask=b_mask[:, None], other=8).to(_tl.int32)
v_full = (_tl.load(lut_ptr + qi) * scale[:, None]).to(out_ptr.dtype.element_ty)
_tl.store(out_ptr + idx, v_full, mask=b_mask[:, None])
@_triton.jit
def _gemv_2bit_g32_triton(
x_ptr,
qp_ptr,
df_ptr,
lut_ptr,
bias_ptr,
e_ids_ptr,
out_ptr,
rows,
cols_real,
pack_cols,
n_groups,
num_experts,
stride_qe,
stride_de,
stride_xk,
IS_MOE: _tl.constexpr,
HAS_BIAS: _tl.constexpr,
BLOCK_R: _tl.constexpr,
GROUPS_K: _tl.constexpr,
):
pid_r = _tl.program_id(0)
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
r_mask = r < rows
r_i64 = r.to(_tl.int64)
if IS_MOE:
pid_k = _tl.program_id(1)
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
qp_base = e_idx * stride_qe
df_base = e_idx * stride_de
x_base = pid_k.to(_tl.int64) * stride_xk
out_base = pid_k.to(_tl.int64) * rows
else:
qp_base = _tl.cast(0, _tl.int64)
df_base = _tl.cast(0, _tl.int64)
x_base = _tl.cast(0, _tl.int64)
out_base = _tl.cast(0, _tl.int64)
acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
g_offs = _tl.arange(0, GROUPS_K)
b_offs = _tl.arange(0, GROUPS_K * 8)
x_offs = _tl.arange(0, GROUPS_K * 32)
for g0 in range(0, n_groups, GROUPS_K):
g = g0 + g_offs
g_mask = g < n_groups
df_off = df_base + r_i64[:, None] * n_groups + g[None, :]
scale = _tl.load(df_ptr + df_off, mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
xc = g0 * 32 + x_offs
xv = _tl.load(x_ptr + x_base + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
xe, xo = _tl.split(xv.reshape(GROUPS_K * 16, 2))
x0, x2 = _tl.split(xe.reshape(GROUPS_K * 8, 2))
x1, x3 = _tl.split(xo.reshape(GROUPS_K * 8, 2))
k_byte = g0 * 8 + b_offs
kb_mask = k_byte < pack_cols
qp_off = qp_base + r_i64[:, None] * pack_cols + k_byte[None, :]
packed = _tl.load(qp_ptr + qp_off, mask=r_mask[:, None] & kb_mask[None, :], other=0).to(_tl.int32)
# L0-cached 16-byte 4-float LUT decode (matches P4 throughput, beats 32-op VALU arithmetic by 1.45x on RDNA4)
v0 = _tl.load(lut_ptr + (packed & 0x03))
v1 = _tl.load(lut_ptr + ((packed >> 2) & 0x03))
v2 = _tl.load(lut_ptr + ((packed >> 4) & 0x03))
v3 = _tl.load(lut_ptr + ((packed >> 6) & 0x03))
dot = (v0 * x0[None, :] + v1 * x1[None, :] + v2 * x2[None, :] + v3 * x3[None, :]).reshape(
BLOCK_R, GROUPS_K, 8
)
acc += _tl.sum(_tl.sum(dot, axis=2) * scale, axis=1)
if HAS_BIAS:
acc += _tl.load(bias_ptr + r, mask=r_mask, other=0.0).to(_tl.float32)
_tl.store(out_ptr + out_base + r_i64, acc.to(out_ptr.dtype.element_ty), mask=r_mask)
@_triton.jit
def _gemv_p4_g32_triton(
x_ptr,
qp_ptr,
df_ptr,
lut_ptr,
bias_ptr,
e_ids_ptr,
out_ptr,
rows,
cols_real,
pack_cols,
n_groups,
num_experts,
stride_qe,
stride_de,
stride_xk,
IS_MOE: _tl.constexpr,
HAS_BIAS: _tl.constexpr,
BLOCK_R: _tl.constexpr,
GROUPS_K: _tl.constexpr,
):
pid_r = _tl.program_id(0)
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
r_mask = r < rows
r_i64 = r.to(_tl.int64)
if IS_MOE:
pid_k = _tl.program_id(1)
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
qp_base = e_idx * stride_qe
df_base = e_idx * stride_de
x_base = pid_k.to(_tl.int64) * stride_xk
out_base = pid_k.to(_tl.int64) * rows
else:
qp_base = _tl.cast(0, _tl.int64)
df_base = _tl.cast(0, _tl.int64)
x_base = _tl.cast(0, _tl.int64)
out_base = _tl.cast(0, _tl.int64)
acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
g_offs = _tl.arange(0, GROUPS_K)
b_offs = _tl.arange(0, GROUPS_K * 16)
x_offs = _tl.arange(0, GROUPS_K * 32)
for g0 in range(0, n_groups, GROUPS_K):
g = g0 + g_offs
g_mask = g < n_groups
df_off = df_base + r_i64[:, None] * n_groups + g[None, :]
scale = _tl.load(df_ptr + df_off, mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
xc = g0 * 32 + x_offs
xv = _tl.load(x_ptr + x_base + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
x0, x1 = _tl.split(xv.reshape(GROUPS_K * 16, 2))
k_byte = g0 * 16 + b_offs
kb_mask = k_byte < pack_cols
qp_off = qp_base + r_i64[:, None] * pack_cols + k_byte[None, :]
packed = _tl.load(qp_ptr + qp_off, mask=r_mask[:, None] & kb_mask[None, :], other=0).to(_tl.int32)
v0 = _tl.load(lut_ptr + (packed & 0x0F))
v1 = _tl.load(lut_ptr + ((packed >> 4) & 0x0F))
dot = (v0 * x0[None, :] + v1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16)
acc += _tl.sum(_tl.sum(dot, axis=2) * scale, axis=1)
if HAS_BIAS:
acc += _tl.load(bias_ptr + r, mask=r_mask, other=0.0).to(_tl.float32)
_tl.store(out_ptr + out_base + r_i64, acc.to(out_ptr.dtype.element_ty), mask=r_mask)
@_triton.jit
def _moe_gu_act_2bit_triton(
x_ptr,
qp_ptr,
df_ptr,
lut_ptr,
e_ids_ptr,
out_ptr,
I_dim,
cols_real,
pack_cols,
n_groups,
num_experts,
stride_qe,
stride_de,
G_CAP: _tl.constexpr,
U_CAP: _tl.constexpr,
BLOCK_R: _tl.constexpr,
GROUPS_K: _tl.constexpr,
):
"""Fused paired gate+up 2-bit MoE GEMV + SwiGLU/SoftcappedSwiGLU epilogue (L0 4-float LUT, 300+ GB/s on RDNA4)."""
pid_r = _tl.program_id(0)
pid_k = _tl.program_id(1)
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
r_mask = r < I_dim
rg = r.to(_tl.int64)
ru = (r + I_dim).to(_tl.int64)
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
qp_base = e_idx * stride_qe
df_base = e_idx * stride_de
acc_g = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
acc_u = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
g_offs = _tl.arange(0, GROUPS_K)
b_offs = _tl.arange(0, GROUPS_K * 8)
x_offs = _tl.arange(0, GROUPS_K * 32)
for g0 in range(0, n_groups, GROUPS_K):
g = g0 + g_offs
g_mask = g < n_groups
sg = _tl.load(df_ptr + df_base + rg[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
su = _tl.load(df_ptr + df_base + ru[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
xc = g0 * 32 + x_offs
xv = _tl.load(x_ptr + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
xe, xo = _tl.split(xv.reshape(GROUPS_K * 16, 2))
x0, x2 = _tl.split(xe.reshape(GROUPS_K * 8, 2))
x1, x3 = _tl.split(xo.reshape(GROUPS_K * 8, 2))
kb = g0 * 8 + b_offs
kbm = kb < pack_cols
pg = _tl.load(qp_ptr + qp_base + rg[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
pu = _tl.load(qp_ptr + qp_base + ru[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
v0 = _tl.load(lut_ptr + (pg & 3))
v1 = _tl.load(lut_ptr + ((pg >> 2) & 3))
v2 = _tl.load(lut_ptr + ((pg >> 4) & 3))
v3 = _tl.load(lut_ptr + ((pg >> 6) & 3))
u0 = _tl.load(lut_ptr + (pu & 3))
u1 = _tl.load(lut_ptr + ((pu >> 2) & 3))
u2 = _tl.load(lut_ptr + ((pu >> 4) & 3))
u3 = _tl.load(lut_ptr + ((pu >> 6) & 3))
dg = (v0 * x0[None, :] + v1 * x1[None, :] + v2 * x2[None, :] + v3 * x3[None, :]).reshape(BLOCK_R, GROUPS_K, 8)
du = (u0 * x0[None, :] + u1 * x1[None, :] + u2 * x2[None, :] + u3 * x3[None, :]).reshape(BLOCK_R, GROUPS_K, 8)
acc_g += _tl.sum(_tl.sum(dg, axis=2) * sg, axis=1)
acc_u += _tl.sum(_tl.sum(du, axis=2) * su, axis=1)
tg = (2.0 * _tl.sigmoid(2.0 * (acc_g / G_CAP)) - 1.0) * G_CAP if G_CAP > 0.0 else acc_g
tu = (2.0 * _tl.sigmoid(2.0 * (acc_u / U_CAP)) - 1.0) * U_CAP if U_CAP > 0.0 else acc_u
res = tg * _tl.sigmoid(acc_g) * tu
_tl.store(out_ptr + pid_k.to(_tl.int64) * I_dim + rg, res.to(out_ptr.dtype.element_ty), mask=r_mask)
@_triton.jit
def _moe_gu_act_p4_triton(
x_ptr,
qp_ptr,
df_ptr,
lut_ptr,
e_ids_ptr,
out_ptr,
I_dim,
cols_real,
pack_cols,
n_groups,
num_experts,
stride_qe,
stride_de,
G_CAP: _tl.constexpr,
U_CAP: _tl.constexpr,
BLOCK_R: _tl.constexpr,
GROUPS_K: _tl.constexpr,
):
"""Fused paired gate+up P4_G32 MoE GEMV + SwiGLU/SoftcappedSwiGLU epilogue."""
pid_r = _tl.program_id(0)
pid_k = _tl.program_id(1)
r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R)
r_mask = r < I_dim
rg = r.to(_tl.int64)
ru = (r + I_dim).to(_tl.int64)
e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64)
e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1)
qp_base = e_idx * stride_qe
df_base = e_idx * stride_de
acc_g = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
acc_u = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
g_offs = _tl.arange(0, GROUPS_K)
b_offs = _tl.arange(0, GROUPS_K * 16)
x_offs = _tl.arange(0, GROUPS_K * 32)
for g0 in range(0, n_groups, GROUPS_K):
g = g0 + g_offs
g_mask = g < n_groups
sg = _tl.load(df_ptr + df_base + rg[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
su = _tl.load(df_ptr + df_base + ru[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32)
xc = g0 * 32 + x_offs
xv = _tl.load(x_ptr + xc, mask=xc < cols_real, other=0.0).to(_tl.float32)
x0, x1 = _tl.split(xv.reshape(GROUPS_K * 16, 2))
kb = g0 * 16 + b_offs
kbm = kb < pack_cols
pg = _tl.load(qp_ptr + qp_base + rg[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
pu = _tl.load(qp_ptr + qp_base + ru[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32)
vg0 = _tl.load(lut_ptr + (pg & 0x0F)); vg1 = _tl.load(lut_ptr + ((pg >> 4) & 0x0F))
vu0 = _tl.load(lut_ptr + (pu & 0x0F)); vu1 = _tl.load(lut_ptr + ((pu >> 4) & 0x0F))
dg = (vg0 * x0[None, :] + vg1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16)
du = (vu0 * x0[None, :] + vu1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16)
acc_g += _tl.sum(_tl.sum(dg, axis=2) * sg, axis=1)
acc_u += _tl.sum(_tl.sum(du, axis=2) * su, axis=1)
tg = (2.0 * _tl.sigmoid(2.0 * (acc_g / G_CAP)) - 1.0) * G_CAP if G_CAP > 0.0 else acc_g
tu = (2.0 * _tl.sigmoid(2.0 * (acc_u / U_CAP)) - 1.0) * U_CAP if U_CAP > 0.0 else acc_u
res = tg * _tl.sigmoid(acc_g) * tu
_tl.store(out_ptr + pid_k.to(_tl.int64) * I_dim + rg, res.to(out_ptr.dtype.element_ty), mask=r_mask)
@_triton.jit
def _moe_weighted_reduce_f32_triton(
x_f32_ptr,
e_ids_ptr,
w_tok_ptr,
out_ptr,
rows,
num_experts,
K_EXP: _tl.constexpr,
BLOCK_R: _tl.constexpr,
):
"""Fused FP32 masked weighted reduction across K active experts `[K, rows] -> [1, rows]` (~1.5 us in L2)."""
pid = _tl.program_id(0)
r = pid * BLOCK_R + _tl.arange(0, BLOCK_R)
rm = r < rows
r_i64 = r.to(_tl.int64)
acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32)
for k in range(0, K_EXP):
e_raw = _tl.load(e_ids_ptr + k).to(_tl.int64)
is_valid = (e_raw >= 0) & (e_raw < num_experts)
wk = _tl.where(is_valid, _tl.load(w_tok_ptr + k).to(_tl.float32), 0.0)
xv = _tl.load(x_f32_ptr + _tl.cast(k, _tl.int64) * rows + r_i64, mask=rm, other=0.0)
acc += wk * xv
_tl.store(out_ptr + r_i64, acc.to(out_ptr.dtype.element_ty), mask=rm)
_HAS_TRITON_UNPACK = True
except Exception:
_HAS_TRITON_UNPACK = False
def _get_triton_lut(device: torch.device, fmt: str = "p4_0") -> torch.Tensor:
key = (device, fmt)
lut = _TRITON_LUT_CACHE.get(key)
if lut is None:
if fmt == "p4_0":
vals = P4_LUT_LIST
elif fmt == "p2_0":
vals = P2_LUT_LIST
else:
vals = [-2.0, -1.0, 0.0, 1.0]
lut = torch.tensor(vals, device=device, dtype=torch.float32).contiguous()
_TRITON_LUT_CACHE[key] = lut
return lut
def _gemv_prime_g32_fast(
x_1d: torch.Tensor,
qp: torch.Tensor,
df: torch.Tensor,
bias: Optional[torch.Tensor],
fmt: str,
rows: int,
cols_real: int,
pcols: int,
) -> torch.Tensor:
"""Fused-register Triton GEMV (`y = W @ x + b`) — 64B cacheline-aligned, zero BF16 materialization."""
out = torch.empty((rows,), device=qp.device, dtype=x_1d.dtype)
x_c = x_1d.contiguous()
n_groups = pcols // 32
pack_cols = qp.shape[1]
has_bias = bias is not None
b_ptr = bias.contiguous() if has_bias else out
lut = _get_triton_lut(qp.device, fmt)
if fmt == "p4_0":
BLOCK_R = 8 if rows >= 256 else 4
grid = (_triton.cdiv(rows, BLOCK_R),)
_gemv_p4_g32_triton[grid](
x_c, qp, df, lut, b_ptr, out, out,
rows, cols_real, pack_cols, n_groups, 1, 0, 0, 0,
IS_MOE=False, HAS_BIAS=has_bias, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=2,
)
else:
BLOCK_R = 8 if rows >= 256 else 4
grid = (_triton.cdiv(rows, BLOCK_R),)
_gemv_2bit_g32_triton[grid](
x_c, qp, df, lut, b_ptr, out, out,
rows, cols_real, pack_cols, n_groups, 1, 0, 0, 0,
IS_MOE=False, HAS_BIAS=has_bias, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2,
)
return out
def _gemv_moe_g32_fast(
x: torch.Tensor,
qp_3d: torch.Tensor,
df_3d: torch.Tensor,
e_ids: torch.Tensor,
fmt: str,
rows: int,
cols_real: int,
pcols: int,
shared_x: bool,
) -> torch.Tensor:
"""Fused-register batched active-expert Triton GEMV (`[K, rows]`) — zero index_select, zero BF16 alloc."""
K = int(e_ids.shape[0])
num_experts = int(qp_3d.shape[0])
out = torch.empty((K, rows), device=qp_3d.device, dtype=x.dtype)
x_c = x.contiguous()
e_c = e_ids.contiguous()
n_groups = pcols // 32
pack_cols = int(qp_3d.shape[2])
stride_qe = int(qp_3d.stride(0))
stride_de = int(df_3d.stride(0))
stride_xk = 0 if shared_x else int(x_c.stride(0))
lut = _get_triton_lut(qp_3d.device, fmt)
if fmt == "p4_0":
BLOCK_R = 4
grid = (_triton.cdiv(rows, BLOCK_R), K)
_gemv_p4_g32_triton[grid](
x_c, qp_3d, df_3d, lut, out, e_c, out,
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
)
else:
BLOCK_R = 8 if rows >= 256 else 4
grid = (_triton.cdiv(rows, BLOCK_R), K)
_gemv_2bit_g32_triton[grid](
x_c, qp_3d, df_3d, lut, out, e_c, out,
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2,
)
return out
def _gemv_moe_gu_act_fast(
x_1d: torch.Tensor,
qp_3d: torch.Tensor,
df_3d: torch.Tensor,
e_ids: torch.Tensor,
fmt: str,
inter_dim: int,
cols_real: int,
pcols: int,
num_experts: int,
g_cap: float,
u_cap: float,
) -> torch.Tensor:
"""Fused paired gate+up Triton MoE GEMV + SwiGLU/SoftcappedSwiGLU -> `[K, inter_dim]` (300+ GB/s on RDNA4)."""
K = int(e_ids.shape[0])
out = torch.empty((K, inter_dim), device=qp_3d.device, dtype=x_1d.dtype)
x_c = x_1d.contiguous()
e_c = e_ids.contiguous()
n_groups = pcols // 32
pack_cols = int(qp_3d.shape[2])
stride_qe = int(qp_3d.stride(0))
stride_de = int(df_3d.stride(0))
lut = _get_triton_lut(qp_3d.device, fmt)
if fmt == "p4_0":
BLOCK_R = 4
grid = (_triton.cdiv(inter_dim, BLOCK_R), K)
_moe_gu_act_p4_triton[grid](
x_c, qp_3d, df_3d, lut, e_c, out,
inter_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de,
G_CAP=g_cap, U_CAP=u_cap, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
)
else:
BLOCK_R = 8 if inter_dim >= 64 else 4
grid = (_triton.cdiv(inter_dim, BLOCK_R), K)
_moe_gu_act_2bit_triton[grid](
x_c, qp_3d, df_3d, lut, e_c, out,
inter_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de,
G_CAP=g_cap, U_CAP=u_cap, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2,
)
return out
def _gemv_moe_dn_reduce_fast(
x_kh: torch.Tensor,
qp_3d: torch.Tensor,
df_3d: torch.Tensor,
e_ids: torch.Tensor,
w_tok: torch.Tensor,
fmt: str,
rows: int,
cols_real: int,
pcols: int,
num_experts: int,
) -> torch.Tensor:
"""Parallel-K down_proj Triton GEMV (FP32 L2 intermediate) + fused masked weighted reduce -> `[1, rows]`."""
K = int(e_ids.shape[0])
out_kh_f32 = torch.empty((K, rows), device=qp_3d.device, dtype=torch.float32)
out = torch.empty((1, rows), device=qp_3d.device, dtype=x_kh.dtype)
x_c = x_kh.contiguous()
e_c = e_ids.contiguous()
w_c = w_tok.contiguous()
n_groups = pcols // 32
pack_cols = int(qp_3d.shape[2])
stride_qe = int(qp_3d.stride(0))
stride_de = int(df_3d.stride(0))
stride_xk = int(x_c.stride(0))
lut = _get_triton_lut(qp_3d.device, fmt)
BLOCK_R = 4
grid = (_triton.cdiv(rows, BLOCK_R), K)
if fmt == "p4_0":
_gemv_p4_g32_triton[grid](
x_c, qp_3d, df_3d, lut, out_kh_f32, e_c, out_kh_f32,
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
)
else:
_gemv_2bit_g32_triton[grid](
x_c, qp_3d, df_3d, lut, out_kh_f32, e_c, out_kh_f32,
rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk,
IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1,
)
_moe_weighted_reduce_f32_triton[(_triton.cdiv(rows, 256),)](
out_kh_f32, e_c, w_c, out, rows, num_experts, K_EXP=K, BLOCK_R=256, num_warps=4,
)
return out
def _unpack_packed_2d_fast(
qp: torch.Tensor,
df: torch.Tensor,
fmt: str,
rows: int,
pcols: int,
group_size: int,
target_dtype: torch.dtype,
) -> torch.Tensor:
"""Fast Triton (G=32 on CUDA for p4_0/p2_0/q2_0) or byte-LUT fallback unpacker -> [rows, pcols]."""
if (
_HAS_TRITON_UNPACK
and qp.is_cuda
and group_size == 32
and fmt in ("p4_0", "p2_0", "q2_0")
and target_dtype in (torch.bfloat16, torch.float16, torch.float32)
and (pcols & 31) == 0
):
qp_c = qp.contiguous()
df_c = df.contiguous()
w2 = torch.empty((rows, pcols), device=qp.device, dtype=target_dtype)
nb = rows * (pcols // 32)
grid = (_triton.cdiv(nb, 32),)
if fmt == "p4_0":
_unpack_p4_g32_triton[grid](qp_c, df_c, _get_triton_lut(qp.device, "p4_0"), w2, nb, BLOCK_B=32)
elif fmt == "p2_0":
_unpack_p2_g32_triton[grid](qp_c, df_c, _get_triton_lut(qp.device, "p2_0"), w2, nb, BLOCK_B=32)
else:
_unpack_q2_g32_triton[grid](qp_c, df_c, w2, nb, BLOCK_B=32)
return w2
lut = _get_byte_lut(qp.device, torch.float32, fmt)
cv = F.embedding(qp.to(torch.int32), lut).view(rows, pcols // group_size, group_size)
return (cv * df.float().unsqueeze(-1)).to(target_dtype).view(rows, pcols)
def _get_byte_lut(device: torch.device, dtype: torch.dtype, fmt: str) -> torch.Tensor:
key = (device, dtype, fmt)
lut = _BYTE_LUT_CACHE.get(key)
if lut is None:
idx = torch.arange(256, dtype=torch.int32)
if fmt == "q2_0":
c0 = (idx & 0x03) - 2
c1 = ((idx >> 2) & 0x03) - 2
c2 = ((idx >> 4) & 0x03) - 2
c3 = ((idx >> 6) & 0x03) - 2
lut = torch.stack([c0, c1, c2, c3], dim=-1).to(device=device, dtype=dtype).contiguous()
elif fmt == "p2_0":
p2_t = torch.tensor(P2_LUT_LIST, dtype=torch.float32)
lut = torch.stack(
[p2_t[idx & 0x03], p2_t[(idx >> 2) & 0x03], p2_t[(idx >> 4) & 0x03], p2_t[(idx >> 6) & 0x03]], dim=-1
).to(device=device, dtype=dtype).contiguous()
else:
p4_t = torch.tensor(P4_LUT_LIST, dtype=torch.float32)
lut = torch.stack([p4_t[idx & 0x0F], p4_t[(idx >> 4) & 0x0F]], dim=-1).to(device=device, dtype=dtype).contiguous()
_BYTE_LUT_CACHE[key] = lut
return lut
def weight_to_2d_tap_separated(mod: nn.Module, G: int = 32) -> Tuple[torch.Tensor, int, int, Tuple[int, ...], bool]:
"""
Maps `Linear`, `Embedding`, `Conv2d`, or `Conv3d` weights to `[rows, pcols]` (`pcols % G == 0`),
isolating spatial/temporal `Conv2d`/`Conv3d` kernel taps `(kT, kH, kW)` into separate rows so
that every `G`-element quantization block lies strictly along `C_in` without cross-tap bleeding.
"""
w = mod.weight.detach().float()
orig_shape = tuple(w.shape)
if isinstance(mod, (nn.Linear, nn.Embedding)):
rows, cols = w.shape
tap_perm = False
w2 = w
elif isinstance(mod, (nn.Conv2d, nn.Conv3d)):
spatial_prod = 1
for d in orig_shape[2:]:
spatial_prod *= d
if spatial_prod > 1 and orig_shape[1] >= G and (orig_shape[1] % G == 0):
perm = [0] + list(range(2, len(orig_shape))) + [1]
w_p = w.permute(*perm).contiguous()
cols = orig_shape[1]
rows = w.numel() // cols
w2 = w_p.view(rows, cols)
tap_perm = True
else:
rows = orig_shape[0]
cols = w.numel() // rows
w2 = w.reshape(rows, cols)
tap_perm = False
else:
raise TypeError(f"Unsupported module type: {type(mod)}")
pad_c = (G - (cols % G)) % G
if pad_c > 0:
w2 = F.pad(w2, (0, pad_c), value=0.0)
return w2, rows, cols, orig_shape, tap_perm
def reconstruct_from_2d(w2: torch.Tensor, orig_shape: Tuple[int, ...], tap_perm: bool, dtype: torch.dtype) -> torch.Tensor:
if not tap_perm:
return w2.reshape(orig_shape).to(dtype)
c_out = orig_shape[0]
c_in = orig_shape[1]
sp = orig_shape[2:]
w_p = w2.view(c_out, *sp, c_in)
inv_perm = [0, len(orig_shape) - 1] + list(range(1, len(orig_shape) - 1))
return w_p.permute(*inv_perm).contiguous().to(dtype)
class PrimeLiveModule(nn.Module):
"""
In-VRAM compressed module (`p4_0`, `p2_0`, or `q2_0`, `G=32`) supporting `linear`, `embedding`,
`conv2d`, and `conv3d` with on-the-fly Triton unpacking and `_keep_in_fp32_modules` protection.
"""
def __init__(
self,
op_kind: str,
fmt: str,
orig_shape: Tuple[int, ...],
cols: int,
tap_perm: bool,
q_pack: torch.Tensor,
d_f16: torch.Tensor,
bias: Optional[torch.Tensor] = None,
compute_dtype: torch.dtype = torch.bfloat16,
conv_kwargs: Optional[Dict[str, Any]] = None,
):
super().__init__()
assert fmt in ("p4_0", "p2_0", "q2_0")
self.op_kind = op_kind
self.fmt = fmt
self.orig_shape = orig_shape
self.rows = q_pack.shape[0]
self.cols = cols
self.pcols = q_pack.shape[1] * (4 if fmt in ("q2_0", "p2_0") else 2)
assert d_f16.ndim == 2 and d_f16.shape[0] == self.rows and (self.pcols % d_f16.shape[1] == 0)
self.group_size = self.pcols // d_f16.shape[1]
self.tap_perm = tap_perm
self.compute_dtype = compute_dtype
self.conv_kwargs = conv_kwargs or {}
if op_kind == "linear":
self.in_features = orig_shape[1]
self.out_features = orig_shape[0]
elif op_kind == "embedding":
self.num_embeddings = orig_shape[0]
self.embedding_dim = orig_shape[1]
else:
self.out_channels = orig_shape[0]
self.in_channels = orig_shape[1] * self.conv_kwargs.get("groups", 1)
self.kernel_size = orig_shape[2:]
self.stride = self.conv_kwargs.get("stride", 1)
self.padding = self.conv_kwargs.get("padding", 0)
self.dilation = self.conv_kwargs.get("dilation", 1)
self.groups = self.conv_kwargs.get("groups", 1)
self.register_buffer("q_pack", q_pack.to(torch.uint8).contiguous())
self.register_buffer("d_f16", d_f16.to(torch.float16).contiguous())
self._dtype_anchor = nn.Parameter(torch.empty(0, dtype=compute_dtype), requires_grad=False)
if bias is not None:
self.register_buffer("bias", bias.to(compute_dtype).contiguous())
else:
self.bias = None
def _apply(self, fn, recurse=True):
# Preserve exact FP16 scale mantissa and FP32-protected bias across dtype casts
# (e.g., `model.to(torch.bfloat16)`), while still honoring device transfers.
orig_d = self.d_f16
orig_bias = self.bias
super()._apply(fn, recurse=recurse)
target_dev = self.q_pack.device
if not orig_d.is_meta and not self.d_f16.is_meta:
if self.d_f16.dtype != torch.float16:
self.d_f16 = orig_d if orig_d.device == target_dev else orig_d.to(device=target_dev, dtype=torch.float16)
elif self.d_f16.dtype != torch.float16:
self.d_f16 = self.d_f16.to(torch.float16)
if self.compute_dtype == torch.float32:
if self._dtype_anchor.dtype != torch.float32:
self._dtype_anchor = nn.Parameter(
torch.empty(0, device=target_dev, dtype=torch.float32), requires_grad=False
)
if orig_bias is not None and not orig_bias.is_meta and not self.bias.is_meta:
if self.bias.dtype != torch.float32:
self.bias = orig_bias if orig_bias.device == target_dev else orig_bias.to(device=target_dev, dtype=torch.float32)
elif self.bias is not None and self.bias.dtype != torch.float32:
self.bias = self.bias.to(torch.float32)
return self
@property
def weight(self) -> torch.Tensor:
return self._dtype_anchor
def unpack_weight(self, target_dtype: torch.dtype) -> torch.Tensor:
w2 = _unpack_packed_2d_fast(self.q_pack, self.d_f16, self.fmt, self.rows, self.pcols, self.group_size, target_dtype)
if self.pcols > self.cols:
w2 = w2[:, : self.cols]
return reconstruct_from_2d(w2, self.orig_shape, self.tap_perm, target_dtype)
def forward(self, x: torch.Tensor) -> torch.Tensor:
if self.op_kind == "embedding":
flat = x.reshape(-1)
n_sel = int(flat.numel())
qp_s = self.q_pack.index_select(0, flat)
df_s = self.d_f16.index_select(0, flat)
w2 = _unpack_packed_2d_fast(qp_s, df_s, self.fmt, n_sel, self.pcols, self.group_size, self.compute_dtype)
if self.pcols > self.cols:
w2 = w2[:, : self.cols]
out = w2.view(*x.shape, self.cols)
embed_norm = getattr(self, "embed_norm", None)
if embed_norm is not None:
out = embed_norm(out)
return out
dt = x.dtype
if (
self.op_kind == "linear"
and _HAS_TRITON_UNPACK
and self.q_pack.is_cuda
and self.group_size == 32
and not self.tap_perm
and self.fmt in ("p4_0", "p2_0", "q2_0")
and dt in (torch.bfloat16, torch.float16, torch.float32)
and x.numel() == self.cols
):
y = _gemv_prime_g32_fast(
x.reshape(-1), self.q_pack, self.d_f16, self.bias, self.fmt, self.rows, self.cols, self.pcols
)
return y.view(*x.shape[:-1], self.rows)
w = self.unpack_weight(dt)
b = (self.bias if self.bias.dtype == dt else self.bias.to(dt)) if self.bias is not None else None
if self.op_kind == "linear":
return F.linear(x, w, b)
if self.op_kind == "conv2d":
return F.conv2d(x, w, b, self.stride, self.padding, self.dilation, self.groups)
return F.conv3d(x, w, b, self.stride, self.padding, self.dilation, self.groups)
class PrimeLiveMoEExperts(nn.Module):
"""
In-VRAM compressed 3D Mixture-of-Experts bank (`gate_up_proj` + `down_proj` across `E` experts)
in `p2_0`, `q2_0`, or `p4_0`. At decode (`T == 1`), runs fused-register batched Triton GEMV
directly over the `top_k` active experts with zero weight materialization; at prefill (`T > 1`),
unpacks one hit expert at a time to keep peak VRAM tiny.
"""
def __init__(
self,
fmt: str,
num_experts: int,
hidden_dim: int,
intermediate_dim: int,
gu_q: torch.Tensor,
gu_d: torch.Tensor,
dn_q: torch.Tensor,
dn_d: torch.Tensor,
act_fn: nn.Module,
compute_dtype: torch.dtype = torch.bfloat16,
dn_fmt: Optional[str] = None,
):
super().__init__()
import inspect
dn_fmt_eff = fmt if dn_fmt is None else dn_fmt
assert fmt in ("p4_0", "p2_0", "q2_0") and dn_fmt_eff in ("p4_0", "p2_0", "q2_0")
self.fmt = fmt
self.dn_fmt = dn_fmt_eff
self.num_experts = int(num_experts)
self.hidden_dim = int(hidden_dim)
self.intermediate_dim = int(intermediate_dim)
self.compute_dtype = compute_dtype
self.act_fn = act_fn
try:
sig = inspect.signature(act_fn.forward)
self._act_two_arg = len(sig.parameters) >= 2
except Exception:
self._act_two_arg = False
if hasattr(act_fn, "gate_softcap") and hasattr(act_fn, "up_softcap"):
g_sc = getattr(act_fn.gate_softcap, "softcap", None)
u_sc = getattr(act_fn.up_softcap, "softcap", None)
self._fused_act: Optional[Tuple[float, float]] = (
float(g_sc) if g_sc is not None else 0.0,
float(u_sc) if u_sc is not None else 0.0,
)
elif isinstance(act_fn, nn.SiLU):
self._fused_act = (0.0, 0.0)
else:
self._fused_act = None
gu_pack_mul = 4 if fmt in ("q2_0", "p2_0") else 2
dn_pack_mul = 4 if dn_fmt_eff in ("q2_0", "p2_0") else 2
self.gu_rows = int(gu_q.shape[1])
self.gu_pcols = int(gu_q.shape[2]) * gu_pack_mul
self.dn_rows = int(dn_q.shape[1])
self.dn_pcols = int(dn_q.shape[2]) * dn_pack_mul
self.group_size = self.gu_pcols // int(gu_d.shape[2])
assert self.dn_pcols // int(dn_d.shape[2]) == self.group_size
self.register_buffer("gu_q", gu_q.to(torch.uint8).contiguous())
self.register_buffer("gu_d", gu_d.to(torch.float16).contiguous())
self.register_buffer("dn_q", dn_q.to(torch.uint8).contiguous())
self.register_buffer("dn_d", dn_d.to(torch.float16).contiguous())
def _apply(self, fn, recurse=True):
orig_gu_d = self.gu_d
orig_dn_d = self.dn_d
super()._apply(fn, recurse=recurse)
target_dev = self.gu_q.device
for attr, orig in (("gu_d", orig_gu_d), ("dn_d", orig_dn_d)):
cur = getattr(self, attr)
if not orig.is_meta and not cur.is_meta:
if cur.dtype != torch.float16:
setattr(self, attr, orig if orig.device == target_dev else orig.to(device=target_dev, dtype=torch.float16))
elif cur.dtype != torch.float16:
setattr(self, attr, cur.to(torch.float16))
return self
def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor:
gate, up = gate_up.chunk(2, dim=-1)
if self._act_two_arg:
return self.act_fn(gate, up)
return self.act_fn(gate) * up
def forward(
self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor
) -> torch.Tensor:
T, H = hidden_states.shape
dt = hidden_states.dtype
if T == 1:
e_raw = top_k_index[0]
if (
_HAS_TRITON_UNPACK
and self.gu_q.is_cuda
and self.group_size == 32
and self.fmt in ("p4_0", "p2_0", "q2_0")
and self.dn_fmt in ("p4_0", "p2_0", "q2_0")
and dt in (torch.bfloat16, torch.float16, torch.float32)
):
if self._fused_act is not None and self.gu_rows == 2 * self.intermediate_dim:
h_mid = _gemv_moe_gu_act_fast(
hidden_states[0], self.gu_q, self.gu_d, e_raw, self.fmt,
self.intermediate_dim, H, self.gu_pcols, self.num_experts,
self._fused_act[0], self._fused_act[1],
)
else:
e_ids = e_raw.clamp(0, self.num_experts - 1)
gu_out = _gemv_moe_g32_fast(
hidden_states[0], self.gu_q, self.gu_d, e_ids, self.fmt,
self.gu_rows, H, self.gu_pcols, shared_x=True,
)
h_mid = self._apply_gate(gu_out)
return _gemv_moe_dn_reduce_fast(
h_mid, self.dn_q, self.dn_d, e_raw, top_k_weights[0], self.dn_fmt,
self.dn_rows, self.intermediate_dim, self.dn_pcols, self.num_experts,
)
valid = ((e_raw >= 0) & (e_raw < self.num_experts)).to(torch.float32)
e_ids = e_raw.clamp(0, self.num_experts - 1)
w_tok = (top_k_weights[0].float() * valid).unsqueeze(-1)
K = int(e_ids.shape[0])
gu_q_k = self.gu_q.index_select(0, e_ids).reshape(K * self.gu_rows, -1)
gu_d_k = self.gu_d.index_select(0, e_ids).reshape(K * self.gu_rows, -1)
w_gu = _unpack_packed_2d_fast(gu_q_k, gu_d_k, self.fmt, K * self.gu_rows, self.gu_pcols, self.group_size, dt)
if self.gu_pcols > H:
w_gu = w_gu[:, :H]
w_gu = w_gu.view(K, self.gu_rows, H)
gu_out = torch.bmm(hidden_states.expand(K, H).unsqueeze(1), w_gu.transpose(1, 2)).squeeze(1)
del w_gu
h_mid = self._apply_gate(gu_out)
dn_q_k = self.dn_q.index_select(0, e_ids).reshape(K * self.dn_rows, -1)
dn_d_k = self.dn_d.index_select(0, e_ids).reshape(K * self.dn_rows, -1)
w_dn = _unpack_packed_2d_fast(dn_q_k, dn_d_k, self.dn_fmt, K * self.dn_rows, self.dn_pcols, self.group_size, dt)
if self.dn_pcols > self.intermediate_dim:
w_dn = w_dn[:, : self.intermediate_dim]
w_dn = w_dn.view(K, self.dn_rows, self.intermediate_dim)
dn_out = torch.bmm(h_mid.unsqueeze(1), w_dn.transpose(1, 2)).squeeze(1).float()
del w_dn
return (dn_out * w_tok).sum(dim=0, keepdim=True).to(dt)
final_hidden_states = torch.zeros_like(hidden_states, dtype=torch.float32)
with torch.no_grad():
expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0)
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
for expert_idx_t in expert_hit:
expert_idx = int(expert_idx_t[0].item())
if expert_idx >= self.num_experts:
continue
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
current_state = hidden_states[token_idx]
w_gu = _unpack_packed_2d_fast(
self.gu_q[expert_idx], self.gu_d[expert_idx], self.fmt, self.gu_rows, self.gu_pcols, self.group_size, dt
)
if self.gu_pcols > H:
w_gu = w_gu[:, :H]
h_mid = self._apply_gate(F.linear(current_state, w_gu))
del w_gu
w_dn = _unpack_packed_2d_fast(
self.dn_q[expert_idx], self.dn_d[expert_idx], self.dn_fmt, self.dn_rows, self.dn_pcols, self.group_size, dt
)
if self.dn_pcols > self.intermediate_dim:
w_dn = w_dn[:, : self.intermediate_dim]
cur_out = F.linear(h_mid, w_dn)
del w_dn
cur_out = cur_out * top_k_weights[token_idx, top_k_pos, None]
final_hidden_states.index_add_(0, token_idx, cur_out.to(torch.float32))
return final_hidden_states.to(dt)
def get_submod(root: nn.Module, path: str) -> nn.Module:
cur = root
for p in path.split("."):
cur = cur[int(p)] if p.isdigit() else getattr(cur, p)
return cur
def set_submod(root: nn.Module, path: str, new_mod: nn.Module) -> None:
parts = path.split(".")
parent = root
for p in parts[:-1]:
parent = parent[int(p)] if p.isdigit() else getattr(parent, p)
last = parts[-1]
if last.isdigit():
parent[int(last)] = new_mod
else:
setattr(parent, last, new_mod)
def _parse_tuple_or_int(s: str):
s = s.strip()
if s.startswith("(") and s.endswith(")"):
return tuple(int(x.strip()) for x in s[1:-1].split(",") if x.strip())
return int(s)
def _get_fp32_patterns(model: nn.Module) -> Tuple[str, ...]:
pats: List[str] = []
for attr in ("_keep_in_fp32_modules", "_keep_in_fp32_modules_strict"):
val = getattr(model, attr, None)
if val:
pats.extend(str(v) for v in val)
return tuple(dict.fromkeys(pats))
def _is_fp32_protected(full_name: str, fp32_patterns: Tuple[str, ...]) -> bool:
if not fp32_patterns:
return False
segs = set(full_name.split("."))
for pat in fp32_patterns:
if "." in pat:
if (
full_name == pat
or full_name.endswith("." + pat)
or (f".{pat}." in full_name)
or full_name.startswith(f"{pat}.")
):
return True
elif pat in segs:
return True
return False
@torch.no_grad()
def load_prime_safetensors(
skeleton_model: nn.Module,
safetensors_path: str,
device: str = "cuda",
compute_dtype: torch.dtype = torch.bfloat16,
) -> Dict[str, Any]:
"""
Hydrates a `torch.device("meta")` or CPU `skeleton_model` with in-VRAM `PrimeLiveModule` and
`PrimeLiveMoEExperts` modules in `<1.5s`, honoring `_keep_in_fp32_modules[_strict]`, persistent
buffers (e.g. MoE router bias), normed embeddings, and tied `shared <-> encoder.embed_tokens`.
"""
fp32_pats = _get_fp32_patterns(skeleton_model)
n_2bit, n_4bit = 0, 0
with safe_open(safetensors_path, framework="pt", device="cpu") as f:
meta = f.metadata() or {}
keys = set(f.keys())
for mk, mval in sorted(meta.items()):
if not mk.startswith("mod:"):
continue
mname = mk[4:]
op_kind, fmt, tap_s, cols_s, shape_s, conv_s = mval.split(";", 5)
tap_perm = bool(int(tap_s))
cols = int(cols_s)
orig_shape = tuple(int(x) for x in shape_s.split(","))
conv_kw = {}
if conv_s:
st_s, pa_s, di_s, gr_s = conv_s.split("|")
conv_kw = {
"stride": _parse_tuple_or_int(st_s),
"padding": _parse_tuple_or_int(pa_s),
"dilation": _parse_tuple_or_int(di_s),
"groups": int(gr_s),
}
qp = f.get_tensor(f"{mname}.__q").to(device)
df = f.get_tensor(f"{mname}.__d").to(device)
bt = f.get_tensor(f"{mname}.__b").to(device) if f"{mname}.__b" in keys else None
is_fp32_mod = _is_fp32_protected(mname, fp32_pats)
eff_dt = torch.float32 if is_fp32_mod else compute_dtype
old_mod = get_submod(skeleton_model, mname)
live_mod = PrimeLiveModule(
op_kind=op_kind,
fmt=fmt,
orig_shape=orig_shape,
cols=cols,
tap_perm=tap_perm,
q_pack=qp,
d_f16=df,
bias=bt,
compute_dtype=eff_dt,
conv_kwargs=conv_kw,
).to(device)
if op_kind == "embedding" and hasattr(old_mod, "embed_norm") and old_mod.embed_norm is not None:
live_mod.embed_norm = old_mod.embed_norm
set_submod(skeleton_model, mname, live_mod)
if fmt in ("q2_0", "p2_0"):
n_2bit += 1
else:
n_4bit += 1
for mk, mval in sorted(meta.items()):
if not mk.startswith("moe:"):
continue
mname = mk[4:]
fmt_spec, ne_s, hd_s, id_s = mval.split(";", 3)
if "/" in fmt_spec:
fmt, dn_fmt = fmt_spec.split("/", 1)
else:
fmt, dn_fmt = fmt_spec, fmt_spec
old_mod = get_submod(skeleton_model, mname)
act_fn = getattr(old_mod, "act_fn", nn.SiLU())
live_moe = PrimeLiveMoEExperts(
fmt=fmt,
num_experts=int(ne_s),
hidden_dim=int(hd_s),
intermediate_dim=int(id_s),
gu_q=f.get_tensor(f"{mname}.__gu_q").to(device),
gu_d=f.get_tensor(f"{mname}.__gu_d").to(device),
dn_q=f.get_tensor(f"{mname}.__dn_q").to(device),
dn_d=f.get_tensor(f"{mname}.__dn_d").to(device),
act_fn=act_fn,
compute_dtype=compute_dtype,
dn_fmt=dn_fmt,
).to(device)
set_submod(skeleton_model, mname, live_moe)
if fmt in ("q2_0", "p2_0") or dn_fmt in ("q2_0", "p2_0"):
n_2bit += 1
else:
n_4bit += 1
q_suffixes = (".__q", ".__d", ".__b", ".__gu_q", ".__gu_d", ".__dn_q", ".__dn_d")
for k in keys:
if k.endswith(q_suffixes):
continue
parts = k.split(".")
parent = get_submod(skeleton_model, ".".join(parts[:-1])) if len(parts) > 1 else skeleton_model
leaf = parts[-1]
if hasattr(parent, "_parameters") and leaf in parent._parameters and parent._parameters[leaf] is not None:
p_tgt = parent._parameters[leaf]
t_src = f.get_tensor(k)
is_fp32_prot = _is_fp32_protected(k, fp32_pats)
tgt_dt = (
(torch.float32 if t_src.dtype in (torch.float16, torch.bfloat16) else t_src.dtype)
if is_fp32_prot
else (compute_dtype if p_tgt.is_floating_point() else p_tgt.dtype)
)
parent._parameters[leaf] = nn.Parameter(t_src.to(device=device, dtype=tgt_dt), requires_grad=False)
elif hasattr(parent, "_buffers") and leaf in parent._buffers:
b_tgt = parent._buffers[leaf]
t_src = f.get_tensor(k)
is_fp32_prot = _is_fp32_protected(k, fp32_pats)
if is_fp32_prot:
tgt_dt = torch.float32 if t_src.dtype in (torch.float16, torch.bfloat16) else t_src.dtype
elif b_tgt is not None:
tgt_dt = t_src.dtype if (t_src.dtype == torch.float32 and b_tgt.dtype == torch.float32) else (compute_dtype if b_tgt.is_floating_point() else b_tgt.dtype)
else:
tgt_dt = t_src.dtype
parent._buffers[leaf] = t_src.to(device=device, dtype=tgt_dt)
if hasattr(skeleton_model, "tie_weights"):
try:
skeleton_model.tie_weights()
except Exception:
pass
if (
hasattr(skeleton_model, "shared")
and hasattr(skeleton_model, "encoder")
and hasattr(skeleton_model.encoder, "embed_tokens")
and isinstance(skeleton_model.shared, PrimeLiveModule)
):
skeleton_model.encoder.embed_tokens = skeleton_model.shared
vault_mods = {m for m in skeleton_model.modules() if isinstance(m, (PrimeLiveModule, PrimeLiveMoEExperts))}
moved_ptrs: Dict[Tuple[int, bool], nn.Parameter] = {}
for sub_path, sub in skeleton_model.named_modules():
if sub in vault_mods:
continue
for pname, p in sub._parameters.items():
if p is not None and not p.is_meta:
full_n = f"{sub_path}.{pname}" if sub_path else pname
is_fp32_prot = _is_fp32_protected(full_n, fp32_pats)
pkey = (p.data_ptr(), is_fp32_prot)
if pkey not in moved_ptrs:
tgt_dt = (
(torch.float32 if p.dtype in (torch.float16, torch.bfloat16) else p.dtype)
if is_fp32_prot
else (compute_dtype if p.is_floating_point() else p.dtype)
)
moved_ptrs[pkey] = nn.Parameter(p.data.to(device=device, dtype=tgt_dt), requires_grad=p.requires_grad)
sub._parameters[pname] = moved_ptrs[pkey]
for bname, b in sub._buffers.items():
if b is not None and not b.is_meta:
full_bn = f"{sub_path}.{bname}" if sub_path else bname
is_fp32_prot = _is_fp32_protected(full_bn, fp32_pats)
tgt_bdt = (
(torch.float32 if b.dtype in (torch.float16, torch.bfloat16) else b.dtype)
if is_fp32_prot
else (compute_dtype if b.is_floating_point() else b.dtype)
)
sub._buffers[bname] = b.to(device=device, dtype=tgt_bdt)
skeleton_model.eval()
vram_bytes = sum(b.numel() * b.element_size() for b in skeleton_model.buffers()) + sum(
p.numel() * p.element_size() for p in skeleton_model.parameters()
)
return {
"modules_2bit": n_2bit,
"modules_4bit": n_4bit,
"resident_vram_mb": round(vram_bytes / 1e6, 2),
"file_mb": round(os.path.getsize(safetensors_path) / 1e6, 2),
}
|