kirad.datasets_and_dataloaders¶
kirad.datasets_and_dataloaders
¶
Data stage: metadata table, per-modality datasets (audio, text, cache) and UUID sampler.
KintsugiMetadata loads the CSV and labels; the audio/text datasets return one recording's windows / tokens by UUID; launcher_utils stacks them and dataset_utils.broadcast_collate batches.
Base datasets and data loaders. Currently only contains the audio loader for the Whisper Medium backbone.
INFERENCE_WINDOW_SIZE = 30
module-attribute
¶
MAX_INFERENCE_WINDOW_OVERLAP_FRACTION = 1 / 3
module-attribute
¶
INFERENCE_BATCH_SIZE = 16
module-attribute
¶
DEFAULT_LABEL_COLUMN = {'depression': 'phq', 'anxiety': 'gad'}
module-attribute
¶
MERGE_ROWS_BY_SUBJECT_VALUES = Literal[False, 'many_to_one', 'many_to_many']
module-attribute
¶
TEXT_OUTPUT_PER_SAMPLE_VALUES = Literal['cyclic', 'merge']
module-attribute
¶
WINDOW_METHOD_VALUES = Literal['all', 'single_random', 'single_start', 'random_adjacent_pair']
module-attribute
¶
KintsugiMetadata
¶
Bases: BaseModel, Dataset
Metadata table indexed by UUID: loads CSV, merges KD scores, filters by duration.
Note: duration_column is required (num_windows and duration filters use it).
Class for reading and processing metadata for training.
Attributes:
| Name | Type | Description |
|---|---|---|
df_or_dataset_version |
DataFrame or string
|
If DataFrame, must contain the filename of the files being loaded in
the |
audio_root |
Path or string
|
If a Path, defines the directory from which audio files should be
loaded. If a string, defines the feature store bucket to load audio
from. Available feature store bucket options are |
text_root |
Path or string
|
Path to directory containing transcription json files. |
data_sources |
string or list of strings, optional
|
If |
dataset_splits |
string or list of strings, optional
|
If |
dataset_fold |
(int, optional)
|
If |
label_column |
(dict, optional)
|
Specify a dictionary with (task name, label_column) key/value pairs for the column containing the ground truth scores for each task |
duration_column |
(string, optional)
|
Specify column containing the audio duration. |
merge_rows_by_subject |
Literal[False, 'many_to_one', 'many_to_many']
|
If False, leave data as is, without combining rows corresponding to the same subject in any way -- this should always be the choice for val and test. Otherwise, replace all the rows corresponding to a subject with either a single row ("many_to_one") or the same number of rows ("many_to_many"), as follows. In both cases the audio is concatenated across all these rows before windows / features are extracted. In the "many_to_one" case the text output is the text of a random one of the subjects' rows, chosen independently at each epoch. In the "many_to_many" case the text isn't changed -- if a subject had three streams before merging with texts A, B, and C, the dataset will still contain three streams, one with each of texts A, B, and C. Only the audio is concatenated, so it no longer corresponds directly to the text. The way these options interact with |
window_duration |
int
|
The number of seconds to grab from each audio file before feature extraction. |
max_overlap_frac |
(float, optional)
|
Specify how much the windows overlap as a fraction of the window length. Default: 0.0. |
score_targets_csv |
Optional[str]
|
If present, filename of a CSV file with columns "uuid" and f"scores_{task}" for each task in
|
Source code in kirad/datasets_and_dataloaders.py
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 | |
model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
class-attribute
instance-attribute
¶
df_or_dataset_version
instance-attribute
¶
data_sources = None
class-attribute
instance-attribute
¶
dataset_splits = None
class-attribute
instance-attribute
¶
dataset_fold = None
class-attribute
instance-attribute
¶
label_column = DEFAULT_LABEL_COLUMN
class-attribute
instance-attribute
¶
duration_column = None
class-attribute
instance-attribute
¶
merge_rows_by_subject = False
class-attribute
instance-attribute
¶
window_duration = INFERENCE_WINDOW_SIZE
class-attribute
instance-attribute
¶
max_overlap_frac = 0.0
class-attribute
instance-attribute
¶
fraction = 1.0
class-attribute
instance-attribute
¶
min_duration = INFERENCE_WINDOW_SIZE
class-attribute
instance-attribute
¶
max_duration = None
class-attribute
instance-attribute
¶
score_targets_csv = None
class-attribute
instance-attribute
¶
audio_root = None
class-attribute
instance-attribute
¶
text_root = None
class-attribute
instance-attribute
¶
__init__(*args, **kwargs)
¶
Load and concatenate all metadata sources, index by uuid, preprocess, filter.
Source code in kirad/datasets_and_dataloaders.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
preprocess_metadata()
¶
Join KD score targets, optionally merge rows per subject, count windows per recording.
Adds column num_windows (windows of the "all" method per recording). Note: uses its own max_overlap_frac; keep it equal to the audio dataset's.
Source code in kirad/datasets_and_dataloaders.py
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 | |
filter_metadata()
¶
Subsample fraction of rows, then drop recordings outside min/max duration (s).
Source code in kirad/datasets_and_dataloaders.py
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 | |
__getitem__(uuid)
¶
Return {uuid, label: {task: {primary: raw score, kd: teacher score}}} for one UUID.
kd is added only when a scores_
Source code in kirad/datasets_and_dataloaders.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | |
__len__()
¶
Number of recordings after filtering.
Source code in kirad/datasets_and_dataloaders.py
312 313 314 | |
KintsugiDatasetBase
¶
Bases: BaseModel, Dataset
Base for modality datasets: holds the shared KintsugiMetadata; length = its rows.
Source code in kirad/datasets_and_dataloaders.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | |
model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
class-attribute
instance-attribute
¶
metadata
instance-attribute
¶
__len__()
¶
Number of recordings in the shared metadata.
Source code in kirad/datasets_and_dataloaders.py
329 330 331 | |
KintsugiAudioDataset
¶
Bases: KintsugiDatasetBase
Audio by UUID: loads WAV, optional augmentations, cuts windows, optional log-mel.
Shapes: raw [W, 480000] if preprocessor=False, else HF log-mel [W, 80, 3000].
An audio dataset that processes and generates log-mel spectrogram features from audio files.
Attributes:
| Name | Type | Description |
|---|---|---|
metadata |
KintsugiMetadata
|
Metadata object |
preprocessor |
string
|
Which preprocessor to use. Allowable values can be found at and include "openai/whisper-large", "openai/whisper-medium.en", "openai/whisper-small.en" (default), or "openai/whisper-base.en". |
normalize_audio |
(bool, optional)
|
If true, then scale the audio waveform to be between -1 and 1. |
normalize_features |
(bool, optional)
|
If true, then normalize the mel-spectrogram to have zero-mean, unit-variance. |
window_duration |
int
|
The number of seconds to grab from each audio file before feature extraction |
window_method |
(str, optional)
|
Specify how that audio is windowed prior to extracting features. The window
length is specified by |
max_overlap_frac |
(float, optional)
|
Specify how much the windows overlap as a fraction of the window length. Default: 0.0. |
ideal_logmel_energies |
(list or ndarray, optional)
|
Specifies the value of each log-mel bin to normalize to. The length of the array must match the number of log-mel bins (eg. 80 for WhisperFeatureExtractor). |
Source code in kirad/datasets_and_dataloaders.py
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 | |
preprocessor = 'openai/whisper-small.en'
class-attribute
instance-attribute
¶
normalize_audio = False
class-attribute
instance-attribute
¶
normalize_features = False
class-attribute
instance-attribute
¶
window_duration = INFERENCE_WINDOW_SIZE
class-attribute
instance-attribute
¶
window_method = 'all'
class-attribute
instance-attribute
¶
max_overlap_frac = 0.0
class-attribute
instance-attribute
¶
ideal_logmel_energies = None
class-attribute
instance-attribute
¶
pad_last_chunk_to_full = False
class-attribute
instance-attribute
¶
augmentations = ()
class-attribute
instance-attribute
¶
__init__(*args, **kwargs)
¶
Load ideal_logmel_energies, build augmentations from config, build preprocessor.
Each augmentation config is {class_name, params, aug_prob}.
Source code in kirad/datasets_and_dataloaders.py
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
init_data_processor()
¶
Create the windowing + feature function (HF extractor or raw passthrough).
Source code in kirad/datasets_and_dataloaders.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
__getitem__(uuid)
¶
Load, concatenate (channel 0), augment and window one recording's audio.
Note: a sample rate other than 16 kHz only logs a warning; audio is not resampled. Shapes: [W, 480000] raw or [W, 80, 3000] log-mel.
Loads an audio tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
The UUID of the sample. |
required |
Returns:
| Type | Description |
|---|---|
Tensor containing audio features.
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the sample rate of the audio file to be loaded is not
|
Source code in kirad/datasets_and_dataloaders.py
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 | |
KintsugiTextDataset
¶
Bases: KintsugiDatasetBase
Transcript by UUID: reads ASR JSON and tokenizes it (BERT by default).
A text dataset that processes and tokenizes strings using a tokenizer (eg. BERT tokenizer).
Attributes:
| Name | Type | Description |
|---|---|---|
metadata |
KintsugiMetadata
|
Metadata object |
preprocessor |
str
|
Which Tokenizer preprocessor to use. Can be "google-bert/bert-base-uncased". See for other possible values. |
prompt |
str
|
Prompt for generative LLM model |
max_tokens |
int
|
Max sequence length to which the sequence is padded or truncated at. If not provided, the default is used. |
text_output_per_sample |
str
|
Specifies how to handle multiple text strings per sample (eg. due to setting
|
Source code in kirad/datasets_and_dataloaders.py
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 | |
preprocessor = 'google-bert/bert-base-uncased'
class-attribute
instance-attribute
¶
text_output_per_sample = 'merge'
class-attribute
instance-attribute
¶
prompt = None
class-attribute
instance-attribute
¶
max_tokens = None
class-attribute
instance-attribute
¶
__init__(*args, **kwargs)
¶
Build the tokenizer after pydantic validation.
Source code in kirad/datasets_and_dataloaders.py
554 555 556 557 | |
init_data_processor()
¶
Load the tokenizer (local/HF name or W&B artifact) and wrap it with get_tokenizer.
Source code in kirad/datasets_and_dataloaders.py
559 560 561 562 563 564 565 566 567 568 569 570 | |
__getitem__(uuid)
¶
Read the transcript JSON(s) of one recording and tokenize them.
Note: only whisper_timestamped JSON ("text" field) works; the Google ASR fallback reopens the same path, so it never succeeds. Shapes: input_ids/attention_mask [1, L] ("merge") or [W, L] ("cyclic").
Loads an audio tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
The UUID of the sample. |
required |
Returns:
| Type | Description |
|---|---|
Dictionary containing text features.
|
|
Source code in kirad/datasets_and_dataloaders.py
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 | |
KintsugiCacheDataset
¶
Bases: KintsugiDatasetBase
Precomputed backbone features by UUID (DAM 3 teacher cache), optional dim slice.
A dataset that returns features from a backbone cache.
Attributes:
| Name | Type | Description |
|---|---|---|
metadata |
KintsugiMetadata
|
Metadata object |
backbone_cache |
pandas DataFrame with 2 columns [uuid, feat]
|
|
Sometimes(e.g. LLMA training case) we can be interested in a specific feature slice of the |
|
|
feature vectors in the backbone cache. |
|
|
feat_start_idx and feat_end_idx params define start and end indices of such a slice. |
|
|
feat_end_idx is a non-inclusive index. |
|
Source code in kirad/datasets_and_dataloaders.py
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 699 700 | |
backbone_cache
instance-attribute
¶
feat_start_idx = 0
class-attribute
instance-attribute
¶
feat_end_idx = None
class-attribute
instance-attribute
¶
__init__(*args, **kwargs)
¶
Load the cache (DataFrame or W&B artifact URL) and index it by uuid.
Source code in kirad/datasets_and_dataloaders.py
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 | |
__getitem__(uuid)
¶
Cached features of one UUID, sliced to [feat_start_idx:feat_end_idx] on dim 1.
Source code in kirad/datasets_and_dataloaders.py
694 695 696 697 698 699 700 | |
UuidSampler
¶
Bases: Sampler[str]
Yields metadata UUIDs (shuffled for train, sequential for val/test) for the loader.
Provides a random sampler to sample UUIDs from the metadata.
Source code in kirad/datasets_and_dataloaders.py
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 | |
uuids = metadata._df.index.tolist()
instance-attribute
¶
sampler = DistributedSampler(self.uuids, shuffle=shuffle)
instance-attribute
¶
__init__(metadata, shuffle=False, distributed=False)
¶
Wrap a Random, Sequential or Distributed sampler over the UUID list.
Source code in kirad/datasets_and_dataloaders.py
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 | |
__iter__()
¶
Yield UUIDs in sampler order.
Source code in kirad/datasets_and_dataloaders.py
728 729 730 731 | |
__len__()
¶
Number of UUIDs.
Source code in kirad/datasets_and_dataloaders.py
733 734 735 | |
dummy_preprocessor(x, *args, **kwargs)
¶
Stack raw window arrays into a tensor [W, samples]; used when preprocessor=False.
Source code in kirad/datasets_and_dataloaders.py
334 335 336 | |
get_window_starts(method, audio_len, inference_window_samples, max_inference_window_overlap_fraction=MAX_INFERENCE_WINDOW_OVERLAP_FRACTION)
¶
Start sample(s) of the windows cut from one recording, by window_method.
"all": evenly spaced via np.linspace, hop >= (1 - overlap) * window, >= 1 window. "single_start": 0. "single_random": one random start. "random_adjacent_pair": 2 starts.
Calculate the audio windows based on the audio duration. Each audio window is inference_window_samples long.
A maximum overlap of max_inference_window_overlap_samples is used, but the overlap is flexible so that as much audio as possible is used.
Arguments
method : The method used for selecting window starts
audio_len : the length of the audio in samples
inference_window_samples : the length of the inference window in samples
max_inference_window_overlap_fraction : fraction of each inference window allowed to overlap with the previous
one (between 0.0 and 1.0)
Returns:
| Type | Description |
|---|---|
For method == "all", a list of window starts overlapping by at most the specified fraction.
|
For method == "single_random", a single window start at a random position. |
Source code in kirad/datasets_and_dataloaders.py
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 | |
get_preprocessor_with_audio_normalization(preprocessor, window_method, normalize_audio=False, normalize_features=False, trim_duration=INFERENCE_WINDOW_SIZE, ideal_logmel_energies=None, max_overlap_frac=MAX_INFERENCE_WINDOW_OVERLAP_FRACTION, pad_last_chunk_to_full=False)
¶
Build the function audio [T] -> windows -> features used by KintsugiAudioDataset.
Steps: optional DC removal + peak scaling to [-1, 1], optional zero-pad to full windows, cut windows (get_window_starts), run preprocessor, optional per-bin shift so each log-mel bin's time-mean equals ideal_logmel_energies. Shapes: [W, window samples] raw, or [W, 80, 3000] with the HF Whisper extractor.
Source code in kirad/datasets_and_dataloaders.py
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 | |
get_tokenizer(tokenizer, prompt=None, max_length=None)
¶
Wrap a HF tokenizer: optional chat prompt, pad/truncate to max_length, return pt tensors.
Get a callable function that tokenizes text with a specified tokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
PreTrainedTokenizerBase
|
The tokenizer to invoke (eg. BertTokenizer.from_pretrained("bert-base-uncased")) |
required |
prompt
|
str
|
Text which prompts generative LLM model. If provided, assume we are dealing with generative LLM. |
None
|
max_length
|
Optional[int]
|
Max sequence length. If provided, it will override default max sequence length. |
None
|
Returns:
| Type | Description |
|---|---|
Callable
|
Function that takes text and returns the tokenization in a dictionary containing the following: - "input_ids": token IDs corresponding to the tokenization of the text - "token_type_ids": token type IDs - "attention_mask": specifies which tokens the LLM should attend to |
Source code in kirad/datasets_and_dataloaders.py
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 | |