seqtree 1.3.3__tar.gz → 1.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. {seqtree-1.3.3 → seqtree-1.3.4}/CHANGELOG.md +5 -0
  2. {seqtree-1.3.3 → seqtree-1.3.4}/PKG-INFO +20 -27
  3. {seqtree-1.3.3 → seqtree-1.3.4}/README.md +19 -26
  4. seqtree-1.3.4/include/seqtree/parallel.hpp +252 -0
  5. {seqtree-1.3.3 → seqtree-1.3.4}/pyproject.toml +1 -1
  6. {seqtree-1.3.3 → seqtree-1.3.4}/src/gapblock.cpp +2 -2
  7. seqtree-1.3.3/include/seqtree/parallel.hpp +0 -134
  8. {seqtree-1.3.3 → seqtree-1.3.4}/.gitattributes +0 -0
  9. {seqtree-1.3.3 → seqtree-1.3.4}/.gitignore +0 -0
  10. {seqtree-1.3.3 → seqtree-1.3.4}/CMakeLists.txt +0 -0
  11. {seqtree-1.3.3 → seqtree-1.3.4}/LICENSE +0 -0
  12. {seqtree-1.3.3 → seqtree-1.3.4}/include/seqtree/kmer_index.hpp +0 -0
  13. {seqtree-1.3.3 → seqtree-1.3.4}/include/seqtree/seqtree.hpp +0 -0
  14. {seqtree-1.3.3 → seqtree-1.3.4}/include/seqtree/text_index.hpp +0 -0
  15. {seqtree-1.3.3 → seqtree-1.3.4}/include/seqtree/types.hpp +0 -0
  16. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/__init__.py +0 -0
  17. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/control.py +0 -0
  18. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/data/control_human_trb_aa.txt.gz +0 -0
  19. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/distance.py +0 -0
  20. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/evalue.py +0 -0
  21. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/gapblock.py +0 -0
  22. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/layout.py +0 -0
  23. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/pairwise.py +0 -0
  24. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/pmhc.py +0 -0
  25. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/pmhc_evalue.py +0 -0
  26. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/py.typed +0 -0
  27. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/seeds.py +0 -0
  28. {seqtree-1.3.3 → seqtree-1.3.4}/python/seqtree/text_evalue.py +0 -0
  29. {seqtree-1.3.3 → seqtree-1.3.4}/src/_bindings.cpp +0 -0
  30. {seqtree-1.3.3 → seqtree-1.3.4}/src/alignment_max.cpp +0 -0
  31. {seqtree-1.3.3 → seqtree-1.3.4}/src/atomic_write.hpp +0 -0
  32. {seqtree-1.3.3 → seqtree-1.3.4}/src/blosum45.inc +0 -0
  33. {seqtree-1.3.3 → seqtree-1.3.4}/src/blosum62.inc +0 -0
  34. {seqtree-1.3.3 → seqtree-1.3.4}/src/blosum80.inc +0 -0
  35. {seqtree-1.3.3 → seqtree-1.3.4}/src/codec.cpp +0 -0
  36. {seqtree-1.3.3 → seqtree-1.3.4}/src/count_unit.hpp +0 -0
  37. {seqtree-1.3.3 → seqtree-1.3.4}/src/distance.cpp +0 -0
  38. {seqtree-1.3.3 → seqtree-1.3.4}/src/engine_seqtm.cpp +0 -0
  39. {seqtree-1.3.3 → seqtree-1.3.4}/src/engine_seqtrie.cpp +0 -0
  40. {seqtree-1.3.3 → seqtree-1.3.4}/src/engines.hpp +0 -0
  41. {seqtree-1.3.3 → seqtree-1.3.4}/src/index.cpp +0 -0
  42. {seqtree-1.3.3 → seqtree-1.3.4}/src/kmer_index.cpp +0 -0
  43. {seqtree-1.3.3 → seqtree-1.3.4}/src/pairwise.cpp +0 -0
  44. {seqtree-1.3.3 → seqtree-1.3.4}/src/pairwise_detail.hpp +0 -0
  45. {seqtree-1.3.3 → seqtree-1.3.4}/src/pam100.inc +0 -0
  46. {seqtree-1.3.3 → seqtree-1.3.4}/src/pam250.inc +0 -0
  47. {seqtree-1.3.3 → seqtree-1.3.4}/src/positional_matrix.cpp +0 -0
  48. {seqtree-1.3.3 → seqtree-1.3.4}/src/searcher.cpp +0 -0
  49. {seqtree-1.3.3 → seqtree-1.3.4}/src/structural.inc +0 -0
  50. {seqtree-1.3.3 → seqtree-1.3.4}/src/substitution_matrix.cpp +0 -0
  51. {seqtree-1.3.3 → seqtree-1.3.4}/src/text_index.cpp +0 -0
  52. {seqtree-1.3.3 → seqtree-1.3.4}/src/trie.cpp +0 -0
  53. {seqtree-1.3.3 → seqtree-1.3.4}/src/trie.hpp +0 -0
@@ -5,6 +5,11 @@ versioning: breaking changes need a **major** bump.
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ ## 1.3.4
9
+
10
+ - Clamp oversized CPU/thread requests to the available budget instead of aborting.
11
+ Preserve automatic selection, explicit smaller budgets and bounded native workers.
12
+
8
13
  ## 1.3.3
9
14
 
10
15
  - Cap automatic native CPU budgets at 16 allocated CPUs; preserve larger explicit
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: seqtree
3
- Version: 1.3.3
3
+ Version: 1.3.4
4
4
  Summary: Fast fuzzy search over biological sequences (C++ core, Python bindings)
5
5
  Keywords: sequence-search,fuzzy-matching,CDR3,immunology,bioinformatics,trie
6
6
  Author-Email: ISALGO laboratory <mikhail.shugay@gmail.com>
@@ -52,7 +52,7 @@ Prebuilt wheels cover **Linux x86-64**, **macOS arm64 (Apple Silicon)**, and **W
52
52
  There are **no Intel/x86-64 macOS wheels** — Intel Macs build from source (see below), which just
53
53
  needs a C++20 compiler and CMake (pulled in automatically by the build).
54
54
 
55
- ## Quickstart
55
+ ## Quick start
56
56
 
57
57
  ```python
58
58
  import seqtree
@@ -63,26 +63,9 @@ p = seqtree.SearchParams(max_subs=2, engine="seqtm")
63
63
  for hit in idx.search("CASSLAPGATNEKLFF", p):
64
64
  print(hit.ref_id, hit.score, hit.n_subs)
65
65
 
66
- # parallel batch (releases the GIL)
67
- results = idx.search_batch(queries, p, threads=0) # 0 = automatic, up to 16 allocated CPUs
68
-
69
- # matrix-weighted budget. Name seqtrie -- engine="auto" always means seqtm.
70
- # gap_open must follow the matrix: 2 * blosum62.scale() == 28, not the default 1.
71
- pm = seqtree.SearchParams(matrix="blosum62", max_penalty=12, engine="seqtrie", gap_open=28)
72
- top = idx.search_top("CASSLAPGATNEKLFF", pm, k=5)
73
-
74
- # alignment on demand
75
- aln = idx.align(0, "CASSLELGATNEKLFF", p)
76
- print(aln.aligned_query, aln.aligned_ref, aln.ops)
77
-
78
- # batch-vs-batch (auto-indexes the larger set)
79
- pairs = seqtree.pairwise_batch(query_set, db_set, p, alphabet="aa")
80
-
81
- # a short query against a long TEXT (a proteome), one index for every query length
82
- tix = seqtree.TextIndex.build(proteome_records, alphabet="aa", k=4)
83
- res = tix.search_batch(peptides, max_subs=2, threads=0)
84
- for hit in res[0]:
85
- print(hit.ref_id, hit.offset, hit.n_subs, hit.mismatches)
66
+ # Batch search uses the automatic budget (allocated physical cores).
67
+ queries = ["CASSLAPGATNEKLFF", "CASSLELGATNEKLFF"]
68
+ results = idx.search_batch(queries, p)
86
69
  ```
87
70
 
88
71
  That is the whole core loop. Significance, gap blocks, alignment and distances are in
@@ -168,7 +151,7 @@ Beyond search, seqtree ships:
168
151
  C++ call (`numpy.asarray` wraps the result with no copy) — no `python-Levenshtein` or `rapidfuzz`
169
152
  dependency needed. Hamming requires equal lengths (it raises otherwise); comparison is
170
153
  case-sensitive. The same module *enumerates* a Hamming ball as well as scoring one:
171
- `neighbourhood(seq, r)` lists its `19·L + 1` members, and `neighbourhood_union(seqs, r)` takes
154
+ `neighbourhood(seq, r=1)` lists its `19·L + 1` amino-acid members, and `neighbourhood_union(seqs, r)` takes
172
155
  the union over many centres with each distinct sequence emitted **once** — deduplicated during
173
156
  the walk, so the `Σ 19·L_i` multiset never exists. For a tight specificity group that is a 41.7%
174
157
  saving, not a rounding correction.
@@ -278,6 +261,20 @@ Figures (throughput, scaling, matrix-scoring overhead, collisions, E-value matri
278
261
  detection) and the full methodology are in the [benchmarks docs](https://antigenomics.github.io/seqtree/benchmarks.html).
279
262
  Set `RUN_BENCHMARK=1` for the large tiers.
280
263
 
264
+ ## Parallel processing
265
+
266
+ CPU budgets use `threads=0` for automatic parallel work, using physical cores within the allocation.
267
+ Use `1` for serial work or a positive
268
+ count to select logical CPUs within the scheduler/container allocation.
269
+
270
+ Automatic sizing counts distinct physical cores within the process affinity mask,
271
+ then respects scheduler and container limits. When topology is unavailable, it
272
+ uses the available logical CPU count. A 40-logical-CPU, 20-core node therefore
273
+ uses up to 20 workers automatically; an explicit budget may use SMT threads.
274
+ Windows uses native core topology, process affinity and the current job CPU-rate
275
+ limit. Processes spanning processor groups must be bound to one group. Parent
276
+ job quotas are not exposed by this query; supply a budget within any parent limit.
277
+
281
278
  ## Development
282
279
 
283
280
  This repo follows **git-flow**:
@@ -305,7 +302,3 @@ and tie, count, exclusion and unsupported-value semantics.
305
302
 
306
303
  The public [seqtree skill](skills/seqtree/SKILL.md) guides use of the C++20 library
307
304
  and Python bindings for sequence search, alignment, distances, and batch operations.
308
-
309
- CPU budgets use `threads=0` for automatic parallel work, capped at 16 allocated CPUs.
310
- Use `1` for serial work or a positive
311
- count to override the automatic cap within the scheduler/container allocation.
@@ -20,7 +20,7 @@ Prebuilt wheels cover **Linux x86-64**, **macOS arm64 (Apple Silicon)**, and **W
20
20
  There are **no Intel/x86-64 macOS wheels** — Intel Macs build from source (see below), which just
21
21
  needs a C++20 compiler and CMake (pulled in automatically by the build).
22
22
 
23
- ## Quickstart
23
+ ## Quick start
24
24
 
25
25
  ```python
26
26
  import seqtree
@@ -31,26 +31,9 @@ p = seqtree.SearchParams(max_subs=2, engine="seqtm")
31
31
  for hit in idx.search("CASSLAPGATNEKLFF", p):
32
32
  print(hit.ref_id, hit.score, hit.n_subs)
33
33
 
34
- # parallel batch (releases the GIL)
35
- results = idx.search_batch(queries, p, threads=0) # 0 = automatic, up to 16 allocated CPUs
36
-
37
- # matrix-weighted budget. Name seqtrie -- engine="auto" always means seqtm.
38
- # gap_open must follow the matrix: 2 * blosum62.scale() == 28, not the default 1.
39
- pm = seqtree.SearchParams(matrix="blosum62", max_penalty=12, engine="seqtrie", gap_open=28)
40
- top = idx.search_top("CASSLAPGATNEKLFF", pm, k=5)
41
-
42
- # alignment on demand
43
- aln = idx.align(0, "CASSLELGATNEKLFF", p)
44
- print(aln.aligned_query, aln.aligned_ref, aln.ops)
45
-
46
- # batch-vs-batch (auto-indexes the larger set)
47
- pairs = seqtree.pairwise_batch(query_set, db_set, p, alphabet="aa")
48
-
49
- # a short query against a long TEXT (a proteome), one index for every query length
50
- tix = seqtree.TextIndex.build(proteome_records, alphabet="aa", k=4)
51
- res = tix.search_batch(peptides, max_subs=2, threads=0)
52
- for hit in res[0]:
53
- print(hit.ref_id, hit.offset, hit.n_subs, hit.mismatches)
34
+ # Batch search uses the automatic budget (allocated physical cores).
35
+ queries = ["CASSLAPGATNEKLFF", "CASSLELGATNEKLFF"]
36
+ results = idx.search_batch(queries, p)
54
37
  ```
55
38
 
56
39
  That is the whole core loop. Significance, gap blocks, alignment and distances are in
@@ -136,7 +119,7 @@ Beyond search, seqtree ships:
136
119
  C++ call (`numpy.asarray` wraps the result with no copy) — no `python-Levenshtein` or `rapidfuzz`
137
120
  dependency needed. Hamming requires equal lengths (it raises otherwise); comparison is
138
121
  case-sensitive. The same module *enumerates* a Hamming ball as well as scoring one:
139
- `neighbourhood(seq, r)` lists its `19·L + 1` members, and `neighbourhood_union(seqs, r)` takes
122
+ `neighbourhood(seq, r=1)` lists its `19·L + 1` amino-acid members, and `neighbourhood_union(seqs, r)` takes
140
123
  the union over many centres with each distinct sequence emitted **once** — deduplicated during
141
124
  the walk, so the `Σ 19·L_i` multiset never exists. For a tight specificity group that is a 41.7%
142
125
  saving, not a rounding correction.
@@ -246,6 +229,20 @@ Figures (throughput, scaling, matrix-scoring overhead, collisions, E-value matri
246
229
  detection) and the full methodology are in the [benchmarks docs](https://antigenomics.github.io/seqtree/benchmarks.html).
247
230
  Set `RUN_BENCHMARK=1` for the large tiers.
248
231
 
232
+ ## Parallel processing
233
+
234
+ CPU budgets use `threads=0` for automatic parallel work, using physical cores within the allocation.
235
+ Use `1` for serial work or a positive
236
+ count to select logical CPUs within the scheduler/container allocation.
237
+
238
+ Automatic sizing counts distinct physical cores within the process affinity mask,
239
+ then respects scheduler and container limits. When topology is unavailable, it
240
+ uses the available logical CPU count. A 40-logical-CPU, 20-core node therefore
241
+ uses up to 20 workers automatically; an explicit budget may use SMT threads.
242
+ Windows uses native core topology, process affinity and the current job CPU-rate
243
+ limit. Processes spanning processor groups must be bound to one group. Parent
244
+ job quotas are not exposed by this query; supply a budget within any parent limit.
245
+
249
246
  ## Development
250
247
 
251
248
  This repo follows **git-flow**:
@@ -273,7 +270,3 @@ and tie, count, exclusion and unsupported-value semantics.
273
270
 
274
271
  The public [seqtree skill](skills/seqtree/SKILL.md) guides use of the C++20 library
275
272
  and Python bindings for sequence search, alignment, distances, and batch operations.
276
-
277
- CPU budgets use `threads=0` for automatic parallel work, capped at 16 allocated CPUs.
278
- Use `1` for serial work or a positive
279
- count to override the automatic cap within the scheduler/container allocation.
@@ -0,0 +1,252 @@
1
+ #pragma once
2
+ // One parallel-for scaffold for the whole tree. Every batch entry point in seqtree used to
3
+ // carry its own copy of this: an atomic cursor, an adaptive chunk, an exception_ptr, a vector
4
+ // of threads, and a rethrow after the join. Seven copies drifted -- one of them had no
5
+ // exception plumbing at all.
6
+ #include <algorithm>
7
+ #include <atomic>
8
+ #include <cstddef>
9
+ #include <cstdint>
10
+ #include <cstdlib>
11
+ #include <exception>
12
+ #include <fstream>
13
+ #include <filesystem>
14
+ #include <sstream>
15
+ #include <mutex>
16
+ #include <set>
17
+ #include <string>
18
+ #include <stdexcept>
19
+ #include <thread>
20
+ #include <vector>
21
+
22
+ #ifdef __linux__
23
+ #include <sched.h>
24
+ #elif defined(__APPLE__)
25
+ #include <sys/sysctl.h>
26
+ #elif defined(_WIN32)
27
+ #ifndef NOMINMAX
28
+ #define NOMINMAX
29
+ #endif
30
+ #ifndef WIN32_LEAN_AND_MEAN
31
+ #define WIN32_LEAN_AND_MEAN
32
+ #endif
33
+ #include <windows.h>
34
+ #endif
35
+
36
+ namespace seqtree {
37
+
38
+ inline unsigned cpu_rate_budget(unsigned available, unsigned system_cpus, unsigned rate) {
39
+ if (!rate || rate > 10000) throw std::invalid_argument("invalid Windows CPU rate limit");
40
+ return std::min(available, std::max(1u, unsigned(uint64_t(system_cpus) * rate / 10000)));
41
+ }
42
+
43
+ #ifdef _WIN32
44
+ inline std::pair<unsigned, unsigned> windows_cpu_budget() {
45
+ const HANDLE process = GetCurrentProcess();
46
+ USHORT group_count = 1, group = 0;
47
+ if (!GetProcessGroupAffinity(process, &group_count, &group) || group_count != 1)
48
+ throw std::runtime_error("CPU budgeting requires a single Windows processor group; bind the process to one group");
49
+ DWORD_PTR mask = 0, system_mask = 0;
50
+ if (!GetProcessAffinityMask(process, &mask, &system_mask) || !mask)
51
+ throw std::runtime_error("cannot read Windows process CPU affinity");
52
+ unsigned logical = 0;
53
+ for (auto bits = mask; bits; bits &= bits - 1) ++logical;
54
+ DWORD bytes = 0;
55
+ GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &bytes);
56
+ if (!bytes) throw std::runtime_error("cannot read Windows physical CPU topology");
57
+ std::vector<unsigned char> buffer(bytes);
58
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore,
59
+ reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &bytes))
60
+ throw std::runtime_error("cannot read Windows physical CPU topology");
61
+ unsigned physical = 0;
62
+ for (size_t offset = 0; offset < bytes;) {
63
+ const auto* info = reinterpret_cast<const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*>(buffer.data() + offset);
64
+ if (!info->Size || offset + info->Size > bytes)
65
+ throw std::runtime_error("invalid Windows physical CPU topology");
66
+ bool allowed = false;
67
+ for (WORD i = 0; i < info->Processor.GroupCount; ++i)
68
+ allowed |= info->Processor.GroupMask[i].Group == group &&
69
+ (info->Processor.GroupMask[i].Mask & mask) != 0;
70
+ physical += allowed;
71
+ offset += info->Size;
72
+ }
73
+ if (!physical) throw std::runtime_error("Windows affinity contains no physical cores");
74
+ BOOL in_job = FALSE;
75
+ if (!IsProcessInJob(process, nullptr, &in_job))
76
+ throw std::runtime_error("cannot inspect Windows CPU job membership");
77
+ if (in_job) {
78
+ JOBOBJECT_CPU_RATE_CONTROL_INFORMATION rate{};
79
+ if (!QueryInformationJobObject(nullptr, JobObjectCpuRateControlInformation, &rate, sizeof(rate), nullptr))
80
+ throw std::runtime_error("cannot inspect Windows CPU job limit");
81
+ if (rate.ControlFlags & JOB_OBJECT_CPU_RATE_CONTROL_ENABLE) {
82
+ unsigned fraction = 0;
83
+ if (rate.ControlFlags & JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP) fraction = rate.CpuRate;
84
+ else if (rate.ControlFlags & JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE) fraction = rate.MaxRate;
85
+ if (fraction) {
86
+ const auto total = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
87
+ logical = cpu_rate_budget(logical, total, fraction);
88
+ }
89
+ }
90
+ }
91
+ return {logical, std::min(logical, physical)};
92
+ }
93
+ #endif
94
+
95
+ // Resolve once per batch; affinity/quota limits can change between calls.
96
+ inline unsigned available_cpus() {
97
+ unsigned count = std::max(1u, std::thread::hardware_concurrency());
98
+ #ifdef __linux__
99
+ cpu_set_t affinity;
100
+ if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0)
101
+ count = std::min(count, unsigned(std::max(1, CPU_COUNT(&affinity))));
102
+ namespace fs = std::filesystem;
103
+ const fs::path root("/sys/fs/cgroup");
104
+ std::vector<fs::path> bases{root, root / "cpu", root / "cpu,cpuacct", root / "cpuacct,cpu"};
105
+ std::vector<fs::path> paths = bases;
106
+ std::ifstream membership("/proc/self/cgroup");
107
+ std::string line;
108
+ while (std::getline(membership, line)) {
109
+ const auto first = line.find(':');
110
+ const auto second = line.find(':', first + 1);
111
+ if (first == std::string::npos || second == std::string::npos) continue;
112
+ const auto controllers = line.substr(first + 1, second - first - 1);
113
+ if (!controllers.empty() && ("," + controllers + ",").find(",cpu,") == std::string::npos) continue;
114
+ const fs::path relative = fs::path(line.substr(second + 1)).relative_path();
115
+ bool safe = true;
116
+ for (const auto& component : relative) if (component == "..") safe = false;
117
+ if (!safe) continue;
118
+ for (const auto& base : bases) {
119
+ if (controllers.empty() && base != root) continue;
120
+ for (auto path = base / relative; path != base; path = path.parent_path())
121
+ paths.push_back(path);
122
+ }
123
+ }
124
+ for (const auto& path : paths) {
125
+ std::string quota_text;
126
+ uint64_t period = 0;
127
+ std::ifstream v2(path / "cpu.max");
128
+ if (!(v2 >> quota_text >> period)) {
129
+ std::ifstream v1quota(path / "cpu.cfs_quota_us"), v1period(path / "cpu.cfs_period_us");
130
+ if (!(v1quota >> quota_text) || !(v1period >> period)) continue;
131
+ }
132
+ if (quota_text == "max" || quota_text == "-1" || !period) continue;
133
+ uint64_t quota = 0;
134
+ std::istringstream parsed(quota_text);
135
+ if (parsed >> quota && quota)
136
+ count = unsigned(std::min<uint64_t>(count, std::max<uint64_t>(1, quota / period)));
137
+ }
138
+ for (const char* name : {"SLURM_CPUS_PER_TASK", "SLURM_CPUS_ON_NODE"}) {
139
+ if (const char* value = std::getenv(name)) {
140
+ char* end = nullptr;
141
+ const auto allocated = std::strtoul(value, &end, 10);
142
+ if (end != value && !*end && allocated)
143
+ count = unsigned(std::min<unsigned long>(count, allocated));
144
+ }
145
+ }
146
+ #elif defined(_WIN32)
147
+ count = std::min(count, windows_cpu_budget().first);
148
+ #endif
149
+ return count;
150
+ }
151
+
152
+ inline unsigned physical_cores_for_cpus(const std::vector<unsigned>& cpus,
153
+ unsigned available,
154
+ const std::string& root = "/sys/devices/system/cpu/") {
155
+ std::set<std::pair<int, int>> cores;
156
+ for (unsigned cpu : cpus) {
157
+ const auto path = root + "cpu" + std::to_string(cpu) + "/topology/";
158
+ int package, core;
159
+ if (!(std::ifstream(path + "physical_package_id") >> package) ||
160
+ !(std::ifstream(path + "core_id") >> core) || package < 0 || core < 0) return available;
161
+ cores.emplace(package, core);
162
+ }
163
+ return cores.empty() ? available : std::min(available, unsigned(cores.size()));
164
+ }
165
+
166
+ // Topology is separate from the logical allocation: explicit budgets may use SMT.
167
+ inline unsigned physical_cpus() {
168
+ const unsigned available = available_cpus();
169
+ #ifdef __linux__
170
+ cpu_set_t affinity;
171
+ if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0) {
172
+ std::vector<unsigned> cpus;
173
+ for (int cpu = 0; cpu < CPU_SETSIZE; ++cpu)
174
+ if (CPU_ISSET(cpu, &affinity)) cpus.push_back(unsigned(cpu));
175
+ return physical_cores_for_cpus(cpus, available);
176
+ }
177
+ #elif defined(__APPLE__)
178
+ unsigned physical = available;
179
+ size_t size = sizeof(physical);
180
+ if (sysctlbyname("hw.physicalcpu", &physical, &size, nullptr, 0) == 0 && physical)
181
+ return std::min(available, physical);
182
+ #elif defined(_WIN32)
183
+ return windows_cpu_budget().second;
184
+ #endif
185
+ return available;
186
+ }
187
+
188
+ // Runs body(i, local) for every i in [0, n), across nt workers pulling contiguous chunks off
189
+ // one atomic cursor. `threads <= 0` selects available physical cores; positive counts may use logical CPUs.
190
+ //
191
+ // `make_local()` is called once per worker and its result handed to every body() that worker
192
+ // runs -- that is how a Searcher or a scratch buffer gets allocated once per thread rather
193
+ // than once per item. Return a dummy for kernels that need no state.
194
+ //
195
+ // The chunk is adaptive: large batches keep ~1024 items per grab so the atomic is not the
196
+ // bottleneck, small ones split ~8 chunks per thread so no worker goes idle. Raise `chunk_min`
197
+ // when the per-item output struct is small enough that neighbouring workers would share a
198
+ // cache line (TextIndex's QueryOut is ~80 bytes, so it passes 8).
199
+ //
200
+ // Workers catch, the first exception is kept, and it is rethrown after the join. This is not
201
+ // optional: an exception escaping a std::thread entry function calls std::terminate, which
202
+ // from Python is an uncatchable SIGABRT rather than a raise.
203
+ template <class MakeLocal, class Body>
204
+ void parallel_for(size_t n, int threads, MakeLocal make_local, Body body,
205
+ size_t chunk_min = 1, size_t chunk_max = 1024) {
206
+ const unsigned available = available_cpus();
207
+ unsigned nt = threads > 0 ? unsigned(threads) : physical_cpus();
208
+ nt = std::min({nt, available, 999u});
209
+ if (n == 0) return;
210
+ nt = unsigned(std::min<size_t>(nt, n)); // Do not start idle workers for absent work.
211
+
212
+ // A serial budget runs on the calling thread; spawning one worker only adds overhead.
213
+ if (nt == 1) {
214
+ auto local = make_local();
215
+ for (size_t i = 0; i < n; ++i) body(i, local);
216
+ return;
217
+ }
218
+
219
+ std::atomic<size_t> next{0};
220
+ const size_t chunk = std::clamp<size_t>(n / (size_t(nt) * 8), chunk_min, chunk_max);
221
+ std::exception_ptr err;
222
+ std::mutex emu;
223
+
224
+ auto worker = [&] {
225
+ // Scratch construction can allocate and throw too. Nothing may escape the entry point.
226
+ try {
227
+ auto local = make_local();
228
+ for (;;) {
229
+ const size_t start = next.fetch_add(chunk);
230
+ if (start >= n) break;
231
+ const size_t end = std::min(n, start + chunk);
232
+ for (size_t i = start; i < end; ++i) {
233
+ body(i, local);
234
+ }
235
+ }
236
+ } catch (...) {
237
+ std::lock_guard<std::mutex> lk(emu);
238
+ if (!err) err = std::current_exception();
239
+ }
240
+ };
241
+
242
+ // A failed thread launch must also join workers already started before unwinding.
243
+ std::vector<std::jthread> pool;
244
+ pool.reserve(nt);
245
+ // The caller is one compute thread: a budget B creates only B-1 OS workers.
246
+ for (unsigned t = 1; t < nt; ++t) pool.emplace_back(worker);
247
+ worker();
248
+ for (auto& th : pool) th.join();
249
+ if (err) std::rethrow_exception(err);
250
+ }
251
+
252
+ } // namespace seqtree
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
4
4
 
5
5
  [project]
6
6
  name = "seqtree"
7
- version = "1.3.3"
7
+ version = "1.3.4"
8
8
  description = "Fast fuzzy search over biological sequences (C++ core, Python bindings)"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1143,8 +1143,8 @@ GroupedCountBatch::GroupedCountBatch(const std::vector<std::string>& qa, const s
1143
1143
  beta->query_groups,beta->reference_groups,beta->group_distances,
1144
1144
  beta->query_weights,beta->reference_weights,beta->features,&bound_b);
1145
1145
  } else if (!qb.empty() || !rb.empty()) throw std::invalid_argument("paired axes require beta geometry");
1146
- if (threads<0 || unsigned(threads)>available_cpus())
1147
- throw std::invalid_argument("worker count exceeds the available CPU budget");
1146
+ if (threads<0)
1147
+ throw std::invalid_argument("worker count must be nonnegative");
1148
1148
  in.cuts=std::move(cuts); in.offsets=std::move(offsets); in.labels=std::move(labels);
1149
1149
  if (!in.return_hits) in.prepare_bins();
1150
1150
  in.target_peptides=std::move(target_peptides); in.exclusive=std::move(exclusive);
@@ -1,134 +0,0 @@
1
- #pragma once
2
- // One parallel-for scaffold for the whole tree. Every batch entry point in seqtree used to
3
- // carry its own copy of this: an atomic cursor, an adaptive chunk, an exception_ptr, a vector
4
- // of threads, and a rethrow after the join. Seven copies drifted -- one of them had no
5
- // exception plumbing at all.
6
- #include <algorithm>
7
- #include <atomic>
8
- #include <cstddef>
9
- #include <cstdint>
10
- #include <cstdlib>
11
- #include <exception>
12
- #include <fstream>
13
- #include <mutex>
14
- #include <stdexcept>
15
- #include <thread>
16
- #include <vector>
17
-
18
- #ifdef __linux__
19
- #include <sched.h>
20
- #elif defined(__APPLE__)
21
- #include <sys/sysctl.h>
22
- #elif defined(_WIN32)
23
- #ifndef NOMINMAX
24
- #define NOMINMAX
25
- #endif
26
- #ifndef WIN32_LEAN_AND_MEAN
27
- #define WIN32_LEAN_AND_MEAN
28
- #endif
29
- #include <windows.h>
30
- #endif
31
-
32
- namespace seqtree {
33
-
34
- // Resolve once per batch; affinity/quota limits can change between calls.
35
- inline unsigned available_cpus() {
36
- unsigned count = std::max(1u, std::thread::hardware_concurrency());
37
- #ifdef __linux__
38
- cpu_set_t affinity;
39
- if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0)
40
- count = std::min(count, unsigned(std::max(1, CPU_COUNT(&affinity))));
41
- std::ifstream limits("/sys/fs/cgroup/cpu.max");
42
- uint64_t quota, period;
43
- if (limits >> quota >> period && period)
44
- count = unsigned(std::min<uint64_t>(count, std::max<uint64_t>(1, quota / period)));
45
- for (const char* name : {"SLURM_CPUS_PER_TASK", "SLURM_CPUS_ON_NODE"}) {
46
- if (const char* value = std::getenv(name)) {
47
- char* end = nullptr;
48
- const auto allocated = std::strtoul(value, &end, 10);
49
- if (end != value && !*end && allocated)
50
- count = unsigned(std::min<unsigned long>(count, allocated));
51
- }
52
- }
53
- #elif defined(__APPLE__)
54
- unsigned physical = count;
55
- size_t size = sizeof(physical);
56
- if (sysctlbyname("hw.physicalcpu", &physical, &size, nullptr, 0) == 0 && physical)
57
- count = std::min(count, physical);
58
- #elif defined(_WIN32)
59
- DWORD_PTR process_mask, system_mask;
60
- if (GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &system_mask)) {
61
- unsigned allowed = 0;
62
- for (; process_mask; process_mask &= process_mask - 1) ++allowed;
63
- if (allowed) count = std::min(count, allowed);
64
- }
65
- #endif
66
- return count;
67
- }
68
-
69
- // Runs body(i, local) for every i in [0, n), across nt workers pulling contiguous chunks off
70
- // one atomic cursor. `threads <= 0` selects up to 16 available CPUs; positive counts may exceed that cap.
71
- //
72
- // `make_local()` is called once per worker and its result handed to every body() that worker
73
- // runs -- that is how a Searcher or a scratch buffer gets allocated once per thread rather
74
- // than once per item. Return a dummy for kernels that need no state.
75
- //
76
- // The chunk is adaptive: large batches keep ~1024 items per grab so the atomic is not the
77
- // bottleneck, small ones split ~8 chunks per thread so no worker goes idle. Raise `chunk_min`
78
- // when the per-item output struct is small enough that neighbouring workers would share a
79
- // cache line (TextIndex's QueryOut is ~80 bytes, so it passes 8).
80
- //
81
- // Workers catch, the first exception is kept, and it is rethrown after the join. This is not
82
- // optional: an exception escaping a std::thread entry function calls std::terminate, which
83
- // from Python is an uncatchable SIGABRT rather than a raise.
84
- template <class MakeLocal, class Body>
85
- void parallel_for(size_t n, int threads, MakeLocal make_local, Body body,
86
- size_t chunk_min = 1, size_t chunk_max = 1024) {
87
- const unsigned available = available_cpus();
88
- unsigned nt = threads > 0 ? unsigned(threads) : std::min(available, 16u);
89
- if (nt > available || nt >= 1000)
90
- throw std::invalid_argument("worker count exceeds the available CPU budget; request fewer threads");
91
- if (n == 0) return;
92
- nt = unsigned(std::min<size_t>(nt, n)); // Do not start idle workers for absent work.
93
-
94
- // A serial budget runs on the calling thread; spawning one worker only adds overhead.
95
- if (nt == 1) {
96
- auto local = make_local();
97
- for (size_t i = 0; i < n; ++i) body(i, local);
98
- return;
99
- }
100
-
101
- std::atomic<size_t> next{0};
102
- const size_t chunk = std::clamp<size_t>(n / (size_t(nt) * 8), chunk_min, chunk_max);
103
- std::exception_ptr err;
104
- std::mutex emu;
105
-
106
- auto worker = [&] {
107
- // Scratch construction can allocate and throw too. Nothing may escape the entry point.
108
- try {
109
- auto local = make_local();
110
- for (;;) {
111
- const size_t start = next.fetch_add(chunk);
112
- if (start >= n) break;
113
- const size_t end = std::min(n, start + chunk);
114
- for (size_t i = start; i < end; ++i) {
115
- body(i, local);
116
- }
117
- }
118
- } catch (...) {
119
- std::lock_guard<std::mutex> lk(emu);
120
- if (!err) err = std::current_exception();
121
- }
122
- };
123
-
124
- // A failed thread launch must also join workers already started before unwinding.
125
- std::vector<std::jthread> pool;
126
- pool.reserve(nt);
127
- // The caller is one compute thread: a budget B creates only B-1 OS workers.
128
- for (unsigned t = 1; t < nt; ++t) pool.emplace_back(worker);
129
- worker();
130
- for (auto& th : pool) th.join();
131
- if (err) std::rethrow_exception(err);
132
- }
133
-
134
- } // namespace seqtree
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes