cangyeone commited on
Commit
afa5fd7
·
verified ·
1 Parent(s): a2e9d14

Upload scripts/run_picker_to_jsonl.py

Browse files
Files changed (1) hide show
  1. scripts/run_picker_to_jsonl.py +2219 -0
scripts/run_picker_to_jsonl.py ADDED
@@ -0,0 +1,2219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Memory-safe phase picking script for large HDF5 continuous waveform datasets.
5
+ Supports Mac/MPS, CUDA (single or multi-GPU), and CPU, with optional multi-process
6
+ DataLoader for parallel waveform prefetching.
7
+
8
+ Key design points:
9
+ 1. Resume skipping is pushed into HDF5WaveformDataset(skip_jsonl=...) so already
10
+ processed samples are filtered from the metadata index before __getitem__ reads
11
+ waveform arrays from HDF5.
12
+ 2. Segment raw data arrays are freed immediately after fill_segments_to_array to
13
+ avoid unbounded RSS growth on day-long waveforms (~100 MB/sample).
14
+ 3. Uses torch.inference_mode() and explicit deletion of large temporary tensors.
15
+ 4. MPS: torch.mps.empty_cache() called every sample; model reloaded periodically
16
+ (--reload_model_interval) to reset TorchScript allocator state.
17
+ 5. CUDA: non_blocking transfers, cuda.empty_cache every N samples; model reload
18
+ disabled by default (not needed for CUDA allocator).
19
+ 6. Multi-process DataLoader: uses 'spawn' context on Linux to avoid h5py + fork
20
+ deadlocks; each worker opens its own HDF5 handles lazily.
21
+
22
+ Recommended — Mac/MPS (restart loop to avoid MPS allocator accumulation):
23
+ # Each run processes --max_samples new samples then exits with code 75.
24
+ # The OS reclaims Metal + HDF5 allocator state on exit. --resume picks up
25
+ # where the previous run left off. When all samples are done the script
26
+ # exits with code 0 and the loop terminates naturally.
27
+ while true; do
28
+ python run_picker_to_jsonl.py \
29
+ --h5_input 'data/hdf5/continuous_waveform_usa_*.h5' \
30
+ --output_jsonl data/picks/output.jsonl \
31
+ --picker_model pickers/pnsn.v1.jit \
32
+ --polar_model pickers/polar.onnx \
33
+ --device mps --max_samples 200
34
+ [ $? -ne 75 ] && break
35
+ done
36
+
37
+ Recommended — CUDA with multi-process prefetch:
38
+ python run_picker_to_jsonl_mps_safe.py \
39
+ --h5_input 'data/hdf5/continuous_waveform_usa_*.h5' \
40
+ --output_jsonl data/picks/output.jsonl \
41
+ --picker_model pickers/pnsn.v1.jit \
42
+ --polar_model pickers/polar.onnx \
43
+ --device cuda \
44
+ --batch_size 4 \
45
+ --num_workers 4 \
46
+ --prefetch_factor 2 \
47
+ --multiprocessing_context spawn
48
+ """
49
+
50
+ import argparse
51
+ import datetime
52
+ import gc
53
+ import json
54
+ import platform
55
+ import signal
56
+ import sys
57
+ import time
58
+ import os
59
+ import heapq
60
+ from bisect import bisect_left
61
+ from pathlib import Path
62
+
63
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
64
+
65
+ # Disable HDF5 POSIX file locking before h5py is imported.
66
+ # h5py calls H5open() (which reads HDF5_USE_FILE_LOCKING) the moment the
67
+ # module is imported. Without this, h5py.File() can block indefinitely
68
+ # waiting to acquire a POSIX fcntl lock held by Spotlight, Time Machine,
69
+ # a crashed previous run, or an NFS server — with no timeout.
70
+ # Setting it here (read-only access) is safe; allow user override via env.
71
+ os.environ.setdefault("HDF5_USE_FILE_LOCKING", "FALSE")
72
+
73
+ import numpy as np
74
+ import torch
75
+ from torch.utils.data import DataLoader
76
+
77
+ try:
78
+ import onnxruntime as ort
79
+ except Exception:
80
+ ort = None
81
+
82
+ # Prefer the revised resume-aware loader. Keep a fallback name for compatibility.
83
+
84
+ from utils.hdf5_waveform_dataset import (
85
+ HDF5WaveformDataset,
86
+ waveform_collate_fn,
87
+ hdf5_worker_init_fn,
88
+ )
89
+
90
+ # orjson is 3-10× faster than stdlib json for serialising Python dicts.
91
+ # Fall back gracefully if it is not installed.
92
+ try:
93
+ import orjson as _orjson
94
+
95
+ def _json_dumps(obj):
96
+ return _orjson.dumps(obj).decode("utf-8")
97
+
98
+ except ImportError:
99
+ _orjson = None
100
+
101
+ def _json_dumps(obj):
102
+ return json.dumps(obj, ensure_ascii=False)
103
+
104
+
105
+ PHASE_ID_TO_NAME = {
106
+ 0: "Pg",
107
+ 1: "Sg",
108
+ 2: "Pn",
109
+ 3: "Sn",
110
+ 4: "P",
111
+ 5: "S",
112
+ }
113
+
114
+
115
+ def format_seconds(seconds):
116
+ seconds = float(seconds)
117
+ if seconds < 60:
118
+ return f"{seconds:.1f}s"
119
+ if seconds < 3600:
120
+ return f"{seconds / 60:.1f}min"
121
+ return f"{seconds / 3600:.2f}h"
122
+
123
+
124
+ def format_rate(num, seconds, suffix="/s"):
125
+ seconds = float(seconds)
126
+ if seconds <= 0:
127
+ return "inf" + suffix
128
+ return f"{float(num) / seconds:.2f}{suffix}"
129
+
130
+
131
+ def safe_shape_text(x):
132
+ try:
133
+ if torch.is_tensor(x):
134
+ return "x".join(str(v) for v in tuple(x.shape))
135
+ if hasattr(x, "shape"):
136
+ return "x".join(str(v) for v in tuple(x.shape))
137
+ except Exception:
138
+ pass
139
+ return "?"
140
+
141
+
142
+ def select_torch_device(device_name="auto"):
143
+ device_name = str(device_name).lower()
144
+
145
+ if device_name == "auto":
146
+ if torch.cuda.is_available():
147
+ return torch.device("cuda"), "cuda"
148
+ if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
149
+ return torch.device("mps"), "mps"
150
+ return torch.device("cpu"), "cpu"
151
+
152
+ if device_name == "cuda":
153
+ if torch.cuda.is_available():
154
+ return torch.device("cuda"), "cuda"
155
+ print("[WARN] CUDA requested but not available. Fallback to CPU.")
156
+ return torch.device("cpu"), "cpu"
157
+
158
+ if device_name == "mps":
159
+ if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
160
+ return torch.device("mps"), "mps"
161
+ print("[WARN] MPS requested but not available. Fallback to CPU.")
162
+ return torch.device("cpu"), "cpu"
163
+
164
+ return torch.device("cpu"), "cpu"
165
+
166
+
167
+ def sync_device(device_type):
168
+ if device_type == "cuda":
169
+ torch.cuda.synchronize()
170
+ elif device_type == "mps":
171
+ try:
172
+ torch.mps.synchronize()
173
+ except Exception:
174
+ pass
175
+
176
+
177
+ def empty_device_cache(device_type):
178
+ if device_type == "cuda":
179
+ torch.cuda.empty_cache()
180
+ elif device_type == "mps":
181
+ try:
182
+ torch.mps.empty_cache()
183
+ except Exception:
184
+ pass
185
+
186
+
187
+ def force_device_cleanup(device_type, do_gc=True):
188
+ """Conservative cleanup for CUDA/MPS/CPU."""
189
+ sync_device(device_type)
190
+ if do_gc:
191
+ gc.collect()
192
+ empty_device_cache(device_type)
193
+
194
+
195
+ # ── Per-sample timeout (SIGALRM, Unix/macOS only) ───────────────────────────
196
+ # On MPS, torch.mps.synchronize() and torch.mps.empty_cache() can hang
197
+ # indefinitely if the Metal command queue enters a bad state. A SIGALRM
198
+ # watchdog lets us escape the hang, write an error record, and continue.
199
+ # SIGALRM is only available on the main thread on Unix; on Windows it is
200
+ # silently disabled.
201
+
202
+ _SIGALRM_AVAILABLE = hasattr(signal, "SIGALRM")
203
+
204
+
205
+ class _SampleTimeout(Exception):
206
+ """Raised by SIGALRM when a single sample exceeds sample_timeout_sec."""
207
+
208
+
209
+ def _sample_timeout_handler(signum, frame):
210
+ raise _SampleTimeout("sample timed out (Metal / ONNX hang?)")
211
+
212
+
213
+ class _SampleTimer:
214
+ """Context manager that arms/disarms SIGALRM around one sample.
215
+
216
+ Usage::
217
+
218
+ with _SampleTimer(timeout_sec):
219
+ ... process one sample ...
220
+
221
+ On timeout, _SampleTimeout is raised in the SIGALRM handler, which
222
+ propagates through the with-block. The caller should catch it, write an
223
+ error record, and continue to the next sample.
224
+
225
+ If SIGALRM is not available (Windows) or timeout_sec <= 0, this is a no-op.
226
+ """
227
+
228
+ __slots__ = ("_timeout",)
229
+
230
+ def __init__(self, timeout_sec: int):
231
+ self._timeout = timeout_sec if _SIGALRM_AVAILABLE and timeout_sec > 0 else 0
232
+
233
+ def __enter__(self):
234
+ if self._timeout > 0:
235
+ signal.signal(signal.SIGALRM, _sample_timeout_handler)
236
+ signal.alarm(self._timeout)
237
+ return self
238
+
239
+ def __exit__(self, exc_type, exc_val, exc_tb):
240
+ if self._timeout > 0:
241
+ signal.alarm(0) # cancel any pending alarm
242
+ signal.signal(signal.SIGALRM, signal.SIG_DFL)
243
+ return False # do not suppress exceptions
244
+
245
+
246
+ def get_process_rss_mb():
247
+ """Return current process RSS in MB if psutil is available."""
248
+ try:
249
+ import psutil
250
+ return psutil.Process(os.getpid()).memory_info().rss / (1024 ** 2)
251
+ except Exception:
252
+ return None
253
+
254
+
255
+ def get_device_memory_text(device_type):
256
+ """Return a short memory stats string for progress logging.
257
+
258
+ For CUDA: shows allocated / reserved MB from torch.cuda.
259
+ For MPS: falls back to process RSS (MPS uses unified memory, no per-device API).
260
+ For CPU: shows process RSS only.
261
+ """
262
+ parts = []
263
+
264
+ if device_type == "cuda":
265
+ try:
266
+ alloc = torch.cuda.memory_allocated() / (1024 ** 2)
267
+ reserved = torch.cuda.memory_reserved() / (1024 ** 2)
268
+ parts.append(f"cuda_alloc={alloc:.0f}MB reserved={reserved:.0f}MB")
269
+ except Exception:
270
+ pass
271
+
272
+ rss = get_process_rss_mb()
273
+ if rss is not None:
274
+ parts.append(f"rss={rss:.0f}MB")
275
+
276
+ return " | " + " | ".join(parts) if parts else ""
277
+
278
+
279
+ def get_dataloader_multiprocessing_context(num_workers, device_type, requested="auto"):
280
+ """Choose a safe multiprocessing start method for the DataLoader.
281
+
282
+ h5py is not fork-safe: accessing inherited file handles from multiple child
283
+ processes causes HDF5 library errors or silent corruption. On Linux the
284
+ default start method is 'fork', so we override it to 'spawn' automatically.
285
+ macOS defaults to 'spawn' (Python ≥ 3.8), so no override is needed there.
286
+
287
+ Args:
288
+ num_workers: DataLoader num_workers value.
289
+ device_type: 'cuda', 'mps', or 'cpu'.
290
+ requested: 'auto' lets this function decide; any other string is used as-is.
291
+
292
+ Returns:
293
+ A multiprocessing context string, or None (use PyTorch default).
294
+ """
295
+ if num_workers == 0:
296
+ return None # single-process mode; no context needed
297
+
298
+ if requested != "auto":
299
+ return requested # user override
300
+
301
+ system = platform.system()
302
+ if system == "Linux":
303
+ # Linux default is 'fork' which is not safe with h5py.
304
+ return "spawn"
305
+
306
+ if system == "Darwin":
307
+ # macOS Python ≥ 3.8 defaults to 'spawn', but be explicit so the
308
+ # log output and MPS+num_workers guidance are unambiguous.
309
+ return "spawn"
310
+
311
+ # Windows: platform default ('spawn') is already safe.
312
+ return None
313
+
314
+
315
+ def load_picker_model(picker_model, device, device_type):
316
+ picker = torch.jit.load(str(picker_model), map_location=device)
317
+ picker.eval()
318
+ picker.to(device)
319
+ sync_device(device_type)
320
+ return picker
321
+
322
+
323
+
324
+ def get_onnx_providers(device_type="cpu", requested="auto"):
325
+ """Select ONNX Runtime providers for picker / polarity inference.
326
+
327
+ device_type is the normalized runtime name from select_torch_device():
328
+ "cuda", "mps", or "cpu". ONNX Runtime does not have an MPS provider;
329
+ on Apple Silicon / macOS acceleration is exposed through CoreMLExecutionProvider.
330
+ """
331
+ if ort is None:
332
+ raise ImportError("onnxruntime is required for ONNX picker inference.")
333
+
334
+ available = list(ort.get_available_providers())
335
+
336
+ if requested and requested != "auto":
337
+ providers = [x.strip() for x in str(requested).split(",") if x.strip()]
338
+ providers = [p for p in providers if p in available]
339
+ if "CPUExecutionProvider" not in providers and "CPUExecutionProvider" in available:
340
+ providers.append("CPUExecutionProvider")
341
+ if not providers:
342
+ providers = ["CPUExecutionProvider"]
343
+ return providers
344
+
345
+ providers = []
346
+ if device_type == "cuda" and "CUDAExecutionProvider" in available:
347
+ providers.append("CUDAExecutionProvider")
348
+ elif device_type == "mps":
349
+ # ONNX Runtime acceleration on macOS is CoreML, not a literal MPS EP.
350
+ if "CoreMLExecutionProvider" in available:
351
+ providers.append("CoreMLExecutionProvider")
352
+
353
+ if "CPUExecutionProvider" in available:
354
+ providers.append("CPUExecutionProvider")
355
+
356
+ return providers or available or ["CPUExecutionProvider"]
357
+
358
+
359
+ def load_onnx_picker_model(picker_model, device_type="cpu", providers="auto"):
360
+ """Load ONNX picker model.
361
+
362
+ Expected model interface:
363
+ input: "wave" with shape [T, 3], float32
364
+ output: "prob" with shape [N, C], "time" with shape [N]
365
+ """
366
+ if ort is None:
367
+ raise ImportError("onnxruntime is required for ONNX picker inference.")
368
+
369
+ sess_options = ort.SessionOptions()
370
+ try:
371
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
372
+ except Exception:
373
+ pass
374
+
375
+ selected = get_onnx_providers(device_type=device_type, requested=providers)
376
+ print(f"[INFO] ONNX Runtime providers for picker model: {selected}")
377
+ return ort.InferenceSession(str(picker_model), sess_options=sess_options, providers=selected)
378
+
379
+
380
+ def infer_picker_backend_from_suffix(picker_model):
381
+ """Infer picker backend from model filename suffix.
382
+
383
+ .onnx -> ONNX Runtime + external heap-NMS
384
+ .jit/.torchscript/.pt/.pth -> TorchScript by default
385
+ """
386
+ suffix = Path(str(picker_model)).suffix.lower()
387
+ if suffix == ".onnx":
388
+ return "onnx"
389
+ if suffix in (".jit", ".torchscript", ".pt", ".pth"):
390
+ return "torchscript"
391
+ # Keep historical behavior for unknown suffixes.
392
+ return "torchscript"
393
+
394
+
395
+ def postprocess_picker_heap_nms(prob, time_values, prob_thresh=0.1, nms_win=200):
396
+ """Heap-based NMS for ONNX picker outputs.
397
+
398
+ prob: [N, C], where channel 0 is usually background and channels 1..C-1 are phases.
399
+ time_values: [N], sample indices corresponding to prob rows.
400
+
401
+ Returns ndarray [K, 3]: phase_id, sample_index, confidence.
402
+ phase_id follows the TorchScript wrapper convention: channel 1 -> 0, channel 2 -> 1, etc.
403
+ """
404
+ prob = np.asarray(prob, dtype=np.float32)
405
+ time_values = np.asarray(time_values, dtype=np.float32).reshape(-1)
406
+
407
+ if prob.ndim != 2:
408
+ raise ValueError(f"Expected ONNX prob with shape [N, C], got {prob.shape}")
409
+ if time_values.ndim != 1:
410
+ raise ValueError(f"Expected ONNX time with shape [N], got {time_values.shape}")
411
+ if prob.shape[0] != time_values.shape[0]:
412
+ raise ValueError(f"ONNX prob/time length mismatch: prob={prob.shape}, time={time_values.shape}")
413
+
414
+ output = []
415
+ n, c = prob.shape
416
+ nms_win = float(nms_win)
417
+
418
+ for itr in range(c - 1):
419
+ pc = prob[:, itr + 1]
420
+ mask = pc > float(prob_thresh)
421
+ if not np.any(mask):
422
+ continue
423
+
424
+ time_sel = time_values[mask]
425
+ score_sel = pc[mask]
426
+
427
+ # Heap sorted by descending score using negative score.
428
+ heap = [(-float(s), float(ts), i) for i, (s, ts) in enumerate(zip(score_sel, time_sel))]
429
+ heapq.heapify(heap)
430
+
431
+ accepted_times = [] # sorted by time
432
+ accepted_idx = []
433
+
434
+ while heap:
435
+ neg_s, ts, i = heapq.heappop(heap)
436
+ pos = bisect_left(accepted_times, ts)
437
+
438
+ conflict = False
439
+ if pos > 0 and abs(ts - accepted_times[pos - 1]) <= nms_win:
440
+ conflict = True
441
+ if pos < len(accepted_times) and abs(accepted_times[pos] - ts) <= nms_win:
442
+ conflict = True
443
+
444
+ if conflict:
445
+ continue
446
+
447
+ accepted_times.insert(pos, ts)
448
+ accepted_idx.append(i)
449
+
450
+ if not accepted_idx:
451
+ continue
452
+
453
+ p_time = time_sel[accepted_idx].astype(np.float32, copy=False)
454
+ p_prob = score_sel[accepted_idx].astype(np.float32, copy=False)
455
+ p_type = np.full(p_time.shape, itr, dtype=np.float32)
456
+ output.append(np.stack([p_type, p_time, p_prob], axis=1))
457
+
458
+ if not output:
459
+ return np.zeros((0, 3), dtype=np.float32)
460
+
461
+ return np.concatenate(output, axis=0).astype(np.float32, copy=False)
462
+
463
+
464
+ def run_onnx_picker_from_tensor(sess, x_cpu, prob_thresh=0.1, nms_win=200):
465
+ """Run ONNX picker and external heap-NMS postprocessing.
466
+
467
+ This replaces the slow TorchScript-internal NMS. The ONNX model should output
468
+ dense probability/time arrays, and this function returns the final [K, 3]
469
+ picks compatible with the rest of the JSONL writer.
470
+ """
471
+ if torch.is_tensor(x_cpu):
472
+ x_np = x_cpu.detach().cpu().numpy()
473
+ else:
474
+ x_np = np.asarray(x_cpu)
475
+
476
+ if x_np.ndim == 1:
477
+ x_np = x_np[:, None]
478
+ if x_np.shape[1] == 1:
479
+ x_np = np.repeat(x_np, 3, axis=1)
480
+ elif x_np.shape[1] > 3:
481
+ x_np = x_np[:, :3]
482
+ elif x_np.shape[1] < 3:
483
+ pad = np.zeros((x_np.shape[0], 3 - x_np.shape[1]), dtype=x_np.dtype)
484
+ x_np = np.concatenate([x_np, pad], axis=1)
485
+
486
+ x_np = np.ascontiguousarray(x_np.astype(np.float32, copy=False))
487
+
488
+ # Prefer named outputs, matching your ONNX example. If names differ, fall back to positional outputs.
489
+ try:
490
+ prob, time_values = sess.run(["prob", "time"], {"wave": x_np})
491
+ except Exception:
492
+ outputs = sess.run(None, {"wave": x_np})
493
+ if len(outputs) < 2:
494
+ raise ValueError("ONNX picker must return at least two outputs: prob and time")
495
+ prob, time_values = outputs[0], outputs[1]
496
+
497
+ picks = postprocess_picker_heap_nms(
498
+ prob,
499
+ time_values,
500
+ prob_thresh=prob_thresh,
501
+ nms_win=nms_win,
502
+ )
503
+ return picks, np.asarray(prob), np.asarray(time_values)
504
+
505
+
506
+ def to_jsonable(obj):
507
+ if torch.is_tensor(obj):
508
+ return {
509
+ "__tensor__": True,
510
+ "shape": list(obj.shape),
511
+ "dtype": str(obj.dtype),
512
+ }
513
+
514
+ if isinstance(obj, np.ndarray):
515
+ return {
516
+ "__ndarray__": True,
517
+ "shape": list(obj.shape),
518
+ "dtype": str(obj.dtype),
519
+ }
520
+
521
+ if isinstance(obj, (np.integer,)):
522
+ return int(obj)
523
+
524
+ if isinstance(obj, (np.floating,)):
525
+ value = float(obj)
526
+ if not np.isfinite(value):
527
+ return None
528
+ return value
529
+
530
+ if isinstance(obj, (np.bool_,)):
531
+ return bool(obj)
532
+
533
+ if isinstance(obj, dict):
534
+ return {str(k): to_jsonable(v) for k, v in obj.items()}
535
+
536
+ if isinstance(obj, (list, tuple)):
537
+ return [to_jsonable(v) for v in obj]
538
+
539
+ if isinstance(obj, bytes):
540
+ return obj.decode("utf-8", errors="ignore")
541
+
542
+ if isinstance(obj, (datetime.datetime, datetime.date)):
543
+ return obj.isoformat()
544
+
545
+ try:
546
+ json.dumps(obj)
547
+ return obj
548
+ except Exception:
549
+ return str(obj)
550
+
551
+
552
+ def parse_starttime_to_datetime(starttime):
553
+ if starttime is None or str(starttime).strip() == "":
554
+ return None
555
+
556
+ s = str(starttime).strip().replace("Z", "")
557
+
558
+ try:
559
+ return datetime.datetime.fromisoformat(s)
560
+ except Exception:
561
+ pass
562
+
563
+ for fmt in [
564
+ "%Y-%m-%dT%H:%M:%S.%f",
565
+ "%Y-%m-%dT%H:%M:%S",
566
+ "%Y-%m-%d %H:%M:%S.%f",
567
+ "%Y-%m-%d %H:%M:%S",
568
+ ]:
569
+ try:
570
+ return datetime.datetime.strptime(s, fmt)
571
+ except Exception:
572
+ continue
573
+
574
+ return None
575
+
576
+
577
+ def isoformat_z(dt):
578
+ if dt is None:
579
+ return None
580
+ return dt.isoformat(timespec="microseconds") + "Z"
581
+
582
+
583
+ def ensure_waveform_tensor_for_picker(waveform):
584
+ """Return CPU float32 tensor with shape [T, 3] without unnecessary NumPy copies."""
585
+ if torch.is_tensor(waveform):
586
+ x = waveform.detach()
587
+ if x.device.type != "cpu":
588
+ x = x.cpu()
589
+ if x.dtype != torch.float32:
590
+ x = x.to(dtype=torch.float32)
591
+ else:
592
+ x = torch.from_numpy(np.asarray(waveform, dtype=np.float32))
593
+
594
+ if x.ndim == 1:
595
+ x = x[:, None]
596
+
597
+ if x.shape[1] == 1:
598
+ x = x.repeat(1, 3)
599
+ elif x.shape[1] > 3:
600
+ x = x[:, :3]
601
+ elif x.shape[1] < 3:
602
+ pad = torch.zeros((x.shape[0], 3 - x.shape[1]), dtype=x.dtype)
603
+ x = torch.cat([x, pad], dim=1)
604
+
605
+ if not x.is_contiguous():
606
+ x = x.contiguous()
607
+
608
+ return x
609
+
610
+
611
+ def get_z_component_numpy(waveform):
612
+ """Return Z component as a NumPy view/copy with minimal conversion."""
613
+ x = ensure_waveform_tensor_for_picker(waveform)
614
+ z = x[:, 2]
615
+ return z.numpy()
616
+
617
+
618
+ def run_torchscript_picker_from_tensor(sess, x_cpu, device):
619
+ """Run picker using an already prepared CPU tensor [T, 3].
620
+
621
+ This avoids constructing the full waveform tensor twice in one sample. The
622
+ output is an ndarray with columns: phase_id, sample_index, confidence.
623
+ """
624
+ xt = None
625
+ y = None
626
+ out_cpu = None
627
+ try:
628
+ with torch.inference_mode():
629
+ # non_blocking=True overlaps CPU→GPU PCIe transfer with other CUDA work.
630
+ # For MPS (unified memory) and CPU it is a no-op but harmless.
631
+ xt = x_cpu.to(device=device, dtype=torch.float32,
632
+ non_blocking=(device.type == "cuda"))
633
+ y = sess(xt)
634
+
635
+ # Move output back to CPU *before* deleting the MPS tensors so the
636
+ # MPS allocator can reclaim the memory on the next empty_cache call.
637
+ if torch.is_tensor(y):
638
+ out_cpu = y.detach().cpu()
639
+ del y
640
+ y = None
641
+ out = out_cpu.numpy().copy() # copy so the tensor can be freed
642
+ del out_cpu
643
+ out_cpu = None
644
+ else:
645
+ out = np.asarray(y)
646
+
647
+ # Release the device-side input tensor now that inference is done.
648
+ del xt
649
+ xt = None
650
+
651
+ if out.ndim == 1:
652
+ out = out[None, :]
653
+
654
+ if out.shape[1] == 2:
655
+ conf = np.ones((out.shape[0], 1), dtype=np.float32)
656
+ out = np.concatenate([out, conf], axis=1)
657
+
658
+ if out.shape[1] < 3:
659
+ raise ValueError(f"Unexpected picker output shape: {out.shape}")
660
+
661
+ return out[:, :3].astype(np.float32, copy=False)
662
+
663
+ finally:
664
+ del xt
665
+ del y
666
+ del out_cpu
667
+
668
+
669
+ def run_torchscript_picker(sess, waveform, device):
670
+ """Backward-compatible wrapper."""
671
+ x_cpu = ensure_waveform_tensor_for_picker(waveform)
672
+ try:
673
+ return run_torchscript_picker_from_tensor(sess, x_cpu, device)
674
+ finally:
675
+ del x_cpu
676
+
677
+ def compute_pick_quality(z, sample_index, sr, snr_window_sec=2.0):
678
+ z = np.asarray(z, dtype=np.float32)
679
+ pidx = int(round(sample_index))
680
+
681
+ if len(z) == 0 or not np.isfinite(sr) or float(sr) <= 0:
682
+ return {
683
+ "snr": None,
684
+ "amplitude": None,
685
+ "pre_std": None,
686
+ "post_std": None,
687
+ "pre_abs_p95": None,
688
+ "post_abs_p95": None,
689
+ }
690
+
691
+ win = max(1, int(round(float(snr_window_sec) * float(sr))))
692
+
693
+ b0 = max(0, pidx - win)
694
+ b1 = max(0, pidx)
695
+ a0 = min(len(z), pidx)
696
+ a1 = min(len(z), pidx + win)
697
+
698
+ pre = z[b0:b1]
699
+ post = z[a0:a1]
700
+
701
+ if len(pre) == 0:
702
+ pre = np.ones(win, dtype=np.float32)
703
+ if len(post) == 0:
704
+ post = np.ones(win, dtype=np.float32)
705
+
706
+ pre_centered = pre - np.mean(pre)
707
+ post_centered = post - np.mean(post)
708
+
709
+ pre_std = float(np.std(pre_centered))
710
+ post_std = float(np.std(post_centered))
711
+ snr = post_std / (pre_std + 1e-6)
712
+
713
+ amp_end = min(len(z), pidx + int(round(1.0 * float(sr))))
714
+ amp_start = max(0, pidx - int(round(0.2 * float(sr))))
715
+ amp_win = z[amp_start:amp_end]
716
+
717
+ amplitude = float(np.max(np.abs(amp_win))) if len(amp_win) > 0 else None
718
+
719
+ return {
720
+ "snr": float(snr),
721
+ "amplitude": amplitude,
722
+ "pre_std": pre_std,
723
+ "post_std": post_std,
724
+ "pre_abs_p95": float(np.percentile(np.abs(pre_centered), 95)),
725
+ "post_abs_p95": float(np.percentile(np.abs(post_centered), 95)),
726
+ }
727
+
728
+
729
+ def load_polar_model(polar_model, device_name="cpu", providers="auto"):
730
+ if not polar_model:
731
+ return None
732
+
733
+ if ort is None:
734
+ raise ImportError("onnxruntime is required for polar model inference.")
735
+
736
+ selected = get_onnx_providers(device_type=device_name, requested=providers)
737
+ print(f"[INFO] ONNX Runtime providers for polarity model: {selected}")
738
+ return ort.InferenceSession(str(polar_model), providers=selected)
739
+
740
+
741
+ def run_polar_picker(polar_sess, z, sample_index):
742
+ """
743
+ Input: Z component, 1024 samples around Pg.
744
+ Output:
745
+ polarity: U/D/N
746
+ polarity probability
747
+ """
748
+ if polar_sess is None:
749
+ return "N", 0.0
750
+
751
+ z = np.asarray(z, dtype=np.float32)
752
+
753
+ if len(z) == 0:
754
+ return "N", 0.0
755
+
756
+ pidx = int(round(sample_index))
757
+
758
+ if pidx <= 512:
759
+ pidx = 512
760
+ if pidx >= len(z) - 512:
761
+ pidx = len(z) - 512
762
+
763
+ if pidx < 0:
764
+ return "N", 0.0
765
+
766
+ pdata = z[pidx - 512:pidx + 512]
767
+
768
+ if len(pdata) > 1024:
769
+ pdata = pdata[:1024]
770
+ if len(pdata) < 1024:
771
+ pdata = np.pad(pdata, (0, 1024 - len(pdata)))
772
+
773
+ pdata = np.ascontiguousarray(pdata.astype(np.float32, copy=False))
774
+ prob, = polar_sess.run(["prob"], {"wave": pdata})
775
+ prob = np.asarray(prob).reshape(-1)
776
+
777
+ polar_id = int(np.argmax(prob))
778
+ polar_prob = float(np.max(prob))
779
+
780
+ if polar_id == 0:
781
+ return "U", polar_prob
782
+ if polar_id == 1:
783
+ return "D", polar_prob
784
+
785
+ return "N", polar_prob
786
+
787
+
788
+ def get_station_info_compact(item):
789
+ info = item.get("station_info", {})
790
+
791
+ return {
792
+ "station_id": item.get("station_id", ""),
793
+ "network": info.get("network", ""),
794
+ "station": info.get("station", ""),
795
+ "location": info.get("location", ""),
796
+ "longitude": info.get("longitude", None),
797
+ "latitude": info.get("latitude", None),
798
+ "elevation": info.get("elevation", None),
799
+ "location_available": bool(info.get("location_available", False)),
800
+ "position_in_time_range": (
801
+ str(info.get("position_match_mode", ""))
802
+ == "strict_time_matched_network_station_only"
803
+ ),
804
+ "position_is_fallback": bool(info.get("position_is_fallback", False)),
805
+ }
806
+
807
+
808
+ def make_sample_key_from_item(item):
809
+ """Build the same key that make_sample_key_from_index_item would produce.
810
+
811
+ Must stay in sync with make_sample_key_from_index_item in
812
+ utils/hdf5_waveform_dataset.py so that no_pick / error sentinel records
813
+ have keys that match the dataset's resume filter.
814
+
815
+ Z-only replicated stations: __getitem__ stores ["EHZ","EHZ","EHZ"] in
816
+ item["channels"] but the index was built from the raw ["EHZ"] list.
817
+ Deduplicate here so the key matches.
818
+ """
819
+ channels = item.get("channels") or []
820
+ # Deduplicate for Z-only replicated stations so key matches the index.
821
+ if item.get("z_only_replicated", False):
822
+ seen: set = set()
823
+ channels = [ch for ch in channels if not (ch in seen or seen.add(ch))]
824
+ channels = ",".join(str(x) for x in channels)
825
+
826
+ return "|".join([
827
+ str(item.get("h5_file", "")),
828
+ str(item.get("year_id", "")),
829
+ str(item.get("day_id", "")),
830
+ str(item.get("station_id", "")),
831
+ str(item.get("channel_family", item.get("channel", ""))),
832
+ channels,
833
+ ])
834
+
835
+
836
+ def build_pick_record(
837
+ item,
838
+ z,
839
+ phase_id,
840
+ sample_index,
841
+ confidence,
842
+ polar_sess=None,
843
+ snr_window_sec=2.0,
844
+ ):
845
+ sr = float(item.get("sampling_rate", np.nan))
846
+ phase_id = int(phase_id)
847
+ sample_index = float(sample_index)
848
+ confidence = float(confidence)
849
+
850
+ phase_name = PHASE_ID_TO_NAME.get(phase_id, f"phase_{phase_id}")
851
+
852
+ if np.isfinite(sr) and sr > 0:
853
+ phase_relative_time = sample_index / sr
854
+ else:
855
+ phase_relative_time = None
856
+
857
+ start_dt = parse_starttime_to_datetime(item.get("starttime", ""))
858
+
859
+ if start_dt is not None and phase_relative_time is not None:
860
+ phase_dt = start_dt + datetime.timedelta(seconds=phase_relative_time)
861
+ else:
862
+ phase_dt = None
863
+
864
+ quality = compute_pick_quality(
865
+ z,
866
+ sample_index=sample_index,
867
+ sr=sr,
868
+ snr_window_sec=snr_window_sec,
869
+ )
870
+
871
+ polarity = "N"
872
+ polarity_prob = 0.0
873
+
874
+ if phase_name == "Pg":
875
+ polarity, polarity_prob = run_polar_picker(
876
+ polar_sess,
877
+ z,
878
+ sample_index=sample_index,
879
+ )
880
+
881
+ record = {
882
+ "record_type": "phase_pick",
883
+ "phase_id": phase_id,
884
+ "phase_name": phase_name,
885
+ "phase_prob": confidence,
886
+ "phase_sample": sample_index,
887
+ "phase_relative_time": phase_relative_time,
888
+ "phase_time": isoformat_z(phase_dt),
889
+ "polarity": polarity,
890
+ "polarity_prob": polarity_prob,
891
+ "polarity_available": bool(polar_sess is not None and phase_name == "Pg"),
892
+ "snr": quality.get("snr", None),
893
+ "amplitude": quality.get("amplitude", None),
894
+ "pre_std": quality.get("pre_std", None),
895
+ "post_std": quality.get("post_std", None),
896
+ "pre_abs_p95": quality.get("pre_abs_p95", None),
897
+ "post_abs_p95": quality.get("post_abs_p95", None),
898
+ "channels": item.get("channels", []),
899
+ "channel_family": item.get("channel_family", ""),
900
+ "component_order": item.get("component_order", ""),
901
+ "is_z_only": bool(item.get("is_z_only", False)),
902
+ "z_only_replicated": bool(item.get("z_only_replicated", False)),
903
+ "waveform_shape": list(item["waveform"].shape),
904
+ "sampling_rate": item.get("sampling_rate", None),
905
+ "original_sampling_rate": item.get("original_sampling_rate", None),
906
+ "target_sampling_rate": item.get("target_sampling_rate", None),
907
+ "resampled": bool(item.get("resampled", False)),
908
+ "h5_file": item.get("h5_file", ""),
909
+ "year_id": item.get("year_id", ""),
910
+ "day_id": item.get("day_id", ""),
911
+ # station_id MUST be a top-level field: load_finished_sample_keys rebuilds
912
+ # the resume key from h5_file|year_id|day_id|station_id|channel_family|channels
913
+ # using item.get("station_id", ""). If it is only inside station_info the
914
+ # scanner always sees "" and no record is ever marked as finished.
915
+ "station_id": item.get("station_id", ""),
916
+ "station_info": get_station_info_compact(item),
917
+ }
918
+
919
+ return to_jsonable(record)
920
+
921
+
922
+ def create_dataset_with_resume_filter(
923
+ h5_input,
924
+ output_jsonl,
925
+ resume,
926
+ allowed_families,
927
+ allowed_z_only_channels,
928
+ allow_z_only,
929
+ replicate_z_only,
930
+ target_sampling_rate,
931
+ include_segments_metadata,
932
+ keep_h5_open,
933
+ use_overlap_mask,
934
+ h5_rdcc_nbytes=8 * 1024 * 1024,
935
+ max_duration_sec=90000.0,
936
+ ):
937
+ kwargs = dict(
938
+ h5_file=h5_input,
939
+ mode="three",
940
+ allowed_families=allowed_families,
941
+ allowed_z_only_channels=allowed_z_only_channels,
942
+ allow_z_only=allow_z_only,
943
+ replicate_z_only=replicate_z_only,
944
+ target_sampling_rate=target_sampling_rate,
945
+ fill_value=0.0,
946
+ dtype=np.float32,
947
+ default_location="--",
948
+ )
949
+
950
+ # These options exist in the revised loader. If the old loader is imported by
951
+ # accident, the TypeError fallback keeps the script usable, but resume filtering
952
+ # will not be memory-safe until utils/hdf5_waveform_dataset_resume.py is used.
953
+ if resume:
954
+ kwargs["skip_jsonl"] = output_jsonl
955
+ kwargs["skip_record_type"] = "phase_pick"
956
+ kwargs["keep_h5_open"] = keep_h5_open
957
+ kwargs["include_segments_metadata"] = include_segments_metadata
958
+ kwargs["use_overlap_mask"] = use_overlap_mask
959
+ kwargs["h5_rdcc_nbytes"] = h5_rdcc_nbytes
960
+ kwargs["max_duration_sec"] = max_duration_sec
961
+
962
+ try:
963
+ return HDF5WaveformDataset(**kwargs), True
964
+ except TypeError as e:
965
+ print("[WARN] Resume-aware loader options were rejected by HDF5WaveformDataset.")
966
+ print(f"[WARN] Details: {e}")
967
+ print("[WARN] Falling back to the old loader API; skip will not happen before waveform loading.")
968
+ for key in [
969
+ "skip_jsonl",
970
+ "skip_record_type",
971
+ "keep_h5_open",
972
+ "include_segments_metadata",
973
+ "use_overlap_mask",
974
+ "h5_rdcc_nbytes",
975
+ "max_duration_sec",
976
+ ]:
977
+ kwargs.pop(key, None)
978
+ return HDF5WaveformDataset(**kwargs), False
979
+
980
+
981
+ def run_picker_to_jsonl(
982
+ h5_input,
983
+ output_jsonl,
984
+ picker_model,
985
+ polar_model=None,
986
+ picker_backend="auto",
987
+ onnx_providers="auto",
988
+ onnx_prob_thresh=0.1,
989
+ onnx_nms_win=200,
990
+ device_name="auto",
991
+ batch_size=1,
992
+ num_workers=0,
993
+ allowed_families=("HH", "BH", "EH", "HN"),
994
+ allowed_z_only_channels=("EHZ",),
995
+ allow_z_only=True,
996
+ replicate_z_only=True,
997
+ target_sampling_rate=100.0,
998
+ min_confidence=0.0,
999
+ snr_window_sec=2.0,
1000
+ progress_interval=100,
1001
+ resume=True,
1002
+ flush_interval=1000,
1003
+ gc_interval=2000,
1004
+ include_segments_metadata=False,
1005
+ keep_h5_open=True,
1006
+ use_overlap_mask=True,
1007
+ mps_empty_cache_interval=1,
1008
+ cuda_empty_cache_interval=200,
1009
+ reload_model_interval=-1,
1010
+ multiprocessing_context="auto",
1011
+ prefetch_factor=2,
1012
+ h5_rdcc_nbytes=8 * 1024 * 1024,
1013
+ max_samples=0,
1014
+ canonical_input_length=0,
1015
+ auto_restart=True,
1016
+ sample_timeout=120,
1017
+ max_picks_per_sample=0,
1018
+ max_duration_sec=90000.0,
1019
+ slow_load_threshold=10.0,
1020
+ slow_infer_threshold=10.0,
1021
+ slow_post_threshold=10.0,
1022
+ slow_total_threshold=30.0,
1023
+ flush_no_pick=False,
1024
+ ):
1025
+ t_all0 = time.perf_counter()
1026
+
1027
+ device, device_type = select_torch_device(device_name)
1028
+
1029
+ # Resolve reload_model_interval: -1 means auto-select per device.
1030
+ # MPS: reloading the model resets the TorchScript allocator state and
1031
+ # avoids unbounded RSS growth — but also triggers Metal kernel
1032
+ # recompilation on the very first inference after each reload, which
1033
+ # can take 30–300 s and blocks the GPU for that entire period.
1034
+ #
1035
+ # When max_samples > 0 the process is restarted via os.execv after
1036
+ # every N samples, which already resets all Metal state cleanly.
1037
+ # Within a single max_samples run there is no benefit to mid-run
1038
+ # reloading — it only adds compilation overhead.
1039
+ if reload_model_interval == -1:
1040
+ if device_type == "mps":
1041
+ if max_samples > 0:
1042
+ # os.execv handles memory reset; no mid-run reload needed.
1043
+ effective_reload_interval = 0
1044
+ else:
1045
+ # Unlimited run: reload periodically to prevent RSS growth,
1046
+ # but much less frequently than the old default of 50.
1047
+ effective_reload_interval = 500
1048
+ else:
1049
+ effective_reload_interval = 0
1050
+ else:
1051
+ effective_reload_interval = reload_model_interval
1052
+
1053
+ # Resolve canonical_input_length.
1054
+ # -1 is the sentinel from argparse; treat it the same as 0 (disabled).
1055
+ # The feature must be opted in explicitly via --canonical_input_length N
1056
+ # because many models (e.g. EQTransformer) use fixed internal windows that
1057
+ # break when the input tensor is padded to an unexpected length.
1058
+ if canonical_input_length <= 0:
1059
+ canonical_input_length = 0
1060
+
1061
+ # Resolve picker backend from suffix unless explicitly specified.
1062
+ picker_backend = str(picker_backend).lower().strip()
1063
+ if picker_backend == "auto":
1064
+ picker_backend = infer_picker_backend_from_suffix(picker_model)
1065
+ if picker_backend not in ("torchscript", "onnx"):
1066
+ raise ValueError(
1067
+ f"Unsupported picker_backend={picker_backend!r}. Use 'auto', 'torchscript', or 'onnx'."
1068
+ )
1069
+
1070
+ # Resolve DataLoader multiprocessing context.
1071
+ mp_context = get_dataloader_multiprocessing_context(
1072
+ num_workers, device_type, multiprocessing_context
1073
+ )
1074
+
1075
+ print("=" * 80)
1076
+ print("[INFO] Starting phase picking")
1077
+ print(f"[INFO] HDF5 input: {h5_input}")
1078
+ print(f"[INFO] Output JSONL: {output_jsonl}")
1079
+ print(f"[INFO] Picker model: {picker_model}")
1080
+ print(f"[INFO] Picker backend: {picker_backend}")
1081
+ if str(picker_backend).lower() == "onnx":
1082
+ print(f"[INFO] ONNX picker postprocess: prob_thresh={onnx_prob_thresh}, nms_win={onnx_nms_win}")
1083
+ print(f"[INFO] ONNX provider request: {onnx_providers}")
1084
+ print(f"[INFO] Polarity model: {polar_model if polar_model else 'disabled'}")
1085
+ print(f"[INFO] Requested device: {device_name}")
1086
+ print(f"[INFO] Using torch device: {device}")
1087
+ print(f"[INFO] Target sampling rate: {target_sampling_rate}")
1088
+ print(f"[INFO] Resume: {resume}")
1089
+ print(f"[INFO] batch_size={batch_size}, num_workers={num_workers}")
1090
+ if num_workers > 0:
1091
+ print(f"[INFO] multiprocessing_context={mp_context!r} prefetch_factor={prefetch_factor}")
1092
+ print(f"[INFO] mps_empty_cache_interval={mps_empty_cache_interval}")
1093
+ print(f"[INFO] cuda_empty_cache_interval={cuda_empty_cache_interval}")
1094
+ print(f"[INFO] reload_model_interval={effective_reload_interval}"
1095
+ f" (requested={reload_model_interval})")
1096
+ print(f"[INFO] h5_rdcc_nbytes={h5_rdcc_nbytes // (1024*1024)} MB per file handle (only current file kept open)")
1097
+ print(f"[INFO] max_duration_sec={max_duration_sec}")
1098
+ print(
1099
+ f"[INFO] slow thresholds: load>{slow_load_threshold}s, infer>{slow_infer_threshold}s, "
1100
+ f"post>{slow_post_threshold}s, total>{slow_total_threshold}s"
1101
+ )
1102
+ _mps_str = str(max_picks_per_sample) if max_picks_per_sample > 0 else "0 (no limit)"
1103
+ print(f"[INFO] max_picks_per_sample={_mps_str} flush_no_pick={flush_no_pick}")
1104
+ if canonical_input_length > 0:
1105
+ print(f"[INFO] canonical_input_length={canonical_input_length} samples "
1106
+ f"(all inputs padded/trimmed to this length to fix Metal pipeline cache growth)")
1107
+ if target_sampling_rate and target_sampling_rate > 0:
1108
+ full_day = int(86400 * target_sampling_rate)
1109
+ if canonical_input_length >= full_day:
1110
+ print(
1111
+ f"[WARN] canonical_input_length={canonical_input_length} is a full day "
1112
+ f"({full_day} @ {target_sampling_rate:.0f} Hz). Gappy or short station-days "
1113
+ f"will be zero-padded to this length. For sliding-window models such as "
1114
+ f"EQTransformer this multiplies the number of inference windows proportionally "
1115
+ f"and can make per-sample runtime 10–100× slower on days with many gaps. "
1116
+ f"Consider removing --canonical_input_length for EQTransformer."
1117
+ )
1118
+ else:
1119
+ print(f"[INFO] canonical_input_length=disabled")
1120
+ if target_sampling_rate and target_sampling_rate > 0:
1121
+ suggested = int(86400 * target_sampling_rate)
1122
+ # EQTransformer has an internal buffer of size 2*input_length; passing
1123
+ # exactly 2*input_length as an index overflows by 1. Use suggested-2
1124
+ # as the safe EQTransformer ceiling.
1125
+ suggested_eqt = suggested - 2
1126
+ if device_type == "mps":
1127
+ print(
1128
+ f"[WARN] MPS + canonical_input_length=disabled: every waveform with "
1129
+ f"a unique sample count triggers a NEW Metal shader compilation. "
1130
+ f"Python SIGALRM cannot interrupt Metal C-layer compilation, so the "
1131
+ f"script will hang indefinitely on each new shape.\n"
1132
+ f"[WARN] Fix: add --canonical_input_length {suggested_eqt} to your "
1133
+ f"command. This pads/trims all waveforms to one shape so Metal "
1134
+ f"compiles exactly once. ({suggested_eqt} = 86400 s × "
1135
+ f"{target_sampling_rate:.0f} Hz − 2, safe for EQTransformer.)"
1136
+ )
1137
+ else:
1138
+ print(
1139
+ f"[INFO] Tip: --canonical_input_length {suggested} "
1140
+ f"({int(86400)} s × {target_sampling_rate:.0f} Hz) fixes the Metal "
1141
+ f"kernel to one shape (MPS only). "
1142
+ f"For EQTransformer use {suggested_eqt} instead (avoids internal OOB)."
1143
+ )
1144
+ if _SIGALRM_AVAILABLE and sample_timeout > 0:
1145
+ print(f"[INFO] sample_timeout={sample_timeout}s "
1146
+ f"(SIGALRM watchdog; hangs exceeding this are written as error records)")
1147
+ else:
1148
+ reason = "disabled by --sample_timeout 0" if sample_timeout <= 0 else "SIGALRM not available on this platform"
1149
+ print(f"[INFO] sample_timeout=off ({reason})")
1150
+ print("=" * 80)
1151
+
1152
+ output_jsonl = Path(output_jsonl)
1153
+ output_jsonl.parent.mkdir(parents=True, exist_ok=True)
1154
+
1155
+ t0 = time.perf_counter()
1156
+ if picker_backend == "onnx":
1157
+ picker = load_onnx_picker_model(picker_model, device_type=device_type, providers=onnx_providers)
1158
+ else:
1159
+ picker = load_picker_model(picker_model, device, device_type)
1160
+ print(f"[INFO] Picker model loaded in {format_seconds(time.perf_counter() - t0)}")
1161
+
1162
+ t0 = time.perf_counter()
1163
+ polar_sess = load_polar_model(polar_model, device_name=device_type, providers=onnx_providers)
1164
+ print(f"[INFO] Polarity model loaded in {format_seconds(time.perf_counter() - t0)}")
1165
+
1166
+ t0 = time.perf_counter()
1167
+ dataset, resume_filter_is_loader_level = create_dataset_with_resume_filter(
1168
+ h5_input=h5_input,
1169
+ output_jsonl=output_jsonl,
1170
+ resume=resume,
1171
+ allowed_families=allowed_families,
1172
+ allowed_z_only_channels=allowed_z_only_channels,
1173
+ allow_z_only=allow_z_only,
1174
+ replicate_z_only=replicate_z_only,
1175
+ target_sampling_rate=target_sampling_rate,
1176
+ include_segments_metadata=include_segments_metadata,
1177
+ keep_h5_open=keep_h5_open,
1178
+ use_overlap_mask=use_overlap_mask,
1179
+ h5_rdcc_nbytes=h5_rdcc_nbytes,
1180
+ max_duration_sec=max_duration_sec,
1181
+ )
1182
+
1183
+ total_dataset_samples = len(dataset)
1184
+
1185
+ print(f"[INFO] Dataset indexed in {format_seconds(time.perf_counter() - t0)}")
1186
+ print(f"[INFO] Number of HDF5 files: {len(dataset.h5_files)}")
1187
+ if hasattr(dataset, "original_index_size"):
1188
+ print(f"[INFO] Original samples before resume filtering: {dataset.original_index_size}")
1189
+ print(f"[INFO] Samples filtered before waveform loading: {dataset.filtered_index_size}")
1190
+ print(f"[INFO] Number of samples to process now: {total_dataset_samples}")
1191
+ if max_samples > 0:
1192
+ restart_mode = "auto os.execv restart" if auto_restart else "exit code 75 (bash loop)"
1193
+ print(f"[INFO] max_samples={max_samples}: {restart_mode} after {max_samples} new samples.")
1194
+ elif device_type == "mps":
1195
+ print("[WARN] MPS detected with max_samples=0 (unlimited run).")
1196
+ print("[WARN] The Metal allocator and CoreML/ONNX Runtime accumulate process-level")
1197
+ print("[WARN] state that Python cannot free. RSS will grow ~20-45 MB/sample early on.")
1198
+ print("[WARN] Strongly recommended: add --max_samples 200 (auto_restart is on by default)")
1199
+ print("[WARN] so the script restarts itself transparently until all samples are done.")
1200
+ if hasattr(dataset, "skip_jsonl_stats") and dataset.skip_jsonl_stats:
1201
+ print(f"[INFO] Resume JSONL stats: {dataset.skip_jsonl_stats}")
1202
+ print(f"[INFO] Loader-level resume filtering active: {resume_filter_is_loader_level}")
1203
+
1204
+ if device_type == "mps":
1205
+ if num_workers == 0:
1206
+ print(
1207
+ "[INFO] Tip (MPS): --num_workers 1 --multiprocessing_context spawn "
1208
+ "enables a background CPU worker to prefetch+decode HDF5 waveforms "
1209
+ "while the GPU runs inference, which can significantly improve GPU "
1210
+ "utilisation. Workers never touch MPS; 'spawn' is macOS default."
1211
+ )
1212
+ else:
1213
+ # Workers run on CPU only (HDF5 decode). MPS state lives in the main
1214
+ # process. This is safe; just confirm spawn context is in use.
1215
+ if mp_context not in ("spawn", None):
1216
+ print(f"[WARN] MPS+num_workers: multiprocessing_context={mp_context!r}; "
1217
+ f"consider 'spawn' (macOS default) to avoid h5py issues.")
1218
+ else:
1219
+ print(f"[INFO] MPS+num_workers={num_workers}: workers do CPU-only HDF5 "
1220
+ f"decoding (safe). GPU inference runs in main process.")
1221
+ elif device_type == "cuda" and num_workers == 0:
1222
+ print("[INFO] Tip: --num_workers 4 (or more) enables parallel waveform "
1223
+ "prefetching on CUDA and can significantly improve throughput.")
1224
+
1225
+ loader_kwargs = dict(
1226
+ batch_size=batch_size,
1227
+ shuffle=False,
1228
+ num_workers=num_workers,
1229
+ collate_fn=waveform_collate_fn,
1230
+ # pin_memory speeds up CPU→GPU transfers on CUDA.
1231
+ pin_memory=(device_type == "cuda"),
1232
+ persistent_workers=(num_workers > 0),
1233
+ )
1234
+ if num_workers > 0:
1235
+ loader_kwargs["prefetch_factor"] = prefetch_factor
1236
+ loader_kwargs["multiprocessing_context"] = mp_context
1237
+ # hdf5_worker_init_fn resets inherited h5 handles when using 'fork'.
1238
+ # It is a no-op with 'spawn'/'forkserver' but safe to always pass.
1239
+ loader_kwargs["worker_init_fn"] = hdf5_worker_init_fn
1240
+
1241
+ loader = DataLoader(dataset, **loader_kwargs)
1242
+
1243
+ # ── Metal kernel pre-warmup (MPS only) ──────────────────────────────────
1244
+ # On the first run (or after a Metal cache clear), PyTorch/Metal must
1245
+ # JIT-compile GPU shaders for every unique input tensor shape encountered.
1246
+ # For a model like EQTransformer this can take 5��15 minutes with ZERO
1247
+ # console output, making the script appear completely hung.
1248
+ #
1249
+ # Running a dummy inference here triggers compilation *before* the main
1250
+ # loop so the user can see what's happening. No SIGALRM applies during
1251
+ # warmup; the per-sample timeout only guards the main loop.
1252
+ # Compiled kernels are cached to ~/Library/Caches/com.apple.metal/ and
1253
+ # are re-used automatically on subsequent runs (warmup then takes < 1 s).
1254
+ if device_type == "mps" and picker_backend == "torchscript":
1255
+ _sr = target_sampling_rate if (target_sampling_rate and target_sampling_rate > 0) else 100.0
1256
+ if canonical_input_length > 0:
1257
+ _warmup_len = canonical_input_length
1258
+ else:
1259
+ # canonical_input_length is disabled: warmup uses the full-day shape,
1260
+ # but real waveforms will differ → Metal recompiles per unique length.
1261
+ # SIGALRM cannot interrupt Metal C-layer compilation, so those will hang.
1262
+ # The warning above (at startup) already told the user to add the flag.
1263
+ _warmup_len = int(86400 * _sr) - 2 # EQTransformer-safe default
1264
+ print(
1265
+ f"[INFO] MPS: running Metal kernel pre-warmup "
1266
+ f"(dummy inference on a {_warmup_len:,}-sample zero tensor). "
1267
+ f"If this is the first run for this model, Metal shader compilation "
1268
+ f"may take 5–15 min — this is NORMAL and will only happen once. "
1269
+ f"Kernels are cached to ~/Library/Caches/com.apple.metal/.",
1270
+ flush=True,
1271
+ )
1272
+ _t_warmup = time.perf_counter()
1273
+ try:
1274
+ with torch.inference_mode():
1275
+ # Shape must match what run_torchscript_picker_from_tensor passes:
1276
+ # ensure_waveform_tensor_for_picker returns [T, 3] (2-D, not batched).
1277
+ _dummy_cpu = torch.zeros(_warmup_len, 3, dtype=torch.float32)
1278
+ _dummy_gpu = _dummy_cpu.to(device)
1279
+ del _dummy_cpu
1280
+ _warmup_out = picker(_dummy_gpu)
1281
+ del _dummy_gpu, _warmup_out
1282
+ torch.mps.synchronize()
1283
+ _warmup_elapsed = time.perf_counter() - _t_warmup
1284
+ if _warmup_elapsed >= 5.0:
1285
+ print(
1286
+ f"[INFO] Metal warmup complete in {format_seconds(_warmup_elapsed)}. "
1287
+ f"Kernels are now cached — main loop inference will be fast.",
1288
+ flush=True,
1289
+ )
1290
+ else:
1291
+ print(
1292
+ f"[INFO] Metal warmup complete in {format_seconds(_warmup_elapsed)} "
1293
+ f"(kernels were already cached).",
1294
+ flush=True,
1295
+ )
1296
+ except Exception as _warmup_exc:
1297
+ print(
1298
+ f"[WARN] Metal warmup failed: {_warmup_exc} "
1299
+ f"Continuing — first sample in the main loop may be slow.",
1300
+ flush=True,
1301
+ )
1302
+
1303
+ total_seen = 0
1304
+ total_processed = 0
1305
+ total_picks = 0
1306
+ total_errors = 0
1307
+ total_written_lines = 0
1308
+
1309
+ t_loop0 = time.perf_counter()
1310
+ t_last = t_loop0
1311
+
1312
+ open_mode = "a" if resume else "w"
1313
+ _max_samples_reached = False
1314
+
1315
+ print("[INFO] Entering main processing loop...", flush=True)
1316
+ try:
1317
+ with open(output_jsonl, open_mode, encoding="utf-8", buffering=1024 * 1024) as f:
1318
+ # ── Manual DataLoader iteration ────────────────────────────────
1319
+ # We use iter(loader)+next() instead of `for batch in loader` so
1320
+ # that we can arm the SIGALRM watchdog BEFORE the HDF5 read.
1321
+ # With num_workers=0, `next(loader_iter)` calls dataset.__getitem__
1322
+ # synchronously in the main thread. A blocked HDF5 syscall IS
1323
+ # interruptible by SIGALRM (POSIX signals interrupt IO syscalls),
1324
+ # so arming here covers both the waveform-load and inference phases.
1325
+ loader_iter = iter(loader)
1326
+ _loop_done = False
1327
+ while not _loop_done:
1328
+ # Declare per-sample state before arming the watchdog so the
1329
+ # outer except and finally can always reference these names.
1330
+ sample_key = ""
1331
+ item = None
1332
+ z = picks = x_cpu = waveform = original_length = None
1333
+ _hdf5_fetched = False
1334
+
1335
+ _timer = _SampleTimer(sample_timeout)
1336
+ _timer.__enter__()
1337
+ # Print a loading marker before every HDF5 read so slow reads
1338
+ # are never confused with a hung process.
1339
+ _load_t0 = time.perf_counter()
1340
+ #print(
1341
+ # f"[LOAD] {total_seen + 1}/{total_dataset_samples} "
1342
+ # f"(HDF5 read)...",
1343
+ # flush=True,
1344
+ #)
1345
+ try:
1346
+ # ── Fetch next batch (HDF5 waveform read) ─────────────
1347
+ # With num_workers=0 this runs in the main thread; the HDF5
1348
+ # C library retries EINTR internally, so SIGALRM cannot
1349
+ # reliably interrupt it. Use --num_workers 1 to move the
1350
+ # read into a subprocess; the main process then blocks on
1351
+ # queue.get() which IS Python-level and interruptible.
1352
+ try:
1353
+ batch = next(loader_iter)
1354
+ except StopIteration:
1355
+ _loop_done = True
1356
+ break # outer finally still runs to disarm timer
1357
+
1358
+ _load_elapsed = time.perf_counter() - _load_t0
1359
+ _hdf5_fetched = True
1360
+ if _load_elapsed >= slow_load_threshold:
1361
+ print(
1362
+ f"[SLOW_LOAD] next_batch={format_seconds(_load_elapsed)} "
1363
+ f"batch_size={len(batch)} num_workers={num_workers} "
1364
+ f"prefetch_factor={prefetch_factor}",
1365
+ flush=True,
1366
+ )
1367
+ else:
1368
+ #print(
1369
+ # f"[LOAD_DONE] next_batch={format_seconds(_load_elapsed)} "
1370
+ # f"batch_size={len(batch)}",
1371
+ # flush=True,
1372
+ #)
1373
+ pass
1374
+
1375
+ for item in batch:
1376
+ _sample_t0 = time.perf_counter()
1377
+ _prep_elapsed = 0.0
1378
+ _infer_elapsed = 0.0
1379
+ _post_elapsed = 0.0
1380
+ _pick_count_written = 0
1381
+ _pick_count_model = 0
1382
+ _pick_count_after_filter = 0
1383
+ _post_t0 = None
1384
+ sample_meta = {}
1385
+ total_seen += 1
1386
+ total_processed += 1
1387
+
1388
+ # Capture the sample key and lightweight metadata now, before
1389
+ # deleting waveform tensors. This is used for slow-sample logs
1390
+ # and error records.
1391
+ sample_key = make_sample_key_from_item(item)
1392
+ sample_meta = {
1393
+ "station_id": item.get("station_id", ""),
1394
+ "h5_file": item.get("h5_file", ""),
1395
+ "year_id": item.get("year_id", ""),
1396
+ "day_id": item.get("day_id", ""),
1397
+ "channels": item.get("channels", []),
1398
+ "channel_family": item.get("channel_family", ""),
1399
+ "sampling_rate": item.get("sampling_rate", None),
1400
+ "original_sampling_rate": item.get("original_sampling_rate", None),
1401
+ "starttime": item.get("starttime", ""),
1402
+ "endtime": item.get("endtime", ""),
1403
+ "npts": item.get("npts", None),
1404
+ }
1405
+
1406
+ try:
1407
+ # ── Per-sample inference ───────────────────────
1408
+ # NOTE: _timer is already armed above (before the
1409
+ # HDF5 read); do NOT create or re-arm it here.
1410
+ _prep_t0 = time.perf_counter()
1411
+ waveform = item["waveform"]
1412
+ # Build the full [T, 3] CPU tensor exactly once.
1413
+ # This avoids two large copies for day-long waveforms.
1414
+ x_cpu = ensure_waveform_tensor_for_picker(waveform)
1415
+ original_length = x_cpu.shape[0]
1416
+ _prep_elapsed = time.perf_counter() - _prep_t0
1417
+
1418
+ # ── Canonical-length padding ───────────────────
1419
+ # On MPS, TorchScript compiles and caches a separate
1420
+ # Metal pipeline for every unique input tensor shape.
1421
+ # Padding every input to one canonical length means
1422
+ # Metal compiles exactly ONE set of kernels and never
1423
+ # allocates another pipeline object.
1424
+ # Picks whose sample_index >= original_length are
1425
+ # filtered out below to suppress padding artefacts.
1426
+ if canonical_input_length > 0 and original_length != canonical_input_length:
1427
+ if original_length < canonical_input_length:
1428
+ pad = torch.zeros(
1429
+ canonical_input_length - original_length,
1430
+ x_cpu.shape[1],
1431
+ dtype=x_cpu.dtype,
1432
+ )
1433
+ x_cpu = torch.cat([x_cpu, pad], dim=0)
1434
+ else:
1435
+ x_cpu = x_cpu[:canonical_input_length]
1436
+
1437
+ z = x_cpu[:original_length, 2].numpy()
1438
+
1439
+ _t_infer = time.perf_counter()
1440
+ _onnx_prob_rows = 0
1441
+ _onnx_prob_shape = ""
1442
+ if picker_backend == "onnx":
1443
+ picks, _prob_raw, _time_raw = run_onnx_picker_from_tensor(
1444
+ picker,
1445
+ x_cpu,
1446
+ prob_thresh=onnx_prob_thresh,
1447
+ nms_win=onnx_nms_win,
1448
+ )
1449
+ _onnx_prob_rows = int(_prob_raw.shape[0]) if hasattr(_prob_raw, "shape") else 0
1450
+ _onnx_prob_shape = safe_shape_text(_prob_raw)
1451
+ # Release dense ONNX outputs immediately; they can be large for full-day traces.
1452
+ del _prob_raw, _time_raw
1453
+ else:
1454
+ picks = run_torchscript_picker_from_tensor(
1455
+ picker,
1456
+ x_cpu,
1457
+ device=device,
1458
+ )
1459
+ _infer_elapsed = time.perf_counter() - _t_infer
1460
+ _pick_count_model = int(len(picks)) if picks is not None else 0
1461
+ # Print one line per sample so slow HDF5 reads and slow
1462
+ # inferences are both immediately visible in the log.
1463
+ _extra = ""
1464
+ if picker_backend == "onnx":
1465
+ _extra = f" prob_shape={_onnx_prob_shape} prob_rows={_onnx_prob_rows}"
1466
+ #print(
1467
+ # f"[INFER] {total_processed}: "
1468
+ # f"{original_length:,}samp "
1469
+ # f"backend={picker_backend} "
1470
+ # f"prep={format_seconds(_prep_elapsed)} "
1471
+ # f"infer+postnms={format_seconds(_infer_elapsed)} "
1472
+ # f"model_picks={_pick_count_model}"
1473
+ # f"{_extra}",
1474
+ # flush=True,
1475
+ #)
1476
+
1477
+ # Remove any picks the model placed in the padded tail.
1478
+ if canonical_input_length > 0 and picks is not None and len(picks) > 0:
1479
+ picks = picks[picks[:, 1] < original_length]
1480
+
1481
+ except Exception as e:
1482
+ _timer.__exit__(type(e), e, None) # disarm SIGALRM
1483
+ total_errors += 1
1484
+ is_timeout = isinstance(e, _SampleTimeout)
1485
+ err_record = {
1486
+ "record_type": "error",
1487
+ "station_id": item.get("station_id", ""),
1488
+ "h5_file": item.get("h5_file", ""),
1489
+ "year_id": item.get("year_id", ""),
1490
+ "day_id": item.get("day_id", ""),
1491
+ "sample_key": sample_key,
1492
+ "error": str(e),
1493
+ }
1494
+ f.write(_json_dumps(to_jsonable(err_record)) + "\n")
1495
+ f.flush()
1496
+ total_written_lines += 1
1497
+ try:
1498
+ if item is not None and "waveform" in item:
1499
+ del item["waveform"]
1500
+ except Exception:
1501
+ pass
1502
+ picks = z = x_cpu = waveform = None
1503
+ item = None
1504
+ if is_timeout:
1505
+ # A timeout means a Metal / ONNX operation may still
1506
+ # be in-flight. Do NOT call synchronize() or
1507
+ # empty_cache() — they can themselves block on the
1508
+ # orphaned operation and cause a cascade hang.
1509
+ print(
1510
+ f"[WARN] Sample timed out after {sample_timeout}s "
1511
+ f"(skipping, Metal ops will drain at next restart): "
1512
+ f"{sample_key}",
1513
+ flush=True,
1514
+ )
1515
+ else:
1516
+ if device_type == "mps":
1517
+ force_device_cleanup(device_type, do_gc=False)
1518
+ continue
1519
+
1520
+ _picks_before = total_picks
1521
+ try:
1522
+ # Cap picks per station-day.
1523
+ _above = picks[picks[:, 2] >= min_confidence] if min_confidence > 0 else picks
1524
+ if max_picks_per_sample > 0 and len(_above) > max_picks_per_sample:
1525
+ _order = _above[:, 2].argsort()[::-1]
1526
+ _above = _above[_order[:max_picks_per_sample]]
1527
+ picks = _above
1528
+ _pick_count_after_filter = int(len(picks)) if picks is not None else 0
1529
+ _post_t0 = time.perf_counter()
1530
+
1531
+ for row in picks:
1532
+ phase_id = int(row[0])
1533
+ sample_index = float(row[1])
1534
+ confidence = float(row[2])
1535
+
1536
+ record = build_pick_record(
1537
+ item=item,
1538
+ z=z,
1539
+ phase_id=phase_id,
1540
+ sample_index=sample_index,
1541
+ confidence=confidence,
1542
+ polar_sess=polar_sess,
1543
+ snr_window_sec=snr_window_sec,
1544
+ )
1545
+
1546
+ f.write(_json_dumps(record) + "\n")
1547
+ total_picks += 1
1548
+ total_written_lines += 1
1549
+ _pick_count_written += 1
1550
+
1551
+ finally:
1552
+ if _post_t0 is not None:
1553
+ try:
1554
+ _post_elapsed = time.perf_counter() - _post_t0
1555
+ except Exception:
1556
+ _post_elapsed = 0.0
1557
+ # Disarm the SIGALRM watchdog on the normal success path.
1558
+ _timer.__exit__(None, None, None)
1559
+ picks = z = x_cpu = waveform = None
1560
+ try:
1561
+ del item["waveform"]
1562
+ except Exception:
1563
+ pass
1564
+ item = None
1565
+
1566
+ # ── No-pick sentinel ───────────────────────────────
1567
+ # If this station-day produced zero detections write a
1568
+ # lightweight record so the resume scanner marks it done.
1569
+ if total_picks == _picks_before:
1570
+ _no_pick = {"record_type": "no_pick", "sample_key": sample_key}
1571
+ f.write(_json_dumps(_no_pick) + "\n")
1572
+ if flush_no_pick:
1573
+ f.flush()
1574
+ total_written_lines += 1
1575
+
1576
+ _sample_elapsed = time.perf_counter() - _sample_t0
1577
+ if (
1578
+ _load_elapsed >= slow_load_threshold
1579
+ or _infer_elapsed >= slow_infer_threshold
1580
+ or _post_elapsed >= slow_post_threshold
1581
+ or _sample_elapsed >= slow_total_threshold
1582
+ ):
1583
+ _meta = dict(sample_meta)
1584
+ if _meta.get("npts") is None:
1585
+ _meta["npts"] = original_length
1586
+ print(
1587
+ "[SLOW_SAMPLE] "
1588
+ f"idx={total_processed} "
1589
+ f"load_batch={format_seconds(_load_elapsed)} "
1590
+ f"prep={format_seconds(_prep_elapsed)} "
1591
+ f"infer={format_seconds(_infer_elapsed)} "
1592
+ f"post_write={format_seconds(_post_elapsed)} "
1593
+ f"sample_total={format_seconds(_sample_elapsed)} "
1594
+ f"model_picks={_pick_count_model} "
1595
+ f"kept_picks={_pick_count_after_filter} "
1596
+ f"written_picks={_pick_count_written} "
1597
+ f"shape={original_length:,}x3 "
1598
+ f"meta={to_jsonable(_meta)}",
1599
+ flush=True,
1600
+ )
1601
+
1602
+ # ── Per-sample allocator cleanup ───────────────────
1603
+ if device_type == "mps" and mps_empty_cache_interval > 0 and total_processed % mps_empty_cache_interval == 0:
1604
+ force_device_cleanup(device_type, do_gc=True)
1605
+ elif device_type == "cuda" and cuda_empty_cache_interval > 0 and total_processed % cuda_empty_cache_interval == 0:
1606
+ force_device_cleanup(device_type, do_gc=False)
1607
+
1608
+ # ── Periodic h5py handle flush ─────────────────────
1609
+ if effective_reload_interval > 0 and total_processed % effective_reload_interval == 0:
1610
+ try:
1611
+ dataset.flush_h5_cache()
1612
+ except Exception:
1613
+ pass
1614
+
1615
+ # ── Periodic model reload ──────────────────────────
1616
+ if effective_reload_interval > 0 and total_processed % effective_reload_interval == 0:
1617
+ sync_device(device_type)
1618
+ del picker
1619
+ if polar_sess is not None:
1620
+ del polar_sess
1621
+ polar_sess = None
1622
+ gc.collect()
1623
+ empty_device_cache(device_type)
1624
+ if picker_backend == "onnx":
1625
+ picker = load_onnx_picker_model(picker_model, device_type=device_type, providers=onnx_providers)
1626
+ else:
1627
+ picker = load_picker_model(picker_model, device, device_type)
1628
+ if polar_model:
1629
+ polar_sess = load_polar_model(polar_model, device_name=device_type, providers=onnx_providers)
1630
+ gc.collect()
1631
+ empty_device_cache(device_type)
1632
+
1633
+ if flush_interval > 0 and total_processed % flush_interval == 0:
1634
+ f.flush()
1635
+
1636
+ if gc_interval > 0 and total_processed % gc_interval == 0 and device_type != "mps":
1637
+ gc.collect()
1638
+ empty_device_cache(device_type)
1639
+
1640
+ if (
1641
+ total_seen % max(1, progress_interval) == 0
1642
+ or total_seen == total_dataset_samples
1643
+ ):
1644
+ sync_device(device_type)
1645
+ now = time.perf_counter()
1646
+ elapsed = now - t_loop0
1647
+ speed = total_seen / max(elapsed, 1e-6)
1648
+
1649
+ if total_dataset_samples > 0:
1650
+ progress = total_seen / total_dataset_samples
1651
+ remaining = total_dataset_samples - total_seen
1652
+ eta = remaining / max(speed, 1e-6)
1653
+ else:
1654
+ progress = 0.0
1655
+ eta = 0.0
1656
+
1657
+ recent_elapsed = now - t_last
1658
+ t_last = now
1659
+
1660
+ mem_text = get_device_memory_text(device_type)
1661
+ print(
1662
+ "[PROGRESS] "
1663
+ f"{total_seen}/{total_dataset_samples} "
1664
+ f"({progress * 100:.2f}%) | "
1665
+ f"processed={total_processed} | "
1666
+ f"picks={total_picks} | "
1667
+ f"errors={total_errors} | "
1668
+ f"speed={speed:.3f} samples/s | "
1669
+ f"elapsed={format_seconds(elapsed)} | "
1670
+ f"eta={format_seconds(eta)} | "
1671
+ f"last_interval={format_seconds(recent_elapsed)}"
1672
+ f"{mem_text}"
1673
+ )
1674
+
1675
+ # ── max_samples early-exit ─────────────────────────
1676
+ if max_samples > 0 and total_processed >= max_samples:
1677
+ _max_samples_reached = True
1678
+ break # break for-item loop
1679
+
1680
+ except _SampleTimeout:
1681
+ # This fires only when the timeout occurs in next(loader_iter)
1682
+ # (HDF5 IO). Timeouts during inference are _SampleTimeout
1683
+ # subclasses of Exception and are caught by the inner except.
1684
+ #
1685
+ # NOTE: with num_workers=0 the HDF5 C library retries EINTR
1686
+ # internally, so SIGALRM may not fire until the read eventually
1687
+ # completes or exceeds sample_timeout at a Python check-point.
1688
+ # With num_workers>=1 the main process blocks in Python-level
1689
+ # queue.get(), which IS interruptible, so timeout is reliable.
1690
+ total_errors += 1
1691
+ err_record = {
1692
+ "record_type": "error",
1693
+ "sample_key": sample_key, # "" if timeout before item was known
1694
+ "error": f"HDF5 read timed out after {sample_timeout}s",
1695
+ }
1696
+ f.write(_json_dumps(to_jsonable(err_record)) + "\n")
1697
+ f.flush()
1698
+ total_written_lines += 1
1699
+ print(
1700
+ f"[WARN] HDF5 read timed out after {sample_timeout}s "
1701
+ f"(sample will be retried on next run)",
1702
+ flush=True,
1703
+ )
1704
+ # With num_workers > 0 the worker process that hung is still
1705
+ # running in the background. Recreating the iterator drops the
1706
+ # reference to the old loader state and spawns a fresh worker,
1707
+ # so subsequent samples are not blocked by the stuck process.
1708
+ if num_workers > 0:
1709
+ print(
1710
+ "[INFO] Restarting DataLoader to replace the hung "
1711
+ "worker process.",
1712
+ flush=True,
1713
+ )
1714
+ try:
1715
+ del loader_iter
1716
+ except Exception:
1717
+ pass
1718
+ loader_iter = iter(loader)
1719
+ # Do NOT call synchronize()/empty_cache() after a timeout.
1720
+
1721
+ finally:
1722
+ # Always disarm; calling __exit__ multiple times is safe
1723
+ # (signal.alarm(0) is idempotent).
1724
+ _timer.__exit__(None, None, None)
1725
+ # Release any refs left by an HDF5-timeout path.
1726
+ picks = z = x_cpu = waveform = None
1727
+ if item is not None:
1728
+ try:
1729
+ del item["waveform"]
1730
+ except Exception:
1731
+ pass
1732
+ item = None
1733
+
1734
+ if _max_samples_reached:
1735
+ break # break while loop
1736
+
1737
+ f.flush()
1738
+
1739
+ finally:
1740
+ try:
1741
+ dataset.close()
1742
+ except Exception:
1743
+ pass
1744
+ gc.collect()
1745
+ empty_device_cache(device_type)
1746
+
1747
+ total_elapsed = time.perf_counter() - t_all0
1748
+ loop_elapsed = time.perf_counter() - t_loop0
1749
+
1750
+ print("=" * 80)
1751
+ print("[OK] Phase picking finished")
1752
+ print(f"[OK] Dataset samples seen by DataLoader: {total_seen}")
1753
+ print(f"[OK] Samples newly processed: {total_processed}")
1754
+ print(f"[OK] Phase picks written: {total_picks}")
1755
+ print(f"[OK] JSONL lines written this run: {total_written_lines}")
1756
+ print(f"[OK] Errors: {total_errors}")
1757
+ print(f"[OK] Output JSONL: {output_jsonl}")
1758
+ print(f"[OK] Processing time: {format_seconds(loop_elapsed)}")
1759
+ print(f"[OK] Total wall time: {format_seconds(total_elapsed)}")
1760
+ if hasattr(dataset, "filtered_index_size"):
1761
+ print(f"[OK] Samples skipped before waveform loading: {dataset.filtered_index_size}")
1762
+ if total_seen > 0:
1763
+ print(f"[OK] Average speed: {total_seen / max(loop_elapsed, 1e-6):.3f} samples/s")
1764
+ print(f"[OK] Average time per sample: {loop_elapsed / total_seen:.3f} s/sample")
1765
+ if total_picks > 0:
1766
+ print(f"[OK] Average time per pick: {loop_elapsed / total_picks:.3f} s/pick")
1767
+ if _max_samples_reached:
1768
+ print(f"[OK] Stopped early: max_samples={max_samples} reached.")
1769
+ if auto_restart:
1770
+ print(f"[OK] auto_restart=True — re-executing this process now to free all OS-level "
1771
+ f"Metal / CoreML allocator state (RSS will reset to baseline).")
1772
+ else:
1773
+ print(f"[OK] auto_restart=False — exiting with code 75. "
1774
+ f"Re-run with --resume to continue from the next sample.")
1775
+ print("=" * 80)
1776
+
1777
+ if _max_samples_reached:
1778
+ sys.stdout.flush()
1779
+ sys.stderr.flush()
1780
+ if auto_restart:
1781
+ # os.execv replaces this process image with a fresh Python process running
1782
+ # the same script and arguments. The OS reclaims ALL Metal / CoreML /
1783
+ # HDF5 allocator state (things that empty_cache and gc.collect cannot touch).
1784
+ # --resume is enabled by default so the new process skips already-written
1785
+ # samples at the dataset level without re-reading any waveform data.
1786
+ os.execv(sys.executable, [sys.executable] + sys.argv)
1787
+ else:
1788
+ sys.exit(75)
1789
+
1790
+
1791
+ def parse_tuple_arg(value):
1792
+ if value is None or str(value).strip() == "":
1793
+ return tuple()
1794
+ return tuple(x.strip().upper() for x in str(value).split(",") if x.strip())
1795
+
1796
+
1797
+ def main():
1798
+ parser = argparse.ArgumentParser(
1799
+ description="Run TorchScript or ONNX seismic picker on HDF5 dataloader samples and write JSONL output."
1800
+ )
1801
+
1802
+ parser.add_argument(
1803
+ "--h5_input",
1804
+ default="data/hdf5/continuous_waveform_usa_*.h5",
1805
+ help='HDF5 file, directory, or glob pattern.',
1806
+ )
1807
+ parser.add_argument(
1808
+ "--output_jsonl",
1809
+ default="data/picks/pnsn.v1.phase.jsonl",
1810
+ help="Output JSONL file.",
1811
+ )
1812
+ parser.add_argument(
1813
+ "--picker_model",
1814
+ default="pickers/pnsn.v1.diff.jit",
1815
+ help="Picker model path. Suffix .onnx uses ONNX Runtime; .jit/.torchscript uses TorchScript by default.",
1816
+ )
1817
+ parser.add_argument(
1818
+ "--picker_backend",
1819
+ default="auto",
1820
+ choices=["auto", "torchscript", "onnx"],
1821
+ help=(
1822
+ "Picker backend. Default 'auto' chooses by --picker_model suffix: "
1823
+ ".onnx -> ONNX Runtime + external heap-NMS; "
1824
+ ".jit/.torchscript -> TorchScript. "
1825
+ "Use 'torchscript' or 'onnx' to override."
1826
+ ),
1827
+ )
1828
+ parser.add_argument(
1829
+ "--onnx_providers",
1830
+ default="auto",
1831
+ help=(
1832
+ "ONNX Runtime provider list. Use 'auto' to select CUDA for --device cuda, "
1833
+ "CoreML for --device mps, and CPU otherwise. You can also pass an explicit "
1834
+ "comma-separated list such as CUDAExecutionProvider,CPUExecutionProvider."
1835
+ ),
1836
+ )
1837
+ parser.add_argument(
1838
+ "--onnx_prob_thresh",
1839
+ type=float,
1840
+ default=0.1,
1841
+ help="Probability threshold for external heap-NMS ONNX picker post-processing.",
1842
+ )
1843
+ parser.add_argument(
1844
+ "--onnx_nms_win",
1845
+ type=int,
1846
+ default=200,
1847
+ help="NMS window in samples for external heap-NMS ONNX picker post-processing.",
1848
+ )
1849
+ parser.add_argument(
1850
+ "--polar_model",
1851
+ default=None,
1852
+ help="Optional ONNX polar model path. Use empty string to disable.",
1853
+ )
1854
+ parser.add_argument(
1855
+ "--device",
1856
+ default="auto",
1857
+ choices=["auto", "cpu", "cuda", "mps"],
1858
+ help="Inference device: auto, cpu, cuda, or mps.",
1859
+ )
1860
+ parser.add_argument(
1861
+ "--batch_size",
1862
+ type=int,
1863
+ default=1,
1864
+ help="Batch size. Samples are still processed one by one inside each batch.",
1865
+ )
1866
+ parser.add_argument(
1867
+ "--num_workers",
1868
+ type=int,
1869
+ default=0,
1870
+ help=(
1871
+ "Number of DataLoader worker processes for parallel waveform prefetching. "
1872
+ "0 = single-process (default). "
1873
+ "MPS: 1 worker overlaps HDF5 decode (CPU) with GPU inference; workers never "
1874
+ "touch MPS so this is safe — use with --multiprocessing_context spawn "
1875
+ "(macOS default). "
1876
+ "CUDA: 4–8 workers is a good starting point to hide HDF5 I/O latency. "
1877
+ "On Linux, workers use 'spawn' by default (see --multiprocessing_context) "
1878
+ "to avoid h5py + fork conflicts."
1879
+ ),
1880
+ )
1881
+ parser.add_argument(
1882
+ "--prefetch_factor",
1883
+ type=int,
1884
+ default=2,
1885
+ help=(
1886
+ "Number of batches pre-loaded per worker (PyTorch default=2). "
1887
+ "Reduce to 1 if workers OOM on large waveforms. "
1888
+ "Ignored when num_workers=0."
1889
+ ),
1890
+ )
1891
+ parser.add_argument(
1892
+ "--multiprocessing_context",
1893
+ default="auto",
1894
+ help=(
1895
+ "Multiprocessing start method for DataLoader workers: "
1896
+ "'auto' (default) selects 'spawn' on Linux to avoid h5py+fork issues, "
1897
+ "and the OS default elsewhere. "
1898
+ "Other valid values: 'spawn', 'fork', 'forkserver'. "
1899
+ "If you use 'fork', the hdf5_worker_init_fn is automatically applied "
1900
+ "to reset inherited HDF5 file handles in each worker. "
1901
+ "Ignored when num_workers=0."
1902
+ ),
1903
+ )
1904
+ parser.add_argument(
1905
+ "--allowed_families",
1906
+ default="HH,BH,EH,HN",
1907
+ help='Comma-separated channel families, e.g. "HH,BH,EH,HN".',
1908
+ )
1909
+ parser.add_argument(
1910
+ "--allowed_z_only_channels",
1911
+ default="EHZ",
1912
+ help='Comma-separated Z-only channels, e.g. "EHZ".',
1913
+ )
1914
+ parser.add_argument(
1915
+ "--allow_z_only",
1916
+ action="store_true",
1917
+ default=True,
1918
+ help="Allow Z-only samples.",
1919
+ )
1920
+ parser.add_argument(
1921
+ "--no_z_only",
1922
+ action="store_false",
1923
+ dest="allow_z_only",
1924
+ help="Disable Z-only samples.",
1925
+ )
1926
+ parser.add_argument(
1927
+ "--replicate_z_only",
1928
+ action="store_true",
1929
+ default=True,
1930
+ help="Replicate Z-only samples to [Z, Z, Z].",
1931
+ )
1932
+ parser.add_argument(
1933
+ "--no_replicate_z_only",
1934
+ action="store_false",
1935
+ dest="replicate_z_only",
1936
+ help="Do not replicate Z-only samples.",
1937
+ )
1938
+ parser.add_argument(
1939
+ "--target_sampling_rate",
1940
+ type=float,
1941
+ default=100.0,
1942
+ help="Target sampling rate in Hz. Use -1 to disable resampling.",
1943
+ )
1944
+ parser.add_argument(
1945
+ "--min_confidence",
1946
+ type=float,
1947
+ default=0.0,
1948
+ help="Minimum pick confidence to write.",
1949
+ )
1950
+ parser.add_argument(
1951
+ "--snr_window_sec",
1952
+ type=float,
1953
+ default=2.0,
1954
+ help="SNR window length before and after pick, in seconds.",
1955
+ )
1956
+ parser.add_argument(
1957
+ "--progress_interval",
1958
+ type=int,
1959
+ default=100,
1960
+ help="Print progress every N samples.",
1961
+ )
1962
+ parser.add_argument(
1963
+ "--flush_interval",
1964
+ type=int,
1965
+ default=100,
1966
+ help="Flush JSONL file every N processed samples. Use 0 to flush only at the end.",
1967
+ )
1968
+ parser.add_argument(
1969
+ "--gc_interval",
1970
+ type=int,
1971
+ default=500,
1972
+ help="Run gc.collect and empty device cache every N samples. Use 0 to disable.",
1973
+ )
1974
+ parser.add_argument(
1975
+ "--resume",
1976
+ action="store_true",
1977
+ default=True,
1978
+ help="Resume from existing JSONL and skip already processed samples before waveform loading.",
1979
+ )
1980
+ parser.add_argument(
1981
+ "--no_resume",
1982
+ action="store_false",
1983
+ dest="resume",
1984
+ help="Disable resume mode and overwrite output JSONL.",
1985
+ )
1986
+ parser.add_argument(
1987
+ "--include_segments_metadata",
1988
+ action="store_true",
1989
+ default=False,
1990
+ help="Return segment metadata from the loader. Default False saves memory.",
1991
+ )
1992
+ parser.add_argument(
1993
+ "--no_keep_h5_open",
1994
+ action="store_false",
1995
+ dest="keep_h5_open",
1996
+ default=True,
1997
+ help="Disable per-process cached HDF5 handles.",
1998
+ )
1999
+ parser.add_argument(
2000
+ "--mps_empty_cache_interval",
2001
+ type=int,
2002
+ default=500,
2003
+ help="For MPS, synchronize + gc.collect + torch.mps.empty_cache every N processed samples. Use 0 to disable.",
2004
+ )
2005
+ parser.add_argument(
2006
+ "--cuda_empty_cache_interval",
2007
+ type=int,
2008
+ default=500,
2009
+ help="For CUDA, synchronize + torch.cuda.empty_cache every N processed samples. Use 0 to disable.",
2010
+ )
2011
+ parser.add_argument(
2012
+ "--reload_model_interval",
2013
+ type=int,
2014
+ default=-1,
2015
+ help=(
2016
+ "Reload TorchScript model every N processed samples. "
2017
+ "-1 (default) = auto: 50 for MPS (Metal allocator state accumulates "
2018
+ "with each TorchScript call; reload is the only way to reset it), "
2019
+ "0 (disabled) for CUDA and CPU. "
2020
+ "Increase if reload overhead is noticeable on very short waveforms. "
2021
+ "Set 0 to disable entirely."
2022
+ ),
2023
+ )
2024
+ parser.add_argument(
2025
+ "--no_overlap_mask",
2026
+ action="store_false",
2027
+ dest="use_overlap_mask",
2028
+ default=True,
2029
+ help="Disable overlap mask in fill_segments_to_array to reduce memory.",
2030
+ )
2031
+ parser.add_argument(
2032
+ "--h5_rdcc_nbytes",
2033
+ type=int,
2034
+ default=8 * 1024 * 1024,
2035
+ help=(
2036
+ "HDF5 raw-data chunk cache size in bytes per open file handle "
2037
+ "(default: 8388608 = 8 MB). h5py's built-in default is 1 MB. "
2038
+ "8 MB is enough for single-pass inference; only the current file's "
2039
+ "handle is kept open — stale file handles are closed as soon as the "
2040
+ "loader moves to the next file, so chunk-cache memory stays O(1). "
2041
+ "Raise to 64 MB for repeated-access / training workloads."
2042
+ ),
2043
+ )
2044
+ parser.add_argument(
2045
+ "--canonical_input_length",
2046
+ type=int,
2047
+ default=0,
2048
+ help=(
2049
+ "Pad or trim every waveform to exactly N samples before sending to "
2050
+ "the picker model. Default 0 = disabled (recommended). "
2051
+ "WARNING: many models (e.g. EQTransformer) use fixed-size internal "
2052
+ "windows and will crash or produce wrong results if the input tensor "
2053
+ "length differs from what the model expects. Only enable if you know "
2054
+ "your model supports variable-length inputs and benefits from a fixed "
2055
+ "shape (e.g. to control TorchScript Metal pipeline cache growth). "
2056
+ "Picks placed in the padded tail (sample_index >= original length) "
2057
+ "are filtered out automatically."
2058
+ ),
2059
+ )
2060
+ parser.add_argument(
2061
+ "--max_samples",
2062
+ type=int,
2063
+ default=0,
2064
+ help=(
2065
+ "Restart the process after processing N new samples. "
2066
+ "With --auto_restart (default), the script calls os.execv to replace "
2067
+ "itself with a fresh process, freeing all Metal / CoreML / HDF5 "
2068
+ "allocator state that Python cannot reclaim. "
2069
+ "--resume is enabled by default, so the new process skips already-written "
2070
+ "samples at the dataset level. "
2071
+ "0 = no limit (process all samples without restart). "
2072
+ "Recommended on Mac/MPS to keep RSS bounded: --max_samples 200."
2073
+ ),
2074
+ )
2075
+ parser.add_argument(
2076
+ "--auto_restart",
2077
+ action="store_true",
2078
+ default=True,
2079
+ help=(
2080
+ "When --max_samples is reached, use os.execv to restart this process "
2081
+ "instead of exiting with code 75. "
2082
+ "The OS reclaims all Metal / CoreML / HDF5 allocator state on process "
2083
+ "replacement; the new process resumes from where the previous one stopped. "
2084
+ "Default: True (recommended for MPS). "
2085
+ "Use --no_auto_restart to get exit-code-75 behavior for external bash loops."
2086
+ ),
2087
+ )
2088
+ parser.add_argument(
2089
+ "--no_auto_restart",
2090
+ action="store_false",
2091
+ dest="auto_restart",
2092
+ help="Disable auto os.execv restart; exit with code 75 when --max_samples is reached.",
2093
+ )
2094
+ parser.add_argument(
2095
+ "--sample_timeout",
2096
+ type=int,
2097
+ default=600,
2098
+ help=(
2099
+ "Maximum seconds allowed to process a single sample before the "
2100
+ "watchdog (SIGALRM) fires and the sample is written as an error "
2101
+ "record. Prevents the script from hanging indefinitely on a stuck "
2102
+ "Metal / ONNX Runtime operation. "
2103
+ "0 = disabled. Default: 120 s. "
2104
+ "Only effective on Unix/macOS (SIGALRM is not available on Windows)."
2105
+ ),
2106
+ )
2107
+ parser.add_argument(
2108
+ "--max_picks_per_sample",
2109
+ type=int,
2110
+ default=0,
2111
+ help=(
2112
+ "Maximum phase detections to write per station-day. When more "
2113
+ "picks are detected (e.g. on a major-earthquake day with thousands "
2114
+ "of aftershocks), the top-N by confidence are kept and the rest "
2115
+ "are discarded. This prevents the per-pick CoreML polarity loop "
2116
+ "from running for hundreds of seconds and triggering the "
2117
+ "--sample_timeout watchdog. 0 = no limit (default). "
2118
+ "Recommended on MPS/Apple Silicon when processing high-seismicity days: 500-2000."
2119
+ ),
2120
+ )
2121
+ parser.add_argument(
2122
+ "--max_duration_sec",
2123
+ type=float,
2124
+ default=90000.0,
2125
+ help=(
2126
+ "Maximum allowed time span for one consolidated channel waveform. "
2127
+ "Default 90000 s = 25 h. If a channel has bad start/end metadata and "
2128
+ "would allocate an abnormal array, the loader raises an error instead "
2129
+ "of appearing to hang."
2130
+ ),
2131
+ )
2132
+ parser.add_argument(
2133
+ "--slow_load_threshold",
2134
+ type=float,
2135
+ default=10.0,
2136
+ help="Print [SLOW_LOAD]/[SLOW_SAMPLE] when DataLoader/HDF5 batch fetch exceeds this many seconds.",
2137
+ )
2138
+ parser.add_argument(
2139
+ "--slow_infer_threshold",
2140
+ type=float,
2141
+ default=10.0,
2142
+ help="Print [SLOW_SAMPLE] when TorchScript model inference exceeds this many seconds.",
2143
+ )
2144
+ parser.add_argument(
2145
+ "--slow_post_threshold",
2146
+ type=float,
2147
+ default=10.0,
2148
+ help="Print [SLOW_SAMPLE] when post-processing / SNR / polarity / JSONL writing exceeds this many seconds.",
2149
+ )
2150
+ parser.add_argument(
2151
+ "--slow_total_threshold",
2152
+ type=float,
2153
+ default=30.0,
2154
+ help="Print [SLOW_SAMPLE] when total per-sample time excluding batch fetch exceeds this many seconds.",
2155
+ )
2156
+ parser.add_argument(
2157
+ "--flush_no_pick",
2158
+ action="store_true",
2159
+ default=False,
2160
+ help=(
2161
+ "Flush output JSONL immediately after every no_pick sentinel. "
2162
+ "Default False because flushing every no-pick sample can be slow on "
2163
+ "external disks or network filesystems."
2164
+ ),
2165
+ )
2166
+ args = parser.parse_args()
2167
+
2168
+ target_sampling_rate = args.target_sampling_rate
2169
+ if target_sampling_rate is not None and target_sampling_rate <= 0:
2170
+ target_sampling_rate = None
2171
+
2172
+ run_picker_to_jsonl(
2173
+ h5_input=args.h5_input,
2174
+ output_jsonl=args.output_jsonl,
2175
+ picker_model=args.picker_model,
2176
+ polar_model=args.polar_model if args.polar_model else None,
2177
+ picker_backend=args.picker_backend,
2178
+ onnx_providers=args.onnx_providers,
2179
+ onnx_prob_thresh=args.onnx_prob_thresh,
2180
+ onnx_nms_win=args.onnx_nms_win,
2181
+ device_name=args.device,
2182
+ batch_size=args.batch_size,
2183
+ num_workers=args.num_workers,
2184
+ allowed_families=parse_tuple_arg(args.allowed_families),
2185
+ allowed_z_only_channels=parse_tuple_arg(args.allowed_z_only_channels),
2186
+ allow_z_only=args.allow_z_only,
2187
+ replicate_z_only=args.replicate_z_only,
2188
+ target_sampling_rate=target_sampling_rate,
2189
+ min_confidence=args.min_confidence,
2190
+ snr_window_sec=args.snr_window_sec,
2191
+ progress_interval=args.progress_interval,
2192
+ resume=args.resume,
2193
+ flush_interval=args.flush_interval,
2194
+ gc_interval=args.gc_interval,
2195
+ include_segments_metadata=args.include_segments_metadata,
2196
+ keep_h5_open=args.keep_h5_open,
2197
+ use_overlap_mask=args.use_overlap_mask,
2198
+ mps_empty_cache_interval=args.mps_empty_cache_interval,
2199
+ cuda_empty_cache_interval=args.cuda_empty_cache_interval,
2200
+ reload_model_interval=args.reload_model_interval,
2201
+ multiprocessing_context=args.multiprocessing_context,
2202
+ prefetch_factor=args.prefetch_factor,
2203
+ h5_rdcc_nbytes=args.h5_rdcc_nbytes,
2204
+ max_samples=args.max_samples,
2205
+ canonical_input_length=args.canonical_input_length,
2206
+ auto_restart=args.auto_restart,
2207
+ sample_timeout=args.sample_timeout,
2208
+ max_picks_per_sample=args.max_picks_per_sample,
2209
+ max_duration_sec=args.max_duration_sec,
2210
+ slow_load_threshold=args.slow_load_threshold,
2211
+ slow_infer_threshold=args.slow_infer_threshold,
2212
+ slow_post_threshold=args.slow_post_threshold,
2213
+ slow_total_threshold=args.slow_total_threshold,
2214
+ flush_no_pick=args.flush_no_pick,
2215
+ )
2216
+
2217
+
2218
+ if __name__ == "__main__":
2219
+ main()