ktransformers: [Bug] deepseek v3/r1 with full context with balance_serve backend

Checklist

  • 1. I have searched related issues but cannot get the expected help.
  • 2. The bug has not been fixed in the latest version.
  • 3. Please note that if the bug-related issue you submitted lacks corresponding environment info and a minimal reproducible demo, it will be challenging for us to reproduce and resolve the issue, reducing the likelihood of receiving feedback.
  • 4. If the issue you raised is not a bug but a question, please raise a discussion at https://github.com/kvcache-ai/ktransformers/discussions. Otherwise, it will be closed.
  • 5. To help the community, I will use Chinese/English or attach an Chinese/English translation if using another language. Non-Chinese/English content without translation may be closed.

Describe the bug

I am not sure how to run the balance_serve backend with a full 128k context. If I will try something like that:

ktransformers \
  --gguf_path /opt/unsloth/DeepSeek-R1-0528-GGUF/UD-Q2_K_XL/DeepSeek-R1-0528-UD-Q2_K_XL-00001-of-00006.gguf \
  --model_path /opt/unsloth/DeepSeek-R1-0528-GGUF/ \
  --model_name unsloth/DeepSeek-R1-0528-Q2-GGUF \
  --cpu_infer $(grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}' | xargs -I{} echo "{}-0" | bc) \
  --optimize_config_path /opt/unsloth/DeepSeek-R1-0528-GGUF/UD-Q2_K_XL/DeepSeek-V3-Chat-serve.yaml \
  --backend_type balance_serve \
  --cache_8bit True \
  --cache_lens $((128*1024)) \
  --length $((128*1024)) \
  --max_new_tokens $((128*1024)) \
  --chunk_size 256 \
  --max_batch_size 1 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

I will have the error regarding the cuda_graphs.

Rebuilding kvcache
kv_cache loaded successfully.
capturing cuda graph 1 1
2025-07-03 13:06:22,408 - INFO - flashinfer.jit: Loading JIT ops: batch_mla_attention_dtype_q_bf16_dtype_kv_bf16_dtype_o_bf16_dtype_idx_i32_head_dim_ckv_512_head_dim_kpe_64_profiler_False
2025-07-03 13:06:46,487 - INFO - flashinfer.jit: Finished loading JIT ops: batch_mla_attention_dtype_q_bf16_dtype_kv_bf16_dtype_o_bf16_dtype_idx_i32_head_dim_ckv_512_head_dim_kpe_64_profiler_False
2025-07-03 13:06:46,536 - INFO - flashinfer.jit: Loading JIT ops: norm
2025-07-03 13:07:02,601 - INFO - flashinfer.jit: Finished loading JIT ops: norm
cuda_graph: 1/6, warmup finished.
capturing cuda graph 2 2
cuda_graph: 2/6, warmup finished.
capturing cuda graph 3 3
Process SpawnProcess-1:
Traceback (most recent call last):
  File "/usr/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap
    self.run()
    ~~~~~~~~^^
  File "/usr/lib/python3.13/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 279, in run_engine
    engine.model_runner.warmup()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/model_runner.py", line 133, in warmup
    self.model_attn_plan(self.input[i], i)
    ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/model_runner.py", line 92, in model_attn_plan
    self.model.flash_infer_attn_plan(batch, self.bsz_tensor_buf, self.num_tokens_tensor_buf,
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                     num_heads=self.model.config.num_attention_heads, head_dim_ckv=self.model.config.kv_lora_rank,
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                     head_dim_kpe=self.model.config.qk_rope_head_dim, page_size=self.model.cache.page_size, causal=True,
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                     sm_scale=self.model.model.layers[0].self_attn.softmax_scale, q_data_type=torch.bfloat16, kv_data_type=torch.bfloat16)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py", line 146, in flash_infer_attn_plan
    self.wrapper.plan(minibatch.q_indptr, minibatch.kv_indptr, minibatch.kv_indices,
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                      minibatch.kv_len, num_heads, head_dim_ckv, head_dim_kpe, page_size, causal, sm_scale, q_data_type, kv_data_type, bsz_tensors)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/mla.py", line 246, in plan
    self._qo_indptr_buf[:len(qo_indptr)].copy_(qo_indptr, non_blocking=True)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 0

I would not have a similar issue in case with ktransformers backend, but it doesn’t support the disk prefix caching. So what to do?

[UPDATE]: the ephemeral vibe-coded solution seems to be currently found. https://github.com/kvcache-ai/ktransformers/issues/1417#issuecomment-3040256985

Reproduction

ktransformers \
  --gguf_path /opt/unsloth/DeepSeek-R1-0528-GGUF/UD-Q2_K_XL/DeepSeek-R1-0528-UD-Q2_K_XL-00001-of-00006.gguf \
  --model_path /opt/unsloth/DeepSeek-R1-0528-GGUF/ \
  --model_name unsloth/DeepSeek-R1-0528-Q2-GGUF \
  --cpu_infer $(grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}' | xargs -I{} echo "{}-0" | bc) \
  --optimize_config_path /opt/unsloth/DeepSeek-R1-0528-GGUF/UD-Q2_K_XL/DeepSeek-V3-Chat-serve.yaml \
  --backend_type balance_serve \
  --cache_8bit True \
  --cache_lens $((128*1024)) \
  --length $((128*1024)) \
  --max_new_tokens $((128*1024)) \
  --chunk_size 256 \
  --max_batch_size 1 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

Environment

uname -a
Linux xxx 6.12.32-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.12.32-1 (2025-06-07) x86_64 GNU/Linux
nvidia-smi
Thu Jul  3 12:32:18 2025
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 575.51.02              Driver Version: 575.51.02      CUDA Version: 12.9     |
|-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  NVIDIA GeForce RTX 3090        Off |   00000000:41:00.0 Off |                  N/A |
| 30%   35C    P8             31W /  350W |     160MiB /  24576MiB |      0%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+
uv pip list
Using Python 3.13.3 environment at: /opt/ktransformers/.ktransformers
Package                  Version
------------------------ ------------------------
accelerate               1.8.1
annotated-types          0.7.0
anyio                    4.9.0
blessed                  1.21.0
build                    1.2.2.post1
certifi                  2025.6.15
charset-normalizer       3.4.2
click                    8.2.1
colorlog                 6.9.0
cpufeature               0.2.1
distro                   1.9.0
fastapi                  0.115.14
filelock                 3.18.0
fire                     0.7.0
flashinfer-python        0.2.3
fsspec                   2025.5.1
greenlet                 3.2.3
h11                      0.16.0
hf-xet                   1.1.5
httpcore                 1.0.9
httpx                    0.28.1
huggingface-hub          0.33.2
idna                     3.10
jinja2                   3.1.6
jiter                    0.10.0
jsonpatch                1.33
jsonpointer              3.0.0
ktransformers            0.3.2+cu129torch29avx2
langchain                0.3.26
langchain-core           0.3.67
langchain-text-splitters 0.3.8
langsmith                0.4.4
markupsafe               2.1.5
mpmath                   1.3.0
networkx                 3.5
ninja                    1.11.1.4
numpy                    2.3.1
nvidia-cublas-cu12       12.8.4.1
nvidia-cuda-cupti-cu12   12.8.90
nvidia-cuda-nvrtc-cu12   12.8.93
nvidia-cuda-runtime-cu12 12.8.90
nvidia-cudnn-cu12        9.10.2.21
nvidia-cufft-cu12        11.3.3.83
nvidia-cufile-cu12       1.13.1.3
nvidia-curand-cu12       10.3.9.90
nvidia-cusolver-cu12     11.7.3.90
nvidia-cusparse-cu12     12.5.8.93
nvidia-cusparselt-cu12   0.7.1
nvidia-nccl-cu12         2.27.3
nvidia-nvjitlink-cu12    12.8.93
nvidia-nvshmem-cu12      3.2.5
nvidia-nvtx-cu12         12.8.90
openai                   1.92.2
orjson                   3.10.18
packaging                24.2
pillow                   11.2.1
protobuf                 6.31.1
psutil                   7.0.0
pydantic                 2.11.7
pydantic-core            2.33.2
pyproject-hooks          1.2.0
pytorch-triton           3.3.1+gitc8757738
pyyaml                   6.0.2
pyzmq                    27.0.0
regex                    2024.11.6
requests                 2.32.4
requests-toolbelt        1.0.0
safetensors              0.5.3
sentencepiece            0.2.0
setuptools               78.1.0
sniffio                  1.3.1
sqlalchemy               2.0.41
starlette                0.46.2
sympy                    1.14.0
tenacity                 9.1.2
termcolor                3.1.0
tokenizers               0.21.2
torch                    2.9.0.dev20250702+cu128
torchaudio               2.8.0.dev20250702+cu128
torchvision              0.24.0.dev20250702+cu128
tqdm                     4.67.1
transformers             4.51.3
triton                   3.3.1
typing-extensions        4.14.0
typing-inspection        0.4.1
urllib3                  2.5.0
uvicorn                  0.35.0
wcwidth                  0.2.13
wheel                    0.45.1
zmq                      0.0.0
zstandard                0.23.0

About this issue

  • Original URL
  • State: open
  • Created a year ago
  • Comments: 69 (3 by maintainers)

Commits related to this issue

Most upvoted comments

fwiw I wrote the early ktransformers guide but have since moved on to spend my time working on https://github.com/ikawrakow/ik_llama.cpp

For folk who don’t know, ik is the author of most of the mainline quant types newer than the original q8_0 and q4_1 types including iq4_xs and q6_K etc.

To be clear, ik_llama.cpp does not use a new file type and easily runs mainline llama.cpp quants from bartowski and unsloth and others.

Basically it runs all those quants and more newer better types.

I’ll have to go update my README hugging face model cards to clarify that if people are mistaking this.

Folks are now getting over 300 tok/sec PP and in the high teens TG with my latest https://huggingface.co/ubergarm/DeepSeek-TNG-R1T2-Chimera-GGUF and no need for newer CUDA GPUs architectures like 8.9 for for native fp8 e4m3

So perfect if you have a mix of older GPUs like 3090TI and RTX A6000 multi-GPU configuration.

Thanks!


顺带一提,我编写了早期的 ktransformers 指南,但现已转向投入时间开发 https://github.com/ikawrakow/ik_llama.cpp。

对于不了解的各位,ik 是大部分新量化类型(超越原始 q8_0 和 q4_1 类型)的作者,包括 iq4_xs 和 q6_K 等。

明确说明:ik_llama.cpp 不使用新的文件类型,可轻松运行来自 bartowski、unsloth 及其他来源的主线 llama.cpp 量化模型。

简言之,它不仅能运行上述量化模型,还兼容更多更新更优的类型。

我需要更新 Hugging Face 模型卡的 README 以澄清此点,若用户存在误解。

目前用户在使用我最新发布的 https://huggingface.co/ubergarm/DeepSeek-TNG-R1T2-Chimera-GGUF 时,可获得超过 300 tok/sec 的 PP和十几的 TG,且无需依赖 8.9 等新 CUDA GPU 架构来实现原生 fp8 e4m3。

因此,若您采用混合旧款 GPU(如 3090TI 与 RTX A6000)的多 GPU 配置,此方案堪称完美。

感谢!

I don’t feel like polluting the KTransformers repository with off-topic stuff. If you are interested you can enter an issue or start a discussion in the ik_llama.cpp repository. But just quickly: a) you most likely want to run cmake with -DGGML_SCHED_MAX_COPIES=1, and b) you need to add -mla 1 to your command line to reproduce llama.cpp behavior (ik_llama.cpp has several MLA options, and can be run without MLA as well, this is what you are doing). For better performance you would change -mla 3 -fmoe and, depending on how much VRAM you have, use much larger batch/u-batch than the defaults. In general, when not familiar with a tool, it is always a good idea to start with small steps, and only then try to fly.

I’ll take a look after dinner!

Another error lol

Jul 05 13:35:11 xxx run-ktransformers.sh[897358]: 2025-07-05 13:35:11,870 DEBUG /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/inter faces/balance_serve.py[418]: get input ids of shape torch.Size([1, 86410])
Jul 05 13:35:12 xxx run-ktransformers.sh[897358]: INFO:     192.168.1.144:34744 - "POST /v1/chat/completions HTTP/1.1" 200 OK
Jul 05 13:35:12 xxx run-ktransformers.sh[897358]: 2025-07-05 13:35:12,314 DEBUG /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/inter
faces/balance_serve.py[418]: get input ids of shape torch.Size([1, 86410])
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]: Process SpawnProcess-1:
B
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]: Traceback (most recent call last):
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/usr/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self.run()
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/usr/lib/python3.13/multiprocessing/process.py", line 108, in run
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self._target(*self._args, **self._kwargs)
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py
", line 282, in run_engine
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     engine.loop()
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py
", line 234, in loop
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self.model_runner.run(self.batch, self.query_manager)
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/model_runne
r.py", line 202, in run
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self.model_attn_plan(self.input[cuda_graph_idx], cuda_graph_idx)
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/model_runne
r.py", line 92, in model_attn_plan
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self.model.flash_infer_attn_plan(batch, self.bsz_tensor_buf, self.num_tokens_tensor_buf,
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                                      num_heads=self.model.config.num_attention_heads, head_dim_ckv=self.model.config.kv_lora_ra
nk,
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                                      head_dim_kpe=self.model.config.qk_rope_head_dim, page_size=self.model.cache.page_size, cau
sal=True,
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                                      sm_scale=self.model.model.layers[0].self_attn.softmax_scale, q_data_type=torch.bfloat16, k
v_data_type=torch.bfloat16)
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py", li
ne 146, in flash_infer_attn_plan
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self.wrapper.plan(minibatch.q_indptr, minibatch.kv_indptr, minibatch.kv_indices,
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                       minibatch.kv_len, num_heads, head_dim_ckv, head_dim_kpe, page_size, causal, sm_scale, q_data_type, kv_dat
a_type, bsz_tensors)
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/mla.py", line 248, in plan
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     self._kv_indices_buf[: len(kv_indices)].copy_(kv_indices, non_blocking=True)
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]:     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 05 13:35:38 xxx run-ktransformers.sh[897447]: RuntimeError: The size of tensor a (8192) must match the size of tensor b (10917) at non-singleton dimension 0
Jul 05 13:35:47 xxx run-ktransformers.sh[897447]: Model execution time (GPU): 202.588 ms, 4.936 tokens/s
Jul 05 13:35:47 xxx run-ktransformers.sh[897447]: 274
Jul 05 13:35:47 xxx run-ktransformers.sh[897447]: 603
Jul 05 13:35:47 xxx run-ktransformers.sh[897447]: decode_batch_i: 2,

[UPDATE]: I will try to vibecode myself out of bugs with DeepSeek V3/R1 UD_Q2/Q4 quants. But lol if the deepseek is right related to the interpretation of the bugs then something is truly wrong with the codebase of the ktransformers. Its a great framework, dont get me wrong, but the stability issues is driving me nuts. I suggest that we have to fix it. May be we could implement some unit tests to see how different backends behave in different environments (prefill length, max tokens, max batches etc. etc.)? Otherwise a lot of people are catching a lot of annoying bugs which is a major inconvenience!

[UPDATE2:] Holy cow! it apparently worked! no crashes yet! I will post the exact fixes later on, after the thorough hardcore testing. Let me know if I should provide the exact patches (which are quite trivial BTW) or make a pull request or something.

@magikRUKKOLA

so in this case the dense experts uploaded to gpu require 17744.02MB. So about 6.5GB is free for the KV-cache related stuff which consists of: CUDA_Host compute buffer size, CUDA0 compute buffer size, KV self size. So with q8 quantisation of KV-cache it would unable to run with 64k context.

The model you chose there is one of the largest which uses Q8_0 quantization for the tensors going onto GPU VRAM pretty sure, so it should line up roughly with the graph I presented before. For my smaller quants that ~17GB fixed size is lower allowing more space for kv-cache.

Is it possible to place the KV-cache onto the second GPU to extend the supported context length?

Of course, by default ik/llama.cpp splits KV-cache across all GPUs or can use CPU RAM (much slower) which some folks choose to do if they require very high kv-cache on dense models with less efficient MQA/GQA.

Cool but what about the matrix absorption for prefill trick??? Its seems more reasonable to use flashinfer to support the long context just like ktransformers are doing. Namely, As far as I can see, its not supported in ik_llama.cpp, right?

To be honest I don’t know for as I have not fully inspected the (three different at least) MLA implementations on ik/llama.cpp. There are many closed PRs on multiple forks from around February of this year with the details. I’m not sure why you’re asking about this specific implementation optimization instead of looking at the actual benchmark results for yourself?

  1. I would ask you: “Regardless of the implementation details, is ik_llama.cpp faster in practice for your application”? Give it a good try and use llama-sweep-bench to see how different configurations work, or check out speeds reported by other uses recently
  2. If you care about the implementation specifics regardless of results, open a discussion and ask on ik’s fork.
  3. I did some digging in closed PRs, as that is where most of the knowledge is, and found some information here specific to how the “absorption trick” having issues with llama.cpp as well as how flash attention is supported with the different K and V head sizes for DeepSeek.
  4. fwiw flash attention is supported with both fp16 and q8_0 quantized cache on both CUDA and CPU backends (look more into -mla 3) and ik even helped nvidia’s jeffbolz get this going to help with the vulkan backend this week

Okay, I’ll stop spamming up this thread and hmu over on ik’s fork. There is a lot of info over there spread out in discussions, closed PRs, my hugging face repo threads etc, so I know it is overwhelming. Feel free to hmu over on ik’s fork with your hardware details, current command, and what it is you are trying to do e.g. “i want to run as much context in the least VRAM as possible” or whatever you’re up to.

Cheers!


magikRUKKOLA

在此案例中,上传至GPU的稠密专家模块需占用17744.02MB显存。因此约6.5GB剩余空间可用于KV缓存相关组件,包括:CUDA_Host计算缓冲区、CUDA0计算缓冲区、KV自注意力大小。若采用q8量化KV缓存,将无法支持64k上下文长度运行。

您选择的模型是当前最大规模之一,其GPU显存中的张量采用Q8_0量化方案,这与之前展示的图表基本吻合。对于我的小型量化模型,约1GB的固定占用会更低,从而为KV缓存预留更多空间。

是否可将KV缓存分配至第二GPU以扩展上下文长度支持?

当然可以。默认情况下ik/llama.cpp会将KV缓存跨GPU分配,亦可使用CPU内存(速度显著降低)。部分用户在运行MQA/GQA效率较低的稠密模型且需超大KV缓存时选择此方案。

那么关于预填充阶段的矩阵吸收优化方案呢?看起来采用flashinfer支持长上下文更为合理,正如ktransformers的实现方案。目前看来 ik_llama.cpp尚未支持此功能?

坦白说,我尚未全面研究ik/llama.cpp中至少三种不同的MLA实现机制。今年二月前后多个分支存在大量已关闭PR涉及该技术细节。我不理 您为何不直接查看实际基准测试结果,而执着于追问具体实现优化?

  1. 建议先思考:“无论实现细节如何,ik_llama.cpp在您的应用场景中是否实际更快?” 建议通过llama-sweep-bench深度测试不同配置, 参考近期用户实测数据
  2. 若您坚持关注实现细节而非结果,请在ik分支发起专项讨论
  3. 我查阅了closed PR(主要技术资料存档处),发现吸收优化在llama.cpp的兼容性问题及DeepSeek模型因K/V头尺寸差异对flash attention的支持情况
  4. 补充说明:flash attention同时支持fp16和q8_0量化缓存,适用于CUDA/CPU后端(详见-mla 3参数)。ik近期还协助nvidia的jeffbo在vulkan后端实现该功能

为避免干扰本讨论区,建议移步ik分支交流。相关技术资料分散在讨论区、closed PR及我的hugging face仓库中,信息量确实庞大。欢迎携带硬件配置、当前命令及具体需求(如"在最小显存下运行最大上下文")至ik分支探讨。

顺颂时祺!

@ubergarm

4. last i recall ktransformers just has llama.cpp under the hood so I decided to just go right to the source, ik, who has even better quality quants.

Cool but what about the matrix absorption for prefill trick??? Its seems more reasonable to use flashinfer to support the long context just like ktransformers are doing. Namely,

https://docs.flashinfer.ai/api/mla.html

class flashinfer.mla.BatchMLAPagedAttentionWrapper(float_workspace_buffer: torch.Tensor, use_cuda_graph: bool = False, qo_indptr: torch.Tensor | None = None, kv_indptr: torch.Tensor | None = None, kv_indices: torch.Tensor | None = None, kv_len_arr: torch.Tensor | None = None, backend: str = ‘auto’) Wrapper class for MLA (Multi-head Latent Attention) PagedAttention on DeepSeek models. This kernel can be used in decode, and incremental prefill and should be used together with Matrix Absorption trick: where is absorbed with , and is absorbed with . For MLA attention without Matrix Absorption (head_dim_qk=192 and head_dim_vo=128, which is used in prefilling self-attention stage), please use flashinfer.prefill.BatchPrefillWithRaggedKVCacheWrapper.

More information about The Paged KV-Cache layout in MLA is explained in our tutorial MLA Page Layout.

For more details about the MLA computation, Matrix Absorption and FlashInfer’s MLA implementation, please refer to our blog post.

As far as I can see, its not supported in ik_llama.cpp, right?

@magikRUKKOLA

As far as I can see, the longer than 64k (?) context in ik_llama.cpp requires [more] than 24GB VRAM. Can the same thing be implemented in ik_llama.cpp for example?

This is not specific to the inference engine, it is more specific to the specific quantization in terms of how large are the tensors your choose to offload onto VRAM and what kv-cache quantization you are using.

ik_llama.cpp implementation of DeepSeek MLA is very efficient, but generally yes you would need more than 24GB VRAM to use the model’s full 160k context. I’ve done it with two RTX A6000s (96GB VRAM total) (the older non-Blackwell ones). Most normal GQA style attention grows exponentially, but MLA is linear which is quite nice for longer context:

Image

You see for this specific quant there is a fixed size for the attn/shexp/first 3 ffn dense layers being offloaded to VRAM plus a variable amount for the kv-cache. My newer quants use slimmer newer IQ3_KS and similar SOTA quants to slim down that fixed amount further so people with 16GB VRAM can run it or you can get more context in 24GB etc.

Also regarding the multi-GPU configuration. I played around with the configs but found not much benefit of using more than 1 GPU (etc. RTX 3090) even though I am using P2P-enabled drivers. Basically, if one have enough RAM there would be no benefit of using more than one GPU? Or … may be just the prefill can be improved, not the decode?

If you read my old guide I have a section addressing this where at least at the time ktransformers did not take advantage of multi-GPU (unless u can offload the whole thing) and it even says so in the documentation. Here is the reference.

ik_llama.cpp has no problem getting more speed using more GPUs. You just have to be careful how to use the -ot --override-tensor command to not split up the tensors wierd. This works well for Qwen3 and other moe as well but the tensor naming convention and exact architectures vary so pay close attention. I’m helping some folks with gaming CPUs who have 5 GPUs with no nvlink no p2p anything and they are getting great speeds here in this discussion. I try to include multiGPU examples on most of my model cards.

But … the TNG-R1T2-Chimera-GGUF is not as “smart” as the R1-0528, right?:

“It depends.” A higher BPW quantization of TNG-R1T2-Chimera may be better than a lower BPW quantization of R1-0528. You really need to choose the right model and tune it specific to your use case e.g. do you need more PP (prefill) or do you want more TG etc.

I also have R1-0528 quants available if you have enough hardware and patience to wait for “the smartest” answer. Choose whatever tool you want.

And with ik_llama.cpp its better in performance than ktransformers? Is that correct?

You’ll probably have to test and it is somewhat difficult to make a direct comparison because the tooling is different between the two ecosystems. In my own experience ik_llama.cpp is better for my use-case becase:

  1. I want to use older GPUs that don’t have native fp8 e4m3. Last I checked the hybrid fp8 / GGUF ktransformers require > sm89 to use
  2. I want to use tooling more similar to llama.cpp for comparing perplexity and making my own quants. This allows me to compare apples-apples with other quantizers like bartowski, unsloth, mradermacher etc. See graph at below for how to compare perplexity of various quants to know what you’re running.
  3. last i recall ktransformers just has llama.cpp under the hood so I decided to just go right to the source, ik, who has even better quality quants.
  4. More flexibility for multi-GPU offload situations
  5. Mandarin Chinese is not my native language and English is more common on ik’s discussion board

I personally also recommend https://github.com/turboderp-org/exllamav3 and vllm and sglang as well depending on what LLM you want to use, how much VRAM you have, what the environment in which you’re working is etc.

But for running these huge 671B MoE’s my weapon of choice for hybrid CPU+GPU inferencing is definitely ik_llama.cpp.

You might argue “well ktransformers has USE_NUMA=1 and supports AMX extensions” sure but in my own testing ik’s avx2 and avx bf16 CPU implementations are faster than the AMX stuff anyway and if you can configure your AMD Epyc to NPS0 or your Intel Xeon to SNC=Disable and try to use single NUMA node then no need to pay for twice the RAM.

There is still room for improvment, and ik has been quite dedicated and all the amazing PP (prefill) speeds optimizations are really adding up now.

As mentioned above, the tooling around the llama.cpp ecosystem allows me to create and compare my quants to other providers and in general ik’s SOTA out perform his older quants which other quant cookers seem to limit themselves:

Image

magikRUKKOLA

据我所知,ik_llama.cpp 中处理超过64k(?)的上下文需要超过24GB显存。能否在ik_llama.cpp中实现类似的功能?

这与推理引擎本身无关,更多取决于具体量化方案的选择:包括选择卸载到显存中的张量大小以及使用的kv缓存量化方法。

ik_llama.cpp对DeepSeek MLA的实现非常高效,但通常确实需要超过24GB显存才能使用模型完整的160k上下文。我曾在两块RTX A6000(非Blackwell版,总计96GB显存)上成功运行。普通GQA风格注意力的计算量呈指数级增长,而MLA是线性的,这对长上下文非常有利:

如图所示,在该特定量化方案中,attn/shexp/前三个ffn密集层有固定大小的显存占用,而kv缓存部分则是可变大小。我更新的量化方案采用了更精简的新式IQ3_KS等SOTA量化方法,进一步减少了固定占用部分,使得16GB显存用户也能运行,或在24GB显存下获得更多上下文。

另外关于多GPU配置的问题。我尝试过不同配置,但发现即使使用启用P2P的驱动程序,使用超过1个GPU(例如RTX 3090)也没有明显收益。是否意味着只要有足够内存,使用多GPU就没有优势?或者… 可能仅能提升预填充(prefill)而非解码(decode)?

如果您读过我的旧版指南,其中专门讨论过这个问题:至少在当时的ktranformers版本中,除非能完全卸载模型,否则无法有效利用多GPU 文档中也明确提及)。参考链接在此

ik_llama.cpp可以毫无问题地通过多GPU获得速度提升。关键是要谨慎使用-ot --override-tensor命令,避免异常张量分割。这种方法对wen3及其他MoE模型同样有效,但需注意不同架构的张量命名规范差异。我目前正在协助一些使用游戏CPU的用户(他们拥有5块无NVLink/P2P的GPU),在此讨论中他们获得了出色性能。我尽量在多数模型卡中提供多GPU示例。

但是… TNG-R1T2-Chimera-GGUF不如R1-0528 “智能”,对吗?

“这取决于具体情况。” 高BPW量化的TNG-R1T2-Chimera可能优于低BPW量化的R1-0528。您需要根据具体用例选择合适模型并进行调优,例如侧重预填充(PP)还是生成(TG)等需求。

如果硬件充足且有耐心等待"最智能"的答案,我也提供R1-0528量化版本。工具选择完全取决于您。

就性能而言,ik_llama.cpp是否优于ktransformers?这个说法正确吗?

可能需要自行测试,因为两者的工具链差异使得直接比较较为困难。根据我的经验,ik_llama.cpp更适合我的使用场景,原因如下:

  1. 我需使用不支持原生fp8 e4m3的老旧GPU。据上次检查,ktranformers的混合fp8/GGUF方案要求>sm89架构
  2. 我希望使用更接近llama.cpp的工具链进行困惑度对比和自主量化。这样可与bartowski、unsloth、mradermacher等其他量化方案进行公平比较(参见下图各量化方案的困惑度对比)
  3. 据我所知,ktransformers底层仍是llama.cpp,因此我选择直接使用量化质量更优的ik版本
  4. 多GPU卸载场景的灵活性更高
  5. 中文非我母语,而ik讨论区以英语为主

根据LLM类型、显存容量和工作环境,我个人也推荐:

但对于运行这些671B参数的巨型MoE模型,ik_llama.cpp绝对是混合CPU+GPU推理的首选工具。

有人可能反驳"ktransformers支持USE_NUMA=1和AMX扩展"——但在我的测试中,ik的avx2/avx bf16 CPU实现反而比AMX更快。若能将AMD Epyc配置为NPS0或Intel Xeon设为SNC=Disable并使用单NUMA节点,则无需支付双倍内存成本。

仍有改进空间,而ik始终专注优化——目前所有的预填充(PP)速度优化成果正在持续累积。

如前所述,llama.cpp生态的工具链使我能够将自己的量化方案与其他提供商对比。总体而言,ik的SOTA量化始终优于其旧版量化,而其他量化工具似乎自我设限:

@createthis

–ctx-size 163840 \

This is not a typo?

It’s not. This is the reported max context length llama.cpp detects in the GGUF.

What do you recommend I change?

The quant type. _R4 have better performance in terms of perplexity per bpw. Example:

#!/usr/bin/env bash
# Fits 32k context in under 24GB VRAM
# Optional `-ser 6,1` improves speed at some cost to quality
# Recommended sampling: --temp 0.6 --top-p 0.95
CUDA_VISIBLE_DEVICES="0,1" \
/opt/ik_llama.cpp/ik_llama.cpp/build/bin/llama-server \
    --model /opt/ubergarm/DeepSeek-R1-0528-GGUF/IQ2_K_R4/DeepSeek-R1-0528-IQ2_K_R4-00001-of-00005.gguf \
    --alias ubergarm/DeepSeek-R1-0528-IQ2_K_R4 \
    --ctx-size 32768 \
    -ctk q8_0 \
    -mla 3 -fa \
    -amb 512 \
    -fmoe \
    --n-gpu-layers 63 \
    -ot "blk\.(3|4)\.ffn_.*=CUDA0" \
    -ot "blk\.(5|6|7)\.ffn_.*=CUDA1" \
    --override-tensor exps=CPU \
    --parallel 1 \
    --threads $(grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}' | xargs -I{} echo "{}-0" | bc) \
    --host 0.0.0.0 \
    --port 8080

@ikawrakow

In what sense does ik_llama.cpp need “yet another file format”? It will happily consume any GGUF usable with llama.cpp.

https://huggingface.co/ubergarm/DeepSeek-R1-0528-GGUF

This quant collection REQUIRES ik_llama.cpp fork to support advanced non-linear SotA quants and Multi-Head Latent Attention (MLA). Do not download these big files and expect them to run on mainline vanilla llama.cpp, ollama, LM Studio, KoboldCpp, etc!

@createthis

I have not tried ik_llama.cpp. I don’t like that it uses yet another file format. I have limited disk space, so I’m sticking to GGUF for now.

In what sense does ik_llama.cpp need “yet another file format”? It will happily consume any GGUF usable with llama.cpp.

I tried balance_serve just now at commit 8c8cb2 with your patch.

I cannot even find such a commit in the recent history. You dont do the latest masters?

https://github.com/kvcache-ai/ktransformers/pull/1422/commits/8c8cb207aa0ebe6d00ede36489adfe6ce23bd436

llama.cpp is faster for me in tok/s than ktransformers, due to the way it handles NUMA. I can run it with NPS4 and tune the number of CPU threads to be optimal instead of NPS0 under ktransformers. I did prefer the prefill cache in the ktransformers backend, but that’s not support now either, so I really no longer have a dog in the race.

llama.cpp does use more VRAM than ktransformers, but I have plenty of VRAM since I upgraded from a 3090 to a blackwell 6000 pro.

I have not tried ik_llama.cpp. I don’t like that it uses yet another file format. I have limited disk space, so I’m sticking to GGUF for now.

I am pretty sure that the problem is similar to what is going on with balance_serve and R1/V3 can fix it. But should we do that? The thing is the ktransformers legacy backend is getting deprecated.

My opinion as an old guy who has worked on a lot of software projects over the years is that this project needs unit tests that prevent this sort of thing from happening and CI/CD to enforce it. If it had that, the ktransformers backend could be maintained in a fork or something if they don’t want to support it. However, without the unit tests and CI/CD, this sort of thing will always happen and the ktransformers project will be unstable. I’ve switched to llama.cpp for this reason.

@createthis

these are with diff -u

--- .ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py.bak    2025-07-03 18:59:17.698822263 +0000
+++ .ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py        2025-07-06 15:06:34.191635341 +0000
@@ -52,8 +52,9 @@
                        self.is_all_greedy = False

 class Sampler(nn.Module):
-       def __init__(self):
+       def __init__(self, device=torch.device('cuda')):
                super().__init__()
+               self.device = device

        def forward(
                self,
@@ -63,7 +64,11 @@
                if sampling_config == None:
                        sampling_config = SamplingOptions()

-               logits = logits.contiguous()
+               # Ensure all tensors are on the same device
+               device = logits.device
+               logits = logits.contiguous().to(device)
+               sampling_config.temperatures = sampling_config.temperatures.to(device)
+
                origin_logits = logits.clone()
                if sampling_config.is_all_greedy:
                        # Use torch.argmax if all requests use greedy sampling
@@ -71,7 +76,8 @@
                        batch_next_token_ids = torch.argmax(logits, -1)
                else:
                        # Post process logits
-                       logits.div_(sampling_config.temperatures)
+                       safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0)
+                       logits.div_(safe_temperatures)
                        max_top_k_round, batch_size = 32, logits.shape[0]
                        if sampling_config.need_min_p_sampling:
                                probs = torch.softmax(logits, dim=-1)
@@ -82,8 +88,10 @@
                                batch_next_token_ids = min_p_sampling_from_probs(
                                        probs, sampling_config.min_ps
                                )
+                               torch.cuda.synchronize()
                                temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]
-                               batch_next_token_ids[temperature_0_idx] = torch.argmax(origin_logits[temperature_0_idx], -1).to(torch.int32)
+                               if temperature_0_idx.numel() > 0:
+                                       batch_next_token_ids[temperature_0_idx] = torch.argmax(origin_logits[temperature_0_idx], -1).to(torch.int32)
                        else:
                                # TODO: use different kernel when don't need top_k or top_p
                                # @TODO get probs
@@ -94,7 +102,9 @@
                                        sampling_config.top_ps,
                                        filter_apply_order="joint",
                                )
+                               torch.cuda.synchronize()
                                temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]
-                               batch_next_token_ids[temperature_0_idx] = torch.argmax(origin_logits[temperature_0_idx], -1).to(torch.int32)
+                               if temperature_0_idx.numel() > 0:
+                                       batch_next_token_ids[temperature_0_idx] = torch.argmax(origin_logits[temperature_0_idx], -1).to(torch.int32)

-               return batch_next_token_ids.to(torch.int32), probs
\ No newline at end of file
+               return batch_next_token_ids.to(torch.int32), probs
--- .ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py.bak 2025-07-05 17:42:32.784284649 +0000
+++ .ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py     2025-07-05 17:12:08.724268395 +0000
@@ -42,20 +42,23 @@

     def init_wrapper(self, use_cuda_graph, device, max_batch_size, max_pages):
         self.use_cuda_graph = use_cuda_graph
-        self.workspace_buffer = torch.empty(128 * 1024 * 1024, dtype=torch.int8).to(0)
+        # Increase buffer sizes to be safe
+        self.workspace_buffer = torch.empty(256 * 1024 * 1024, dtype=torch.int8).to(0)
         self.qo_indptr_buf = torch.empty((max_batch_size+2,), dtype=torch.int32, device=device)
         self.paged_kv_indptr_buf = torch.empty((max_batch_size+2,), dtype=torch.int32, device=device)
-        self.paged_kv_indices_buf = torch.empty((max_pages,), dtype=torch.int32, device=device)
+        # Make sure this buffer is large enough
+        self.paged_kv_indices_buf = torch.empty((max_pages * 2,), dtype=torch.int32, device=device)
         self.paged_kv_len_buf = torch.empty((max_batch_size+1,), dtype=torch.int32, device=device)
         self.bsz_tensor_buf = torch.empty((1, ), dtype=torch.int32, device=device)
-

         self.wrapper = flashinfer.mla.BatchMLAPagedAttentionWrapper(
             self.workspace_buffer, use_cuda_graph=use_cuda_graph,
-            qo_indptr=self.qo_indptr_buf,kv_indptr=self.paged_kv_indptr_buf,
-            kv_indices=self.paged_kv_indices_buf,kv_len_arr=self.paged_kv_len_buf,
+            qo_indptr=self.qo_indptr_buf,
+            kv_indptr=self.paged_kv_indptr_buf,
+            kv_indices=self.paged_kv_indices_buf,
+            kv_len_arr=self.paged_kv_len_buf,
             bsz_tensor=self.bsz_tensor_buf,
-            backend = "fa2",
+            backend="fa2",
         )

     def batch_embeddings(self, batch: ForwardBatchInput, device="cuda:0"):
@@ -145,4 +148,4 @@
         minibatch = batch.minibatch
         self.wrapper.plan(minibatch.q_indptr, minibatch.kv_indptr, minibatch.kv_indices,
                           minibatch.kv_len, num_heads, head_dim_ckv, head_dim_kpe, page_size, causal, sm_scale, q_data_type, kv_data_type, bsz_tensors)
-
\ No newline at end of file
+

lol no errors yet

So what does that all mean? All the time there was a race condition in the balance_serve backend sampler of ktransformers which leads to the invalid memory read? Is it correct?

[UPDATE]: a different error!

 decode_batch_i: 1,
 Model execution time (GPU): 220.592 ms, 4.533 tokens/s
 722
 decode_batch_i: 1,
 Model execution time (GPU): 220.786 ms, 4.529 tokens/sCUDA Error: an illegal memory access was encountered (700) /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/data/include/flashinfer/sampling.cuh: line 927 at function cudaLaunchKernel((void*)kernel, nblks, nthrs, args, smem_size, stream)
 Process SpawnProcess-1:
 Traceback (most recent call last):
   File "/usr/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap
     self.run()
     ~~~~~~~~^^
   File "/usr/lib/python3.13/multiprocessing/process.py", line 108, in run
     self._target(*self._args, **self._kwargs)
     ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 282, in run_engine
     engine.loop()
     ~~~~~~~~~~~^^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 260, in loop
     generated_tokens, probs = self.sampling( self.model_runner.output)
                               ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 224, in sampling
     generated_tokens, probs=self.sampler(logit, sample_options)
                             ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
     return self._call_impl(*args, **kwargs)
            ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
     return forward_call(*args, **kwargs)
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py", line 100, in forward
     batch_next_token_ids = top_k_top_p_sampling_from_logits(
             logits,
     ...<2 lines>...
             filter_apply_order="joint",
     )
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/sampling.py", line 818, in top_k_top_p_sampling_from_logits
     return get_sampling_module().top_k_top_p_sampling_from_probs(
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
         probs,
         ^^^^^^
     ...<4 lines>...
         generator,
         ^^^^^^^^^^
     )
     ^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/sampling.py", line 214, in top_k_top_p_sampling_from_probs
     module.top_k_top_p_sampling_from_probs.default(
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
         probs,
         ^^^^^^
     ...<7 lines>...
         generator,
         ^^^^^^^^^^
     )
     ^
   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/_ops.py", line 829, in __call__
     return self._op(*args, **kwargs)
            ~~~~~~~~^^^^^^^^^^^^^^^^^
 RuntimeError: TopKTopPSamplingFromProbs failed with error code an illegal memory access was encountered
 terminate called after throwing an instance of 'c10::AcceleratorError'
   what():  CUDA error: an illegal memory access was encountered
 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
 Exception raised from c10_cuda_check_implementation at /pytorch/c10/cuda/CUDAException.cpp:42 (most recent call first):
 frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x80 (0x7fdcda0d9f00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
 frame #1: <unknown function> + 0x111a7 (0x7fdcda16c1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #2: <unknown function> + 0x1c3cb (0x7fdcda1773cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #3: <unknown function> + 0x1771c (0x7fdcda17271c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #4: <unknown function> + 0x1be27 (0x7fdcda176e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #5: <unknown function> + 0x1d646 (0x7fdcda178646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #6: <unknown function> + 0x31b9d (0x7fdcda18cb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #7: <unknown function> + 0x36ccda (0x7fdccc96ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #8: <unknown function> + 0x628158 (0x7fdcccc28158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #9: <unknown function> + 0x438b28 (0x7fdccca38b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7fdcda0b7145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
 frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7fdcda0b71c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
 frame #12: <unknown function> + 0x6cfb48 (0x7fdcccccfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #13: <unknown function> + 0x6cff1d (0x7fdcccccff1d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #14: /opt/ktransformers/.ktransformers/bin/python3() [0x52daa2]
 frame #15: /opt/ktransformers/.ktransformers/bin/python3() [0x54247d]
 frame #16: /opt/ktransformers/.ktransformers/bin/python3() [0x5cb058]
 frame #17: /opt/ktransformers/.ktransformers/bin/python3() [0x54219a]
 frame #18: /opt/ktransformers/.ktransformers/bin/python3() [0x54219a]
 frame #19: /opt/ktransformers/.ktransformers/bin/python3() [0x5cb058]
 frame #20: /opt/ktransformers/.ktransformers/bin/python3() [0x5cab4a]
 frame #21: /opt/ktransformers/.ktransformers/bin/python3() [0x5cab4a]
 frame #22: /opt/ktransformers/.ktransformers/bin/python3() [0x59c1af]
 frame #23: /opt/ktransformers/.ktransformers/bin/python3() [0x59991b]
 frame #24: /opt/ktransformers/.ktransformers/bin/python3() [0x59996f]
 frame #25: /opt/ktransformers/.ktransformers/bin/python3() [0x59996f]
 frame #26: /opt/ktransformers/.ktransformers/bin/python3() [0x5b3118]
 frame #27: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3)
 frame #28: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3)
 frame #29: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21]
 frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c]
 frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015]
 frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c]
 frame #33: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3)
 frame #34: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3)
 frame #35: <unknown function> + 0x29ca8 (0x7fdcdcc17ca8 in /lib/x86_64-linux-gnu/libc.so.6)
 frame #36: __libc_start_main + 0x85 (0x7fdcdcc17d65 in /lib/x86_64-linux-gnu/libc.so.6)
 frame #37: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)