Datasets API¶
Dataset loading and management utilities for text and classification datasets.
mi_crow.datasets ¶
BaseDataset ¶
BaseDataset(ds, store, loading_strategy=LoadingStrategy.MEMORY)
Bases: ABC
Abstract base class for datasets with support for multiple sources, loading strategies, and Store integration.
Loading Strategies: - MEMORY: Load entire dataset into memory (fastest random access, highest memory usage) - DISK: Save to disk, read dynamically via memory-mapped Arrow files (supports len/getitem, lower memory usage) - STREAMING: True streaming mode using IterableDataset (lowest memory, no len/getitem support, no stratification and limit support)
Initialize dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset | IterableDataset
|
HuggingFace Dataset or IterableDataset |
required |
store
|
Store
|
Store instance for caching/persistence |
required |
loading_strategy
|
LoadingStrategy
|
How to load data (MEMORY, DISK, or STREAMING) |
MEMORY
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If store is None, loading_strategy is invalid, or dataset operations fail |
OSError
|
If file system operations fail |
Source code in src/mi_crow/datasets/base_dataset.py
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 | |
__getitem__
abstractmethod
¶
__getitem__(idx)
Get item(s) by index.
Source code in src/mi_crow/datasets/base_dataset.py
405 406 407 408 | |
__len__
abstractmethod
¶
__len__()
Return the number of items in the dataset.
Source code in src/mi_crow/datasets/base_dataset.py
400 401 402 403 | |
extract_texts_from_batch
abstractmethod
¶
extract_texts_from_batch(batch)
Extract text strings from a batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
List[Any]
|
A batch as returned by iter_batches() |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List of text strings ready for model inference |
Source code in src/mi_crow/datasets/base_dataset.py
420 421 422 423 424 425 426 427 428 429 430 | |
from_csv
classmethod
¶
from_csv(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', delimiter=',', stratify_by=None, stratify_seed=None, drop_na_columns=None, **kwargs)
Load dataset from CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to CSV file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the column containing text |
'text'
|
delimiter
|
str
|
CSV delimiter (default: comma) |
','
|
stratify_by
|
Optional[str]
|
Optional column used for stratified sampling (non-streaming only) |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
drop_na_columns
|
Optional[List[str]]
|
Optional list of columns to check for None/empty values |
None
|
**kwargs
|
Any
|
Additional arguments passed to load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'BaseDataset'
|
BaseDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If CSV file doesn't exist |
ValueError
|
If store is None or source is invalid |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/base_dataset.py
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 | |
from_disk
classmethod
¶
from_disk(store, *, loading_strategy=LoadingStrategy.MEMORY, **kwargs)
Load dataset from already-saved Arrow files on disk.
Use this when you've previously saved a dataset and want to reload it without re-downloading from HuggingFace or re-applying transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
Store
|
Store instance pointing to where the dataset was saved (dataset will be loaded from store.base_path/store.dataset_prefix/) |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy (MEMORY or DISK only, not STREAMING) |
MEMORY
|
**kwargs
|
Any
|
Additional arguments (for subclass compatibility) |
{}
|
Returns:
| Type | Description |
|---|---|
'BaseDataset'
|
BaseDataset instance loaded from disk |
Raises:
| Type | Description |
|---|---|
ValueError
|
If store is None or loading_strategy is STREAMING |
FileNotFoundError
|
If dataset directory doesn't exist |
RuntimeError
|
If dataset loading fails |
Example
First: save dataset¶
dataset_store = LocalStore("store/my_dataset") dataset = ClassificationDataset.from_huggingface(..., store=dataset_store)
Dataset saved to: store/my_dataset/datasets/*.arrow¶
Later: reload from disk¶
dataset_store = LocalStore("store/my_dataset") dataset = ClassificationDataset.from_disk(store=dataset_store)
Source code in src/mi_crow/datasets/base_dataset.py
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 | |
from_huggingface
classmethod
¶
from_huggingface(repo_id, store, *, split='train', loading_strategy=LoadingStrategy.MEMORY, revision=None, streaming=None, filters=None, limit=None, stratify_by=None, stratify_seed=None, **kwargs)
Load dataset from HuggingFace Hub.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_id
|
str
|
HuggingFace dataset repository ID |
required |
store
|
Store
|
Store instance |
required |
split
|
str
|
Dataset split (e.g., "train", "validation") |
'train'
|
loading_strategy
|
LoadingStrategy
|
Loading strategy (MEMORY, DISK, or STREAMING) |
MEMORY
|
revision
|
Optional[str]
|
Optional git revision/branch/tag |
None
|
streaming
|
Optional[bool]
|
Optional override for streaming (if None, uses loading_strategy) |
None
|
filters
|
Optional[Dict[str, Any]]
|
Optional dict of column->value pairs used for exact-match filtering |
None
|
limit
|
Optional[int]
|
Optional maximum number of rows to keep (applied after filtering/stratification) |
None
|
stratify_by
|
Optional[str]
|
Optional column to use for stratified sampling (non-streaming only) |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for deterministic stratification |
None
|
**kwargs
|
Any
|
Additional arguments passed to load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'BaseDataset'
|
BaseDataset instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If repo_id is empty or store is None |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/base_dataset.py
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 | |
from_json
classmethod
¶
from_json(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', stratify_by=None, stratify_seed=None, drop_na_columns=None, **kwargs)
Load dataset from JSON or JSONL file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to JSON or JSONL file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the field containing text (for JSON objects) |
'text'
|
stratify_by
|
Optional[str]
|
Optional column used for stratified sampling (non-streaming only) |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
drop_na_columns
|
Optional[List[str]]
|
Optional list of columns to check for None/empty values |
None
|
**kwargs
|
Any
|
Additional arguments passed to load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'BaseDataset'
|
BaseDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If JSON file doesn't exist |
ValueError
|
If store is None or source is invalid |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/base_dataset.py
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 699 700 701 702 703 704 705 706 707 708 709 710 | |
get_all_texts
abstractmethod
¶
get_all_texts()
Get all texts from the dataset.
Returns:
| Type | Description |
|---|---|
List[str]
|
List of all text strings in the dataset |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not supported for streaming datasets |
Source code in src/mi_crow/datasets/base_dataset.py
432 433 434 435 436 437 438 439 440 441 442 | |
get_batch ¶
get_batch(start, batch_size)
Get a contiguous batch of items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
Starting index |
required |
batch_size
|
int
|
Number of items to retrieve |
required |
Returns:
| Type | Description |
|---|---|
List[Any]
|
List of items |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
Source code in src/mi_crow/datasets/base_dataset.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 | |
head ¶
head(n=5)
Get first n items.
Works for all loading strategies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of items to retrieve (default: 5) |
5
|
Returns:
| Type | Description |
|---|---|
List[Any]
|
List of first n items |
Source code in src/mi_crow/datasets/base_dataset.py
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
iter_batches
abstractmethod
¶
iter_batches(batch_size)
Iterate over items in batches.
Source code in src/mi_crow/datasets/base_dataset.py
415 416 417 418 | |
iter_items
abstractmethod
¶
iter_items()
Iterate over items one by one.
Source code in src/mi_crow/datasets/base_dataset.py
410 411 412 413 | |
sample ¶
sample(n=5)
Get n random items from the dataset.
Works for MEMORY and DISK strategies only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of items to sample |
5
|
Returns:
| Type | Description |
|---|---|
List[Any]
|
List of n randomly sampled items |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
Source code in src/mi_crow/datasets/base_dataset.py
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 | |
ClassificationDataset ¶
ClassificationDataset(ds, store, loading_strategy=LoadingStrategy.MEMORY, text_field='text', category_field='category')
Bases: BaseDataset
Classification dataset with text and category/label columns. Each item is a dict with 'text' and label column(s) as keys. Supports single or multiple label columns.
Initialize classification dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset | IterableDataset
|
HuggingFace Dataset or IterableDataset |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the column containing text |
'text'
|
category_field
|
Union[str, List[str]]
|
Name(s) of the column(s) containing category/label. Can be a single string or a list of strings for multiple labels. |
'category'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If text_field or category_field is empty, or fields not found in dataset |
Source code in src/mi_crow/datasets/classification_dataset.py
20 21 22 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 | |
__getitem__ ¶
__getitem__(idx)
Get item(s) by index. Returns dict with 'text' and label column(s) as keys.
For single label: {"text": "...", "category": "..."} For multiple labels: {"text": "...", "label1": "...", "label2": "..."}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
IndexLike
|
Index (int), slice, or sequence of indices |
required |
Returns:
| Type | Description |
|---|---|
Union[Dict[str, Any], List[Dict[str, Any]]]
|
Single item dict or list of item dicts |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
IndexError
|
If index is out of bounds |
ValueError
|
If dataset is empty |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
__len__ ¶
__len__()
Return the number of items in the dataset.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
Source code in src/mi_crow/datasets/classification_dataset.py
129 130 131 132 133 134 135 136 137 138 | |
extract_texts_from_batch ¶
extract_texts_from_batch(batch)
Extract text strings from a batch of classification items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
List[Dict[str, Any]]
|
List of dicts with 'text' and category fields |
required |
Returns:
| Type | Description |
|---|---|
List[Optional[str]]
|
List of text strings from the batch |
Raises:
| Type | Description |
|---|---|
ValueError
|
If 'text' key is not found in any batch item |
Source code in src/mi_crow/datasets/classification_dataset.py
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
from_csv
classmethod
¶
from_csv(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', category_field='category', delimiter=',', stratify_by=None, stratify_seed=None, drop_na=False, **kwargs)
Load classification dataset from CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to CSV file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the column containing text |
'text'
|
category_field
|
Union[str, List[str]]
|
Name(s) of the column(s) containing category/label |
'category'
|
delimiter
|
str
|
CSV delimiter (default: comma) |
','
|
stratify_by
|
Optional[str]
|
Optional column used for stratified sampling |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
drop_na
|
bool
|
Whether to drop rows with None/empty text or categories |
False
|
**kwargs
|
Any
|
Additional arguments for load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'ClassificationDataset'
|
ClassificationDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If CSV file doesn't exist |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
from_disk
classmethod
¶
from_disk(store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', category_field='category')
Load classification dataset from already-saved Arrow files on disk.
Use this when you've previously saved a dataset and want to reload it without re-downloading from HuggingFace or re-applying transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
Store
|
Store instance pointing to where the dataset was saved |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy (MEMORY or DISK only) |
MEMORY
|
text_field
|
str
|
Name of the column containing text |
'text'
|
category_field
|
Union[str, List[str]]
|
Name(s) of the column(s) containing category/label |
'category'
|
Returns:
| Type | Description |
|---|---|
'ClassificationDataset'
|
ClassificationDataset instance loaded from disk |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If dataset directory doesn't exist or contains no Arrow files |
ValueError
|
If required fields are not in the loaded dataset |
Example
First: save dataset¶
dataset_store = LocalStore("store/wgmix_test") dataset = ClassificationDataset.from_huggingface( "allenai/wildguardmix", store=dataset_store, limit=100 )
Dataset saved to: store/wgmix_test/datasets/*.arrow¶
Later: reload from disk¶
dataset_store = LocalStore("store/wgmix_test") dataset = ClassificationDataset.from_disk( store=dataset_store, text_field="prompt", category_field="prompt_harm_label" )
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
from_huggingface
classmethod
¶
from_huggingface(repo_id, store, *, split='train', loading_strategy=LoadingStrategy.MEMORY, revision=None, text_field='text', category_field='category', filters=None, limit=None, stratify_by=None, stratify_seed=None, streaming=None, drop_na=False, **kwargs)
Load classification dataset from HuggingFace Hub.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_id
|
str
|
HuggingFace dataset repository ID |
required |
store
|
Store
|
Store instance |
required |
split
|
str
|
Dataset split |
'train'
|
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
revision
|
Optional[str]
|
Optional git revision |
None
|
text_field
|
str
|
Name of the column containing text |
'text'
|
category_field
|
Union[str, List[str]]
|
Name(s) of the column(s) containing category/label |
'category'
|
filters
|
Optional[Dict[str, Any]]
|
Optional filters to apply (dict of column: value) |
None
|
limit
|
Optional[int]
|
Optional limit on number of rows |
None
|
stratify_by
|
Optional[str]
|
Optional column used for stratified sampling (non-streaming only) |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
streaming
|
Optional[bool]
|
Optional override for streaming |
None
|
drop_na
|
bool
|
Whether to drop rows with None/empty text or categories |
False
|
**kwargs
|
Any
|
Additional arguments for load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'ClassificationDataset'
|
ClassificationDataset instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters are invalid |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
from_json
classmethod
¶
from_json(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', category_field='category', stratify_by=None, stratify_seed=None, drop_na=False, **kwargs)
Load classification dataset from JSON/JSONL file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to JSON or JSONL file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the field containing text |
'text'
|
category_field
|
Union[str, List[str]]
|
Name(s) of the field(s) containing category/label |
'category'
|
stratify_by
|
Optional[str]
|
Optional column used for stratified sampling |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
drop_na
|
bool
|
Whether to drop rows with None/empty text or categories |
False
|
**kwargs
|
Any
|
Additional arguments for load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'ClassificationDataset'
|
ClassificationDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If JSON file doesn't exist |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
get_all_texts ¶
get_all_texts()
Get all texts from the dataset.
Returns:
| Type | Description |
|---|---|
List[Optional[str]]
|
List of all text strings |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING and dataset is very large |
Source code in src/mi_crow/datasets/classification_dataset.py
305 306 307 308 309 310 311 312 313 314 315 316 | |
get_categories ¶
get_categories()
Get unique categories in the dataset, excluding None values.
Returns:
| Type | Description |
|---|---|
Union[List[Any], Dict[str, List[Any]]]
|
|
Union[List[Any], Dict[str, List[Any]]]
|
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING and dataset is large |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
get_categories_for_texts ¶
get_categories_for_texts(texts)
Get categories for given texts (if texts match dataset texts).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
List[Optional[str]]
|
List of text strings to look up |
required |
Returns:
| Type | Description |
|---|---|
Union[List[Any], List[Dict[str, Any]]]
|
|
Union[List[Any], List[Dict[str, Any]]]
|
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
ValueError
|
If texts list is empty |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
iter_batches ¶
iter_batches(batch_size)
Iterate over items in batches. Each batch is a list of dicts with 'text' and label column(s) as keys.
For single label: [{"text": "...", "category_column_1": "..."}, ...] For multiple labels: [{"text": "...", "category_column_1": "...", "category_column_2": "..."}, ...]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of items per batch |
required |
Yields:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
Lists of item dictionaries (batches) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If batch_size <= 0 or required fields are not found in any row |
Source code in src/mi_crow/datasets/classification_dataset.py
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 | |
iter_items ¶
iter_items()
Iterate over items one by one. Yields dict with 'text' and label column(s) as keys.
For single label: {"text": "...", "category_column_1": "..."} For multiple labels: {"text": "...", "category_column_1": "...", "category_column_2": "..."}
Yields:
| Type | Description |
|---|---|
Dict[str, Any]
|
Item dictionaries with text and category fields |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required fields are not found in any row |
Source code in src/mi_crow/datasets/classification_dataset.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
LoadingStrategy ¶
Bases: Enum
Strategy for loading dataset data.
Choose the best strategy for your use case:
-
MEMORY: Load entire dataset into memory (fastest random access, highest memory usage) Best for: Small datasets that fit in memory, when you need fast random access
-
DISK: Save to disk, read dynamically via memory-mapped Arrow files (supports len/getitem, lower memory usage) Best for: Large datasets that don't fit in memory, when you need random access
-
STREAMING: True streaming mode using IterableDataset (lowest memory, no len/getitem support) Best for: Very large datasets, when you only need sequential iteration
TextDataset ¶
TextDataset(ds, store, loading_strategy=LoadingStrategy.DISK, text_field='text')
Bases: BaseDataset
Text-only dataset with support for multiple sources and loading strategies. Each item is a string (text snippet).
Initialize text dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ds
|
Dataset | IterableDataset
|
HuggingFace Dataset or IterableDataset |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
DISK
|
text_field
|
str
|
Name of the column containing text |
'text'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If text_field is empty or not found in dataset |
Source code in src/mi_crow/datasets/text_dataset.py
20 21 22 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 | |
__getitem__ ¶
__getitem__(idx)
Get text item(s) by index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
IndexLike
|
Index (int), slice, or sequence of indices |
required |
Returns:
| Type | Description |
|---|---|
Union[Optional[str], List[Optional[str]]]
|
Single text string or list of text strings |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
IndexError
|
If index is out of bounds |
ValueError
|
If dataset is empty |
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
__len__ ¶
__len__()
Return the number of items in the dataset.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
Source code in src/mi_crow/datasets/text_dataset.py
92 93 94 95 96 97 98 99 100 101 | |
extract_texts_from_batch ¶
extract_texts_from_batch(batch)
Extract text strings from a batch.
For TextDataset, batch items are already strings, so return as-is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
List[Optional[str]]
|
List of text strings |
required |
Returns:
| Type | Description |
|---|---|
List[Optional[str]]
|
List of text strings (same as input) |
Source code in src/mi_crow/datasets/text_dataset.py
193 194 195 196 197 198 199 200 201 202 203 204 | |
from_csv
classmethod
¶
from_csv(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', delimiter=',', stratify_by=None, stratify_seed=None, drop_na=False, **kwargs)
Load text dataset from CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to CSV file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the column containing text |
'text'
|
delimiter
|
str
|
CSV delimiter (default: comma) |
','
|
stratify_by
|
Optional[str]
|
Optional column to use for stratified sampling |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
drop_na
|
bool
|
Whether to drop rows with None/empty text |
False
|
**kwargs
|
Any
|
Additional arguments for load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'TextDataset'
|
TextDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If CSV file doesn't exist |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
from_disk
classmethod
¶
from_disk(store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text')
Load text dataset from already-saved Arrow files on disk.
Use this when you've previously saved a dataset and want to reload it without re-downloading from HuggingFace or re-applying transformations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
Store
|
Store instance pointing to where the dataset was saved |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy (MEMORY or DISK only) |
MEMORY
|
text_field
|
str
|
Name of the column containing text |
'text'
|
Returns:
| Type | Description |
|---|---|
'TextDataset'
|
TextDataset instance loaded from disk |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If dataset directory doesn't exist or contains no Arrow files |
Example
First: save dataset¶
dataset_store = LocalStore("store/my_texts") dataset = TextDataset.from_huggingface( "wikipedia", store=dataset_store, limit=1000 )
Dataset saved to: store/my_texts/datasets/*.arrow¶
Later: reload from disk¶
dataset_store = LocalStore("store/my_texts") dataset = TextDataset.from_disk(store=dataset_store)
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
from_huggingface
classmethod
¶
from_huggingface(repo_id, store, *, split='train', loading_strategy=LoadingStrategy.MEMORY, revision=None, text_field='text', filters=None, limit=None, stratify_by=None, stratify_seed=None, streaming=None, drop_na=False, **kwargs)
Load text dataset from HuggingFace Hub.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_id
|
str
|
HuggingFace dataset repository ID |
required |
store
|
Store
|
Store instance |
required |
split
|
str
|
Dataset split |
'train'
|
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
revision
|
Optional[str]
|
Optional git revision |
None
|
text_field
|
str
|
Name of the column containing text |
'text'
|
filters
|
Optional[Dict[str, Any]]
|
Optional filters to apply (dict of column: value) |
None
|
limit
|
Optional[int]
|
Optional limit on number of rows |
None
|
stratify_by
|
Optional[str]
|
Optional column used for stratified sampling (non-streaming only) |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for deterministic stratification |
None
|
streaming
|
Optional[bool]
|
Optional override for streaming |
None
|
drop_na
|
bool
|
Whether to drop rows with None/empty text |
False
|
**kwargs
|
Any
|
Additional arguments for load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'TextDataset'
|
TextDataset instance |
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters are invalid |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
from_json
classmethod
¶
from_json(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', stratify_by=None, stratify_seed=None, drop_na=False, **kwargs)
Load text dataset from JSON/JSONL file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to JSON or JSONL file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the field containing text |
'text'
|
stratify_by
|
Optional[str]
|
Optional column to use for stratified sampling |
None
|
stratify_seed
|
Optional[int]
|
Optional RNG seed for stratified sampling |
None
|
drop_na
|
bool
|
Whether to drop rows with None/empty text |
False
|
**kwargs
|
Any
|
Additional arguments for load_dataset |
{}
|
Returns:
| Type | Description |
|---|---|
'TextDataset'
|
TextDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If JSON file doesn't exist |
RuntimeError
|
If dataset loading fails |
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
from_local
classmethod
¶
from_local(source, store, *, loading_strategy=LoadingStrategy.MEMORY, text_field='text', recursive=True)
Load from a local directory or file(s).
Supported
- Directory of .txt files (each file becomes one example)
- JSONL/JSON/CSV/TSV files with a text column
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Union[str, Path]
|
Path to directory or file |
required |
store
|
Store
|
Store instance |
required |
loading_strategy
|
LoadingStrategy
|
Loading strategy |
MEMORY
|
text_field
|
str
|
Name of the column/field containing text |
'text'
|
recursive
|
bool
|
Whether to recursively search directories for .txt files |
True
|
Returns:
| Type | Description |
|---|---|
'TextDataset'
|
TextDataset instance |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If source path doesn't exist |
ValueError
|
If source is invalid or unsupported file type |
RuntimeError
|
If file operations fail |
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
get_all_texts ¶
get_all_texts()
Get all texts from the dataset.
Returns:
| Type | Description |
|---|---|
List[Optional[str]]
|
List of all text strings |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
Source code in src/mi_crow/datasets/text_dataset.py
206 207 208 209 210 211 212 213 214 215 216 217 | |
iter_batches ¶
iter_batches(batch_size)
Iterate over text items in batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of items per batch |
required |
Yields:
| Type | Description |
|---|---|
List[Optional[str]]
|
Lists of text strings (batches) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If batch_size <= 0 or text field is not found in any row |
Source code in src/mi_crow/datasets/text_dataset.py
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 | |
iter_items ¶
iter_items()
Iterate over text items one by one.
Yields:
| Type | Description |
|---|---|
Optional[str]
|
Text strings from the dataset |
Raises:
| Type | Description |
|---|---|
ValueError
|
If text field is not found in any row |
Source code in src/mi_crow/datasets/text_dataset.py
151 152 153 154 155 156 157 158 159 160 161 162 | |
random_sample ¶
random_sample(n, seed=None)
Create a new TextDataset with n randomly sampled items.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of items to sample |
required |
seed
|
Optional[int]
|
Optional random seed for reproducibility |
None
|
Returns:
| Type | Description |
|---|---|
'TextDataset'
|
New TextDataset instance with sampled items |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If loading_strategy is STREAMING |
ValueError
|
If n <= 0 |
Source code in src/mi_crow/datasets/text_dataset.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 | |
TextDataset.random_sample()¶
The TextDataset.random_sample() method creates a new TextDataset instance with randomly sampled items from the original dataset. This is useful for creating smaller subsets of large datasets for testing or training.
Parameters¶
n(int): Number of items to sample. Must be greater than 0.seed(Optional[int]): Optional random seed for reproducibility. If provided, ensures the same random sample is generated across runs.
Returns¶
A new TextDataset instance containing the randomly sampled items.
Example¶
from mi_crow.datasets import TextDataset
from mi_crow.store import LocalStore
store = LocalStore(base_path="./store")
# Load a large dataset
dataset = TextDataset.from_huggingface(
"roneneldan/TinyStories",
split="train",
store=store,
text_field="text"
)
print(f"Original dataset size: {len(dataset)}") # e.g., 2119719
# Sample 1000 random items
sampled_dataset = dataset.random_sample(1000, seed=42)
print(f"Sampled dataset size: {len(sampled_dataset)}") # 1000
# Use the sampled dataset for activation saving or training
run_id = lm.activations.save_activations_dataset(
dataset=sampled_dataset,
layer_signature="layer_0",
batch_size=4
)
Notes¶
- Works with
MEMORYandDISKloading strategies only. Not supported forSTREAMINGdatasets. - If
n >= len(dataset), returns all items in random order. - The method preserves the original dataset's loading strategy, store, and text field configuration.
- For reproducible results, always specify a
seedparameter.