Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/GLM.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ goes on from where it stopped, and an edit goes back to the nearest checkpoint.
| `--expert-profile FILE` | | expert use counts, read at the start and written back after an answer, every 10 seconds at most, and at the end |
| `--no-gpu-experts` | | keep every routed expert on the CPU |
| `--any-node` | | on a PC with several NUMA nodes, let the CPU threads run on any of them |
| `--pin-workers MODE` | off | Linux: keep each CPU thread on one CPU. `auto`: one thread a performance core but the first, then the efficiency cores, then the second threads of the cores; or a list such as `2,4,6-9`; also `STRATA_POLY_PIN_WORKERS`. On an i9-12900H laptop it was not faster; with the default `balance_performance` power setting the speed varied less from run to run |
| `--no-graphs` | | launch a token's kernels one by one, not as the CUDA graph a layer that is recorded at the first token |
| `--expert-swaps N` | 64 | while an answer is written, experts on their way into VRAM at a time, each in place of a cached one the answer uses less; 0 = the cache stays as it was loaded |
| `--window N` | 4; 8 for the other models | the most tokens that go through the model together while an answer is written: the known one and guesses after it: the draft block's three at most, and more than three only from a repeat of eight tokens or more; 1 = no guesses |
Expand Down
3 changes: 2 additions & 1 deletion docs/SETTINGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ A number or a word is set like any environment variable, for example `STRATA_KVA
(`terminal/strata-<model>.json`), which the server passes to the engine. The Strata project's Terminal writes it there with
`strata launch --set NAME=value`.

## Switches you can turn on (365)
## Switches you can turn on (366)

Off unless you set them. The last column says where each one is described.

Expand Down Expand Up @@ -267,6 +267,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_PIPE_BYIELD_NODRAIN` | on / off | NVIDIA and AMD | [BATCHING.md](BATCHING.md) |
| `STRATA_PLE_COMPACT` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
| `STRATA_PLE_COPY_STREAM` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
| `STRATA_POLY_PIN_WORKERS` | text | NVIDIA and AMD | [GLM.md](GLM.md) |
| `STRATA_POLY_STAGE_RING` | on / off | NVIDIA and AMD | [inkling.md](models/inkling.md) |
| `STRATA_POLY_STREAM_STAGE` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
| `STRATA_POOL_CORES` | on / off | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md), [release-notes-0.2.2.md](release-notes-0.2.2.md) |
Expand Down
117 changes: 117 additions & 0 deletions engine/src/poly/cpu_experts.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// src/poly/cpu_experts.cpp - see the header.
#include "cpu_experts.hpp"

#if defined(__linux__)
#include <pthread.h>
#include <sched.h>
#endif

#include "strata/platform/cpu_relax.hpp"
#include "strata/poly/cpu_topology.hpp"
#include "strata/quant/act.hpp"
Expand All @@ -11,6 +16,7 @@
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <numeric>
Expand Down Expand Up @@ -140,6 +146,117 @@ Workers::Workers(int threads) : busy_((size_t) std::max(threads - 1, 0)) {
for (int i = 1; i < threads; ++i) th_.emplace_back([this, i] { loop(i - 1); });
}

int Workers::pin(const std::vector<int>& cpus) {
if (cpus.empty()) return 0;
#if defined(__linux__)
int done = 0;
for (size_t i = 0; i < th_.size(); ++i) {
const int c = cpus[i % cpus.size()];
if (c < 0 || c >= CPU_SETSIZE) continue;
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(c, &set);
if (pthread_setaffinity_np(th_[i].native_handle(), sizeof set, &set) == 0) ++done;
}
return done;
#else
return 0;
#endif
}

bool parse_cpu_list(const std::string& s, std::vector<int>& out) {
out.clear();
size_t i = 0;
const auto number = [&](int& v) {
if (i >= s.size() || s[i] < '0' || s[i] > '9') return false;
long n = 0;
for (; i < s.size() && s[i] >= '0' && s[i] <= '9'; ++i) {
n = n * 10 + (s[i] - '0');
if (n > 1 << 20) return false;
}
v = (int) n;
return true;
};
while (i < s.size()) {
int a = 0, b = 0;
if (!number(a)) return false;
b = a;
if (i < s.size() && s[i] == '-') {
++i;
if (!number(b) || b < a) return false;
}
for (int c = a; c <= b; ++c) out.push_back(c);
if (i < s.size()) {
if (s[i] != ',' || i + 1 == s.size()) return false;
++i;
}
}
return !out.empty();
}

std::vector<int> worker_cpu_order(std::vector<CpuSlot> cpus) {
std::vector<int> order;
if (cpus.empty()) return order;
std::sort(cpus.begin(), cpus.end(), [](const CpuSlot& a, const CpuSlot& b) { return a.cpu < b.cpu; });
// the first performance core (or the first core of all where there is none): the caller's
int first = -1;
for (const CpuSlot& c : cpus)
if (!c.efficient) {
first = c.core;
break;
}
if (first < 0) first = cpus.front().core;
std::vector<int> seen, firsts, efficient, seconds, own;
for (const CpuSlot& c : cpus) {
if (c.core == first) {
own.push_back(c.cpu);
} else if (c.efficient) {
efficient.push_back(c.cpu);
} else if (std::find(seen.begin(), seen.end(), c.core) == seen.end()) {
seen.push_back(c.core);
firsts.push_back(c.cpu);
} else {
seconds.push_back(c.cpu);
}
}
for (const std::vector<int>* v : {&firsts, &efficient, &seconds, &own}) order.insert(order.end(), v->begin(), v->end());
return order;
}

std::vector<CpuSlot> cpu_slots() {
std::vector<CpuSlot> out;
#if defined(__linux__)
cpu_set_t may;
if (sched_getaffinity(0, sizeof may, &may) != 0) return out;
const auto read_int = [](const std::string& path, int& v) {
FILE* f = std::fopen(path.c_str(), "r");
if (!f) return false;
const bool ok = std::fscanf(f, "%d", &v) == 1;
std::fclose(f);
return ok;
};
std::vector<int> atom; // a hybrid Intel CPU's efficiency cores (the cpu_atom PMU's CPUs)
if (FILE* f = std::fopen("/sys/devices/cpu_atom/cpus", "r")) {
char buf[512] = {};
if (std::fgets(buf, sizeof buf, f)) {
std::string s(buf);
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
if (!parse_cpu_list(s, atom)) atom.clear();
}
std::fclose(f);
}
for (int c = 0; c < CPU_SETSIZE; ++c) {
if (!CPU_ISSET(c, &may)) continue;
const std::string dir = "/sys/devices/system/cpu/cpu" + std::to_string(c) + "/topology/";
int core = c, pkg = 0;
read_int(dir + "core_id", core);
read_int(dir + "physical_package_id", pkg);
out.push_back({c, pkg * 65536 + core, std::find(atom.begin(), atom.end(), c) != atom.end()});
}
#endif
return out;
}

Workers::~Workers() {
quit_.store(true);
posted_.fetch_add(1);
Expand Down
22 changes: 22 additions & 0 deletions engine/src/poly/cpu_experts.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ class Workers {

void run(int n, const std::function<void(int)>& fn);
int threads() const { return (int) th_.size() + 1; }
/// --pin-workers: worker i (not the calling thread) runs on CPU cpus[i % size] from now on. The workers pinned;
/// 0 where the system has no way to (only Linux here).
int pin(const std::vector<int>& cpus);

private:
// Every thread takes tasks from next and counts what it ran down from left once, when it finds no more: with a
Expand Down Expand Up @@ -58,6 +61,25 @@ class Workers {
std::atomic<bool> quit_{false};
};

/// A logical CPU for --pin-workers: its number, its physical core (package and core), and whether it is an
/// efficiency core of a hybrid CPU.
struct CpuSlot {
int cpu = 0;
int core = 0;
bool efficient = false;
};

/// The order --pin-workers auto gives the workers the CPUs in: one thread of each performance core but the first,
/// then the efficiency cores, then the performance cores' second threads, then the first core's. While the
/// workers are fewer, the first core and the second threads stay to the calling thread and the GPU driver's threads,
/// and two workers do not share a core. (Measured on an i9-12900H: workers on both threads of the P-cores were
/// slower than one a core.)
std::vector<int> worker_cpu_order(std::vector<CpuSlot> cpus);
/// The CPUs this process may run on, with their cores and kinds: Linux's /sys; empty elsewhere.
std::vector<CpuSlot> cpu_slots();
/// A CPU list as Linux writes one ("2,4,6-9") into its numbers; false on anything else.
bool parse_cpu_list(const std::string& s, std::vector<int>& out);

/// A thread of its own that runs one function at a time beside the caller: start() hands it over, finish() returns
/// once it has run and throws what it threw. Workers::run() returns when every task of a batch is done, so work
/// handed to one of its tasks held the whole batch up while it ran.
Expand Down
20 changes: 20 additions & 0 deletions engine/src/poly/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4045,6 +4045,8 @@ void Engine::load(const Options& o) {
if (block_ != dg_.get()) dg_.reset();
hi_ = end_ < 0 ? n_layer_ : end_;

// STRATA_POLY_PIN_WORKERS=auto|off|LIST: --pin-workers
if (const char* v = std::getenv("STRATA_POLY_PIN_WORKERS"); v && *v) opt_.pin_workers = v;
// STRATA_POLY_STAGE_RING=1: --stage-ring 1
if (const char* v = std::getenv("STRATA_POLY_STAGE_RING"); v && *v) opt_.stage_ring = v[0] != '0';
// STRATA_POLY_STAGED_TILES=8,16,32: a prompt batch's staged experts go to llama.cpp's MMQ in size classes, the
Expand Down Expand Up @@ -4507,6 +4509,24 @@ void Engine::load(const Options& o) {
node_ = stay_near(spans, files, threads, node_share_);
}
workers_ = std::make_shared<Workers>(threads);
if (!opt_.pin_workers.empty() && opt_.pin_workers != "off") { // --pin-workers
std::vector<int> cpus;
if (opt_.pin_workers == "auto") {
cpus = worker_cpu_order(cpu_slots());
} else if (!parse_cpu_list(opt_.pin_workers, cpus)) {
throw std::invalid_argument("--pin-workers takes auto, off or a CPU list such as 2,4,6-9, not '" +
opt_.pin_workers + "'");
}
const int pinned = workers_->pin(cpus);
std::string used;
for (int i = 0; i < pinned; ++i) used += (i ? "," : "") + std::to_string(cpus[(size_t) i % cpus.size()]);
if (pinned > 0)
std::fprintf(stderr, "strata-poly: %d CPU threads pinned to CPUs %s (--pin-workers %s; the first "
"thread is not)\n", pinned, used.c_str(), opt_.pin_workers.c_str());
else
std::fprintf(stderr, "strata-poly: --pin-workers %s: the CPU threads are not pinned (Linux only, or "
"no CPU to give them)\n", opt_.pin_workers.c_str());
}
}
if (!aside_) aside_ = std::make_unique<Aside>();
if (opt_.defer_rank >= 0 && !defer_aside_) defer_aside_ = std::make_unique<Aside>();
Expand Down
3 changes: 3 additions & 0 deletions engine/src/poly/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ struct Options {
std::string model;
int max_context = 8192;
int threads = 0; ///< 0: the CPUs this process may use
std::string pin_workers; ///< the CPU threads' CPUs: "" or "off" none (the system places them), "auto"
///< (worker_cpu_order()), or a list such as "2,4,6-9" (STRATA_POLY_PIN_WORKERS,
///< --pin-workers; Linux)
int vram_reserve_mib = -1; ///< left free after the expert cache is filled; below 0: by the card's size
bool vram_pool = false; ///< one pool of VRAM claimed at load, kept for the whole run: the expert cache and the
///< attention caches trade pieces of it and nothing is given back to the card; the
Expand Down
4 changes: 4 additions & 0 deletions engine/src/poly/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2280,6 +2280,9 @@ void usage() {
" --no-gpu-experts keep every routed expert on the CPU\n"
" --any-node on a PC with several NUMA nodes, let the CPU threads run on any of them\n"
" (default: on the node whose memory holds most of the experts)\n"
" --pin-workers MODE Linux: keep each CPU thread on one CPU. auto: one thread a performance\n"
" core but the first, then the efficiency cores; or a list such as 2,4,6-9\n"
" (default off: the system places them; also STRATA_POLY_PIN_WORKERS)\n"
" --window N the most tokens that go through the model at once while an answer is\n"
" written: the one that is known and guesses at the ones after it, which\n"
" count when they turn out right (1 = no guesses; default 8, of which\n"
Expand Down Expand Up @@ -2514,6 +2517,7 @@ int main(int argc, char** argv) {
else if (a == "--pin-cache-mib") cache.o.pin_mib = std::atoll(val());
else if (a == "--no-gpu-experts") o.gpu_experts = false;
else if (a == "--any-node") o.stay_near = false;
else if (a == "--pin-workers") o.pin_workers = val();
else if (a == "--lock-experts") o.lock_experts = true;
else if (a == "--cold-lut") o.cold_lut = true;
else if (a == "--cold-q2-lut") o.cold_q2_lut = true;
Expand Down
48 changes: 48 additions & 0 deletions engine/src/poly/workers_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <cstdio>
#include <cstdlib>
#include <thread>
#include <vector>

using strata::poly::Workers;

Expand All @@ -20,7 +21,54 @@ int main() {
std::_Exit(1);
}
});
// --pin-workers: the CPU lists and the order auto gives the workers
{
using strata::poly::CpuSlot;
std::vector<int> v;
const auto list_is = [&](const char* text, std::vector<int> want) {
const bool ok = strata::poly::parse_cpu_list(text, v);
if (want.empty() ? ok : (!ok || v != want)) {
std::fprintf(stderr, "FAIL: parse_cpu_list(\"%s\")\n", text);
std::_Exit(1);
}
};
list_is("0", {0});
list_is("2,4,6-9", {2, 4, 6, 7, 8, 9});
list_is("12-19", {12, 13, 14, 15, 16, 17, 18, 19});
list_is("", {});
list_is("3-1", {});
list_is("1,,2", {});
list_is("1,", {});
list_is("a", {});
// an i9-12900H: P-cores 0-5 with two threads each (CPUs 2c, 2c+1), E-cores 12-19 (core ids 8-15)
std::vector<CpuSlot> h;
for (int c = 0; c < 12; ++c) h.push_back({c, c / 2, false});
for (int c = 12; c < 20; ++c) h.push_back({c, c - 4, true});
const std::vector<int> want = {2, 4, 6, 8, 10, 12, 13, 14, 15, 16, 17, 18, 19, 3, 5, 7, 9, 11, 0, 1};
if (strata::poly::worker_cpu_order(h) != want) {
std::fprintf(stderr, "FAIL: worker_cpu_order on a hybrid CPU\n");
std::_Exit(1);
}
// eight cores of two threads whose numbers go 0-7 then 8-15 for the second threads (as AMD's do)
std::vector<CpuSlot> a;
for (int c = 0; c < 16; ++c) a.push_back({c, c % 8, false});
const std::vector<int> want_a = {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 0, 8};
if (strata::poly::worker_cpu_order(a) != want_a) {
std::fprintf(stderr, "FAIL: worker_cpu_order on a CPU of one kind\n");
std::_Exit(1);
}
if (!strata::poly::worker_cpu_order({}).empty()) {
std::fprintf(stderr, "FAIL: worker_cpu_order of no CPUs\n");
std::_Exit(1);
}
}
Workers pool(8);
#if defined(__linux__)
if (pool.pin(strata::poly::worker_cpu_order(strata::poly::cpu_slots())) != 7) {
std::fprintf(stderr, "FAIL: Workers::pin\n");
std::_Exit(1);
}
#endif
int checks = 0;
for (int round = 0; round < 2000; ++round) {
std::atomic<int> outer{0}, inner{0};
Expand Down
35 changes: 35 additions & 0 deletions terminal/data/settings-register.json
Original file line number Diff line number Diff line change
Expand Up @@ -35735,6 +35735,41 @@
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_POLY_PIN_WORKERS",
"backends": [
"cuda-hip"
],
"reads": [
{
"file": "engine/src/poly/engine.cpp",
"line": 4049,
"backend": "cuda-hip",
"fn": "getenv"
}
],
"parse": "string",
"default_state": null,
"code_default": null,
"engine_sets": [],
"engine_defaults": [],
"launch_files": [],
"launch_sets": [],
"launch_reads": [],
"doc_mentions": [
"docs/GLM.md"
],
"first_commit": null,
"first_date": null,
"since": null,
"last_commit": null,
"last_date": null,
"status": "opt-in",
"owner": "poly",
"note": "Linux: pin the CPU expert threads (auto or a CPU list); same as --pin-workers",
"retire_after": "",
"retired_in": ""
},
{
"name": "STRATA_POLY_PROMPT_BLAS",
"backends": [
Expand Down