utils
sleap_nn.data.utils
¶
Miscellaneous utility functions for data processing.
Functions:
| Name | Description |
|---|---|
check_cache_memory |
Check memory requirements for in-memory caching dataset pipeline. |
check_memory |
Return memory required for caching the image samples from a single labels object. |
embedding_detections |
|
ensure_list |
Convert the input into a list if it is not already. |
estimate_cache_memory |
Estimate memory requirements for in-memory caching dataset pipeline. |
expand_to_rank |
Expand a tensor to a target rank by adding singleton dimensions in PyTorch. |
gaussian_pdf |
Compute the PDF of an unnormalized 0-centered Gaussian distribution. |
get_symmetric_inds |
Resolve symmetric node-index pairs from a skeleton's raw symmetries. |
make_grid_vectors |
Make sampling grid vectors from image dimensions. |
superseded_predictions |
|
worker_memory_overhead_factor |
Return the per-worker in-memory-cache overhead, as a fraction of the cache. |
check_cache_memory(train_labels, val_labels, memory_buffer=0.2, num_workers=0)
¶
Check memory requirements for in-memory caching dataset pipeline.
This function determines if the system has sufficient memory for in-memory image caching, accounting for DataLoader worker processes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_labels
|
List[Labels]
|
List of |
required |
val_labels
|
List[Labels]
|
List of |
required |
memory_buffer
|
float
|
Fraction of memory to reserve as buffer. Default: 0.2 (20%). |
0.2
|
num_workers
|
int
|
Number of DataLoader worker processes. When > 0, additional memory overhead is estimated for worker process duplication. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the total memory required for caching is within available system memory, False otherwise. |
Source code in sleap_nn/data/utils.py
check_memory(labels)
¶
Return memory required for caching the image samples from a single labels object.
Estimates total memory using video.shape (which may load a single frame
lazily but caches the result) instead of decompressing every frame from HDF5.
Note
Assumes uint8 (1 byte per element), which is true for all supported sleap-io video backends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Labels
|
A |
required |
Returns:
| Type | Description |
|---|---|
int
|
Memory in bytes required to cache the image samples from the labels object. |
Source code in sleap_nn/data/utils.py
embedding_detections(lf, user_instances_only)
¶
(instances, masks) of a frame that the embedding model may train on.
This is the one reading of data_config.user_instances_only for the embedding
model type. With True, only the predictions a user label on the same frame
supersedes are left out (:func:superseded_predictions). Re-ID training data is
often predicted poses whose tracks were proofread, and those stay
PredictedInstances, so dropping every prediction would leave nothing to
train on. With False, every detection is kept.
Source code in sleap_nn/data/utils.py
ensure_list(x)
¶
estimate_cache_memory(train_labels, val_labels, num_workers=0, memory_buffer=0.2)
¶
Estimate memory requirements for in-memory caching dataset pipeline.
This function calculates the total memory needed for caching images, accounting for: - Raw image data size - Python object overhead (dictionary keys, numpy array wrappers) - DataLoader worker memory overhead (Copy-on-Write duplication on Unix systems) - General memory buffer for training overhead
When using DataLoader with num_workers > 0, worker processes are spawned via fork() on Unix systems. While Copy-on-Write (CoW) initially shares memory, Python's reference counting can trigger memory page duplication when workers access cached data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_labels
|
List[Labels]
|
List of |
required |
val_labels
|
List[Labels]
|
List of |
required |
num_workers
|
int
|
Number of DataLoader worker processes. When > 0, additional memory overhead is estimated for worker process duplication. |
0
|
memory_buffer
|
float
|
Fraction of memory to reserve as buffer for training overhead (model weights, activations, gradients, etc.). Default: 0.2 (20%). |
0.2
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Memory estimation breakdown with keys: - 'raw_cache_bytes': Raw image data size in bytes - 'python_overhead_bytes': Estimated Python object overhead - 'worker_overhead_bytes': Estimated memory for DataLoader workers - 'buffer_bytes': Memory buffer for training overhead - 'total_bytes': Total estimated memory requirement - 'available_bytes': Available system memory - 'sufficient': True if total <= available, False otherwise |
Source code in sleap_nn/data/utils.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
expand_to_rank(x, target_rank, prepend=True)
¶
Expand a tensor to a target rank by adding singleton dimensions in PyTorch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Any |
required |
target_rank
|
int
|
Rank to expand the input to. |
required |
prepend
|
bool
|
If True, singleton dimensions are added before the first axis of the data. If False, singleton dimensions are added after the last axis. |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
The expanded tensor of the same dtype as the input, but with rank |
Source code in sleap_nn/data/utils.py
gaussian_pdf(x, sigma)
¶
Compute the PDF of an unnormalized 0-centered Gaussian distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
A tensor of dtype torch.float32 with values to compute the PDF for. |
required |
sigma
|
float
|
Standard deviation of the Gaussian distribution. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A tensor of the same shape as |
Source code in sleap_nn/data/utils.py
get_symmetric_inds(skeleton)
¶
Resolve symmetric node-index pairs from a skeleton's raw symmetries.
Used by flip augmentation to swap left/right (or top/bottom) symmetric body parts after mirroring, so semantic labels stay correct.
This intentionally reads only the stable skeleton.symmetries field (each
Symmetry iterates to its two Nodes) and resolves indices via the node
ordering ourselves, rather than relying on newer sleap-io convenience
properties (symmetry_inds, symmetry_names, flipped_node_inds) that
are absent in older sleap-io versions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
skeleton
|
Skeleton
|
A |
required |
Returns:
| Type | Description |
|---|---|
List[Tuple[int, int]]
|
A list of |
Source code in sleap_nn/data/utils.py
make_grid_vectors(image_height, image_width, output_stride=1)
¶
Make sampling grid vectors from image dimensions.
This is a useful function for creating the x- and y-vectors that define a sampling grid over an image space. These vectors can be used to generate a full meshgrid or for equivalent broadcasting operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_height
|
int
|
Height of the image grid that will be sampled, specified as a scalar integer. |
required |
image_width
|
int
|
width of the image grid that will be sampled, specified as a scalar integer. |
required |
output_stride
|
int
|
Sampling step size, specified as a scalar integer. This can be used to specify a sampling grid that has a smaller shape than the image grid but with values span the same range. This can be thought of as the reciprocal of the output scale, i.e., it will induce subsampling when set to values greater than 1. |
1
|
Returns:
| Type | Description |
|---|---|
Tuple[Tensor, Tensor]
|
Tuple of grid vectors (xv, yv). These are tensors of dtype tf.float32 with shapes (grid_width,) and (grid_height,) respectively. The grid dimensions are calculated as: grid_width = image_width // output_stride grid_height = image_height // output_stride |
Source code in sleap_nn/data/utils.py
superseded_predictions(lf)
¶
ids of the frame's predictions that a user label on the same frame supersedes.
sleap-io's own rule, from LabeledFrame.unused_predictions and
unused_predicted_masks:
- A
PredictedInstanceis superseded when a userInstanceon the frame has its track. When no instance on the frame has a track, it is superseded when a userInstancelinks to it throughfrom_predicted. - A
PredictedSegmentationMaskis superseded when a user mask links to it throughfrom_predictedor overlaps it (bbox centroids within 5 px).
Every other prediction (on a frame nobody proofread, or an animal the user did not relabel) stands on its own.
Source code in sleap_nn/data/utils.py
worker_memory_overhead_factor()
¶
Return the per-worker in-memory-cache overhead, as a fraction of the cache.
Each DataLoader worker adds a share of the image cache on top of the parent process, and how big that share is depends on the multiprocessing start method:
- Linux forks, so the cache starts out shared Copy-on-Write; Python refcounting still dirties pages, costing roughly a quarter of it.
- macOS / Windows spawn (macOS has defaulted to spawn since Python 3.8), so the cache dict is pickled into each worker, which then holds its own full copy: measured at 1.0x the cache per worker on both Windows 11 and macOS (worker private memory with the in-memory cache minus with the disk cache).
Kept as a single named constant because both the memory estimate and the
num_workers: "auto" resolver (which inverts that estimate to find how
many workers fit) must agree on it.
Returns:
| Type | Description |
|---|---|
float
|
Fraction of |