abs
Abstract base class for all models.
Author: Heli Qi Affiliation: NAIST Date: 2022.07
Model
Bases: Module
, ABC
Model is the base class for all models in this toolkit. The main job of a model includes: 1. (optional) preprocess the input batch data to the trainable format 2. calculate the model prediction results by the Module members 3. evaluate the prediction results by the Criterion members
Each model has several built-in Module members that make up the neural network structure of the model. These Module
members will be initialized by the module_conf
given in your configuration.
There are a built-in dictionary named init_class_dict
and a built-in list named default_init_modules
in the
base class. init_class_dictcontains all the available initialization functions of the model parameters while
default_init_modules` includes the network layers that have their own initialization functions.
Attributes:
Name | Type | Description |
---|---|---|
init_class_dict |
Dict
|
Available parameter initialization functions |
default_init_modules |
List
|
Network layers with own initialization functions |
Source code in speechain/model/abs.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 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 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 785 786 787 788 789 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 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 924 925 926 927 928 929 |
|
__init__(device, module_conf, result_path, model_conf=None, criterion_conf=None, non_blocking=False, distributed=False)
In this initialization function, there are two parts of initialization: model-specific customized initialization and model- independent general initialization.
Model-specific customized initialization is done by two interface functions: module_init() and criterion_init(). module_init() initializes the neural network structure of the model while criterion_init() initializes the criteria used to optimize (loss functions) and evaluate (validation metrics) the model.
After the customized initialization, there are 3 steps for general initialization:
1. Pretrained parameters will be loaded into your model if the key pretrained_model
is given. Multiple
pretrained models can be specified and each of them can be loaded into different parts of your model. The
mismatch between the names of pretrained parameters and the parameters of your model is handled by the key
'mapping'. The value of the key mapping
is a dictionary where each key-value item corresponds to a mapping
of parameter names. The key is the parameter name in the pretrained parameters while the value is the
parameter name of your model.
2. If `pretrained_model` is not given, the parameters of your model will be initialized by the function that
matches your input query 'init'. Please refer to the built-in dictionary `init_class_dict` for the available
initialization functions. If `init` is not given, the default initialization function
`torch.nn.init.xavier_normal_` will be used to initialize your model.
3. Finally, the specified parts of your model will be frozen if 'frozen_modules' is given. If there is only
one frozen module, you can directly give the string of its name to 'frozen_modules' like
'frozen_modules: {module_name}'; if there are multiple modules you want to freeze, you can give their names
in a list as
```
frozen_modules:
- {module_name1}
- {module_name2}
- ...
```
Moreover, the frozen granularity depends on your input `frozen_modules`.
For example,
1. If you give 'frozen_modules: encoder_prenet', all parameters of the prenet of your encoder will be
frozen
2. If you give 'frozen_modules: encoder_prenet.conv', only the convolution layers of the prenet of your
encoder will be frozen
3. If you give 'frozen_modules: encoder_prenet.conv.0', only the first convolution layer of the prenet
of your encoder will be frozen
4. If you give 'frozen_modules: encoder_prenet.conv.0.bias', only the bias vector of the first
convolution layer of the prenet of your encoder will be frozen
Parameters:
Name | Type | Description | Default |
---|---|---|---|
device
|
device
|
The computational device used for model calculation in the current GPU process. |
required |
model_conf
|
Dict
|
The model configuration used for general model initialization. |
None
|
module_conf
|
Dict
|
The module configuration used for network structure initialization. |
required |
criterion_conf
|
Dict
|
The criterion configuration used for criterion (loss functions and evaluation metrics) initialization. |
None
|
Source code in speechain/model/abs.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
|
attention_reshape(hypo_attention, prefix_list=None)
Used by the abstract function visualize() to reshape the attention matrices before matrix_snapshot().
Source code in speechain/model/abs.py
aver_metrics_across_procs(metrics, batch_data)
This function averages the evaluation metrics across all GPU processes in the DDP mode for model distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metrics
|
Dict[str, Tensor]
|
Dict[str, torch.Tensor] The evaluation metrics to be averaged across all GPU processes. |
required |
batch_data
|
Dict
|
Dict The input batch data used to calculate the batch size for averaging evaluation metrics. |
required |
Dict[str, torch.Tensor]
Type | Description |
---|---|
Dict[str, Tensor]
|
The evaluation metrics Dict after averaging. The key names remain the same. |
Source code in speechain/model/abs.py
bad_cases_selection_init_fn()
staticmethod
This hook function returns the default bad case selection method of each Model object. This default value will be referred by the Runner to present the top-N bad cases.
The original hook implementation in the base Model class returns None which means no default value.
List[List[str or int]]
Type | Description |
---|---|
List[List[str or int]] or None
|
The returned default value should be a list of tri-list where each tri-list is in the form of |
List[List[str or int]] or None
|
[ |
List[List[str or int]] or None
|
waveforms with the largest WER will be selected. |
Source code in speechain/model/abs.py
batch_preprocess_fn(batch_data)
This hook function does the preprocessing for the input batch data before using them in self.model_forward(). This function is not mandatory to be overridden and the original implementation in the base Model class does the tensor transformation for the string-like data in batch_data (i.e., text and spk_ids).
Note: the key names in the returned Dict should match the argument names in self.model_forward().
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_data
|
Dict
|
Dict The raw data of the input batch to be preprocessed in this hook function. |
required |
Dict
Type | Description |
---|---|
Dict
|
The processed data of the input batch that is ready to be used in |
Source code in speechain/model/abs.py
batch_to_cuda(data)
The recursive function that transfers the batch data to the specified device in the current process.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Dict[str, Tensor] or Tensor
|
Dict or torch.Tensor The input batch data. It should be either a Tensor or a Dict of Tensors. For the Dict input, the function itself will be called once by each Tensor element. |
required |
Dict or torch.Tensor
Type | Description |
---|---|
Dict[str, Tensor] or Tensor
|
If the input is a Dict, the returned output will also be a Dict of Tensors transferred to the target device; |
Dict[str, Tensor] or Tensor
|
If the input is a Tensor, the returned output will be its copy on the target device. |
Source code in speechain/model/abs.py
criterion_forward(**kwargs)
abstractmethod
This interface function is activated after self.model_forward()
. It
receives the model prediction results from self.model_forward()
and input
batch data from self.batch_preprocess_fn()
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
The combination of the returned arguments from |
{}
|
(Dict[str, torch.Tensor], Dict[str, torch.Tensor]) or Dict[str, torch.Tensor]
Type | Description |
---|---|
(Dict[str, Tensor], Dict[str, Tensor]) or Dict[str, Tensor]
|
The returned values should be different for the training and validation branches. |
(Dict[str, Tensor], Dict[str, Tensor]) or Dict[str, Tensor]
|
|
(Dict[str, Tensor], Dict[str, Tensor]) or Dict[str, Tensor]
|
trainable training losses for optimization and the second one contains all the non-trainable evaluation |
(Dict[str, Tensor], Dict[str, Tensor]) or Dict[str, Tensor]
|
metrics used to record the training status. |
(Dict[str, Tensor], Dict[str, Tensor]) or Dict[str, Tensor]
|
|
(Dict[str, Tensor], Dict[str, Tensor]) or Dict[str, Tensor]
|
evaluation metrics used to record the validation status. |
Source code in speechain/model/abs.py
criterion_init(**criterion_conf)
abstractmethod
The interface function that initializes the Criterion members of the model. These Criterion members can be divided into two parts: the loss functions used for training and the evaluation metrics used for validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**criterion_conf
|
The arguments in your given |
{}
|
Source code in speechain/model/abs.py
evaluate(test_batch, infer_conf)
The shared evaluation function by all Model subclasses. This evaluation function has 2 steps: 1. preprocess and transfer the batch data to GPUs 2. calculate the inference results
For each step above, we provide interface functions for you to override and make your own implementation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test_batch
|
Dict
|
Dict
The input batch data received from the |
required |
infer_conf
|
Dict
|
Dict The configuration used for model inference. |
required |
Returns:
Type | Description |
---|---|
A Dict of the inference results where each key-value item corresponds to one evaluation metric you want to |
|
save to the disk. |
Source code in speechain/model/abs.py
forward(batch_data, epoch=None, **kwargs)
The general model forward function shared by all the Model subclasses. This forward function has 3 steps: 1. preprocess and transfer the batch data to GPUs 2. obtain the model prediction results 3. calculate the loss function and evaluate the prediction results
For each step above, we provide interface functions for you to override and make your own implementation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_data
|
Dict
|
Dict
The input batch data received from the |
required |
epoch
|
int
|
int = None The number of the current epoch. Used for real-time model visualization and model prediction. |
None
|
**kwargs
|
The additional arguments for real-time model visualization. If given, the code will go through the model visualization branch. |
{}
|
Returns:
Type | Description |
---|---|
In the training branch, the loss functions and evaluation metrics will be returned each of which is in the |
|
form of a Dict. |
|
In the validation branch, only the evaluation metrics will be returned. |
|
In the visualization branch, the model snapshots on the given validation instance will be returned. |
Source code in speechain/model/abs.py
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 |
|
get_recordable_para()
Recursively retrieves the recordable parameters from the module's sub- modules.
Returns:
Type | Description |
---|---|
Dict[str, Tensor]
|
Dict[str, torch.Tensor]: A dictionary mapping the parameter names to their corresponding tensor values. |
Source code in speechain/model/abs.py
inference(infer_conf, **kwargs)
abstractmethod
This function receives the test data and test configuration. The inference results will be packaged into a Dict[str, Dict] which is passed to TestMonitor for disk storage. The returned Dict should be in the form of ``` dict( {file_name}=dict( format={file_format},
content={file_content}
)
)
``
The first-level key is used to decide the name of the meta file as
idx2{file_name}`. Its value is also a Dict
and there must be two keys in this sub-Dict: 'format' and 'content'. The configuration of the sub-Dict is
different for different file formats:
1. For pure text metadata files, the value of 'format' must be 'txt' and the value of 'content' must be a
list of Python built-in data type (i.e.,. int, float, str, bool, ...).
Each line of the file `idx2{file_name}` will be made up of the index of a test data instance and its
metadata value in the `content` List which are separated by a blank.
For example,
`dict(cer=dict(format='txt', content=[0.1, 0.2, 0.3]))` will create a pure text file named 'idx2cer' which
looks like
```
{test_index1} 0.1
{test_index2} 0.2
{test_index3} 0.3
```
Note: if the first-level key ends with '.md', there will not be 'idx2' attached at the beginning of the
file name.
2. For audio files, the value of 'format' must be either 'wav' or 'flac' and the value of 'content' must be
a list of array-like data type (e.g. numpy.ndarry, torch.Tensor, ...).
Moreover, there must be an additional key named 'sample_rate' to indicate the sampling rate of the waveforms
to be saved in audio files.
There will be a folder named `{file_name}` that contains all the audio files and a pure text file named
`idx2{file_name}` that contains the absolute paths of all the saved audio files.
For example,
`dict(wav=dict(format='flac', content=[np_arr1, np_arr2, np_arr3]))` will create a folder named 'wav' and
a pure text file named 'idx2wav' in the same directory. The file 'idx2wav' looks like:
```
{test_index1} /x/xx/wav/{test_index1}.flac
{test_index2} /x/xx/wav/{test_index2}.flac
{test_index3} /x/xx/wav/{test_index3}.flac
```
where `/x/xx/` is your result path given in your `exp_cfg`.
3. For binary files, the value of 'format' in the sub-Dict must be 'npy' and the value of 'content' must be
a list of numpy.ndarry (torch.Tensor is not supported).
There will be a folder named `{file_name}` that contains all the .npy files and a pure text file
named `idx2{file_name}` that contains the absolute paths of all the saved binary files.
For example,
`dict(feat=dict(format='npy', content=[np_arr1, np_arr2, np_arr3]))`
will create a folder named 'feat' and a pure text file named 'idx2feat'. The 'idx2feat' file is like:
```
{test_index1} /x/xx/feat/{test_index1}.npy
{test_index2} /x/xx/feat/{test_index2}.npy
{test_index3} /x/xx/feat/{test_index3}.npy
```
where `/x/xx/` is your result path given in your `exp_cfg`.
Source code in speechain/model/abs.py
matrix_snapshot(vis_logs, hypo_attention, subfolder_names, epoch)
Used by the abstract function visualize() to make the snapshot materials for attention matrices.
Source code in speechain/model/abs.py
module_forward(epoch=None, **batch_data)
abstractmethod
This function forwards the input batch data by all Module members.
Note:
1. This interface function must be overridden for each Model subclass.
2. The argument names should match the key names in the returned Dict of self.batch_preprocess_fn()
.
3. The key names in the returned Dict should match the argument names of self.loss_calculation()
and
self.metrics_calculation()
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
epoch
|
int
|
|
None
|
**batch_data
|
Processed data of the input batch received from |
{}
|
Dict
Type | Description |
---|---|
Dict
|
Prediction results (logits) of the model on the input batch data. |
Dict
|
Some intermediate results (e.g., attention matrices) can also be returned for later use. |
Source code in speechain/model/abs.py
module_init(**kwargs)
abstractmethod
The interface function that initializes the Module members of the model. These Module members make up the neural network structure of the model. Some models have their customized part that also needs to be initialization in this function, e.g. the tokenizer of ASR and TTS models.
Note: This interface function must be overridden for each Model subclass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
The combination of the arguments in your given |
{}
|
Source code in speechain/model/abs.py
register_instance_reports(md_list_dict, extra_string_list=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
md_list_dict
|
Dict[str, List]
|
|
required |
extra_string_list
|
List[str]
|
|
None
|
Returns:
Source code in speechain/model/abs.py
visualize(epoch, sample_index, **valid_sample)
abstractmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
epoch
|
int
|
|
required |
sample_index
|
str
|
|
required |
**valid_sample
|
|
{}
|
Returns: