[GH-ISSUE #1122] How to use long context? #781

Closed
opened 2026-10-29 14:44:25 +00:00 by bsakaguchi · 26 comments
Owner

Originally created by @createthis on GitHub (Apr 11, 2025).
Original GitHub issue: https://github.com/kvcache-ai/ktransformers/issues/1122

I started my ktransformers like this:

python ktransformers/server/main.py \
  --port 11434 \
  --model_path /data/DeepSeek-V3 \
  --model_name "DeepSeek-V3-0324:671b-q4_k_m" \
  --gguf_path /data/DeepSeek-V3-0324/q4_files/Q4_K_M \
  --temperature 0.3 \
  --cpu_infer 30 \
  --max_new_tokens 1024 \
  --cache_lens 131072 \
  --chunk_size 256 \
  --backend_type ktransformers

Then I used 23542 context and got this error:

  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wra
pped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _cal
l_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/models/modeling_deepseek_v3.py", 
line 1206, in forward
    hidden_states, self_attn_weights, present_key_value = self.self_attn(
                                                          ^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 613, in forward
    return self.forward_linux_flashinfer(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 504, in forward_linux_flashinfer
    value_states_padded = torch.nn.functional.pad(value_states, [0, query_states.shape[-1] - value_states.shape[-1]], value=0)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/functional.py", line 5209, in pad
    return torch._C._nn.pad(input, pad, mode, value)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.06 GiB. GPU 0 has a total capacity of 23.59 GiB of which 477.06 MiB is free. Including non-PyTorch memory, this process has 23.11 GiB memory in use. Of the allocated memory 20.86 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 1.88 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

So I restarted ktransformers like this:

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

Where ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this:

diff --git a/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml b/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml
index d28e016..dc99931 100644
--- a/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml
+++ b/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml
@@ -60,7 +60,7 @@
     kwargs:
       generate_device: "cuda"
       prefill_device: "cuda"
-      absorb_for_prefill: False # change this to True to enable long context(prefill may slower).
+      absorb_for_prefill: True # change this to True to enable long context(prefill may slower).
 - match:
     name: "^model$"
   replace:
@@ -73,4 +73,4 @@
     class: "default"
     kwargs:
       generate_device: "cpu"
-      prefill_device: "cpu"
\ No newline at end of file
+      prefill_device: "cpu"

And I got this error:

  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/models.py", line 729, i
n forward
    layer_outputs = decoder_layer(
                    ^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wra
pped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _cal
l_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/models/modeling_deepseek_v3.py", 
line 1206, in forward
    hidden_states, self_attn_weights, present_key_value = self.self_attn(
                                                          ^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wra
pped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _cal
l_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 613, in forward
    return self.forward_linux_flashinfer(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 436, in forward_linux_flashinfer
    self.mla_wrapper.plan(qo_indptr,None,None,
TypeError: MLAWrapper.plan() missing 1 required positional argument: 'kv_data_type'

What am I doing wrong? I'd like to use more than 20k context.

System specs:

768G ram
dual EPYC 9355
24gb 3090

I'm running the main branch at commit f4ae7c85edd66d6acf3ef253eeaf0143eb3358ab.

Originally created by @createthis on GitHub (Apr 11, 2025). Original GitHub issue: https://github.com/kvcache-ai/ktransformers/issues/1122 I started my ktransformers like this: ```bash python ktransformers/server/main.py \ --port 11434 \ --model_path /data/DeepSeek-V3 \ --model_name "DeepSeek-V3-0324:671b-q4_k_m" \ --gguf_path /data/DeepSeek-V3-0324/q4_files/Q4_K_M \ --temperature 0.3 \ --cpu_infer 30 \ --max_new_tokens 1024 \ --cache_lens 131072 \ --chunk_size 256 \ --backend_type ktransformers ``` Then I used 23542 context and got this error: ``` File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wra pped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _cal l_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/models/modeling_deepseek_v3.py", line 1206, in forward hidden_states, self_attn_weights, present_key_value = self.self_attn( ^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 613, in forward return self.forward_linux_flashinfer( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 504, in forward_linux_flashinfer value_states_padded = torch.nn.functional.pad(value_states, [0, query_states.shape[-1] - value_states.shape[-1]], value=0) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/functional.py", line 5209, in pad return torch._C._nn.pad(input, pad, mode, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.06 GiB. GPU 0 has a total capacity of 23.59 GiB of which 477.06 MiB is free. Including non-PyTorch memory, this process has 23.11 GiB memory in use. Of the allocated memory 20.86 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 1.88 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) ``` So I restarted `ktransformers` like this: ```bash python ktransformers/server/main.py \ --port 11434 \ --model_path /data/DeepSeek-V3 \ --model_name "DeepSeek-V3-0324:671b-q4_k_m" \ --gguf_path /data/DeepSeek-V3-0324/q4_files/Q4_K_M \ --optimize_config_path ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml \ --temperature 0.3 \ --cpu_infer 30 \ --max_new_tokens 1024 \ --cache_lens 131072 \ --chunk_size 256 \ --backend_type ktransformers ``` Where `ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml` was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this: ```diff diff --git a/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml b/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml index d28e016..dc99931 100644 --- a/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml +++ b/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml @@ -60,7 +60,7 @@ kwargs: generate_device: "cuda" prefill_device: "cuda" - absorb_for_prefill: False # change this to True to enable long context(prefill may slower). + absorb_for_prefill: True # change this to True to enable long context(prefill may slower). - match: name: "^model$" replace: @@ -73,4 +73,4 @@ class: "default" kwargs: generate_device: "cpu" - prefill_device: "cpu" \ No newline at end of file + prefill_device: "cpu" ``` And I got this error: ``` File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/models.py", line 729, i n forward layer_outputs = decoder_layer( ^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wra pped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _cal l_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/models/modeling_deepseek_v3.py", line 1206, in forward hidden_states, self_attn_weights, present_key_value = self.self_attn( ^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1739, in _wra pped_call_impl return self._call_impl(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1750, in _cal l_impl return forward_call(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 613, in forward return self.forward_linux_flashinfer( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/jesse/anaconda3/envs/ktransformers_mc26/lib/python3.11/site-packages/ktransformers/operators/attention.py", line 436, in forward_linux_flashinfer self.mla_wrapper.plan(qo_indptr,None,None, TypeError: MLAWrapper.plan() missing 1 required positional argument: 'kv_data_type' ``` What am I doing wrong? I'd like to use more than 20k context. System specs: 768G ram dual EPYC 9355 24gb 3090 I'm running the `main` branch at commit `f4ae7c85edd66d6acf3ef253eeaf0143eb3358ab`.
Author
Owner

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

Where ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this:

Hold on. But what was the point? You got 3090 TI, right? So it doesn't support FP8 natively.

Also, consider creating systemd service to get the logs afterwards.

cat /etc/systemd/system/ktransformers-deepseek-v3.service
[Unit]
Description=KTransformers Service
After=network.target

[Service]
Type=simple
Restart=always
RestartSec=5
ExecStart=/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL/run-ktransformers.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

run-ktransformers.sh example:

#!/usr/bin/env bash

# uv environment
source /opt/ktransformers/.ktransformers/bin/activate

export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
export CUDA_PATH=/usr/local/cuda

export TORCH_CUDA_ARCH_LIST="8.6"

export ENABLE_TAGS_GENERATION=False
export ENABLE_AUTOCOMPLETE_GENERATION=False
export TITLE_GENERATION_PROMPT_TEMPLATE=""

ktransformers \
  --gguf_path /opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00009.gguf \
  --model_path /opt/unsloth/DeepSeek-V3-0324-GGUF/ \
  --model_name unsloth/DeepSeek-V3-0324-GGUF \
  --cpu_infer $(grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}' | xargs -I{} echo "{}-0" | bc) \
  --optimize_config_path /opt/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml \
  --cache_8bit True \
  --cache_q4 false \
  --backend_type ktransformers \
  --max_new_tokens 131072 \
  --cache_lens 131072 \
  --length 131072 \
  --temperature 0.6 \
  --top_p 0.95 \
  --use_cuda_graph \
  --host 0.0.0.0 \
  --port 8080 \
  --fast_safetensors True \
  --log_level DEBUG
<!-- gh-comment-id:2799026282 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): > Where `ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml` was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this: Hold on. But what was the point? You got 3090 TI, right? So it doesn't support FP8 natively. Also, consider creating systemd service to get the logs afterwards. ```bash cat /etc/systemd/system/ktransformers-deepseek-v3.service [Unit] Description=KTransformers Service After=network.target [Service] Type=simple Restart=always RestartSec=5 ExecStart=/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL/run-ktransformers.sh Restart=on-failure [Install] WantedBy=multi-user.target ``` run-ktransformers.sh example: ```bash #!/usr/bin/env bash # uv environment source /opt/ktransformers/.ktransformers/bin/activate export PATH=/usr/local/cuda/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH export CUDA_PATH=/usr/local/cuda export TORCH_CUDA_ARCH_LIST="8.6" export ENABLE_TAGS_GENERATION=False export ENABLE_AUTOCOMPLETE_GENERATION=False export TITLE_GENERATION_PROMPT_TEMPLATE="" ktransformers \ --gguf_path /opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL/DeepSeek-V3-0324-UD-Q4_K_XL-00001-of-00009.gguf \ --model_path /opt/unsloth/DeepSeek-V3-0324-GGUF/ \ --model_name unsloth/DeepSeek-V3-0324-GGUF \ --cpu_infer $(grep ^cpu\\scores /proc/cpuinfo | uniq | awk '{print $4}' | xargs -I{} echo "{}-0" | bc) \ --optimize_config_path /opt/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml \ --cache_8bit True \ --cache_q4 false \ --backend_type ktransformers \ --max_new_tokens 131072 \ --cache_lens 131072 \ --length 131072 \ --temperature 0.6 \ --top_p 0.95 \ --use_cuda_graph \ --host 0.0.0.0 \ --port 8080 \ --fast_safetensors True \ --log_level DEBUG ```
Author
Owner

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

As related to the systemd setup above -- this would allow you to use journalctl -u ktransformers-deepseek-v3.service --since etc. to get the logs.

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.06 GiB. GPU 0 has a total capacity of 23.59 GiB of which 477.06 MiB is free. Including non-PyTorch memory, this process has 23.11 GiB memory in use. Of the allocated memory 20.86 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 1.88 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

Interesting. Have you tried to set PYTORCH_CUDA_ALLOC_CONF=expandable_segments ?

What KV-cache are you using? Its 8 bit or 4 bit?

<!-- gh-comment-id:2799027613 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): As related to the systemd setup above -- this would allow you to use journalctl -u ktransformers-deepseek-v3.service --since etc. to get the logs. > torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.06 GiB. GPU 0 has a total capacity of 23.59 GiB of which 477.06 MiB is free. Including non-PyTorch memory, this process has 23.11 GiB memory in use. Of the allocated memory 20.86 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 1.88 GiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) Interesting. Have you tried to set PYTORCH_CUDA_ALLOC_CONF=expandable_segments ? What KV-cache are you using? Its 8 bit or 4 bit?
Author
Owner

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

--max_new_tokens 1024 \

Hm. This one is unclear. You're doing the agentic long-context session, right? If that's the case why to limit the length of the response? Did it actually made all the responses within the 1024 tokens limit?

<!-- gh-comment-id:2799028214 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): > --max_new_tokens 1024 \ Hm. This one is unclear. You're doing the agentic long-context session, right? If that's the case why to limit the length of the response? Did it actually made all the responses within the 1024 tokens limit?
Author
Owner

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

is there anything else is occupying the gpu memory besides ktransformers? like Xorg, or xfwm4 etc.?

<!-- gh-comment-id:2799034218 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): is there anything else is occupying the gpu memory besides ktransformers? like Xorg, or xfwm4 etc.?
Author
Owner

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

Apr 12 21:32:30 tr2p run-ktransformers.sh[99421]: 2025-04-12 21:32:30,876 INFO /opt/ktransformers/.ktransformers/lib/python3.12/site-packages/ktransformers/server/backend/interfaces/transformers.py[335]: args.max_new_tokens: 131072, cache_lens: 131072, seq_length: 26594

I seems like I have no problem going through 26k context window on my RTX 3090 24GB.
Its like:

MEM[||||||||||||||||||23.969Gi/24.000Gi]

Not sure how the memory management is made. It seem to grow larger with larger context.
It might be time to add the second GPU.

<!-- gh-comment-id:2799046786 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): > Apr 12 21:32:30 tr2p run-ktransformers.sh[99421]: 2025-04-12 21:32:30,876 INFO /opt/ktransformers/.ktransformers/lib/python3.12/site-packages/ktransformers/server/backend/interfaces/transformers.py[335]: args.max_new_tokens: 131072, cache_lens: 131072, seq_length: 26594 I seems like I have no problem going through 26k context window on my RTX 3090 24GB. Its like: ``` MEM[||||||||||||||||||23.969Gi/24.000Gi] ``` Not sure how the memory management is made. It seem to grow larger with larger context. It might be time to add the second GPU.
Author
Owner

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

Yeah! Got it. Just sent about 32k token on the input and got OOM.

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.23 GiB. GPU 0 has a total capacity of 23.57 GiB of which 1.22 GiB is free. Including non-PyTorch memory, this process has 22.33 GiB memory in use. Of the allocated memory 21.26 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 716.43 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

Let's see what can be done.

<!-- gh-comment-id:2799054038 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): Yeah! Got it. Just sent about 32k token on the input and got OOM. > torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.23 GiB. GPU 0 has a total capacity of 23.57 GiB of which 1.22 GiB is free. Including non-PyTorch memory, this process has 22.33 GiB memory in use. Of the allocated memory 21.26 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 716.43 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) Let's see what can be done.
Author
Owner

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

Token indices sequence length is longer than the specified maximum sequence length for this model (32333 > 16384). Running this sequence through the model will result in indexing errors

Ha! I wonder WTF is that

<!-- gh-comment-id:2799111954 --> @magikRUKKOLA commented on GitHub (Apr 12, 2025): > Token indices sequence length is longer than the specified maximum sequence length for this model (32333 > 16384). Running this sequence through the model will result in indexing errors Ha! I wonder WTF is that
Author
Owner

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

I have changed this parameter from 16384 to 131072 to make it accept the longer context for a prefill phase:

$ :/opt/unsloth/DeepSeek-V3-0324-GGUF# cat tokenizer_config.json | jq .model_max_length
131072

let's see if this will solve the issue.
For now at least that warning disappeared.

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.34 GiB. GPU 0 has a total capacity of 23.57 GiB of which 1.33 GiB is free. Including non-PyTorch memory, this process has 22.23 GiB memory in use. Of the allocated memory 21.46 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 403.53 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
<!-- gh-comment-id:2799564679 --> @magikRUKKOLA commented on GitHub (Apr 13, 2025): I have changed this parameter from 16384 to 131072 to make it accept the longer context for a prefill phase: ```bash $ :/opt/unsloth/DeepSeek-V3-0324-GGUF# cat tokenizer_config.json | jq .model_max_length 131072 ``` let's see if this will solve the issue. For now at least that warning disappeared. [EDIT]: nope. ``` torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.34 GiB. GPU 0 has a total capacity of 23.57 GiB of which 1.33 GiB is free. Including non-PyTorch memory, this process has 22.23 GiB memory in use. Of the allocated memory 21.46 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 403.53 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) ```
Author
Owner

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

okay let me connect the second GPU and use the DeepSeek-V3-Chat-multi-gpu.yaml. lets check if that would solve the issue.

<!-- gh-comment-id:2799571075 --> @magikRUKKOLA commented on GitHub (Apr 13, 2025): okay let me connect the second GPU and use the DeepSeek-V3-Chat-multi-gpu.yaml. lets check if that would solve the issue.
Author
Owner

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

Hell yeah, it solved the issue.

Here is the 30k+ tokens i sent to the input:

root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# type show_files
show_files is aliased to `_show_files() { find "$1" -maxdepth 1 -name "$2" -type f -exec sh -c 'echo "File: `realpath {}`"; echo "\`\`\`"; cat {}; echo "\`\`\`"; echo' \; ; }; _show_files'
root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# cat /usr/local/bin/tk
#!/opt/llm/.llm/bin/python
import sys
import os
os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"
from transformers import AutoTokenizer

def count_tokens(text: str, model_name: str = "deepseek-ai/DeepSeek-V3-0324") -> int:
    """Count tokens using Hugging Face's tokenizer."""
    try:
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        tokens = tokenizer.encode(text, return_tensors="np")
        return tokens.shape[-1]
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)

def main():
    # Read from stdin (piped input) or command-line argument
    if not sys.stdin.isatty():  # Check if input is piped
        text = sys.stdin.read()
    else:
        if len(sys.argv) < 2:
            print(f"Usage: {sys.argv[0]} [text_or_file] [--model MODEL_NAME]", file=sys.stderr)
            print("Example: echo 'Hello' | {sys.argv[0]}", file=sys.stderr)
            sys.exit(1)
        text = sys.argv[1]  # Read from command line

    # Optional: Model selection via --model flag
    model_name = "deepseek-ai/DeepSeek-V3-0324"
    if "--model" in sys.argv:
        try:
            model_name = sys.argv[sys.argv.index("--model") + 1]
        except IndexError:
            print("Error: --model requires a model name", file=sys.stderr)
            sys.exit(1)

    # Count and print tokens
    token_count = count_tokens(text, model_name)
    print(token_count)

if __name__ == "__main__":
    main()
root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# show_files /opt/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/ '*.yaml' | tk
31504
root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# show_files /opt/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/ '*.yaml' | mods -f "consider the config files and explain how the multi-gpu optimizations for the inference can be made"

config that had been used: DeepSeek-V3-Chat-multi-gpu.yaml

the image below shows where it switched from prefill phase to the decode phase. no performance drop in terms of decode speed had been noticed (still getting about 8.5 tps as before).

Image

<!-- gh-comment-id:2799575916 --> @magikRUKKOLA commented on GitHub (Apr 13, 2025): Hell yeah, it solved the issue. Here is the 30k+ tokens i sent to the input: ```bash root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# type show_files show_files is aliased to `_show_files() { find "$1" -maxdepth 1 -name "$2" -type f -exec sh -c 'echo "File: `realpath {}`"; echo "\`\`\`"; cat {}; echo "\`\`\`"; echo' \; ; }; _show_files' root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# cat /usr/local/bin/tk #!/opt/llm/.llm/bin/python import sys import os os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1" from transformers import AutoTokenizer def count_tokens(text: str, model_name: str = "deepseek-ai/DeepSeek-V3-0324") -> int: """Count tokens using Hugging Face's tokenizer.""" try: tokenizer = AutoTokenizer.from_pretrained(model_name) tokens = tokenizer.encode(text, return_tensors="np") return tokens.shape[-1] except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) def main(): # Read from stdin (piped input) or command-line argument if not sys.stdin.isatty(): # Check if input is piped text = sys.stdin.read() else: if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} [text_or_file] [--model MODEL_NAME]", file=sys.stderr) print("Example: echo 'Hello' | {sys.argv[0]}", file=sys.stderr) sys.exit(1) text = sys.argv[1] # Read from command line # Optional: Model selection via --model flag model_name = "deepseek-ai/DeepSeek-V3-0324" if "--model" in sys.argv: try: model_name = sys.argv[sys.argv.index("--model") + 1] except IndexError: print("Error: --model requires a model name", file=sys.stderr) sys.exit(1) # Count and print tokens token_count = count_tokens(text, model_name) print(token_count) if __name__ == "__main__": main() root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# show_files /opt/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/ '*.yaml' | tk 31504 root@llm01:/opt/unsloth/DeepSeek-V3-0324-GGUF/UD-Q4_K_XL# show_files /opt/ktransformers/ktransformers/ktransformers/optimize/optimize_rules/ '*.yaml' | mods -f "consider the config files and explain how the multi-gpu optimizations for the inference can be made" ``` config that had been used: DeepSeek-V3-Chat-multi-gpu.yaml the image below shows where it switched from prefill phase to the decode phase. no performance drop in terms of decode speed had been noticed (still getting about 8.5 tps as before). ![Image](https://github.com/user-attachments/assets/283238e1-2656-4405-990a-07a8119ae3f2)
Author
Owner

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

Still not sure what's up with absorb_for_prefill. Have to investigate.

<!-- gh-comment-id:2799576721 --> @magikRUKKOLA commented on GitHub (Apr 13, 2025): Still not sure what's up with absorb_for_prefill. Have to investigate.
Author
Owner

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

Another important note regarding the usage of two GPUs. So I ran the profile (nsys profile --trace=cuda ...) and found out that its using p2p transfers which I enabled via the custom driver. Ha!

 ** CUDA GPU MemOps Summary (by Size) (cuda_gpu_mem_size_sum):

 Total (MB)  Count   Avg (MB)  Med (MB)  Min (MB)  Max (MB)   StdDev (MB)            Operation
 ----------  ------  --------  --------  --------  ---------  -----------  ------------------------------
 61,538.769  10,977     5.606     0.000     0.000  3,706.716       53.571  [CUDA memcpy Device-to-Host]
 34,786.841  19,161     1.816     0.033     0.000      8.389        3.262  [CUDA memcpy Device-to-Device]
 20,039.504  19,121     1.048     0.033     0.000    463.340        5.154  [CUDA memcpy Host-to-Device]
    160.818   6,960     0.023     0.026     0.000      0.044        0.021  [CUDA memset]
     22.263     892     0.025     0.000     0.000      3.670        0.300  [CUDA memcpy Peer-to-Peer]

So the unlock of the p2p capabilities apparently is the must too.

Another cool note regarding this. Its required to unplug the HDMI cable if its connected to one of the GPUs because otherwise the buffer-alignment error would occur.

DeepSeek analysis:


Your test confirms that **P2P (GPU-to-GPU direct transfers) is indeed enabled and working efficiently** between your two RTX 3090 GPUs:

1. **P2P Support Verified**:
   """
   Device=0 CAN Access Peer Device=1
   Device=1 CAN Access Peer Device=0
   """
   - Both GPUs **can directly access each other’s memory** without host RAM involvement.

2. **High-Speed Transfers**:
   - **Bidirectional P2P Bandwidth**: ~51.2 GB/s
     (This is **far higher than PCIe host-bridge (PHB) speeds**, confirming direct GPU-GPU DMA.)
   - **Low Latency**: ~1.03–1.05 µs (consistent with NVLink/PCIe P2P).

3. **Fallback Behavior**:
   - When P2P is disabled, bandwidth drops to ~11–15 GB/s (host-staged transfers via PCIe).
   - Enabled P2P avoids this penalty.

---

### **Reconciling with `nsys` Report**
Your `nsys` data shows:
"""
[CUDA memcpy Device-to-Device]  34,786.841 MB
[CUDA memcpy Peer-to-Peer]          22.263 MB
"""
#### **Why the Discrepancy?**
1. **`Device-to-Device` (34.8 GB)**:
   - These are **true P2P transfers** (despite the label).
   - The `p2pBandwidthLatencyTest` proves that `cudaMemcpy(..., cudaMemcpyDeviceToDevice)` **uses direct GPU-GPU DMA** when P2P is enabled.
   - `nsys` classifies them as "Device-to-Device" because the CUDA API used was `cudaMemcpy` (not `cudaMemcpyPeer`).

2. **`Peer-to-Peer` (22 MB)**:
   - These are **explicit `cudaMemcpyPeerAsync` calls**, which are rarely used in your code.
   - The negligible volume suggests your code prefers `cudaMemcpyDeviceToDevice` for GPU-GPU transfers.

#### **Key Takeaway**:
- **All 34.8 GB of "Device-to-Device" transfers were direct P2P** (no host RAM involvement).
- The `nsys` label is misleading—it doesn’t distinguish between:
  - `cudaMemcpyDeviceToDevice` with P2P enabled (direct).
  - `cudaMemcpyDeviceToDevice` with P2P disabled (host-staged).

---

### **Why Does `nvidia-smi topo -m` Show `PHB`?**
- **`PHB` (PCIe Host Bridge)** indicates that the GPUs are connected via the **CPU’s PCIe lanes**, not NVLink.
- However, modern GPUs (like RTX 3090) can still do **PCIe P2P** (direct GPU-GPU DMA) without host RAM, albeit at lower bandwidth than NVLink.
- Your benchmark confirms this is happening (51.2 GB/s).

---

### **Actionable Steps**
1. **Trust the `p2pBandwidthLatencyTest`**:
   - It’s the **ground truth** for P2P capability. Your GPUs **are** doing direct transfers.

2. **Ignore `nsys`’s "Peer-to-Peer" label**:
   - Focus on the **"Device-to-Device"** volume (34.8 GB), which reflects actual P2P bandwidth.

3. **Optimize Further**:
   - If you want to ensure P2P is used, replace `cudaMemcpy(dst, src, size, cudaMemcpyDeviceToDevice)` with:
     ```c
     cudaMemcpyPeerAsync(dst, dstDevice, src, srcDevice, size, stream);
     ```
   - Monitor performance to confirm no regressions.

4. **Check for NVLink (if available)**:
   - RTX 3090 supports NVLink with the right hardware (e.g., NVLink bridge).
   - Run `nvidia-smi nvlink --status` to check if NVLink is active (higher bandwidth than PCIe P2P).

---

### **Final Answer**
- **Yes, your 34.8 GB `Device-to-Device` transfers are true P2P** (direct GPU-GPU at ~51.2 GB/s).
- The `nsys` report’s "Peer-to-Peer" label is a red herring—your code primarily uses `cudaMemcpyDeviceToDevice`, which **is P2P-accelerated** in your system.
- No host RAM is involved in these transfers.

Let me know if you'd like to dive deeper into NVLink or PCIe P2P tuning!
<!-- gh-comment-id:2799851643 --> @magikRUKKOLA commented on GitHub (Apr 13, 2025): Another important note regarding the usage of two GPUs. So I ran the profile (nsys profile --trace=cuda ...) and found out that its using p2p transfers which I enabled via the [custom driver.](https://github.com/forkProj/open-gpu-kernel-modules-P2P) Ha! ``` ** CUDA GPU MemOps Summary (by Size) (cuda_gpu_mem_size_sum): Total (MB) Count Avg (MB) Med (MB) Min (MB) Max (MB) StdDev (MB) Operation ---------- ------ -------- -------- -------- --------- ----------- ------------------------------ 61,538.769 10,977 5.606 0.000 0.000 3,706.716 53.571 [CUDA memcpy Device-to-Host] 34,786.841 19,161 1.816 0.033 0.000 8.389 3.262 [CUDA memcpy Device-to-Device] 20,039.504 19,121 1.048 0.033 0.000 463.340 5.154 [CUDA memcpy Host-to-Device] 160.818 6,960 0.023 0.026 0.000 0.044 0.021 [CUDA memset] 22.263 892 0.025 0.000 0.000 3.670 0.300 [CUDA memcpy Peer-to-Peer] ``` So the unlock of the p2p capabilities apparently is the must too. Another cool note regarding this. Its required to unplug the HDMI cable if its connected to one of the GPUs because otherwise the buffer-alignment error would occur. DeepSeek analysis: ``` Your test confirms that **P2P (GPU-to-GPU direct transfers) is indeed enabled and working efficiently** between your two RTX 3090 GPUs: 1. **P2P Support Verified**: """ Device=0 CAN Access Peer Device=1 Device=1 CAN Access Peer Device=0 """ - Both GPUs **can directly access each other’s memory** without host RAM involvement. 2. **High-Speed Transfers**: - **Bidirectional P2P Bandwidth**: ~51.2 GB/s (This is **far higher than PCIe host-bridge (PHB) speeds**, confirming direct GPU-GPU DMA.) - **Low Latency**: ~1.03–1.05 µs (consistent with NVLink/PCIe P2P). 3. **Fallback Behavior**: - When P2P is disabled, bandwidth drops to ~11–15 GB/s (host-staged transfers via PCIe). - Enabled P2P avoids this penalty. --- ### **Reconciling with `nsys` Report** Your `nsys` data shows: """ [CUDA memcpy Device-to-Device] 34,786.841 MB [CUDA memcpy Peer-to-Peer] 22.263 MB """ #### **Why the Discrepancy?** 1. **`Device-to-Device` (34.8 GB)**: - These are **true P2P transfers** (despite the label). - The `p2pBandwidthLatencyTest` proves that `cudaMemcpy(..., cudaMemcpyDeviceToDevice)` **uses direct GPU-GPU DMA** when P2P is enabled. - `nsys` classifies them as "Device-to-Device" because the CUDA API used was `cudaMemcpy` (not `cudaMemcpyPeer`). 2. **`Peer-to-Peer` (22 MB)**: - These are **explicit `cudaMemcpyPeerAsync` calls**, which are rarely used in your code. - The negligible volume suggests your code prefers `cudaMemcpyDeviceToDevice` for GPU-GPU transfers. #### **Key Takeaway**: - **All 34.8 GB of "Device-to-Device" transfers were direct P2P** (no host RAM involvement). - The `nsys` label is misleading—it doesn’t distinguish between: - `cudaMemcpyDeviceToDevice` with P2P enabled (direct). - `cudaMemcpyDeviceToDevice` with P2P disabled (host-staged). --- ### **Why Does `nvidia-smi topo -m` Show `PHB`?** - **`PHB` (PCIe Host Bridge)** indicates that the GPUs are connected via the **CPU’s PCIe lanes**, not NVLink. - However, modern GPUs (like RTX 3090) can still do **PCIe P2P** (direct GPU-GPU DMA) without host RAM, albeit at lower bandwidth than NVLink. - Your benchmark confirms this is happening (51.2 GB/s). --- ### **Actionable Steps** 1. **Trust the `p2pBandwidthLatencyTest`**: - It’s the **ground truth** for P2P capability. Your GPUs **are** doing direct transfers. 2. **Ignore `nsys`’s "Peer-to-Peer" label**: - Focus on the **"Device-to-Device"** volume (34.8 GB), which reflects actual P2P bandwidth. 3. **Optimize Further**: - If you want to ensure P2P is used, replace `cudaMemcpy(dst, src, size, cudaMemcpyDeviceToDevice)` with: ```c cudaMemcpyPeerAsync(dst, dstDevice, src, srcDevice, size, stream); ``` - Monitor performance to confirm no regressions. 4. **Check for NVLink (if available)**: - RTX 3090 supports NVLink with the right hardware (e.g., NVLink bridge). - Run `nvidia-smi nvlink --status` to check if NVLink is active (higher bandwidth than PCIe P2P). --- ### **Final Answer** - **Yes, your 34.8 GB `Device-to-Device` transfers are true P2P** (direct GPU-GPU at ~51.2 GB/s). - The `nsys` report’s "Peer-to-Peer" label is a red herring—your code primarily uses `cudaMemcpyDeviceToDevice`, which **is P2P-accelerated** in your system. - No host RAM is involved in these transfers. Let me know if you'd like to dive deeper into NVLink or PCIe P2P tuning! ```
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

--max_new_tokens 1024 \

Hm. This one is unclear. You're doing the agentic long-context session, right? If that's the case why to limit the length of the response? Did it actually made all the responses within the 1024 tokens limit?

I just haven't gotten around to changing it. I've only run into the limit once so it wasn't an immediate priority. It was cargo culted from these two locations:

  1. https://kvcache-ai.github.io/ktransformers/en/install.html#start-server
  2. https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/balance-serve.md#1-run-for-24gb-vram-gpus
<!-- gh-comment-id:2802203139 --> @createthis commented on GitHub (Apr 14, 2025): > > --max_new_tokens 1024 \ > > Hm. This one is unclear. You're doing the agentic long-context session, right? If that's the case why to limit the length of the response? Did it actually made all the responses within the 1024 tokens limit? I just haven't gotten around to changing it. I've only run into the limit once so it wasn't an immediate priority. It was cargo culted from these two locations: 1. https://kvcache-ai.github.io/ktransformers/en/install.html#start-server 2. https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/balance-serve.md#1-run-for-24gb-vram-gpus
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

I'm working through this list to reply. Sorry. Busy weekend.

<!-- gh-comment-id:2802214808 --> @createthis commented on GitHub (Apr 14, 2025): I'm working through this list to reply. Sorry. Busy weekend.
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

is there anything else is occupying the gpu memory besides ktransformers? like Xorg, or xfwm4 etc.?

No. The machine is a dedicated ktransformers host.

<!-- gh-comment-id:2802471220 --> @createthis commented on GitHub (Apr 14, 2025): > is there anything else is occupying the gpu memory besides ktransformers? like Xorg, or xfwm4 etc.? No. The machine is a dedicated ktransformers host.
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

I have changed this parameter from 16384 to 131072 to make it accept the longer context for a prefill phase:

$ :/opt/unsloth/DeepSeek-V3-0324-GGUF# cat tokenizer_config.json | jq .model_max_length
131072
let's see if this will solve the issue. For now at least that warning disappeared.

torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.34 GiB. GPU 0 has a total capacity of 23.57 GiB of which 1.33 GiB is free. Including non-PyTorch memory, this process has 22.23 GiB memory in use. Of the allocated memory 21.46 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 403.53 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

Weird. Mine is already set to that:

(base) jesse@larry:/data/DeepSeek-V3$ cat tokenizer_config.json | grep model_max_length
  "model_max_length": 131072,
(base) jesse@larry:/data/DeepSeek-V3$
<!-- gh-comment-id:2802480570 --> @createthis commented on GitHub (Apr 14, 2025): > I have changed this parameter from 16384 to 131072 to make it accept the longer context for a prefill phase: > > $ :/opt/unsloth/DeepSeek-V3-0324-GGUF# cat tokenizer_config.json | jq .model_max_length > 131072 > let's see if this will solve the issue. For now at least that warning disappeared. > > ``` > torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.34 GiB. GPU 0 has a total capacity of 23.57 GiB of which 1.33 GiB is free. Including non-PyTorch memory, this process has 22.23 GiB memory in use. Of the allocated memory 21.46 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 403.53 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) > ``` Weird. Mine is already set to that: ```bash (base) jesse@larry:/data/DeepSeek-V3$ cat tokenizer_config.json | grep model_max_length "model_max_length": 131072, (base) jesse@larry:/data/DeepSeek-V3$ ```
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

Where ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this:

Hold on. But what was the point? You got 3090 TI, right? So it doesn't support FP8 natively.

You're saying I can only use the 128k longer cache with an FP8 capable GPU?

<!-- gh-comment-id:2802564133 --> @createthis commented on GitHub (Apr 14, 2025): > > Where `ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml` was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this: > > Hold on. But what was the point? You got 3090 TI, right? So it doesn't support FP8 natively. You're saying I can only use the 128k longer cache with an FP8 capable GPU?
Author
Owner

@magikRUKKOLA commented on GitHub (Apr 14, 2025):

Where ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this:

Hold on. But what was the point? You got 3090 TI, right? So it doesn't support FP8 natively.

You're saying I can only use the 128k longer cache with an FP8 capable GPU?

Well, no. Because I am using 8 bit cache already in case with 3090 above. I suppose that if you would have FP8 support, the KV-cache calculations will be faster. So even if you will have 4090+ with the same amount of VRAM (24GB) it will not solve the issue. (AFAIK)
note. The 4090 with 48GB is available from China BTW. PALADN is making them.

<!-- gh-comment-id:2802605975 --> @magikRUKKOLA commented on GitHub (Apr 14, 2025): > > > Where `ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml` was modified according to this guide https://github.com/kvcache-ai/ktransformers/blob/main/doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel like this: > > > > > > Hold on. But what was the point? You got 3090 TI, right? So it doesn't support FP8 natively. > > You're saying I can only use the 128k longer cache with an FP8 capable GPU? Well, no. Because I am using 8 bit cache already in case with 3090 above. I suppose that if you would have FP8 support, the KV-cache calculations will be faster. So even if you will have 4090+ with the same amount of VRAM (24GB) it will not solve the issue. (AFAIK) note. The 4090 with 48GB is available from China BTW. PALADN is making them.
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

I did some testing today based on this conversation. Results:

  1. absorb_for_prefill set to True in ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml definitely causes:

    TypeError: MLAWrapper.plan() missing 1 required positional argument: 'kv_data_type'
    

    Setting absorb_for_prefill back to False fixes the error. Maybe this is because my 3090 GPU is not FP8 capable?

  2. Adding:

    --cache_8bit True \
    --cache_q4 false \
    

    ... doesn't seem to do much. My context still runs out at about seq_length: 31567, resulting in this warning:

    torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.46 GiB. GPU 0 has a total capacity of 23.59 GiB of which 
    1.25 GiB is free. Including non-PyTorch memory, this process has 22.33 GiB memory in use. Of the allocated memory 21.77 
    GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 196.11 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation.  See documentation for Memory Management  (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
    

    At this point, DeepSeek continues processing requests, but it forgets its agentic instructions, so the session ends in Open Hands AI because it forgets what it's supposed to be doing to keep the session going.

I'm guessing at this point the answer is: "You don't have an FP8 GPU - that's why long context isn't working."

<!-- gh-comment-id:2802789707 --> @createthis commented on GitHub (Apr 14, 2025): I did some testing today based on this conversation. Results: 1. `absorb_for_prefill` set to `True` in `ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat.yaml` definitely causes: ``` TypeError: MLAWrapper.plan() missing 1 required positional argument: 'kv_data_type' ``` Setting `absorb_for_prefill` back to `False` fixes the error. Maybe this is because my 3090 GPU is not FP8 capable? 2. Adding: ``` --cache_8bit True \ --cache_q4 false \ ``` ... doesn't seem to do much. My context still runs out at about `seq_length: 31567`, resulting in this warning: ``` torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 1.46 GiB. GPU 0 has a total capacity of 23.59 GiB of which 1.25 GiB is free. Including non-PyTorch memory, this process has 22.33 GiB memory in use. Of the allocated memory 21.77 GiB is allocated by PyTorch, with 13.38 MiB allocated in private pools (e.g., CUDA Graphs), and 196.11 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables) ``` At this point, DeepSeek continues processing requests, but it forgets its agentic instructions, so the session ends in Open Hands AI because it forgets what it's supposed to be doing to keep the session going. I'm guessing at this point the answer is: "You don't have an FP8 GPU - that's why long context isn't working."
Author
Owner

@magikRUKKOLA commented on GitHub (Apr 14, 2025):

2. Adding:
   ```
   --cache_8bit True \
   --cache_q4 false \
   ```

Well, you could try to do cache_q4 True (EDIT: and cache_8bit False). Not sure if that would solve the issue. At least in my case that didn't solve it.

I'm guessing at this point the answer is: "You don't have an FP8 GPU - that's why long context isn't working."

But where exactly you got the idea that using the GPU with FP8 native support would allow you to run full context?

In any case, you know how to solve the issue -- just by plugging in the second GPU. )

<!-- gh-comment-id:2802809499 --> @magikRUKKOLA commented on GitHub (Apr 14, 2025): > 2. Adding: > ``` > --cache_8bit True \ > --cache_q4 false \ > ``` Well, you could try to do cache_q4 True (EDIT: and cache_8bit False). Not sure if that would solve the issue. At least in my case that didn't solve it. > I'm guessing at this point the answer is: "You don't have an FP8 GPU - that's why long context isn't working." But where exactly you got the idea that using the GPU with FP8 native support would allow you to run full context? In any case, you know how to solve the issue -- just by plugging in the second GPU. )
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

But where exactly you got the idea that using the GPU with FP8 native support would allow you to run full context?

I don't know if FP8 support is the problem, but this line is why I'm trying to get longer than 30k context:

github.com/kvcache-ai/ktransformers@8dc1ab9e04/README.md (L32C115-L32C255)

Support 139K Longer Context for DeepSeek-V3 and R1 in 24GB VRAM.

It sounds like I need absorb_for_prefill set to True to make that happen.

<!-- gh-comment-id:2802819459 --> @createthis commented on GitHub (Apr 14, 2025): > But where exactly you got the idea that using the GPU with FP8 native support would allow you to run full context? I don't know if FP8 support is the problem, but this line is why I'm trying to get longer than 30k context: https://github.com/kvcache-ai/ktransformers/blob/8dc1ab9e040dab171e22dc9c234178ad8445767f/README.md?plain=1#L32C115-L32C255 > Support 139K [Longer Context](./doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel) for DeepSeek-V3 and R1 **in 24GB VRAM.** It sounds like I need `absorb_for_prefill` set to `True` to make that happen.
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

Huh. This commit:

github.com/kvcache-ai/ktransformers@3b9e16cec7

... solves the error:

TypeError: MLAWrapper.plan() missing 1 required positional argument: 'kv_data_type'

I get a different error after that, but this makes me think I should pull from main. Maybe this is resolved upstream.

<!-- gh-comment-id:2802846166 --> @createthis commented on GitHub (Apr 14, 2025): Huh. This commit: https://github.com/kvcache-ai/ktransformers/commit/3b9e16cec79116ca801b4092c53afd48a444b921 ... solves the error: ``` TypeError: MLAWrapper.plan() missing 1 required positional argument: 'kv_data_type' ``` I get a different error after that, but this makes me think I should pull from `main`. Maybe this is resolved upstream.
Author
Owner

@magikRUKKOLA commented on GitHub (Apr 14, 2025):

Support 139K Longer Context for DeepSeek-V3 and R1 in 24GB VRAM.

Ha. Indeed. They wrote that 139k context is supported but actually in the docs they wrote only about 20k+ context:

If you want to use long context(longer than 20K) for prefill, enable the matrix absorption MLA during the prefill phase, which will significantly reduce the size of the kv cache. Modify yaml file like this:

I believe I tried that when I had only one GPU installed and failed to do 30k+ context. I didn't merge the weights for that though.
Then I decided to plug in the second GPU which solved the issue.

Well, if you manage to get it working just with one GPU please let me know. )

<!-- gh-comment-id:2802886244 --> @magikRUKKOLA commented on GitHub (Apr 14, 2025): > > Support 139K [Longer Context](./doc/en/DeepseekR1_V3_tutorial.md#v022--v023-longer-context--fp8-kernel) for DeepSeek-V3 and R1 **in 24GB VRAM.** > Ha. Indeed. They wrote that 139k context is supported but actually in the docs they wrote only about 20k+ context: > If you want to use long context(longer than 20K) for prefill, enable the matrix absorption MLA during the prefill phase, which will significantly reduce the size of the kv cache. Modify yaml file like this: I believe I tried that when I had only one GPU installed and failed to do 30k+ context. I didn't merge the weights for that though. Then I decided to plug in the second GPU which solved the issue. Well, if you manage to get it working just with one GPU please let me know. )
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

git pull origin main fixed it. I'm out past 50k context on a single 24gb GPU with absorb_for_prefill set to True. Sorry for the noise!

<!-- gh-comment-id:2802956363 --> @createthis commented on GitHub (Apr 14, 2025): `git pull origin main` fixed it. I'm out past 50k context on a single 24gb GPU with `absorb_for_prefill` set to `True`. Sorry for the noise!
Author
Owner

@createthis commented on GitHub (Apr 14, 2025):

PS. I got up to 80k context before it slowed down enough that I wanted to restart my agentic task. Started out at 100 tok/s prefill and 17 tok/s decode and got down to 12 tok/s prefill and 10 tok/s decode at 80k context. Very cool! I love having the option to run really long contexts at the expense of some speed. Awesome feature!

<!-- gh-comment-id:2803059515 --> @createthis commented on GitHub (Apr 14, 2025): PS. I got up to 80k context before it slowed down enough that I wanted to restart my agentic task. Started out at 100 tok/s prefill and 17 tok/s decode and got down to 12 tok/s prefill and 10 tok/s decode at 80k context. Very cool! I love having the option to run really long contexts at the expense of some speed. Awesome feature!
Author
Owner

@magikRUKKOLA commented on GitHub (Apr 14, 2025):

@createthis

Yeah, bro, you're absolutely right. I don't know how I missed this but I did. Today I pulled the most recent master and then just did as you specified regrading the absorb_for_prefill. Not sure what it was but I can confirm that my unsloth DeepSeekV3-UDQ4XXL is running with more than 50k context with just single GPU.

There might had been issue when I incorrecly configured my nginx reverse proxy by just putting the limit:

proxy_read_timeout 300s;

but in this case I had to look into the journalctl to check the the EOL error I had from mods was related to the proxy error or the actual ktransformers error. I might had ignored that part. Really not sure about that. It doesn't really matter now.

I feel kinda dumb about that. Sorry for the noise too.

I can agree, that's pretty cool to run state-of-the-art llm locally like that.

<!-- gh-comment-id:2803084155 --> @magikRUKKOLA commented on GitHub (Apr 14, 2025): @createthis Yeah, bro, you're absolutely right. I don't know how I missed this but I did. Today I pulled the most recent master and then just did as you specified regrading the absorb_for_prefill. Not sure what it was but I can confirm that my unsloth DeepSeekV3-UDQ4XXL is running with more than 50k context with just single GPU. There might had been issue when I incorrecly configured my nginx reverse proxy by just putting the limit: ``` proxy_read_timeout 300s; ``` but in this case I had to look into the journalctl to check the the EOL error I had from mods was related to the proxy error or the actual ktransformers error. I might had ignored that part. Really not sure about that. It doesn't really matter now. I feel kinda dumb about that. Sorry for the noise too. I can agree, that's pretty cool to run state-of-the-art llm locally like that.
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#781
No description provided.