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 pre-tokenized single-cell data for machine learning applications. It uses async batch processing and provides device-agnostic CPU tensor output for maximum training flexibility.
Key Features
- Multiple tokenization strategies (GeneFormer, scGPT)
- Pre-tokenized sequences for maximum performance
- Device-agnostic CPU tensor output
- Async batch processing with background prefetching
- Memory-efficient streaming
- PyTorch tensor output with attention masks
- Comprehensive error handling and validation
Examples:
>>> # Basic usage with default settings
>>> 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])
>>> # Custom configuration for training
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... tokenizer_type="scgpt",
... batch_size=64,
... max_genes=1024
... )
>>> print(f"Number of batches: {len(dataloader)}")
Number of batches: 42
>>> # 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 |
|
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 = 50, by_fragment: bool = False)
¶
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. | 'geneformer' |
batch_size | int | Number of cells per batch. Larger batches use more memory but may improve training efficiency. Range: 1-512, default: 32. | 32 |
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 |
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 sparse CSR tensors instead of pre-tokenized sequences. Default: False. | False |
verbose | bool | If True, print detailed timing and progress information. If False, suppress all SLAF internal prints for clean output. Default: True. | True |
batches_per_chunk | int | Number of Lance batches to load per chunk for batch-based loading. Higher values use more memory but may improve throughput. Range: 10-200, default: 50. | 50 |
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. Default: False. | False |
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. |
Examples:
>>> # Basic initialization
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> dataloader = SLAFDataLoader(slaf_array)
>>> print(f"Batch size: {dataloader.batch_size}")
Batch size: 32
>>> # Custom configuration
>>> 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
>>> # Multi-epoch training
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... n_epochs=5
... )
>>> print(f"Number of epochs: {dataloader.n_epochs}")
Number of epochs: 5
>>> # Raw mode for external comparisons
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... raw_mode=True
... )
>>> print(f"Raw mode: {dataloader.raw_mode}")
Raw mode: True
>>> # Fragment-based loading for higher entropy
>>> dataloader = SLAFDataLoader(
... slaf_array=slaf_array,
... by_fragment=True
... )
>>> print(f"Fragment-based loading: {dataloader.by_fragment}")
Fragment-based loading: True
>>> # 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
>>> # Error handling for invalid SLAF array
>>> try:
... dataloader = SLAFDataLoader(None)
... except TypeError as e:
... print(f"Error: {e}")
Error: slaf_array must be a valid SLAFArray instance
Source code in slaf/ml/dataloaders.py
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 |
|
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
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]