gputls 2.1.1__tar.gz → 2.2.2__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 (34) hide show
  1. {gputls-2.1.1/src/gputls.egg-info → gputls-2.2.2}/PKG-INFO +4 -16
  2. {gputls-2.1.1 → gputls-2.2.2}/README.md +1 -1
  3. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/constants.py +2 -1
  4. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/core.py +296 -61
  5. gputls-2.2.2/src/gputls/kernels.cu +1574 -0
  6. gputls-2.2.2/src/gputls/screening.py +269 -0
  7. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/stats.py +37 -20
  8. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/version.py +1 -1
  9. gputls-2.2.2/src/gputls/workspace.py +57 -0
  10. {gputls-2.1.1 → gputls-2.2.2/src/gputls.egg-info}/PKG-INFO +4 -16
  11. {gputls-2.1.1 → gputls-2.2.2}/src/gputls.egg-info/SOURCES.txt +9 -1
  12. gputls-2.2.2/tests/test_bucket_sort.py +103 -0
  13. gputls-2.2.2/tests/test_candidate_screening.py +593 -0
  14. gputls-2.2.2/tests/test_patch_scan.py +39 -0
  15. gputls-2.2.2/tests/test_stats.py +76 -0
  16. gputls-2.2.2/tests/test_window_reuse.py +73 -0
  17. gputls-2.2.2/tests/test_workspace.py +135 -0
  18. gputls-2.1.1/src/gputls/kernels.cu +0 -369
  19. {gputls-2.1.1 → gputls-2.2.2}/LICENSE +0 -0
  20. {gputls-2.1.1 → gputls-2.2.2}/pyproject.toml +0 -0
  21. {gputls-2.1.1 → gputls-2.2.2}/setup.cfg +0 -0
  22. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/__init__.py +0 -0
  23. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/grid.py +0 -0
  24. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/helpers.py +0 -0
  25. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/interpolation.py +0 -0
  26. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/main.py +0 -0
  27. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/results.py +0 -0
  28. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/transit.py +0 -0
  29. {gputls-2.1.1 → gputls-2.2.2}/src/gputls/validate.py +0 -0
  30. {gputls-2.1.1 → gputls-2.2.2}/src/gputls.egg-info/dependency_links.txt +0 -0
  31. {gputls-2.1.1 → gputls-2.2.2}/src/gputls.egg-info/requires.txt +4 -4
  32. {gputls-2.1.1 → gputls-2.2.2}/src/gputls.egg-info/top_level.txt +0 -0
  33. {gputls-2.1.1 → gputls-2.2.2}/tests/test_gtls.py +0 -0
  34. {gputls-2.1.1 → gputls-2.2.2}/tests/test_tls_compare.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.1
2
2
  Name: gputls
3
- Version: 2.1.1
3
+ Version: 2.2.2
4
4
  Summary: GPU-accelerated Transit Least Squares (TLS) for periodic transit detection
5
5
  Author-email: Quanquan Hu <huqq1917@outlook.com>
6
6
  Maintainer-email: Quanquan Hu <huqq1917@outlook.com>
@@ -39,23 +39,11 @@ Classifier: Programming Language :: Python :: 3
39
39
  Classifier: Programming Language :: Python :: 3 :: Only
40
40
  Requires-Python: >=3.8
41
41
  Description-Content-Type: text/markdown
42
- License-File: LICENSE
43
- Requires-Dist: numpy
44
- Requires-Dist: numba
45
- Requires-Dist: tqdm
46
- Requires-Dist: batman-package
47
- Requires-Dist: setuptools
48
42
  Provides-Extra: cuda11
49
- Requires-Dist: cupy-cuda11x; extra == "cuda11"
50
43
  Provides-Extra: cuda12
51
- Requires-Dist: cupy-cuda12x[ctk]; extra == "cuda12"
52
44
  Provides-Extra: cuda13
53
- Requires-Dist: cupy-cuda13x[ctk]; extra == "cuda13"
54
45
  Provides-Extra: test
55
- Requires-Dist: pytest; extra == "test"
56
- Requires-Dist: astropy; extra == "test"
57
- Requires-Dist: lightkurve; extra == "test"
58
- Dynamic: license-file
46
+ License-File: LICENSE
59
47
 
60
48
  # GTLS: GPU Transit Least Squares
61
49
 
@@ -144,7 +132,7 @@ print(result.period, result.T0, result.duration, result.depth, result.SDE)
144
132
  | `duration_grid_step` | `1.1` | Multiplicative step of the duration grid |
145
133
  | `transit_depth_min` | `1e-5` | Minimum depth of a trial transit |
146
134
  | `transit_template` | `"default"` | `"default"`, `"grazing"` or `"box"` |
147
- | `T0_fit_margin` | `0.125` | Epoch step of the coarse search as a fraction of the duration (0 to 0.125; 0 tests every cadence) |
135
+ | `T0_fit_margin` | `0.01` | Epoch step of the coarse search as a fraction of the duration (0 to 0.125; 0 tests every cadence) |
148
136
  | `T0_refine_margin` | `0.01` | Epoch step when the strongest peaks are re-searched, as a fraction of the duration (0 to 0.125; 0 tests every cadence). 0.01 is the T0 resolution of TLS |
149
137
  | `GPUDeviceID` | `0` | CUDA device to run on |
150
138
  | `GPUDeviceIDs` | `None` | List of CUDA devices to split the search across (e.g. `[0, 1]`); overrides `GPUDeviceID`. Results are identical to a single-GPU run |
@@ -85,7 +85,7 @@ print(result.period, result.T0, result.duration, result.depth, result.SDE)
85
85
  | `duration_grid_step` | `1.1` | Multiplicative step of the duration grid |
86
86
  | `transit_depth_min` | `1e-5` | Minimum depth of a trial transit |
87
87
  | `transit_template` | `"default"` | `"default"`, `"grazing"` or `"box"` |
88
- | `T0_fit_margin` | `0.125` | Epoch step of the coarse search as a fraction of the duration (0 to 0.125; 0 tests every cadence) |
88
+ | `T0_fit_margin` | `0.01` | Epoch step of the coarse search as a fraction of the duration (0 to 0.125; 0 tests every cadence) |
89
89
  | `T0_refine_margin` | `0.01` | Epoch step when the strongest peaks are re-searched, as a fraction of the duration (0 to 0.125; 0 tests every cadence). 0.01 is the T0 resolution of TLS |
90
90
  | `GPUDeviceID` | `0` | CUDA device to run on |
91
91
  | `GPUDeviceIDs` | `None` | List of CUDA devices to split the search across (e.g. `[0, 1]`); overrides `GPUDeviceID`. Results are identical to a single-GPU run |
@@ -88,7 +88,8 @@ SDE_MEDIAN_KERNEL_SIZE = 30
88
88
 
89
89
  # Step between trial transit start points in the coarse period search, as a fraction
90
90
  # of the transit duration (clipped to [0, 0.125]); 0 tests every cadence (slowest).
91
- T0_FIT_MARGIN = 0.125
91
+ # Both search stages default to a 1% duration step.
92
+ T0_FIT_MARGIN = 0.01
92
93
 
93
94
  # Step between trial transit start points when the best candidate periods are re-searched,
94
95
  # as a fraction of the transit duration (clipped to [0, 0.125]); 0 tests every cadence.
@@ -10,14 +10,23 @@ import tqdm
10
10
  from . import constants
11
11
  from .grid import duration_limit_masses
12
12
  from .helpers import transit_mask
13
+ from .screening import (certificates, MIN_WIDTH, SCREEN_TOLERANCES,
14
+ UNIFORM_PREFIX_STRIDE, GENERAL_PREFIX_STRIDE,
15
+ uniform_sparse_certificate, sparse_certificate, prefix_quantization)
13
16
  from .stats import all_transit_times, calcDurationDays, intransit_stats, snr_stats, spectra
17
+ from .workspace import (BatchWorkspace, LAYOUT_ALLOWANCE, bucket_count,
18
+ bytes_per_period as workspace_bytes_per_period)
14
19
 
15
20
  KERNEL_SOURCE = Path(__file__).with_name("kernels.cu")
16
21
 
17
22
 
18
23
  def load_module():
19
24
  """Compile the CUDA kernels."""
20
- return cp.RawModule(code=KERNEL_SOURCE.read_text())
25
+ # The extra FP64 bound pays off on A100-class devices; the 3090's 1:64 FP64
26
+ # rate showed no gain. Compile out the shortcut on those devices entirely.
27
+ ratio = cp.cuda.Device().attributes.get("SingleToDoublePrecisionPerfRatio", 64)
28
+ options = (f"-DGTLS_CHEAP_SCREEN_BOUNDS={int(ratio <= 2)}",)
29
+ return cp.RawModule(code=KERNEL_SOURCE.read_text(), options=options)
21
30
 
22
31
 
23
32
  def foldCPU(time, flux, dy, period):
@@ -59,7 +68,9 @@ def find_nearest_indices(a, b):
59
68
 
60
69
 
61
70
  EMPTY_KEY = 0xFFFFFFFFFFFFFFFF
62
- SCAN_THREADS = 512 # threads per row of the scan kernels
71
+ SCAN_THREADS = 512 # threads per row of the integer scan kernels
72
+ SCREEN_SCAN_THREADS = 32 # 16 samples per thread: a 512-point screening tile
73
+ SCREEN_THREADS = 32 # nearby starts share prefix cache lines across durations
63
74
  MAX_BATCH = 65535 # periods are the y dimension of the kernel grids
64
75
  BATCHES_MIN = 30 # the first pass is split into at least this many batches
65
76
  MEMORY_FRACTION = 0.9 # share of the free device memory used by one batch
@@ -75,7 +86,18 @@ def start_strides(widths, margin):
75
86
  return np.where(widths > skip, widths // skip, 1).astype(np.int32)
76
87
 
77
88
 
78
- WINDOW_LANES = (1, 2, 4, 8, 16, 32) # threads per window of the searchChi2_G* kernels
89
+ def screen_block_map(offsets, strides):
90
+ """Schedule contiguous candidate blocks by start time, retaining original IDs."""
91
+ counts = (np.diff(offsets) + SCREEN_THREADS - 1) // SCREEN_THREADS
92
+ duration = np.repeat(np.arange(len(strides), dtype=np.int32), counts)
93
+ item = np.concatenate([np.arange(left, right, SCREEN_THREADS, dtype=np.int32)
94
+ for left, right in zip(offsets[:-1], offsets[1:])])
95
+ start = (item - offsets[duration]) * strides[duration]
96
+ order = np.argsort(start, kind='stable')
97
+ return np.column_stack((duration[order], item[order])).astype(np.int32)
98
+
99
+
100
+ WINDOW_LANES = (1, 2, 4, 8, 16, 32) # threads per window of the searchChi2G* kernels
79
101
  LANE_STEP_BYTES = 64 # bytes of start stride per thread of a window, see lanes_per_window
80
102
  POINT_BYTES = 8 # bytes read per point by searchChi2 (float2 of w r and w)
81
103
 
@@ -131,6 +153,19 @@ def decode_keys(keys, base):
131
153
  class GPUSearch:
132
154
  """GPU state shared by all chi2 evaluations of one light curve."""
133
155
 
156
+ def window_standard_deviations(self, data, width):
157
+ """Reuse completed search buffers for the final pink-noise statistic."""
158
+ size = len(data)
159
+ count = size - width + 1
160
+ with cp.cuda.Device(self.tGPU.device.id):
161
+ source = self.workspace.view('scratch', (size,), cp.float64)
162
+ output = self.workspace.view('cumulative', (count,), cp.float64)
163
+ source.set(np.ascontiguousarray(data))
164
+ self.module.get_function('windowStd')(
165
+ ((count + 255) // 256,), (256,),
166
+ (source, output, np.int32(count), np.int32(width)))
167
+ return output.get()
168
+
134
169
  def __init__(self, module, t, y, dy, transit_depth_min, lc_arr, lc_cache_overview, T0_fit_margin,
135
170
  T0_refine_margin, R_star_min=constants.R_STAR_MIN, R_star_max=constants.R_STAR_MAX,
136
171
  M_star_min=constants.M_STAR_MIN, M_star_max=constants.M_STAR_MAX):
@@ -150,6 +185,7 @@ class GPUSearch:
150
185
  self.maxDuration = maxDuration
151
186
 
152
187
  self.tSize = len(t)
188
+ self.nBuckets = bucket_count(self.tSize)
153
189
  self.patchedDatasSize = int(self.tSize + maxDuration)
154
190
 
155
191
  self.tGPU = cp.asarray(t).astype(cp.float64)
@@ -161,13 +197,19 @@ class GPUSearch:
161
197
  self.transit_depth_min = np.float32(transit_depth_min)
162
198
  self.constant_residual = float(np.sum(((1.0 - y) / dy) ** 2))
163
199
 
164
- # chi2 without transit, sum of w r^2 as searchChi2 weights the points (patchWeighted):
200
+ # Rebuild from this call's dy; only the per-period permutation is repeated.
201
+ self.preparedGPU = cp.empty((self.tSize, 2), dtype=cp.float32)
202
+ module.get_function("prepareWeights")(
203
+ ((self.tSize + 255) // 256,), (256,),
204
+ (self.residualGPU, self.dyGPU, self.preparedGPU, np.int32(self.tSize)))
205
+
206
+ # chi2 without transit, sum of w r^2 as searchChi2 weights the points:
165
207
  # it does not depend on the order of the points, so it is the same for every period
166
208
  dy2 = cp.maximum(self.dyGPU * self.dyGPU, cp.float32(1e-10))
167
209
  weightedResidual = (cp.float32(1.0) / dy2) * self.residualGPU
168
210
  self.base = float(cp.sum(weightedResidual.astype(cp.float64) * self.residualGPU.astype(cp.float64)))
169
211
 
170
- # Fixed-point scale 2^E of the residual prefix sums (scanResidual): the largest E with
212
+ # Fixed-point scale 2^E of the residual prefix sums: the largest E with
171
213
  # patchedDatasSize * max|r| * 2^E < 2^62, so no prefix sum can overflow int64
172
214
  bound = self.patchedDatasSize * float(cp.max(cp.abs(self.residualGPU)))
173
215
  exponent = 62 - int(np.ceil(np.log2(bound))) if bound > 0 else 62
@@ -184,6 +226,79 @@ class GPUSearch:
184
226
  self.overshootGPU = cp.asarray(self.lc_cache_overview["overshoot"]).astype(cp.float32)
185
227
  self.widthsGPU = cp.asarray(durations).astype(cp.int32)
186
228
 
229
+ # Screening is useful for long templates and a sampled start grid. The final
230
+ # every-point fit and small curves retain the adjacent-window path.
231
+ self.screening = (self.tSize >= 8192 and self.maxWidth >= MIN_WIDTH
232
+ and min(T0_fit_margin, T0_refine_margin) > 0)
233
+ self.uniformWeight = None
234
+ self.screenPrefixStride = 1
235
+ self.screenQuantization = None
236
+ if self.screening:
237
+ max_z = float(cp.max(cp.abs(weightedResidual)))
238
+ max_w = float(cp.max(cp.float32(1) / dy2))
239
+ self.screening = bool(np.isfinite(max_z) and np.isfinite(max_w))
240
+ # First-time Numba compilation can retain its caller frame until GC.
241
+ # Drop temporary device arrays before entering that compiler.
242
+ del dy2, weightedResidual
243
+ if self.screening:
244
+ self.screenPrefixStride = GENERAL_PREFIX_STRIDE
245
+ # Check this call's actual FP32 weights, including the variance
246
+ # floor. No uniform-weight assumption survives across searches.
247
+ if bool(cp.all(self.preparedGPU[:, 1] == self.preparedGPU[0, 1])):
248
+ self.uniformWeight = np.float32(self.preparedGPU[0, 1].get())
249
+ self.screenPrefixStride = UNIFORM_PREFIX_STRIDE
250
+ stride = self.screenPrefixStride
251
+ certificateSize = (self.patchedDatasSize+stride-1)//stride*stride
252
+ if cp.cuda.Device().attributes.get("SingleToDoublePrecisionPerfRatio", 64) > 2:
253
+ self.screenQuantization = prefix_quantization(certificateSize, max_z, max_w)
254
+ point_error = None if self.screenQuantization is None else self.screenQuantization[2]
255
+ prefix_maxima = (np.array([max_z, max_w]) if point_error is None else
256
+ np.nextafter(np.array([max_z, max_w])+point_error, np.inf))
257
+ self.screenCertificates = []
258
+ for tolerance in SCREEN_TOLERANCES:
259
+ pos, coef, meta, mass_error = certificates(
260
+ signal, durations, max_z, max_w, certificateSize, tolerance, point_error)
261
+ if self.uniformWeight is not None:
262
+ pos, coef, meta = uniform_sparse_certificate(
263
+ pos, coef, meta, stride, certificateSize, prefix_maxima[0])
264
+ else:
265
+ pos, coef, meta = sparse_certificate(
266
+ pos, coef, meta, stride, certificateSize, *prefix_maxima)
267
+ self.screenCertificates.append((cp.asarray(pos), cp.asarray(coef),
268
+ cp.asarray(meta), *map(np.float64, mass_error)))
269
+ self.workspace = None
270
+ self.screenMapKey = None
271
+ self.screenMapGPU = None
272
+ self.screenBudgetsGPU = None
273
+ self.uniformSquareGPU = (cp.empty(len(self.durations), dtype=cp.float32)
274
+ if self.uniformWeight is not None else None)
275
+ self.screenPrefixBytes = 12 if self.uniformWeight is not None else 24
276
+ self.screenPrefixSize = ((self.patchedDatasSize+self.screenPrefixStride-1)//self.screenPrefixStride+1
277
+ if self.screenPrefixStride > 1 else self.patchedDatasSize)
278
+ self.weightedPointBytes = 4 if self.uniformWeight is not None else 8
279
+ self.maxScreenStarts = (int(np.sum(-(-self.tSize // start_strides(
280
+ self.durations, min(T0_fit_margin, T0_refine_margin))))) if self.screening else 0)
281
+
282
+ def close(self):
283
+ """Release device resources even if a compiler/debugger retains this object."""
284
+ self.workspace = None
285
+ if hasattr(self, 'screenCertificates'):
286
+ self.screenCertificates.clear()
287
+ for name, value in vars(self).items():
288
+ if isinstance(value, cp.ndarray):
289
+ setattr(self, name, None)
290
+
291
+ def reserve_workspace(self, capacity):
292
+ """Keep the largest batch allocation for the search, including short tail/refit calls."""
293
+ if self.workspace is None or self.workspace.capacity < capacity:
294
+ self.workspace = None
295
+ self.workspace = BatchWorkspace(capacity, self.tSize, self.patchedDatasSize,
296
+ self.maxScreenStarts, self.screening,
297
+ prefix_bytes=self.screenPrefixBytes,
298
+ weighted_bytes=self.weightedPointBytes,
299
+ prefix_points=self.screenPrefixSize)
300
+ return self.workspace
301
+
187
302
  def duration_mask(self, periods):
188
303
  """Boolean array (periods x durations) of physically plausible durations per period."""
189
304
  module = self.module
@@ -217,6 +332,10 @@ class GPUSearch:
217
332
  tSize = self.tSize
218
333
  patchedSize = self.patchedDatasSize
219
334
  nPeriods = len(periods)
335
+ workspace = self.reserve_workspace(nPeriods)
336
+ # Offsets use the allocated capacity; active views have tightly packed rows
337
+ # for the current (possibly shorter) batch, as expected by the CUDA kernels.
338
+ index_bytes = workspace.index_bytes
220
339
 
221
340
  durationsBool = cp.any(periodMaskGPU, axis=0).get()
222
341
  selected = np.flatnonzero(durationsBool).astype(np.int32)
@@ -227,70 +346,161 @@ class GPUSearch:
227
346
 
228
347
  # Phase fold and sort (bucket sort, equal to a stable argsort of the phases)
229
348
  inversePeriodsGPU = cp.asarray(1.0 / np.asarray(periods, dtype=np.float64))
230
- phasesGPU = cp.empty((nPeriods, tSize), dtype=cp.float64)
231
- countsGPU = cp.zeros((nPeriods, tSize), dtype=cp.int32)
349
+ phasesGPU = workspace.view('scratch', (nPeriods, tSize), cp.uint32, index_bytes)
350
+ nBuckets = self.nBuckets
351
+ countsGPU = workspace.view('scratch', (nPeriods, nBuckets), cp.int32, 2*index_bytes)
352
+ countsGPU.fill(0)
232
353
  grid = ((tSize + 255) // 256, nPeriods)
233
- module.get_function("foldBuckets")(
234
- grid, (256,), (self.tGPU, inversePeriodsGPU, phasesGPU, countsGPU, np.int32(tSize)))
235
- cursorGPU = cp.empty((nPeriods, tSize), dtype=cp.int32)
236
- module.get_function("scanCounts")((nPeriods,), (SCAN_THREADS,), (countsGPU, cursorGPU, np.int32(tSize)))
237
- sortIndexGPU = cp.empty((nPeriods, tSize), dtype=cp.int32)
238
- module.get_function("bucketScatter")(
239
- grid, (256,), (phasesGPU, cursorGPU, sortIndexGPU, np.int32(tSize)))
240
- module.get_function("sortBuckets")(
241
- grid, (256,), (phasesGPU, countsGPU, cursorGPU, sortIndexGPU, np.int32(tSize)))
354
+ module.get_function("foldBucketsPackedPhase")(
355
+ grid, (256,), (self.tGPU, inversePeriodsGPU, phasesGPU, countsGPU, np.int32(tSize), np.int32(nBuckets)))
356
+ cursorGPU = workspace.view('scratch', (nPeriods, nBuckets), cp.int32, workspace.cursor_offset)
357
+ module.get_function("scanCounts")((nPeriods,), (SCAN_THREADS,), (countsGPU, cursorGPU, np.int32(nBuckets)))
358
+ sortIndexGPU = workspace.view('scratch', (nPeriods, tSize), cp.int32)
359
+ module.get_function("bucketScatterPackedPhase")(
360
+ grid, (256,), (phasesGPU, self.tGPU, inversePeriodsGPU, cursorGPU, sortIndexGPU,
361
+ np.int32(tSize), np.int32(nBuckets)))
362
+ module.get_function("sortBucketsPackedPhase")(
363
+ ((nBuckets+255)//256, nPeriods), (256,),
364
+ (phasesGPU, self.tGPU, inversePeriodsGPU, countsGPU, cursorGPU, sortIndexGPU,
365
+ np.int32(tSize), np.int32(nBuckets)))
242
366
  del phasesGPU, countsGPU, cursorGPU
243
367
 
244
368
  # Folded data, extended by maxDuration points to handle transits at the phase edge
245
- residualGPU = cp.empty((nPeriods, patchedSize), dtype=cp.float32)
246
- weightedGPU = cp.empty((nPeriods, patchedSize, 2), dtype=cp.float32)
247
- module.get_function("patchWeighted")(
248
- ((patchedSize + 255) // 256, nPeriods), (256,),
249
- (sortIndexGPU, self.residualGPU, self.dyGPU, residualGPU, weightedGPU,
250
- np.int32(tSize), np.int32(patchedSize)))
369
+ packed = self.uniformWeight is not None
370
+ weightedGPU = workspace.view('weighted', (nPeriods, patchedSize, 1 if packed else 2), cp.float32)
371
+ cumResidualGPU = workspace.view('cumulative', (nPeriods, patchedSize), cp.int64)
372
+ patchThreads = min(1024, max(32, 1 << ((patchedSize+1)//2-1).bit_length()))
373
+ module.get_function("patchScanPacked" if packed else "patchScan")(
374
+ (nPeriods,), (patchThreads,),
375
+ (sortIndexGPU, self.preparedGPU, weightedGPU, cumResidualGPU,
376
+ self.fixedScale, np.int32(tSize), np.int32(patchedSize)))
251
377
  del sortIndexGPU
252
378
 
253
- # Fixed-point prefix sums of the residuals
254
- cumResidualGPU = cp.empty((nPeriods, patchedSize), dtype=cp.int64)
255
- module.get_function("scanResidual")(
256
- (nPeriods,), (SCAN_THREADS,),
257
- (residualGPU, cumResidualGPU, self.fixedScale, np.int32(patchedSize)))
258
- del residualGPU
259
-
260
- # One launch per run of durations sharing the same threads per window (the strides,
261
- # and so the lanes, grow with the duration)
379
+ # Adjacent windows share input loads for the longer windows. Group within each
380
+ # duration, so an incomplete group never consumes starts from the next duration.
262
381
  bestGPU = cp.full(nPeriods, EMPTY_KEY, dtype=cp.uint64)
263
382
  lanes = lanes_per_window(strides)
383
+ screening = self.screening and margin > 0
384
+ if not screening and not packed and np.any(lanes >= 8):
385
+ adjacent = np.where(lanes == 32, 4, np.where(lanes >= 8, 2, 1))
386
+ group_counts = (np.diff(offsets) + adjacent - 1) // adjacent
387
+ offsets = np.concatenate(([0], np.cumsum(group_counts)))
264
388
  selectedGPU = cp.asarray(selected)
265
389
  offsetsGPU = cp.asarray(offsets.astype(np.int32))
266
390
  stridesGPU = cp.asarray(strides)
391
+ if screening:
392
+ # Only geometry is reused, within this search. The latest map suffices
393
+ # for consecutive batches; weights and bounds are always input-dependent.
394
+ mapKey = (tuple(selected), tuple(strides))
395
+ lanesGPU = cp.asarray(lanes)
396
+ if mapKey != self.screenMapKey:
397
+ self.screenMapGPU = cp.asarray(screen_block_map(offsets, strides))
398
+ if self.screenBudgetsGPU is None:
399
+ self.screenBudgetsGPU = cp.empty((3*len(self.durations), 4), dtype=cp.float64)
400
+ module.get_function("prepareScreenBudgetsUniformSparse" if packed else "prepareScreenBudgetsSparse")(
401
+ ((len(selected)+63)//64,), (64,),
402
+ (self.widthsGPU, selectedGPU, lanesGPU, self.screenCertificates[0][2],
403
+ self.screenBudgetsGPU, np.int32(len(selected)), np.int32(len(self.durations))))
404
+ if self.uniformWeight is not None:
405
+ module.get_function("prepareUniformSquare")(
406
+ (len(selected),), (32,),
407
+ (self.signalGPU, self.widthsGPU, selectedGPU, lanesGPU,
408
+ np.int32(self.maxWidth), self.uniformWeight, self.uniformSquareGPU))
409
+ self.screenMapKey = mapKey
410
+ prefixGPU = workspace.view('scratch', (nPeriods, self.screenPrefixSize, self.screenPrefixBytes), cp.uint8)
411
+ prefixKernel = "scanScreeningUniformSparse" if packed else "scanScreeningSparse"
412
+ prefix_args = (weightedGPU, prefixGPU, np.int32(patchedSize))
413
+ if self.screenQuantization is not None:
414
+ prefixKernel = "scanScreeningUniformInteger" if packed else "scanScreeningInteger"
415
+ prefix_args += (*self.screenQuantization[0], *self.screenQuantization[1])
416
+ module.get_function(prefixKernel)(
417
+ (nPeriods,), (SCREEN_SCAN_THREADS,), prefix_args)
418
+ nBounds = int(offsets[-1])
419
+ lowerGPU = workspace.view('lower', (nPeriods, nBounds), cp.float32)
420
+ upperGPU = cp.full(nPeriods, EMPTY_KEY, dtype=cp.uint64)
421
+ if len(selected)*tSize < 2**32:
422
+ # Reuse the upper-bound buffer for the chosen original-grid
423
+ # location, then replace it with that candidate's exact delta.
424
+ module.get_function("seedScreenCandidates")(
425
+ (nPeriods,), (256,),
426
+ (upperGPU, cumResidualGPU, self.fixedInvScale, self.widthsGPU,
427
+ selectedGPU, offsetsGPU, stridesGPU, periodMaskGPU,
428
+ np.int32(len(selected)), np.int32(len(self.durations)),
429
+ np.int32(tSize), np.int32(patchedSize), self.transit_depth_min))
430
+ module.get_function("evaluateScreenSeedPacked" if packed else "evaluateScreenSeed")(
431
+ (nPeriods,), (32,),
432
+ (upperGPU, cumResidualGPU, self.fixedInvScale, weightedGPU,
433
+ self.signalGPU, self.overshootGPU, self.widthsGPU, selectedGPU,
434
+ lanesGPU, np.int32(tSize), np.int32(patchedSize), np.int32(self.maxWidth),
435
+ self.uniformWeight if packed else np.float32(0)))
436
+ screen_before = (lowerGPU, upperGPU, prefixGPU, cumResidualGPU, self.fixedInvScale,
437
+ self.overshootGPU, self.widthsGPU, selectedGPU, offsetsGPU, stridesGPU,
438
+ lanesGPU, periodMaskGPU)
439
+ screen_after = (np.int32(len(selected)), np.int32(len(self.durations)), np.int32(tSize),
440
+ np.int32(patchedSize), self.transit_depth_min)
441
+ # Tight certificates only visit survivors of the preceding pass. All
442
+ # passes reuse the same prefix and bound buffers; final FP32 evaluation
443
+ # and tie ordering are unchanged.
444
+ for level, certificate in enumerate(self.screenCertificates):
445
+ kernel = "refineCandidates" if level else "screenCandidates"
446
+ kernel += "UniformSparse" if self.uniformWeight is not None else "MappedSparse"
447
+ uniform_args = ((self.uniformSquareGPU, self.uniformWeight)
448
+ if self.uniformWeight is not None else ())
449
+ module.get_function(kernel)(
450
+ (len(self.screenMapGPU), nPeriods), (SCREEN_THREADS,),
451
+ screen_before + certificate + screen_after
452
+ + (self.screenMapGPU, self.screenBudgetsGPU) + uniform_args)
453
+ del prefixGPU
267
454
  yBegin = 0
268
455
  while yBegin < len(selected):
269
456
  G = int(lanes[yBegin])
270
457
  yEnd = yBegin + 1
271
458
  while yEnd < len(selected) and lanes[yEnd] == G:
272
459
  yEnd += 1
273
- nWindows = int(offsets[yEnd] - offsets[yBegin])
274
- module.get_function(f"searchChi2_G{G}")(
275
- ((nWindows * G + 255) // 256, nPeriods), (256,),
276
- (bestGPU, cumResidualGPU, self.fixedInvScale, weightedGPU, self.signalGPU, self.overshootGPU,
277
- self.widthsGPU, selectedGPU, offsetsGPU, stridesGPU, periodMaskGPU,
278
- np.int32(yBegin), np.int32(yEnd), np.int32(len(self.durations)),
279
- np.int32(tSize), np.int32(patchedSize), np.int32(self.maxWidth), self.transit_depth_min))
460
+ nGroups = int(offsets[yEnd] - offsets[yBegin])
461
+ kernel = (f"searchChi2ScreenedG{G}" if screening else
462
+ f"searchChi2AdjacentG{G}" if G >= 8 else f"searchChi2G{G}")
463
+ if packed:
464
+ kernel = f"searchChi2PackedScreenedG{G}" if screening else f"searchChi2PackedG{G}"
465
+ work_items = nGroups
466
+ compact_args = ()
467
+ # Prefix data are dead after screening. Reuse their arena for the
468
+ # surviving indices and row counts, retaining the original path if
469
+ # this layout does not fit or the candidate set is dense.
470
+ if screening and 4*nPeriods*(nGroups+1) <= workspace.regions['scratch'][1]:
471
+ candidatesGPU = workspace.view('scratch', (nPeriods, nGroups), cp.int32)
472
+ countsGPU = workspace.view('scratch', (nPeriods,), cp.int32, 4*nPeriods*nGroups)
473
+ countsGPU.fill(0)
474
+ module.get_function("compactCandidates")(
475
+ ((nGroups + 255)//256, nPeriods), (256,),
476
+ (lowerGPU, upperGPU, candidatesGPU, countsGPU, np.int32(offsets[yBegin]),
477
+ np.int32(offsets[yEnd]), np.int32(nBounds), np.int32(nGroups)))
478
+ survivors = int(cp.max(countsGPU))
479
+ if survivors*4 <= nGroups:
480
+ kernel = f"searchChi2{'Packed' if packed else ''}CompactedG{G}"
481
+ work_items = survivors
482
+ compact_args = (candidatesGPU, countsGPU, np.int32(nGroups))
483
+ if work_items:
484
+ module.get_function(kernel)(
485
+ ((work_items * G + 255) // 256, nPeriods), (256,),
486
+ (bestGPU, cumResidualGPU, self.fixedInvScale, weightedGPU, self.signalGPU, self.overshootGPU,
487
+ self.widthsGPU, selectedGPU, offsetsGPU, stridesGPU, periodMaskGPU,
488
+ np.int32(yBegin), np.int32(yEnd), np.int32(len(self.durations)),
489
+ np.int32(tSize), np.int32(patchedSize), np.int32(self.maxWidth), self.transit_depth_min)
490
+ + ((lowerGPU, upperGPU, np.int32(nBounds)) if screening else ()) + compact_args
491
+ + ((self.uniformWeight,) if packed else ()))
280
492
  yBegin = yEnd
281
493
  return bestGPU
282
494
 
283
495
  def chi2_batch(self, periods, size, refine):
284
- """Lowest chi2 of each period of one batch, padded to size periods.
496
+ """Lowest chi2 of each period of one batch, using its actual length.
285
497
 
286
498
  Each period is searched over its own plausible durations only, so results depend
287
499
  neither on the batching nor on the device evaluating each batch. A period without
288
500
  plausible duration gets the chi2 of the light curve without transit.
501
+ size is the planned batch capacity; the final batch need not fill it.
289
502
  """
290
503
  valid_range = len(periods)
291
- # Pad the last batch with its last period, so all batches have the same shape
292
- if valid_range < size:
293
- periods = np.append(periods, np.full(size - valid_range, periods[-1]))
294
504
 
295
505
  periodMaskGPU = self.duration_mask(periods)
296
506
  if not bool(periodMaskGPU.any()):
@@ -319,30 +529,34 @@ class MultiGPUSearch:
319
529
  return self.searches[0]
320
530
 
321
531
  def bytes_per_period(self):
322
- """Peak device memory of one period of a best_keys batch, in bytes.
532
+ """Persistent workspace plus small per-period masks, scalars and decoded results.
323
533
 
324
- Live arrays peak in scanResidual at 20 P + 16 (P = patchedDatasSize): residual (4 P),
325
- weighted (8 P), cumResidual (8 P) and periods (bounded by 16 bytes). The memory pool places residual
326
- inside the freed 8 N phase buffer of the sort and cannot return that buffer to the
327
- driver, so the device footprint is 8 N + 16 P + 16 (N = tSize), plus one byte per
328
- duration for the period mask of searchChi2. Independent of T0_fit_margin.
534
+ One allocation owns the workspace across all batches. Its stage aliases
535
+ are explicit, so pool splitting cannot change its physical footprint.
536
+ Layout padding is budgeted separately in batch_size.
329
537
  """
330
538
  s = self.primary
331
- return 8 * s.tSize + 16 * s.patchedDatasSize + len(s.durations) + 16
539
+ return (workspace_bytes_per_period(s.tSize, s.patchedDatasSize, s.maxScreenStarts, s.screening,
540
+ prefix_bytes=s.screenPrefixBytes,
541
+ weighted_bytes=s.weightedPointBytes,
542
+ prefix_points=s.screenPrefixSize)
543
+ + len(s.durations) + 128)
332
544
 
333
545
  @staticmethod
334
546
  def available_memory(device_id):
335
547
  """Free device memory, including blocks cached but unused by the CuPy memory pool."""
336
548
  with cp.cuda.Device(device_id):
337
549
  pool = cp.get_default_memory_pool()
338
- return cp.cuda.Device(device_id).mem_info[0] + pool.total_bytes() - pool.used_bytes()
550
+ free = cp.cuda.Device(device_id).mem_info[0] + pool.total_bytes() - pool.used_bytes()
551
+ limit = pool.get_limit()
552
+ return min(free, max(0, limit-pool.used_bytes())) if limit else free
339
553
 
340
554
  def batch_size(self, n_periods):
341
555
  """Periods per batch: at least BATCHES_MIN batches (progress bar and balance between
342
556
  devices), within the memory of the fullest device. Results do not depend on it."""
343
557
  free = min(self.available_memory(device_id) for device_id in self.device_ids)
344
- by_memory = int(MEMORY_FRACTION * free // self.bytes_per_period())
345
- if free < self.bytes_per_period():
558
+ by_memory = int((MEMORY_FRACTION * free - LAYOUT_ALLOWANCE) // self.bytes_per_period())
559
+ if free < self.bytes_per_period() + LAYOUT_ALLOWANCE:
346
560
  raise MemoryError(
347
561
  f"One period needs {self.bytes_per_period() / 2**20:.0f} MiB of GPU memory, "
348
562
  f"{free / 2**20:.0f} MiB are free")
@@ -351,8 +565,7 @@ class MultiGPUSearch:
351
565
  def chi2(self, periods, singleCalcPeriods, refine, pbar=None):
352
566
  """Lowest chi2 of each period, evaluated in batches of singleCalcPeriods periods."""
353
567
  periods = np.asarray(periods)
354
- # Short lists (the refinement passes) are padded to their own length, not to a full batch;
355
- # padding repeats the last period, so the searched durations are the same either way
568
+ # Bound the planned capacity for short lists such as the refinement passes.
356
569
  singleCalcPeriods = max(min(singleCalcPeriods, len(periods)), 1)
357
570
  chi2 = np.empty(len(periods), dtype=np.float32)
358
571
  batches = iter(range(0, len(periods), singleCalcPeriods))
@@ -360,13 +573,31 @@ class MultiGPUSearch:
360
573
 
361
574
  def worker(device_id, search):
362
575
  with cp.cuda.Device(device_id):
576
+ capacity = singleCalcPeriods
363
577
  while True:
364
578
  with lock:
365
579
  start_idx = next(batches, None)
366
580
  if start_idx is None:
367
581
  return
368
- end_idx = start_idx + singleCalcPeriods
369
- chi2[start_idx:end_idx] = search.chi2_batch(periods[start_idx:end_idx], singleCalcPeriods, refine)
582
+ end_idx = min(start_idx + singleCalcPeriods, len(periods))
583
+ cursor = start_idx
584
+ while cursor < end_idx:
585
+ stop = min(cursor+capacity, end_idx)
586
+ failed = False
587
+ try:
588
+ chi2[cursor:stop] = search.chi2_batch(periods[cursor:stop], capacity, refine)
589
+ except cp.cuda.memory.OutOfMemoryError:
590
+ if stop-cursor == 1:
591
+ raise
592
+ failed = True
593
+ if failed:
594
+ # Leave the except block before releasing storage: the
595
+ # exception traceback otherwise keeps failed arrays alive.
596
+ search.workspace = None
597
+ cp.get_default_memory_pool().free_all_blocks()
598
+ capacity = max(1, (stop-cursor)//2)
599
+ continue
600
+ cursor = stop
370
601
  if pbar is not None:
371
602
  with lock:
372
603
  pbar.update(1)
@@ -383,7 +614,8 @@ class MultiGPUSearch:
383
614
 
384
615
  def close(self):
385
616
  """Release the GPU arrays and return the cached memory to the driver."""
386
- self.searches = []
617
+ while self.searches:
618
+ self.searches.pop().close()
387
619
  for device_id in self.device_ids:
388
620
  with cp.cuda.Device(device_id):
389
621
  cp.get_default_memory_pool().free_all_blocks()
@@ -507,23 +739,25 @@ def search_single_period(search, period, t, y, dy):
507
739
 
508
740
  dataOutTransit = np.concatenate((bestFlux[0:bestRowT0], bestFlux[bestRowT0 + durationPointsNum:]))
509
741
 
510
- snrFit = transitDepth * (durationPointsNum ** 0.5) / np.std(dataOutTransit)
742
+ whiteNoise = np.std(dataOutTransit)
743
+ snrFit = transitDepth * (durationPointsNum ** 0.5) / whiteNoise
511
744
  DataCumsum = np.cumsum(dataOutTransit)
512
745
  DataSlideAvg = (DataCumsum[durationPointsNum:] - DataCumsum[:-durationPointsNum]) / durationPointsNum
513
746
  redNoise = np.std(DataSlideAvg)
514
747
 
515
748
  Tx = bestTime[bestRowT0]
516
- T0 = Tx - int((Tx - min(t)) / period) * period - period
749
+ minTime = min(t)
750
+ T0 = Tx - int((Tx - minTime) / period) * period - period
517
751
  transit_times = all_transit_times(T0, t, period)
518
752
 
519
753
  snrFitPink = transitDepth / (
520
- (np.std(dataOutTransit) ** 2 / (durationPointsNum)) + (redNoise ** 2 / (len(transit_times)))) ** 0.5
754
+ (whiteNoise ** 2 / (durationPointsNum)) + (redNoise ** 2 / (len(transit_times)))) ** 0.5
521
755
 
522
756
  transit_duration_in_days = calcDurationDays(t, period, T0, rawDuration)
523
757
 
524
758
  T0 = T0 + transit_duration_in_days / 2
525
759
  transit_times = transit_times + transit_duration_in_days / 2
526
- if T0 < min(t):
760
+ if T0 < minTime:
527
761
  T0 = T0 + period
528
762
 
529
763
  # SNR
@@ -538,6 +772,7 @@ def search_single_period(search, period, t, y, dy):
538
772
  transit_times=transit_times,
539
773
  transit_duration_in_days=transit_duration_in_days,
540
774
  per_transit_count=per_transit_count,
775
+ window_std=search.window_standard_deviations,
541
776
  )
542
777
 
543
778
  all_flux_intransit = np.concatenate([all_flux_intransit_odd, all_flux_intransit_even])