w11wo commited on
Commit
95a05a3
1 Parent(s): 3f382a9

Added training scripts

Browse files
run.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_distil_audio_multilabel_classification.py \
2
+ --model_name_or_path MIT/ast-finetuned-audioset-10-10-0.4593 \
3
+ --dataset_name bookbot/audioset \
4
+ --output_dir distil-ast-audioset-2 \
5
+ --overwrite_output_dir \
6
+ --remove_unused_columns False \
7
+ --freeze_feature_encoder False \
8
+ --do_train --do_eval \
9
+ --fp16 \
10
+ --learning_rate 3e-5 \
11
+ --alpha 0.5 \
12
+ --temperature 2.0 \
13
+ --layer_prefix audio_spectrogram_transformer.encoder.layer \
14
+ --delimiter . \
15
+ --teacher_blocks 0 2 4 6 8 10 \
16
+ --attention_mask False \
17
+ --warmup_ratio 0.1 \
18
+ --num_train_epochs 10 \
19
+ --per_device_train_batch_size 32 \
20
+ --gradient_accumulation_steps 4 \
21
+ --per_device_eval_batch_size 32 \
22
+ --dataloader_num_workers 4 \
23
+ --logging_strategy epoch \
24
+ --evaluation_strategy epoch \
25
+ --save_strategy epoch \
26
+ --save_total_limit 3 \
27
+ --seed 0 \
28
+ --report_to tensorboard \
29
+ --push_to_hub \
30
+ --hub_model_id bookbot/distil-ast-audioset-2 \
31
+ --hub_private_repo True \
32
+ --use_auth_token True
run_distil_audio_multilabel_classification.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import logging
18
+ import os
19
+ import sys
20
+ import warnings
21
+ from dataclasses import dataclass, field, asdict
22
+ from typing import Optional, List
23
+
24
+ import datasets
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ from datasets import DatasetDict, load_dataset
30
+
31
+ import transformers
32
+ from transformers import (
33
+ AutoConfig,
34
+ AutoFeatureExtractor,
35
+ AutoModelForAudioClassification,
36
+ EvalPrediction,
37
+ HfArgumentParser,
38
+ Trainer,
39
+ TrainingArguments,
40
+ set_seed,
41
+ )
42
+ from transformers.trainer_utils import get_last_checkpoint
43
+ from transformers.utils import send_example_telemetry
44
+ from transformers.utils.versions import require_version
45
+
46
+ from sklearn.metrics import (
47
+ accuracy_score,
48
+ average_precision_score,
49
+ f1_score,
50
+ roc_auc_score,
51
+ )
52
+
53
+ logger = logging.getLogger(__name__)
54
+
55
+ require_version(
56
+ "datasets>=1.14.0",
57
+ "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt",
58
+ )
59
+
60
+
61
+ def list_field(default=None, metadata=None):
62
+ return field(default_factory=lambda: default, metadata=metadata)
63
+
64
+
65
+ @dataclass
66
+ class DistillationTrainingArguments:
67
+ """
68
+ Arguments pertaining to distillation settings.
69
+ """
70
+
71
+ alpha: float = field(
72
+ default=0.5,
73
+ metadata={
74
+ "help": "Hyperparameter to control the relative strength of each loss."
75
+ },
76
+ )
77
+ temperature: float = field(
78
+ default=2.0,
79
+ metadata={"help": "Scale factor of logits to soften the probabilities."},
80
+ )
81
+ layer_prefix: str = field(
82
+ default=None,
83
+ metadata={
84
+ "help": "Layer name prefix to copy from teacher model. E.g. `wav2vec2.encoder.layers`."
85
+ },
86
+ )
87
+ delimiter: str = field(
88
+ default=".", metadata={"help": "Layer name components delimiter."}
89
+ )
90
+ teacher_blocks: List[str] = list_field(
91
+ default=None,
92
+ metadata={
93
+ "help": "A list of teacher block indices to copy from. E.g. `'0 2 4 6 8 10'`"
94
+ },
95
+ )
96
+
97
+
98
+ class MultiLabelDistillationTrainer(Trainer):
99
+ def __init__(self, *args, teacher_model=None, **kwargs):
100
+ super().__init__(*args, **kwargs)
101
+ self.teacher_model = teacher_model
102
+
103
+ def compute_loss(self, model, inputs, return_outputs=False):
104
+ labels = inputs.pop("labels")
105
+ outputs_stu = model(**inputs)
106
+ logits_stu = outputs_stu.logits
107
+ bce_loss_fct = torch.nn.BCEWithLogitsLoss()
108
+ loss_bce = bce_loss_fct(
109
+ logits_stu.view(-1, self.model.config.num_labels),
110
+ labels.float().view(-1, self.model.config.num_labels),
111
+ )
112
+ with torch.no_grad():
113
+ outputs_tea = self.teacher_model(**inputs)
114
+ logits_tea = outputs_tea.logits
115
+ kd_loss_fct = nn.KLDivLoss(reduction="batchmean")
116
+ loss_kd = self.args.temperature**2 * kd_loss_fct(
117
+ F.log_softmax(logits_stu / self.args.temperature, dim=-1),
118
+ F.softmax(logits_tea / self.args.temperature, dim=-1),
119
+ )
120
+ loss = self.args.alpha * loss_bce + (1.0 - self.args.alpha) * loss_kd
121
+ return (loss, outputs_stu) if return_outputs else loss
122
+
123
+
124
+ @dataclass
125
+ class DataTrainingArguments:
126
+ """
127
+ Arguments pertaining to what data we are going to input our model for training and eval.
128
+ Using `HfArgumentParser` we can turn this class
129
+ into argparse arguments to be able to specify them on
130
+ the command line.
131
+ """
132
+
133
+ dataset_name: Optional[str] = field(
134
+ default=None, metadata={"help": "Name of a dataset from the datasets package"}
135
+ )
136
+ dataset_config_name: Optional[str] = field(
137
+ default=None,
138
+ metadata={
139
+ "help": "The configuration name of the dataset to use (via the datasets library)."
140
+ },
141
+ )
142
+ train_file: Optional[str] = field(
143
+ default=None,
144
+ metadata={"help": "A file containing the training audio paths and labels."},
145
+ )
146
+ eval_file: Optional[str] = field(
147
+ default=None,
148
+ metadata={"help": "A file containing the validation audio paths and labels."},
149
+ )
150
+ train_split_name: str = field(
151
+ default="train",
152
+ metadata={
153
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
154
+ },
155
+ )
156
+ eval_split_name: str = field(
157
+ default="validation",
158
+ metadata={
159
+ "help": (
160
+ "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
161
+ )
162
+ },
163
+ )
164
+ audio_column_name: str = field(
165
+ default="audio",
166
+ metadata={
167
+ "help": "The name of the dataset column containing the audio data. Defaults to 'audio'"
168
+ },
169
+ )
170
+ label_column_name: Optional[str] = field(
171
+ default="label",
172
+ metadata={
173
+ "help": "The name of the dataset column containing the labels. Defaults to 'label'"
174
+ },
175
+ )
176
+ max_train_samples: Optional[int] = field(
177
+ default=None,
178
+ metadata={
179
+ "help": (
180
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
181
+ "value if set."
182
+ )
183
+ },
184
+ )
185
+ max_eval_samples: Optional[int] = field(
186
+ default=None,
187
+ metadata={
188
+ "help": (
189
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
190
+ "value if set."
191
+ )
192
+ },
193
+ )
194
+ max_length_seconds: float = field(
195
+ default=20,
196
+ metadata={
197
+ "help": "Audio clips will be randomly cut to this length during training if the value is set."
198
+ },
199
+ )
200
+
201
+
202
+ @dataclass
203
+ class ModelArguments:
204
+ """
205
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
206
+ """
207
+
208
+ model_name_or_path: str = field(
209
+ default="facebook/wav2vec2-base",
210
+ metadata={
211
+ "help": "Path to pretrained model or model identifier from huggingface.co/models"
212
+ },
213
+ )
214
+ config_name: Optional[str] = field(
215
+ default=None,
216
+ metadata={
217
+ "help": "Pretrained config name or path if not the same as model_name"
218
+ },
219
+ )
220
+ cache_dir: Optional[str] = field(
221
+ default=None,
222
+ metadata={
223
+ "help": "Where do you want to store the pretrained models downloaded from the Hub"
224
+ },
225
+ )
226
+ model_revision: str = field(
227
+ default="main",
228
+ metadata={
229
+ "help": "The specific model version to use (can be a branch name, tag name or commit id)."
230
+ },
231
+ )
232
+ feature_extractor_name: Optional[str] = field(
233
+ default=None, metadata={"help": "Name or path of preprocessor config."}
234
+ )
235
+ freeze_feature_encoder: bool = field(
236
+ default=True,
237
+ metadata={"help": "Whether to freeze the feature encoder layers of the model."},
238
+ )
239
+ attention_mask: bool = field(
240
+ default=True,
241
+ metadata={
242
+ "help": "Whether to generate an attention mask in the feature extractor."
243
+ },
244
+ )
245
+ use_auth_token: bool = field(
246
+ default=False,
247
+ metadata={
248
+ "help": (
249
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
250
+ "with private models)."
251
+ )
252
+ },
253
+ )
254
+ freeze_feature_extractor: Optional[bool] = field(
255
+ default=None,
256
+ metadata={
257
+ "help": "Whether to freeze the feature extractor layers of the model."
258
+ },
259
+ )
260
+ ignore_mismatched_sizes: bool = field(
261
+ default=False,
262
+ metadata={
263
+ "help": "Will enable to load a pretrained model whose head dimensions are different."
264
+ },
265
+ )
266
+
267
+ def __post_init__(self):
268
+ if not self.freeze_feature_extractor and self.freeze_feature_encoder:
269
+ warnings.warn(
270
+ "The argument `--freeze_feature_extractor` is deprecated and "
271
+ "will be removed in a future version. Use `--freeze_feature_encoder`"
272
+ "instead. Setting `freeze_feature_encoder==True`.",
273
+ FutureWarning,
274
+ )
275
+ if self.freeze_feature_extractor and not self.freeze_feature_encoder:
276
+ raise ValueError(
277
+ "The argument `--freeze_feature_extractor` is deprecated and "
278
+ "should not be used in combination with `--freeze_feature_encoder`."
279
+ "Only make use of `--freeze_feature_encoder`."
280
+ )
281
+
282
+
283
+ def main():
284
+ # See all possible arguments in src/transformers/training_args.py
285
+ # or by passing the --help flag to this script.
286
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
287
+
288
+ parser = HfArgumentParser(
289
+ (
290
+ ModelArguments,
291
+ DataTrainingArguments,
292
+ TrainingArguments,
293
+ DistillationTrainingArguments,
294
+ )
295
+ )
296
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
297
+ # If we pass only one argument to the script and it's the path to a json file,
298
+ # let's parse it to get our arguments.
299
+ model_args, data_args, training_args, distil_args = parser.parse_json_file(
300
+ json_file=os.path.abspath(sys.argv[1])
301
+ )
302
+ else:
303
+ (
304
+ model_args,
305
+ data_args,
306
+ training_args,
307
+ distil_args,
308
+ ) = parser.parse_args_into_dataclasses()
309
+
310
+ # copy alpha and temperature values from DistillationTrainingArguments to TrainingArguments
311
+ for key, value in asdict(distil_args).items():
312
+ setattr(training_args, key, value)
313
+
314
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
315
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
316
+ send_example_telemetry("run_audio_classification", model_args, data_args)
317
+
318
+ # Setup logging
319
+ logging.basicConfig(
320
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
321
+ datefmt="%m/%d/%Y %H:%M:%S",
322
+ handlers=[logging.StreamHandler(sys.stdout)],
323
+ )
324
+
325
+ if training_args.should_log:
326
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
327
+ transformers.utils.logging.set_verbosity_info()
328
+
329
+ log_level = training_args.get_process_log_level()
330
+ logger.setLevel(log_level)
331
+ transformers.utils.logging.set_verbosity(log_level)
332
+ transformers.utils.logging.enable_default_handler()
333
+ transformers.utils.logging.enable_explicit_format()
334
+
335
+ # Log on each process the small summary:
336
+ logger.warning(
337
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
338
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
339
+ )
340
+ logger.info(f"Training/evaluation parameters {training_args}")
341
+
342
+ # Set seed before initializing model.
343
+ set_seed(training_args.seed)
344
+
345
+ # Detecting last checkpoint.
346
+ last_checkpoint = None
347
+ if (
348
+ os.path.isdir(training_args.output_dir)
349
+ and training_args.do_train
350
+ and not training_args.overwrite_output_dir
351
+ ):
352
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
353
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
354
+ raise ValueError(
355
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
356
+ "Use --overwrite_output_dir to train from scratch."
357
+ )
358
+ elif (
359
+ last_checkpoint is not None and training_args.resume_from_checkpoint is None
360
+ ):
361
+ logger.info(
362
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
363
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
364
+ )
365
+
366
+ # Initialize our dataset and prepare it for the audio classification task.
367
+ raw_datasets = DatasetDict()
368
+ raw_datasets["train"] = load_dataset(
369
+ data_args.dataset_name,
370
+ data_args.dataset_config_name,
371
+ split=data_args.train_split_name,
372
+ use_auth_token=True if model_args.use_auth_token else None,
373
+ )
374
+ raw_datasets["eval"] = load_dataset(
375
+ data_args.dataset_name,
376
+ data_args.dataset_config_name,
377
+ split=data_args.eval_split_name,
378
+ use_auth_token=True if model_args.use_auth_token else None,
379
+ )
380
+
381
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
382
+ raise ValueError(
383
+ f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
384
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
385
+ f"{', '.join(raw_datasets['train'].column_names)}."
386
+ )
387
+
388
+ # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
389
+ # transformer outputs in the classifier, but it doesn't always lead to better accuracy
390
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
391
+ model_args.feature_extractor_name or model_args.model_name_or_path,
392
+ return_attention_mask=model_args.attention_mask,
393
+ cache_dir=model_args.cache_dir,
394
+ revision=model_args.model_revision,
395
+ use_auth_token=True if model_args.use_auth_token else None,
396
+ )
397
+
398
+ # `datasets` takes care of automatically loading and resampling the audio,
399
+ # so we just need to set the correct target sampling rate.
400
+ raw_datasets = raw_datasets.cast_column(
401
+ data_args.audio_column_name,
402
+ datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate),
403
+ )
404
+
405
+ model_input_name = feature_extractor.model_input_names[0]
406
+
407
+ def preprocess_data(examples):
408
+ # get audio arrays
409
+ audio_arrays = [x["array"] for x in examples[data_args.audio_column_name]]
410
+ # encode batch of audio
411
+ inputs = feature_extractor(
412
+ audio_arrays, sampling_rate=feature_extractor.sampling_rate
413
+ )
414
+ # add labels
415
+ labels_batch = {k: examples[k] for k in examples.keys() if k in labels}
416
+ # create numpy array of shape (batch_size, num_labels)
417
+ labels_matrix = np.zeros((len(audio_arrays), len(labels)))
418
+ # fill numpy array
419
+ for idx, label in enumerate(labels):
420
+ labels_matrix[:, idx] = labels_batch[label]
421
+
422
+ output_batch = {model_input_name: inputs.get(model_input_name)}
423
+ output_batch["labels"] = labels_matrix.tolist()
424
+
425
+ return output_batch
426
+
427
+ def multi_label_metrics(predictions, labels, threshold=0.5):
428
+ # first, apply sigmoid on predictions which are of shape (batch_size, num_labels)
429
+ sigmoid = torch.nn.Sigmoid()
430
+ probs = sigmoid(torch.Tensor(predictions)).cpu().numpy()
431
+ # next, use threshold to turn them into integer predictions
432
+ y_pred = np.zeros(probs.shape)
433
+ y_pred[np.where(probs >= threshold)] = 1
434
+ # finally, compute metrics
435
+ f1_micro_average = f1_score(y_true=labels, y_pred=y_pred, average="micro")
436
+ roc_auc = roc_auc_score(labels, y_pred, average="micro")
437
+ accuracy = accuracy_score(labels, y_pred)
438
+ mAP = average_precision_score(labels, probs, average="micro")
439
+ # return as dictionary
440
+ metrics = {
441
+ "f1": f1_micro_average,
442
+ "roc_auc": roc_auc,
443
+ "accuracy": accuracy,
444
+ "mAP": mAP,
445
+ }
446
+ return metrics
447
+
448
+ def compute_metrics(p: EvalPrediction):
449
+ """Computes mean average precision (mAP) score"""
450
+ preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
451
+ result = multi_label_metrics(predictions=preds, labels=p.label_ids)
452
+ return result
453
+
454
+ teacher_config = AutoConfig.from_pretrained(
455
+ model_args.config_name or model_args.model_name_or_path,
456
+ cache_dir=model_args.cache_dir,
457
+ revision=model_args.model_revision,
458
+ use_auth_token=True if model_args.use_auth_token else None,
459
+ )
460
+ teacher_model = AutoModelForAudioClassification.from_pretrained(
461
+ model_args.model_name_or_path,
462
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
463
+ config=teacher_config,
464
+ cache_dir=model_args.cache_dir,
465
+ revision=model_args.model_revision,
466
+ use_auth_token=True if model_args.use_auth_token else None,
467
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
468
+ ).to(training_args.device)
469
+
470
+ labels = list(teacher_config.id2label.values())
471
+
472
+ layer_num_idx: int = len(distil_args.layer_prefix.split(distil_args.delimiter))
473
+ num_hidden_layers: int = len(distil_args.teacher_blocks)
474
+ assert num_hidden_layers <= teacher_model.config.num_hidden_layers
475
+
476
+ student_config = AutoConfig.from_pretrained(
477
+ model_args.config_name or model_args.model_name_or_path,
478
+ num_hidden_layers=num_hidden_layers,
479
+ cache_dir=model_args.cache_dir,
480
+ revision=model_args.model_revision,
481
+ use_auth_token=True if model_args.use_auth_token else None,
482
+ )
483
+ student_model = AutoModelForAudioClassification.from_pretrained(
484
+ model_args.model_name_or_path,
485
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
486
+ config=student_config,
487
+ cache_dir=model_args.cache_dir,
488
+ revision=model_args.model_revision,
489
+ use_auth_token=True if model_args.use_auth_token else None,
490
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
491
+ )
492
+
493
+ # initialize student's weights from teacher's
494
+ teacher_weights = teacher_model.state_dict()
495
+ student_weights = student_model.state_dict()
496
+
497
+ for name, param in student_weights.items():
498
+ if name.startswith(distil_args.layer_prefix):
499
+ # split layer name to its components
500
+ student_layer_name_comps = name.split(distil_args.delimiter)
501
+ student_layer_num = student_layer_name_comps[layer_num_idx]
502
+ # replace the layer num with teacher's layer num
503
+ student_layer_name_comps[layer_num_idx] = distil_args.teacher_blocks[
504
+ int(student_layer_num)
505
+ ]
506
+ # join to get teacher's layer name
507
+ teacher_layer_name = distil_args.delimiter.join(student_layer_name_comps)
508
+ # in-place copy to student params
509
+ param.copy_(teacher_weights[teacher_layer_name])
510
+
511
+ # freeze the convolutional waveform encoder
512
+ if model_args.freeze_feature_encoder:
513
+ student_model.freeze_feature_encoder()
514
+
515
+ if training_args.do_train:
516
+ if data_args.max_train_samples is not None:
517
+ raw_datasets["train"] = (
518
+ raw_datasets["train"]
519
+ .shuffle(seed=training_args.seed)
520
+ .select(range(data_args.max_train_samples))
521
+ )
522
+ # Set the training transforms
523
+ raw_datasets["train"].set_transform(preprocess_data, output_all_columns=False)
524
+
525
+ if training_args.do_eval:
526
+ if data_args.max_eval_samples is not None:
527
+ raw_datasets["eval"] = (
528
+ raw_datasets["eval"]
529
+ .shuffle(seed=training_args.seed)
530
+ .select(range(data_args.max_eval_samples))
531
+ )
532
+ # Set the validation transforms
533
+ raw_datasets["eval"].set_transform(preprocess_data, output_all_columns=False)
534
+
535
+ # Initialize our trainer
536
+ trainer = MultiLabelDistillationTrainer(
537
+ model=student_model,
538
+ teacher_model=teacher_model,
539
+ args=training_args,
540
+ train_dataset=raw_datasets["train"] if training_args.do_train else None,
541
+ eval_dataset=raw_datasets["eval"] if training_args.do_eval else None,
542
+ compute_metrics=compute_metrics,
543
+ tokenizer=feature_extractor,
544
+ )
545
+
546
+ # Training
547
+ if training_args.do_train:
548
+ checkpoint = None
549
+ if training_args.resume_from_checkpoint is not None:
550
+ checkpoint = training_args.resume_from_checkpoint
551
+ elif last_checkpoint is not None:
552
+ checkpoint = last_checkpoint
553
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
554
+ trainer.save_model()
555
+ trainer.log_metrics("train", train_result.metrics)
556
+ trainer.save_metrics("train", train_result.metrics)
557
+ trainer.save_state()
558
+
559
+ # Evaluation
560
+ if training_args.do_eval:
561
+ metrics = trainer.evaluate()
562
+ trainer.log_metrics("eval", metrics)
563
+ trainer.save_metrics("eval", metrics)
564
+
565
+ # Write model card and (optionally) push to hub
566
+ kwargs = {
567
+ "finetuned_from": model_args.model_name_or_path,
568
+ "tasks": "audio-classification",
569
+ "dataset": data_args.dataset_name,
570
+ "tags": ["audio-classification"],
571
+ }
572
+ if training_args.push_to_hub:
573
+ trainer.push_to_hub(**kwargs)
574
+ else:
575
+ trainer.create_model_card(**kwargs)
576
+
577
+
578
+ if __name__ == "__main__":
579
+ main()