Skip to content

perf(gguf): run llama.cpp on PyTorch's thread count, not its default 4; same probabilities - #20

Merged
rkinas merged 4 commits into
rkinas:mainfrom
Butterski:perf/gguf-physical-threads
Oct 20, 2026
Merged

rkinas merged 4 commits into
rkinas:mainfrom
Butterski:perf/gguf-physical-threads

Conversation

@Butterski

@Butterski Butterski commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

GGUFBackend never set the thread counts, so llama.cpp ran on its default GGML_DEFAULT_N_THREADS (4) and left
cores idle. Now:

cp.n_threads = cp.n_threads_batch = torch.get_num_threads()

That is the physical cores by default and follows OMP_NUM_THREADS / torch.set_num_threads. Physical, not logical:
12 threads (SMT) on a 6-core CPU was slower than 4. Builds with every layer on Metal or CUDA are not affected.

Same output. ggml computes every output element as one dot product inside one thread; the thread count only changes
which thread computes it, not the order of the sum.

Measured (basal-2.0-mini Q8_0, CPU only, Ryzen 5 PRO 4650GE 6c/12t, 16 recorded requests, variants alternated):
4 threads 28.8 s, 6 threads 21.6 s (1.34x); probabilities equal with == on 16/16.

Tests: new test_thread_count_does_not_change_probabilities (bit-identical at 1, 2, 3 and 5 threads);
tests/test_gguf.py, tests/test_context.py: 12 passed. One line in WHATS_NEW.md 2.2.1 (it sits next to #16's;
whichever merges second needs the two lines side by side).

Summary by Sourcery

Align GGUF CPU inference with PyTorch's configured thread count to improve performance without changing model outputs.

Enhancements:

  • Configure GGUF llama.cpp inference to use PyTorch's process thread count for both regular and batch work, improving CPU utilization while preserving bit-identical probabilities.

Documentation:

  • Document the GGUF CPU threading improvement, measured performance gain, output stability, and GPU backend scope.

Tests:

  • Add coverage confirming GGUF contexts inherit PyTorch's thread count and produce identical probabilities across multiple thread counts.

Butterski added a commit to Butterski/basal that referenced this pull request Oct 19, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

GGUF CPU inference now inherits PyTorch’s configured thread count for both regular and batch llama.cpp work instead of using llama.cpp’s default of four threads, improving CPU throughput while regression tests verify bit-identical probabilities across multiple thread counts; release notes document the behavior and benchmark result.

Sequence diagram for GGUF CPU inference thread configuration

sequenceDiagram
    participant GGUFBackend
    participant PyTorch
    participant LlamaCpp
    GGUFBackend->>PyTorch: get_num_threads()
    PyTorch-->>GGUFBackend: configured thread count
    GGUFBackend->>LlamaCpp: llama_init_from_model(cp)
    Note over GGUFBackend,LlamaCpp: cp.n_threads = cp.n_threads_batch = configured count
    LlamaCpp-->>GGUFBackend: CPU inference with configured threads
Loading

Flow diagram for thread-count-invariant GGUF probabilities

flowchart LR
    Config["PyTorch thread configuration"] --> Context["GGUF context"]
    Context --> Threads["CPU inference with n_threads and n_threads_batch"]
    Threads --> Logits["Logits and probabilities"]
    Logits --> Equal["Bit-identical probabilities across tested counts"]
Loading

File-Level Changes

Change Details Files
Configure GGUF llama.cpp contexts to use PyTorch’s configured thread count for both single-token and batch work.
  • Set n_threads and n_threads_batch from torch.get_num_threads() during context initialization.
  • Preserve existing behavior for fully Metal- or CUDA-offloaded builds, which do not execute layers on the CPU.
basal/engine.py
Add regression coverage that varying llama.cpp thread counts preserves probability outputs exactly.
  • Run the same shared request with 1, 2, 3, and 5 threads.
  • Restore the original context thread count after the test and compare all results with bitwise array equality.
tests/test_gguf.py
Document the CPU threading change and its measured performance impact.
  • Explain inheritance from PyTorch, OMP_NUM_THREADS, and torch.set_num_threads.
  • Record the measured 1.34× speedup and bit-identical probabilities, including the unaffected accelerator case.
docs/WHATS_NEW.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="basal/engine.py" line_range="1877" />
<code_context>
         cp.swa_full = True  # sliding-window layers (Gemma 4) keep every cell: a shared prefix cell stays readable
+        # llama.cpp's own default is 4 threads (GGML_DEFAULT_N_THREADS); PyTorch's count is the physical cores (or
+        # OMP_NUM_THREADS / torch.set_num_threads). Each output element stays one dot product in one thread: same logits.
+        cp.n_threads = cp.n_threads_batch = torch.get_num_threads()
         self.ctx = C.llama_init_from_model(self.cmodel, cp)
         if not self.ctx:
</code_context>
<issue_to_address>
**GGUF inference can regress**

When pyTorch reports SMT siblings or more CPUs than the process can use, `torch.get_num_threads()` assigns that oversubscribed count to llama.cpp for prompt processing and generation, so GGUF inference can be slower than the physical-core setting measured in the PR and the release note’s physical-core claim is inaccurate.

Choose the physical-core count by default instead of copying `torch.get_num_threads()` unconditionally, while preserving explicit thread-count overrides.

Also at `docs/WHATS_NEW.md:8-10`.
</issue_to_address>

### Comment 2
<location path="tests/test_gguf.py" line_range="137" />
<code_context>
+    try:
+        runs = []
+        for k in (1, 2, 3, 5):
+            C.llama_set_n_threads(backend.ctx, k, k)
+            runs.append(backend.run_shared([g])[0])
+    finally:
</code_context>
<issue_to_address>
**Constructor thread count goes untested**

When the constructor’s thread-count assignment is removed or changed to the wrong value, the test setters overwrite both context thread counts before the output comparison, so the test passes without checking the constructor’s value and users can receive llama.cpp’s default instead of PyTorch’s count.

Assert the context’s thread counts immediately after construction, before changing them for the output comparisons.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/engine.py Resolved
Comment thread tests/test_gguf.py Resolved
…4; same probabilities

GGUFBackend left n_threads / n_threads_batch at GGML_DEFAULT_N_THREADS
(4). Use torch.get_num_threads(): the physical cores by default, and it
honours OMP_NUM_THREADS / torch.set_num_threads. ggml computes every
output element as one dot product in one thread, so the thread count
does not change the sum order.

basal-2.0-mini Q8_0, 6-core Zen 2, 16 recorded requests: 28.8 s -> 21.6 s
(1.34x), bit-identical on 16/16. Logical cores (12, SMT) were slower
than 4 in the research runs, so physical cores is the right count.
@Butterski
Butterski force-pushed the perf/gguf-physical-threads branch from ac086eb to 2ce06f4 Compare October 20, 2026 12:11
@rkinas
rkinas merged commit 6f7f86f into rkinas:main Oct 20, 2026
1 check passed
@rkinas

rkinas commented Oct 20, 2026

Copy link
Copy Markdown
Owner

Thanks, Milosz! Merged for basal 2.3.1. llama.cpp now runs on PyTorch's thread count, and your tests show the same probabilities bit for bit at 1, 2, 3 and 5 threads. You are credited in WHATS_NEW and in the 2.3.1 release notes.

rkinas added a commit that referenced this pull request Oct 20, 2026
rkinas added a commit that referenced this pull request Oct 21, 2026
…) into 2.3.1

# Conflicts:
#	docs/WHATS_NEW.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants