kirad.base_models¶
kirad.base_models
¶
Model building blocks.
Stage: model + loss + thresholds/metrics. Pretrained backbones (Whisper, BERT, LLaMA), the shared MultitaskHead, and the Lightning modules that compute the CORAL loss per task, tune thresholds on validation and log Sn/Sp metrics. Used by research/stable/*/model.py.
DATA_LOADER_ATTR_NAMES = {'train': 'train_dataloader', 'val': 'val_dataloaders', 'test': 'test_dataloaders'}
module-attribute
¶
rank_zero_log_info = rank_zero_only(logger.info)
module-attribute
¶
OrdinalRegressionPLModule
¶
Bases: LightningModule
An ordinal regression model with CORAL loss and threshold tuning.
This class can be used in two ways:
(1) subclass and override the forward method to get a class whose instances can be passed directly to trainer.fit
(2) instantiate within a class to customize the behavior, e.g. having multiple ordinal regression heads whose inputs
and labels are different, but which share some backbone computation.
In case (1) the following methods are called automatically
* on_validation_epoch_end
* on_test_epoch_end
* training_step
* validation_step
* test_step
to compute losses, tune thresholds, and compute metrics. In case (2) these methods must be called manually,
presumably by methods with the same name in the parent object.
Case (2) requires pytorch-lightning 1.7+ for self.log to work correctly with nested LightningModules.
Source code in kirad/base_models.py
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 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 | |
THRESH_LIM = 10000
class-attribute
instance-attribute
¶
metric_target_cutoff_names = metric_target_cutoffs
instance-attribute
¶
loss = CORALLoss(num_classes=num_classes, weights=[float(i in loss_target_cutoffs) for i in range(num_classes - 1)])
instance-attribute
¶
kd_loss = nn.MSELoss(reduction='none')
instance-attribute
¶
thresholding = nn.ModuleDict(dict(accuracy=MaxAccuracyOrdinalThresholding(num_targets), absolute_error=MinAbsoluteErrorOrdinalThresholding(num_targets), macro_recall=MaxMacroRecallOrdinalThresholding(num_targets), macro_precision=MaxMacroPrecisionOrdinalThresholding(num_targets), macro_f1=MaxMacroF1OrdinalThresholding(num_targets)))
instance-attribute
¶
indet_thresholding = nn.ModuleDict({str(c_idx): IndetSnSpTensorModule() for c_idx in self.metric_target_cutoff_names})
instance-attribute
¶
accumulators = nn.ModuleDict({key: MultiCatMetric(4) for key in ('val', 'test')})
instance-attribute
¶
loss_name = loss_name
instance-attribute
¶
score_table_name = score_table_name
instance-attribute
¶
indet_budget_names = {budget: f'@{budget:.0%}i' for budget in indet_budgets}
instance-attribute
¶
score_variance_loss_weight = score_variance_loss_weight
instance-attribute
¶
kd_loss_weight = kd_loss_weight
instance-attribute
¶
coral_loss_weight = coral_loss_weight
instance-attribute
¶
mean_before_loss = {'train': False, 'val': True, 'test': True}
instance-attribute
¶
__init__(num_classes, loss_target_cutoffs, metric_target_cutoffs, loss_name='loss', score_table_name='scores', indet_budgets=(0.0, 0.4), coral_loss_weight=1.0, score_variance_loss_weight=0.0, kd_loss_weight=0.0, mean_before_loss=None)
¶
Build CORAL loss, six threshold tuners, Sn=Sp buffers and val/test accumulators.
Initialize the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_classes
|
number of classes to classify inputs into
|
|
required |
loss_target_cutoffs
|
for each element, include a CORAL loss classifying whether inputs are greater than that
|
(typically |
required |
metric_target_cutoffs
|
OrderedDict[int, str] | Sequence[int]
|
output label to names of corresponding divisions of output labels, e.g. {9: "LvMH", 14: "LMvH"} for depression, or (b) increasing sequence of input labels, e.g. (9, 14), from which the labels {9: ">9", 14: ">14"} would be inferred. |
required |
increasing
|
(e.g. [9, 14] to indicate that the upper limit of a "low depression" (0) output is PHQ of 9 and the upper limit of "medium depression" (1) is PHQ of 14. |
required | |
loss_name
|
string describing `loss_target_cutoffs`, so experiments with different losses are displayed on
|
separate plots in wandb |
'loss'
|
indet_budgets
|
fractions of outputs allowed to be indeterminate in metric computations (will compute separate
|
metrics for each entry) |
(0.0, 0.4)
|
score_variance_loss_weight
|
Weight to apply to variance of scores over chunks within each stream when computing
|
loss, relative to weight of CORAL loss |
0.0
|
mean_before_loss
|
mapping from split to bool. If True, compute loss for split as loss(mean(scores)); if False,
|
compute loss as mean(loss(scores)). Defaults to False for "train" and True for "val" and "test". |
None
|
Source code in kirad/base_models.py
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 | |
load_state_dict(state_dict, strict=True)
¶
Resize indet-threshold buffers to the checkpoint's shapes, then load weights.
Source code in kirad/base_models.py
199 200 201 202 203 204 205 206 207 208 | |
forward(x)
¶
Identity: the multi-task parent computes scores; this module only adds loss/metrics.
Defaults to identity for case where this class is instantiated directly rather than subclassed.
This default is to enable the case where a model contains multiple ordinal regression tasks (e.g. depression
and anxiety) sharing some computation, which is therefore implemented elsewhere. If there is only a single
task, it is simpler to subclass this class and override forward.
Source code in kirad/base_models.py
210 211 212 213 214 215 216 217 218 219 220 | |
quantize_labels(labels)
¶
Map input labels (e.g. PHQ-9 sum) to output labels (e.g. 0/1/2 for L/M/H).
Source code in kirad/base_models.py
222 223 224 225 226 | |
log_ordinal_metrics(split, issas, *, scores, labels)
¶
Log AUROC and min(Sn, Sp) per binary cut and indet budget, plus their mean.
On test, also Sn/Sp/indet fraction at the thresholds tuned on validation. Returns the dict of logged metrics (keys bucketed_metrics/... and metrics/...).
Source code in kirad/base_models.py
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 | |
log_thresholding_metrics(split, *, scores, quantized_labels)
¶
Log each tuned method's cost when scored with every method's thresholds.
Also logs the cost of the best constant-output classifier as a baseline.
Source code in kirad/base_models.py
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 | |
log_test_indet_analysis(*, scores, labels)
¶
W&B line plots of test Sn, Sp, indet fraction vs the val indeterminate budget.
One plot per binary cut, plus the average over cuts. Test split only. Hardcoded: 1000 interpolation points for the averaged curve.
Source code in kirad/base_models.py
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 | |
on_validation_epoch_end()
¶
Lightning hook: run the val epoch-end logic and free CUDA cache.
Source code in kirad/base_models.py
414 415 416 417 | |
on_test_epoch_end()
¶
Lightning hook: run the test epoch-end logic.
Source code in kirad/base_models.py
419 420 421 | |
on_validation_test_epoch_end(split)
¶
Gather scores, log W&B table, tune thresholds on val, compute Sn/Sp metrics.
Dedups uuids (DDP repeats samples), uploads scores-
Source code in kirad/base_models.py
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 | |
compute_and_log_loss(logits, y, lengths, split)
¶
Loss = coral_w·CORAL + var_w·Var(window scores) + kd_w·MSE(teacher), logged.
CORAL is loss(mean(scores)) if mean_before_loss[split] else mean(loss(per-window)). KD term only if the label dict has the KD field (teacher score per recording). Shapes: logits [ΣW, 1], y[PRIMARY][B], lengths [B] -> scalar.
Source code in kirad/base_models.py
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 | |
step(split, batch, batch_idx)
¶
Accumulate per-recording mean/var scores for val/test, then return the loss.
Shapes: batch features -> forward -> [ΣW, 1]; accumulated per recording [B].
Source code in kirad/base_models.py
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |
training_step(batch, batch_idx)
¶
Lightning train step for a single-task subclass.
Source code in kirad/base_models.py
596 597 598 | |
validation_step(batch, batch_idx)
¶
Lightning val step; loss is logged, not returned.
Source code in kirad/base_models.py
600 601 602 | |
test_step(batch, batch_idx)
¶
Lightning test step; loss is logged, not returned.
Source code in kirad/base_models.py
604 605 606 | |
predict_step(batch, batch_idx, dataloader_idx=0)
¶
Per-recording score: forward, then mean over its windows. Shapes: [B, 1].
Source code in kirad/base_models.py
608 609 610 611 612 613 614 615 616 | |
MultiTaskOrdinalRegressionPLModule
¶
Bases: LightningModule
Multi-task wrapper: one OrdinalRegressionPLModule per task on a shared model.
Subclasses (the DAM models) define forward(features, lengths) -> ({task: scores}, lengths).
Source code in kirad/base_models.py
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 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 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 | |
tasks = nn.ModuleDict(tasks)
instance-attribute
¶
__init__(tasks)
¶
Store the per-task modules (loss, thresholds, accumulators) in a ModuleDict.
Source code in kirad/base_models.py
624 625 626 627 | |
load_state_dict(state_dict, strict=True)
¶
Resize every task's indet-threshold buffers, then load weights.
Missing/unexpected keys are only logged (with strict=False).
Source code in kirad/base_models.py
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 | |
configure_model()
¶
Give each task the trainer and a logger that prefixes names with '
Source code in kirad/base_models.py
663 664 665 666 667 668 669 670 | |
get_sub_logger(key)
¶
Return a log function that prefixes metric names with '
Source code in kirad/base_models.py
672 673 674 675 676 677 678 | |
on_validation_test_epoch_end(split)
¶
Run each task's epoch end, then log harmonic mean of shared metrics across tasks.
The combined metric (e.g. metrics/val/sn_eq_sp@0%i) drives checkpointing.
Source code in kirad/base_models.py
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | |
on_validation_epoch_end()
¶
Lightning hook: val epoch end for all tasks.
Source code in kirad/base_models.py
702 703 704 | |
on_test_epoch_end()
¶
Lightning hook: test epoch end for all tasks.
Source code in kirad/base_models.py
706 707 708 | |
compute_features_to_cache(x, lengths)
¶
Backbone embeddings split per recording, for the cache command (abstract).
Returns list of tensors with shapes N_ExD, where N_E - number of embedding vectors associated with each sample and D - embedding dimensionality. N_E depends on a mode (training,validation) as well as model architecture
Source code in kirad/base_models.py
710 711 712 713 714 715 716 717 718 719 720 | |
training_step(batch, batch_idx)
¶
Lightning train step: returns the step dict with total_loss.
Source code in kirad/base_models.py
722 723 724 | |
validation_step(batch, batch_idx)
¶
Lightning val step; losses are logged, not returned.
Source code in kirad/base_models.py
726 727 728 | |
test_step(batch, batch_idx)
¶
Lightning test step; losses are logged, not returned.
Source code in kirad/base_models.py
730 731 732 | |
step(split, batch, batch_idx)
¶
Run model once, sum each task's loss (task.step) into total_loss.
Each task gets its own scores and labels: logits[task], batch[label][task].
Source code in kirad/base_models.py
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 | |
predict_step(batch, batch_idx, dataloader_idx=0)
¶
Per-recording scores for each task: {task: [B, 1]} (mean over windows).
Source code in kirad/base_models.py
773 774 775 776 777 778 779 780 781 782 783 784 | |
MultiTaskOrdinalRegressionBackboneDictPLModule
¶
Bases: MultiTaskOrdinalRegressionPLModule
Multi-task module whose backbone is a ModuleDict; loads DAM 1 weights into "audio".
Version of MultiTaskOrdinalRegressionPLModule that correctly loads DAM 1 weights into the audio backbone.
Source code in kirad/base_models.py
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 | |
backbone
instance-attribute
¶
load_state_dict(state_dict, strict=True)
¶
Rename backbone.base_model.* keys to backbone.audio.base_model.* before loading.
Source code in kirad/base_models.py
796 797 798 799 800 801 802 803 804 805 806 807 | |
KintsugiBackboneBase
¶
Bases: LightningModule
Base for pretrained backbones: holds self.backbone and adds optional LoRA.
Source code in kirad/base_models.py
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 | |
backbone
instance-attribute
¶
__init__()
¶
No parameters; subclasses build self.backbone.
Source code in kirad/base_models.py
814 815 816 | |
apply_lora(lora_params=None)
¶
Wrap self.backbone with PEFT LoRA from lora_params; no-op (full fine-tune) if empty.
lora_params go straight to peft.LoraConfig (r, lora_alpha, target_modules, modules_to_save, ...); modules_to_save layers (e.g. conv1/conv2) train fully.
Source code in kirad/base_models.py
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 | |
WhisperBackbone
¶
Bases: KintsugiBackboneBase
Whisper encoder only (decoder dropped), optionally mean-pooled over time.
Source code in kirad/base_models.py
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 | |
backbone = WhisperModel.from_pretrained(model, config=backbone_config, ignore_mismatched_sizes=backbone_config.max_source_positions != 1500).get_encoder().train()
instance-attribute
¶
backbone_dim = backbone_config.hidden_size
instance-attribute
¶
mean_pool = mean_pool
instance-attribute
¶
__init__(model='openai/whisper-small.en', hf_config=None, lora_params=None, mean_pool=True)
¶
Load the pretrained Whisper encoder from HuggingFace and apply LoRA.
Note: if max_source_positions != 1500, mismatched weights (positional table) are re-initialized.
Source code in kirad/base_models.py
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 | |
forward(x, *args, **kwargs)
¶
Whisper encoder on log-mel windows, mean over time -> [ΣW, D] (768 for small.en).
Shapes: x["audio"][ΣW, 80, 3000] -> hidden [ΣW, 1500, D] -> [ΣW, D] if mean_pool.
Source code in kirad/base_models.py
877 878 879 880 881 882 883 884 885 | |
Wav2Vec2Backbone
¶
Bases: KintsugiBackboneBase
wav2vec2 encoder on raw audio, mean-pooled (not used by the stable DAM configs).
Source code in kirad/base_models.py
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 | |
backbone = Wav2Vec2Model.from_pretrained(model, config=backbone_config).train()
instance-attribute
¶
backbone_dim = backbone_config.hidden_size
instance-attribute
¶
mean_pool = mean_pool
instance-attribute
¶
__init__(model='facebook/wav2vec2-xls-r-300m', hf_config=None, lora_params=None, mean_pool=True)
¶
Load the pretrained wav2vec2 model from HuggingFace and apply LoRA.
Source code in kirad/base_models.py
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 | |
forward(x, *args, **kwargs)
¶
Encode raw audio x["audio"][ΣW, samples] -> [ΣW, D] (mean over frames if mean_pool).
Source code in kirad/base_models.py
910 911 912 913 914 915 | |
BERTBackbone
¶
Bases: KintsugiBackboneBase
BERT on transcript tokens; returns the pooler output [ΣW, 768] (DAM 2 text branch).
Source code in kirad/base_models.py
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 | |
backbone = BertModel.from_pretrained(model, config=backbone_config).train()
instance-attribute
¶
backbone_dim = backbone_config.hidden_size
instance-attribute
¶
__init__(model='google-bert/bert-base-uncased', hf_config=None, lora_params=None)
¶
Load pretrained BERT from HuggingFace and apply LoRA.
Source code in kirad/base_models.py
920 921 922 923 924 925 926 927 928 929 930 931 932 933 | |
forward(x, *args, **kwargs)
¶
Pooler output ([CLS] + dense + tanh) of x["text"] tokens. Shapes: -> [ΣW, 768].
Source code in kirad/base_models.py
935 936 937 938 | |
LLAMABackbone
¶
Bases: KintsugiBackboneBase
LLaMA cut to num_layers layers; embeds text as the last real token's hidden state.
Source code in kirad/base_models.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 | |
param_group_name = 'llama_backbone'
class-attribute
instance-attribute
¶
backbone = LlamaForCausalLM.from_pretrained(model, config=backbone_config).train()
instance-attribute
¶
backbone_dim = self.backbone.config.hidden_size
instance-attribute
¶
__init__(model='meta-llama/Llama-3.2-3B-Instruct', hf_config=None, lora_params=None, num_layers=15)
¶
Load LLaMA (HF id or W&B artifact URL), keep the first num_layers layers, LoRA.
Note: LLaMA is gated on HuggingFace, so configs pass a W&B artifact URL.
Source code in kirad/base_models.py
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 | |
forward(x, *args, **kwargs)
¶
Last hidden state at the last non-padded token of each sequence.
Shapes: x["text"] input_ids/attention_mask [ΣW, L] -> [ΣW, D] (3072 for Llama-3.2-3B).
Source code in kirad/base_models.py
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 | |
MultitaskHead
¶
Bases: LightningModule
Shared MLP followed by one small head per task (depression, anxiety).
e.g. D -> 256 (Mish) -> 64, then per task 64 -> 128 (Mish, dropout) -> 1.
Source code in kirad/base_models.py
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 | |
shared_layers = self.SharedLayers(backbone_dim, shared_projection_dim)
instance-attribute
¶
classifier_head = nn.ModuleDict({task: self.TaskHead(shared_projection_dim[-1], **task_config) for task, task_config in tasks.items()})
instance-attribute
¶
SharedLayers
¶
Bases: Module
Shared MLP: Linear+Mish per proj_dim, last Linear without activation (e.g. D->256->64).
The activation-free last layer acts as shared low-rank B in W_t = H_t·B. With a single proj_dim, Mish is kept after it (no factorization).
Source code in kirad/base_models.py
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 | |
shared_layers = nn.Sequential(*modules)
instance-attribute
¶
__init__(input_dim, proj_dims)
¶
Build Linear(+Mish) layers input_dim -> proj_dims[0] -> ... -> proj_dims[-1].
Source code in kirad/base_models.py
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 | |
forward(x)
¶
Shapes: [ΣW, D] -> [ΣW, proj_dims[-1]].
Source code in kirad/base_models.py
1030 1031 1032 | |
TaskHead
¶
Bases: Module
Per-task head: Linear(in, proj_dim) -> Mish -> Dropout -> Linear(proj_dim, 1, no bias).
Source code in kirad/base_models.py
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 | |
linear = nn.Linear(input_dim, proj_dim)
instance-attribute
¶
activation = nn.Mish()
instance-attribute
¶
dropout = nn.Dropout(dropout)
instance-attribute
¶
final_layer = nn.Linear(proj_dim, 1, bias=False)
instance-attribute
¶
__init__(input_dim, proj_dim, dropout)
¶
No bias on the final layer: CORAL learns the per-cutoff biases instead.
Source code in kirad/base_models.py
1036 1037 1038 1039 1040 1041 1042 1043 | |
forward(x)
¶
Shapes: [ΣW, in] -> [ΣW, 1] (one ordinal score per window).
Source code in kirad/base_models.py
1045 1046 1047 1048 1049 1050 1051 | |
__init__(backbone_dim, shared_projection_dim, tasks)
¶
Build SharedLayers(backbone_dim, shared_projection_dim) and a TaskHead per task config.
Source code in kirad/base_models.py
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 | |
forward(x)
¶
Shared layers, then one TaskHead per task -> {task: [ΣW, 1] score}.
Source code in kirad/base_models.py
1075 1076 1077 1078 | |
ResNetHead
¶
Bases: LightningModule
Alternative head: 2-D ResNet over [N, T, D] features, one logit per task (unused).
Source code in kirad/base_models.py
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 | |
resnet = ResNetForImageClassification(resnet_config)
instance-attribute
¶
tasks = tasks
instance-attribute
¶
__init__(resnet_model, tasks)
¶
ResNet from a HF config, randomly initialized, 1 input channel, len(tasks) outputs.
Source code in kirad/base_models.py
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 | |
forward(x)
¶
Shapes: [N, T, D] -> {task: [N, 1]}.
Source code in kirad/base_models.py
1096 1097 1098 1099 | |
ResNetHead1d
¶
Bases: LightningModule
Alternative head: ResNet with feature dim as channels over time (unused).
Source code in kirad/base_models.py
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 | |
resnet = ResNetForImageClassification(resnet_config)
instance-attribute
¶
tasks = tasks
instance-attribute
¶
__init__(resnet_model, tasks, backbone_dim)
¶
ResNet from a HF config, randomly initialized, backbone_dim channels, len(tasks) outputs.
Source code in kirad/base_models.py
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | |
forward(x)
¶
Shapes: [N, T, D] -> transposed to [N, D, T, 1] -> {task: [N, 1]}.
Source code in kirad/base_models.py
1118 1119 1120 1121 | |