[GH-ISSUE #1417] [Bug] deepseek v3/r1 with full context with balance_serve backend #950

Open
opened 2026-10-29 14:46:38 +00:00 by bsakaguchi · 74 comments
Owner

Originally created by @magikRUKKOLA on GitHub (Jul 3, 2025).
Original GitHub issue: https://github.com/kvcache-ai/ktransformers/issues/1417

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
Originally created by @magikRUKKOLA on GitHub (Jul 3, 2025). Original GitHub issue: https://github.com/kvcache-ai/ktransformers/issues/1417 ### Checklist - [x] 1. I have searched related issues but cannot get the expected help. - [x] 2. The bug has not been fixed in the latest version. - [x] 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. - [x] 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. - [x] 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
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 3, 2025):

In case I am using the --no-use_cuda_graph it seems to solve the issue but the inference speed (decode, not prefill) is getting x2 times slower.

So what is going on? Why the one-session ktransformers backend works fine with cuda_graphs but the balance_serve backend doesn't seem to be functional with one session and if I am to try to support [four] sessions with full context on 24 GB VRAM there would be OOM. :)

Namely, if I would try this:

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 4 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

I would get this during the inference:

2025-07-03 17:46:18,122 DEBUG /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[418]: get input ids of shape torch.Size([1, 126174])
add query id: 2, batch.query_lengths: 126174, batch_query_tokens: torch.Size([131072]), batch.block_indexes: tensor([1023,    0,    1,  ..., 1020, 1021, 1022], dtype=torch.int32)
prefill_batch_i: 254,
Model execution time (GPU): 4192.625 ms, 0.239 tokens/s
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 97, in forward
    temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]
                        ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
torch.AcceleratorError: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

terminate called after throwing an instance of 'c10::AcceleratorError'
  what():  CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
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 (0x7f30eb57ef00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #1: <unknown function> + 0x111a7 (0x7f30f211f1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #2: <unknown function> + 0x1c3cb (0x7f30f212a3cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #3: <unknown function> + 0x1771c (0x7f30f212571c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #4: <unknown function> + 0x1be27 (0x7f30f2129e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #5: <unknown function> + 0x1d646 (0x7f30f212b646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #6: <unknown function> + 0x31b9d (0x7f30f213fb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #7: <unknown function> + 0x36ccda (0x7f30e496ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #8: <unknown function> + 0x628158 (0x7f30e4c28158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #9: <unknown function> + 0x438b28 (0x7f30e4a38b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f30eb55c145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f30eb55c1c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #12: <unknown function> + 0x6cfb48 (0x7f30e4ccfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #13: <unknown function> + 0x6cff1d (0x7f30e4ccff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16]
frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3)
frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3)
frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21]
frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c]
frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015]
frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c]
frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3)
frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3)
frame #36: <unknown function> + 0x29ca8 (0x7f30f4b4bca8 in /lib/x86_64-linux-gnu/libc.so.6)
frame #37: __libc_start_main + 0x85 (0x7f30f4b4bd65 in /lib/x86_64-linux-gnu/libc.so.6)
frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)
[Thu Jul  3 17:46:22 2025] NVRM: Xid (PCI:0000:41:00): 31, pid=610922, name=python3, Ch 0000001f, intr 00000000. MMU Fault: ENGINE GRAPHICS GPC1 GPCCLIENT_T1_0 faulted @ 0x4_0da53000. Fault is of type FAULT_PDE ACCESS_TYPE_VIRT_READ
<!-- gh-comment-id:3032240989 --> @magikRUKKOLA commented on GitHub (Jul 3, 2025): In case I am using the --no-use_cuda_graph it seems to solve the issue but the inference speed (decode, not prefill) is getting x2 times slower. So what is going on? Why the one-session ktransformers backend works fine with cuda_graphs but the balance_serve backend doesn't seem to be functional with one session and if I am to try to support [four] sessions with full context on 24 GB VRAM there would be OOM. :) Namely, if I would try this: ``` 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 4 \ --temperature 0.6 \ --top_p 0.95 \ --host 0.0.0.0 \ --port 8080 \ --fast_safetensors True \ --log_level DEBUG \ --use_cuda_graph ``` I would get this during the inference: ``` 2025-07-03 17:46:18,122 DEBUG /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[418]: get input ids of shape torch.Size([1, 126174]) add query id: 2, batch.query_lengths: 126174, batch_query_tokens: torch.Size([131072]), batch.block_indexes: tensor([1023, 0, 1, ..., 1020, 1021, 1022], dtype=torch.int32) prefill_batch_i: 254, Model execution time (GPU): 4192.625 ms, 0.239 tokens/s 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 97, in forward temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ torch.AcceleratorError: CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. terminate called after throwing an instance of 'c10::AcceleratorError' what(): CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 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 (0x7f30eb57ef00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #1: <unknown function> + 0x111a7 (0x7f30f211f1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #2: <unknown function> + 0x1c3cb (0x7f30f212a3cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #3: <unknown function> + 0x1771c (0x7f30f212571c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #4: <unknown function> + 0x1be27 (0x7f30f2129e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #5: <unknown function> + 0x1d646 (0x7f30f212b646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #6: <unknown function> + 0x31b9d (0x7f30f213fb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #7: <unknown function> + 0x36ccda (0x7f30e496ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #8: <unknown function> + 0x628158 (0x7f30e4c28158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #9: <unknown function> + 0x438b28 (0x7f30e4a38b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f30eb55c145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f30eb55c1c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #12: <unknown function> + 0x6cfb48 (0x7f30e4ccfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #13: <unknown function> + 0x6cff1d (0x7f30e4ccff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16] frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3) frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3) frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21] frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c] frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015] frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c] frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3) frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3) frame #36: <unknown function> + 0x29ca8 (0x7f30f4b4bca8 in /lib/x86_64-linux-gnu/libc.so.6) frame #37: __libc_start_main + 0x85 (0x7f30f4b4bd65 in /lib/x86_64-linux-gnu/libc.so.6) frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3) ``` ``` [Thu Jul 3 17:46:22 2025] NVRM: Xid (PCI:0000:41:00): 31, pid=610922, name=python3, Ch 0000001f, intr 00000000. MMU Fault: ENGINE GRAPHICS GPC1 GPCCLIENT_T1_0 faulted @ 0x4_0da53000. Fault is of type FAULT_PDE ACCESS_TYPE_VIRT_READ ```
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 3, 2025):

Is there any config for a multi-gpu with balance_serve support?

<!-- gh-comment-id:3033043367 --> @magikRUKKOLA commented on GitHub (Jul 3, 2025): Is there any config for a multi-gpu with balance_serve support?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 3, 2025):

I don't get why the prefix caching with disk support wasn't implemented in ktransformers backend?

The balance_serve backend unfortunately is not usable. It limits the the output of the model up to 32k tokens in order to do what? To potentially support up to 4 simultaneous clients? What for? In case I would want 4 simultaneous sessions I would build 4 separate computers and route the queries myself. I DO NOT need a support of such stuff in the llm inference framework. Please make something to work stable with full 128k context. Otherwise its impossible to run deepseek with full 128k context nowhere -- neither with balance_serve (as it seems mandatory to specify four sessions and limit the max token output to 32k) or its fully working with ktransfomers backend but it doesn't support the prefix disk caching and its seems to getting deprecated. This is clearly ridiculous.

<!-- gh-comment-id:3033097942 --> @magikRUKKOLA commented on GitHub (Jul 3, 2025): I don't get why the prefix caching with disk support wasn't implemented in ktransformers backend? The balance_serve backend unfortunately is not usable. It limits the the output of the model up to 32k tokens in order to do what? To potentially support up to 4 simultaneous clients? What for? In case I would want 4 simultaneous sessions I would build 4 separate computers and route the queries myself. I DO NOT need a support of such stuff in the llm inference framework. Please make something to work stable with full 128k context. Otherwise its impossible to run deepseek with full 128k context nowhere -- neither with balance_serve (as it seems mandatory to specify four sessions and limit the max token output to 32k) or its fully working with ktransfomers backend but it doesn't support the prefix disk caching and its seems to getting deprecated. This is clearly ridiculous.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 3, 2025):

Ha. I can't even do 126k prefill with max_batches=4 and max_tokens=132k. Ha. Its doing OOM at about 90k prefill.

Not sure what is going on. Let me kill the xfce4 process that tool 50MB of VRAM and try again. May be there is an issue with gpu_utilization configuration.

[EDIT]. I tried with xfce4 killed so that only ktransformers takes up the VRAM and result is the same.

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 $((32*1024)) \
  --chunk_size 256 \
  --max_batch_size 4 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

and its crashing after 98k context prefill. Its steadily consuming about 22.6 GB of VRAM and its just crashing. So not only decode of 128k context is NOT working with balance_serve. But the prefill is failing too. Did anyone actually tested it?


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 97, in forward
    temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]
                        ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
torch.AcceleratorError: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

terminate called after throwing an instance of 'c10::AcceleratorError'
  what():  CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
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 (0x7f699b97ef00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #1: <unknown function> + 0x111a7 (0x7f699bd751a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #2: <unknown function> + 0x1c3cb (0x7f699bd803cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #3: <unknown function> + 0x1771c (0x7f699bd7b71c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #4: <unknown function> + 0x1be27 (0x7f699bd7fe27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #5: <unknown function> + 0x1d646 (0x7f699bd81646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #6: <unknown function> + 0x31b9d (0x7f699bd95b9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #7: <unknown function> + 0x36ccda (0x7f698e16ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #8: <unknown function> + 0x628158 (0x7f698e428158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #9: <unknown function> + 0x438b28 (0x7f698e238b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f699b95c145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f699b95c1c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #12: <unknown function> + 0x6cfb48 (0x7f698e4cfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #13: <unknown function> + 0x6cff1d (0x7f698e4cff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16]
frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3)
frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3)
frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21]
frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c]
frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015]
frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c]
frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3)
frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3)
frame #36: <unknown function> + 0x29ca8 (0x7f699e4f4ca8 in /lib/x86_64-linux-gnu/libc.so.6)
frame #37: __libc_start_main + 0x85 (0x7f699e4f4d65 in /lib/x86_64-linux-gnu/libc.so.6)
frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)
[Thu Jul  3 20:27:30 2025] python3[621906]: segfault at 7f1dcebab ip 00007f250d5be9a7 sp 00007ffda8b68f40 error 6 in libpage_aligned_memory_pool.so[1f9a7,7f250d5bd000+35000] likely on CPU 81 (core 17, socket 0)
[Thu Jul  3 20:27:30 2025] Code: 00 48 39 d3 73 30 66 66 2e 0f 1f 84 00 00 00 00 00 66 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 80 00 00 00 00 48 8b 81 c0 03 00 00 <c6> 04 18 00 48 ff c3 48 39 d3 75 ed 49 81 e6 00 f0 ff ff f0 4d 29

[EDIT2]:

Uh oh! It seems to be working with the following config:

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 4 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

indeed the prefill became 2x slower, but now its not crashing after 98k tokens prefill. Let's see what it will output after the full 126k context... [EDIT3]: oh lol the client I am using (charmbracelet/mods) just crashed, but the ktransformers still doing the prefill. So now I will wait till the end of the processing and send the same query via the mods once again. Actually, to make sure the disk storage prefill works properly, first I will shut down the ktransformers, then set it to load the prefill cache from the disk, and only after that would send the same question. If everything works, it should respond within 20s. Let's see...

[EDIT4]:

omg it went through entire context up until the 132k, stopped, and apparently didnt save the prefill cache.


prefill length: 126174, prefill time: 5941.570858716965, prefill tps 21.23579824262944, decode length: 4895, decode time: 741.1875729560852, decode tps 6.60426615151847


[2025-07-03 22:45:00.137] [debug] [prefix.cpp:1632] Append Tokens to 131056
[2025-07-03 22:45:00.326] [info] [prefix.cpp:1790] GPU Flushed Back 1 cols
[2025-07-03 22:45:00.326] [debug] [gpu_cache.cpp:279] Free Page: 0/8192
[2025-07-03 22:45:00.395] [debug] [prefix.cpp:1719] 61 dirty CPU pages flushed.
2025/07/03 22:45:00.153291|INFO |th=00007F63CB08CC40|async_store.cpp:177|io_perf:IO queue remaining: 0 , processed 0.5006 M.  IO count: 0.0610 Kops, 2.2487 M/s
[2025-07-03 22:45:02.115] [info] [scheduler.cpp:760] Finish Query 2
[2025-07-03 22:45:02.642] [info] [scheduler.cpp:661] Batch 0x7f632d8381e0 is not consumed


Shutting down scheduler RPC service...
[W703 22:47:22.872010790 CudaIPCTypes.cpp:16] Producer process has been terminated before all shared CUDA tensors released. See Note [Sharing CUDA tensors]

                                                                               22:53:46 [293/1888]
==> /root/.ktransformers/logs/rpc.log <==
[2025-07-03 22:53:20.095] [info] [scheduler.cpp:661] Batch 0x7f60f80058c0 is not consumed
[2025-07-03 22:53:20.118] [info] [scheduler.cpp:661] Batch 0x7f60f8005f50 is not consumed
[2025-07-03 22:53:20.462] [info] [scheduler.cpp:661] Batch 0x7f60f80056e0 is not consumed
[2025-07-03 22:53:20.471] [info] [scheduler.cpp:661] Batch 0x7f60f80055f0 is not consumed
[2025-07-03 22:53:20.651] [info] [scheduler.cpp:597] New Query 1 is added
[2025-07-03 22:53:20.651] [info] [scheduler.cpp:720] Preparing Query 1
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:1286] Lookup TokenLength 126174
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 60a6062a5c4da9d3
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash bac7c6447e25116e
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash d61ca2a840b2a41c
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 460976e194ef97b5
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 9f4bf781e0eda9e8
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash b65bfb4764ada1ef
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 9d5c2fcfc75ac239
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 2d19fae6b86768cd
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash aa7932f86890cce6
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 14141805e2925d5c
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 6baa3912e464521e
[2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 5dfe22f04fdd23e3
[2025-07-03 22:53:20.875] [info] [prefix.cpp:1508] New Handles: 499712/499712
[2025-07-03 22:53:38.528] [debug] [prefix.cpp:1294] Found 0, Prompt Length 126174, Estimated Length 131072
[2025-07-03 22:53:38.528] [info] [prefix.cpp:1303] No Match, No need to load
[2025-07-03 22:53:38.554] [info] [prefix.cpp:1536] No match, No need to load to gpu
[2025-07-03 22:53:38.554] [info] [scheduler.cpp:735] Get handle from kvc2 Success.
[2025-07-03 22:53:38.554] [info] [scheduler.cpp:743] Ready Query 1
[2025-07-03 22:53:38.554] [info] [scheduler.cpp:915] Active query 1
[2025-07-03 22:53:38.554] [info] [scheduler.cpp:746] Prefilling Query 1
[2025-07-03 22:53:46.361] [debug] [prefix.cpp:1632] Append Tokens to 254
2025/07/03 22:53:46.990185|INFO |th=0000000000000000|async_store.cpp:66|ArrayStore:Opening /mnt/data/kvc/DeepSeek-R1-0528-GGUF/BF16/key/laye
r-0.kvc

after I restarted the ktransformers it didnt picked up the 126k previous prefill and started the prefill all over again.

<!-- gh-comment-id:3033415208 --> @magikRUKKOLA commented on GitHub (Jul 3, 2025): Ha. I can't even do 126k prefill with max_batches=4 and max_tokens=132k. Ha. Its doing OOM at about 90k prefill. Not sure what is going on. Let me kill the xfce4 process that tool 50MB of VRAM and try again. May be there is an issue with gpu_utilization configuration. [EDIT]. I tried with xfce4 killed so that only ktransformers takes up the VRAM and result is the same. ``` 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 $((32*1024)) \ --chunk_size 256 \ --max_batch_size 4 \ --temperature 0.6 \ --top_p 0.95 \ --host 0.0.0.0 \ --port 8080 \ --fast_safetensors True \ --log_level DEBUG \ --use_cuda_graph ``` and its crashing after 98k context prefill. Its steadily consuming about 22.6 GB of VRAM and its just crashing. So not only decode of 128k context is NOT working with balance_serve. But the prefill is failing too. Did anyone actually tested it? ``` 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 97, in forward temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ torch.AcceleratorError: CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. terminate called after throwing an instance of 'c10::AcceleratorError' what(): CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 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 (0x7f699b97ef00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #1: <unknown function> + 0x111a7 (0x7f699bd751a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #2: <unknown function> + 0x1c3cb (0x7f699bd803cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #3: <unknown function> + 0x1771c (0x7f699bd7b71c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #4: <unknown function> + 0x1be27 (0x7f699bd7fe27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #5: <unknown function> + 0x1d646 (0x7f699bd81646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #6: <unknown function> + 0x31b9d (0x7f699bd95b9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #7: <unknown function> + 0x36ccda (0x7f698e16ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #8: <unknown function> + 0x628158 (0x7f698e428158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #9: <unknown function> + 0x438b28 (0x7f698e238b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f699b95c145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f699b95c1c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #12: <unknown function> + 0x6cfb48 (0x7f698e4cfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #13: <unknown function> + 0x6cff1d (0x7f698e4cff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16] frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3) frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3) frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21] frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c] frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015] frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c] frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3) frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3) frame #36: <unknown function> + 0x29ca8 (0x7f699e4f4ca8 in /lib/x86_64-linux-gnu/libc.so.6) frame #37: __libc_start_main + 0x85 (0x7f699e4f4d65 in /lib/x86_64-linux-gnu/libc.so.6) frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3) ``` ``` [Thu Jul 3 20:27:30 2025] python3[621906]: segfault at 7f1dcebab ip 00007f250d5be9a7 sp 00007ffda8b68f40 error 6 in libpage_aligned_memory_pool.so[1f9a7,7f250d5bd000+35000] likely on CPU 81 (core 17, socket 0) [Thu Jul 3 20:27:30 2025] Code: 00 48 39 d3 73 30 66 66 2e 0f 1f 84 00 00 00 00 00 66 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 80 00 00 00 00 48 8b 81 c0 03 00 00 <c6> 04 18 00 48 ff c3 48 39 d3 75 ed 49 81 e6 00 f0 ff ff f0 4d 29 ``` [EDIT2]: Uh oh! It seems to be working with the following config: ``` 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 4 \ --temperature 0.6 \ --top_p 0.95 \ --host 0.0.0.0 \ --port 8080 \ --fast_safetensors True \ --log_level DEBUG \ --use_cuda_graph ``` indeed the prefill became 2x slower, but now its not crashing after 98k tokens prefill. Let's see what it will output after the full 126k context... [EDIT3]: oh lol the client I am using (charmbracelet/mods) just crashed, but the ktransformers still doing the prefill. So now I will wait till the end of the processing and send the same query via the mods once again. Actually, to make sure the disk storage prefill works properly, first I will shut down the ktransformers, then set it to load the prefill cache from the disk, and only after that would send the same question. If everything works, it should respond within 20s. Let's see... [EDIT4]: omg it went through entire context up until the 132k, stopped, and apparently didnt save the prefill cache. ``` prefill length: 126174, prefill time: 5941.570858716965, prefill tps 21.23579824262944, decode length: 4895, decode time: 741.1875729560852, decode tps 6.60426615151847 [2025-07-03 22:45:00.137] [debug] [prefix.cpp:1632] Append Tokens to 131056 [2025-07-03 22:45:00.326] [info] [prefix.cpp:1790] GPU Flushed Back 1 cols [2025-07-03 22:45:00.326] [debug] [gpu_cache.cpp:279] Free Page: 0/8192 [2025-07-03 22:45:00.395] [debug] [prefix.cpp:1719] 61 dirty CPU pages flushed. 2025/07/03 22:45:00.153291|INFO |th=00007F63CB08CC40|async_store.cpp:177|io_perf:IO queue remaining: 0 , processed 0.5006 M. IO count: 0.0610 Kops, 2.2487 M/s [2025-07-03 22:45:02.115] [info] [scheduler.cpp:760] Finish Query 2 [2025-07-03 22:45:02.642] [info] [scheduler.cpp:661] Batch 0x7f632d8381e0 is not consumed Shutting down scheduler RPC service... [W703 22:47:22.872010790 CudaIPCTypes.cpp:16] Producer process has been terminated before all shared CUDA tensors released. See Note [Sharing CUDA tensors] 22:53:46 [293/1888] ==> /root/.ktransformers/logs/rpc.log <== [2025-07-03 22:53:20.095] [info] [scheduler.cpp:661] Batch 0x7f60f80058c0 is not consumed [2025-07-03 22:53:20.118] [info] [scheduler.cpp:661] Batch 0x7f60f8005f50 is not consumed [2025-07-03 22:53:20.462] [info] [scheduler.cpp:661] Batch 0x7f60f80056e0 is not consumed [2025-07-03 22:53:20.471] [info] [scheduler.cpp:661] Batch 0x7f60f80055f0 is not consumed [2025-07-03 22:53:20.651] [info] [scheduler.cpp:597] New Query 1 is added [2025-07-03 22:53:20.651] [info] [scheduler.cpp:720] Preparing Query 1 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:1286] Lookup TokenLength 126174 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 60a6062a5c4da9d3 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash bac7c6447e25116e [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash d61ca2a840b2a41c [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 460976e194ef97b5 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 9f4bf781e0eda9e8 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash b65bfb4764ada1ef [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 9d5c2fcfc75ac239 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 2d19fae6b86768cd [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash aa7932f86890cce6 [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 14141805e2925d5c [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 6baa3912e464521e [2025-07-03 22:53:20.651] [debug] [prefix.cpp:590] Binary Prefix Search: Not Found prefix with hash 5dfe22f04fdd23e3 [2025-07-03 22:53:20.875] [info] [prefix.cpp:1508] New Handles: 499712/499712 [2025-07-03 22:53:38.528] [debug] [prefix.cpp:1294] Found 0, Prompt Length 126174, Estimated Length 131072 [2025-07-03 22:53:38.528] [info] [prefix.cpp:1303] No Match, No need to load [2025-07-03 22:53:38.554] [info] [prefix.cpp:1536] No match, No need to load to gpu [2025-07-03 22:53:38.554] [info] [scheduler.cpp:735] Get handle from kvc2 Success. [2025-07-03 22:53:38.554] [info] [scheduler.cpp:743] Ready Query 1 [2025-07-03 22:53:38.554] [info] [scheduler.cpp:915] Active query 1 [2025-07-03 22:53:38.554] [info] [scheduler.cpp:746] Prefilling Query 1 [2025-07-03 22:53:46.361] [debug] [prefix.cpp:1632] Append Tokens to 254 2025/07/03 22:53:46.990185|INFO |th=0000000000000000|async_store.cpp:66|ArrayStore:Opening /mnt/data/kvc/DeepSeek-R1-0528-GGUF/BF16/key/laye r-0.kvc ``` after I restarted the ktransformers it didnt picked up the 126k previous prefill and started the prefill all over again.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 4, 2025):

[EDIT5]:

the same config, but I didn't restart the ktransformers yet.

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 4 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

[2025-07-04 06:36:04.819] [info] [scheduler.cpp:597] New Query 2 is added
[2025-07-04 06:36:04.819] [info] [scheduler.cpp:720] Preparing Query 2
[2025-07-04 06:36:04.819] [debug] [prefix.cpp:1286] Lookup TokenLength 126174
[2025-07-04 06:36:04.819] [debug] [prefix.cpp:587] Binary Prefix Search: Found prefix with hash 60a6062a5c4da9d3

[2025-07-04 06:36:06.195] [debug] [prefix.cpp:149] Block 7884 -> Disk Location 7884
[2025-07-04 06:36:06.218] [debug] [prefix.cpp:966] Segment IO Submitted, total task count 0
[2025-07-04 06:36:06.218] [info] [prefix.cpp:1301] Loaded to mem
[2025-07-04 06:36:06.227] [info] [gpu_cache.cpp:187] GPU: Evicted 307 GPU pages
[2025-07-04 06:36:06.238] [info] [scheduler.cpp:735] Get handle from kvc2 Success.
[2025-07-04 06:36:06.242] [info] [scheduler.cpp:743] Ready Query 2
[2025-07-04 06:36:06.243] [info] [scheduler.cpp:915] Active query 2
[2025-07-04 06:36:06.243] [info] [scheduler.cpp:746] Prefilling Query 2
[2025-07-04 06:36:06.243] [info] [scheduler.cpp:756] Decoding Query 2
[2025-07-04 06:36:08.645] [debug] [prefix.cpp:1632] Append Tokens to 126176
[2025-07-04 06:36:08.686] [info] [prefix.cpp:1790] GPU Flushed Back 1 cols
[2025-07-04 06:36:08.686] [debug] [gpu_cache.cpp:279] Free Page: 0/8192
[2025-07-04 06:36:08.745] [debug] [prefix.cpp:1719] 61 dirty CPU pages flushed.


2025-07-04 06:44:29,467 INFO /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[102]: Performance(T/s): prefill 35275.513847621936, decode 6.6112784278642875. Time(s): tokenize 0.8327920436859131, prefill 3.576815366744995, decode 501.1133680343628
<!-- gh-comment-id:3034729919 --> @magikRUKKOLA commented on GitHub (Jul 4, 2025): [EDIT5]: the same config, but I didn't restart the ktransformers yet. ``` 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 4 \ --temperature 0.6 \ --top_p 0.95 \ --host 0.0.0.0 \ --port 8080 \ --fast_safetensors True \ --log_level DEBUG \ --use_cuda_graph ``` ``` [2025-07-04 06:36:04.819] [info] [scheduler.cpp:597] New Query 2 is added [2025-07-04 06:36:04.819] [info] [scheduler.cpp:720] Preparing Query 2 [2025-07-04 06:36:04.819] [debug] [prefix.cpp:1286] Lookup TokenLength 126174 [2025-07-04 06:36:04.819] [debug] [prefix.cpp:587] Binary Prefix Search: Found prefix with hash 60a6062a5c4da9d3 [2025-07-04 06:36:06.195] [debug] [prefix.cpp:149] Block 7884 -> Disk Location 7884 [2025-07-04 06:36:06.218] [debug] [prefix.cpp:966] Segment IO Submitted, total task count 0 [2025-07-04 06:36:06.218] [info] [prefix.cpp:1301] Loaded to mem [2025-07-04 06:36:06.227] [info] [gpu_cache.cpp:187] GPU: Evicted 307 GPU pages [2025-07-04 06:36:06.238] [info] [scheduler.cpp:735] Get handle from kvc2 Success. [2025-07-04 06:36:06.242] [info] [scheduler.cpp:743] Ready Query 2 [2025-07-04 06:36:06.243] [info] [scheduler.cpp:915] Active query 2 [2025-07-04 06:36:06.243] [info] [scheduler.cpp:746] Prefilling Query 2 [2025-07-04 06:36:06.243] [info] [scheduler.cpp:756] Decoding Query 2 [2025-07-04 06:36:08.645] [debug] [prefix.cpp:1632] Append Tokens to 126176 [2025-07-04 06:36:08.686] [info] [prefix.cpp:1790] GPU Flushed Back 1 cols [2025-07-04 06:36:08.686] [debug] [gpu_cache.cpp:279] Free Page: 0/8192 [2025-07-04 06:36:08.745] [debug] [prefix.cpp:1719] 61 dirty CPU pages flushed. 2025-07-04 06:44:29,467 INFO /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[102]: Performance(T/s): prefill 35275.513847621936, decode 6.6112784278642875. Time(s): tokenize 0.8327920436859131, prefill 3.576815366744995, decode 501.1133680343628 ```
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 4, 2025):

Wait a second. How the prefix cache is working exactly? Does it make s snapshot right after the prefill phase? Or only after the whole conversation is done. That is, will I be able to send a prefill chunk of text to cache it and then just append the additional questions? Because as of now it doesnt seem to support such stuff -- one can only continue the conversation by adding the questions to the conversation, but not "replacing" them via the prefix cache disk storage utilization.

<!-- gh-comment-id:3034777734 --> @magikRUKKOLA commented on GitHub (Jul 4, 2025): Wait a second. How the prefix cache is working exactly? Does it make s snapshot right after the prefill phase? Or only after the whole conversation is done. That is, will I be able to send a prefill chunk of text to cache it and then just append the additional questions? Because as of now it doesnt seem to support such stuff -- one can only continue the conversation by adding the questions to the conversation, but not "replacing" them via the prefix cache disk storage utilization.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 4, 2025):

Why there is no API to make a dump (or restore) of the KV-cache on-demand? Right now the cache just grows in size and I am not sure now to work with it. Its basically a binary blob (per layer). Why the separate files weren't used for example (say, per prefill batch)?

<!-- gh-comment-id:3034782631 --> @magikRUKKOLA commented on GitHub (Jul 4, 2025): Why there is no API to make a dump (or restore) of the KV-cache on-demand? Right now the cache just grows in size and I am not sure now to work with it. Its basically a binary blob (per layer). Why the separate files weren't used for example (say, per prefill batch)?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 4, 2025):

UPDATE!

As related to the issue regarding the:

temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]

the Deepseek V3 0324 provided the following patch to resolve the issue:

./ktransformers/server/balance_serve/inference/sampling/sampler.py

7a8
> import time
53a55,60
>       def to(self, device: torch.device):
>         #"""Move all tensors to the specified device"""
>               for attr in ['temperatures', 'top_ps', 'top_ks', 'min_ps']:
>                       if hasattr(self, attr) and getattr(self, attr) is not None:
>                               setattr(self, attr, getattr(self, attr).to(device))
>
56a64,72
>               self.last_sync_time = time.time()
>
>       def sync_if_needed(self):
>               """Synchronize CUDA operations if enough time has passed"""
>               current_time = time.time()
>               if current_time - self.last_sync_time > 0.1:  # Sync every 100ms
>                       if torch.cuda.is_available():
>                               torch.cuda.synchronize()
>                       self.last_sync_time = current_time
63,65c79,94
<               if sampling_config == None:
<                       sampling_config = SamplingOptions()
<
---
>               # Ensure proper device synchronization
>               self.sync_if_needed()
>
>               # Create sampling config if not provided
>               if sampling_config is None:
>                       sampling_config = SamplingOptions(bsz=logits.size(0),
>                                                                                        device=logits.device)
>               else:
>                       # Ensure sampling config is on the correct device
>                       sampling_config.to(logits.device)
>
>               # Verify device consistency
>               if logits.device != sampling_config.temperatures.device:
>                       raise ValueError(f"Device mismatch: logits on {logits.device}, "
>                                                        f"temperatures on {sampling_config.temperatures.device}")
>
68,89c97,100
<               if sampling_config.is_all_greedy:
<                       # Use torch.argmax if all requests use greedy sampling
<                       probs = logits
<                       batch_next_token_ids = torch.argmax(logits, -1)
<               else:
<                       # Post process logits
<                       logits.div_(sampling_config.temperatures)
<                       max_top_k_round, batch_size = 32, logits.shape[0]
<                       if sampling_config.need_min_p_sampling:
<                               probs = torch.softmax(logits, dim=-1)
<                               logits = None
<                               del logits
<                               probs = top_k_renorm_probs(probs, sampling_config.top_ks)
<                               probs = top_p_renorm_probs(probs, sampling_config.top_ps)
<                               batch_next_token_ids = min_p_sampling_from_probs(
<                                       probs, sampling_config.min_ps
<                               )
<                               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)
<                       else:
<                               # TODO: use different kernel when don't need top_k or top_p
<                               # @TODO get probs
---
>
>               try:
>                       if sampling_config.is_all_greedy:
>                               # Use torch.argmax if all requests use greedy sampling
91,98c102,152
<                               batch_next_token_ids = top_k_top_p_sampling_from_logits(
<                                       logits,
<                                       sampling_config.top_ks,
<                                       sampling_config.top_ps,
<                                       filter_apply_order="joint",
<                               )
<                               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)
---
>                               batch_next_token_ids = torch.argmax(logits, -1)
>                       else:
>                               # Post process logits
>                               logits.div_(sampling_config.temperatures)
>                               max_top_k_round, batch_size = 32, logits.shape[0]
>                               if sampling_config.need_min_p_sampling:
>                                       probs = torch.softmax(logits, dim=-1)
>                                       logits = None
>                                       del logits
>                                       probs = top_k_renorm_probs(probs, sampling_config.top_ks)
>                                       probs = top_p_renorm_probs(probs, sampling_config.top_ps)
>                                       batch_next_token_ids = min_p_sampling_from_probs(
>                                               probs, sampling_config.min_ps
>                                       )
>                                       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)
>                               else:
>                                       # TODO: use different kernel when don't need top_k or top_p
>                                       # @TODO get probs
>                                       probs = logits
>                                       batch_next_token_ids = top_k_top_p_sampling_from_logits(
>                                               logits,
>                                               sampling_config.top_ks,
>                                               sampling_config.top_ps,
>                                               filter_apply_order="joint",
>                                       )
>                                       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)
>
>                               # Add synchronization before the problematic operation
>                               if torch.cuda.is_available():
>                                       torch.cuda.synchronize()
>
>                               # Safe temperature index calculation
>                               if sampling_config.temperatures.numel() > 0:
>                                       # Use in-place operation to avoid creating intermediate tensors
>                                       temperature_0_idx = (sampling_config.temperatures == 0).nonzero(as_tuple=True)[0]
>
>                                       # Add synchronization after operation
>                                       if torch.cuda.is_available():
>                                               torch.cuda.synchronize()
>
>                                       # Only process if indices are found
>                                       if temperature_0_idx.numel() > 0:
>                                               # Ensure indices are on correct device
>                                               temperature_0_idx = temperature_0_idx.to(logits.device)
>
>                                               # Safe indexing
>                                               if temperature_0_idx.max() < origin_logits.shape[0]:
>                                                       greedy_tokens = torch.argmax(origin_logits[temperature_0_idx], -1)
>                                                       batch_next_token_ids[temperature_0_idx] = greedy_tokens.to(torch.int32)
100c154,164
<               return batch_next_token_ids.to(torch.int32), probs
\ No newline at end of file
---
>                       return batch_next_token_ids.to(torch.int32), probs
>
>               except RuntimeError as e:
>                       # Add detailed error information
>                       if "CUDA" in str(e):
>                               current_device = torch.cuda.current_device() if torch.cuda.is_available() else -1
>                               mem_info = torch.cuda.memory_summary() if torch.cuda.is_available() else "No CUDA memory info"
>                               logger.error(f"CUDA error occurred: {str(e)}")
>                               logger.error(f"Current device: {current_device}")
>                               logger.error(f"Memory info:\n{mem_info}")
>                       raise

let me check if that would solve the issue [...]

related:

https://github.com/kvcache-ai/ktransformers/issues/1269
https://github.com/kvcache-ai/ktransformers/issues/1324
https://github.com/kvcache-ai/ktransformers/issues/1376
https://github.com/kvcache-ai/ktransformers/issues/1062

<!-- gh-comment-id:3037438315 --> @magikRUKKOLA commented on GitHub (Jul 4, 2025): UPDATE! As related to the issue regarding the: ``` temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0] ``` the Deepseek V3 0324 provided the following patch to resolve the issue: **./ktransformers/server/balance_serve/inference/sampling/sampler.py** ```diff 7a8 > import time 53a55,60 > def to(self, device: torch.device): > #"""Move all tensors to the specified device""" > for attr in ['temperatures', 'top_ps', 'top_ks', 'min_ps']: > if hasattr(self, attr) and getattr(self, attr) is not None: > setattr(self, attr, getattr(self, attr).to(device)) > 56a64,72 > self.last_sync_time = time.time() > > def sync_if_needed(self): > """Synchronize CUDA operations if enough time has passed""" > current_time = time.time() > if current_time - self.last_sync_time > 0.1: # Sync every 100ms > if torch.cuda.is_available(): > torch.cuda.synchronize() > self.last_sync_time = current_time 63,65c79,94 < if sampling_config == None: < sampling_config = SamplingOptions() < --- > # Ensure proper device synchronization > self.sync_if_needed() > > # Create sampling config if not provided > if sampling_config is None: > sampling_config = SamplingOptions(bsz=logits.size(0), > device=logits.device) > else: > # Ensure sampling config is on the correct device > sampling_config.to(logits.device) > > # Verify device consistency > if logits.device != sampling_config.temperatures.device: > raise ValueError(f"Device mismatch: logits on {logits.device}, " > f"temperatures on {sampling_config.temperatures.device}") > 68,89c97,100 < if sampling_config.is_all_greedy: < # Use torch.argmax if all requests use greedy sampling < probs = logits < batch_next_token_ids = torch.argmax(logits, -1) < else: < # Post process logits < logits.div_(sampling_config.temperatures) < max_top_k_round, batch_size = 32, logits.shape[0] < if sampling_config.need_min_p_sampling: < probs = torch.softmax(logits, dim=-1) < logits = None < del logits < probs = top_k_renorm_probs(probs, sampling_config.top_ks) < probs = top_p_renorm_probs(probs, sampling_config.top_ps) < batch_next_token_ids = min_p_sampling_from_probs( < probs, sampling_config.min_ps < ) < 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) < else: < # TODO: use different kernel when don't need top_k or top_p < # @TODO get probs --- > > try: > if sampling_config.is_all_greedy: > # Use torch.argmax if all requests use greedy sampling 91,98c102,152 < batch_next_token_ids = top_k_top_p_sampling_from_logits( < logits, < sampling_config.top_ks, < sampling_config.top_ps, < filter_apply_order="joint", < ) < 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) --- > batch_next_token_ids = torch.argmax(logits, -1) > else: > # Post process logits > logits.div_(sampling_config.temperatures) > max_top_k_round, batch_size = 32, logits.shape[0] > if sampling_config.need_min_p_sampling: > probs = torch.softmax(logits, dim=-1) > logits = None > del logits > probs = top_k_renorm_probs(probs, sampling_config.top_ks) > probs = top_p_renorm_probs(probs, sampling_config.top_ps) > batch_next_token_ids = min_p_sampling_from_probs( > probs, sampling_config.min_ps > ) > 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) > else: > # TODO: use different kernel when don't need top_k or top_p > # @TODO get probs > probs = logits > batch_next_token_ids = top_k_top_p_sampling_from_logits( > logits, > sampling_config.top_ks, > sampling_config.top_ps, > filter_apply_order="joint", > ) > 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) > > # Add synchronization before the problematic operation > if torch.cuda.is_available(): > torch.cuda.synchronize() > > # Safe temperature index calculation > if sampling_config.temperatures.numel() > 0: > # Use in-place operation to avoid creating intermediate tensors > temperature_0_idx = (sampling_config.temperatures == 0).nonzero(as_tuple=True)[0] > > # Add synchronization after operation > if torch.cuda.is_available(): > torch.cuda.synchronize() > > # Only process if indices are found > if temperature_0_idx.numel() > 0: > # Ensure indices are on correct device > temperature_0_idx = temperature_0_idx.to(logits.device) > > # Safe indexing > if temperature_0_idx.max() < origin_logits.shape[0]: > greedy_tokens = torch.argmax(origin_logits[temperature_0_idx], -1) > batch_next_token_ids[temperature_0_idx] = greedy_tokens.to(torch.int32) 100c154,164 < return batch_next_token_ids.to(torch.int32), probs \ No newline at end of file --- > return batch_next_token_ids.to(torch.int32), probs > > except RuntimeError as e: > # Add detailed error information > if "CUDA" in str(e): > current_device = torch.cuda.current_device() if torch.cuda.is_available() else -1 > mem_info = torch.cuda.memory_summary() if torch.cuda.is_available() else "No CUDA memory info" > logger.error(f"CUDA error occurred: {str(e)}") > logger.error(f"Current device: {current_device}") > logger.error(f"Memory info:\n{mem_info}") > raise ``` let me check if that would solve the issue [...] related: https://github.com/kvcache-ai/ktransformers/issues/1269 https://github.com/kvcache-ai/ktransformers/issues/1324 https://github.com/kvcache-ai/ktransformers/issues/1376 https://github.com/kvcache-ai/ktransformers/issues/1062
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

Nope, still having the same issue.


CUDA error occurred: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

Current device: 0
Memory info:
|===========================================================================|
|                  PyTorch CUDA memory summary, device ID 0                 |
|---------------------------------------------------------------------------|
|            CUDA OOMs: 0            |        cudaMalloc retries: 0         |
|===========================================================================|
|        Metric         | Cur Usage  | Peak Usage | Tot Alloc  | Tot Freed  |
|---------------------------------------------------------------------------|
| Allocated memory      |  12121 MiB |  12400 MiB |    912 GiB |    900 GiB |
|       from large pool |  12007 MiB |  12400 MiB |    881 GiB |    869 GiB |
|       from small pool |    114 MiB |    118 MiB |     30 GiB |     30 GiB |
|---------------------------------------------------------------------------|
| Active memory         |  12121 MiB |  12400 MiB |    912 GiB |    900 GiB |
|       from large pool |  12007 MiB |  12400 MiB |    881 GiB |    869 GiB |
|       from small pool |    114 MiB |    118 MiB |     30 GiB |     30 GiB |
|---------------------------------------------------------------------------|
| Requested memory      |  12121 MiB |  12400 MiB |    911 GiB |    900 GiB |
|       from large pool |  12007 MiB |  12400 MiB |    881 GiB |    869 GiB |
|       from small pool |    114 MiB |    118 MiB |     30 GiB |     30 GiB |
|---------------------------------------------------------------------------|
| GPU reserved memory   |  12526 MiB |  14182 MiB | 178026 MiB | 165500 MiB |
|       from large pool |  12400 MiB |  14180 MiB | 177800 MiB | 165400 MiB |
|       from small pool |    126 MiB |    126 MiB |    226 MiB |    100 MiB |
|---------------------------------------------------------------------------|
| Non-releasable memory |      0 B   |      0 B   |      0 B   |      0 B   |
|       from large pool |      0 B   |      0 B   |      0 B   |      0 B   |
|       from small pool |      0 B   |      0 B   |      0 B   |      0 B   |
|---------------------------------------------------------------------------|
| Allocations           |    2022    |    2026    |     814 K  |     812 K  |
|       from large pool |     812    |     819    |      60 K  |      59 K  |
|       from small pool |    1210    |    1214    |     754 K  |     753 K  |
|---------------------------------------------------------------------------|
| Active allocs         |    2022    |    2026    |     814 K  |     812 K  |
|       from large pool |     812    |     819    |      60 K  |      59 K  |
|       from small pool |    1210    |    1214    |     754 K  |     753 K  |
|---------------------------------------------------------------------------|
| GPU reserved segments |       0    |       0    |       0    |       0    |
|       from large pool |       0    |       0    |       0    |       0    |
|       from small pool |       0    |       0    |       0    |       0    |
|---------------------------------------------------------------------------|
| Non-releasable allocs |       0    |       0    |       0    |       0    |
|       from large pool |       0    |       0    |       0    |       0    |
|       from small pool |       0    |       0    |       0    |       0    |
|---------------------------------------------------------------------------|
| Oversize allocations  |       0    |       0    |       0    |       0    |
|---------------------------------------------------------------------------|
| Oversize GPU segments |       0    |       0    |       0    |       0    |
|===========================================================================|

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 128, in forward
    temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]
                        ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
torch.AcceleratorError: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

terminate called after throwing an instance of 'c10::AcceleratorError'
  what():  CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
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 (0x7f59c5d7ef00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #1: <unknown function> + 0x111a7 (0x7f59c619a1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #2: <unknown function> + 0x1c3cb (0x7f59c61a53cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #3: <unknown function> + 0x1771c (0x7f59c61a071c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #4: <unknown function> + 0x1be27 (0x7f59c61a4e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #5: <unknown function> + 0x1d646 (0x7f59c61a6646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #6: <unknown function> + 0x31b9d (0x7f59c61bab9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #7: <unknown function> + 0x36ccda (0x7f59b856ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #8: <unknown function> + 0x628158 (0x7f59b8828158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #9: <unknown function> + 0x438b28 (0x7f59b8638b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f59c5d5c145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f59c5d5c1c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #12: <unknown function> + 0x6cfb48 (0x7f59b88cfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #13: <unknown function> + 0x6cff1d (0x7f59b88cff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16]
frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3)
frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3)
frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21]
frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c]
frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015]
frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c]
frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3)
frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3)
frame #36: <unknown function> + 0x29ca8 (0x7f59c8906ca8 in /lib/x86_64-linux-gnu/libc.so.6)
frame #37: __libc_start_main + 0x85 (0x7f59c8906d65 in /lib/x86_64-linux-gnu/libc.so.6)
frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)`

So the issue appears to be related to ... inability of the sample[r] to pick up the index of the tensor which has the zero temperature?

<!-- gh-comment-id:3037771077 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): Nope, still having the same issue. ``` CUDA error occurred: CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. Current device: 0 Memory info: |===========================================================================| | PyTorch CUDA memory summary, device ID 0 | |---------------------------------------------------------------------------| | CUDA OOMs: 0 | cudaMalloc retries: 0 | |===========================================================================| | Metric | Cur Usage | Peak Usage | Tot Alloc | Tot Freed | |---------------------------------------------------------------------------| | Allocated memory | 12121 MiB | 12400 MiB | 912 GiB | 900 GiB | | from large pool | 12007 MiB | 12400 MiB | 881 GiB | 869 GiB | | from small pool | 114 MiB | 118 MiB | 30 GiB | 30 GiB | |---------------------------------------------------------------------------| | Active memory | 12121 MiB | 12400 MiB | 912 GiB | 900 GiB | | from large pool | 12007 MiB | 12400 MiB | 881 GiB | 869 GiB | | from small pool | 114 MiB | 118 MiB | 30 GiB | 30 GiB | |---------------------------------------------------------------------------| | Requested memory | 12121 MiB | 12400 MiB | 911 GiB | 900 GiB | | from large pool | 12007 MiB | 12400 MiB | 881 GiB | 869 GiB | | from small pool | 114 MiB | 118 MiB | 30 GiB | 30 GiB | |---------------------------------------------------------------------------| | GPU reserved memory | 12526 MiB | 14182 MiB | 178026 MiB | 165500 MiB | | from large pool | 12400 MiB | 14180 MiB | 177800 MiB | 165400 MiB | | from small pool | 126 MiB | 126 MiB | 226 MiB | 100 MiB | |---------------------------------------------------------------------------| | Non-releasable memory | 0 B | 0 B | 0 B | 0 B | | from large pool | 0 B | 0 B | 0 B | 0 B | | from small pool | 0 B | 0 B | 0 B | 0 B | |---------------------------------------------------------------------------| | Allocations | 2022 | 2026 | 814 K | 812 K | | from large pool | 812 | 819 | 60 K | 59 K | | from small pool | 1210 | 1214 | 754 K | 753 K | |---------------------------------------------------------------------------| | Active allocs | 2022 | 2026 | 814 K | 812 K | | from large pool | 812 | 819 | 60 K | 59 K | | from small pool | 1210 | 1214 | 754 K | 753 K | |---------------------------------------------------------------------------| | GPU reserved segments | 0 | 0 | 0 | 0 | | from large pool | 0 | 0 | 0 | 0 | | from small pool | 0 | 0 | 0 | 0 | |---------------------------------------------------------------------------| | Non-releasable allocs | 0 | 0 | 0 | 0 | | from large pool | 0 | 0 | 0 | 0 | | from small pool | 0 | 0 | 0 | 0 | |---------------------------------------------------------------------------| | Oversize allocations | 0 | 0 | 0 | 0 | |---------------------------------------------------------------------------| | Oversize GPU segments | 0 | 0 | 0 | 0 | |===========================================================================| 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 128, in forward temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ torch.AcceleratorError: CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. terminate called after throwing an instance of 'c10::AcceleratorError' what(): CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 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 (0x7f59c5d7ef00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #1: <unknown function> + 0x111a7 (0x7f59c619a1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #2: <unknown function> + 0x1c3cb (0x7f59c61a53cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #3: <unknown function> + 0x1771c (0x7f59c61a071c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #4: <unknown function> + 0x1be27 (0x7f59c61a4e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #5: <unknown function> + 0x1d646 (0x7f59c61a6646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #6: <unknown function> + 0x31b9d (0x7f59c61bab9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #7: <unknown function> + 0x36ccda (0x7f59b856ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #8: <unknown function> + 0x628158 (0x7f59b8828158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #9: <unknown function> + 0x438b28 (0x7f59b8638b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f59c5d5c145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f59c5d5c1c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #12: <unknown function> + 0x6cfb48 (0x7f59b88cfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #13: <unknown function> + 0x6cff1d (0x7f59b88cff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16] frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3) frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3) frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21] frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c] frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015] frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c] frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3) frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3) frame #36: <unknown function> + 0x29ca8 (0x7f59c8906ca8 in /lib/x86_64-linux-gnu/libc.so.6) frame #37: __libc_start_main + 0x85 (0x7f59c8906d65 in /lib/x86_64-linux-gnu/libc.so.6) frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)` ``` So the issue appears to be related to ... inability of the sample[r] to pick up the index of the tensor which has the zero temperature?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

Let's try this one:

86c86,87
<                               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)
98c99,100
<                               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)

[EDIT]:

also as related to division by zero and NaN values (makes sense?):

74c74,76
<                       logits.div_(sampling_config.temperatures)
---
>                       #logits.div_(sampling_config.temperatures)
>                       safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0)
>                       logits.div_(safe_temperatures)

[EDIT2]:

so the aforementioned safetycheck would prevent the write operation into the batch_next_token_ids array. So .. why it wasn't implemented in the first place?

[EDIT3]:

lol still the same error

 prefill_batch_i: 254,
 Model execution time (GPU): 26489.635 ms, 0.038 tokens/s
 2352
 prefill_batch_i: 254,
 Model execution time (GPU): 26605.902 ms, 0.038 tokens/s
 73
 prefill_batch_i: 254,
 Model execution time (GPU): 26662.541 ms, 0.038 tokens/sProcess 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
     temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0]
                         ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 torch.AcceleratorError: CUDA error: an illegal memory access was encountered
 CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
 For debugging consider passing CUDA_LAUNCH_BLOCKING=1
 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
 terminate called after throwing an instance of 'c10::AcceleratorError'
   what():  CUDA error: an illegal memory access was encountered
 CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
 For debugging consider passing CUDA_LAUNCH_BLOCKING=1
 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 (0x7f4c02ed9f00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
 frame #1: <unknown function> + 0x111a7 (0x7f4c02f6c1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #2: <unknown function> + 0x1c3cb (0x7f4c02f773cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #3: <unknown function> + 0x1771c (0x7f4c02f7271c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #4: <unknown function> + 0x1be27 (0x7f4c02f76e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #5: <unknown function> + 0x1d646 (0x7f4c02f78646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #6: <unknown function> + 0x31b9d (0x7f4c02f8cb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
 frame #7: <unknown function> + 0x36ccda (0x7f4bf576ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #8: <unknown function> + 0x628158 (0x7f4bf5a28158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #9: <unknown function> + 0x438b28 (0x7f4bf5838b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f4c02eb7145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
 frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f4c02eb71c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
 frame #12: <unknown function> + 0x6cfb48 (0x7f4bf5acfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
 frame #13: <unknown function> + 0x6cff1d (0x7f4bf5acff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16]
 frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3)
 frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3)
 frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21]
 frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c]
 frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015]
 frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c]
 frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3)
 frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3)
 frame #36: <unknown function> + 0x29ca8 (0x7f4c05a0fca8 in /lib/x86_64-linux-gnu/libc.so.6)
 frame #37: __libc_start_main + 0x85 (0x7f4c05a0fd65 in /lib/x86_64-linux-gnu/libc.so.6)
 frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)

so its apparently related to the sync issue between the cpu and gpu huh?

[EDIT4]:

okay lets try this one:

66c66,74
<               logits = logits.contiguous()
---
>               #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)
>
>               # Add synchronization
>               torch.cuda.synchronize()
>
74c82,84
<                       logits.div_(sampling_config.temperatures)
---
>                       #logits.div_(sampling_config.temperatures)
>                       safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0)
>                       logits.div_(safe_temperatures)
84a95
>                               torch.cuda.synchronize()
86c97,98
<                               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)
96a109
>                               torch.cuda.synchronize()
98c111,112
<                               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)
<!-- gh-comment-id:3037855488 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): Let's try this one: ```diff 86c86,87 < 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) 98c99,100 < 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) ``` [EDIT]: also as related to division by zero and NaN values (makes sense?): ```diff 74c74,76 < logits.div_(sampling_config.temperatures) --- > #logits.div_(sampling_config.temperatures) > safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0) > logits.div_(safe_temperatures) ``` [EDIT2]: so the aforementioned safetycheck would prevent the write operation into the batch_next_token_ids array. So .. why it wasn't implemented in the first place? [EDIT3]: lol still the same error ``` prefill_batch_i: 254, Model execution time (GPU): 26489.635 ms, 0.038 tokens/s 2352 prefill_batch_i: 254, Model execution time (GPU): 26605.902 ms, 0.038 tokens/s 73 prefill_batch_i: 254, Model execution time (GPU): 26662.541 ms, 0.038 tokens/sProcess 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 temperature_0_idx = torch.where(sampling_config.temperatures == 0)[0] ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ torch.AcceleratorError: CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. terminate called after throwing an instance of 'c10::AcceleratorError' what(): CUDA error: an illegal memory access was encountered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 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 (0x7f4c02ed9f00 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #1: <unknown function> + 0x111a7 (0x7f4c02f6c1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #2: <unknown function> + 0x1c3cb (0x7f4c02f773cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #3: <unknown function> + 0x1771c (0x7f4c02f7271c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #4: <unknown function> + 0x1be27 (0x7f4c02f76e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #5: <unknown function> + 0x1d646 (0x7f4c02f78646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #6: <unknown function> + 0x31b9d (0x7f4c02f8cb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #7: <unknown function> + 0x36ccda (0x7f4bf576ccda in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #8: <unknown function> + 0x628158 (0x7f4bf5a28158 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #9: <unknown function> + 0x438b28 (0x7f4bf5838b28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f4c02eb7145 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f4c02eb71c9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #12: <unknown function> + 0x6cfb48 (0x7f4bf5acfb48 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #13: <unknown function> + 0x6cff1d (0x7f4bf5acff1d 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: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16] frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3) frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3) frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21] frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c] frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015] frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c] frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3) frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3) frame #36: <unknown function> + 0x29ca8 (0x7f4c05a0fca8 in /lib/x86_64-linux-gnu/libc.so.6) frame #37: __libc_start_main + 0x85 (0x7f4c05a0fd65 in /lib/x86_64-linux-gnu/libc.so.6) frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3) ``` so its apparently related to the sync issue between the cpu and gpu huh? [EDIT4]: okay lets try this one: ```diff 66c66,74 < logits = logits.contiguous() --- > #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) > > # Add synchronization > torch.cuda.synchronize() > 74c82,84 < logits.div_(sampling_config.temperatures) --- > #logits.div_(sampling_config.temperatures) > safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0) > logits.div_(safe_temperatures) 84a95 > torch.cuda.synchronize() 86c97,98 < 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) 96a109 > torch.cuda.synchronize() 98c111,112 < 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) ```
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

Apparently the solution would look like:

./ktransformers/server/balance_serve/inference/sampling/sampler.py

66c66,71
<               logits = logits.contiguous()
---
>               #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)
>
74c79,81
<                       logits.div_(sampling_config.temperatures)
---
>                       #logits.div_(sampling_config.temperatures)
>                       safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0)
>                       logits.div_(safe_temperatures)
84a92
>                               torch.cuda.synchronize()
86c94,95
<                               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)
96a106
>                               torch.cuda.synchronize()
98c108,109
<                               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)
100c111
<               return batch_next_token_ids.to(torch.int32), probs
\ No newline at end of file
---
>               return batch_next_token_ids.to(torch.int32), probs

Explanation:

  ### Why the Synchronization is Needed Where You've Kept It

  1. CUDA Graph Safety: The synchronization right before  torch.
  where(sampling_config.temperatures == 0)[0]  is crucial because:
    • The  temperatures  tensor might have been modified by previous
    operations that ran asynchronously on the GPU
    •  torch.where()  is a synchronization point that needs consistent data
  2. Race Condition Prevention: Without this sync, there could be a race
  condition where:
    • The GPU is still processing the temperature modifications
    • The CPU tries to read the temperatures for the  where()  operation
    before they're ready
  3. Correct Placement: Your sync calls are now optimally placed - right
  before the operations that actually need the synchronized state

[EDIT]: not sure if torch.cuda.synchronize() is necessary since the .to() suppose to do the sync.

<!-- gh-comment-id:3038639287 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): Apparently the solution would look like: ./ktransformers/server/balance_serve/inference/sampling/sampler.py ```diff 66c66,71 < logits = logits.contiguous() --- > #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) > 74c79,81 < logits.div_(sampling_config.temperatures) --- > #logits.div_(sampling_config.temperatures) > safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0) > logits.div_(safe_temperatures) 84a92 > torch.cuda.synchronize() 86c94,95 < 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) 96a106 > torch.cuda.synchronize() 98c108,109 < 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) 100c111 < return batch_next_token_ids.to(torch.int32), probs \ No newline at end of file --- > return batch_next_token_ids.to(torch.int32), probs ``` Explanation: ```md ### Why the Synchronization is Needed Where You've Kept It 1. CUDA Graph Safety: The synchronization right before torch. where(sampling_config.temperatures == 0)[0] is crucial because: • The temperatures tensor might have been modified by previous operations that ran asynchronously on the GPU • torch.where() is a synchronization point that needs consistent data 2. Race Condition Prevention: Without this sync, there could be a race condition where: • The GPU is still processing the temperature modifications • The CPU tries to read the temperatures for the where() operation before they're ready 3. Correct Placement: Your sync calls are now optimally placed - right before the operations that actually need the synchronized state ``` [EDIT]: not sure if torch.cuda.synchronize() is necessary since the .to() suppose to do the sync.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

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)

<!-- gh-comment-id:3038837767 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): 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) ```
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

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.

<!-- gh-comment-id:3039106635 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): 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.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

I will provide the draft for the fix below. The Deepseek R1/V3 with long context doesn't output any gibberish or any runtime error [anymore] thanks to this fix. It seems to work fine. Just in case if anyone would like to help me out debugging further they are welcome to check this out:

diff .ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py.bak .ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py
45c45,46
<         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)
48c49,50
<         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)
51d52
< 		
55,56c56,59
<             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,
58c61
<             backend = "fa2",
---
>             backend="fa2",
148c151
<         
\ No newline at end of file
---
>         
diff .ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py.bak .ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py
55c55
<       def __init__(self):
---
>       def __init__(self, device=torch.device('cuda')):
56a57
>               self.device = device
66c67,71
<               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)
>
74c79,80
<                       logits.div_(sampling_config.temperatures)
---
>                       safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0)
>                       logits.div_(safe_temperatures)
84a91
>                               torch.cuda.synchronize()
86c93,94
<                               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)
96a105
>                               torch.cuda.synchronize()
98c107,108
<                               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)
100c110
<               return batch_next_token_ids.to(torch.int32), probs
\ No newline at end of file
---
>               return batch_next_token_ids.to(torch.int32), probs

DISCLAIMER
ATTN! The code above IS NOT ready for any deployment! The code has been written by the LLM so I am not (yet) responsible for any of it!

The code is pretty much ready for the deployment.

<!-- gh-comment-id:3040256985 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): I will provide the draft for the fix below. The Deepseek R1/V3 with long context doesn't output any gibberish or any runtime error [anymore] thanks to this fix. It seems to work fine. Just in case if anyone would like to help me out debugging further they are welcome to check this out: ```bash diff .ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py.bak .ktransformers/lib/python3.13/site-packages/ktransformers/models/custom_modeling_deepseek_v3.py ``` ```diff 45c45,46 < 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) 48c49,50 < 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) 51d52 < 55,56c56,59 < 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, 58c61 < backend = "fa2", --- > backend="fa2", 148c151 < \ No newline at end of file --- > ``` ```bash diff .ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py.bak .ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py ``` ```diff 55c55 < def __init__(self): --- > def __init__(self, device=torch.device('cuda')): 56a57 > self.device = device 66c67,71 < 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) > 74c79,80 < logits.div_(sampling_config.temperatures) --- > safe_temperatures = sampling_config.temperatures.masked_fill(sampling_config.temperatures == 0, 1.0) > logits.div_(safe_temperatures) 84a91 > torch.cuda.synchronize() 86c93,94 < 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) 96a105 > torch.cuda.synchronize() 98c107,108 < 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) 100c110 < return batch_next_token_ids.to(torch.int32), probs \ No newline at end of file --- > return batch_next_token_ids.to(torch.int32), probs ``` ~~**DISCLAIMER** ATTN! The code above IS NOT ready for any deployment! The code has been written by the LLM so I am not (yet) responsible for any of it!~~ The code is pretty much ready for the deployment.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 5, 2025):

@createthis

the urgent help of the nitro coffee drinkers required!!!

<!-- gh-comment-id:3040277763 --> @magikRUKKOLA commented on GitHub (Jul 5, 2025): @createthis the urgent help of the nitro coffee drinkers required!!!
Author
Owner

@createthis commented on GitHub (Jul 5, 2025):

I’ll take a look after dinner!

<!-- gh-comment-id:3040335339 --> @createthis commented on GitHub (Jul 5, 2025): I’ll take a look after dinner!
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 6, 2025):

No crashes with the latest fix (above). Also not sure why the load of the cache from the storage device is turned off by default. Here is how to enable it:

jq '.load_from_disk = true' /mnt/data/kvc/config.json | sponge /mnt/data/kvc/config.json

the prefix caching is working great (even after the daemon restart). The only thing left to do is the management of the cache etc.

<!-- gh-comment-id:3042143786 --> @magikRUKKOLA commented on GitHub (Jul 6, 2025): No crashes with the latest fix (above). Also not sure why the load of the cache from the storage device is turned off by default. Here is how to enable it: ```bash jq '.load_from_disk = true' /mnt/data/kvc/config.json | sponge /mnt/data/kvc/config.json ``` the prefix caching is working great (even after the daemon restart). The only thing left to do is the management of the cache etc.
Author
Owner

@createthis commented on GitHub (Jul 6, 2025):

@magikRUKKOLA Sorry I didn't get to it last night. I tried to apply these diffs this morning and my patch tool is saying:

patch: **** Only garbage was found in the patch input.

I tried having ChatGPT convert the diffs to unified format, but there's a section of the second diff that has me wondering if we're patching from the same commit of the code. There's no context in your diff at that spot, so I have no idea where my chunk should go.

Can you do one of these, please:

1.) fork ktransformers to your github, then create a branch and push it, then let me know the branch so I can check it out

or

2.) Reply with the commit your code is currently at ( git log copy paste the first commit hash) and then reply with unified diffs git diff or git diff -uwb or diff -u <old> <new>.

Thanks!

<!-- gh-comment-id:3042171896 --> @createthis commented on GitHub (Jul 6, 2025): @magikRUKKOLA Sorry I didn't get to it last night. I tried to apply these diffs this morning and my patch tool is saying: ``` patch: **** Only garbage was found in the patch input. ``` I tried having ChatGPT convert the diffs to unified format, but there's a section of the second diff that has me wondering if we're patching from the same commit of the code. There's no context in your diff at that spot, so I have no idea where my chunk should go. ## Can you do one of these, please: 1.) fork `ktransformers` to your github, then create a branch and push it, then let me know the branch so I can check it out or 2.) Reply with the commit your code is currently at ( `git log` copy paste the first commit hash) and then reply with unified diffs `git diff` or `git diff -uwb` or `diff -u <old> <new>`. Thanks!
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 6, 2025):

@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
+
<!-- gh-comment-id:3042230646 --> @magikRUKKOLA commented on GitHub (Jul 6, 2025): @createthis these are with diff -u ```diff --- .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 ``` ```diff --- .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 + ```
Author
Owner

@createthis commented on GitHub (Jul 6, 2025):

Ah. There are mixed tab and space characters in those files and therefore the diffs that are making them hard to apply - probably because github or markdown is stripping the tab characters out. I had to apply them manually. Python. 🙄

I've put this into a branch on my fork and issued a PR for it: https://github.com/kvcache-ai/ktransformers/pull/1422

It's still compiling on my end. I'll test as soon as it's done.

<!-- gh-comment-id:3042413993 --> @createthis commented on GitHub (Jul 6, 2025): Ah. There are mixed tab and space characters in those files and therefore the diffs that are making them hard to apply - probably because github or markdown is stripping the tab characters out. I had to apply them manually. Python. 🙄 I've put this into a branch on my fork and issued a PR for it: https://github.com/kvcache-ai/ktransformers/pull/1422 It's still compiling on my end. I'll test as soon as it's done.
Author
Owner

@createthis commented on GitHub (Jul 6, 2025):

Tested with:

python ktransformers/server/main.py \
  --port 11434 \
  --model_path /data/DeepSeek-V3 \
  --model_name "DeepSeek-V3-0324:671b-q4_k_xl" \
  --gguf_path /data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL \
  --optimize_config_path /home/jesse/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml \
  --temperature 0.3 \
  --cpu_infer 30 \
  --cache_lens 131072 \
  --chunk_size 256 \
  --max_new_tokens 1024 \
  --backend_type ktransformers

I realize this is mostly a balance_serve PR, but all of my testing to date has focused on the ktransformers backend, so that's all I can test with confidence.

flow1.sh still crashes the ktransformers backend in one shot with this patch applied:

jesse@Jesses-MacBook-Pro ktransformers_8dc1ab9_bug_deepseek_v3_0324 % ./flow1.sh
Internal Server Error%

The backtrace looks like this:

  File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/api/openai/endpoints/chat.py", line 436, in chat_completion
    async for res in interface.inference(input_message, id, create.temperature, create.top_p, create.max_tokens, create.max_completion_tokens):
  File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 241, in inference
    async for v in super().inference(local_messages, thread_id, temperature, top_p, max_tokens, max_completion_tokens):
  File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 466, in inference
    for t in self.prefill(input_ids, self.check_is_new(thread_id), temperature, top_p, max_tokens, max_completion_tokens):
  File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 36, in generator_context
    response = gen.send(None)
               ^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 230, in prefill
    next_token = self.logits_to_token(logits[0, -1, :])
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 295, in logits_to_token
    last = torch.multinomial(probs, num_samples=1)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: CUDA error: device-side assert triggered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

/pytorch/aten/src/ATen/native/cuda/TensorCompare.cu:112: _assert_async_cuda_kernel: block: [0,0,0], thread: [0,0,0] Assertion `probability tensor contains either `inf`, `nan` or element < 0` failed.

So, it didn't really solve the issues I've identified, but it may solve other issues that don't affect me, my hardware, and environment. HTH.

<!-- gh-comment-id:3042498545 --> @createthis commented on GitHub (Jul 6, 2025): Tested with: ```bash python ktransformers/server/main.py \ --port 11434 \ --model_path /data/DeepSeek-V3 \ --model_name "DeepSeek-V3-0324:671b-q4_k_xl" \ --gguf_path /data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL \ --optimize_config_path /home/jesse/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml \ --temperature 0.3 \ --cpu_infer 30 \ --cache_lens 131072 \ --chunk_size 256 \ --max_new_tokens 1024 \ --backend_type ktransformers ``` I realize this is mostly a `balance_serve` PR, but all of my testing to date has focused on the `ktransformers` backend, so that's all I can test with confidence. [flow1.sh](https://github.com/createthis/ktransformers_8dc1ab9_bug_deepseek_v3_0324/blob/main/flow1.sh) still crashes the `ktransformers` backend in one shot with this patch applied: ```bash jesse@Jesses-MacBook-Pro ktransformers_8dc1ab9_bug_deepseek_v3_0324 % ./flow1.sh Internal Server Error% ``` The backtrace looks like this: ``` File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/api/openai/endpoints/chat.py", line 436, in chat_completion async for res in interface.inference(input_message, id, create.temperature, create.top_p, create.max_tokens, create.max_completion_tokens): File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 241, in inference async for v in super().inference(local_messages, thread_id, temperature, top_p, max_tokens, max_completion_tokens): File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 466, in inference for t in self.prefill(input_ids, self.check_is_new(thread_id), temperature, top_p, max_tokens, max_completion_tokens): File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/torch/utils/_contextlib.py", line 36, in generator_context response = gen.send(None) ^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 230, in prefill next_token = self.logits_to_token(logits[0, -1, :]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_head_cu128/lib/python3.11/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 295, in logits_to_token last = torch.multinomial(probs, num_samples=1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: CUDA error: device-side assert triggered CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. /pytorch/aten/src/ATen/native/cuda/TensorCompare.cu:112: _assert_async_cuda_kernel: block: [0,0,0], thread: [0,0,0] Assertion `probability tensor contains either `inf`, `nan` or element < 0` failed. ``` So, it didn't really solve the issues I've identified, but it may solve other issues that don't affect me, my hardware, and environment. HTH.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 6, 2025):

I realize this is mostly a balance_serve PR, but all of my testing to date has focused on the ktransformers backend, so that's all I can test with confidence.

I see your point. Recently I was doing the same but with the newest release ktransformers introduced the on-storage prefix caching which is available only with the balance_serve backend. So all my testing was focused only on balance_serve backend.

flow1.sh still crashes the ktransformers backend in one shot with this patch applied:

Okay great! Its great to have the bug-case isolated as a curl command. Just for fun I will try to reproduce your bug-case with the ktransformers legacy backend today.

<!-- gh-comment-id:3042515133 --> @magikRUKKOLA commented on GitHub (Jul 6, 2025): > I realize this is mostly a `balance_serve` PR, but all of my testing to date has focused on the `ktransformers` backend, so that's all I can test with confidence. > I see your point. Recently I was doing the same but with the newest release ktransformers introduced the on-storage prefix caching which is available only with the balance_serve backend. So all my testing was focused only on balance_serve backend. > > [flow1.sh](https://github.com/createthis/ktransformers_8dc1ab9_bug_deepseek_v3_0324/blob/main/flow1.sh) still crashes the `ktransformers` backend in one shot with this patch applied: > Okay great! Its great to have the bug-case isolated as a curl command. Just for fun I will try to reproduce your bug-case with the ktransformers legacy backend today.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

@createthis

yeah, the ktransformers is crashing indeed.

[68/1344]
   |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 263, in __call__
   |     async with anyio.create_task_group() as task_group:
   |                ~~~~~~~~~~~~~~~~~~~~~~~^^
   |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/anyio/_backends/_asyncio.py", line 772, in __aexit__
   |     raise BaseExceptionGroup(
   |         "unhandled errors in a TaskGroup", self._exceptions
   |     ) from None
   | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
   +-+---------------- 1 ----------------
     | Traceback (most recent call last):
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/uvicorn/protocols/http/h11_impl.py", line 403, in run_asgi
     |     result = await app(  # type: ignore[func-returns-value]
     |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     |         self.scope, self.receive, self.send
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     |     )
     |     ^
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
     |     return await self.app(scope, receive, send)
     |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/fastapi/applications.py", line 1054, in __call__
     |     await super().__call__(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/applications.py", line 112, in __call__
     |     await self.middleware_stack(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/errors.py", line 187, in __call__
     |     raise exc
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/errors.py", line 165, in __call__
     |     await self.app(scope, receive, _send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/cors.py", line 85, in __call__
     |     await self.app(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
     |     await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
     |     raise exc
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
     |     await app(scope, receive, sender)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 714, in __call__
     |     await self.middleware_stack(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 734, in app
     |     await route.handle(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 288, in handle
     |     await self.app(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 76, in app
     |     await wrap_app_handling_exceptions(app, request)(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
     |     raise exc
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
     |     await app(scope, receive, sender)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 74, in app
     |     await response(scope, receive, send)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 262, in __call__
     |     with collapse_excgroups():
     |          ~~~~~~~~~~~~~~~~~~^^
     |   File "/usr/lib/python3.13/contextlib.py", line 162, in __exit__
     |     self.gen.throw(value)
     |     ~~~~~~~~~~~~~~^^^^^^^
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_utils.py", line 82, in collapse_excgroups
     |     raise exc
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 266, in wrap
     |     await func()
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 246, in stream_response
     |     async for chunk in self.body_iterator:
     |     ...<2 lines>...
     |         await send({"type": "http.response.body", "body": chunk, "more_body": True})
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 80, in check_client_link
     |     async for event in async_events:
     |     ...<2 lines>...
     |         yield event
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 93, in to_stream_reply
     |     async for event in async_events:
     |     ...<3 lines>...
     |             yield event.to_stream_reply()
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 87, in add_done
     |     async for event in async_events:
     |         yield event
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 107, in filter_chat_chunk
     |     async for event in async_events:
     |         if isinstance(event, ChatCompletionChunk):
     |             yield event
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/api/openai/endpoints/chat.py", line 266, in inner
     |     async for res in interface.inference(input_message, id, create.temperature, create.top_p, create.max_tokens, create.max_completion_tokens):
     |     ...<135 lines>...
     |                         yield chunk
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 241, in inference
     |     async for v in super().inference(local_messages, thread_id, temperature, top_p, max_tokens, max_completion_tokens):
     |         yield v
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 466, in inference
     |     for t in self.prefill(input_ids, self.check_is_new(thread_id), temperature, top_p, max_tokens, max_completion_tokens):
     |              ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/utils/_contextlib.py", line 38, in generator_context
     |     response = gen.send(None)
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 230, in prefill
     |     next_token = self.logits_to_token(logits[0, -1, :])
     |   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 295, in logits_to_token
     |     last = torch.multinomial(probs, num_samples=1)
     | torch.AcceleratorError: CUDA error: device-side assert triggered
     | CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
     | For debugging consider passing CUDA_LAUNCH_BLOCKING=1
     | Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
     |
     +------------------------------------

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.

<!-- gh-comment-id:3043936404 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): @createthis yeah, the ktransformers is crashing indeed. ``` [68/1344] | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 263, in __call__ | async with anyio.create_task_group() as task_group: | ~~~~~~~~~~~~~~~~~~~~~~~^^ | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/anyio/_backends/_asyncio.py", line 772, in __aexit__ | raise BaseExceptionGroup( | "unhandled errors in a TaskGroup", self._exceptions | ) from None | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/uvicorn/protocols/http/h11_impl.py", line 403, in run_asgi | result = await app( # type: ignore[func-returns-value] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | self.scope, self.receive, self.send | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ) | ^ | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__ | return await self.app(scope, receive, send) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/fastapi/applications.py", line 1054, in __call__ | await super().__call__(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/applications.py", line 112, in __call__ | await self.middleware_stack(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/errors.py", line 187, in __call__ | raise exc | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/errors.py", line 165, in __call__ | await self.app(scope, receive, _send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/cors.py", line 85, in __call__ | await self.app(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/middleware/exceptions.py", line 62, in __call__ | await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | raise exc | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app | await app(scope, receive, sender) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 714, in __call__ | await self.middleware_stack(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 734, in app | await route.handle(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 288, in handle | await self.app(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 76, in app | await wrap_app_handling_exceptions(app, request)(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app | raise exc | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app | await app(scope, receive, sender) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/routing.py", line 74, in app | await response(scope, receive, send) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 262, in __call__ | with collapse_excgroups(): | ~~~~~~~~~~~~~~~~~~^^ | File "/usr/lib/python3.13/contextlib.py", line 162, in __exit__ | self.gen.throw(value) | ~~~~~~~~~~~~~~^^^^^^^ | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/_utils.py", line 82, in collapse_excgroups | raise exc | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 266, in wrap | await func() | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/starlette/responses.py", line 246, in stream_response | async for chunk in self.body_iterator: | ...<2 lines>... | await send({"type": "http.response.body", "body": chunk, "more_body": True}) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 80, in check_client_link | async for event in async_events: | ...<2 lines>... | yield event | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 93, in to_stream_reply | async for event in async_events: | ...<3 lines>... | yield event.to_stream_reply() | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 87, in add_done | async for event in async_events: | yield event | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/schemas/assistants/streaming.py", line 107, in filter_chat_chunk | async for event in async_events: | if isinstance(event, ChatCompletionChunk): | yield event | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/api/openai/endpoints/chat.py", line 266, in inner | async for res in interface.inference(input_message, id, create.temperature, create.top_p, create.max_tokens, create.max_completion_tokens): | ...<135 lines>... | yield chunk | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 241, in inference | async for v in super().inference(local_messages, thread_id, temperature, top_p, max_tokens, max_completion_tokens): | yield v | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 466, in inference | for t in self.prefill(input_ids, self.check_is_new(thread_id), temperature, top_p, max_tokens, max_completion_tokens): | ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/utils/_contextlib.py", line 38, in generator_context | response = gen.send(None) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/ktransformers.py", line 230, in prefill | next_token = self.logits_to_token(logits[0, -1, :]) | File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/transformers.py", line 295, in logits_to_token | last = torch.multinomial(probs, num_samples=1) | torch.AcceleratorError: CUDA error: device-side assert triggered | CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. | For debugging consider passing CUDA_LAUNCH_BLOCKING=1 | Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. | +------------------------------------ ``` 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.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

@createthis

yeah itis either crashing (above) or outputting the garbage with ktransformers legacy backend.

in fact, its seems like it wants to rape someone:

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుrapeutాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుా
 ుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుrapeutాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుrapeutాలు
 "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Paglinాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Bourgoinాలుాలుrapeutాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}

data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}
<!-- gh-comment-id:3043988311 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): @createthis yeah itis either crashing (above) or outputting the garbage with ktransformers legacy backend. in fact, its seems like it wants to rape someone: ``` data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుrapeutాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుా ుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుrapeutాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null} data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుrapeutాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null} data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Paglinాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null} data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null} data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null} data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Bourgoinాలుాలుrapeutాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null} data: {"id":"d41995247d054bdf8f0d2549d8048634","choices":[{"index":0,"delta":{"content":"Ouvrardాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలుాలు "},"finish_reason":null}],"created":1751876661,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_9779974fc781","usage":null}
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

@createthis

that's the output from the balance_serve backend with our input (with on-storage prefix cache enabled):

(no crashes, no gibberish)


data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"I'll "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"start "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"by "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"reading "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"the "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"first "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"required "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"file "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"`/workspace/WHI.Web.ClientUI/wwwroot/js/pages/care/watch.js`:\n\n"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"<function=read_file>\n"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"<parameter=path>/workspace/WHI.Web.ClientUI/wwwroot/js/pages/care/watch.js</parameter>\n"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"</function>"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":{"prompt_tokens":7936,"completion_tokens":65,"total_tokens":8001,"prompt_tokens_details":null,"completion_tokens_details":null}}

data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":{"prompt_tokens":7936,"completion_tokens":65,"total_tokens":8001,"prompt_tokens_details":null,"completion_tokens_details":null}}

data: [DONE]
<!-- gh-comment-id:3044106990 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): @createthis that's the output from the balance_serve backend with our input (with on-storage prefix cache enabled): (no crashes, no gibberish) ```text data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"I'll "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"start "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"by "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"reading "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"the "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"first "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"required "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"file "},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"`/workspace/WHI.Web.ClientUI/wwwroot/js/pages/care/watch.js`:\n\n"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"<function=read_file>\n"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"<parameter=path>/workspace/WHI.Web.ClientUI/wwwroot/js/pages/care/watch.js</parameter>\n"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{"content":"</function>"},"finish_reason":null}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":null} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":{"prompt_tokens":7936,"completion_tokens":65,"total_tokens":8001,"prompt_tokens_details":null,"completion_tokens_details":null}} data: {"id":"fc415af8b6d64cef82e967eaf687ee2f","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"created":1751879117,"model":"unsloth/DeepSeek-V3-0324-GGUF","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":"fp_f68a31478966","usage":{"prompt_tokens":7936,"completion_tokens":65,"total_tokens":8001,"prompt_tokens_details":null,"completion_tokens_details":null}} data: [DONE] ```
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

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.

<!-- gh-comment-id:3044787410 --> @createthis commented on GitHub (Jul 7, 2025): > 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.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

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.

Lets see if the authors will merge the PR you made. If not, I am forking it lol and doing everything properly.

<!-- gh-comment-id:3044877936 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): > 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. Lets see if the authors will merge the PR you made. If not, I am forking it lol and doing everything properly.
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

Lets see if the authors will merge the PR you made. If not, I am forking it lol and doing everything properly.

I wish I knew enough about LLM architecture to help. I honestly can't tell if the PR we made solves anything or if it just moves the problem around a bit like a mop with dirty water.

<!-- gh-comment-id:3044953371 --> @createthis commented on GitHub (Jul 7, 2025): > Lets see if the authors will merge the PR you made. If not, I am forking it lol and doing everything properly. I wish I knew enough about LLM architecture to help. I honestly can't tell if the PR we made solves anything or if it just moves the problem around a bit like a mop with dirty water.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

Lets see if the authors will merge the PR you made. If not, I am forking it lol and doing everything properly.

I wish I knew enough about LLM architecture to help. I honestly can't tell if the PR we made solves anything or if it just moves the problem around a bit like a mop with dirty water.

Well, at least a cannot crash the ktransformers with balance_serve backend anymore, nor it outputs some gibberish as before. The problem appears to be related to how the sampler interacts with GPU->CPU during the inference (and it increases the buffer to deal with 128k context). I mean, any kind of unit test would catch it before the release. I have no idea if anyone in ktransformers tested it before the release. Apparently not.

llama.cpp is too slow. Have you tried ik_llama.cpp with _R4 quants? It works stable but it doesn't have the tool calls or the prefix on-storage caching. So ktransformers is actually more progressive than any other framework, but it needs some polishing.

<!-- gh-comment-id:3044990311 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): > > Lets see if the authors will merge the PR you made. If not, I am forking it lol and doing everything properly. > > I wish I knew enough about LLM architecture to help. I honestly can't tell if the PR we made solves anything or if it just moves the problem around a bit like a mop with dirty water. Well, at least a cannot crash the ktransformers with balance_serve backend anymore, nor it outputs some gibberish as before. The problem appears to be related to how the sampler interacts with GPU->CPU during the inference (and it increases the buffer to deal with 128k context). I mean, any kind of unit test would catch it before the release. I have no idea if anyone in ktransformers tested it before the release. Apparently not. llama.cpp is too slow. Have you tried ik_llama.cpp with _R4 quants? It works stable but it doesn't have the tool calls or the prefix on-storage caching. So ktransformers is actually more progressive than any other framework, but it needs some polishing.
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

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.

<!-- gh-comment-id:3045026282 --> @createthis commented on GitHub (Jul 7, 2025): `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.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

@createthis but why you can't just switch to the balance_serve backend for example? Because the llama.cpp works faster in decode?

<!-- gh-comment-id:3045043210 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): @createthis but why you can't just switch to the balance_serve backend for example? Because the llama.cpp works faster in decode?
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

@createthis but why you can't just switch to the balance_serve backend for example? Because the llama.cpp works faster in decode?

Well, I didn't previously because it crashed around 30k context. My 100% reproducible bug reports for the ktransformers backend were ignored, so I moved on to a more reliable project.

You're saying the balance_serve backend has a faster prefill than llama.cpp. I wasn't aware that was the case. I can test with my next agentic batch and report back whether it crashes or not and whether it's faster or not.

<!-- gh-comment-id:3045108133 --> @createthis commented on GitHub (Jul 7, 2025): > [@createthis](https://github.com/createthis) but why you can't just switch to the balance_serve backend for example? Because the llama.cpp works faster in decode? Well, I didn't previously because it crashed around 30k context. My 100% reproducible bug reports for the ktransformers backend were ignored, so I moved on to a more reliable project. You're saying the balance_serve backend has a faster prefill than `llama.cpp`. I wasn't aware that was the case. I can test with my next agentic batch and report back whether it crashes or not and whether it's faster or not.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

Well, I didn't previously because it crashed around 30k context. My 100% reproducible bug reports for the ktransformers backend were ignored, so I moved on to a more reliable project.

Well, just to make sure, I will provide the bash script to run the ktransformers with the 128k context (for the UD-Q2_K_XL quant, you are using the different one).

export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
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 $((32*1024)) \
  --chunk_size 256 \
  --max_batch_size 4 \
  --temperature 0.6 \
  --top_p 0.95 \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG \
  --use_cuda_graph

its basically like you can to change the --optimize_config_path to the one without the '-serve' suffix and change the --backend_type as well.

be aware that the response is limited to the 32k context. But you can prefill up to 128k context.

You're saying the balance_serve backend has a faster prefill than llama.cpp. I wasn't aware that was the case. I can test with my next agentic batch and report back whether it crashes or not and whether it's faster or not.

Well, I am saying that thanks to the recently added support of the on-storage prefill, now we can prefill certain collection of the files we are working on and the backend with the on-storage prefix support will pick it up from the storage, upload it to the VRAM and continue on. In case if its stored like this, the actual prefill speed is a few thousands tokens per second, which is neat.

[EDIT]:
I am talking about the newest version with on-storage prefill support: https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/prefix_cache.md

Now its saving the prefill KV-caches into the storage device and upon every prefill it check for the matches.
But to make it work even after the restart of the service you would have to make load_from_disk: true in the config to make it load the tree.json upon the service start (I mentioned it above).

<!-- gh-comment-id:3045403172 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): > Well, I didn't previously because it crashed around 30k context. My 100% reproducible bug reports for the ktransformers backend were ignored, so I moved on to a more reliable project. Well, just to make sure, I will provide the bash script to run the ktransformers with the 128k context (for the UD-Q2_K_XL quant, you are using the different one). ```bash export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True 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 $((32*1024)) \ --chunk_size 256 \ --max_batch_size 4 \ --temperature 0.6 \ --top_p 0.95 \ --host 0.0.0.0 \ --port 8080 \ --fast_safetensors True \ --log_level DEBUG \ --use_cuda_graph ``` its basically like you can to change the --optimize_config_path to the one without the '-serve' suffix and change the --backend_type as well. be aware that the response is limited to the 32k context. But you can prefill up to 128k context. > > You're saying the balance_serve backend has a faster prefill than `llama.cpp`. I wasn't aware that was the case. I can test with my next agentic batch and report back whether it crashes or not and whether it's faster or not. Well, I am saying that thanks to the recently added support of the on-storage prefill, now we can prefill certain collection of the files we are working on and the backend with the on-storage prefix support will pick it up from the storage, upload it to the VRAM and continue on. In case if its stored like this, the actual prefill speed is a few thousands tokens per second, which is neat. [EDIT]: I am talking about the newest version with on-storage prefill support: https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/prefix_cache.md Now its saving the prefill KV-caches into the storage device and upon every prefill it check for the matches. But to make it work even after the restart of the service you would have to make load_from_disk: true in the config to make it load the tree.json upon the service start (I mentioned it above).
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

@magikRUKKOLA I tried balance_serve just now at commit 8c8cb2 with your patch. It doesn't crash, but the model (DeepSeek V3 0324 671b:Q4_K_XL) goes insane at about 17k context. Speed isn't useful without accuracy. I'm going back to llama.cpp.

<!-- gh-comment-id:3046028547 --> @createthis commented on GitHub (Jul 7, 2025): @magikRUKKOLA I tried `balance_serve` just now at commit `8c8cb2` with your patch. It doesn't crash, but the model (DeepSeek V3 0324 671b:Q4_K_XL) goes insane at about 17k context. Speed isn't useful without accuracy. I'm going back to `llama.cpp`.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

@magikRUKKOLA I tried balance_serve just now at commit 8c8cb2 with your patch. It doesn't crash, but the model (DeepSeek V3 0324 671b:Q4_K_XL) goes insane at about 17k context.

Can you share the prompt?
Because I tried with 120k+ and it doesn't output the gibberish etc. No issues basically lol

Speed isn't useful without accuracy

Absolutely.

<!-- gh-comment-id:3046063487 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): > [@magikRUKKOLA](https://github.com/magikRUKKOLA) I tried `balance_serve` just now at commit `8c8cb2` with your patch. It doesn't crash, but the model (DeepSeek V3 0324 671b:Q4_K_XL) goes insane at about 17k context. Can you share the prompt? Because I tried with 120k+ and it doesn't output the gibberish etc. No issues basically lol > Speed isn't useful without accuracy Absolutely.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

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?

<!-- gh-comment-id:3046068485 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): > 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?~~
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

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

<!-- gh-comment-id:3046091267 --> @createthis commented on GitHub (Jul 7, 2025): > > 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
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

Can you share the prompt?
Because I tried with 120k+ and it doesn't output the gibberish etc. No issues basically lol

I can't, sorry. It's proprietary. It doesn't output gibberish, it just stops following instructions in an agentic context using Open Hands AI. I'd have to record the session using a reverse proxy to see exactly what is going on with the conversation on a low level.

<!-- gh-comment-id:3046097835 --> @createthis commented on GitHub (Jul 7, 2025): > Can you share the prompt? > Because I tried with 120k+ and it doesn't output the gibberish etc. No issues basically lol I can't, sorry. It's proprietary. It doesn't output gibberish, it just stops following instructions in an agentic context using Open Hands AI. I'd have to record the session using a reverse proxy to see exactly what is going on with the conversation on a low level.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

I can't, sorry. It's proprietary. It doesn't output gibberish, it just stops following instructions in an agentic context using Open Hands AI. I'd have to record the session using a reverse proxy to see exactly what is going on with the conversation on a low level.

Stops following instructions upon reaching a certain context length? Is that correct?
And you didnt observe similar behaviour in llama.cpp?

<!-- gh-comment-id:3046125860 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): > I can't, sorry. It's proprietary. It doesn't output gibberish, it just stops following instructions in an agentic context using Open Hands AI. I'd have to record the session using a reverse proxy to see exactly what is going on with the conversation on a low level. Stops following instructions upon reaching a certain context length? Is that correct? And you didnt observe similar behaviour in llama.cpp?
Author
Owner

@createthis commented on GitHub (Jul 7, 2025):

Stops following instructions upon reaching a certain context length? Is that correct? And you didnt observe similar behaviour in llama.cpp?

Correct. This is after several turns. 3 or 4.

<!-- gh-comment-id:3046156827 --> @createthis commented on GitHub (Jul 7, 2025): > Stops following instructions upon reaching a certain context length? Is that correct? And you didnt observe similar behaviour in llama.cpp? Correct. This is after several turns. 3 or 4.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 7, 2025):

This stuff is absolutely crazy dude.

The message to the authors of the ktransformers. You guys, clearly having the issues with the stability. I am proposing the following. Lets implement the --seed parameter (as similar to the vllm) to setup the initial state and to produce the deterministic outputs. Then we would setup some test units with various prompts but with the constant models so the exact outputs of the tests will be deterministic. So every new release we would run all the tests to make sure there is no issues with the stability. It had to be done long time ago. Why no one implemented it?

[EDIT]:
basically lets implement the --seed parameter and just compare the outputs with other frameworks such as llama.cpp, vllm etc. In case they are different, we could find some bugs in the implementation of the framework in question etc.

<!-- gh-comment-id:3046165412 --> @magikRUKKOLA commented on GitHub (Jul 7, 2025): This stuff is absolutely crazy dude. The message to the authors of the ktransformers. You guys, clearly having the issues with the stability. I am proposing the following. Lets implement the --seed parameter (as similar to the vllm) to setup the initial state and to produce the deterministic outputs. Then we would setup some test units with various prompts but with the constant models so the exact outputs of the tests will be deterministic. So every new release we would run all the tests to make sure there is no issues with the stability. It had to be done long time ago. Why no one implemented it? [EDIT]: basically lets implement the --seed parameter and just compare the outputs with other frameworks such as llama.cpp, vllm etc. In case they are different, we could find some bugs in the implementation of the framework in question etc.
Author
Owner

@ikawrakow commented on GitHub (Jul 8, 2025):

@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.

<!-- gh-comment-id:3050142253 --> @ikawrakow commented on GitHub (Jul 8, 2025): @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`.
Author
Owner

@createthis commented on GitHub (Jul 8, 2025):

@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!

<!-- gh-comment-id:3050238074 --> @createthis commented on GitHub (Jul 8, 2025): @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](https://github.com/ikawrakow/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!
Author
Owner

@ikawrakow commented on GitHub (Jul 8, 2025):

And from this you concluded that ik_llama.cpp needs a different file format? It only means that ik_llama.cpp can do stuff that the other cannot. In no way does it man that ik_llama.cpp cannot do what the others can.

Just try the DeepSeek model you are trying to run with llama.cpp and KTransformers, you may be pleasantly surprised.

<!-- gh-comment-id:3050264764 --> @ikawrakow commented on GitHub (Jul 8, 2025): And from this you concluded that `ik_llama.cpp` needs a different file format? It only means that `ik_llama.cpp` can do stuff that the other cannot. In no way does it man that `ik_llama.cpp` cannot do what the others can. Just try the DeepSeek model you are trying to run with `llama.cpp` and `KTransformers`, you may be pleasantly surprised.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 8, 2025):

And from this you concluded that ik_llama.cpp needs a different file format?

In terms of getting the full advantage out of Deepseek V3/R1? Yes. So in a strictly practical sense the feeling is such. I, however, have no problem downloading it etc. ) So the point is that the Deepseek V3/R1 is the best opensource LLM so we don't see much point running anything else. So we do like to think of frameworks in terms of what quants they support etc. :) Please don't take it personally. )

<!-- gh-comment-id:3050345410 --> @magikRUKKOLA commented on GitHub (Jul 8, 2025): > And from this you concluded that `ik_llama.cpp` needs a different file format? In terms of getting the full advantage out of Deepseek V3/R1? Yes. So in a strictly practical sense the feeling is such. I, however, have no problem downloading it etc. ) So the point is that the Deepseek V3/R1 is the best opensource LLM so we don't see much point running anything else. So we do like to think of frameworks in terms of what quants they support etc. :) Please don't take it personally. )
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 8, 2025):

Just try the DeepSeek model you are trying to run with llama.cpp and KTransformers, you may be pleasantly surprised.

You mean like llama.cpp doesn't crash, works pretty stable and requires more RAM and its slow? :D At least for now it seems this way.
ktransformers are great but ... unfortunately I observed the similar behaviour as the @createthis was mentioning. It loses context from time to time. That is, its forgetting the very strict rules how the tool call had to be done etc and the whole agentic workflow with thousands of preprocessed tokens goes into shit. That's the experience of the regular user of the ktransformers now. :D

<!-- gh-comment-id:3050353328 --> @magikRUKKOLA commented on GitHub (Jul 8, 2025): > Just try the DeepSeek model you are trying to run with `llama.cpp` and `KTransformers`, you may be pleasantly surprised. You mean like llama.cpp doesn't crash, works pretty stable and requires more RAM and its slow? :D At least for now it seems this way. ktransformers are great but ... unfortunately I observed the similar behaviour as the @createthis was mentioning. It loses context from time to time. That is, its forgetting the very strict rules how the tool call had to be done etc and the whole agentic workflow with thousands of preprocessed tokens goes into shit. That's the experience of the regular user of the ktransformers now. :D
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 8, 2025):

@createthis, btw dude. I will leave some idea below related to the agentic workflow. I seen the flow1.sh of yours and the prompt from the openhands ai. And the stop-tag lol to terminate the execution after the first tool call. It looks VERY sketchy. The LLMs supposed to be pretrained to respond with a certain tool tags (see the tokenizer config). So and its seems logical that if we would want to use the tool calls, we would just ask the LLM to call the tools they way it used to. What's the point of making a new tool call format etc.? It works more stable than the native format? That's unclear.
Anyway, there is small chance that the problems you described with ktransformers (that its losing the context, that is, the workflow instructions) are actually the artifact of that custom protocol of yours. That is, everything is the other way around -- some custom glitch in llama.cpp related to the attention is responsible for correct behaviour of the agent of yours. (That's pretty unlikelty but still).
So please share the command how you run llama.cpp (at least I will make sure you're not running it with low context windows or something).

Have you experimented with a regular native tool-call format?

<!-- gh-comment-id:3050373731 --> @magikRUKKOLA commented on GitHub (Jul 8, 2025): @createthis, btw dude. I will leave some idea below related to the agentic workflow. I seen the flow1.sh of yours and the prompt from the openhands ai. And the stop-tag lol to terminate the execution after the first tool call. It looks VERY sketchy. The LLMs supposed to be pretrained to respond with a certain tool tags (see the tokenizer config). So and its seems logical that if we would want to use the tool calls, we would just ask the LLM to call the tools they way it used to. What's the point of making a new tool call format etc.? It works more stable than the native format? That's unclear. Anyway, there is small chance that the problems you described with ktransformers (that its losing the context, that is, the workflow instructions) are actually the artifact of that custom protocol of yours. That is, everything is the other way around -- some custom glitch in llama.cpp related to the attention is responsible for correct behaviour of the agent of yours. (That's pretty unlikelty but still). So please share the command how you run llama.cpp (at least I will make sure you're not running it with low context windows or something). Have you experimented with a regular native tool-call format?
Author
Owner

@createthis commented on GitHub (Jul 9, 2025):

@ikawrakow

Seriously off topic, but you brought it up, so...

I compiled ik_llama.cpp this morning with:

cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release

I started it with:

./build/bin/llama-server \
    --model /data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf \
    --alias DeepSeek-V3-0324:671b-q4_k_xl \
    --threads 32 \
    --ctx-size 163840 \
    --n-gpu-layers 62 \
    -ot ".ffn_.*_exps.=CPU" \
    --seed 3407 \
    --temp 0.3 \
    --min-p 0.0 \
    --flash-attn \
    --host 0.0.0.0 \
    --port 11434

I see this as it loads:

llm_load_tensors: offloading 61 repeating layers to GPU
llm_load_tensors: offloading non-repeating layers to GPU
llm_load_tensors: offloaded 62/62 layers to GPU
llm_load_tensors:        CPU buffer size = 44141.62 MiB
llm_load_tensors:        CPU buffer size = 46252.42 MiB
llm_load_tensors:        CPU buffer size = 45782.11 MiB
llm_load_tensors:        CPU buffer size = 47461.64 MiB
llm_load_tensors:        CPU buffer size = 45809.78 MiB
llm_load_tensors:        CPU buffer size = 46233.83 MiB
llm_load_tensors:        CPU buffer size = 47374.39 MiB
llm_load_tensors:        CPU buffer size = 40536.70 MiB
llm_load_tensors:        CPU buffer size =   497.11 MiB
llm_load_tensors:      CUDA0 buffer size =  9996.68 MiB
....................................................................................................
============ llm_prepare_mla: need to compute 61 wkv_b tensors

Then this happens:

llama_new_context_with_model: n_ctx      = 163840
llama_new_context_with_model: n_batch    = 2048
llama_new_context_with_model: n_ubatch   = 512
llama_new_context_with_model: flash_attn = 1
llama_new_context_with_model: mla_attn   = 0
llama_new_context_with_model: attn_max_b = 0
llama_new_context_with_model: fused_moe  = 0
llama_new_context_with_model: ser        = -1, 0
llama_new_context_with_model: freq_base  = 10000.0
llama_new_context_with_model: freq_scale = 0.025
ggml_backend_cuda_buffer_type_alloc_buffer: allocating 780800.00 MiB on device 0: cudaMalloc failed: out of memory
llama_kv_cache_init: failed to allocate buffer for kv cache
llama_new_context_with_model: llama_kv_cache_init() failed for self-attention cache
llama_init_from_gpt_params: error: failed to create context with model '/data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf'
 ERR [              load_model] unable to load model | tid="123346953596928" timestamp=1752067619 model="/data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf"
Segmentation fault (core dumped)

What do you recommend I change?

<!-- gh-comment-id:3052707855 --> @createthis commented on GitHub (Jul 9, 2025): @ikawrakow Seriously off topic, but you brought it up, so... I compiled `ik_llama.cpp` this morning with: ```bash cmake -B build -DGGML_CUDA=ON cmake --build build --config Release ``` I started it with: ```bash ./build/bin/llama-server \ --model /data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf \ --alias DeepSeek-V3-0324:671b-q4_k_xl \ --threads 32 \ --ctx-size 163840 \ --n-gpu-layers 62 \ -ot ".ffn_.*_exps.=CPU" \ --seed 3407 \ --temp 0.3 \ --min-p 0.0 \ --flash-attn \ --host 0.0.0.0 \ --port 11434 ``` I see this as it loads: ``` llm_load_tensors: offloading 61 repeating layers to GPU llm_load_tensors: offloading non-repeating layers to GPU llm_load_tensors: offloaded 62/62 layers to GPU llm_load_tensors: CPU buffer size = 44141.62 MiB llm_load_tensors: CPU buffer size = 46252.42 MiB llm_load_tensors: CPU buffer size = 45782.11 MiB llm_load_tensors: CPU buffer size = 47461.64 MiB llm_load_tensors: CPU buffer size = 45809.78 MiB llm_load_tensors: CPU buffer size = 46233.83 MiB llm_load_tensors: CPU buffer size = 47374.39 MiB llm_load_tensors: CPU buffer size = 40536.70 MiB llm_load_tensors: CPU buffer size = 497.11 MiB llm_load_tensors: CUDA0 buffer size = 9996.68 MiB .................................................................................................... ============ llm_prepare_mla: need to compute 61 wkv_b tensors ``` Then this happens: ``` llama_new_context_with_model: n_ctx = 163840 llama_new_context_with_model: n_batch = 2048 llama_new_context_with_model: n_ubatch = 512 llama_new_context_with_model: flash_attn = 1 llama_new_context_with_model: mla_attn = 0 llama_new_context_with_model: attn_max_b = 0 llama_new_context_with_model: fused_moe = 0 llama_new_context_with_model: ser = -1, 0 llama_new_context_with_model: freq_base = 10000.0 llama_new_context_with_model: freq_scale = 0.025 ggml_backend_cuda_buffer_type_alloc_buffer: allocating 780800.00 MiB on device 0: cudaMalloc failed: out of memory llama_kv_cache_init: failed to allocate buffer for kv cache llama_new_context_with_model: llama_kv_cache_init() failed for self-attention cache llama_init_from_gpt_params: error: failed to create context with model '/data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf' ERR [ load_model] unable to load model | tid="123346953596928" timestamp=1752067619 model="/data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf" Segmentation fault (core dumped) ``` What do you recommend I change?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 9, 2025):

@createthis

--ctx-size 163840 \

This is not a typo?

<!-- gh-comment-id:3052780105 --> @magikRUKKOLA commented on GitHub (Jul 9, 2025): @createthis > --ctx-size 163840 \ This is not a typo?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 9, 2025):

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
<!-- gh-comment-id:3052793867 --> @magikRUKKOLA commented on GitHub (Jul 9, 2025): > 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 ```
Author
Owner

@createthis commented on GitHub (Jul 9, 2025):

@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.

<!-- gh-comment-id:3052821492 --> @createthis commented on GitHub (Jul 9, 2025): > [@createthis](https://github.com/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.
Author
Owner

@ikawrakow commented on GitHub (Jul 9, 2025):

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.

<!-- gh-comment-id:3052844557 --> @ikawrakow commented on GitHub (Jul 9, 2025): 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.
Author
Owner

@createthis commented on GitHub (Jul 9, 2025):

@ikawrakow

Without recompiling with -DGGML_SCHED_MAX_COPIES=1 (I have no idea what that does), and when running with:

./build/bin/llama-server \
    --model /data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf \
    --alias DeepSeek-V3-0324:671b-q4_k_xl \
    --numa numactl \
    --threads 32 \
    --ctx-size 163840 \
    --n-gpu-layers 62 \
    -ot ".ffn_.*_exps.=CPU" \
    --seed 3407 \
    --temp 0.3 \
    --min-p 0.0 \
    --flash-attn \
    --host 0.0.0.0 \
    -mla 3 \
    -fmoe \
    --port 11434

I get about 63.26 tok/s prompt eval and 5.47 tok/s generation. I feel like regular llama.cpp's performance is better in generation and worse in prompt eval. I agree we shouldn't pollute this thread further as it's off topic. Thanks for the info though. I may play with this more.

<!-- gh-comment-id:3052914225 --> @createthis commented on GitHub (Jul 9, 2025): @ikawrakow Without recompiling with `-DGGML_SCHED_MAX_COPIES=1` (I have no idea what that does), and when running with: ```bash ./build/bin/llama-server \ --model /data/DeepSeek-V3-0324-GGUF-UD/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00008.gguf \ --alias DeepSeek-V3-0324:671b-q4_k_xl \ --numa numactl \ --threads 32 \ --ctx-size 163840 \ --n-gpu-layers 62 \ -ot ".ffn_.*_exps.=CPU" \ --seed 3407 \ --temp 0.3 \ --min-p 0.0 \ --flash-attn \ --host 0.0.0.0 \ -mla 3 \ -fmoe \ --port 11434 ``` I get about 63.26 tok/s prompt eval and 5.47 tok/s generation. I feel like regular llama.cpp's performance is better in generation and worse in prompt eval. I agree we shouldn't pollute this thread further as it's off topic. Thanks for the info though. I may play with this more.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 9, 2025):

Got the new crash recently.


Jul 09 16:25:42 xxx run-ktransformers.sh[77228]: 2025-07-09 16:25:42,502 INFO /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[102]: Performance(T/s): prefill 59.334404141554366, decode 9.977635570727058. Time(s): tokenize 0.12057065963745117, prefill 69.1335837841034, decode 373.9362871646881
Jul 09 16:30:34 xxx run-ktransformers.sh[77228]: INFO:     192.168.1.144:57922 - "GET /api/tags HTTP/1.1" 200 OK
Jul 09 16:30:34 xxx run-ktransformers.sh[77228]: INFO:     192.168.1.144:57928 - "GET /v1/models HTTP/1.1" 200 OK
Jul 09 16:30:35 xxx run-ktransformers.sh[77228]: INFO:     192.168.1.144:57928 - "POST /v1/chat/completions HTTP/1.1" 200 OK
Jul 09 16:30:35 xxx run-ktransformers.sh[77228]: 2025-07-09 16:30:35,431 DEBUG /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[418]: get input ids of shape torch.Size([1, 81338])
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Process SpawnProcess-1:
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Traceback (most recent call last):
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/usr/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     self.run()
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     ~~~~~~~~^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/usr/lib/python3.13/multiprocessing/process.py", line 108, in run
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     self._target(*self._args, **self._kwargs)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 282, in run_engine
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     engine.loop()
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     ~~~~~~~~~~~^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 260, in loop
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     generated_tokens, probs = self.sampling( self.model_runner.output)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:                               ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 224, in sampling
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     generated_tokens, probs=self.sampler(logit, sample_options)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:                             ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     return self._call_impl(*args, **kwargs)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:            ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     return forward_call(*args, **kwargs)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py", line 105, in forward
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     torch.cuda.synchronize()
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     ~~~~~~~~~~~~~~~~~~~~~~^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/cuda/__init__.py", line 1057, in synchronize
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:     return torch._C._cuda_synchronize()
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:            ~~~~~~~~~~~~~~~~~~~~~~~~~~^^
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: torch.AcceleratorError: CUDA error: an illegal memory access was encountered
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: terminate called after throwing an instance of 'c10::AcceleratorError'
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]:   what():  CUDA error: an illegal memory access was encountered
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Exception raised from c10_cuda_check_implementation at /pytorch/c10/cuda/CUDAException.cpp:42 (most recent call first):
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x80 (0x7f9470ed9240 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #1: <unknown function> + 0x111a7 (0x7f9470f6c1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #2: <unknown function> + 0x1c3cb (0x7f9470f773cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #3: <unknown function> + 0x1771c (0x7f9470f7271c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #4: <unknown function> + 0x1be27 (0x7f9470f76e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #5: <unknown function> + 0x1d646 (0x7f9470f78646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #6: <unknown function> + 0x31b9d (0x7f9470f8cb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #7: <unknown function> + 0x36e2da (0x7f946376e2da in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #8: <unknown function> + 0x629798 (0x7f9463a29798 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #9: <unknown function> + 0x43a1b8 (0x7f946383a1b8 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f9470eb6435 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f9470eb64b9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #12: <unknown function> + 0x6d1488 (0x7f9463ad1488 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #13: <unknown function> + 0x6d185d (0x7f9463ad185d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #14: /opt/ktransformers/.ktransformers/bin/python3() [0x52daa2]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #15: /opt/ktransformers/.ktransformers/bin/python3() [0x54247d]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #16: /opt/ktransformers/.ktransformers/bin/python3() [0x5cb058]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #17: /opt/ktransformers/.ktransformers/bin/python3() [0x54219a]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #18: /opt/ktransformers/.ktransformers/bin/python3() [0x54219a]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #19: /opt/ktransformers/.ktransformers/bin/python3() [0x5cb058]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #20: /opt/ktransformers/.ktransformers/bin/python3() [0x5cab4a]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #21: /opt/ktransformers/.ktransformers/bin/python3() [0x5cab4a]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #22: /opt/ktransformers/.ktransformers/bin/python3() [0x59c1af]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #23: /opt/ktransformers/.ktransformers/bin/python3() [0x59991b]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #24: /opt/ktransformers/.ktransformers/bin/python3() [0x59996f]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #25: /opt/ktransformers/.ktransformers/bin/python3() [0x59996f]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #26: /opt/ktransformers/.ktransformers/bin/python3() [0x5b3118]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #27: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c]
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #36: <unknown function> + 0x29ca8 (0x7f94757e7ca8 in /lib/x86_64-linux-gnu/libc.so.6)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #37: __libc_start_main + 0x85 (0x7f94757e7d65 in /lib/x86_64-linux-gnu/libc.so.6)
Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)

Its a very hard to catch error. The first one for a few days. I started to play with custom allocators like jemalloc to increase the probability of the occurrence of the error, but its seems to be unrelated. Some tools like cuda-memcheck are available from the cuda toolkit so I will try to debug the issue.

Surprisingly, the authors seems to be uninterested in the issue at all. Its probably makes more sense to [move to] the projects like ik_llama.cpp. At least, they dont crash like this.

[EDIT]:

https://docs.nvidia.com/compute-sanitizer/ComputeSanitizer/index.html#racecheck-tool

<!-- gh-comment-id:3053337246 --> @magikRUKKOLA commented on GitHub (Jul 9, 2025): Got the new crash recently. ``` Jul 09 16:25:42 xxx run-ktransformers.sh[77228]: 2025-07-09 16:25:42,502 INFO /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[102]: Performance(T/s): prefill 59.334404141554366, decode 9.977635570727058. Time(s): tokenize 0.12057065963745117, prefill 69.1335837841034, decode 373.9362871646881 Jul 09 16:30:34 xxx run-ktransformers.sh[77228]: INFO: 192.168.1.144:57922 - "GET /api/tags HTTP/1.1" 200 OK Jul 09 16:30:34 xxx run-ktransformers.sh[77228]: INFO: 192.168.1.144:57928 - "GET /v1/models HTTP/1.1" 200 OK Jul 09 16:30:35 xxx run-ktransformers.sh[77228]: INFO: 192.168.1.144:57928 - "POST /v1/chat/completions HTTP/1.1" 200 OK Jul 09 16:30:35 xxx run-ktransformers.sh[77228]: 2025-07-09 16:30:35,431 DEBUG /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py[418]: get input ids of shape torch.Size([1, 81338]) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Process SpawnProcess-1: Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Traceback (most recent call last): Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/usr/lib/python3.13/multiprocessing/process.py", line 313, in _bootstrap Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: self.run() Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/usr/lib/python3.13/multiprocessing/process.py", line 108, in run Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: self._target(*self._args, **self._kwargs) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 282, in run_engine Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: engine.loop() Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 260, in loop Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: generated_tokens, probs = self.sampling( self.model_runner.output) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/backend/interfaces/balance_serve.py", line 224, in sampling Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: generated_tokens, probs=self.sampler(logit, sample_options) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1773, in _wrapped_call_impl Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: return self._call_impl(*args, **kwargs) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1784, in _call_impl Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: return forward_call(*args, **kwargs) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/ktransformers/server/balance_serve/inference/sampling/sampler.py", line 105, in forward Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: torch.cuda.synchronize() Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~~~~~~~~~~~~^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: File "/opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/cuda/__init__.py", line 1057, in synchronize Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: return torch._C._cuda_synchronize() Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: ~~~~~~~~~~~~~~~~~~~~~~~~~~^^ Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: torch.AcceleratorError: CUDA error: an illegal memory access was encountered Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: terminate called after throwing an instance of 'c10::AcceleratorError' Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: what(): CUDA error: an illegal memory access was encountered Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions. Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: Exception raised from c10_cuda_check_implementation at /pytorch/c10/cuda/CUDAException.cpp:42 (most recent call first): Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) + 0x80 (0x7f9470ed9240 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #1: <unknown function> + 0x111a7 (0x7f9470f6c1a7 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #2: <unknown function> + 0x1c3cb (0x7f9470f773cb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #3: <unknown function> + 0x1771c (0x7f9470f7271c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #4: <unknown function> + 0x1be27 (0x7f9470f76e27 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #5: <unknown function> + 0x1d646 (0x7f9470f78646 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #6: <unknown function> + 0x31b9d (0x7f9470f8cb9d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #7: <unknown function> + 0x36e2da (0x7f946376e2da in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #8: <unknown function> + 0x629798 (0x7f9463a29798 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #9: <unknown function> + 0x43a1b8 (0x7f946383a1b8 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7f9470eb6435 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7f9470eb64b9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #12: <unknown function> + 0x6d1488 (0x7f9463ad1488 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #13: <unknown function> + 0x6d185d (0x7f9463ad185d in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #14: /opt/ktransformers/.ktransformers/bin/python3() [0x52daa2] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #15: /opt/ktransformers/.ktransformers/bin/python3() [0x54247d] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #16: /opt/ktransformers/.ktransformers/bin/python3() [0x5cb058] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #17: /opt/ktransformers/.ktransformers/bin/python3() [0x54219a] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #18: /opt/ktransformers/.ktransformers/bin/python3() [0x54219a] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #19: /opt/ktransformers/.ktransformers/bin/python3() [0x5cb058] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #20: /opt/ktransformers/.ktransformers/bin/python3() [0x5cab4a] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #21: /opt/ktransformers/.ktransformers/bin/python3() [0x5cab4a] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #22: /opt/ktransformers/.ktransformers/bin/python3() [0x59c1af] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #23: /opt/ktransformers/.ktransformers/bin/python3() [0x59991b] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #24: /opt/ktransformers/.ktransformers/bin/python3() [0x59996f] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #25: /opt/ktransformers/.ktransformers/bin/python3() [0x59996f] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #26: /opt/ktransformers/.ktransformers/bin/python3() [0x5b3118] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #27: /opt/ktransformers/.ktransformers/bin/python3() [0x5cad16] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #28: _PyEval_EvalFrameDefault + 0x4bde (0x561a1e in /opt/ktransformers/.ktransformers/bin/python3) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #29: PyEval_EvalCode + 0xcc (0x64d9ac in /opt/ktransformers/.ktransformers/bin/python3) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #30: /opt/ktransformers/.ktransformers/bin/python3() [0x66da21] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #31: /opt/ktransformers/.ktransformers/bin/python3() [0x669a8c] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #32: /opt/ktransformers/.ktransformers/bin/python3() [0x65c015] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #33: /opt/ktransformers/.ktransformers/bin/python3() [0x65be2c] Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #34: Py_RunMain + 0x2a9 (0x680df9 in /opt/ktransformers/.ktransformers/bin/python3) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #35: Py_BytesMain + 0x2b (0x63d36b in /opt/ktransformers/.ktransformers/bin/python3) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #36: <unknown function> + 0x29ca8 (0x7f94757e7ca8 in /lib/x86_64-linux-gnu/libc.so.6) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #37: __libc_start_main + 0x85 (0x7f94757e7d65 in /lib/x86_64-linux-gnu/libc.so.6) Jul 09 16:33:22 xxx run-ktransformers.sh[77306]: frame #38: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3) ``` Its a very hard to catch error. The first one for a few days. I started to play with custom allocators like jemalloc to increase the probability of the occurrence of the error, but its seems to be unrelated. Some tools like cuda-memcheck are available from the cuda toolkit so I will try to debug the issue. Surprisingly, the authors seems to be uninterested in the issue at all. Its probably makes more sense to [move to] the projects like ik_llama.cpp. At least, they dont crash like this. [EDIT]: https://docs.nvidia.com/compute-sanitizer/ComputeSanitizer/index.html#racecheck-tool
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 9, 2025):

I agree we shouldn't pollute this thread further as it's off topic.

Its not actually an off-topic. Its an extremely important issue how to run the full deepseek locally. The exact framework in question is irrelevant since as you pointed out, the speed doesn't matter much of its unstable. In any case, make sure to make a reference to this topic further on so I can track your progress.

<!-- gh-comment-id:3053363677 --> @magikRUKKOLA commented on GitHub (Jul 9, 2025): > I agree we shouldn't pollute this thread further as it's off topic. Its not actually an off-topic. Its an extremely important issue how to run the full deepseek locally. The exact framework in question is irrelevant since as you pointed out, the speed doesn't matter much of its unstable. In any case, make sure to make a reference to this topic further on so I can track your progress.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 9, 2025):

As related to the recent quants cooked.

https://huggingface.co/anikifoss/DeepSeek-R1-0528-DQ4_K_R4

Dynamic quantization of DeepSeek-R1-0528 for ik_llama fork, optimized to run with 24GB to 32GB VRAM and 512GB RAM systems while providing the best balance between quality and performance for coding.
THIS QUANT ONLY RUNS ON THE IK_LLAMA FORK!!!

Given the issues with the stability in ktransformers it looks like the best option is to move to the ik_llama.cpp (and add the tool calling support and fancy on-storage prefix caching). I guess the issue can be closed.
[EDIT]: i will try to find out what is causing the issues in ktranformers though.

<!-- gh-comment-id:3054318121 --> @magikRUKKOLA commented on GitHub (Jul 9, 2025): As related to the recent quants cooked. https://huggingface.co/anikifoss/DeepSeek-R1-0528-DQ4_K_R4 > Dynamic quantization of DeepSeek-R1-0528 for ik_llama fork, optimized to run with 24GB to 32GB VRAM and 512GB RAM systems while providing the best balance between quality and performance for coding. > THIS QUANT ONLY RUNS ON THE IK_LLAMA FORK!!! Given the issues with the stability in ktransformers it looks like the best option is to move to the ik_llama.cpp (and add the tool calling support and fancy on-storage prefix caching). I guess the issue can be closed. [EDIT]: i will try to find out what is causing the issues in ktranformers though.
Author
Owner

@ubergarm commented on GitHub (Jul 10, 2025):

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 配置,此方案堪称完美。

感谢!

<!-- gh-comment-id:3058222619 --> @ubergarm commented on GitHub (Jul 10, 2025): fwiw I wrote [the early ktransformers guide](https://github.com/ubergarm/r1-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/ubergarm/r1-ktransformers-guide),但现已转向投入时间开发 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 配置,此方案堪称完美。 感谢!
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 10, 2025):

@ubergarm thanks for the info!

Can you please comment regarding the issue with the context length of the Deepseek V3/R1. In ktransformers its possible to run 128k context (recently I noted that it actually supports 163k) on a single 24GB VRAM GPU by using the trick with matrix absorption. https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel
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?

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?

[EDIT]: regarding the multi-GPU config and the longer context of Deepseek V3/R1 -- may be the KV-cache for ik_llama.cpp can be distributed to two 24 GB VRAM GPUs? Unfortunately I could not find the docs regarding this. Can you point out the direction?

<!-- gh-comment-id:3058352244 --> @magikRUKKOLA commented on GitHub (Jul 10, 2025): @ubergarm thanks for the info! Can you please comment regarding the issue with the context length of the Deepseek V3/R1. In ktransformers its possible to run 128k context (recently I noted that it actually supports 163k) on a single 24GB VRAM GPU by using the trick with matrix absorption. https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel 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? 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? [EDIT]: regarding the multi-GPU config and the longer context of Deepseek V3/R1 -- may be the KV-cache for ik_llama.cpp can be distributed to two 24 GB VRAM GPUs? Unfortunately I could not find the docs regarding this. Can you point out the direction?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 10, 2025):

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

But ... the TNG-R1T2-Chimera-GGUF is not as "smart" as the R1-0528, right?:

vs R1-0528: R1T2 is a much cheaper alternative to the full R1-0528, if the full 0528-level intelligence is not required

So ... its more like a replacement of the V3-0324 then? And with ik_llama.cpp its better in performance than ktransformers? Is that correct?

<!-- gh-comment-id:3058405143 --> @magikRUKKOLA commented on GitHub (Jul 10, 2025): > 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 But ... the TNG-R1T2-Chimera-GGUF is not as "smart" as the R1-0528, right?: > vs R1-0528: R1T2 is a much cheaper alternative to the full R1-0528, if the full 0528-level intelligence is not required So ... its more like a replacement of the V3-0324 then? And with ik_llama.cpp its better in performance than ktransformers? Is that correct?
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 10, 2025):

Lets see ...

32k context:

#CUDA_VISIBLE_DEVICES="0,1" \
CUDA_VISIBLE_DEVICES="0" \
/opt/ik_llama.cpp/ik_llama.cpp/build/bin/llama-server \
    --model /opt/anikifoss/DeepSeek-R1-0528-DQ4_K_R4/DeepSeek-R1-0528-DQ4_K_R4-00001-of-00010.gguf \
    --alias anikifoss/DeepSeek-R1-0528-DQ4_K_R4 \
    --ctx-size $((32 * 1024)) \
    -ctk q8_0 \
    -mla 3 -fa \
    -amb 512 \
    -fmoe \
    --n-gpu-layers 63 \
    --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
llm_load_tensors: offloading 61 repeating layers to GPU
llm_load_tensors: offloading non-repeating layers to GPU
llm_load_tensors: offloaded 62/62 layers to GPU
llm_load_tensors:        CPU buffer size = 43123.39 MiB
llm_load_tensors:        CPU buffer size = 46063.45 MiB
llm_load_tensors:        CPU buffer size = 47413.67 MiB
llm_load_tensors:        CPU buffer size = 46321.67 MiB
llm_load_tensors:        CPU buffer size = 47413.67 MiB
llm_load_tensors:        CPU buffer size = 46321.67 MiB
llm_load_tensors:        CPU buffer size = 47413.67 MiB
llm_load_tensors:        CPU buffer size = 46321.67 MiB
llm_load_tensors:        CPU buffer size = 46336.65 MiB
llm_load_tensors:        CPU buffer size =  2016.00 MiB
llm_load_tensors:        CPU buffer size =   938.98 MiB
llm_load_tensors:      CUDA0 buffer size = 17744.02 MiB
....................................................................................................
llama_new_context_with_model: n_ctx      = 32768
llama_new_context_with_model: n_batch    = 2048
llama_new_context_with_model: n_ubatch   = 512
llama_new_context_with_model: flash_attn = 1
llama_new_context_with_model: mla_attn   = 3
llama_new_context_with_model: attn_max_b = 512
llama_new_context_with_model: fused_moe  = 1
llama_new_context_with_model: ser        = -1, 0
llama_new_context_with_model: freq_base  = 10000.0
llama_new_context_with_model: freq_scale = 0.025
llama_kv_cache_init:      CUDA0 KV buffer size =  1166.65 MiB
llama_new_context_with_model: KV self size  = 1166.62 MiB, c^KV (q8_0): 1166.62 MiB, kv^T: not used
llama_new_context_with_model:  CUDA_Host  output buffer size =     0.99 MiB
llama_new_context_with_model:      CUDA0 compute buffer size =  3425.00 MiB
llama_new_context_with_model:  CUDA_Host compute buffer size =   176.01 MiB
llama_new_context_with_model: graph nodes  = 8245
llama_new_context_with_model: graph splits = 118

64k context:

llm_load_tensors: offloaded 62/62 layers to GPU
llm_load_tensors:        CPU buffer size = 43123.39 MiB
llm_load_tensors:        CPU buffer size = 46063.45 MiB
llm_load_tensors:        CPU buffer size = 47413.67 MiB
llm_load_tensors:        CPU buffer size = 46321.67 MiB
llm_load_tensors:        CPU buffer size = 47413.67 MiB
llm_load_tensors:        CPU buffer size = 46321.67 MiB
llm_load_tensors:        CPU buffer size = 47413.67 MiB
llm_load_tensors:        CPU buffer size = 46321.67 MiB
llm_load_tensors:        CPU buffer size = 46336.65 MiB
llm_load_tensors:        CPU buffer size =  2016.00 MiB
llm_load_tensors:        CPU buffer size =   938.98 MiB
llm_load_tensors:      CUDA0 buffer size = 17744.02 MiB
....................................................................................................
llama_new_context_with_model: n_ctx      = 65536
llama_new_context_with_model: n_batch    = 2048
llama_new_context_with_model: n_ubatch   = 512
llama_new_context_with_model: flash_attn = 1
llama_new_context_with_model: mla_attn   = 3
llama_new_context_with_model: attn_max_b = 512
llama_new_context_with_model: fused_moe  = 1
llama_new_context_with_model: ser        = -1, 0
llama_new_context_with_model: freq_base  = 10000.0
llama_new_context_with_model: freq_scale = 0.025
llama_kv_cache_init:      CUDA0 KV buffer size =  2333.28 MiB
llama_new_context_with_model: KV self size  = 2333.25 MiB, c^KV (q8_0): 2333.25 MiB, kv^T: not used
llama_new_context_with_model:  CUDA_Host  output buffer size =     0.99 MiB
ggml_backend_cuda_buffer_type_alloc_buffer: allocating 6081.00 MiB on device 0: cudaMalloc failed: out of memory
ggml_gallocr_reserve_n: failed to allocate CUDA0 buffer of size 6376392704
llama_new_context_with_model: failed to allocate compute buffers

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. Is it possible to place the KV-cache onto the second GPU to extend the supported context length?

<!-- gh-comment-id:3058472386 --> @magikRUKKOLA commented on GitHub (Jul 10, 2025): Lets see ... 32k context: ``` #CUDA_VISIBLE_DEVICES="0,1" \ CUDA_VISIBLE_DEVICES="0" \ /opt/ik_llama.cpp/ik_llama.cpp/build/bin/llama-server \ --model /opt/anikifoss/DeepSeek-R1-0528-DQ4_K_R4/DeepSeek-R1-0528-DQ4_K_R4-00001-of-00010.gguf \ --alias anikifoss/DeepSeek-R1-0528-DQ4_K_R4 \ --ctx-size $((32 * 1024)) \ -ctk q8_0 \ -mla 3 -fa \ -amb 512 \ -fmoe \ --n-gpu-layers 63 \ --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 ``` ``` llm_load_tensors: offloading 61 repeating layers to GPU llm_load_tensors: offloading non-repeating layers to GPU llm_load_tensors: offloaded 62/62 layers to GPU llm_load_tensors: CPU buffer size = 43123.39 MiB llm_load_tensors: CPU buffer size = 46063.45 MiB llm_load_tensors: CPU buffer size = 47413.67 MiB llm_load_tensors: CPU buffer size = 46321.67 MiB llm_load_tensors: CPU buffer size = 47413.67 MiB llm_load_tensors: CPU buffer size = 46321.67 MiB llm_load_tensors: CPU buffer size = 47413.67 MiB llm_load_tensors: CPU buffer size = 46321.67 MiB llm_load_tensors: CPU buffer size = 46336.65 MiB llm_load_tensors: CPU buffer size = 2016.00 MiB llm_load_tensors: CPU buffer size = 938.98 MiB llm_load_tensors: CUDA0 buffer size = 17744.02 MiB .................................................................................................... llama_new_context_with_model: n_ctx = 32768 llama_new_context_with_model: n_batch = 2048 llama_new_context_with_model: n_ubatch = 512 llama_new_context_with_model: flash_attn = 1 llama_new_context_with_model: mla_attn = 3 llama_new_context_with_model: attn_max_b = 512 llama_new_context_with_model: fused_moe = 1 llama_new_context_with_model: ser = -1, 0 llama_new_context_with_model: freq_base = 10000.0 llama_new_context_with_model: freq_scale = 0.025 llama_kv_cache_init: CUDA0 KV buffer size = 1166.65 MiB llama_new_context_with_model: KV self size = 1166.62 MiB, c^KV (q8_0): 1166.62 MiB, kv^T: not used llama_new_context_with_model: CUDA_Host output buffer size = 0.99 MiB llama_new_context_with_model: CUDA0 compute buffer size = 3425.00 MiB llama_new_context_with_model: CUDA_Host compute buffer size = 176.01 MiB llama_new_context_with_model: graph nodes = 8245 llama_new_context_with_model: graph splits = 118 ``` 64k context: ``` llm_load_tensors: offloaded 62/62 layers to GPU llm_load_tensors: CPU buffer size = 43123.39 MiB llm_load_tensors: CPU buffer size = 46063.45 MiB llm_load_tensors: CPU buffer size = 47413.67 MiB llm_load_tensors: CPU buffer size = 46321.67 MiB llm_load_tensors: CPU buffer size = 47413.67 MiB llm_load_tensors: CPU buffer size = 46321.67 MiB llm_load_tensors: CPU buffer size = 47413.67 MiB llm_load_tensors: CPU buffer size = 46321.67 MiB llm_load_tensors: CPU buffer size = 46336.65 MiB llm_load_tensors: CPU buffer size = 2016.00 MiB llm_load_tensors: CPU buffer size = 938.98 MiB llm_load_tensors: CUDA0 buffer size = 17744.02 MiB .................................................................................................... llama_new_context_with_model: n_ctx = 65536 llama_new_context_with_model: n_batch = 2048 llama_new_context_with_model: n_ubatch = 512 llama_new_context_with_model: flash_attn = 1 llama_new_context_with_model: mla_attn = 3 llama_new_context_with_model: attn_max_b = 512 llama_new_context_with_model: fused_moe = 1 llama_new_context_with_model: ser = -1, 0 llama_new_context_with_model: freq_base = 10000.0 llama_new_context_with_model: freq_scale = 0.025 llama_kv_cache_init: CUDA0 KV buffer size = 2333.28 MiB llama_new_context_with_model: KV self size = 2333.25 MiB, c^KV (q8_0): 2333.25 MiB, kv^T: not used llama_new_context_with_model: CUDA_Host output buffer size = 0.99 MiB ggml_backend_cuda_buffer_type_alloc_buffer: allocating 6081.00 MiB on device 0: cudaMalloc failed: out of memory ggml_gallocr_reserve_n: failed to allocate CUDA0 buffer of size 6376392704 llama_new_context_with_model: failed to allocate compute buffers ``` 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. Is it possible to place the KV-cache onto the second GPU to extend the supported context length?
Author
Owner

@ubergarm commented on GitHub (Jul 10, 2025):

@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量化始终优于其旧版量化,而其他量化工具似乎自我设限:

<!-- gh-comment-id:3058482605 --> @ubergarm commented on GitHub (Jul 10, 2025): @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: <img width="2140" height="1456" alt="Image" src="https://github.com/user-attachments/assets/3aae0a27-2ecc-40a4-8087-747e0caf3336" /> 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.](https://github.com/ubergarm/r1-ktransformers-guide?tab=readme-ov-file#cuda-graphs) 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](https://huggingface.co/ubergarm/DeepSeek-TNG-R1T2-Chimera-GGUF/discussions/2). 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: 2. 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 3. 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. 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. 5. More flexibility for multi-GPU offload situations 6. 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: <img width="1782" height="1184" alt="Image" src="https://github.com/user-attachments/assets/f2194395-b749-460e-b8c8-b0ad5792f5b0" /> --- 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 文档中也明确提及)。[参考链接在此](https://github.com/ubergarm/r1-ktransformers-guide?tab=readme-ov-file#cuda-graphs) ik_llama.cpp可以毫无问题地通过多GPU获得速度提升。关键是要谨慎使用`-ot --override-tensor`命令,避免异常张量分割。这种方法对wen3及其他MoE模型同样有效,但需注意不同架构的张量命名规范差异。我目前正在协助一些使用游戏CPU的用户(他们拥有5块无NVLink/P2P的GPU),[在此讨论中](https://huggingface.co/ubergarm/DeepSeek-TNG-R1T2-Chimera-GGUF/discussions/2)他们获得了出色性能。我尽量在多数模型卡中提供多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更适合我的使用场景,原因如下: 2. 我需使用不支持原生fp8 e4m3的老旧GPU。据上次检查,ktranformers的混合fp8/GGUF方案要求>sm89架构 3. 我希望使用更接近llama.cpp的工具链进行困惑度对比和自主量化。这样可与bartowski、unsloth、mradermacher等其他量化方案进行公平比较(参见下图各量化方案的困惑度对比) 4. 据我所知,ktransformers底层仍是llama.cpp,因此我选择直接使用量化质量更优的ik版本 5. 多GPU卸载场景的灵活性更高 6. 中文非我母语,而ik讨论区以英语为主 根据LLM类型、显存容量和工作环境,我个人也推荐: - https://github.com/turboderp-org/exllamav3 - vllm - sglang 但对于运行这些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量化始终优于其旧版量化,而其他量化工具似乎自我设限:
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 10, 2025):

@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?

<!-- gh-comment-id:3058737352 --> @magikRUKKOLA commented on GitHub (Jul 10, 2025): @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](https://arxiv.org/abs/2405.04434)) PagedAttention on DeepSeek models. This kernel can be used in decode, and incremental prefill and should be used together with [Matrix Absorption trick](https://github.com/madsys-dev/deepseekv2-profile/blob/main/workspace/blog/optimizing-mla.md): 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](https://docs.flashinfer.ai/api/prefill.html#flashinfer.prefill.BatchPrefillWithRaggedKVCacheWrapper). > > More information about The Paged KV-Cache layout in MLA is explained in our tutorial [MLA Page Layout](https://docs.flashinfer.ai/tutorials/kv_layout.html#mla-page-layout). > > For more details about the MLA computation, Matrix Absorption and FlashInfer’s MLA implementation, please refer to our [blog post](http://flashinfer.ai/2025/02/10/flashinfer-deepseek-mla.html). As far as I can see, its not supported in ik_llama.cpp, right?
Author
Owner

@ubergarm commented on GitHub (Jul 10, 2025):

@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分支探讨。

顺颂时祺!

<!-- gh-comment-id:3058985739 --> @ubergarm commented on GitHub (Jul 10, 2025): @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](https://github.com/ikawrakow/ik_llama.cpp/discussions/258#discussioncomment-13724065) 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](https://github.com/ggml-org/llama.cpp/pull/11446#issuecomment-2624177134) as well as how [flash attention is supported with the different K and V head sizes for DeepSeek](https://github.com/ikawrakow/ik_llama.cpp/pull/200). 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](https://github.com/ikawrakow/ik_llama.cpp/pull/584) 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深度测试不同配置, 参考[近期用户实测数据](https://github.com/ikawrakow/ik_llama.cpp/discussions/258#discussioncomment-13724065) 2. 若您坚持关注实现细节而非结果,请在ik分支发起专项讨论 3. 我查阅了closed PR(主要技术资料存档处),发现[吸收优化在llama.cpp的兼容性问题](https://github.com/ggml-org/llama.cpp/pull/11446#issuecomment-2624177134)及[DeepSeek模型因K/V头尺寸差异对flash attention的支持情况](https://github.com/ikawrakow/ikllama.cpp/pull/200) 4. 补充说明:flash attention同时支持fp16和q8_0量化缓存,适用于CUDA/CPU后端(详见`-mla 3`参数)。ik近期还协助nvidia的jeffbo在[vulkan后端实现该功能](https://github.com/ikawrakow/ik_llama.cpp/pull/584) 为避免干扰本讨论区,建议移步ik分支交流。相关技术资料分散在讨论区、closed PR及我的hugging face仓库中,信息量确实庞大。欢迎携带硬件配置、当前命令及具体需求(如"在最小显存下运行最大上下文")至ik分支探讨。 顺颂时祺!
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 12, 2025):

I think I know what's up.
There is a forked flashinfer. And the according bugreports. For example:

https://github.com/flashinfer-ai/flashinfer/pull/1178
https://github.com/flashinfer-ai/flashinfer/pull/1206
https://github.com/flashinfer-ai/flashinfer/pull/1008
https://github.com/flashinfer-ai/flashinfer/pull/1059 (not sure if POD is used in ktransformers)

etc.

So I decided to use the sampling.cuh from the master branch of the flashinfer project.

[EDIT]: also pulled the mask.cuh and utils.cuh from the master. Now I will try to crash it once more.


我大概明白怎么回事了。
存在一个分叉版本的 flashinfer,以及相关的漏洞报告。例如:

https://github.com/flashinfer-ai/flashinfer/pull/1178
https://github.com/flashinfer-ai/flashinfer/pull/1206
https://github.com/flashinfer-ai/flashinfer/pull/1008
https://github.com/flashinfer-ai/flashinfer/pull/1059 (不确定 ktransformers 是否使用了 POD)

等等。

因此我决定直接采用 flashinfer 项目主分支的 sampling.cuh 文件。

<!-- gh-comment-id:3064726887 --> @magikRUKKOLA commented on GitHub (Jul 12, 2025): I think I know what's up. There is a forked flashinfer. And the according bugreports. For example: https://github.com/flashinfer-ai/flashinfer/pull/1178 https://github.com/flashinfer-ai/flashinfer/pull/1206 https://github.com/flashinfer-ai/flashinfer/pull/1008 https://github.com/flashinfer-ai/flashinfer/pull/1059 (not sure if POD is used in ktransformers) etc. So I decided to use the sampling.cuh from the master branch of the flashinfer project. [EDIT]: also pulled the mask.cuh and utils.cuh from the master. Now I will try to crash it once more. --- 我大概明白怎么回事了。 存在一个分叉版本的 flashinfer,以及相关的漏洞报告。例如: https://github.com/flashinfer-ai/flashinfer/pull/1178 https://github.com/flashinfer-ai/flashinfer/pull/1206 https://github.com/flashinfer-ai/flashinfer/pull/1008 https://github.com/flashinfer-ai/flashinfer/pull/1059 (不确定 ktransformers 是否使用了 POD) 等等。 因此我决定直接采用 flashinfer 项目主分支的 sampling.cuh 文件。
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 12, 2025):

@createthis

I honestly can't tell if the PR we made solves anything or if it just moves the problem around a bit like a mop with dirty water.

So yeah, you were right. The solution was kinda easier -- the fix sampler from the flashinfer master's has to be manually merged into custom_flashinfer of the ktransformer's master.

<!-- gh-comment-id:3065031420 --> @magikRUKKOLA commented on GitHub (Jul 12, 2025): @createthis > I honestly can't tell if the PR we made solves anything or if it just moves the problem around a bit like a mop with dirty water. So yeah, you were right. The solution was kinda easier -- the fix sampler from the flashinfer master's has to be manually merged into custom_flashinfer of the ktransformer's master.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 13, 2025):

I am having hard time crashing the ktransformers after the patching it from the latest master of flashinfer. It just outputs garbage after a really long prompt.

I can't get why no one is interested in solving this. Without it ktransformers is basically straight garbage. Imagine you prefilling 100k+ to the llm and after close to hour of waiting you getting garbage as a response. Or its just crashing (if you are lucky). Its unstable. I can't understand why you are bragging so much with how fast the ktransformers are. Its irrelevant because its unusable.


我在修补最新版本的flashinfer后,崩溃问题一直困扰着ktransformers。在输入超长提示后,它只会输出一堆乱码。

实在无法理解为什么没人愿意解决这个问题。没有修复的ktransformers简直就是废品。想象一下:你给大语言模型输入超过10万字符的前缀,苦等近一小时
后,得到的却是垃圾输出——或者干脆崩溃(如果你够幸运的话)。这玩意儿太不稳定了。真不明白你们凭什么吹嘘ktransformers的速度有多快,连基本使用都
成问题,速度快又有何意义?

(翻译说明:

  1. 将技术术语"ktransformers"和"flashinfer"保留原样
  2. "garbage"根据语境分别处理为"乱码"和"废品",在情绪表达处强化为"垃圾输出"
  3. 将"prefilling 100k+"意译为"输入超过10万字符的前缀"更符合中文表达
  4. 保留原文的讽刺语气,通过"苦等"、"玩意儿"等措辞强化不满情绪
  5. 结尾反问句"速度快又有何意义"比直译更符合中文质疑表达方式)
<!-- gh-comment-id:3066839761 --> @magikRUKKOLA commented on GitHub (Jul 13, 2025): I am having hard time crashing the ktransformers after the patching it from the latest master of flashinfer. It just outputs garbage after a really long prompt. I can't get why no one is interested in solving this. Without it ktransformers is basically straight garbage. Imagine you prefilling 100k+ to the llm and after close to hour of waiting you getting garbage as a response. Or its just crashing (if you are lucky). Its unstable. I can't understand why you are bragging so much with how fast the ktransformers are. Its irrelevant because its unusable. --- 我在修补最新版本的flashinfer后,崩溃问题一直困扰着ktransformers。在输入超长提示后,它只会输出一堆乱码。 实在无法理解为什么没人愿意解决这个问题。没有修复的ktransformers简直就是废品。想象一下:你给大语言模型输入超过10万字符的前缀,苦等近一小时 后,得到的却是垃圾输出——或者干脆崩溃(如果你够幸运的话)。这玩意儿太不稳定了。真不明白你们凭什么吹嘘ktransformers的速度有多快,连基本使用都 成问题,速度快又有何意义? (翻译说明: 1. 将技术术语"ktransformers"和"flashinfer"保留原样 2. "garbage"根据语境分别处理为"乱码"和"废品",在情绪表达处强化为"垃圾输出" 3. 将"prefilling 100k+"意译为"输入超过10万字符的前缀"更符合中文表达 4. 保留原文的讽刺语气,通过"苦等"、"玩意儿"等措辞强化不满情绪 5. 结尾反问句"速度快又有何意义"比直译更符合中文质疑表达方式)
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 13, 2025):

BTW I can't run the compute-sanitizer in order to check for the memory access violations etc. because its consuming too much VRAM. So you can't run it with compute-sanitizer and debug. Only cuda-gdb can be used.

<!-- gh-comment-id:3066866462 --> @magikRUKKOLA commented on GitHub (Jul 13, 2025): BTW I can't run the compute-sanitizer in order to check for the memory access violations etc. because its consuming too much VRAM. So you can't run it with compute-sanitizer and debug. Only cuda-gdb can be used.
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 13, 2025):

Nah, I can't figure this out. It doesn't crash and outputs garbage now (at a long context 100k+).
The ktransformers is using flashinfer (not the latest master even, but some old for with 0.2.3 version). The flashinfer IS UNSTABLE. Hence the ktransformers IS UNSTABLE AND UNUSABLE.

I will just plug-in more GPUs to increase the prefill and the context and will switch to ik_llama.cpp. I will not waste my time with this half-ass backed project. Too bad.

add query id: 2, batch.query_lengths: 101087, batch_query_tokens: torch.Size([131072]), batch.block_indexes: tensor([2049, 2050, 2051,  ..., 2046, 2047, 2048], dtype=torch.int32)
prefill_batch_i: 15,
Model execution time (GPU): 1762.493 ms, 0.567 tokens/s
CUDA Error: an illegal memory access was encountered (700) /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/data/include/flashinfer/sampling.cuh: line 1524 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 91, 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 884, 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 280, 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 (0x7fffe5d7cda0 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #1: <unknown function> + 0xa7d1 (0x7ffff25397d1 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #2: <unknown function> + 0x154bb (0x7ffff25444bb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #3: <unknown function> + 0x1094c (0x7ffff253f94c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #4: <unknown function> + 0x14f17 (0x7ffff2543f17 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #5: <unknown function> + 0x16736 (0x7ffff2545736 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #6: <unknown function> + 0x257dd (0x7ffff25547dd in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so)
frame #7: <unknown function> + 0x36f5ba (0x7fffe4d6f5ba in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #8: <unknown function> + 0x640be8 (0x7fffe5040be8 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #9: <unknown function> + 0x43e4a8 (0x7fffe4e3e4a8 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7fffe5d5a475 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7fffe5d5a4f9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so)
frame #12: <unknown function> + 0x6ecc28 (0x7fffe50ecc28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so)
frame #13: <unknown function> + 0x6ecffd (0x7fffe50ecffd 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 (0x7ffff7943ca8 in /lib/x86_64-linux-gnu/libc.so.6)
frame #36: __libc_start_main + 0x85 (0x7ffff7943d65 in /lib/x86_64-linux-gnu/libc.so.6)
frame #37: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3)
<!-- gh-comment-id:3067005362 --> @magikRUKKOLA commented on GitHub (Jul 13, 2025): Nah, I can't figure this out. It doesn't crash and outputs garbage now (at a long context 100k+). The ktransformers is using flashinfer (not the latest master even, but some old for with 0.2.3 version). The flashinfer IS UNSTABLE. Hence the ktransformers IS UNSTABLE AND UNUSABLE. I will just plug-in more GPUs to increase the prefill and the context and will switch to ik_llama.cpp. I will not waste my time with this half-ass backed project. Too bad. ``` add query id: 2, batch.query_lengths: 101087, batch_query_tokens: torch.Size([131072]), batch.block_indexes: tensor([2049, 2050, 2051, ..., 2046, 2047, 2048], dtype=torch.int32) prefill_batch_i: 15, Model execution time (GPU): 1762.493 ms, 0.567 tokens/s CUDA Error: an illegal memory access was encountered (700) /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/flashinfer/data/include/flashinfer/sampling.cuh: line 1524 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 91, 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 884, 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 280, 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 (0x7fffe5d7cda0 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #1: <unknown function> + 0xa7d1 (0x7ffff25397d1 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #2: <unknown function> + 0x154bb (0x7ffff25444bb in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #3: <unknown function> + 0x1094c (0x7ffff253f94c in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #4: <unknown function> + 0x14f17 (0x7ffff2543f17 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #5: <unknown function> + 0x16736 (0x7ffff2545736 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #6: <unknown function> + 0x257dd (0x7ffff25547dd in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10_cuda.so) frame #7: <unknown function> + 0x36f5ba (0x7fffe4d6f5ba in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #8: <unknown function> + 0x640be8 (0x7fffe5040be8 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #9: <unknown function> + 0x43e4a8 (0x7fffe4e3e4a8 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #10: c10::TensorImpl::~TensorImpl() + 0x1c5 (0x7fffe5d5a475 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #11: c10::TensorImpl::~TensorImpl() + 0x9 (0x7fffe5d5a4f9 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libc10.so) frame #12: <unknown function> + 0x6ecc28 (0x7fffe50ecc28 in /opt/ktransformers/.ktransformers/lib/python3.13/site-packages/torch/lib/libtorch_python.so) frame #13: <unknown function> + 0x6ecffd (0x7fffe50ecffd 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 (0x7ffff7943ca8 in /lib/x86_64-linux-gnu/libc.so.6) frame #36: __libc_start_main + 0x85 (0x7ffff7943d65 in /lib/x86_64-linux-gnu/libc.so.6) frame #37: _start + 0x21 (0x63c701 in /opt/ktransformers/.ktransformers/bin/python3) ```
Author
Owner

@magikRUKKOLA commented on GitHub (Jul 13, 2025):

Got 100% reproducible bug. The KV-cache is saved into a dump, and on[c]e I am sending the same 100k+ prefill the ktransformers is loading up the cache and crashing. Its about 5GB in size and I can upload it. If there is a need to debug it, please contact me.

[EDIT]:
Nope, its not 100% reproducible. Sometimes it crashes, sometimes it outputs garbage. Absolute disaster.

cat /tmp/wtf | mods -m r1q2

    We are facing a CUDA illegal memory access error in the sampling function
  during inference. The issue appears to be related to the `flashinfer`
  library's sampling implementation, specifically the `sampler.py` file where
  the `min_p_sampling_from_probs` function is called. The illegal memory
  access occurs during the `torch.where` operation in the temperature mask
  application. The `softmax` kernel produces NaN results when a thread sees a
  slice of input made up entirely of `-inf`s. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by
  zero and other potential precision errors. The `sampler.py` file has been
  updated to fix this issue by adding checks to avoid the `-inf` division by

[EDIT2]:

another example of the garbage response after 120k of context:

**Assistant**:  ==int,         ,
               , "             (),)
,
,
),
,           ,)
)
.,
,],
,],
,
          }
,       :)
,'],
,}
)
, }
            },
)
,       ],
, },
0 }
]
,       1 ',
")}        ,
            ,
           ,,
,        },
,
               ,
,
}
 of,
        )
,
,
 },
,
           ,
,
-        },

)
 },
 },
}
           )
,end)
}

and this is after the latest patches from flashinfer.

lol

<!-- gh-comment-id:3067021034 --> @magikRUKKOLA commented on GitHub (Jul 13, 2025): Got 100% reproducible bug. The KV-cache is saved into a dump, and on[c]e I am sending the same 100k+ prefill the ktransformers is loading up the cache and crashing. Its about 5GB in size and I can upload it. If there is a need to debug it, please contact me. [EDIT]: Nope, its not 100% reproducible. Sometimes it crashes, sometimes it outputs garbage. Absolute disaster. ``` cat /tmp/wtf | mods -m r1q2 We are facing a CUDA illegal memory access error in the sampling function during inference. The issue appears to be related to the `flashinfer` library's sampling implementation, specifically the `sampler.py` file where the `min_p_sampling_from_probs` function is called. The illegal memory access occurs during the `torch.where` operation in the temperature mask application. The `softmax` kernel produces NaN results when a thread sees a slice of input made up entirely of `-inf`s. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by zero and other potential precision errors. The `sampler.py` file has been updated to fix this issue by adding checks to avoid the `-inf` division by ``` [EDIT2]: another example of the garbage response after 120k of context: ``` **Assistant**: ==int, , , " (),) , , ), , ,) ) ., ,], ,], , } , :) ,'], ,} ) , } }, ) , ], , }, 0 } ] , 1 ', ")} , , ,, , }, , , , } of, ) , , }, , , , - }, ) }, }, } ) ,end) } ``` and this is after the latest patches from flashinfer. lol
Author
Owner

@BoxuanYang commented on GitHub (Sep 3, 2025):

i hv same issue, hope this can be fixed

<!-- gh-comment-id:3247401102 --> @BoxuanYang commented on GitHub (Sep 3, 2025): i hv same issue, hope this can be fixed
Author
Owner

@magikRUKKOLA commented on GitHub (Sep 3, 2025):

@BoxuanYang

i hv same issue, hope this can be fixed

2.5 months went by already. Its unlikely that it will be fixed. The FLASHINFER is unreliable.

<!-- gh-comment-id:3247752687 --> @magikRUKKOLA commented on GitHub (Sep 3, 2025): @BoxuanYang > i hv same issue, hope this can be fixed 2.5 months went by already. Its unlikely that it will be fixed. The FLASHINFER is unreliable.
Author
Owner

@jagmarques commented on GitHub (Apr 7, 2026):

The garbage-output-at-100k+ context issue @magikRUKKOLA describes is a known failure mode in FlashInfer's paged attention when the KV cache index tables overflow a certain threshold — it's not strictly a FlashInfer version issue but a configuration one.

A few things worth checking before switching away entirely:

1. Page size and block count: If block_size * max_blocks < your actual sequence length, FlashInfer silently wraps indices rather than throwing an OOM. Check that --cache-size (in tokens) is explicitly set to cover your full 100k+ prompt, not left at the default.

2. KV cache dtype mismatch: Garbage output (not crash) at long context often means the KV tensors are being written as FP16 but read as BF16, or vice versa. This gets triggered specifically at long sequences because earlier tokens' cache entries were written under one dtype and later ones under another after some internal state transition. Check model.config.torch_dtype vs what FlashInfer is initialized with.

3. Sequence ID overflow: Some older FlashInfer builds use int32 for sequence position encoding internally. At 100k+ tokens the arithmetic doesn't overflow, but if you're doing multiple turns the cumulative position counter can. Force --no-context-shift and start fresh sessions to isolate whether this is session-length vs token-length.

Workaround: For the cache-dump reload crash specifically — try clearing the KV dump and regenerating it after updating to the latest ktransformers master (the FlashInfer pinned version was bumped in a recent commit). The serialization format changed and old dumps may be incompatible.

Agree that this class of bug is painful because it's non-deterministic. Worth filing upstream with FlashInfer with a minimal reproduction if you can isolate it.

<!-- gh-comment-id:4201258624 --> @jagmarques commented on GitHub (Apr 7, 2026): The garbage-output-at-100k+ context issue @magikRUKKOLA describes is a known failure mode in FlashInfer's paged attention when the KV cache index tables overflow a certain threshold — it's not strictly a FlashInfer version issue but a configuration one. A few things worth checking before switching away entirely: **1. Page size and block count**: If `block_size * max_blocks` < your actual sequence length, FlashInfer silently wraps indices rather than throwing an OOM. Check that `--cache-size` (in tokens) is explicitly set to cover your full 100k+ prompt, not left at the default. **2. KV cache dtype mismatch**: Garbage output (not crash) at long context often means the KV tensors are being written as FP16 but read as BF16, or vice versa. This gets triggered specifically at long sequences because earlier tokens' cache entries were written under one dtype and later ones under another after some internal state transition. Check `model.config.torch_dtype` vs what FlashInfer is initialized with. **3. Sequence ID overflow**: Some older FlashInfer builds use int32 for sequence position encoding internally. At 100k+ tokens the arithmetic doesn't overflow, but if you're doing multiple turns the *cumulative* position counter can. Force `--no-context-shift` and start fresh sessions to isolate whether this is session-length vs token-length. **Workaround**: For the cache-dump reload crash specifically — try clearing the KV dump and regenerating it after updating to the latest ktransformers master (the FlashInfer pinned version was bumped in a recent commit). The serialization format changed and old dumps may be incompatible. Agree that this class of bug is painful because it's non-deterministic. Worth filing upstream with FlashInfer with a minimal reproduction if you can isolate it.
Author
Owner

@magikRUKKOLA commented on GitHub (Apr 7, 2026):

@jagmarques

Ha! Okay, suppose so.
Is there any benchmarks available for the latest version of ktransformers? For example, Kimi K2.5 Q4_X. Is there any prefill/decode available so I can cross-compare with ik_llama.cpp see https://github.com/ikawrakow/ik_llama.cpp/discussions/1544#discussioncomment-16398222

I am having close to 11 tps decode and about 120 tps prefill at zero ctx. Can ktransformers beat that?

<!-- gh-comment-id:4201329209 --> @magikRUKKOLA commented on GitHub (Apr 7, 2026): @jagmarques Ha! Okay, suppose so. Is there any benchmarks available for the latest version of ktransformers? For example, `Kimi K2.5 Q4_X`. Is there any prefill/decode available so I can cross-compare with `ik_llama.cpp` see https://github.com/ikawrakow/ik_llama.cpp/discussions/1544#discussioncomment-16398222 I am having close to 11 tps decode and about 120 tps prefill at zero ctx. Can `ktransformers` beat that?
Author
Owner

@jagmarques commented on GitHub (Apr 7, 2026):

Good question on the Kimi K2.5 benchmarks. I don't have direct numbers for ktransformers on K2.5 Q4 specifically, but from what I've seen the decode throughput depends heavily on whether you're hitting the FlashInfer paged attention path vs the fallback.

For the 11 tps decode and 120 tps prefill you're getting on ik_llama.cpp with zero context, that's solid for a single 3090. ktransformers should be in the same ballpark for decode on short context, but the stability issues you documented above are real and would eat any performance advantage at 100k+.

If you do test it, the key comparison would be at 64k+ context where the KV cache pressure actually matters. Short context benchmarks don't tell the full story since everything fits in VRAM anyway.

Let me know how the ik_llama.cpp comparison goes at long context. The community needs honest head-to-head data at 100k+ tokens, not just short-context throughput numbers.

<!-- gh-comment-id:4201413096 --> @jagmarques commented on GitHub (Apr 7, 2026): Good question on the Kimi K2.5 benchmarks. I don't have direct numbers for ktransformers on K2.5 Q4 specifically, but from what I've seen the decode throughput depends heavily on whether you're hitting the FlashInfer paged attention path vs the fallback. For the 11 tps decode and 120 tps prefill you're getting on ik_llama.cpp with zero context, that's solid for a single 3090. ktransformers should be in the same ballpark for decode on short context, but the stability issues you documented above are real and would eat any performance advantage at 100k+. If you do test it, the key comparison would be at 64k+ context where the KV cache pressure actually matters. Short context benchmarks don't tell the full story since everything fits in VRAM anyway. Let me know how the ik_llama.cpp comparison goes at long context. The community needs honest head-to-head data at 100k+ tokens, not just short-context throughput numbers.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
kvcache-ai/ktransformers#950
No description provided.