Skip to main content

Pool

Struct Pool 

Source
pub struct Pool { /* private fields */ }
Expand description

Persistent thread pool: shared job slot, epoch dispatch, caller participation.

Implementations§

Source§

impl Pool

Source

pub fn new(n_workers: usize) -> Self

Examples found in repository?
examples/pool_lat.rs (line 15)
13fn main() {
14    for nt in [2usize, 4, 6, 8, 10] {
15        let pool = Pool::new(nt);
16        let noop: &(dyn Fn(usize, usize) + Sync) = &|_w, _n| {};
17        // Warm: first dispatch spawns/parks the workers.
18        for _ in 0..100 {
19            pool.run(noop);
20        }
21        let iters = 20_000;
22        let t0 = Instant::now();
23        for _ in 0..iters {
24            pool.run(noop);
25        }
26        let el = t0.elapsed().as_secs_f64();
27        let per = el / iters as f64 * 1e6;
28        println!(
29            "threads={nt:2}  {per:7.2} us/dispatch  -> {:6.2} ms/token at 200 matvecs",
30            per * 200.0 / 1e3
31        );
32    }
33}
More examples
Hide additional examples
examples/matvec_bw.rs (line 49)
21fn main() {
22    let mut args = std::env::args().skip(1);
23    let path = args.next().expect("usage: matvec_bw <model.cmf> [sweep|one <tensor>]");
24    let mode = args.next().unwrap_or_else(|| "sweep".to_string());
25    let model = Arc::new(cortiq_core::CmfModel::open(&path).expect("open model"));
26
27    // Real LM activations carry a few heavy channels (>8·rms); measured
28    // mean on this model is ~3.7. NOUT models that distribution.
29    let nout: usize = std::env::var("NOUT").ok().and_then(|v| v.parse().ok()).unwrap_or(4);
30    let mk_x = |cols: usize| -> Vec<f32> {
31        let mut x: Vec<f32> = (0..cols).map(|i| ((i % 17) as f32 - 8.0) / 8.0).collect();
32        for k in 0..nout {
33            x[k * 37 % cols] = 40.0;
34        }
35        x
36    };
37
38    if mode == "one" {
39        let name = args.next().unwrap_or_else(|| "model.embed_tokens.weight".to_string());
40        let entry = model.tensor(&name).expect("tensor not found");
41        let (rows, cols) = (entry.shape[0], entry.shape[1]);
42        let nbytes = entry.nbytes as f64;
43        println!("tensor {name}: {rows}x{cols} {:?} = {:.1} MB, NOUT={nout}", entry.dtype, nbytes / 1e6);
44        let t = QTensor::from_model(&model, &name).expect("wrap");
45        let x = mk_x(cols);
46        let mut out = vec![0f32; rows];
47        t.matvec(&x, &mut out, None);
48        for nt in [1usize, 2, 4, 6, 8, 10] {
49            let pool = if nt == 1 { None } else { Some(Pool::new(nt)) };
50            let iters = 8;
51            t.matvec(&x, &mut out, pool.as_ref());
52            let t0 = Instant::now();
53            for _ in 0..iters {
54                t.matvec(&x, &mut out, pool.as_ref());
55            }
56            let el = t0.elapsed().as_secs_f64();
57            println!("threads={nt:2}  {:6.2} ms/matvec  {:6.1} GB/s (sink {:.3})",
58                el / iters as f64 * 1e3, nbytes * iters as f64 / el / 1e9, out[0]);
59        }
60        return;
61    }
62
63    // sweep: every 2-D q8_2f tensor once = one decode's worth of weights.
64    let names: Vec<String> = model
65        .tensors
66        .iter()
67        .filter(|t| t.dtype == TensorDtype::Q8_2f && t.shape.len() == 2)
68        .map(|t| t.name.clone())
69        .collect();
70    let total_bytes: f64 = model
71        .tensors
72        .iter()
73        .filter(|t| t.dtype == TensorDtype::Q8_2f && t.shape.len() == 2)
74        .map(|t| t.nbytes as f64)
75        .sum();
76    println!(
77        "sweep: {} q8_2f tensors, {:.2} GB total (= weights streamed per decode token), NOUT={nout}",
78        names.len(),
79        total_bytes / 1e9
80    );
81
82    let tensors: Vec<(QTensor, Vec<f32>, Vec<f32>)> = names
83        .iter()
84        .map(|n| {
85            let e = model.tensor(n).unwrap();
86            let (rows, cols) = (e.shape[0], e.shape[1]);
87            (QTensor::from_model(&model, n).expect("wrap"), mk_x(cols), vec![0f32; rows])
88        })
89        .collect();
90    let mut tensors = tensors;
91
92    // Whole-model residency pass BEFORE any timing: the first touch of a
93    // 4.2 GB mmap faults ~260k pages, which would otherwise be charged to
94    // whichever thread count happens to run first. REVERSE=1 flips the
95    // order as a check that no first-touch cost is left in the table.
96    for _ in 0..2 {
97        for (t, x, out) in tensors.iter_mut() {
98            t.matvec(x, out, None);
99        }
100    }
101    let mut counts = vec![1usize, 2, 4, 6, 8, 10];
102    if std::env::var("REVERSE").is_ok() {
103        counts.reverse();
104    }
105    for nt in counts {
106        let pool = if nt == 1 { None } else { Some(Pool::new(nt)) };
107        // one warm pass, then two measured
108        for (t, x, out) in tensors.iter_mut() {
109            t.matvec(x, out, pool.as_ref());
110        }
111        let iters = 2;
112        let t0 = Instant::now();
113        for _ in 0..iters {
114            for (t, x, out) in tensors.iter_mut() {
115                t.matvec(x, out, pool.as_ref());
116            }
117        }
118        let el = t0.elapsed().as_secs_f64();
119        let per_tok = el / iters as f64;
120        println!(
121            "threads={nt:2}  {:7.1} ms/sweep  {:6.1} GB/s  -> weight-path-only ceiling {:5.1} tok/s",
122            per_tok * 1e3,
123            total_bytes * iters as f64 / el / 1e9,
124            1.0 / per_tok
125        );
126    }
127}
Source

pub fn with_spin(n_workers: usize, spin_budget: usize) -> Self

Explicit spin budget (tests pin it without touching the env).

Source

pub fn from_env() -> Option<Arc<Self>>

Pool sized from CMF_THREADS (see module docs). None = serial.

Source

pub fn n_workers(&self) -> usize

Spawned worker threads (the caller joins each job on top).

Source

pub fn run_rows(&self, rows: usize, f: &(dyn Fn(usize, usize) + Sync))

Run f(row_start, row_end) over 0..rows, self-balancing.

One dispatch, but workers pull row-ranges from a shared cursor instead of each taking a fixed 1/n slice. On a heterogeneous CPU (Apple Silicon: 4 P-cores + 6 E-cores here) a static split makes every matvec end at the SLOWEST core’s pace while the fast ones idle at the barrier; pulling by grain lets a P-core take several chunks for each one an E-core takes, so skew collapses to a single grain. Row ranges stay disjoint and each row’s dot is computed exactly as in the serial path → bit-identical output.

Source

pub fn run_many(&self, parts: &[(usize, &(dyn Fn(usize, usize) + Sync))])

Multi-matrix job: one dispatch serves SEVERAL row spaces (roadmap §3 P0 — «одна внешняя публикация job на слой»). Parts are laid out back-to-back in a virtual row space and pulled by grain from one shared cursor, so QKV or gate+up cost a single barrier instead of one each. Each part’s f(start, end) sees its OWN row indices — per-row math and outputs are bit-identical to separate run_rows calls.

Source

pub fn run(&self, f: &(dyn Fn(usize, usize) + Sync))

Run f(worker_idx, n_participants) on every worker AND the calling thread (worker_idx = n_workers() for the caller); returns when all participants have finished.

Examples found in repository?
examples/pool_lat.rs (line 19)
13fn main() {
14    for nt in [2usize, 4, 6, 8, 10] {
15        let pool = Pool::new(nt);
16        let noop: &(dyn Fn(usize, usize) + Sync) = &|_w, _n| {};
17        // Warm: first dispatch spawns/parks the workers.
18        for _ in 0..100 {
19            pool.run(noop);
20        }
21        let iters = 20_000;
22        let t0 = Instant::now();
23        for _ in 0..iters {
24            pool.run(noop);
25        }
26        let el = t0.elapsed().as_secs_f64();
27        let per = el / iters as f64 * 1e6;
28        println!(
29            "threads={nt:2}  {per:7.2} us/dispatch  -> {:6.2} ms/token at 200 matvecs",
30            per * 200.0 / 1e3
31        );
32    }
33}

Trait Implementations§

Source§

impl Drop for Pool

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Pool

§

impl !UnwindSafe for Pool

§

impl Freeze for Pool

§

impl Send for Pool

§

impl Sync for Pool

§

impl Unpin for Pool

§

impl UnsafeUnpin for Pool

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more