fastmixture2 2.0.9__tar.gz → 2.1.0__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.
- {fastmixture2-2.0.9/fastmixture2.egg-info → fastmixture2-2.1.0}/PKG-INFO +12 -24
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/README.md +11 -23
- fastmixture2-2.1.0/fastmixture2/__init__.py +1 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/defaults.py +2 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/fastmixture2.py +3 -3
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/functions.py +1 -3
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/gpu.py +9 -1
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/shared.pyx +48 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/utils.py +102 -22
- {fastmixture2-2.0.9 → fastmixture2-2.1.0/fastmixture2.egg-info}/PKG-INFO +12 -24
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2.egg-info/SOURCES.txt +1 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/check_portable.py +1 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_streamed.py +122 -0
- fastmixture2-2.1.0/tests/test_sample_subset.py +294 -0
- fastmixture2-2.0.9/fastmixture2/__init__.py +0 -1
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/LICENSE +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/MANIFEST.in +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/em.pyx +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/kernels.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/main.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/packed.pxd +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/plink.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/sqp.pyx +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/svd.pyx +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2/threads.pxd +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2.egg-info/dependency_links.txt +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2.egg-info/entry_points.txt +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2.egg-info/requires.txt +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/fastmixture2.egg-info/top_level.txt +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/pyproject.toml +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/setup.cfg +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/setup.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/helpers.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/run_tests.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_adversarial_io.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_bootstrap.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_cli.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_convergence.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_cpu_scaling.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_cpu_subset.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_cross_validation.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_distribution.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_frequency_cache.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_genotypes.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_called.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_em.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_gl_precision.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_large.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_modes.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_precision.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_safety.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_stat_reuse.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_subset.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_supervision.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_gpu_svd_cache.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_initialization.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_likelihoods.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_numerical_equivalence.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_optimizers.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_plink_files.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_q_constraints.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_restarts.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_sqp_scoring.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_sqp_solver.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_subset_modes.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/test_threads.py +0 -0
- {fastmixture2-2.0.9 → fastmixture2-2.1.0}/tests/validate_distribution.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastmixture2
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Biobank-scale ancestry estimation in unrelated individuals
|
|
5
5
|
Author-email: "J. Meisner" <meisnerucph@gmail.com>, "L. Thunegard" <lisathunegard@icloud.com>
|
|
6
6
|
License-Expression: GPL-3.0-only
|
|
@@ -61,8 +61,7 @@ python -m pip install .
|
|
|
61
61
|
```
|
|
62
62
|
|
|
63
63
|
Source builds need a C compiler with OpenMP. On macOS, install OpenMP with
|
|
64
|
-
`brew install libomp`.
|
|
65
|
-
analyses.
|
|
64
|
+
`brew install libomp`.
|
|
66
65
|
|
|
67
66
|
With Conda, the [CPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-cpu.yml)
|
|
68
67
|
and [GPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-gpu.yml)
|
|
@@ -153,17 +152,19 @@ CUDA keeps input data on the GPU when they fit and streams in blocks otherwise.
|
|
|
153
152
|
Small CPU/GPU differences can arise from floating-point arithmetic.
|
|
154
153
|
|
|
155
154
|
At K > 1, unsupervised fits use SVD/ALS on up to 50,000 genome-wide SNPs, with
|
|
156
|
-
subset refinement for larger panels.
|
|
155
|
+
subset refinement for larger panels. For called genotypes, joint subset refinement
|
|
156
|
+
uses up to 50,000 randomly selected individuals. The remaining Q rows are fitted
|
|
157
|
+
at fixed P before full-data fitting. All modes use safeguarded SQP/ZAL with EM/QN
|
|
157
158
|
rescue and float64 likelihood checks. CPU fitting uses float64. CUDA uses
|
|
158
159
|
mixed precision followed by float64 refinement.
|
|
159
160
|
|
|
160
161
|
Processing uses bounded tiles. Total memory still grows with panel size and K.
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
sufficient space.
|
|
162
|
+
Temporary files use `TMPDIR`. For large panels, use disk-backed scratch with
|
|
163
|
+
enough space.
|
|
164
164
|
|
|
165
165
|
The defaults are `--threads 1`, `--seed 42`, `--iter 1000` and `--tole 1e-10`.
|
|
166
|
-
`--threads` also controls CPU work during GPU fits.
|
|
166
|
+
`--threads` also controls CPU work during GPU fits. On HPC, use the allocated
|
|
167
|
+
CPU count.
|
|
167
168
|
The optimizer scales the tolerance by observed genotypes or informative
|
|
168
169
|
likelihood triplets. `--iter` and `--tole` apply to each refinement stage.
|
|
169
170
|
Run `fastmixture2 --help` for the full CLI.
|
|
@@ -316,22 +317,9 @@ For `--out cohort --K 5 --seed 42`:
|
|
|
316
317
|
| `cohort.K5.s42.Q_se` | Q standard errors when bootstrap is requested |
|
|
317
318
|
| `cohort.K5.s42.log` | Settings, likelihood, convergence and CV/bootstrap summaries |
|
|
318
319
|
|
|
319
|
-
Rows follow input order and columns correspond to components.
|
|
320
|
-
|
|
321
|
-
P
|
|
322
|
-
For Beagle, it is the frequency of allele2.
|
|
323
|
-
|
|
324
|
-
Matrices use ten decimal places. Logs retain full-precision likelihoods and
|
|
325
|
-
iteration counts, including ALS when used.
|
|
326
|
-
|
|
327
|
-
Outputs, checkpoints and caches use standard file permissions controlled by
|
|
328
|
-
your umask.
|
|
329
|
-
|
|
330
|
-
The log distinguishes convergence, iteration limits, stalled optimization and
|
|
331
|
-
numerical failure. Unsuccessful fits retain the best accepted parameters.
|
|
332
|
-
|
|
333
|
-
Parallel jobs should use distinct output prefixes. Build each likelihood cache
|
|
334
|
-
with one job, then reuse it across fits, or use a separate cache path per job.
|
|
320
|
+
Rows follow input order and columns correspond to components. `--write-info`
|
|
321
|
+
adds headers and IDs. `--no-freqs` omits P, which is also omitted in projection.
|
|
322
|
+
P is the frequency of BIM A1 for PLINK and allele2 for Beagle.
|
|
335
323
|
|
|
336
324
|
## Authors and license
|
|
337
325
|
|
|
@@ -30,8 +30,7 @@ python -m pip install .
|
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
Source builds need a C compiler with OpenMP. On macOS, install OpenMP with
|
|
33
|
-
`brew install libomp`.
|
|
34
|
-
analyses.
|
|
33
|
+
`brew install libomp`.
|
|
35
34
|
|
|
36
35
|
With Conda, the [CPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-cpu.yml)
|
|
37
36
|
and [GPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-gpu.yml)
|
|
@@ -122,17 +121,19 @@ CUDA keeps input data on the GPU when they fit and streams in blocks otherwise.
|
|
|
122
121
|
Small CPU/GPU differences can arise from floating-point arithmetic.
|
|
123
122
|
|
|
124
123
|
At K > 1, unsupervised fits use SVD/ALS on up to 50,000 genome-wide SNPs, with
|
|
125
|
-
subset refinement for larger panels.
|
|
124
|
+
subset refinement for larger panels. For called genotypes, joint subset refinement
|
|
125
|
+
uses up to 50,000 randomly selected individuals. The remaining Q rows are fitted
|
|
126
|
+
at fixed P before full-data fitting. All modes use safeguarded SQP/ZAL with EM/QN
|
|
126
127
|
rescue and float64 likelihood checks. CPU fitting uses float64. CUDA uses
|
|
127
128
|
mixed precision followed by float64 refinement.
|
|
128
129
|
|
|
129
130
|
Processing uses bounded tiles. Total memory still grows with panel size and K.
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
sufficient space.
|
|
131
|
+
Temporary files use `TMPDIR`. For large panels, use disk-backed scratch with
|
|
132
|
+
enough space.
|
|
133
133
|
|
|
134
134
|
The defaults are `--threads 1`, `--seed 42`, `--iter 1000` and `--tole 1e-10`.
|
|
135
|
-
`--threads` also controls CPU work during GPU fits.
|
|
135
|
+
`--threads` also controls CPU work during GPU fits. On HPC, use the allocated
|
|
136
|
+
CPU count.
|
|
136
137
|
The optimizer scales the tolerance by observed genotypes or informative
|
|
137
138
|
likelihood triplets. `--iter` and `--tole` apply to each refinement stage.
|
|
138
139
|
Run `fastmixture2 --help` for the full CLI.
|
|
@@ -285,22 +286,9 @@ For `--out cohort --K 5 --seed 42`:
|
|
|
285
286
|
| `cohort.K5.s42.Q_se` | Q standard errors when bootstrap is requested |
|
|
286
287
|
| `cohort.K5.s42.log` | Settings, likelihood, convergence and CV/bootstrap summaries |
|
|
287
288
|
|
|
288
|
-
Rows follow input order and columns correspond to components.
|
|
289
|
-
|
|
290
|
-
P
|
|
291
|
-
For Beagle, it is the frequency of allele2.
|
|
292
|
-
|
|
293
|
-
Matrices use ten decimal places. Logs retain full-precision likelihoods and
|
|
294
|
-
iteration counts, including ALS when used.
|
|
295
|
-
|
|
296
|
-
Outputs, checkpoints and caches use standard file permissions controlled by
|
|
297
|
-
your umask.
|
|
298
|
-
|
|
299
|
-
The log distinguishes convergence, iteration limits, stalled optimization and
|
|
300
|
-
numerical failure. Unsuccessful fits retain the best accepted parameters.
|
|
301
|
-
|
|
302
|
-
Parallel jobs should use distinct output prefixes. Build each likelihood cache
|
|
303
|
-
with one job, then reuse it across fits, or use a separate cache path per job.
|
|
289
|
+
Rows follow input order and columns correspond to components. `--write-info`
|
|
290
|
+
adds headers and IDs. `--no-freqs` omits P, which is also omitted in projection.
|
|
291
|
+
P is the frequency of BIM A1 for PLINK and allele2 for Beagle.
|
|
304
292
|
|
|
305
293
|
## Authors and license
|
|
306
294
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.1.0"
|
|
@@ -16,6 +16,7 @@ LIKELIHOOD_FREQUENCY_VERSION = 2
|
|
|
16
16
|
|
|
17
17
|
# Initialization
|
|
18
18
|
INITIALIZATION_MARKERS = 50_000
|
|
19
|
+
INITIALIZATION_SAMPLES = 50_000
|
|
19
20
|
SVD_POWER_ITERATIONS = 10
|
|
20
21
|
SVD_CHUNK_MARKERS = 4_096
|
|
21
22
|
SVD_WORKSPACE_BYTES = 512 << 20
|
|
@@ -38,6 +39,7 @@ LIKELIHOOD_CONVERGENCE_WINDOW = 10
|
|
|
38
39
|
# CUDA storage
|
|
39
40
|
GPU_TILE_BYTES = 512 << 20
|
|
40
41
|
GPU_SQP_STAT_BYTES = 512 << 20
|
|
42
|
+
GPU_SQP_FULL_STAT_BYTES = 1 << 30
|
|
41
43
|
GPU_SQP_WORKSPACE_BYTES = 128 << 20
|
|
42
44
|
GPU_BOOT_STAT_BYTES = 64 << 20
|
|
43
45
|
GPU_MIN_TILE_BYTES = 128 << 20
|
|
@@ -958,7 +958,7 @@ def _run(args, stack):
|
|
|
958
958
|
# Run fixed-P projection or joint P/Q estimation
|
|
959
959
|
res = functions.hybridRun(G, P, Q, q_nrm, y, run, fixed=args.projection is not None)
|
|
960
960
|
if args.restarts:
|
|
961
|
-
rs_rng = np.random.default_rng(
|
|
961
|
+
rs_rng = np.random.default_rng([args.seed, 0x5253])
|
|
962
962
|
res = functions.restartRun(G, P, Q, q_nrm, rs_rng, run, res, args.restarts)
|
|
963
963
|
G.pop("freq", None)
|
|
964
964
|
|
|
@@ -970,7 +970,7 @@ def _run(args, stack):
|
|
|
970
970
|
cv_run["tole"] = args.cv_tole
|
|
971
971
|
cv_run["cv"] = args.cv
|
|
972
972
|
cv_run["random_init"] = args.random_init
|
|
973
|
-
cv_rng = np.random.default_rng(
|
|
973
|
+
cv_rng = np.random.default_rng([args.seed, 0x4356])
|
|
974
974
|
P0, Q0 = (None, None) if args.exact_cv else (P, Q)
|
|
975
975
|
cv_res = cvRun(G, P0, Q0, q_nrm, args.K, cv_rng, cv_run)
|
|
976
976
|
|
|
@@ -987,7 +987,7 @@ def _run(args, stack):
|
|
|
987
987
|
"boot_tole": args.bootstrap_tole,
|
|
988
988
|
"log": runtime.append,
|
|
989
989
|
}
|
|
990
|
-
boot_rng = np.random.default_rng(
|
|
990
|
+
boot_rng = np.random.default_rng([args.seed, 0x4253])
|
|
991
991
|
Q_se = functions.bootRun(G, P, Q, y, boot_rng, boot_run)
|
|
992
992
|
|
|
993
993
|
# Save estimates in physical input order
|
|
@@ -1044,9 +1044,7 @@ def restartRun(G, P, Q, q_nrm, rng, run, res, n):
|
|
|
1044
1044
|
step = time()
|
|
1045
1045
|
name = "merge/split" if t else "Q permutation"
|
|
1046
1046
|
draw = (
|
|
1047
|
-
np.random.default_rng(
|
|
1048
|
-
np.random.SeedSequence([run["seed"], K, i, 0x4D53 if t else 0x4652])
|
|
1049
|
-
)
|
|
1047
|
+
np.random.default_rng([run["seed"], K, i, 0x4D53 if t else 0x4652])
|
|
1050
1048
|
if "seed" in run
|
|
1051
1049
|
else rng
|
|
1052
1050
|
)
|
|
@@ -2876,7 +2876,7 @@ def _initializeUnsupervised(cp, np, utils, G, K, rng, strict, f, run=None):
|
|
|
2876
2876
|
)
|
|
2877
2877
|
del U, S, V
|
|
2878
2878
|
if refine:
|
|
2879
|
-
utils._refineSubset(G, P, Q, s, run, fit, defaults.GPU_SVD_WORKSPACE_BYTES)
|
|
2879
|
+
utils._refineSubset(G, P, Q, s, run, fit, defaults.GPU_SVD_WORKSPACE_BYTES, rng=rng)
|
|
2880
2880
|
T = _svdTiles(cp, np, G, f, K, defaults.GPU_SVD_WORKSPACE_BYTES)
|
|
2881
2881
|
P0 = P
|
|
2882
2882
|
P = _projectP(cp, np, utils, T, Q)
|
|
@@ -2950,6 +2950,14 @@ def _tiledWorkspace(D, kern, mixed=True, rows=None, fp64=True):
|
|
|
2950
2950
|
free, _ = cp.cuda.runtime.memGetInfo()
|
|
2951
2951
|
size = min(defaults.GPU_SQP_STAT_BYTES, max(0, free - reserve))
|
|
2952
2952
|
qn = min(D["N"], max(r, size // (8 * (K + kp)) // r * r))
|
|
2953
|
+
if qn < D["N"] and "B" in D and not D.get("supervision_bytes", 0):
|
|
2954
|
+
# Avoid another scan while reserving the second input buffer
|
|
2955
|
+
size = 8 * D["N"] * (K + kp)
|
|
2956
|
+
if (
|
|
2957
|
+
size <= defaults.GPU_SQP_FULL_STAT_BYTES
|
|
2958
|
+
and size + D["B"].nbytes <= free - reserve
|
|
2959
|
+
):
|
|
2960
|
+
qn = D["N"]
|
|
2953
2961
|
W["qn"] = qn
|
|
2954
2962
|
W["g"] = cp.empty((max(r, qn), K), dtype=cp.float64)
|
|
2955
2963
|
W["h"] = cp.empty((max(r, qn), kp), dtype=cp.float64)
|
|
@@ -10,6 +10,7 @@ from cpython.unicode cimport Py_UNICODE_ISSPACE
|
|
|
10
10
|
cimport openmp as omp
|
|
11
11
|
from cython.parallel import parallel, prange
|
|
12
12
|
from libc.math cimport fabs, fmax, fmin, isfinite, log, pow
|
|
13
|
+
from libc.stddef cimport size_t
|
|
13
14
|
from libc.stdint cimport uint8_t, uint32_t, uint64_t, uintptr_t
|
|
14
15
|
from libc.stdlib cimport calloc, free, malloc
|
|
15
16
|
from fastmixture2.packed cimport (
|
|
@@ -965,6 +966,53 @@ cdef int _inspectPackedRows(
|
|
|
965
966
|
return 0
|
|
966
967
|
|
|
967
968
|
|
|
969
|
+
cdef extern from *:
|
|
970
|
+
"""
|
|
971
|
+
static inline void fm_select_samples(
|
|
972
|
+
const uint8_t *src, uint8_t *out, const uint32_t *idx, size_t n) {
|
|
973
|
+
size_t i = 0;
|
|
974
|
+
for (; i + 4 <= n; i += 4) {
|
|
975
|
+
const uint32_t a = idx[i], b = idx[i + 1];
|
|
976
|
+
const uint32_t c = idx[i + 2], d = idx[i + 3];
|
|
977
|
+
out[i >> 2] = ((src[a >> 2] >> (2 * (a & 3))) & 3)
|
|
978
|
+
| (((src[b >> 2] >> (2 * (b & 3))) & 3) << 2)
|
|
979
|
+
| (((src[c >> 2] >> (2 * (c & 3))) & 3) << 4)
|
|
980
|
+
| (((src[d >> 2] >> (2 * (d & 3))) & 3) << 6);
|
|
981
|
+
}
|
|
982
|
+
if (i < n) {
|
|
983
|
+
/* Pad unused calls as missing */
|
|
984
|
+
uint8_t v = 0x55;
|
|
985
|
+
for (size_t j = 0; i + j < n; ++j) {
|
|
986
|
+
const uint32_t a = idx[i + j];
|
|
987
|
+
const uint8_t c = (src[a >> 2] >> (2 * (a & 3))) & 3;
|
|
988
|
+
v = (v & ~(3U << (2 * j))) | (c << (2 * j));
|
|
989
|
+
}
|
|
990
|
+
out[i >> 2] = v;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
"""
|
|
994
|
+
void fm_select_samples(const u8*, u8*, const u32*, size_t) noexcept nogil
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
### Split selected marker rows into two packed sample panels
|
|
998
|
+
def splitSamples(
|
|
999
|
+
const u8[:, ::1] B, u8[:, ::1] A, u8[:, ::1] C,
|
|
1000
|
+
const u32[::1] s, const u32[::1] idx, const u32[::1] rest,
|
|
1001
|
+
const uintptr_t[::1] rows=None):
|
|
1002
|
+
cdef:
|
|
1003
|
+
Py_ssize_t j = 0, n = idx.shape[0], nr = rest.shape[0], m = s.shape[0]
|
|
1004
|
+
const u8 *row = NULL
|
|
1005
|
+
|
|
1006
|
+
if m < 1 or n < 1 or nr < 1 or A.shape[0] != m or C.shape[0] != m:
|
|
1007
|
+
raise ValueError("Invalid split dimensions")
|
|
1008
|
+
if A.shape[1] != (n + 3) // 4 or C.shape[1] != (nr + 3) // 4:
|
|
1009
|
+
raise ValueError("Invalid split row widths")
|
|
1010
|
+
for j in prange(m, nogil=True, schedule="static"):
|
|
1011
|
+
row = packedRow(B, rows, s[j])
|
|
1012
|
+
fm_select_samples(row, &A[j, 0], &idx[0], n)
|
|
1013
|
+
fm_select_samples(row, &C[j, 0], &rest[0], nr)
|
|
1014
|
+
|
|
1015
|
+
|
|
968
1016
|
### Count observed alleles in one packed pass
|
|
969
1017
|
cpdef int countPackedRows(
|
|
970
1018
|
const u8[:, ::1] B, f64[::1] q_nrm,
|
|
@@ -848,7 +848,7 @@ def initializeUnsupervised(G, K, rng, strict=True, run=None, fit=None, limit=Non
|
|
|
848
848
|
from fastmixture2 import functions
|
|
849
849
|
|
|
850
850
|
fit = partial(functions.likelihoodRun if gl else functions.sqpRun, subset=True)
|
|
851
|
-
_refineSubset(G, P, Q, s, run, fit, limit)
|
|
851
|
+
_refineSubset(G, P, Q, s, run, fit, limit, rng=rng)
|
|
852
852
|
P0 = P
|
|
853
853
|
P = _projectP(G, f, Q)
|
|
854
854
|
P[s] = P0
|
|
@@ -929,18 +929,76 @@ def _subsetData(G, s, limit, order=None):
|
|
|
929
929
|
return packedGenotypes(X, G["samples"], mapped=mapped)
|
|
930
930
|
|
|
931
931
|
|
|
932
|
+
### Split packed samples without expanding calls or exceeding the copy budget
|
|
933
|
+
def _sampleData(G, s, idx, rest, limit):
|
|
934
|
+
a, b = (len(idx) + 3) // 4, (len(rest) + 3) // 4
|
|
935
|
+
m = len(s)
|
|
936
|
+
B, rows = nativeData(G), packedRows(G)
|
|
937
|
+
mapped = m * (a + b) > limit
|
|
938
|
+
if mapped:
|
|
939
|
+
r = max(1, min(m, defaults.SVD_CHUNK_MARKERS, limit // (a + b)))
|
|
940
|
+
A, C = np.empty((r, a), np.uint8), np.empty((r, b), np.uint8)
|
|
941
|
+
with (
|
|
942
|
+
tempfile.TemporaryFile(prefix=".fastmixture2-init-", buffering=0) as out,
|
|
943
|
+
tempfile.TemporaryFile(prefix=".fastmixture2-init-", buffering=0) as other,
|
|
944
|
+
):
|
|
945
|
+
for j in range(0, m, r):
|
|
946
|
+
e = min(j + r, m)
|
|
947
|
+
x, z = A[: e - j], C[: e - j]
|
|
948
|
+
shared.splitSamples(B, x, z, s[j:e], idx, rest, rows=rows)
|
|
949
|
+
x.tofile(out)
|
|
950
|
+
z.tofile(other)
|
|
951
|
+
del A, C, x, z
|
|
952
|
+
A = np.memmap(out, mode="r", dtype=np.uint8, shape=(m, a))
|
|
953
|
+
C = np.memmap(other, mode="r", dtype=np.uint8, shape=(m, b))
|
|
954
|
+
else:
|
|
955
|
+
A, C = np.empty((m, a), np.uint8), np.empty((m, b), np.uint8)
|
|
956
|
+
shared.splitSamples(B, A, C, s, idx, rest, rows=rows)
|
|
957
|
+
return packedGenotypes(A, len(idx), mapped), packedGenotypes(C, len(rest), mapped)
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
### Refine selected individuals and project remaining Q at fixed P
|
|
961
|
+
def _refineSamples(G, P, Q, s, fit, sub, limit, rng):
|
|
962
|
+
N, m = len(Q), len(s)
|
|
963
|
+
n = defaults.INITIALIZATION_SAMPLES
|
|
964
|
+
idx = np.sort(rng.choice(N, n, replace=False)).astype(np.uint32)
|
|
965
|
+
mask = np.ones(N, dtype=bool)
|
|
966
|
+
mask[idx] = False
|
|
967
|
+
rest = np.flatnonzero(mask).astype(np.uint32)
|
|
968
|
+
del mask
|
|
969
|
+
X, Z = _sampleData(G, s, idx, rest, limit)
|
|
970
|
+
nrm = np.full(N, 2.0 * m)
|
|
971
|
+
shared.countPackedRows(X["data"], nrm[:n], n)
|
|
972
|
+
shared.countPackedRows(Z["data"], nrm[n:], N - n)
|
|
973
|
+
if np.min(nrm) == 0:
|
|
974
|
+
return
|
|
975
|
+
q = np.ascontiguousarray(Q[idx])
|
|
976
|
+
res = fit(X, P, q, nrm[:n], None, sub)
|
|
977
|
+
Q[idx] = q
|
|
978
|
+
del X, q
|
|
979
|
+
q = np.ascontiguousarray(Q[rest])
|
|
980
|
+
proj = fit(Z, P, q, nrm[n:], None, sub, fixed=True)
|
|
981
|
+
Q[rest] = q
|
|
982
|
+
status = res["status"]
|
|
983
|
+
if status == "subset handoff" or proj["status"] == "numerical failure":
|
|
984
|
+
status = proj["status"]
|
|
985
|
+
return {
|
|
986
|
+
**res,
|
|
987
|
+
"like": res["like"] + proj["like"],
|
|
988
|
+
"elapsed": res["elapsed"] + proj["elapsed"],
|
|
989
|
+
"conv": res["conv"] and proj["conv"],
|
|
990
|
+
"status": status,
|
|
991
|
+
"samples": n,
|
|
992
|
+
"projection": proj,
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
|
|
932
996
|
### Refine subset P/Q with isolated fit settings
|
|
933
|
-
def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None):
|
|
997
|
+
def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None, rng=None):
|
|
934
998
|
from fastmixture2.functions import logInfo
|
|
935
999
|
|
|
936
1000
|
N, m = Q.shape[0], len(s)
|
|
937
1001
|
limit = defaults.SVD_WORKSPACE_BYTES if limit is None else limit
|
|
938
|
-
X = _subsetData(G, s, limit, order=order)
|
|
939
|
-
nrm = np.full(N, 2.0 * m)
|
|
940
|
-
if not isLikelihood(G):
|
|
941
|
-
shared.countPackedRows(X["data"], nrm, N)
|
|
942
|
-
if np.min(nrm) == 0:
|
|
943
|
-
return
|
|
944
1002
|
opt = {} if run is None else run
|
|
945
1003
|
sub = {
|
|
946
1004
|
"iter": opt.get("iter", 1000),
|
|
@@ -949,23 +1007,45 @@ def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None):
|
|
|
949
1007
|
"quiet": True,
|
|
950
1008
|
"gpu": opt.get("gpu", False),
|
|
951
1009
|
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
1010
|
+
if (
|
|
1011
|
+
rng is not None
|
|
1012
|
+
and order is None
|
|
1013
|
+
and not isLikelihood(G)
|
|
1014
|
+
and N > defaults.INITIALIZATION_SAMPLES
|
|
1015
|
+
):
|
|
1016
|
+
if "seed" in opt:
|
|
1017
|
+
# Keep sample selection independent of SVD/ALS draws
|
|
1018
|
+
rng = np.random.default_rng([opt["seed"], N, 0x53414D50, 0])
|
|
1019
|
+
res = _refineSamples(G, P, Q, s, fit, sub, limit, rng)
|
|
1020
|
+
if res is None:
|
|
1021
|
+
return
|
|
1022
|
+
else:
|
|
1023
|
+
X = _subsetData(G, s, limit, order=order)
|
|
1024
|
+
nrm = np.full(N, 2.0 * m)
|
|
1025
|
+
if not isLikelihood(G):
|
|
1026
|
+
shared.countPackedRows(X["data"], nrm, N)
|
|
1027
|
+
if np.min(nrm) == 0:
|
|
1028
|
+
return
|
|
1029
|
+
y = None
|
|
1030
|
+
dst = Q
|
|
1031
|
+
if order is not None:
|
|
1032
|
+
Q = np.ascontiguousarray(Q[order])
|
|
1033
|
+
if N > 1:
|
|
1034
|
+
sub["n_chunk"] = defaults.sqpSampleChunk(N - N // 2, Q.shape[1])
|
|
1035
|
+
y = Q[N - N // 2 :].copy()
|
|
1036
|
+
res = fit(X, P, Q, nrm, y, sub)
|
|
1037
|
+
if order is not None:
|
|
1038
|
+
dst[order] = Q
|
|
1039
|
+
del X
|
|
963
1040
|
if run is not None:
|
|
964
1041
|
run["init"] = {**res, "markers": m}
|
|
1042
|
+
msg = f"{res['iter']} SQP iterations"
|
|
1043
|
+
if "projection" in res:
|
|
1044
|
+
msg += (
|
|
1045
|
+
f" + {res['projection']['iter']} Q iterations | {res['samples']}/{N} joint samples"
|
|
1046
|
+
)
|
|
965
1047
|
logInfo(
|
|
966
|
-
run,
|
|
967
|
-
f"Subset refinement: {m} SNPs | {res['iter']} SQP iterations | "
|
|
968
|
-
f"{res['elapsed']:.1f} s | {res['status']}",
|
|
1048
|
+
run, f"Subset refinement: {m} SNPs | {msg} | {res['elapsed']:.1f} s | {res['status']}"
|
|
969
1049
|
)
|
|
970
1050
|
return res
|
|
971
1051
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastmixture2
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Biobank-scale ancestry estimation in unrelated individuals
|
|
5
5
|
Author-email: "J. Meisner" <meisnerucph@gmail.com>, "L. Thunegard" <lisathunegard@icloud.com>
|
|
6
6
|
License-Expression: GPL-3.0-only
|
|
@@ -61,8 +61,7 @@ python -m pip install .
|
|
|
61
61
|
```
|
|
62
62
|
|
|
63
63
|
Source builds need a C compiler with OpenMP. On macOS, install OpenMP with
|
|
64
|
-
`brew install libomp`.
|
|
65
|
-
analyses.
|
|
64
|
+
`brew install libomp`.
|
|
66
65
|
|
|
67
66
|
With Conda, the [CPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-cpu.yml)
|
|
68
67
|
and [GPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-gpu.yml)
|
|
@@ -153,17 +152,19 @@ CUDA keeps input data on the GPU when they fit and streams in blocks otherwise.
|
|
|
153
152
|
Small CPU/GPU differences can arise from floating-point arithmetic.
|
|
154
153
|
|
|
155
154
|
At K > 1, unsupervised fits use SVD/ALS on up to 50,000 genome-wide SNPs, with
|
|
156
|
-
subset refinement for larger panels.
|
|
155
|
+
subset refinement for larger panels. For called genotypes, joint subset refinement
|
|
156
|
+
uses up to 50,000 randomly selected individuals. The remaining Q rows are fitted
|
|
157
|
+
at fixed P before full-data fitting. All modes use safeguarded SQP/ZAL with EM/QN
|
|
157
158
|
rescue and float64 likelihood checks. CPU fitting uses float64. CUDA uses
|
|
158
159
|
mixed precision followed by float64 refinement.
|
|
159
160
|
|
|
160
161
|
Processing uses bounded tiles. Total memory still grows with panel size and K.
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
sufficient space.
|
|
162
|
+
Temporary files use `TMPDIR`. For large panels, use disk-backed scratch with
|
|
163
|
+
enough space.
|
|
164
164
|
|
|
165
165
|
The defaults are `--threads 1`, `--seed 42`, `--iter 1000` and `--tole 1e-10`.
|
|
166
|
-
`--threads` also controls CPU work during GPU fits.
|
|
166
|
+
`--threads` also controls CPU work during GPU fits. On HPC, use the allocated
|
|
167
|
+
CPU count.
|
|
167
168
|
The optimizer scales the tolerance by observed genotypes or informative
|
|
168
169
|
likelihood triplets. `--iter` and `--tole` apply to each refinement stage.
|
|
169
170
|
Run `fastmixture2 --help` for the full CLI.
|
|
@@ -316,22 +317,9 @@ For `--out cohort --K 5 --seed 42`:
|
|
|
316
317
|
| `cohort.K5.s42.Q_se` | Q standard errors when bootstrap is requested |
|
|
317
318
|
| `cohort.K5.s42.log` | Settings, likelihood, convergence and CV/bootstrap summaries |
|
|
318
319
|
|
|
319
|
-
Rows follow input order and columns correspond to components.
|
|
320
|
-
|
|
321
|
-
P
|
|
322
|
-
For Beagle, it is the frequency of allele2.
|
|
323
|
-
|
|
324
|
-
Matrices use ten decimal places. Logs retain full-precision likelihoods and
|
|
325
|
-
iteration counts, including ALS when used.
|
|
326
|
-
|
|
327
|
-
Outputs, checkpoints and caches use standard file permissions controlled by
|
|
328
|
-
your umask.
|
|
329
|
-
|
|
330
|
-
The log distinguishes convergence, iteration limits, stalled optimization and
|
|
331
|
-
numerical failure. Unsuccessful fits retain the best accepted parameters.
|
|
332
|
-
|
|
333
|
-
Parallel jobs should use distinct output prefixes. Build each likelihood cache
|
|
334
|
-
with one job, then reuse it across fits, or use a separate cache path per job.
|
|
320
|
+
Rows follow input order and columns correspond to components. `--write-info`
|
|
321
|
+
adds headers and IDs. `--no-freqs` omits P, which is also omitted in projection.
|
|
322
|
+
P is the frequency of BIM A1 for PLINK and allele2 for Beagle.
|
|
335
323
|
|
|
336
324
|
## Authors and license
|
|
337
325
|
|
|
@@ -38,6 +38,7 @@ def main():
|
|
|
38
38
|
"test_genotypes.GenotypesTest.test_packed_svd_decoder_covers_all_bytes_and_sample_tails",
|
|
39
39
|
"test_genotypes.GenotypesTest.test_packed_svd_decoder_preserves_simd_tails_unaligned_rows_and_zero_signs",
|
|
40
40
|
"test_genotypes.GenotypesTest.test_packed_float64_decoder_matches_float32_bits_and_tile_offsets",
|
|
41
|
+
"test_sample_subset.SampleStorageTest.test_all_codes_tails_and_partitioned_rows_match_reference",
|
|
41
42
|
"test_cpu_scaling.CpuScalingTest.test_full_likelihood_em_matches_extended_precision_posteriors",
|
|
42
43
|
"test_cpu_scaling.BlasTest.test_called_statistics_cover_packed_bytes_offsets_and_scored_tails",
|
|
43
44
|
"test_cpu_scaling.BlasTest.test_called_statistics_match_float64_algebra_at_clipped_bounds",
|
|
@@ -15,6 +15,62 @@ from fastmixture2 import defaults, gpu, kernels, shared
|
|
|
15
15
|
|
|
16
16
|
### Check allocation bounds and low-memory fallback without CUDA
|
|
17
17
|
class StreamedPlanTest(unittest.TestCase):
|
|
18
|
+
def test_full_q_span_reserves_both_buffers_and_keeps_the_stat_limit(self):
|
|
19
|
+
M, K, r, total, buf = 1_000_000, 32, 17, 16 << 30, 512 << 20
|
|
20
|
+
kp = K * (K + 1) // 2
|
|
21
|
+
scratch = 8 * r * ((K + 2) ** 2 + 2 * kp) + 16 * r * r
|
|
22
|
+
names = ("tile_weights", "tile_outer", "tile_solve")
|
|
23
|
+
for N in (126_000, 252_000):
|
|
24
|
+
need = 8 * N * (K + kp)
|
|
25
|
+
for gl in (False, True):
|
|
26
|
+
for fixed in (False, True):
|
|
27
|
+
for room, cap, supervision in (
|
|
28
|
+
(need + buf, defaults.GPU_SQP_FULL_STAT_BYTES, 0),
|
|
29
|
+
(need + buf - 1, defaults.GPU_SQP_FULL_STAT_BYTES, 0),
|
|
30
|
+
(need + buf, need - 1, 0),
|
|
31
|
+
(need + buf, defaults.GPU_SQP_FULL_STAT_BYTES, 9 * N),
|
|
32
|
+
):
|
|
33
|
+
reserve = gpu._optimizerBytes(M, N, K, fixed) + supervision
|
|
34
|
+
reserve += max(defaults.GPU_MEMORY_RESERVE_BYTES, total // 10)
|
|
35
|
+
free = [reserve + scratch + room]
|
|
36
|
+
|
|
37
|
+
def empty(shape, dtype):
|
|
38
|
+
size = int(np.prod(shape)) * np.dtype(dtype).itemsize
|
|
39
|
+
free[0] -= size
|
|
40
|
+
return SimpleNamespace(shape=shape, nbytes=size)
|
|
41
|
+
|
|
42
|
+
cp = SimpleNamespace(
|
|
43
|
+
empty=empty,
|
|
44
|
+
float32=np.float32,
|
|
45
|
+
float64=np.float64,
|
|
46
|
+
cuda=SimpleNamespace(
|
|
47
|
+
runtime=SimpleNamespace(memGetInfo=lambda: (free[0], total))
|
|
48
|
+
),
|
|
49
|
+
)
|
|
50
|
+
D = dict(
|
|
51
|
+
cp=cp,
|
|
52
|
+
M=M,
|
|
53
|
+
N=N,
|
|
54
|
+
K=K,
|
|
55
|
+
gl=gl,
|
|
56
|
+
fixed=fixed,
|
|
57
|
+
mode="streamed",
|
|
58
|
+
B=SimpleNamespace(nbytes=buf),
|
|
59
|
+
supervision_bytes=supervision,
|
|
60
|
+
)
|
|
61
|
+
with (
|
|
62
|
+
self.subTest(N=N, gl=gl, fixed=fixed, room=room, cap=cap),
|
|
63
|
+
patch.object(defaults, "GPU_SQP_FULL_STAT_BYTES", cap),
|
|
64
|
+
):
|
|
65
|
+
W = gpu._tiledWorkspace(D, dict.fromkeys(names), mixed=False, rows=r)
|
|
66
|
+
full = not supervision and need <= cap and room >= need + buf
|
|
67
|
+
self.assertEqual(W["qn"] == N, full)
|
|
68
|
+
stats = W["g"].nbytes + W["h"].nbytes
|
|
69
|
+
self.assertLessEqual(
|
|
70
|
+
stats, cap if full else defaults.GPU_SQP_STAT_BYTES
|
|
71
|
+
)
|
|
72
|
+
self.assertGreaterEqual(free[0], reserve + (buf if full else 0))
|
|
73
|
+
|
|
18
74
|
def test_fixed_q_products_use_only_spare_workspace(self):
|
|
19
75
|
def empty(shape, dtype):
|
|
20
76
|
size = int(np.prod(shape)) * np.dtype(dtype).itemsize
|
|
@@ -229,6 +285,69 @@ class StreamedPlanTest(unittest.TestCase):
|
|
|
229
285
|
|
|
230
286
|
### Check actual native and cuBLAS kernels with shards and tile tails
|
|
231
287
|
class StreamedCudaTest(unittest.TestCase):
|
|
288
|
+
def test_full_q_span_preserves_mixed_exact_and_projection_maps(self):
|
|
289
|
+
cp = loadCupy()
|
|
290
|
+
try:
|
|
291
|
+
for gl in (False, True):
|
|
292
|
+
for fixed in (False, True):
|
|
293
|
+
G, P, Q, _ = makeEmFixture("likelihood" if gl else "packed", 73, 53, 32)
|
|
294
|
+
G["mapped"] = True
|
|
295
|
+
G["data"].flags.writeable = False
|
|
296
|
+
G = kernels.foldView(G, 1, 3, 429)
|
|
297
|
+
before = G["data"].tobytes()
|
|
298
|
+
ref = {}
|
|
299
|
+
for full in (False, True):
|
|
300
|
+
with (
|
|
301
|
+
patch.object(gpu, "_tiledRows", return_value=17),
|
|
302
|
+
patch.object(defaults, "GPU_SQP_STAT_BYTES", 34 * 8 * (32 + 528)),
|
|
303
|
+
patch.object(
|
|
304
|
+
defaults, "GPU_SQP_FULL_STAT_BYTES", (1 << 30) if full else 0
|
|
305
|
+
),
|
|
306
|
+
):
|
|
307
|
+
build = gpu._likelihoodStreamedBackend if gl else gpu._streamedBackend
|
|
308
|
+
D = build(
|
|
309
|
+
cp,
|
|
310
|
+
np,
|
|
311
|
+
G,
|
|
312
|
+
P,
|
|
313
|
+
Q,
|
|
314
|
+
max_bytes=11 * G["data"][0].nbytes,
|
|
315
|
+
prefetch=True,
|
|
316
|
+
exact=True,
|
|
317
|
+
mixed=True,
|
|
318
|
+
fixed=fixed,
|
|
319
|
+
)
|
|
320
|
+
self.assertEqual(D["tiled"]["qn"], 53 if full else 34)
|
|
321
|
+
po, qo = cp.empty_like(D["P"]), cp.empty_like(D["Q"])
|
|
322
|
+
fn = (
|
|
323
|
+
D["sqp_q" if fixed else "sqp"] if gl else D["map_q" if fixed else "map"]
|
|
324
|
+
)
|
|
325
|
+
for mixed in (True, False):
|
|
326
|
+
with patch.object(
|
|
327
|
+
gpu, "_backendTiles", wraps=gpu._backendTiles
|
|
328
|
+
) as tiles:
|
|
329
|
+
if fixed:
|
|
330
|
+
fn(D, D["P"], D["Q"], qo, mixed)
|
|
331
|
+
cp.copyto(po, D["P"])
|
|
332
|
+
else:
|
|
333
|
+
fn(D, D["P"], D["Q"], po, qo, mixed)
|
|
334
|
+
p, q = cp.asnumpy(po), cp.asnumpy(qo)
|
|
335
|
+
with self.subTest(gl=gl, fixed=fixed, full=full, mixed=mixed):
|
|
336
|
+
self.assertEqual(
|
|
337
|
+
tiles.call_count, (1 if full else 2) + int(not fixed)
|
|
338
|
+
)
|
|
339
|
+
if full:
|
|
340
|
+
np.testing.assert_array_equal(p, ref[mixed][0])
|
|
341
|
+
np.testing.assert_array_equal(q, ref[mixed][1])
|
|
342
|
+
else:
|
|
343
|
+
ref[mixed] = p, q
|
|
344
|
+
assertValid(p, q)
|
|
345
|
+
self.assertEqual(G["data"].tobytes(), before)
|
|
346
|
+
del D, po, qo
|
|
347
|
+
gpu._releaseCuda(cp)
|
|
348
|
+
finally:
|
|
349
|
+
gpu._releaseCuda(cp)
|
|
350
|
+
|
|
232
351
|
def test_q_cast_reuse_preserves_shards_and_rotating_states(self):
|
|
233
352
|
cp = loadCupy()
|
|
234
353
|
try:
|
|
@@ -419,6 +538,7 @@ class StreamedCudaTest(unittest.TestCase):
|
|
|
419
538
|
self.subTest(K=K),
|
|
420
539
|
patch.object(gpu, "_tiledRows", return_value=17),
|
|
421
540
|
patch.object(defaults, "GPU_SQP_STAT_BYTES", 34 * 8 * (K + len(a))),
|
|
541
|
+
patch.object(defaults, "GPU_SQP_FULL_STAT_BYTES", 0),
|
|
422
542
|
):
|
|
423
543
|
D = gpu._likelihoodStreamedBackend(
|
|
424
544
|
cp,
|
|
@@ -497,6 +617,7 @@ class StreamedCudaTest(unittest.TestCase):
|
|
|
497
617
|
self.subTest(K=K),
|
|
498
618
|
patch.object(gpu, "_tiledRows", return_value=17),
|
|
499
619
|
patch.object(defaults, "GPU_SQP_STAT_BYTES", cap),
|
|
620
|
+
patch.object(defaults, "GPU_SQP_FULL_STAT_BYTES", 0),
|
|
500
621
|
):
|
|
501
622
|
D = gpu._streamedBackend(
|
|
502
623
|
cp,
|
|
@@ -549,6 +670,7 @@ class StreamedCudaTest(unittest.TestCase):
|
|
|
549
670
|
patch.object(
|
|
550
671
|
defaults, "GPU_SQP_STAT_BYTES", 34 * 8 * (K + K * (K + 1) // 2)
|
|
551
672
|
),
|
|
673
|
+
patch.object(defaults, "GPU_SQP_FULL_STAT_BYTES", 0),
|
|
552
674
|
):
|
|
553
675
|
build = gpu._likelihoodStreamedBackend if gl else gpu._streamedBackend
|
|
554
676
|
D = build(
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Check bounded sample splitting and CPU/CUDA subset projection."""
|
|
2
|
+
|
|
3
|
+
__author__ = "Jonas Meisner"
|
|
4
|
+
|
|
5
|
+
import tempfile
|
|
6
|
+
import unittest
|
|
7
|
+
import weakref
|
|
8
|
+
from functools import partial
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from unittest.mock import Mock, patch
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
from helpers import _unpack, assertValid, loadCupy, makeEmFixture, packGenotypes, sharedAls
|
|
14
|
+
|
|
15
|
+
from fastmixture2 import defaults, functions, gpu, kernels, plink, shared, utils
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
### Compare the initializer with independently packed sample panels
|
|
19
|
+
def checkCap(test, device, N, streamed=False):
|
|
20
|
+
M, m, K, n, seed = 139, 50, 5, 31, 42
|
|
21
|
+
G, _, _, _ = makeEmFixture("packed", M, N, K)
|
|
22
|
+
g = _unpack(G)
|
|
23
|
+
G["data"].flags.writeable = False
|
|
24
|
+
f = np.empty(M, np.float32)
|
|
25
|
+
kernels.estimateFreq(G, f)
|
|
26
|
+
G["freq"] = f
|
|
27
|
+
s = utils.initializationMarkers(M, m)
|
|
28
|
+
X = packGenotypes(g[s])
|
|
29
|
+
X["freq"] = f[s].copy()
|
|
30
|
+
draw = np.random.default_rng(np.random.SeedSequence([seed, N, 0x53414D50, 0]))
|
|
31
|
+
idx = np.sort(draw.choice(N, n, replace=False))
|
|
32
|
+
rest = np.setdiff1d(np.arange(N), idx)
|
|
33
|
+
module = gpu if device else functions
|
|
34
|
+
init = gpu.initializeUnsupervised if device else utils.initializeUnsupervised
|
|
35
|
+
fit = module.sqpRun
|
|
36
|
+
run = {"seed": seed, "iter": 3, "tole": 0, "quiet": True, "check": 1, "gpu": device}
|
|
37
|
+
cap = 3 * ((n + 3) // 4 + (N - n + 3) // 4)
|
|
38
|
+
seen = []
|
|
39
|
+
select = gpu._selectBackend
|
|
40
|
+
|
|
41
|
+
def backend(cp, np, G, P, Q, run, gl=False, fixed=False, y=None):
|
|
42
|
+
if not streamed:
|
|
43
|
+
return select(cp, np, G, P, Q, run, gl=gl, fixed=fixed, y=y)
|
|
44
|
+
D = gpu._streamedBackend(
|
|
45
|
+
cp, np, G, P, Q, max_bytes=7 * G["data"].shape[1], exact=True, mixed=True, fixed=fixed
|
|
46
|
+
)
|
|
47
|
+
test.assertEqual(D["chunk"], 7)
|
|
48
|
+
return gpu._prepareOptimizer(D, y, fixed)
|
|
49
|
+
|
|
50
|
+
def tracked(X, P, Q, nrm, y, opt, fixed=False, subset=False):
|
|
51
|
+
test.assertTrue(subset)
|
|
52
|
+
test.assertNotIn("save", opt)
|
|
53
|
+
test.assertNotIn("off", opt)
|
|
54
|
+
test.assertNotIn("seed", opt)
|
|
55
|
+
test.assertIsNone(y)
|
|
56
|
+
if fixed:
|
|
57
|
+
test.assertIsNone(seen[0][2]())
|
|
58
|
+
np.testing.assert_array_equal(nrm, 2.0 * (_unpack(X) != 9).sum(axis=0))
|
|
59
|
+
before = P.copy()
|
|
60
|
+
res = fit(X, P, Q, nrm, y, opt, fixed=fixed, subset=subset)
|
|
61
|
+
if fixed:
|
|
62
|
+
np.testing.assert_array_equal(P, before)
|
|
63
|
+
seen.append((len(Q), fixed, weakref.ref(X["data"])))
|
|
64
|
+
return res
|
|
65
|
+
|
|
66
|
+
with (
|
|
67
|
+
patch.object(defaults, "INITIALIZATION_MARKERS", m),
|
|
68
|
+
patch.object(defaults, "INITIALIZATION_SAMPLES", n),
|
|
69
|
+
patch.object(defaults, "SVD_POWER_ITERATIONS", 1),
|
|
70
|
+
patch.object(defaults, "ALS_MAX_ITERATIONS", 3),
|
|
71
|
+
patch.object(defaults, "SVD_WORKSPACE_BYTES", cap),
|
|
72
|
+
patch.object(defaults, "GPU_SVD_WORKSPACE_BYTES", cap),
|
|
73
|
+
patch.object(utils, "factorALS", side_effect=sharedAls()),
|
|
74
|
+
patch.object(gpu, "_selectBackend", new=backend),
|
|
75
|
+
):
|
|
76
|
+
p0, q0 = init(X, K, np.random.default_rng(seed))
|
|
77
|
+
for take, fixed in ((idx, False), (rest, True)):
|
|
78
|
+
sub = packGenotypes(g[s][:, take])
|
|
79
|
+
q = np.ascontiguousarray(q0[take])
|
|
80
|
+
nrm = 2.0 * (g[s][:, take] != 9).sum(axis=0)
|
|
81
|
+
fit(sub, p0, q, nrm, None, run.copy(), fixed=fixed, subset=True)
|
|
82
|
+
q0[take] = q
|
|
83
|
+
exact = kernels.loglikeMissing(packGenotypes(g[s]), p0, q0)
|
|
84
|
+
ps = p0
|
|
85
|
+
p0 = gpu.projectP(G, f, q0) if device else utils._projectP(G, f, q0)
|
|
86
|
+
p0[s] = ps
|
|
87
|
+
messages = []
|
|
88
|
+
run.update(
|
|
89
|
+
log=messages.append, save=Mock(side_effect=AssertionError("Saved subset")), off=9
|
|
90
|
+
)
|
|
91
|
+
with patch.object(module, "sqpRun", new=tracked):
|
|
92
|
+
p, q = init(G, K, np.random.default_rng(seed), run=run)
|
|
93
|
+
test.assertEqual([(x[0], x[1]) for x in seen], [(n, False), (N - n, True)])
|
|
94
|
+
test.assertTrue(all(ref() is None for _, _, ref in seen))
|
|
95
|
+
test.assertEqual(run["init"]["samples"], n)
|
|
96
|
+
test.assertEqual(run["init"]["markers"], m)
|
|
97
|
+
test.assertIn("projection", run["init"])
|
|
98
|
+
np.testing.assert_allclose(run["init"]["like"], exact, atol=1e-7, rtol=2e-13)
|
|
99
|
+
np.testing.assert_allclose(p, p0, atol=3e-6 if device else 1e-12, rtol=0)
|
|
100
|
+
np.testing.assert_allclose(q, q0, atol=3e-6 if device else 1e-12, rtol=0)
|
|
101
|
+
test.assertIn(f"{n}/{N} joint samples", messages[-1])
|
|
102
|
+
test.assertIn("Q iterations", messages[-1])
|
|
103
|
+
assertValid(p, q)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
### Preserve packed bytes and bound both output buffers
|
|
107
|
+
class SampleStorageTest(unittest.TestCase):
|
|
108
|
+
def test_all_codes_tails_and_partitioned_rows_match_reference(self):
|
|
109
|
+
rng = np.random.default_rng(791)
|
|
110
|
+
B = np.tile(np.arange(256, dtype=np.uint8), (7, 1))
|
|
111
|
+
B.flags.writeable = False
|
|
112
|
+
for N in (1021, 1022, 1023, 1024):
|
|
113
|
+
G = kernels.packedGenotypes(B, N)
|
|
114
|
+
g = _unpack(G)
|
|
115
|
+
s = np.array([6, 1, 4, 0], np.uint32)
|
|
116
|
+
for n in (1, 31, N - 1):
|
|
117
|
+
idx = np.sort(rng.choice(N, n, replace=False)).astype(np.uint32)
|
|
118
|
+
rest = np.setdiff1d(np.arange(N, dtype=np.uint32), idx)
|
|
119
|
+
row = (n + 3) // 4 + (N - n + 3) // 4
|
|
120
|
+
for parts in (False, True):
|
|
121
|
+
X = (
|
|
122
|
+
kernels.packedGenotypes(plink.packedFiles([B[:2], B[2:5], B[5:]]), N)
|
|
123
|
+
if parts
|
|
124
|
+
else G
|
|
125
|
+
)
|
|
126
|
+
for limit in (row, len(s) * row):
|
|
127
|
+
with self.subTest(N=N, n=n, parts=parts, limit=limit):
|
|
128
|
+
A, C = utils._sampleData(X, s, idx, rest, limit)
|
|
129
|
+
np.testing.assert_array_equal(
|
|
130
|
+
A["data"], packGenotypes(g[s][:, idx])["data"]
|
|
131
|
+
)
|
|
132
|
+
np.testing.assert_array_equal(
|
|
133
|
+
C["data"], packGenotypes(g[s][:, rest])["data"]
|
|
134
|
+
)
|
|
135
|
+
self.assertEqual(A["mapped"], limit < len(s) * row)
|
|
136
|
+
self.assertEqual(C["mapped"], A["mapped"])
|
|
137
|
+
|
|
138
|
+
def test_sample_indices_above_uint16_match_reference(self):
|
|
139
|
+
rng = np.random.default_rng(792)
|
|
140
|
+
for N in (65_539, 252_007):
|
|
141
|
+
g = rng.choice(np.array([0, 1, 2, 9], np.uint8), (3, N))
|
|
142
|
+
G = packGenotypes(g)
|
|
143
|
+
idx = np.sort(rng.choice(N, 50_000, replace=False)).astype(np.uint32)
|
|
144
|
+
rest = np.setdiff1d(np.arange(N, dtype=np.uint32), idx)
|
|
145
|
+
A, C = utils._sampleData(G, np.array([2, 0], np.uint32), idx, rest, 16 << 20)
|
|
146
|
+
np.testing.assert_array_equal(A["data"], packGenotypes(g[[2, 0]][:, idx])["data"])
|
|
147
|
+
np.testing.assert_array_equal(C["data"], packGenotypes(g[[2, 0]][:, rest])["data"])
|
|
148
|
+
|
|
149
|
+
def test_copy_budget_and_temporary_cleanup_on_success_and_failure(self):
|
|
150
|
+
G, _, _, _ = makeEmFixture("packed", 29, 87, 3)
|
|
151
|
+
idx, rest = np.arange(31, dtype=np.uint32), np.arange(31, 87, dtype=np.uint32)
|
|
152
|
+
s = np.arange(29, dtype=np.uint32)
|
|
153
|
+
limit = 3 * (8 + 14)
|
|
154
|
+
temporary, split = tempfile.TemporaryFile, shared.splitSamples
|
|
155
|
+
for fail in (False, True):
|
|
156
|
+
files, sizes = [], []
|
|
157
|
+
with tempfile.TemporaryDirectory() as dr:
|
|
158
|
+
|
|
159
|
+
def out(*args, **kw):
|
|
160
|
+
f = temporary(*args, dir=dr, **kw)
|
|
161
|
+
files.append(f)
|
|
162
|
+
return f
|
|
163
|
+
|
|
164
|
+
def copy(B, A, C, *args, **kw):
|
|
165
|
+
sizes.append(A.nbytes + C.nbytes)
|
|
166
|
+
self.assertLessEqual(sizes[-1], limit)
|
|
167
|
+
if fail and len(sizes) == 2:
|
|
168
|
+
raise OSError("sample split failed")
|
|
169
|
+
return split(B, A, C, *args, **kw)
|
|
170
|
+
|
|
171
|
+
with (
|
|
172
|
+
self.subTest(fail=fail),
|
|
173
|
+
patch.object(utils.tempfile, "TemporaryFile", side_effect=out),
|
|
174
|
+
patch.object(shared, "splitSamples", side_effect=copy),
|
|
175
|
+
):
|
|
176
|
+
if fail:
|
|
177
|
+
with self.assertRaisesRegex(OSError, "sample split failed"):
|
|
178
|
+
utils._sampleData(G, s, idx, rest, limit)
|
|
179
|
+
else:
|
|
180
|
+
A, C = utils._sampleData(G, s, idx, rest, limit)
|
|
181
|
+
refs = [weakref.ref(x["data"].base) for x in (A, C)]
|
|
182
|
+
del A, C
|
|
183
|
+
self.assertTrue(all(ref() is None for ref in refs))
|
|
184
|
+
self.assertTrue(all(f.closed for f in files))
|
|
185
|
+
self.assertEqual(list(Path(dr).iterdir()), [])
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
### Check the shared CPU path and its activation boundaries
|
|
189
|
+
class SampleSubsetTest(unittest.TestCase):
|
|
190
|
+
def test_initializer_matches_explicit_packed_pipeline(self):
|
|
191
|
+
checkCap(self, False, 87)
|
|
192
|
+
|
|
193
|
+
def test_cap_preserves_gl_restart_and_small_panel_paths(self):
|
|
194
|
+
n = 31
|
|
195
|
+
for kind, N, ordered, draw in (
|
|
196
|
+
("packed", n, False, True),
|
|
197
|
+
("likelihood", 53, False, True),
|
|
198
|
+
("packed", 53, True, True),
|
|
199
|
+
("packed", 53, False, False),
|
|
200
|
+
):
|
|
201
|
+
G, p, q, rng = makeEmFixture(kind, 139, N, 3)
|
|
202
|
+
fit = partial(
|
|
203
|
+
functions.likelihoodRun if kind == "likelihood" else functions.sqpRun, subset=True
|
|
204
|
+
)
|
|
205
|
+
with (
|
|
206
|
+
self.subTest(kind=kind, N=N, ordered=ordered, draw=draw),
|
|
207
|
+
patch.object(defaults, "INITIALIZATION_SAMPLES", n),
|
|
208
|
+
patch.object(utils, "_refineSamples", side_effect=AssertionError("Capped samples")),
|
|
209
|
+
):
|
|
210
|
+
utils._refineSubset(
|
|
211
|
+
G,
|
|
212
|
+
p[:50],
|
|
213
|
+
q,
|
|
214
|
+
np.arange(50, dtype=np.uint32),
|
|
215
|
+
{"iter": 1},
|
|
216
|
+
fit,
|
|
217
|
+
order=rng.permutation(N) if ordered else None,
|
|
218
|
+
rng=rng if draw else None,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def test_unobserved_samples_skip_both_fits_without_mutation(self):
|
|
222
|
+
G, p, q, rng = makeEmFixture("packed", 139, 53, 3)
|
|
223
|
+
g = _unpack(G)
|
|
224
|
+
draw = np.random.default_rng(np.random.SeedSequence([42, 53, 0x53414D50, 0]))
|
|
225
|
+
idx = draw.choice(53, 31, replace=False)
|
|
226
|
+
rest = np.setdiff1d(np.arange(53), idx)
|
|
227
|
+
for i in (idx[0], rest[0]):
|
|
228
|
+
x = g.copy()
|
|
229
|
+
x[:50, i] = 9
|
|
230
|
+
fit = Mock(side_effect=AssertionError("Unobserved sample"))
|
|
231
|
+
P, Q = p[:50].copy(), q.copy()
|
|
232
|
+
run = {"seed": 42}
|
|
233
|
+
with patch.object(defaults, "INITIALIZATION_SAMPLES", 31):
|
|
234
|
+
res = utils._refineSubset(
|
|
235
|
+
packGenotypes(x), P, Q, np.arange(50, dtype=np.uint32), run, fit, rng=rng
|
|
236
|
+
)
|
|
237
|
+
self.assertIsNone(res)
|
|
238
|
+
self.assertNotIn("init", run)
|
|
239
|
+
np.testing.assert_array_equal(P, p[:50])
|
|
240
|
+
np.testing.assert_array_equal(Q, q)
|
|
241
|
+
|
|
242
|
+
def test_optimizer_errors_release_both_mapped_sample_panels(self):
|
|
243
|
+
G, p, q, rng = makeEmFixture("packed", 139, 87, 3)
|
|
244
|
+
for fail in (1, 2):
|
|
245
|
+
refs = []
|
|
246
|
+
|
|
247
|
+
def fit(X, *args, **kw):
|
|
248
|
+
self.assertTrue(X["mapped"])
|
|
249
|
+
refs.append(weakref.ref(X["data"].base))
|
|
250
|
+
if len(refs) == fail:
|
|
251
|
+
raise OSError("sample fit failed")
|
|
252
|
+
return {
|
|
253
|
+
"like": 0.0,
|
|
254
|
+
"iter": 1,
|
|
255
|
+
"elapsed": 0.0,
|
|
256
|
+
"conv": False,
|
|
257
|
+
"status": "iteration limit",
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
with (
|
|
261
|
+
self.subTest(fail=fail),
|
|
262
|
+
patch.object(defaults, "INITIALIZATION_SAMPLES", 31),
|
|
263
|
+
self.assertRaisesRegex(OSError, "sample fit failed"),
|
|
264
|
+
):
|
|
265
|
+
utils._refineSubset(
|
|
266
|
+
G,
|
|
267
|
+
p[:50].copy(),
|
|
268
|
+
q.copy(),
|
|
269
|
+
np.arange(50, dtype=np.uint32),
|
|
270
|
+
{"seed": 42},
|
|
271
|
+
fit,
|
|
272
|
+
limit=66,
|
|
273
|
+
rng=rng,
|
|
274
|
+
)
|
|
275
|
+
self.assertTrue(all(ref() is None for ref in refs))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
### Check both CUDA SVD dispatches and streamed Q projection
|
|
279
|
+
class SampleSubsetCudaTest(unittest.TestCase):
|
|
280
|
+
def test_initializer_matches_explicit_pipeline_on_both_svd_backends(self):
|
|
281
|
+
cp = loadCupy()
|
|
282
|
+
try:
|
|
283
|
+
for N in (87, 269):
|
|
284
|
+
with self.subTest(N=N):
|
|
285
|
+
checkCap(self, True, N)
|
|
286
|
+
finally:
|
|
287
|
+
gpu._releaseCuda(cp)
|
|
288
|
+
|
|
289
|
+
def test_streamed_sample_projection_matches_reference(self):
|
|
290
|
+
cp = loadCupy()
|
|
291
|
+
try:
|
|
292
|
+
checkCap(self, True, 269, streamed=True)
|
|
293
|
+
finally:
|
|
294
|
+
gpu._releaseCuda(cp)
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "2.0.9"
|
|
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
|
|
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
|