I summed the same 10 million float32 numbers five times on my laptop, changing only torch.set_num_threads. I got five different answers:
1 thread: -177.465576171875
2 threads: -177.46554565429688
4 threads: -177.46632385253906
8 threads: -177.4659423828125
16 threads: -177.46597290039062
Then I ran a transformer layer plus a 32,000-way output head at the same five thread counts. All 32,000 logits came out bit-identical every time.
So the honest answer to "does the thread count change my output?" is: sometimes, and you can predict when. This post shows which operations changed, which didn't, and why the line falls where it does.
The setup
One script, blog_04_script.py (full code at the end). Laptop: AMD Ryzen (Family 23 Model 96, 16 logical cores), Windows, PyTorch 2.10.0 CPU build, which uses OpenMP for its own kernels and Intel MKL for matrix multiplies.
For each of 11 operations and each thread count in 1, 2, 4, 8, 16, the script:
- runs the operation twice and checks the two results hash the same (is it repeatable at a fixed thread count?);
- compares the result bit for bit with the 1-thread result (does the thread count matter?).
"Bit for bit" means I reinterpret the float tensors as integers and compare those, so a difference in the last bit counts.
Results
Repeatable at a fixed thread count: all 11 operations, at all 5 thread counts. Run the same thing twice with the same settings and you get the same bits. Thread count is not randomness. It is a setting, and it changes the answer only for some operations.
Bit-identical to 1 thread at every thread count (2, 4, 8, 16):
- matrix-vector product, fp32, 1x4096 times 4096x4096: 0 of 4,096 outputs differ
- matrix multiply, fp32, 64x4096 times 4096x4096: 0 of 262,144 differ
- the same matrix multiply in bf16: 0 of 262,144 differ
- "tall-K" matmul, 1x65536 times 65536x64 (long dot products, few outputs): 0 of 64 differ
- softmax over 8 rows of 1 million values: 0 of 8,000,000 differ
- row sums, 8 rows of 1 million: 0 of 8 differ
- a
TransformerEncoderLayer(d_model 512, 8 heads) on 128 tokens, then a 512x32000 linear head: 0 of 32,000 logits differ, argmax 23228 every time
Different from 1 thread:
- sum of 10M fp32 values: differs at 2, 4, 8 and 16 threads (the five values at the top)
- dot product of two 10M vectors: differs at every thread count above 1: 2414.21533203125 at 1 thread, 2414.23583984375 at 2, 2414.194580078125 at 4, 2414.169189453125 at 8, 2414.175048828125 at 16
- mean of 10M: differs at every thread count above 1, in the 6th to 8th significant digit
- sum of 10M values in bf16: the same as 1 thread at 2 and 4 threads (-180.0), then -182.0 at 8 threads and -175.0 at 16
The threads were really in use. In two runs the bf16 matmul took 452.6 and 359.0 ms at 1 thread, and 79.0 and 76.3 ms at 16 (single timings, so treat them as rough). The speed changed 5x or more; the bits did not change at all.
Why the line falls there
Floating-point addition is not associative: (a + b) + c and a + (b + c) can round differently. Any time a thread count changes which numbers get added together first, the result can change.
Look at how each operation gets split across threads.
A full reduction (sum, dot, mean of one big vector) has to cut the vector into chunks, one per thread. Each thread adds up its chunk, then the partial sums are combined. With 2 threads you get 2 partial sums of 5 million values each; with 8 threads, 8 partials of 1.25 million each. Different chunk boundaries mean a different addition order, which means different rounding. The thread count is part of the arithmetic.
A matrix multiply has lots of independent outputs. The easy way to parallelise it is to give each thread its own block of outputs, and let each thread compute every one of its dot products in the same fixed way. Then which thread computes output (i, j) has no effect on how it is computed. On this build, MKL did exactly that, even for the tall-K case where splitting the long dot products would have been tempting. (Libraries are allowed to split the K dimension too, and some do for shapes like that. Intel ships a "conditional numerical reproducibility" mode for MKL for exactly this reason. Don't read my result as a promise about every BLAS on every CPU.)
Row-wise operations (softmax over a row, sum along the last dimension) work the same way here: PyTorch handed whole rows to threads, so each row was reduced in the same order no matter how many threads there were.
The transformer layer is almost all matmuls, softmax and layer norm along rows, so it inherited the invariance. Its logits did not move.
Which answer is right?
None of them. I recomputed both reductions in float64:
- the sum is -177.4660289124614. The 1-thread fp32 result is off by about 4.5e-4; 16 threads is off by about 5.6e-5; 4 threads is off by about 3.0e-4. More threads happened to help here, but not steadily.
- the dot product is 2414.2034363339835. Every fp32 result misses it, by 0.009 to 0.034.
Each thread count gives a different, roughly equally good approximation. If one of them is your "golden" reference, a run with a different thread count will fail the comparison for no real reason.
The bf16 sum is a warning of a different kind. The float64 sum of the same bf16 inputs is about -179.52. The bf16 results (-180, -182, -175) are not just reordered, they're coarse. bf16 has only 8 significant bits, so near 180 adjacent values are 1 apart, and each partial sum gets rounded hard. Accumulate in fp32.
Why this matters for ML work
Most of an LLM forward pass is matmuls and row-wise operations, so on a setup like mine, changing the thread count won't change the generated tokens. The full reductions are where it bites, and they show up in places people compare across machines:
- losses and metrics: a mean over a large batch or a whole eval set is exactly the "mean of 10M" case;
- gradient norms for clipping: a global norm is a sum of squares over every parameter;
- checksums or "golden" values in tests, where a CI runner with 2 cores and a workstation with 16 compute slightly different numbers and the test fails.
And the thread count is often not something you chose. It defaults to the core count of whatever machine the job lands on, and it moves with OMP_NUM_THREADS, container CPU limits and cloud instance size. So "same code, same seed, same thread count" can quietly become "same code, same seed, different thread count" when you change machines.
What you can do:
- Pin the thread count for anything you compare bit for bit (
torch.set_num_threads(n)orOMP_NUM_THREADS=n), and record it next to the result. - Compare reductions with a tolerance sized to the problem, not with
==. The fp32 differences here were at most a few parts in 100,000. - If you need identical bits no matter the thread count, fix the reduction order yourself: split into a fixed number of chunks that does not depend on the thread count, sum each chunk in order, then combine the partials in a fixed tree. Threads then only decide who does the work, not what the work is.
The script
Save as blog_04_script.py and run python blog_04_script.py. It prints one line per operation per thread count: whether two runs matched, how many output elements differ from the 1-thread run, a rough timing, and the value for scalar results.
import torch, hashlib, time, os, platform
def h(t):
return hashlib.sha256(t.detach().reshape(-1).contiguous()
.view(torch.uint8).numpy().tobytes()).hexdigest()[:12]
def ndiff(a, b):
dt = {torch.float32: torch.int32, torch.bfloat16: torch.int16}[a.dtype]
ai = a.reshape(-1).contiguous().view(dt)
bi = b.reshape(-1).contiguous().view(dt)
return int((ai != bi).sum()), a.numel()
g = torch.Generator().manual_seed(1)
v = torch.randn(10_000_000, generator=g); w = torch.randn(10_000_000, generator=g)
x = torch.randn(1, 4096, generator=g); X = torch.randn(64, 4096, generator=g)
W = torch.randn(4096, 4096, generator=g) / 64
A = torch.randn(1, 65536, generator=g); B = torch.randn(65536, 64, generator=g) / 256
rows = torch.randn(8, 1_000_000, generator=g)
torch.manual_seed(2)
layer = torch.nn.TransformerEncoderLayer(512, 8, 2048, dropout=0.0, batch_first=True).eval()
head = torch.nn.Linear(512, 32000).eval()
tok = torch.randn(1, 128, 512, generator=g)
def model():
with torch.no_grad():
return head(layer(tok))[0, -1]
cases = {
"matvec fp32 1x4096 @ 4096x4096": lambda: x @ W.T,
"matmul fp32 64x4096 @ 4096x4096": lambda: X @ W.T,
"matmul bf16 64x4096 @ 4096x4096": lambda: X.bfloat16() @ W.bfloat16().T,
"tall-K matmul 1x65536 @ 65536x64": lambda: A @ B,
"softmax over 8 rows x 1M": lambda: torch.softmax(rows, dim=-1),
"row sums, 8 rows x 1M": lambda: rows.sum(-1),
"sum of 10M fp32": lambda: v.sum(),
"dot of two 10M vectors": lambda: torch.dot(v, w),
"mean of 10M": lambda: v.mean(),
"sum of 10M in bf16": lambda: v.bfloat16().sum(),
"transformer layer + 32k logits": model,
}
print(platform.processor(), "| torch", torch.__version__, "| logical cores", os.cpu_count())
ref = {}
for t in [1, 2, 4, 8, 16]:
torch.set_num_threads(t)
for name, f in cases.items():
a = f(); b = f()
if t == 1:
ref[name] = a
d, n = ndiff(a, ref[name])
t0 = time.perf_counter(); f(); ms = (time.perf_counter() - t0) * 1000
extra = f" | value {a.item()!r}" if a.numel() == 1 else ""
if name.startswith("transformer"):
extra = f" | argmax {int(a.argmax())}"
print(f"threads={t:2d} | {name:33s} | same twice: {h(a)==h(b)} | "
f"differ from 1 thread: {d}/{n} | {ms:7.1f} ms{extra}")
Your exact values will differ from mine (different CPU, different library build), and on another BLAS the matmul lines might not be all zeros. That's the point of running it: find out which of your operations depend on the thread count before a test on someone else's machine tells you.
I'm building Vahana, an open-source engine for exact MoE inference: github.com/vahana-ai/Vahana
Top comments (0)