σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
BLAS and LAPACK skill›Module 3 · Speed and implementations›Topic 3.1·~45 minAdvanced

Threading and oversubscription

Skill positionModule 3 of 4 · Topic 1 of 2
3.1 Threading and oversubscription
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 3

  1. 01The idea in plain words
  2. 02One call, several threads
  3. 03A thousand small calls
  4. 04What the tasks ask

A thousand small covariance matrices take 0.0085 seconds when 8 workers each run one thread on an 8-core machine, and 1.81 seconds when the same 8 workers each ask for 8 threads. The faster setting uses fewer threads. Why is more parallelism 213 times slower, and when is it the right choice?

01

The idea in plain words

Where we are. The first six topics were about a single BLAS call: what it costs, how it uses the cache, how its matrix is laid out, what it solves and whether to trust it. Now we look at how many such calls a machine can run, and how a library uses several cores for one of them. The next topic asks which library to buy or link, which is only a sensible question once you know that the number of threads changes the answer.

A machine has a fixed number of cores, and a thread is what runs on one. A threaded BLAS call cuts one big job into slices, one per thread. Two costs push back. Every thread costs time to start and to wait for the others, which we call sync. And when more threads want to run than there are cores, the operating system swaps them in and out, which wastes time on every swap and throws away what each thread had cached. That is oversubscription.

The model in this lab

The formulas are a model, chosen to be simple and exact, not a measurement of any one CPU. The rate is 4 billion flops per second per core, each thread costs 50 microseconds, and every full extra layer of threads beyond the cores adds 50%. The shapes of the curves are what real machines show; the exact numbers will differ on yours.

02

One call, several threads

To share a matrix product over threads, split the rows of the left matrix. Xt has 12 rows, one per stock, so four threads get three rows each; with 5 threads the sizes are 3, 3, 2, 2, 2. One window of the covariance is a dgemm of 72,000 flops, the same count as in the first topic.

main.pyPython
# Twelve rows of Xt shared over 4 and over 5 threads, and the cost of one covariance windowprint("4 threads:", split_rows(12, 4))print("5 threads:", split_rows(12, 5))blas = Blas()window = dgemm(blas, Xt, X)print("one 12-stock window:", blas.flops, "flops")1
4 threads: [(0, 3), (3, 6), (6, 9), (9, 12)]
5 threads: [(0, 3), (3, 6), (6, 8), (8, 10), (10, 12)]
one 12-stock window: 72000 flops
  1. 172,000 flops is about 18 microseconds of work at 4 billion flops per second: too small to share.
main.pyPython
# How long does one call take with more and more threads, on 8 cores?for flops in (72_000, 2e10):    times = [parallel_time(flops, t, cores, rate, sync) for t in (1, 2, 4, 8, 16)]    print(f"{flops:>10.3g} flops:", [f"{s:.6f}" for s in times])1
   7.2e+04 flops: ['0.000068', '0.000109', '0.000205', '0.000402', '0.002403']
     2e+10 flops: ['5.000050', '2.500100', '1.250200', '0.625400', '0.939900']
  1. 1The small call gets slower with every thread. The big one, 2·10¹⁰ flops (the covariance of 2,000 stocks over 2,500 days), speeds up almost perfectly to 8 threads, then gets worse at 16.
The same call on 8 coresSeconds from parallel_time
Big call, 1 thread5.00s
Big call, 8 threads0.63s8.0 times faster
Big call, 16 threads0.94sworse: oversubscribed
Small call, 1 thread68µs8 threads: 402 µs
03

A thousand small calls

A rolling covariance is a thousand small, independent jobs, which can be spread over worker processes instead. Now two settings multiply: the number of workers and the number of threads each BLAS call may use. What counts for the cores is the product.

main.pyPython
# 1,000 windows of 72,000 flops each: different splits of 8 cores between workers and threadsfor workers, threads in ((1, 1), (1, 8), (8, 1), (2, 4), (4, 2), (16, 1), (8, 8)):    seconds = batch_time(1000, 72_000, workers, threads, cores, rate, sync)    print(f"{workers:2} workers x {threads} threads = {workers * threads:2} threads: {seconds:8.4f} s")print("best layout:", best_layout(1000, 72_000, cores, rate, sync))1print("one big job:", best_layout(1, 2e10, cores, rate, sync))
 1 workers x 1 threads =  1 threads:   0.0680 s
 1 workers x 8 threads =  8 threads:   0.4022 s
 8 workers x 1 threads =  8 threads:   0.0085 s
 2 workers x 4 threads =  8 threads:   0.1023 s
 4 workers x 2 threads =  8 threads:   0.0273 s
16 workers x 1 threads = 16 threads:   0.0129 s
 8 workers x 8 threads = 64 threads:   1.8101 s
best layout: (8, 1)
one big job: (1, 8)
  1. 18 x 1 wins: one single-threaded worker on each core. 8 x 8 puts 64 threads on 8 cores and is 213 times slower.
The same mistake in real programs

NumPy and SciPy start one BLAS thread per core by default, and so does every process you launch. Eight worker processes calling NumPy on an 8-core machine therefore make 64 threads without anyone asking for them. The usual cure is to give each worker one BLAS thread by setting the environment variables OMP_NUM_THREADS=1 (and OPENBLAS_NUM_THREADS=1 or MKL_NUM_THREADS=1) before the library loads.

04

What the tasks ask

  1. 1
    `split_rows`Contiguous ranges of rows, sizes differing by at most one with the larger ones first, and no empty ranges.
  2. 2
    `parallel_time` and `batch_time`The two formulas, with oversub_factor applied to the total number of threads that compete for the cores.
  3. 3
    `best_layout`Try every split of workers and threads up to twice the cores, score each with batch_time, and break ties towards fewer threads.

Key takeaways

  • More threads is not faster Threads pay off only for calls big enough to cover their start-up cost, and only up to the number of cores.
  • Count workers times threads Many small jobs belong on many single-threaded workers; one big job belongs on one worker with all the cores.
  • Which library is fastest? Next: reading a benchmark table to choose a BLAS implementation, now that you know what such a table leaves out.
Quick check
Your program starts 8 worker processes on an 8-core machine, and each worker calls NumPy with its default BLAS settings. What is probably happening?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Share the rows with split_rows25 pts
  • Time one threaded call with parallel_time25 pts
  • Time a batch with batch_time25 pts
  • Choose workers and threads with best_layout25 pts
Explorer · lab-7-1
▾ lab-7-1
…
bash · in-browser
learner@quantcraft:~/lab-7-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-7-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes