Skip to content

Dataset Module

PyTorch Dataset classes for loading training data.

Overview

The dataset module provides PyTorch Dataset implementations for efficient data loading during training.

LeechDataset

LeechDataset(chunk_path: Path | None = None, signal_len: int = 400, kmer_len: int = 11, model_type: str = 'ConvLSTMDwell', dwell_offset: int = 0, chunks: list[dict] | None = None, augmentation: dict | None = None, seq_encoding: str = 'signal_kmer', signal_kmer_context: tuple[int, int] = (4, 4), allow_encoding_fallback: bool = True, left_context: int | None = None, right_context: int | None = None, strict_window: bool = False, confound_encoder: ConfoundEncoder | None = None, label_noise_rates: dict[str, float] | None = None, cl_regression: bool = False, signal_mode: str = 'both', time_mask_bases: int = 0, time_mask_count: int = 1, shift_max_bases: float = 0.0, feature_noise_scale: float = 0.0, time_stretch_range: tuple[float, float] | None = None, dwell_template_table: str | Path | None = None, motif_offset: int | None = None, standardize_features: bool = False, feature_channel_names: Sequence[str] | None = None, selected_feature_channels: Sequence[str] | None = None)

Bases: Dataset

PyTorch Dataset for leech training chunks.

Handles loading and preprocessing of training data.

Parameters:

Name Type Description Default
chunk_path Path | None

Path to .npz file with training chunks

None
signal_len int

Expected signal length (will pad/truncate)

400
kmer_len int

Expected k-mer length

11
model_type str

Model architecture name (e.g., "ConvLSTMDwell", "TransformerDwell")

'ConvLSTMDwell'
dwell_offset int

Shift dwell/feature window toward 3' end (bases). Compensates for physical offset between motor protein and sensing region. Requires feature_left >= kmer_context + offset.

0
chunks list[dict] | None

Pre-loaded list of chunk dicts. When provided, chunk_path is ignored and no disk I/O occurs (useful for grid search caching).

None
augmentation dict | None

Signal augmentation config dict. Keys: - jitter_std (float): Gaussian noise std dev (0 = disabled) - scale_range (tuple[float, float]): Random scale range (1.0, 1.0 = disabled)

None
allow_encoding_fallback bool

When seq_encoding="signal_kmer" and the corpus carries no base-to-signal maps at all, fall back to base_onehot (warning) rather than raising. A corpus that carries them for some chunks is damaged and raises either way. Read :attr:effective_seq_encoding for what the dataset actually yields — it is a different model input, not a tuning difference, so callers that persist a config must record it.

True
left_context int | None

Left signal context (samples before focus base). When both left_context and right_context are provided, crop asymmetrically around the focus base instead of center-cropping.

None
right_context int | None

Right signal context (samples after focus base).

None
strict_window bool

When the asymmetric crop (left_context/ right_context) reaches outside the stored chunk -- the corpus was prepared with a narrower signal_context than this window -- the shortfall is zero-padded either way; the default (False) logs one warning for the whole dataset the first time it happens, True raises immediately instead. A silently zero-padded tail is exactly what went undetected in two production retrains that trained with a wider right_context than the corpus was prepared with (#255).

False
confound_encoder ConfoundEncoder | None

Optional :class:~leech.confounds.ConfoundEncoder that maps each chunk to an integer confound class. When provided, each batch includes a confound_label tensor for adversarial training. Chunks whose confound value is unknown get -1 (ignored by the CE loss via ignore_index=-1).

None
label_noise_rates dict[str, float] | None

Optional {source_group: flip_rate} mapping. When provided, each batch includes a noise_rate tensor (shape matching label) built by looking up each chunk's source_group (missing/empty -> "unknown"); groups absent from the mapping get rate 0. Consumed by leech.losses.NoiseCorrectedBCEWithLogitsLoss.

None
cl_regression bool

When True, include cl_target in each batch (cl_value / 255.0 in [0,1]; sentinel -1.0 for missing).

False
time_mask_bases int

Max width in bases for time masking (0 = disabled). Zeros out contiguous blocks across signal, features, and sequence.

0
time_mask_count int

Number of time masks to apply per sample.

1
shift_max_bases float

Max cross-layer shift in bases (0 = disabled). Simulates motif anchor offset, applied consistently to all branches.

0.0
feature_noise_scale float

Per-channel Gaussian noise multiplier (0 = disabled). Noise std = feature_noise_scale * per-channel empirical std.

0.0
time_stretch_range tuple[float, float] | None

(min, max) per-sample time-stretch factor, drawn uniformly per chunk (1.0, 1.0) = disabled). Resamples the signal window about the focus position (cropped/padded back to signal_len), scales the CSR base-to-signal map by the same factor (so signal_kmer stays aligned), and scales the dwell-derived feature channels -- see :meth:_apply_time_stretch for the exact per-channel rule. Level channels are unchanged. Implemented only on the batched __getitems__ fetch path: incompatible with shift_max_bases/time_mask_bases (which force the per-sample fallback) and with a corpus that degrades to a per-chunk list -- both raise at construction rather than silently skipping the augmentation.

None
dwell_template_table str | Path | None

Path to TSV with per-AA per-position expected dwell times. When provided, 20 dwell ratio channels are appended to features: dwell / expected_dwell[AA_i, pos] for each of 20 AAs. The correct AA's channel has ratio closest to 1.0. TSV columns: aa, position, dwell_mean, ... -- see :func:load_dwell_template_table for the optional header lines recording the motif_offset the table was built against. The dwell row to divide is resolved by name from :attr:effective_feature_channels, not assumed to be row 0 (issue #366) -- raises ValueError at construction if dwell is not an effective channel. The table's covered position range is also checked against the corpus's feature window (issue #367; see :func:check_dwell_template_coverage and :attr:dwell_template_positions/ :attr:dwell_template_uncovered_columns). Incompatible with time_stretch_range (issue #368): the template ratios are computed once here and are not rescaled by time-stretch.

None
motif_offset int | None

This run's motif_offset, used only to guard dwell_template_table against issue #364 -- a table whose position column was counted from a different focus base. Checked via :func:check_dwell_template_motif_offset when both this and dwell_template_table are given; None (default) skips the check, e.g. for callers that do not yet know their own motif_offset.

None
standardize_features bool

Compute corpus-wide per-channel feature mean/std once (see :attr:feature_mean/:attr:feature_std) for --standardize-features. This dataset never applies them to its own output -- the caller (train_model) reads them and passes them to the model constructor, which builds a frozen affine layer from them. Meaningful only for the training dataset; a validation/test/predict dataset should leave this False and reuse the training corpus's stats via the model instead.

False
feature_channel_names Sequence[str] | None

The corpus's recorded feature-channel list (issue #358), e.g. read from prepare_config.json's feature_channels key. None (default) means :data:~leech.constants.DEFAULT_FEATURE_CHANNELS -- the historical twelve, which keys _apply_time_stretch's dwell/dwell_log/dwell_mean rule to the same positions (0, 1, 2) it always used, so an unset corpus behaves identically to before this existed. Consulted when time_stretch_range is active (for the by-name lookup) and whenever selected_feature_channels is given (as the nominal list to reconcile against the tensor's actual stored row count -- see :func:~leech.constants.resolve_stored_feature_channels).

None
selected_feature_channels Sequence[str] | None

Channel ablation (issue #358 follow-up) -- select and reorder a SUBSET of the corpus's feature rows by name, resolved once here against the actual stored row count (not assumed position) and applied to every per-chunk feature array before anything else touches it, so num_features, per-channel standardization stats, feature-noise augmentation and time-stretch's by-name dwell lookup all see the selected tensor. None (default) keeps every row exactly as before this existed -- selection logic does not run at all in that case, so an unset corpus is byte-identical. Raises ValueError naming any requested channel absent from the corpus's actual data (see :func:~leech.constants.select_feature_channels).

None
Source code in src/leech/dataset.py
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
def __init__(
    self,
    chunk_path: Path | None = None,
    signal_len: int = 400,
    kmer_len: int = 11,
    model_type: str = "ConvLSTMDwell",
    dwell_offset: int = 0,
    chunks: list[dict] | None = None,
    augmentation: dict | None = None,
    seq_encoding: str = "signal_kmer",
    signal_kmer_context: tuple[int, int] = (4, 4),
    allow_encoding_fallback: bool = True,
    left_context: int | None = None,
    right_context: int | None = None,
    strict_window: bool = False,
    confound_encoder: "ConfoundEncoder | None" = None,
    label_noise_rates: dict[str, float] | None = None,
    cl_regression: bool = False,
    signal_mode: str = "both",
    time_mask_bases: int = 0,
    time_mask_count: int = 1,
    shift_max_bases: float = 0.0,
    feature_noise_scale: float = 0.0,
    time_stretch_range: tuple[float, float] | None = None,
    dwell_template_table: str | Path | None = None,
    motif_offset: int | None = None,
    standardize_features: bool = False,
    feature_channel_names: Sequence[str] | None = None,
    selected_feature_channels: Sequence[str] | None = None,
):
    """
    Initialize dataset.

    Args:
        chunk_path: Path to .npz file with training chunks
        signal_len: Expected signal length (will pad/truncate)
        kmer_len: Expected k-mer length
        model_type: Model architecture name (e.g., "ConvLSTMDwell", "TransformerDwell")
        dwell_offset: Shift dwell/feature window toward 3' end (bases).
            Compensates for physical offset between motor protein and
            sensing region. Requires feature_left >= kmer_context + offset.
        chunks: Pre-loaded list of chunk dicts. When provided, chunk_path is
            ignored and no disk I/O occurs (useful for grid search caching).
        augmentation: Signal augmentation config dict. Keys:
            - jitter_std (float): Gaussian noise std dev (0 = disabled)
            - scale_range (tuple[float, float]): Random scale range (1.0, 1.0 = disabled)
        allow_encoding_fallback: When ``seq_encoding="signal_kmer"`` and the
            corpus carries no base-to-signal maps at all, fall back to
            ``base_onehot`` (warning) rather than raising. A corpus that
            carries them for *some* chunks is damaged and raises either way.
            Read :attr:`effective_seq_encoding` for what the dataset
            actually yields — it is a different model input, not a tuning
            difference, so callers that persist a config must record it.
        left_context: Left signal context (samples before focus base).
            When both left_context and right_context are provided, crop
            asymmetrically around the focus base instead of center-cropping.
        right_context: Right signal context (samples after focus base).
        strict_window: When the asymmetric crop (``left_context``/
            ``right_context``) reaches outside the stored chunk -- the
            corpus was prepared with a narrower ``signal_context`` than
            this window -- the shortfall is zero-padded either way; the
            default (False) logs one warning for the whole dataset the
            first time it happens, ``True`` raises immediately instead.
            A silently zero-padded tail is exactly what went undetected
            in two production retrains that trained with a wider
            ``right_context`` than the corpus was prepared with (#255).
        confound_encoder: Optional :class:`~leech.confounds.ConfoundEncoder`
            that maps each chunk to an integer confound class. When provided,
            each batch includes a ``confound_label`` tensor for adversarial
            training. Chunks whose confound value is unknown get ``-1``
            (ignored by the CE loss via ``ignore_index=-1``).
        label_noise_rates: Optional ``{source_group: flip_rate}`` mapping.
            When provided, each batch includes a ``noise_rate`` tensor
            (shape matching ``label``) built by looking up each chunk's
            ``source_group`` (missing/empty -> "unknown"); groups absent
            from the mapping get rate 0. Consumed by
            ``leech.losses.NoiseCorrectedBCEWithLogitsLoss``.
        cl_regression: When True, include ``cl_target`` in each batch
            (cl_value / 255.0 in [0,1]; sentinel -1.0 for missing).
        time_mask_bases: Max width in bases for time masking (0 = disabled).
            Zeros out contiguous blocks across signal, features, and sequence.
        time_mask_count: Number of time masks to apply per sample.
        shift_max_bases: Max cross-layer shift in bases (0 = disabled).
            Simulates motif anchor offset, applied consistently to all branches.
        feature_noise_scale: Per-channel Gaussian noise multiplier (0 = disabled).
            Noise std = feature_noise_scale * per-channel empirical std.
        time_stretch_range: ``(min, max)`` per-sample time-stretch factor,
            drawn uniformly per chunk ``(1.0, 1.0)`` = disabled). Resamples
            the signal window about the focus position (cropped/padded back
            to ``signal_len``), scales the CSR base-to-signal map by the
            same factor (so ``signal_kmer`` stays aligned), and scales the
            dwell-derived feature channels -- see
            :meth:`_apply_time_stretch` for the exact per-channel rule.
            Level channels are unchanged. Implemented only on the batched
            ``__getitems__`` fetch path: incompatible with
            ``shift_max_bases``/``time_mask_bases`` (which force the
            per-sample fallback) and with a corpus that degrades to a
            per-chunk list -- both raise at construction rather than
            silently skipping the augmentation.
        dwell_template_table: Path to TSV with per-AA per-position expected
            dwell times. When provided, 20 dwell ratio channels are appended
            to features: ``dwell / expected_dwell[AA_i, pos]`` for each of
            20 AAs. The correct AA's channel has ratio closest to 1.0.
            TSV columns: aa, position, dwell_mean, ... -- see
            :func:`load_dwell_template_table` for the optional header lines
            recording the motif_offset the table was built against. The
            ``dwell`` row to divide is resolved by name from
            :attr:`effective_feature_channels`, not assumed to be row 0
            (issue #366) -- raises ``ValueError`` at construction if
            ``dwell`` is not an effective channel. The table's covered
            position range is also checked against the corpus's feature
            window (issue #367; see :func:`check_dwell_template_coverage`
            and :attr:`dwell_template_positions`/
            :attr:`dwell_template_uncovered_columns`). Incompatible with
            ``time_stretch_range`` (issue #368): the template ratios are
            computed once here and are not rescaled by time-stretch.
        motif_offset: This run's motif_offset, used only to guard
            ``dwell_template_table`` against issue #364 -- a table whose
            ``position`` column was counted from a different focus base.
            Checked via :func:`check_dwell_template_motif_offset` when
            both this and ``dwell_template_table`` are given; ``None``
            (default) skips the check, e.g. for callers that do not yet
            know their own motif_offset.
        standardize_features: Compute corpus-wide per-channel feature
            mean/std once (see :attr:`feature_mean`/:attr:`feature_std`)
            for ``--standardize-features``. This dataset never applies
            them to its own output -- the caller (``train_model``) reads
            them and passes them to the model constructor, which builds a
            frozen affine layer from them. Meaningful only for the
            *training* dataset; a validation/test/predict dataset should
            leave this False and reuse the training corpus's stats via
            the model instead.
        feature_channel_names: The corpus's recorded feature-channel list
            (issue #358), e.g. read from ``prepare_config.json``'s
            ``feature_channels`` key. ``None`` (default) means
            :data:`~leech.constants.DEFAULT_FEATURE_CHANNELS` -- the
            historical twelve, which keys ``_apply_time_stretch``'s
            dwell/dwell_log/dwell_mean rule to the same positions (0, 1,
            2) it always used, so an unset corpus behaves identically to
            before this existed. Consulted when ``time_stretch_range`` is
            active (for the by-name lookup) and whenever
            ``selected_feature_channels`` is given (as the *nominal* list
            to reconcile against the tensor's actual stored row count --
            see :func:`~leech.constants.resolve_stored_feature_channels`).
        selected_feature_channels: Channel ablation (issue #358
            follow-up) -- select and reorder a SUBSET of the corpus's
            feature rows by name, resolved once here against the actual
            stored row count (not assumed position) and applied to every
            per-chunk feature array before anything else touches it, so
            ``num_features``, per-channel standardization stats,
            feature-noise augmentation and time-stretch's by-name dwell
            lookup all see the selected tensor. ``None`` (default) keeps
            every row exactly as before this existed -- selection logic
            does not run at all in that case, so an unset corpus is
            byte-identical. Raises ``ValueError`` naming any requested
            channel absent from the corpus's actual data (see
            :func:`~leech.constants.select_feature_channels`).
    """
    self.chunk_path = chunk_path
    self.signal_len = signal_len
    self.kmer_len = kmer_len
    self.model_type = model_type
    self.dwell_offset = dwell_offset
    self.augmentation = augmentation
    self.seq_encoding = seq_encoding
    self.signal_kmer_context = signal_kmer_context
    self.left_context = left_context
    self.right_context = right_context
    self._strict_window = strict_window
    self._crop_pad_warned = False
    self._time_mask_bases = time_mask_bases
    self._time_mask_count = time_mask_count
    self._shift_max_bases = shift_max_bases
    self._feature_noise_scale = feature_noise_scale
    self._standardize_features = standardize_features
    # Name -> row index in the recorded feature-channel list (issue
    # #358), resolved once here rather than per-batch. `None` when a
    # name is absent from the list (a custom `--feature-channels` run
    # that dropped it, or a channel that needs a k-mer table the run
    # didn't configure) -- `_apply_time_stretch` skips the corresponding
    # transform rather than guessing at a position.
    _fc_names = (
        list(feature_channel_names)
        if feature_channel_names is not None
        else list(DEFAULT_FEATURE_CHANNELS)
    )
    self._dwell_idx = _fc_names.index("dwell") if "dwell" in _fc_names else None
    self._dwell_log_idx = _fc_names.index("dwell_log") if "dwell_log" in _fc_names else None
    self._dwell_mean_idx = _fc_names.index("dwell_mean") if "dwell_mean" in _fc_names else None
    self._time_stretch_range = (
        tuple(time_stretch_range) if time_stretch_range is not None else (1.0, 1.0)
    )
    if self._time_stretch_range != (1.0, 1.0):
        lo, hi = self._time_stretch_range
        if lo <= 0 or hi <= 0 or lo > hi:
            raise ValueError(
                f"time_stretch_range must be a positive (min, max) with min <= max, "
                f"got {self._time_stretch_range}"
            )
        if self._forces_per_sample_fetch():
            raise ValueError(
                "time_stretch_range is only implemented on the batched __getitems__ "
                "fetch path, which shift_max_bases and time_mask_bases both bypass "
                "(they draw one offset per sample and fall back to the per-sample "
                "__getitem__ path). Disable one or the other."
            )
        if dwell_template_table is not None:
            # The 20 template ratio rows are computed once, at
            # construction, as dwell / expected -- time-stretch then
            # rescales `dwell` per sample without touching them, so under
            # stretch they silently stop equalling dwell / expected
            # (issue #368). Refuse the combination rather than accept it
            # quietly, same shape as the shift_max_bases/time_mask_bases
            # refusal just above.
            raise ValueError(
                "time_stretch_range is incompatible with dwell_template_table: "
                "the precomputed dwell-template ratio channels are not rescaled "
                "by time-stretch, so they would silently disagree with a "
                "stretched 'dwell' channel. Disable one or the other."
            )

    # Load dwell template table for 20-channel AA template features
    self._dwell_templates: np.ndarray | None = None
    self._template_min_pos: int = 0
    self._template_max_pos: int = 0
    self._template_aa_order: list[str] = []
    self._dwell_template_table_path: Path | None = None
    self.motif_offset = motif_offset
    self.dwell_template_motif_offset: int | None = None
    self.dwell_template_motif: str | None = None
    self.dwell_template_positions: tuple[int, int] | None = None
    self.dwell_template_header: dict[str, str] = {}
    self.dwell_template_uncovered_columns: int | None = None
    if dwell_template_table is not None:
        self._load_dwell_templates(Path(dwell_template_table))

    self._needs_features = requires_features(model_type)
    # Cached like _needs_features above: for a TOML/Graph architecture,
    # wide_features() re-resolves the config's `[params]` (dict build +
    # eval of every "${...}" expression) on every call, and the
    # row-wise fallback path calls it once per chunk.
    self._wide_features = wide_features(model_type)

    # Use pre-loaded chunks or load from file. Loading from a path streams
    # the per-chunk arrays out of the npz a row block at a time instead of
    # holding a full numpy copy alongside the tensors built from it (#211);
    # pre-loaded chunks have already paid that cost.
    self._array_stream: _ArrayStream | None = None
    self._npz_members: set[str] = set()
    self._s2s_csr: tuple[np.ndarray, np.ndarray] | None = None
    self._s2s_rows: np.ndarray | None = None
    if chunks is not None:
        logger.info(f"Using {len(chunks)} pre-loaded chunks (skipping disk I/O)")
        self.chunks = chunks
    elif chunk_path is not None:
        self._load_from_path(
            Path(chunk_path), signal_mode=signal_mode, seq_encoding=seq_encoding
        )
    else:
        raise ValueError("Either chunk_path or chunks must be provided")

    # Filter chunks with valid numeric labels (label_int). The columnar
    # path applied this at load, recording the same mask so npz rows stay
    # aligned with self.chunks — a mismatch here would pair signals with
    # the wrong labels silently.
    if not isinstance(self.chunks, ChunkTable):
        self.chunks = [c for c in self.chunks if c["label_int"] is not None]

    if len(self.chunks) == 0:
        raise ValueError(f"No valid chunks found{f' in {chunk_path}' if chunk_path else ''}")

    # Channel ablation (issue #358 follow-up): resolve and apply a
    # `selected_feature_channels` subset, once, against the corpus's
    # ACTUAL stored row count -- not the (possibly wider, if a `kmer_*`
    # name was recorded but never computed) nominal recorded list. Gated
    # entirely on `selected_feature_channels is not None` so an unset
    # corpus runs none of this new code and stays byte-identical to
    # before it existed.
    self._feature_row_idx: np.ndarray | None = None
    self.effective_feature_channels: list[str] | None = None
    if self._needs_features:
        if selected_feature_channels is not None:
            actual_count = self._stored_feature_row_count()
            if actual_count is None:
                raise ValueError(
                    "selected_feature_channels was requested but this dataset's "
                    "stored feature row count could not be determined"
                    f"{f' ({chunk_path})' if chunk_path else ''}"
                )
            available = resolve_stored_feature_channels(_fc_names, actual_count)
            row_idx = select_feature_channels(available, selected_feature_channels)
            self._feature_row_idx = np.asarray(row_idx, dtype=np.int64)
            effective_names = list(selected_feature_channels)
            # The tensor's channel axis now has the SELECTED order, not
            # the corpus's recorded order -- recompute the by-name
            # indices _apply_time_stretch uses against it.
            self._dwell_idx = (
                effective_names.index("dwell") if "dwell" in effective_names else None
            )
            self._dwell_log_idx = (
                effective_names.index("dwell_log") if "dwell_log" in effective_names else None
            )
            self._dwell_mean_idx = (
                effective_names.index("dwell_mean") if "dwell_mean" in effective_names else None
            )
            self.effective_feature_channels = effective_names
        else:
            self.effective_feature_channels = _fc_names

    # Resolve the dwell-template append's row index by NAME, not by
    # convention (issue #366): a --feature-channels reorder can put
    # `dwell` at any row, and dividing row 0 regardless silently computes
    # nonsense ratios for every non-default channel order. Also check the
    # table's position coverage of the corpus's feature window, once,
    # here rather than per chunk (issue #367).
    self._dwell_template_row: int | None = None
    if self._dwell_templates is not None:
        if self.effective_feature_channels is None or (
            "dwell" not in self.effective_feature_channels
        ):
            raise ValueError(
                "dwell_template_table requires a 'dwell' feature channel, but "
                f"the effective feature channels are "
                f"{self.effective_feature_channels!r}"
            )
        self._dwell_template_row = self.effective_feature_channels.index("dwell")
        logger.info(
            "dwell-template append resolved dwell channel to row %d of %s",
            self._dwell_template_row,
            self.effective_feature_channels,
        )

        kmer_context = self.kmer_len // 2
        fw_source = self.chunks if isinstance(self.chunks, ChunkTable) else self.chunks[0]
        raw_feat_start, raw_feat_end = feature_window_from_metadata(fw_source, kmer_context)
        feat_start, feat_end, _ = resolve_feature_window(
            raw_feat_start, raw_feat_end, kmer_context
        )
        self.dwell_template_uncovered_columns = check_dwell_template_coverage(
            self._dwell_template_table_path,
            self._template_min_pos,
            self._template_max_pos,
            feat_start,
            feat_end,
        )

    # Pre-tensorize: encode sequences, labels, signals, and features once.
    # Each accumulator fills one preallocated contiguous tensor — see
    # _TensorFill for why stacking a list instead doubles the peak.
    n_chunks = len(self.chunks)
    fill_encoded_seqs = _TensorFill("Encoded-sequence", n_chunks)
    fill_labels = _TensorFill("Label", n_chunks)
    fill_signals = _TensorFill("Signal", n_chunks)
    fill_features = _TensorFill("Feature", n_chunks)
    fill_confounds = _TensorFill("Confound", n_chunks)
    fill_cl_targets = _TensorFill("CL target", n_chunks)
    fill_noise_rates = _TensorFill("Noise rate", n_chunks)
    fill_focus_idx = _TensorFill("Focus-idx", n_chunks)
    self._encoded_seqs: list[torch.Tensor] = []
    self._labels: list[torch.Tensor] = []
    self._signals: list[torch.Tensor] = []
    self._features: list[torch.Tensor] = []
    self._confound_encoder = confound_encoder
    self._has_confound = confound_encoder is not None
    self._confound_labels: list[torch.Tensor] = []
    self._cl_regression = cl_regression
    self._cl_targets: list[torch.Tensor] = []
    self._label_noise_rates = label_noise_rates or {}
    self._has_noise_rates = bool(label_noise_rates)
    self._noise_rates: list[torch.Tensor] = []

    # Determine effective encoding, from the whole corpus rather than from
    # chunk 0 (#230). A corpus carries the signal_kmer inputs for every
    # chunk or for none: none is the version-skew case the fallback exists
    # for, and anything in between is damage.
    self._effective_seq_encoding = seq_encoding
    if seq_encoding == "signal_kmer":
        n_covered, n_total = self._signal_kmer_coverage()
        if n_covered < n_total:
            n_missing = n_total - n_covered
            detail = (
                f"{n_missing} of {n_total} chunks ({n_missing / n_total:.1%}) lack "
                f"seq_to_sig_map/sequence_with_kmer_context"
                f"{f' in {chunk_path}' if chunk_path else ''}"
            )
            if n_covered:
                # Ragged, not legacy — and no automatic choice is right.
                # Encoding the uncovered rows anyway gives them all-zero
                # sequence channels; switching the whole corpus to
                # base_onehot on the strength of a few bad rows throws the
                # encoding away for every good one. Both are the silent
                # representation change this guard exists to prevent.
                raise ValueError(
                    f"seq_encoding='signal_kmer': {detail}. A corpus carries "
                    "base-to-signal maps for every chunk or for none; re-prepare "
                    "it, or ask for --seq-encoding base_onehot explicitly."
                )
            if not allow_encoding_fallback:
                raise ValueError(
                    f"seq_encoding='signal_kmer' was requested but {detail}. "
                    "Re-prepare the corpus with a leech version that writes "
                    "base-to-signal maps, or ask for --seq-encoding base_onehot "
                    "explicitly."
                )
            logger.warning("%s; falling back to base_onehot encoding", detail)
            self._effective_seq_encoding = "base_onehot"
            self._s2s_csr = None

    # Detect signal_residual channel and apply signal_mode
    self._signal_mode = signal_mode
    if self._array_stream is not None:
        # Arrays were deferred, so presence is a property of the file.
        self._has_signal_residual = bool(
            {"signal_residuals_flat", "signal_residuals"} & self._npz_members
        )
    else:
        self._has_signal_residual = self.chunks[0].get("signal_residual") is not None
    if signal_mode == "both" and self._has_signal_residual:
        self.signal_channels = 2
    else:
        self.signal_channels = 1

    # Detect multi-class: if any label_int > 1, use long dtype for
    # CrossEntropyLoss. Off the column when there is one — the generator
    # form builds a row view per chunk, 150 ms per 200k chunks for a max.
    if isinstance(self.chunks, ChunkTable):
        max_label = int(self.chunks.require_values("label_int").max())
    else:
        max_label = max(c["label_int"] for c in self.chunks)
    self._multiclass = max_label > 1

    # For signal_kmer encoding, the on-the-fly inputs are a few hundred
    # bytes/chunk (seq_ints int8 + seq_to_sig_map int32) vs ~77 KB/chunk
    # for the encoded output — orders of magnitude smaller. We stash the
    # compact inputs here and encode lazily: `__getitems__` calls
    # `encode_signal_kmer_batch` once per DataLoader batch (rayon-parallel
    # in Rust, issue #260) rather than looping the single-row encoder once
    # per chunk; `__getitem__`'s single-item path still calls the
    # single-row `encode_signal_kmer`. base_onehot stays eagerly
    # tensorized (88 floats/chunk; not worth deferring).
    self._seq_ints: list[np.ndarray] = []
    self._seq_to_sig: list[np.ndarray] = []
    self._seq_ints_tensor: torch.Tensor | None = None

    # Arrays come either from the chunk dicts (pre-loaded / legacy corpus)
    # or a row-block stream over the npz. Both fill the same accumulators.
    # A streamed corpus is handled a whole block at a time: the arrays
    # arrive in blocks of ~1,500 rows, and taking them apart to prepare one
    # row at a time cost 58-67 us per chunk — six to seven minutes of
    # single-threaded startup on a 6.7M-chunk corpus, none of it I/O.
    fills = {
        "signals": fill_signals,
        "encoded_seqs": fill_encoded_seqs,
        "labels": fill_labels,
        "features": fill_features,
        "confounds": fill_confounds,
        "cl_targets": fill_cl_targets,
        "noise_rates": fill_noise_rates,
    }
    # Per-chunk focus index within the final signal_len tensor, needed only
    # by time-stretch. Computed here (not re-derived later) because the raw,
    # pre-pad/crop signal length is only available during this fill pass --
    # self.chunks' array fields are nulled out once tensorization finishes.
    if self._time_stretch_range != (1.0, 1.0):
        fills["focus_idx"] = fill_focus_idx
    if self._block_fill_supported():
        self._fill_from_blocks(fills)
    else:
        self._fill_from_rows(fills)

    # Every per-chunk tensor now lives in one contiguous buffer. That isn't
    # just for cache friendliness — it's required for fork-safety. A
    # DataLoader with num_workers > 0 forks worker processes that COW-inherit
    # the parent's address space. CPython refcounts live inside each
    # PyObject header, so a worker iterating a list of N tensors writes to N
    # separate page-resident headers and faults every page into a private
    # copy, multiplying peak RSS by (1 + num_workers). A single contiguous
    # tensor keeps its data buffer outside Python's GC, so the buffer
    # pages are genuinely shared across the fork.
    self._signals_tensor, self._signals = fill_signals.finish()
    self._encoded_seqs_tensor, self._encoded_seqs = fill_encoded_seqs.finish()

    # Compact signal_kmer inputs — only populated when encoding == signal_kmer.
    # Stacked into fork-safe int tensors. encode_signal_kmer is then called
    # lazily per-sample in __getitem__ (workers parallelize behind prefetch).
    # Chunks have variable basecalled sequence lengths near the motif, so we
    # pad to the per-array max. Padding values are chosen so the encoder
    # gracefully ignores them: seq_ints=-1 hits the encoder's `base < 0`
    # skip; seq_to_sig=signal_len makes its `sig_start < signal_len` check
    # fail, writing nothing for the padded positions.
    #
    # The block-wise filler builds the padded int8 matrix straight off the
    # text column and leaves ``_seq_ints_tensor`` set; the per-chunk path
    # leaves a list to pad here. Either way the CSR expansion below runs.
    self._seq_to_sig_tensor: torch.Tensor | None = None
    if self._effective_seq_encoding == "signal_kmer" and (
        self._seq_ints or self._seq_ints_tensor is not None
    ):
        if self._seq_ints:
            max_seq_ints_len = max(s.shape[0] for s in self._seq_ints)
            n = len(self._seq_ints)
            padded_seq_ints = np.full((n, max_seq_ints_len), -1, dtype=np.int8)
            for i, si in enumerate(self._seq_ints):
                padded_seq_ints[i, : si.shape[0]] = si
            self._seq_ints_tensor = torch.from_numpy(padded_seq_ints)
            self._seq_ints = []
        n = int(self._seq_ints_tensor.shape[0])

        if self._s2s_csr is not None:
            # Streaming path: expand every map at once from the CSR pair,
            # instead of one astype/clip per chunk.
            values, offsets = self._s2s_csr
            crop_starts = None
            if self.left_context is not None and self.right_context is not None:
                crop_starts = self._crop_starts(values, offsets) - self.left_context
            padded_s2s = _expand_seq_to_sig_csr(
                values,
                offsets,
                self._s2s_rows,
                signal_len=signal_len,
                crop_starts=crop_starts,
            )
            self._s2s_csr = None
        else:
            max_s2s_len = max(s.shape[0] for s in self._seq_to_sig)
            padded_s2s = np.full((n, max_s2s_len), signal_len, dtype=np.int32)
            for i, s2s in enumerate(self._seq_to_sig):
                padded_s2s[i, : s2s.shape[0]] = s2s
        self._seq_to_sig_tensor = torch.from_numpy(padded_s2s)
        self._seq_to_sig = []

    self._labels_tensor, self._labels = fill_labels.finish()

    self._features_tensor: torch.Tensor | None = None
    if self._needs_features:
        self._features_tensor, self._features = fill_features.finish()

    self._confound_labels_tensor: torch.Tensor | None = None
    if self._has_confound:
        self._confound_labels_tensor, self._confound_labels = fill_confounds.finish()

    self._cl_targets_tensor: torch.Tensor | None = None
    if self._cl_regression:
        self._cl_targets_tensor, self._cl_targets = fill_cl_targets.finish()

    self._noise_rates_tensor: torch.Tensor | None = None
    if self._has_noise_rates:
        self._noise_rates_tensor, self._noise_rates = fill_noise_rates.finish()

    self._focus_idx_tensor: torch.Tensor | None = None
    if self._time_stretch_range != (1.0, 1.0):
        self._focus_idx_tensor, _leftover_focus_idx = fill_focus_idx.finish()
        if _leftover_focus_idx:
            # A per-chunk scalar column never disagrees in shape, so this
            # should be unreachable -- but if it ever is, time-stretch has
            # no per-row focus to anchor on, and _apply_time_stretch would
            # silently fall back to a wrong constant. Fail loudly instead.
            raise ValueError(
                "time_stretch_range: could not build a per-chunk focus-index "
                "column (unexpected shape mismatch in _TensorFill)"
            )

    # Drop the raw numpy arrays from self.chunks now that everything has
    # been pre-tensorized. External code (samplers, label tally, feature
    # window introspection) still reads the small scalar/string fields,
    # so we keep self.chunks alive but null out the per-chunk arrays.
    # Without this, each chunk dict keeps a ~50 KB numpy view alive and
    # the same COW blowup hits during DataLoader fork.
    if not isinstance(self.chunks, ChunkTable):
        for chunk in self.chunks:
            for key in (
                "signal",
                "signal_residual",
                "dwell",
                "features",
                "seq_to_sig_map",
                "sequence_with_kmer_context",
            ):
                if key in chunk:
                    chunk[key] = None

    # Same reasoning for the streaming bookkeeping: one row per chunk each,
    # and a DataLoader that spawns workers pickles whatever is still here.
    self._s2s_csr = None
    self._s2s_rows = None
    if self._array_stream is not None:
        self._array_stream.keep = None

    # Precompute per-channel feature stds for feature noise augmentation.
    # Reuse the already-stacked features tensor when available.
    self._feature_stds: torch.Tensor | None = None
    if self._feature_noise_scale > 0 and self._needs_features:
        if self._features_tensor is not None:
            self._feature_stds = self._features_tensor.std(dim=0)  # (C, K)
        else:
            logger.warning("Feature shapes differ, feature noise disabled")
            self._feature_noise_scale = 0.0

    # Corpus-wide per-channel mean/std for --standardize-features (#283):
    # one number per feature channel, reusing the same already-stacked
    # _features_tensor as the noise pass above rather than a second scan.
    # Collapsed over both the chunk axis AND the window axis (dim 0 and
    # 2) -- unlike the noise std, which is deliberately per-position --
    # because a channel's physical scale (a dwell sample count, a
    # MAD-unit level stat, ...) is a property of the channel, not of
    # where in the window it's read.
    self.feature_mean: torch.Tensor | None = None
    self.feature_std: torch.Tensor | None = None
    if self._standardize_features and self._needs_features:
        if self._features_tensor is not None:
            self.feature_mean = self._features_tensor.mean(dim=(0, 2))  # (C,)
            self.feature_std = self._features_tensor.std(dim=(0, 2))  # (C,)
        else:
            logger.warning(
                "Feature shapes differ across chunks; --standardize-features disabled"
            )
            self._standardize_features = False

    # Approx samples per base for cross-layer shift/mask
    self._samples_per_base = signal_len / max(kmer_len, 1)

    # Whether __getitems__ can gather a batch straight out of the
    # contiguous tensors. Every field has to be one: a field that degraded
    # to a list of per-chunk tensors has no batch to gather.
    self._batched_fetch = (
        self._signals_tensor is not None
        and self._labels_tensor is not None
        and (not self._needs_features or self._features_tensor is not None)
        and (not self._has_confound or self._confound_labels_tensor is not None)
        and (not self._cl_regression or self._cl_targets_tensor is not None)
        and (not self._has_noise_rates or self._noise_rates_tensor is not None)
        and (self._time_stretch_range == (1.0, 1.0) or self._focus_idx_tensor is not None)
        and (
            (self._seq_ints_tensor is not None and self._seq_to_sig_tensor is not None)
            if self._effective_seq_encoding == "signal_kmer"
            else self._encoded_seqs_tensor is not None
        )
    )
    if self._time_stretch_range != (1.0, 1.0) and not self._batched_fetch:
        raise ValueError(
            "time_stretch_range requires the dataset to support the batched "
            "__getitems__ fetch path (contiguous per-field tensors); this corpus "
            "degraded to a per-chunk list (see the 'shapes differ' warning above "
            "if logged), which has no per-sample implementation of time-stretch."
        )

    _n_encoded = (
        self._encoded_seqs_tensor.shape[0]
        if self._encoded_seqs_tensor is not None
        else len(self._encoded_seqs)
    )
    logger.debug(
        f"Pre-tensorized {len(self.chunks)} chunks "
        f"({_n_encoded} sequences encoded, encoding={self._effective_seq_encoding})"
    )

effective_seq_encoding property

effective_seq_encoding: str

The encoding this dataset actually yields.

Differs from the requested seq_encoding only when a signal_kmer request fell back to base_onehot. That is a different model input — (36, signal_len) against (4, kmer_len) — so anything that builds a model or writes a config has to read this rather than what was asked for (#230).

Data Collation

LeechDataset also implements __getitems__, so a DataLoader fetches a whole batch in one call and gets back an already-collated dict rather than a list of samples -- one gather per field instead of one slice per sample plus a torch.stack. collate_fn passes such a dict through untouched, and still stacks a list when it gets one (the per-sample path, used for the list-fallback dataset and for the cross-layer shift/time-mask augmentations, which roll by a per-sample offset).

collate_fn

collate_fn(batch: list[dict[str, Tensor]] | dict[str, Tensor]) -> dict[str, torch.Tensor]

Collate function for DataLoader.

Parameters:

Name Type Description Default
batch list[dict[str, Tensor]] | dict[str, Tensor]

List of samples from __getitem__, or the already-collated batch LeechDataset.__getitems__ returns.

required

Returns:

Type Description
dict[str, Tensor]

Batched tensors

Source code in src/leech/dataset.py
def collate_fn(
    batch: list[dict[str, torch.Tensor]] | dict[str, torch.Tensor],
) -> dict[str, torch.Tensor]:
    """
    Collate function for DataLoader.

    Args:
        batch: List of samples from ``__getitem__``, or the already-collated
            batch ``LeechDataset.__getitems__`` returns.

    Returns:
        Batched tensors
    """
    if isinstance(batch, dict):
        # __getitems__ gathered the batch out of the contiguous tensors in one
        # go; there is nothing left to stack.
        return batch

    # Stack all tensors
    signals = torch.stack([item["signal"] for item in batch])
    sequences = torch.stack([item["sequence"] for item in batch])
    labels = torch.stack([item["label"] for item in batch])

    result = {
        "signal": signals,
        "sequence": sequences,
        "label": labels,
    }

    # Add features if present
    if "features" in batch[0]:
        features = torch.stack([item["features"] for item in batch])
        result["features"] = features

    # Add confound labels if present (adversarial training)
    if "confound_label" in batch[0]:
        result["confound_label"] = torch.stack([item["confound_label"] for item in batch])

    # Add CL regression targets if present
    if "cl_target" in batch[0]:
        result["cl_target"] = torch.stack([item["cl_target"] for item in batch])

    # Add per-sample label-noise flip rates if present (noise_corrected_bce)
    if "noise_rate" in batch[0]:
        result["noise_rate"] = torch.stack([item["noise_rate"] for item in batch])

    return result

DataLoader Sizing

Every leech DataLoader -- training, validation and evaluation -- gets its worker count from this one function, so the rules (auto on GPU, serial on CPU, never workers inside a daemonic pool worker) cannot drift between call sites.

resolve_dataloader_workers

resolve_dataloader_workers(num_workers: int, device: str, local_world_size: int = 1) -> int

Resolve how many DataLoader workers to actually use.

num_workers=0 means AUTO here, not "no workers": on CUDA it becomes AUTO_DATALOADER_WORKERS, on CPU it stays 0. Feeding a GPU from the main process serializes collate, host-to-device copy and forward pass onto one core, which is how eval test sat at 8% GPU on an A5000 (issue #205). On CPU the workers would compete with the compute for the same cores, and __getitem__ is trivially fast against pre-tensorized data, so they only add overhead.

The daemon check is not an optimization: daemonic processes (a multiprocessing.Pool worker, as in grid search) cannot spawn children, so a DataLoader with workers raises there. Every caller that builds a loader goes through this function, so that guard lives in one place.

The auto count is capped by the CPUs this process may actually run on -- sched_getaffinity, which respects the Slurm cpuset -- because a GPU job allocated 2 cores would otherwise fork 8 workers onto them and thrash. An explicit request is honoured as given; only "auto" is capped.

local_world_size divides that cap. Under --gpus N every rank sees the whole allocation through sched_getaffinity -- the cpuset is the job's, not the rank's -- so each of them would claim the full worker count and the node would carry N times as many as the cap intends.

Source code in src/leech/dataset.py
def resolve_dataloader_workers(num_workers: int, device: str, local_world_size: int = 1) -> int:
    """Resolve how many DataLoader workers to actually use.

    ``num_workers=0`` means AUTO here, not "no workers": on CUDA it becomes
    ``AUTO_DATALOADER_WORKERS``, on CPU it stays 0. Feeding a GPU from the main
    process serializes collate, host-to-device copy and forward pass onto one
    core, which is how ``eval test`` sat at 8% GPU on an A5000 (issue #205).
    On CPU the workers would compete with the compute for the same cores, and
    ``__getitem__`` is trivially fast against pre-tensorized data, so they only
    add overhead.

    The daemon check is not an optimization: daemonic processes (a
    ``multiprocessing.Pool`` worker, as in grid search) cannot spawn children,
    so a DataLoader with workers raises there. Every caller that builds a
    loader goes through this function, so that guard lives in one place.

    The auto count is capped by the CPUs this process may actually run on --
    ``sched_getaffinity``, which respects the Slurm cpuset -- because a GPU job
    allocated 2 cores would otherwise fork 8 workers onto them and thrash. An
    explicit request is honoured as given; only "auto" is capped.

    ``local_world_size`` divides that cap. Under ``--gpus N`` every rank sees
    the *whole* allocation through ``sched_getaffinity`` -- the cpuset is the
    job's, not the rank's -- so each of them would claim the full worker count
    and the node would carry N times as many as the cap intends.
    """
    import multiprocessing

    is_daemon = multiprocessing.current_process().daemon
    if is_daemon:
        effective = 0
    elif num_workers > 0:
        effective = num_workers
    elif device == "cpu":
        effective = 0
    else:
        per_rank_cpus = max(1, (_usable_cpus() - 1) // max(1, local_world_size))
        effective = min(AUTO_DATALOADER_WORKERS, per_rank_cpus)

    logger.info(
        f"DataLoader workers: {effective} "
        f"(requested={num_workers}, daemon={is_daemon}, device={device}, "
        f"local_world_size={local_world_size})"
    )
    return effective