Machine Learning API¶
ML utilities including dataloaders and tokenizers.
DataLoaders¶
slaf.ml.dataloaders ¶
Classes¶
SLAFDataLoader ¶
High-performance DataLoader for SLAF data optimized for ML training.
SLAFDataLoader provides efficient streaming of single-cell data for machine learning applications with multiple loading strategies for different use cases. It uses async batch processing and provides device-agnostic CPU tensor output for maximum training flexibility.
Key Features
- Multiple tokenization strategies (GeneFormer, scGPT)
- Multiple loading modes for different entropy requirements:
- Mixture of Scanners (MoS): Maximum entropy, best randomization (default)
- Fragment-based loading: Higher entropy, moderate performance
- Sequential loading: Fastest, lowest entropy
- Pre-tokenized sequences for maximum performance (tokenized mode)
- Raw data output for external processing (raw mode)
- Device-agnostic CPU tensor output
- Async batch processing with background prefetching
- Memory-efficient streaming
- Multi-epoch training support
- Comprehensive error handling and validation
Loading Modes
- Mixture of Scanners (default): Randomly samples from multiple fragment generators for maximum entropy and randomization (88% of random entropy)
- Fragment-based: Loads complete Lance fragments for higher data entropy
- Sequential: Loads contiguous Lance batches for maximum throughput
Examples:
>>> # Basic usage with default settings (MoS loading)
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> dataloader = SLAFDataLoader(slaf_array)
>>> for batch in dataloader:
... print(f"Batch shape: {batch['input_ids'].shape}")
... print(f"Cell IDs: {batch['cell_ids']}")
... break
Batch shape: torch.Size([32, 2048])
Cell IDs: tensor([0, 1, 2, ..., 29, 30, 31])
>>> print(f"MoS enabled: {dataloader.use_mixture_of_scanners}")
MoS enabled: True
>>> # Sequential loading for maximum throughput
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... use_mixture_of_scanners=False,
... by_fragment=False
... )
>>> print(f"Sequential loading: {not dataloader.use_mixture_of_scanners}")
Sequential loading: True
>>> # Fragment-based loading for higher entropy
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... use_mixture_of_scanners=False,
... by_fragment=True
... )
>>> print(f"Fragment-based loading: {dataloader.by_fragment}")
Fragment-based loading: True
>>> # Raw mode for external processing
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... raw_mode=True
... )
>>> for batch in dataloader:
... print(f"Raw data type: {type(batch['x'])}")
... break
Raw data type: <class 'polars.dataframe.frame.DataFrame'>
>>> # Multi-epoch training
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... n_epochs=5
... )
>>> print(f"Number of epochs: {dataloader.n_epochs}")
Number of epochs: 5
>>> # Custom configuration for training
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... tokenizer_type="scgpt",
... batch_size=64,
... max_genes=1024
... )
>>> print(f"Tokenizer type: {dataloader.tokenizer_type}")
Tokenizer type: scgpt
>>> # Training loop example
>>> for batch_idx, batch in enumerate(dataloader):
... input_ids = batch["input_ids"]
... attention_mask = batch["attention_mask"]
... cell_ids = batch["cell_ids"]
... # Your training code here
... if batch_idx >= 2: # Just test first few batches
... break
>>> print("Training loop completed")
Training loop completed
>>> # Error handling for invalid tokenizer type
>>> try:
... dataloader = SLAFDataLoader(slaf_array, tokenizer_type="invalid")
... except ValueError as e:
... print(f"Error: {e}")
Error: Unsupported tokenizer type: invalid
Source code in slaf/ml/dataloaders.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 | |
Functions¶
__init__(slaf_array: SLAFArray, tokenizer_type: str = 'geneformer', batch_size: int = 32, max_genes: int = 2048, vocab_size: int = 50000, n_expression_bins: int = 10, n_epochs: int = 1, raw_mode: bool = False, verbose: bool = True, batches_per_chunk: int = 1, by_fragment: bool = True, use_mixture_of_scanners: bool = True, n_scanners: int = 16, prefetch_batch_size: int = 4194304) ¶
Initialize the SLAF DataLoader with training configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slaf_array | SLAFArray | SLAFArray instance containing the single-cell data. Must be a valid SLAFArray with proper Lance dataset structure. | required |
tokenizer_type | str | Tokenization strategy to use. Options: "geneformer", "scgpt". Geneformer uses ranked gene sequences, scGPT uses interleaved gene-expression pairs. Ignored when raw_mode=True. | 'geneformer' |
max_genes | int | Maximum number of genes to include in each cell's tokenization. For Geneformer: same as sequence length. For scGPT: number of gene-expression pairs (sequence length = 2*max_genes+2). | 2048 |
vocab_size | int | Size of the tokenizer vocabulary. Higher values allow more genes but use more memory. Range: 1000-100000, default: 50000. | 50000 |
n_expression_bins | int | Number of expression level bins for scGPT discretization. Higher values provide finer expression resolution. Range: 1-1000, default: 10. | 10 |
batch_size | int | Number of cells per batch. Larger batches use more memory but may improve training efficiency. Range: 1-512, default: 32. | 32 |
n_epochs | int | Number of epochs to run. The generator will automatically reset after each epoch, enabling multi-epoch training on small datasets. Default: 1. | 1 |
raw_mode | bool | If True, return raw cell × gene data as Polars DataFrames instead of pre-tokenized sequences. This bypasses tokenization and windowing for maximum flexibility. Default: False. | False |
batches_per_chunk | int | Number of Lance batches to load per chunk for sequential loading. Higher values use more memory but may improve throughput. Range: 1-200, default: 1 (optimized for MoS). Only used when by_fragment=False. | 1 |
by_fragment | bool | If True, use fragment-based loading instead of batch-based loading. Fragment-based loading provides higher entropy but may be slightly slower. Automatically enabled when use_mixture_of_scanners=True. Default: True (enabled for MoS). | True |
use_mixture_of_scanners | bool | If True, use mixture of scanners (MoS) approach for higher entropy by randomly sampling from multiple fragment generators. This provides the best randomization and is now the default for foundation model training. Default: True. | True |
n_scanners | int | Number of fragment generators to sample from simultaneously when using MoS. Higher values provide better entropy but use more memory. Range: 1-100, default: 16. Only used when use_mixture_of_scanners=True. | 16 |
prefetch_batch_size | int | Target number of rows to load per prefetch batch when using MoS. Higher values improve throughput but use more memory. Range: 1000-10000000, default: 4194304. Only used when use_mixture_of_scanners=True. | 4194304 |
verbose | bool | If True, print detailed timing and progress information. If False, suppress all SLAF internal prints for clean output. Default: True. | True |
Raises:
| Type | Description |
|---|---|
ValueError | If tokenizer_type is not supported or parameters are invalid. |
RuntimeError | If PyTorch is not available or datasets module is missing. |
TypeError | If slaf_array is not a valid SLAFArray instance. |
ImportError | If required dependencies are not available. |
Loading Strategy Selection Guide
- For foundation model training: Use default settings (MoS provides 88% random entropy)
- For maximum throughput: Set use_mixture_of_scanners=False, by_fragment=False
- For external processing: Set raw_mode=True
Examples:
>>> # Basic initialization (MoS is now default)
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> dataloader = SLAFDataLoader(slaf_array)
>>> print(f"Batch size: {dataloader.batch_size}")
Batch size: 32
>>> print(f"MoS enabled: {dataloader.use_mixture_of_scanners}")
MoS enabled: True
>>> # Sequential loading for maximum throughput
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... use_mixture_of_scanners=False,
... by_fragment=False
... )
>>> print(f"Sequential loading: {not dataloader.use_mixture_of_scanners}")
Sequential loading: True
>>> # Fragment-based loading for higher entropy
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... use_mixture_of_scanners=False,
... by_fragment=True
... )
>>> print(f"Fragment-based loading: {dataloader.by_fragment}")
Fragment-based loading: True
>>> # Raw mode for external processing
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... raw_mode=True
... )
>>> print(f"Raw mode: {dataloader.raw_mode}")
Raw mode: True
>>> # Error handling for invalid parameters
>>> try:
... dataloader = SLAFDataLoader(slaf_array, n_scanners=0)
... except ValueError as e:
... print(f"Error: {e}")
Error: n_scanners must be at least 1
Source code in slaf/ml/dataloaders.py
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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | |
Functions¶
get_optimal_device() ¶
Get the optimal device for PyTorch operations (CUDA > MPS > CPU).
This function determines the best available device for PyTorch operations by checking for CUDA first, then MPS (Apple Silicon), and falling back to CPU if neither is available.
Returns:
| Type | Description |
|---|---|
| torch.device | None: The optimal device, or None if PyTorch is not available. |
Examples:
>>> # Check optimal device
>>> device = get_optimal_device()
>>> print(f"Optimal device: {device}")
Optimal device: cuda
>>> # Device priority (CUDA > MPS > CPU)
>>> # If CUDA is available: cuda
>>> # If MPS is available but not CUDA: mps
>>> # If neither: cpu
>>> device = get_optimal_device()
>>> if device.type == "cuda":
... print("Using CUDA GPU")
... elif device.type == "mps":
... print("Using Apple Silicon GPU")
... else:
... print("Using CPU")
Using CUDA GPU
>>> # Handle PyTorch not available
>>> # This would return None if PyTorch is not installed
>>> device = get_optimal_device()
>>> if device is None:
... print("PyTorch not available")
... else:
... print(f"Device available: {device}")
Device available: cuda
Source code in slaf/ml/dataloaders.py
get_device_info() ¶
Get comprehensive device information for debugging.
This function returns detailed information about the available PyTorch devices, including CUDA and MPS availability, device counts, and capabilities. Useful for debugging device-related issues and understanding the system configuration.
Returns:
| Name | Type | Description |
|---|---|---|
dict | Device information dictionary containing: - torch_available: Whether PyTorch is available - cuda_available: Whether CUDA is available - mps_available: Whether MPS (Apple Silicon) is available - optimal_device: String representation of the optimal device - cuda_device_count: Number of CUDA devices (if CUDA available) - cuda_device_name: Name of the first CUDA device (if available) - cuda_device_capability: Compute capability of first CUDA device |
Examples:
>>> # Get device information
>>> info = get_device_info()
>>> print(f"PyTorch available: {info['torch_available']}")
PyTorch available: True
>>> print(f"CUDA available: {info['cuda_available']}")
CUDA available: True
>>> print(f"Optimal device: {info['optimal_device']}")
Optimal device: cuda
>>> # Check CUDA details
>>> if info['cuda_available']:
... print(f"CUDA devices: {info['cuda_device_count']}")
... print(f"Device name: {info['cuda_device_name']}")
... print(f"Capability: {info['cuda_device_capability']}")
CUDA devices: 1
Device name: NVIDIA GeForce RTX 3080
Capability: (8, 6)
>>> # Check MPS availability
>>> print(f"MPS available: {info['mps_available']}")
MPS available: False
>>> # Handle PyTorch not available
>>> # This would show torch_available: False if PyTorch is not installed
>>> info = get_device_info()
>>> if not info['torch_available']:
... print("PyTorch not available")
... else:
... print("PyTorch is available")
PyTorch is available
Source code in slaf/ml/dataloaders.py
slaf.ml.tiledb_dataloaders ¶
TileDB Dataloader for Single-Cell Data
This module provides efficient streaming of single-cell data from TileDB SOMA format using PyTorch IterableDataset and DataLoader. It follows a similar pattern to SLAF's dataloader implementation for consistency and performance comparison.
Classes¶
TileDBPrefetchBatch dataclass ¶
Container for a batch of TileDB data with metadata.
This dataclass holds a processed batch of TileDB SOMA data along with associated metadata for tracking performance and debugging. It serves as the primary data structure passed between the batch processor and the async prefetcher.
Attributes:
| Name | Type | Description |
|---|---|---|
batch_id | int | Unique identifier for this batch within the current epoch. |
batch_df | DataFrame | Polars DataFrame containing the cell-gene expression data with columns: cell_integer_id, gene_integer_id, value. |
cell_integer_ids | list[int] | List of unique cell IDs present in this batch. |
process_time | float | Time taken to process this batch (in seconds). |
memory_mb | float | Memory usage at the time of batch creation (in MB). |
Examples:
>>> # Create a batch container
>>> batch = TileDBPrefetchBatch(
... batch_id=0,
... batch_df=df,
... cell_integer_ids=[0, 1, 2, 3],
... process_time=0.1,
... memory_mb=128.5
... )
>>> print(f"Batch {batch.batch_id} has {len(batch.cell_integer_ids)} cells")
Batch 0 has 4 cells
Source code in slaf/ml/tiledb_dataloaders.py
TileDBBatchProcessor ¶
High-performance batch processor for TileDB SOMA data with multiple loading strategies.
TileDBBatchProcessor provides efficient streaming and processing of single-cell data from TileDB SOMA format. It supports multiple loading strategies including Mixture of Scanners (MoS) for maximum entropy and sequential loading for maximum throughput.
Key Features
- Multiple loading strategies:
- Mixture of Scanners (MoS): Random sampling from multiple generators for maximum entropy and randomization (default)
- Sequential loading: Contiguous data loading for maximum throughput
- Streaming data processing with configurable batch sizes
- Built-in shuffling strategies for data randomization
- Multi-epoch training support with automatic epoch transitions
- Comprehensive timing and memory monitoring
- Error handling and recovery mechanisms
- Configurable prefetch batch sizes for different dataset sizes
Loading Strategies
- Mixture of Scanners (default): Randomly samples from multiple fragment generators for maximum entropy and randomization
- Sequential: Loads contiguous data chunks for maximum throughput
Examples:
>>> # Basic usage with default MoS strategy
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... batch_size=32,
... prefetch_batch_size=100
... )
>>> batch = processor.load_prefetch_batch()
>>> print(f"Loaded batch with {len(batch.cell_integer_ids)} cells")
Loaded batch with 100 cells
>>> # Sequential loading for maximum throughput
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False,
... batch_size=64
... )
>>> print(f"MoS enabled: {processor.use_mixture_of_scanners}")
MoS enabled: False
>>> # Multi-epoch training
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... n_epochs=3
... )
>>> print(f"Number of epochs: {processor.n_epochs}")
Number of epochs: 3
Source code in slaf/ml/tiledb_dataloaders.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 | |
Functions¶
__init__(tiledb_path: str, batch_size: int = 32, prefetch_batch_size: int = 100, seed: int = 42, n_epochs: int = 1, verbose: bool = True, log_metrics: bool = False, use_mixture_of_scanners: bool = True, n_readers: int = 50, n_scanners: int = 8) ¶
Initialize the TileDB batch processor with training configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiledb_path | str | Path to the TileDB SOMA experiment directory. Must contain a valid SOMA experiment with RNA measurement data. | required |
batch_size | int | Number of cells per training batch. Larger batches use more memory but may improve training efficiency. Range: 1-512, default: 32. | 32 |
prefetch_batch_size | int | Number of cells to load per prefetch batch from TileDB. Higher values improve throughput but use more memory. Range: 10-10000, default: 100. | 100 |
seed | int | Random seed for reproducible shuffling and MoS sampling. Used for consistent data ordering across runs. Default: 42. | 42 |
n_epochs | int | Number of epochs to run. The processor will automatically reset after each epoch, enabling multi-epoch training. Default: 1. | 1 |
verbose | bool | If True, print detailed timing and progress information. If False, suppress all internal prints for clean output. Default: True. | True |
log_metrics | bool | If True, collect detailed timing metrics for performance analysis. Metrics include loading time, shuffle time, and memory usage. Default: False. | False |
use_mixture_of_scanners | bool | If True, use MoS strategy for higher entropy by randomly sampling from multiple fragment generators. Provides better randomization for foundation model training. Default: True. | True |
n_readers | int | Total number of fragment generators to create when using MoS. Higher values provide better entropy but use more memory. Range: 1-1000, default: 50. | 50 |
n_scanners | int | Number of active scanners to sample from simultaneously when using MoS. Higher values provide better entropy but use more memory. Range: 1-100, default: 8. | 8 |
Raises:
| Type | Description |
|---|---|
ImportError | If TileDB SOMA is not available. |
ValueError | If MoS parameters are invalid (n_readers < 1, n_scanners < 1, or n_scanners > n_readers). |
RuntimeError | If the TileDB experiment cannot be opened or is invalid. |
Examples:
>>> # Basic initialization with default MoS strategy
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... batch_size=32,
... prefetch_batch_size=100
... )
>>> print(f"Total cells: {processor.total_cells}")
Total cells: 50000
>>> # Sequential loading for maximum throughput
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False,
... batch_size=64
... )
>>> print(f"MoS enabled: {processor.use_mixture_of_scanners}")
MoS enabled: False
>>> # High-entropy MoS configuration
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... n_readers=100,
... n_scanners=16
... )
>>> print(f"MoS readers: {processor.n_readers}, scanners: {processor.n_scanners}")
MoS readers: 100, scanners: 16
Source code in slaf/ml/tiledb_dataloaders.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 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 | |
reset_for_epoch(epoch: int) -> None ¶
Reset the processor for a new epoch.
This method resets the batch processor state to start a new epoch, including resetting batch counters, MoS generator positions, and shuffling seeds. It is called automatically during multi-epoch training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch | int | The epoch number to start (0-based indexing). Must be 0 <= epoch < n_epochs. | required |
Raises:
| Type | Description |
|---|---|
ValueError | If epoch is invalid (negative or >= n_epochs). |
Examples:
>>> # Reset for epoch 1
>>> processor = TileDBBatchProcessor("path/to/experiment", n_epochs=3)
>>> processor.reset_for_epoch(1)
>>> print(f"Current epoch: {processor.current_epoch}")
Current epoch: 1
>>> # Invalid epoch raises error
>>> try:
... processor.reset_for_epoch(5) # n_epochs=3
... except ValueError as e:
... print(f"Error: {e}")
Error: Invalid epoch 5. Must be 0 <= epoch < 3
Source code in slaf/ml/tiledb_dataloaders.py
load_prefetch_batch() -> TileDBPrefetchBatch ¶
Load and process a chunk of TileDB data into batches using configured strategy.
This method loads a batch of data from TileDB SOMA format, applies shuffling, and returns a processed batch ready for training. It supports both MoS and sequential loading strategies and handles epoch transitions automatically.
The method performs the following steps: 1. Load data from TileDB using the configured strategy (MoS or sequential) 2. Convert Arrow data to Polars DataFrame 3. Apply shuffling strategy for data randomization 4. Return processed batch with metadata
Returns:
| Name | Type | Description |
|---|---|---|
TileDBPrefetchBatch | TileDBPrefetchBatch | Processed batch containing: - batch_df: Polars DataFrame with cell-gene expression data - cell_integer_ids: List of unique cell IDs in the batch - process_time: Time taken to process the batch - memory_mb: Memory usage at batch creation time |
Raises:
| Type | Description |
|---|---|
StopIteration | When all epochs are completed and no more data is available. |
RuntimeError | If TileDB data loading fails. |
Examples:
>>> # Load a batch with MoS strategy
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=True
... )
>>> batch = processor.load_prefetch_batch()
>>> print(f"Batch {batch.batch_id} has {len(batch.cell_integer_ids)} cells")
Batch 0 has 100 cells
>>> # Load a batch with sequential strategy
>>> processor = TileDBBatchProcessor(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False
... )
>>> batch = processor.load_prefetch_batch()
>>> print(f"Sequential batch shape: {batch.batch_df.shape}")
Sequential batch shape: (100, 3)
>>> # Handle epoch completion
>>> processor = TileDBBatchProcessor("path/to/experiment", n_epochs=1)
>>> try:
... while True:
... batch = processor.load_prefetch_batch()
... print(f"Processed batch {batch.batch_id}")
... except StopIteration:
... print("All epochs completed")
All epochs completed
Source code in slaf/ml/tiledb_dataloaders.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 | |
TileDBAsyncPrefetcher ¶
Asynchronous prefetcher for TileDB batch processing with background loading.
TileDBAsyncPrefetcher provides background batch processing and prefetching for TileDB data to improve training throughput. It runs a separate worker thread that continuously loads and processes batches while the main training loop consumes pre-processed data.
Key Features
- Background batch processing in separate worker thread
- Configurable queue size for memory management
- Comprehensive performance monitoring and statistics
- Automatic epoch transition handling
- Graceful shutdown and cleanup
- Real-time rate monitoring and reporting
- Error handling and recovery
The prefetcher maintains a queue of pre-processed batches and provides statistics about loading rates, memory usage, and processing times.
Examples:
>>> # Create prefetcher with a batch processor
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor, max_queue_size=100)
>>>
>>> # Start background processing
>>> prefetcher.start()
>>>
>>> # Get pre-processed batches
>>> batch = prefetcher.get_batch()
>>> if batch:
... print(f"Got batch {batch.batch_id} with {len(batch.cell_integer_ids)} cells")
>>>
>>> # Check performance statistics
>>> stats = prefetcher.get_stats()
>>> print(f"Loading rate: {stats['cells_per_sec']:.1f} cells/sec")
>>>
>>> # Stop background processing
>>> prefetcher.stop()
Source code in slaf/ml/tiledb_dataloaders.py
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 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 | |
Functions¶
__init__(batch_processor: TileDBBatchProcessor, max_queue_size: int = 500) ¶
Initialize the TileDB async prefetcher with background processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_processor | TileDBBatchProcessor | TileDBBatchProcessor instance to use for loading batches. Must be properly initialized with TileDB path and configuration. | required |
max_queue_size | int | Maximum number of pre-processed batches to keep in queue. Higher values use more memory but provide better buffering. Range: 10-10000, default: 500. | 500 |
Examples:
>>> # Create prefetcher with default queue size
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor)
>>> print(f"Max queue size: {prefetcher.max_queue_size}")
Max queue size: 500
>>> # Create prefetcher with custom queue size
>>> prefetcher = TileDBAsyncPrefetcher(processor, max_queue_size=1000)
>>> print(f"Custom queue size: {prefetcher.max_queue_size}")
Custom queue size: 1000
Source code in slaf/ml/tiledb_dataloaders.py
start() ¶
Start the prefetching worker thread for background batch processing.
This method starts a background worker thread that continuously loads and processes batches from the TileDB batch processor. The worker thread runs as a daemon thread and will automatically stop when the main process exits.
The prefetcher will begin loading batches immediately after starting. Use get_batch() to retrieve pre-processed batches from the queue.
Examples:
>>> # Start background prefetching
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor)
>>> prefetcher.start()
>>> print("Prefetcher started")
Prefetcher started
>>> # Check if prefetcher is ready
>>> import time
>>> time.sleep(1) # Wait for first batch
>>> if prefetcher.has_batch():
... print("Prefetcher is ready with data")
... else:
... print("Prefetcher not ready yet")
Prefetcher is ready with data
Source code in slaf/ml/tiledb_dataloaders.py
stop() ¶
Stop the prefetching worker thread and clean up resources.
This method gracefully stops the background worker thread and waits for it to finish processing the current batch. It sets the stop flag and joins the thread with a timeout to prevent hanging.
After calling stop(), the prefetcher will no longer load new batches. Any remaining batches in the queue can still be retrieved with get_batch().
Examples:
>>> # Stop the prefetcher
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor)
>>> prefetcher.start()
>>>
>>> # Do some work...
>>> batch = prefetcher.get_batch()
>>>
>>> # Stop when done
>>> prefetcher.stop()
>>> print("Prefetcher stopped")
Prefetcher stopped
Source code in slaf/ml/tiledb_dataloaders.py
get_batch() -> TileDBPrefetchBatch | None ¶
Get the next pre-processed batch from the queue.
This method retrieves a pre-processed batch from the internal queue. If no batch is available, it returns None. The method has a timeout to prevent blocking indefinitely.
Returns:
| Type | Description |
|---|---|
TileDBPrefetchBatch | None | TileDBPrefetchBatch | None: The next available batch, or None if no batch is available within the timeout. |
Examples:
>>> # Get a batch from the prefetcher
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor)
>>> prefetcher.start()
>>>
>>> # Wait for a batch
>>> batch = prefetcher.get_batch()
>>> if batch:
... print(f"Got batch {batch.batch_id} with {len(batch.cell_integer_ids)} cells")
... else:
... print("No batch available")
Got batch 0 with 100 cells
>>> # Check for multiple batches
>>> batches = []
>>> for _ in range(3):
... batch = prefetcher.get_batch()
... if batch:
... batches.append(batch)
... else:
... break
>>> print(f"Retrieved {len(batches)} batches")
Retrieved 3 batches
Source code in slaf/ml/tiledb_dataloaders.py
has_batch() -> bool ¶
Check if a pre-processed batch is available in the queue.
This method provides a non-blocking way to check if batches are available for immediate retrieval. It returns True if the queue contains at least one batch, False otherwise.
Returns:
| Name | Type | Description |
|---|---|---|
bool | bool | True if at least one batch is available, False otherwise. |
Examples:
>>> # Check for available batches
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor)
>>> prefetcher.start()
>>>
>>> # Check if batches are ready
>>> if prefetcher.has_batch():
... batch = prefetcher.get_batch()
... print(f"Processing batch {batch.batch_id}")
... else:
... print("No batches ready yet")
No batches ready yet
>>> # Wait and check again
>>> import time
>>> time.sleep(2)
>>> if prefetcher.has_batch():
... print("Batches are now available")
... else:
... print("Still waiting for batches")
Batches are now available
Source code in slaf/ml/tiledb_dataloaders.py
get_stats() -> dict ¶
Get comprehensive statistics about the prefetcher's performance.
This method returns detailed performance statistics including loading rates, memory usage, queue status, and processing times. Useful for monitoring and debugging the prefetcher's performance.
Returns:
| Name | Type | Description |
|---|---|---|
dict | dict | Performance statistics dictionary containing: - total_cells: Total number of cells processed - elapsed_time: Total time since prefetcher started (seconds) - cells_per_sec: Average loading rate (cells per second) - queue_size: Current number of batches in queue - queue_full: Whether the queue is at maximum capacity - total_process_time: Total time spent processing batches - process_count: Number of batches processed - avg_process_time_ms: Average processing time per batch (ms) - current_epoch: Current epoch number - n_epochs: Total number of epochs configured |
Examples:
>>> # Get performance statistics
>>> processor = TileDBBatchProcessor("path/to/experiment")
>>> prefetcher = TileDBAsyncPrefetcher(processor)
>>> prefetcher.start()
>>>
>>> # Wait for some processing
>>> import time
>>> time.sleep(5)
>>>
>>> # Get and display stats
>>> stats = prefetcher.get_stats()
>>> print(f"Loading rate: {stats['cells_per_sec']:.1f} cells/sec")
>>> print(f"Queue size: {stats['queue_size']}/{prefetcher.max_queue_size}")
>>> print(f"Current epoch: {stats['current_epoch']}/{stats['n_epochs']}")
Loading rate: 1250.5 cells/sec
Queue size: 45/500
Current epoch: 0/1
>>> # Monitor performance over time
>>> for i in range(3):
... stats = prefetcher.get_stats()
... print(f"Check {i+1}: {stats['cells_per_sec']:.1f} cells/sec")
... time.sleep(2)
Check 1: 1200.3 cells/sec
Check 2: 1250.5 cells/sec
Check 3: 1180.7 cells/sec
Source code in slaf/ml/tiledb_dataloaders.py
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 | |
TileDBIterableDataset ¶
Bases: IterableDataset
PyTorch IterableDataset for streaming TileDB SOMA data with async prefetching.
TileDBIterableDataset provides a PyTorch-compatible interface for streaming single-cell data from TileDB SOMA format. It combines the TileDBBatchProcessor and TileDBAsyncPrefetcher to provide efficient, asynchronous data loading for machine learning training.
Key Features
- PyTorch IterableDataset compatibility
- Asynchronous background prefetching for improved throughput
- Multiple loading strategies (MoS and sequential)
- Multi-epoch training support
- Automatic epoch transition handling
- Memory-efficient streaming
- Comprehensive error handling
- Configurable batch and prefetch sizes
The dataset automatically manages background prefetching and provides seamless iteration over batches of TileDB data. It handles epoch transitions and provides detailed timing information for performance monitoring.
Examples:
>>> # Create dataset with default MoS strategy
>>> dataset = TileDBIterableDataset(
... tiledb_path="path/to/experiment",
... batch_size=32,
... prefetch_batch_size=100
... )
>>>
>>> # Iterate through batches
>>> for batch in dataset:
... print(f"Batch keys: {list(batch.keys())}")
... print(f"Cell IDs: {batch['cell_ids']}")
... break
Batch keys: ['X', 'cell_ids']
Cell IDs: [0, 1, 2, ..., 29, 30, 31]
>>> # Sequential loading for maximum throughput
>>> dataset = TileDBIterableDataset(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False,
... batch_size=64
... )
>>> print(f"MoS enabled: {dataset.use_mixture_of_scanners}")
MoS enabled: False
>>> # Multi-epoch training
>>> dataset = TileDBIterableDataset(
... tiledb_path="path/to/experiment",
... n_epochs=3
... )
>>> epochs_seen = set()
>>> for batch in dataset:
... if 'epoch' in batch:
... epochs_seen.add(batch['epoch'])
... if len(epochs_seen) >= 3:
... break
>>> print(f"Epochs completed: {sorted(epochs_seen)}")
Epochs completed: [0, 1, 2]
Source code in slaf/ml/tiledb_dataloaders.py
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 | |
Functions¶
__init__(tiledb_path: str, batch_size: int = 32, prefetch_batch_size: int = 100, seed: int = 42, max_queue_size: int = 500, n_epochs: int = 1, verbose: bool = True, use_mixture_of_scanners: bool = True, n_readers: int = 50, n_scanners: int = 8) ¶
Initialize the TileDB IterableDataset with async prefetching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiledb_path | str | Path to the TileDB SOMA experiment directory. Must contain a valid SOMA experiment with RNA measurement data. | required |
batch_size | int | Number of cells per training batch. Larger batches use more memory but may improve training efficiency. Range: 1-512, default: 32. | 32 |
prefetch_batch_size | int | Number of cells to load per prefetch batch from TileDB. Higher values improve throughput but use more memory. Range: 10-10000, default: 100. | 100 |
seed | int | Random seed for reproducible shuffling and MoS sampling. Used for consistent data ordering across runs. Default: 42. | 42 |
max_queue_size | int | Maximum number of pre-processed batches to keep in queue. Higher values use more memory but provide better buffering. Range: 10-10000, default: 500. | 500 |
n_epochs | int | Number of epochs to run. The dataset will automatically reset after each epoch, enabling multi-epoch training. Default: 1. | 1 |
verbose | bool | If True, print detailed timing and progress information. If False, suppress all internal prints for clean output. Default: True. | True |
use_mixture_of_scanners | bool | If True, use MoS strategy for higher entropy by randomly sampling from multiple fragment generators. Provides better randomization for foundation model training. Default: True. | True |
n_readers | int | Total number of fragment generators to create when using MoS. Higher values provide better entropy but use more memory. Range: 1-1000, default: 50. | 50 |
n_scanners | int | Number of active scanners to sample from simultaneously when using MoS. Higher values provide better entropy but use more memory. Range: 1-100, default: 8. | 8 |
Raises:
| Type | Description |
|---|---|
ImportError | If TileDB SOMA is not available. |
ValueError | If MoS parameters are invalid. |
RuntimeError | If the TileDB experiment cannot be opened or is invalid. |
Examples:
>>> # Basic initialization with default MoS strategy
>>> dataset = TileDBIterableDataset(
... tiledb_path="path/to/experiment",
... batch_size=32,
... prefetch_batch_size=100
... )
>>> print(f"MoS enabled: {dataset.use_mixture_of_scanners}")
MoS enabled: True
>>> # Sequential loading for maximum throughput
>>> dataset = TileDBIterableDataset(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False,
... batch_size=64
... )
>>> print(f"Sequential loading: {not dataset.use_mixture_of_scanners}")
Sequential loading: True
>>> # High-entropy MoS configuration
>>> dataset = TileDBIterableDataset(
... tiledb_path="path/to/experiment",
... n_readers=100,
... n_scanners=16
... )
>>> print(f"MoS readers: {dataset.n_readers}, scanners: {dataset.n_scanners}")
MoS readers: 100, scanners: 16
Source code in slaf/ml/tiledb_dataloaders.py
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 | |
TileDBDataLoader ¶
High-performance DataLoader for TileDB SOMA data optimized for ML training.
TileDBDataLoader provides efficient streaming of single-cell data from TileDB SOMA format for machine learning applications. It uses async batch processing and provides multiple loading strategies for different use cases.
Key Features
- Multiple loading strategies for different entropy requirements:
- Mixture of Scanners (MoS): Maximum entropy, best randomization (default)
- Sequential loading: Fastest, lowest entropy
- Asynchronous background prefetching for improved throughput
- Multi-epoch training support with automatic epoch transitions
- Memory-efficient streaming with configurable batch sizes
- Comprehensive error handling and validation
- Performance monitoring and statistics
- PyTorch IterableDataset compatibility
Loading Strategies
- Mixture of Scanners (default): Randomly samples from multiple generators for maximum entropy and randomization
- Sequential: Loads contiguous data chunks for maximum throughput
Examples:
>>> # Basic usage with default MoS strategy
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... batch_size=32,
... prefetch_batch_size=100
... )
>>> for batch in dataloader:
... print(f"Batch keys: {list(batch.keys())}")
... print(f"Cell IDs: {batch['cell_ids']}")
... break
Batch keys: ['X', 'cell_ids']
Cell IDs: [0, 1, 2, ..., 29, 30, 31]
>>> # Sequential loading for maximum throughput
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False,
... batch_size=64
... )
>>> print(f"MoS enabled: {dataloader.use_mixture_of_scanners}")
MoS enabled: False
>>> # Multi-epoch training
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... n_epochs=3
... )
>>> print(f"Number of epochs: {dataloader.n_epochs}")
Number of epochs: 3
>>> # Custom MoS configuration
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... n_readers=100,
... n_scanners=16
... )
>>> print(f"MoS readers: {dataloader.n_readers}, scanners: {dataloader.n_scanners}")
MoS readers: 100, scanners: 16
Source code in slaf/ml/tiledb_dataloaders.py
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 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 | |
Functions¶
__init__(tiledb_path: str, batch_size: int = 32, prefetch_batch_size: int = 100, seed: int = 42, n_epochs: int = 1, verbose: bool = True, max_queue_size: int = 500, use_mixture_of_scanners: bool = True, n_readers: int = 50, n_scanners: int = 8) ¶
Initialize the TileDB DataLoader with training configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiledb_path | str | Path to the TileDB SOMA experiment directory. Must contain a valid SOMA experiment with RNA measurement data. | required |
batch_size | int | Number of cells per training batch. Larger batches use more memory but may improve training efficiency. Range: 1-512, default: 32. | 32 |
prefetch_batch_size | int | Number of cells to prefetch from TileDB per batch. Higher values improve throughput but use more memory. Range: 10-10000, default: 100. | 100 |
seed | int | Random seed for reproducible shuffling and MoS sampling. Used for consistent data ordering across runs. Default: 42. | 42 |
n_epochs | int | Number of epochs to run. The dataloader will automatically reset after each epoch, enabling multi-epoch training. Default: 1. | 1 |
verbose | bool | If True, print detailed timing and progress information. If False, suppress all internal prints for clean output. Default: True. | True |
max_queue_size | int | Maximum number of pre-processed batches to keep in queue. Higher values use more memory but provide better buffering. Range: 10-10000, default: 500. | 500 |
use_mixture_of_scanners | bool | If True, use MoS strategy for higher entropy by randomly sampling from multiple fragment generators. Provides better randomization for foundation model training. Default: True. | True |
n_readers | int | Total number of fragment generators to create when using MoS. Higher values provide better entropy but use more memory. Range: 1-1000, default: 50. | 50 |
n_scanners | int | Number of active scanners to sample from simultaneously when using MoS. Higher values provide better entropy but use more memory. Range: 1-100, default: 8. | 8 |
Raises:
| Type | Description |
|---|---|
ImportError | If TileDB SOMA is not available. |
ValueError | If MoS parameters are invalid. |
RuntimeError | If the TileDB experiment cannot be opened or is invalid. |
Examples:
>>> # Basic initialization with default MoS strategy
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... batch_size=32,
... prefetch_batch_size=100
... )
>>> print(f"MoS enabled: {dataloader.use_mixture_of_scanners}")
MoS enabled: True
>>> # Sequential loading for maximum throughput
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... use_mixture_of_scanners=False,
... batch_size=64
... )
>>> print(f"Sequential loading: {not dataloader.use_mixture_of_scanners}")
Sequential loading: True
>>> # High-entropy MoS configuration
>>> dataloader = TileDBDataLoader(
... tiledb_path="path/to/experiment",
... n_readers=100,
... n_scanners=16
... )
>>> print(f"MoS readers: {dataloader.n_readers}, scanners: {dataloader.n_scanners}")
MoS readers: 100, scanners: 16
Source code in slaf/ml/tiledb_dataloaders.py
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 | |
Functions¶
print_prefetch(message: str, verbose: bool = True) ¶
Print prefetch-related messages with colored formatting.
This function prints prefetch-related messages using rich console formatting when available, or falls back to loguru logging. Messages are displayed in cyan-colored panels for better visual distinction during training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message | str | The message to print. | required |
verbose | bool | If True, print the message. If False, suppress output. | True |
Examples:
>>> # Print a prefetch message
>>> print_prefetch("Loading batch 1 of 100")
>>> # Suppress output
>>> print_prefetch("Loading batch 1 of 100", verbose=False)
Source code in slaf/ml/tiledb_dataloaders.py
print_training(message: str, verbose: bool = True) ¶
Print training-related messages with colored formatting.
This function prints training-related messages using rich console formatting when available, or falls back to loguru logging. Messages are displayed in green-colored panels for better visual distinction during training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message | str | The message to print. | required |
verbose | bool | If True, print the message. If False, suppress output. | True |
Examples:
>>> # Print a training message
>>> print_training("Processing batch with 32 cells")
>>> # Suppress output
>>> print_training("Processing batch with 32 cells", verbose=False)
Source code in slaf/ml/tiledb_dataloaders.py
Tokenizers¶
slaf.ml.tokenizers ¶
Classes¶
TokenizerType ¶
SLAFTokenizer ¶
Tokenizer for single-cell RNA-seq data in SLAF format.
SLAFTokenizer converts single-cell gene expression data into token sequences suitable for machine learning models. It supports multiple tokenization strategies including GeneFormer and scGPT formats with optimized vectorized operations.
Key Features
- Multiple tokenization strategies (GeneFormer, scGPT)
- Vectorized tokenization for high performance
- Expression binning for scGPT format
- Device-agnostic CPU tensor output
- Memory-efficient processing
- Comprehensive vocabulary management
Examples:
>>> # Basic usage with GeneFormer
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> tokenizer = SLAFTokenizer(slaf_array, tokenizer_type="geneformer")
>>> gene_sequences = [[1, 2, 3], [4, 5, 6]]
>>> input_ids, attention_mask = tokenizer.tokenize(gene_sequences)
>>> print(f"Input shape: {input_ids.shape}")
Input shape: torch.Size([2, 2048])
>>> # scGPT with expression sequences
>>> tokenizer = SLAFTokenizer(slaf_array, tokenizer_type="scgpt")
>>> gene_sequences = [[1, 2, 3], [4, 5, 6]]
>>> expr_sequences = [[0.5, 0.8, 0.2], [0.9, 0.1, 0.7]]
>>> input_ids, attention_mask = tokenizer.tokenize(
... gene_sequences, expr_sequences
... )
>>> print(f"Input shape: {input_ids.shape}")
Input shape: torch.Size([2, 2050])
>>> # Error handling for invalid tokenizer type
>>> try:
... tokenizer = SLAFTokenizer(slaf_array, tokenizer_type="invalid")
... except ValueError as e:
... print(f"Error: {e}")
Error: Unsupported tokenizer type: invalid. Supported types: ['geneformer', 'scgpt']
>>> # Vocabulary information
>>> vocab_info = tokenizer.get_vocab_info()
>>> print(f"Vocabulary size: {vocab_info['vocab_size']}")
Vocabulary size: 50000
Source code in slaf/ml/tokenizers.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 | |
Functions¶
__init__(slaf_array: SLAFArray, tokenizer_type: TokenizerType | str = TokenizerType.GENEFORMER, vocab_size: int = 50000, n_expression_bins: int = 10) ¶
Initialize SLAFTokenizer with SLAF array and vocabulary settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slaf_array | SLAFArray | Initialized SLAFArray instance containing the single-cell data. Used to build the gene vocabulary and access expression data. Must be a valid SLAFArray with proper var DataFrame. | required |
tokenizer_type | TokenizerType | str | Type of tokenizer to use. Options: "geneformer", "scgpt". Can be passed as string or TokenizerType enum. | GENEFORMER |
vocab_size | int | Maximum size of gene vocabulary. Genes beyond this limit are excluded from tokenization. Higher values use more memory. | 50000 |
n_expression_bins | int | Number of expression bins for scGPT tokenization. Higher values provide finer expression resolution. Range: 1-1000, default: 10. | 10 |
Raises:
| Type | Description |
|---|---|
ValueError | If tokenizer_type is not supported or vocab_size is invalid. |
RuntimeError | If SLAF array is not properly initialized. |
TypeError | If slaf_array is not a valid SLAFArray instance. |
Examples:
>>> # Basic initialization
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> tokenizer = SLAFTokenizer(slaf_array)
>>> print(f"Tokenizer type: {tokenizer.tokenizer_type}")
Tokenizer type: TokenizerType.GENEFORMER
>>> # scGPT with custom settings
>>> tokenizer = SLAFTokenizer(
... slaf_array=slaf_array,
... tokenizer_type="scgpt",
... vocab_size=30000,
... n_expression_bins=20
... )
>>> print(f"Expression bins: {tokenizer.n_expression_bins}")
Expression bins: 20
>>> # Error handling for invalid tokenizer type
>>> try:
... tokenizer = SLAFTokenizer(slaf_array, tokenizer_type="invalid")
... except ValueError as e:
... print(f"Error: {e}")
Error: Unsupported tokenizer type: invalid. Supported types: ['geneformer', 'scgpt']
>>> # Error handling for invalid SLAF array
>>> try:
... tokenizer = SLAFTokenizer(None)
... except TypeError as e:
... print(f"Error: {e}")
Error: slaf_array must be a valid SLAFArray instance
Source code in slaf/ml/tokenizers.py
tokenize(gene_sequences: list[list[int] | list[tuple[int, float]]], expr_sequences: list[list[float]] | None = None, max_genes: int | None = None) -> tuple[torch.Tensor, torch.Tensor] ¶
Tokenize gene expression sequences into model-ready tensors.
This method converts gene and expression sequences into tokenized tensors suitable for machine learning models. It supports both GeneFormer and scGPT tokenization strategies with optimized vectorized operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gene_sequences | list[list[int] | list[tuple[int, float]]] | List of gene ID sequences for each cell | required |
expr_sequences | list[list[float]] | None | List of expression value sequences for each cell (required for scGPT) | None |
max_genes | int | None | Maximum number of genes per cell (defaults based on tokenizer type) | None |
Returns:
| Name | Type | Description |
|---|---|---|
tuple | tuple[Tensor, Tensor] | (input_ids, attention_mask) tensors - input_ids: Tokenized sequences with padding - attention_mask: Boolean mask indicating valid tokens |
Raises:
| Type | Description |
|---|---|
ValueError | If gene_sequences is empty |
Examples:
>>> # GeneFormer tokenization
>>> gene_sequences = [[1, 2, 3], [4, 5, 6]]
>>> input_ids, attention_mask = tokenizer.tokenize(gene_sequences)
>>> print(f"Shape: {input_ids.shape}")
Shape: torch.Size([2, 2048])
>>> # scGPT tokenization
>>> gene_sequences = [[1, 2, 3], [4, 5, 6]]
>>> expr_sequences = [[0.5, 0.8, 0.2], [0.9, 0.1, 0.7]]
>>> input_ids, attention_mask = tokenizer.tokenize(gene_sequences, expr_sequences)
>>> print(f"Shape: {input_ids.shape}")
Shape: torch.Size([2, 2050])
Source code in slaf/ml/tokenizers.py
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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
get_vocab_info() -> dict[str, Any] ¶
Get vocabulary information for debugging and analysis.
Returns:
| Name | Type | Description |
|---|---|---|
dict | dict[str, Any] | Vocabulary information including size, special tokens, etc. |
Examples:
>>> vocab_info = tokenizer.get_vocab_info()
>>> print(f"Vocabulary size: {vocab_info['vocab_size']}")
>>> print(f"Special tokens: {vocab_info['special_tokens']}")
Vocabulary size: 50000
Special tokens: {'PAD': 0, 'CLS': 1, 'SEP': 2, 'MASK': 3}
Source code in slaf/ml/tokenizers.py
decode_tokens(tokens: list[int]) -> dict[str, Any] ¶
Decode token sequence back to gene information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens | list[int] | List of token IDs to decode | required |
Returns:
| Name | Type | Description |
|---|---|---|
dict | dict[str, Any] | Decoded information including genes, expressions, etc. |
Examples:
>>> # Decode a token sequence
>>> tokens = [1, 100, 50050, 200, 50060, 2] # CLS, gene1, expr1, gene2, expr2, SEP
>>> decoded = tokenizer.decode_tokens(tokens)
>>> print(f"Genes: {decoded['genes']}")
>>> print(f"Expressions: {decoded['expressions']}")
Genes: ['gene_100', 'gene_200']
Expressions: [0.5, 0.6]