kirad.utils¶
kirad.utils
¶
Shared helpers: per-recording averaging, W&B artifact I/O, dynamic imports, analysis.
Stages: launch (import_object, localize_wandb_artifact), loss (segment mean/variance), outputs (cache_backbone, score dataframes, indeterminate analysis, report cards).
Various utility functions, such as label smoothing and computing thresholds.
TSVAccumulator
¶
Helper for formatting tab-separated-value data with section headers in the first row.
Source code in kirad/utils.py
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 | |
header = ''
instance-attribute
¶
rows = [[]]
instance-attribute
¶
__init__()
¶
Start with an empty header and one empty row.
Source code in kirad/utils.py
224 225 226 227 | |
set_header(header)
¶
Set the section prefix used by later write calls.
Source code in kirad/utils.py
229 230 231 | |
write(first, *rest)
¶
Add one column: "rest down the rows.
Source code in kirad/utils.py
233 234 235 236 237 238 239 240 241 242 243 | |
__str__()
¶
Render rows as TSV text.
Source code in kirad/utils.py
245 246 247 248 249 250 | |
load_audio(fp, target_sample_rate=None)
¶
Load channel 0 of an audio file, optionally resampling; not used by the datasets.
Load and resample an audio file.
Returns None if the audio cannot be loaded or is empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fp
|
string or Path
|
Filepath to the audio file to be loaded |
required |
target_sample_rate
|
int or None
|
Sample rate to resample the audio file to. If None, does not resample |
None
|
Returns:
| Type | Description |
|---|---|
Tensor or None
|
Returns the resampled audio file, or None if the audio cannot be loaded or is empty. |
Source code in kirad/utils.py
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 | |
average_tensor_in_segments(tensor, lengths)
¶
Mean over each recording's windows: [ΣW, ...] -> [B, ...] using length.
Average segments of a tensor based on a list of lengths
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
The tensor to average |
required |
lengths
|
list of ints
|
The lengths of each segment to average in the tensor, in order |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The tensor with relevant segments averaged |
Source code in kirad/utils.py
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 | |
average_and_variance_tensor_in_segments(tensor, lengths)
¶
Per-recording mean and (biased) variance of window scores: [ΣW, ...] -> two [B, ...].
Average and variance of segments of a tensor based on a list of lengths
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
The tensor to whose segments' averages and variances should be computed |
required |
lengths
|
list of ints
|
The lengths of each segment of in the tensor, in order |
required |
Returns:
| Type | Description |
|---|---|
(Tensor, Tensor)
|
The tensors with relevant segments' averages and variances |
Source code in kirad/utils.py
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 | |
localize_wandb_artifact(run, artifact_name, tag='best', return_dir=False)
¶
Download a W&B artifact once to ~/.cache/kintsugi and return its local path.
Download an artifact from wandb and return its local path.
Note: returns the first file in the folder unless return_dir; cache is never refreshed.
Source code in kirad/utils.py
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 | |
get_wandb_run_name_tag_from_artifact_url(url)
¶
Parse a W&B artifact URL into (run that logged it, artifact name, tag).
Resolves wandb run and name from artifact url
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Standard Wandb URL of the artifact, such as https://entity.wandb.io/entity/project/artifacts/model/model-run_id/best |
required |
Returns:
| Name | Type | Description |
|---|---|---|
run |
`wandb.apis.public.Run` object corresponding to the given url
|
|
name |
Name of the artifact inside the run (without tag)
|
|
tag |
identifier for a specific model within this run; typically "best" or "v0", "v1", "v2", etc.
|
|
Source code in kirad/utils.py
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 | |
get_wandb_report_card_tsvs(wandb_path, wandb_path_test=None, threshold_objective='macro_f1')
¶
Build a TSV report card per task from a W&B run and log it back as an artifact.
Create model report cards for each task, suitable for pasting into google sheets. Note: reads the "best" checkpoint's thresholds and test summary keys (sn_eq_sp@0%i, auroc@0%i).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wandb_path
|
output from the copy button on a wandb run overview page, e.g. "entity/project/run_id"
|
|
required |
threshold_objective
|
condition used for selecting model thresholds; allowable values depend on run
|
|
'macro_f1'
|
Returns:
| Type | Description |
|---|---|
mapping from task name to tab-separated-value formatted report card for that task
|
|
Source code in kirad/utils.py
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 | |
get_wandb_report_card_tsvs_with_instructions(wandb_path, wandb_path_test=None, threshold_objective='macro_f1')
¶
Report cards from get_wandb_report_card_tsvs, prefixed with paste instructions.
Create model report cards for each task, and instructions for pasting into google sheets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wandb_path
|
output from the copy button on a wandb run overview page, e.g. "entity/project/run_id"
|
|
required |
threshold_objective
|
condition used for selecting model thresholds; allowable values depend on run
|
|
'macro_f1'
|
Returns:
| Type | Description |
|---|---|
String with report cards and instructions for pasting these into google sheets.
|
|
Source code in kirad/utils.py
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 | |
str_to_tensor(s)
¶
Encode a python string as 1-d torch.Tensor of uint8s.
Source code in kirad/utils.py
418 419 420 | |
strs_to_tensor(strs)
¶
Encode strings as a zero-padded 2-d uint8 tensor (uuids for MultiCatMetric).
Encode a sequence of python strings of equal length as a 2-d torch.Tensor of uint8s.
Source code in kirad/utils.py
423 424 425 426 427 428 429 | |
tensor_to_str(t)
¶
Decode a 1-d torch.Tensor of uint8s into a python string (strips zero padding).
Source code in kirad/utils.py
432 433 434 | |
tensor_to_strs(t)
¶
Decode a 2-d torch.Tensor of uint8s into a list of python strings.
Source code in kirad/utils.py
437 438 439 | |
get_dataframe_with_scores(wandb_path, split, scores_tag=None, model_tag=None)
¶
Join a run's metadata CSVs with its W&B scores-
Fetches val or test metadata used for a training run and joins with the scores computed during training.
Arguments
wandb_path : run path copied from wandb run overview page, e.g. "entity/project/run_id"
split : which of "val" or "test" to fetch data for
scores_tag : wandb tag specifying which epoch's scores to use. Can only specify one of scores_tag or model_tag.
By default, gets scores from best-tagged model. Ignored if split == "test" since test scores are only computed
once.
model_tag : wandb tag specifying which model to get scores of. Can only specify one of scores_tag or model_tag.
By default, gets scores from best-tagged model. Ignored if split == "test" since test scores are only computed
once.
Returns:
| Type | Description |
|---|---|
Dataframe of metadata with two additional columns for each task model was trained on:
|
scores_{task} : model scores on that task quantified_labels_{task} : quantfied labels used during eval, e.g. takes values 0, 1, 2 for a 3-class model |
Source code in kirad/utils.py
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 | |
indet_analysis(wandb_path, wandb_path_test=None, budgets=tuple(np.linspace(0.0, 0.9, 10)))
¶
Tune sn_eq_sp thresholds on val per budget and binary cut, then measure them on test.
Returns (per-cut records, mean over cuts per task and budget) as DataFrames. Hardcoded: tasks ("anxiety", "depression"); budgets 0.0..0.9 in steps of 0.1.
Source code in kirad/utils.py
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 | |
analyze_dataframe_with_scores(df, quantize_and_groupby, tasks=('anxiety', 'depression'))
¶
Mean AUROC and sn_eq_sp (0% indet) over binary cuts, per subgroup of the dataframe.
Group dataframe by specified columns (possibly quantizing), computing metrics for each group.
Note: adds quantized_<key> columns to df in place.
Arguments
df : DataFrame containing columns for each key of quantize_and_groupby as well as f"quantized_labels_{task}"
and f"scores_{task}" for each task in tasks and a row for each scored utterance in the dataset
quantize_and_groupby : dictionary whose keys are the column names by which rows of df should be grouped and whose
values are either None if the column values should be used as is or a sequence of bin endpoints if the column
values should be binned before grouping
tasks : names of tasks to analyze scores and labels for, e.g. ("anxiety", "depression")
Source code in kirad/utils.py
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 | |
get_package_path(package)
¶
Repo root of kipy or kirad (env KIPY_PATH / KINTSUGI_RAD_PATH, else from import).
Get local paths to kintsugi-rad and kipy.
Use the paths in the environment variables KIPY_PATH and KINTSUGI_RAD_PATH if
specified. Otherwise, first find the paths to the kipy and kirad packages. The
packages kipy and kirad are installed one level under kipy and kintsugi-rad
respectively, so set the paths to kipy and kintsugi-rad as the parent
directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str
|
Name of the package to get the local path. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised if |
Source code in kirad/utils.py
698 699 700 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 | |
get_package_info(package)
¶
Version (from setup.cfg) and git commit/dirty state of kipy or kirad.
Get package version and git commit hash for kipy and kirad. Note: raises if the package is not importable, e.g. the private kipy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str
|
Name of the package to get the version and commit hash. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
contains the package name, package version, git commit hash, and whether the
|
repo is in a dirty state. |
Source code in kirad/utils.py
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 | |
import_object(object_path)
¶
Import a class/function from a dotted path, e.g. "model.DepAnxClassifier".
Return a reference to the object specified by the object path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_path
|
str
|
Path to an object to load. Can be a path inside a package or a python file that is in the python system path. Examples of paths inside a package: "kipy.models.e2e.whisper_ft_model.WhisperFTModel" "kirad.base_models.WhisperBackbone" Example of loading "DepAnxClassifer" inside model.py that is in the system path: "model.DepAnxClassifier" |
required |
Returns:
| Type | Description |
|---|---|
type[Any]
|
The object. Note that this is not an instantiation of the object; is a reference to the object itself. |
Source code in kirad/utils.py
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 | |
transfer_to_cuda(x, device=0)
¶
Move a tensor or a (nested) dict of tensors to a CUDA device.
Source code in kirad/utils.py
821 822 823 824 825 826 827 828 829 830 | |
cache_backbone(backbone, wandb_logger, datasets, data_loader_args, state_dict)
¶
Run the backbone on all datasets, gather outputs by uuid across ranks, log to W&B.
Runs inference on a backbone and stores it, along with inference results, into wandb by using current wandb_logger session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backbone
|
Callable
|
Callable object, which receives 2 inputs -- (x, lengths) and returns backbone output. Underlying model should be set to a proper device before calling cache_backbone() Outputs will be on cpu. |
required |
wandb_logger
|
Optional[WandbLogger]
|
Wandb logger is supposed to be valid for global_rank == 0 node. See _setup_launcher function for details. |
required |
datasets
|
list[Dataset]
|
List of Dataset objects to iterate through and cache |
required |
data_loader_args
|
list[dict]
|
Arguments of the dataloaders |
required |
state_dict
|
dict
|
Backbone's state_dict with the correct param names with respect to the root module in the object hierarchy. For example: if the original backbone module has the object hierarchy model.my_submodule.my_backbone, then the keys in the state dict should start with the prefix "my_submodule.my_backbone." |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
State dict which contains backbone porams and inference cache written under
|
|
'backbone_cache' key
|
|
Source code in kirad/utils.py
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 | |
read_whisper_timestamped_json(json_file)
¶
Transcript text ("text" field) from a whisper-timestamped JSON.
Get the text transcription from the JSON file output by whisper-timestamped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_file
|
str or Path
|
Path to a JSON file output by whisper-timestamped |
required |
Returns:
| Type | Description |
|---|---|
str
|
The transcription. |
Source code in kirad/utils.py
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 | |
read_google_asr_json(json_file)
¶
Transcript from a Google Speech API JSON: top alternative of each result, joined.
Get the text transcription from the JSON file output by the Google Speech API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_file
|
str or Path
|
Path to a JSON file output by whisper-timestamped |
required |
Returns:
| Type | Description |
|---|---|
str
|
The transcription. |
Source code in kirad/utils.py
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 | |
flat_to_nested_dict(d_in, sep='.')
¶
Split dot-separated keys into nested dicts.
Convert a flat dict with dot-separated keys to a nested dict so e.g. d_out['a']['b']['c'] = d_in['a.b.c'].
d_in = {"first.second.third" : 3, "first.other": 4} d_out = flat_to_nested_dict(d_in) assert d_out == {"first": {"second": {"third": 3}, "other": 4}}
Source code in kirad/utils.py
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 | |
nested_to_flat_dict(d_in, d_out=None, prefix=None)
¶
Flatten nested dicts into dot-separated keys.
Convert a nested dict to a flat one with dot-separated keys so e.g. d_out['a.b.c'] = d_in['a']['b']['c'].
d_in = {"first": {"second": {"third": 3}, "other": 4}} d_out = nested_to_flat_dict(d_in) assert d_out == {"first.second.third" : 3, "first.other": 4} True
Source code in kirad/utils.py
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 | |
combine_backbone_modality_state_dicts(**backbone_dicts)
¶
Merge backbones of several checkpoints into one DAM 2 state_dict (backbone.
Create a DAM 2 style backbone-only state_dict from the backbones of the given DAM 1 or 2 style state_dicts.
e.g. combine_backbone_state_dicts(audio=dam_1_state_dict, text=dam_2_state_dict).
Source code in kirad/utils.py
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 | |
combine_backbone_modality_state_dicts_from_wandb(output_filename, **backbone_run_ids)
¶
Save a merged DAM 2 backbone checkpoint built from the "best" models of W&B runs.
Create a checkpoint for a DAM 2 style backbone-only state_dict from wandb run ids of individual backbones.
Source code in kirad/utils.py
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 | |
dataframe_to_wandb_table(*, dataframe, **kwargs)
¶
wandb.Table from a DataFrame, raising W&B's row limit so large tables are not cut.
Source code in kirad/utils.py
1070 1071 1072 1073 | |
open_single_file_wandb_artifact(artifact)
¶
Download the only file of a W&B artifact and return an open handle.
Source code in kirad/utils.py
1076 1077 1078 1079 1080 1081 | |
wandb_table_artifact_to_dataframe(artifact)
¶
DataFrame from a single-table W&B artifact, read directly from its JSON.
Get dataframe from a wandb artifact containing a single table much faster than using artifact.get.
Source code in kirad/utils.py
1084 1085 1086 1087 1088 1089 1090 1091 | |