sanchit-gandhi HF staff commited on
Commit
662b801
1 Parent(s): f8a23a5
Files changed (2) hide show
  1. run.sh +28 -0
  2. run_audio_classification.py +422 -0
run.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_audio_classification.py \
2
+ --model_name_or_path openai/whisper-base \
3
+ --dataset_name common_language \
4
+ --output_dir whisper-base-ft-common-language-id \
5
+ --overwrite_output_dir \
6
+ --remove_unused_columns False \
7
+ --do_train \
8
+ --do_eval \
9
+ --fp16 \
10
+ --learning_rate 1e-5 \
11
+ --max_length_seconds 30 \
12
+ --attention_mask False \
13
+ --warmup_ratio 0.1 \
14
+ --num_train_epochs 10 \
15
+ --per_device_train_batch_size 32 \
16
+ --per_device_eval_batch_size 16 \
17
+ --gradient_checkpointing \
18
+ --dataloader_num_workers 4 \
19
+ --logging_strategy steps \
20
+ --logging_steps 25 \
21
+ --evaluation_strategy epoch \
22
+ --save_strategy epoch \
23
+ --load_best_model_at_end True \
24
+ --metric_for_best_model accuracy \
25
+ --seed 0 \
26
+ --freeze_feature_encoder False \
27
+ --label_column_name language \
28
+ --push_to_hub
run_audio_classification.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
22
+ from random import randint
23
+ from typing import Optional
24
+
25
+ import datasets
26
+ import evaluate
27
+ import numpy as np
28
+ from datasets import DatasetDict, load_dataset
29
+
30
+ import transformers
31
+ from transformers import (
32
+ AutoConfig,
33
+ AutoFeatureExtractor,
34
+ AutoModelForAudioClassification,
35
+ HfArgumentParser,
36
+ Trainer,
37
+ TrainingArguments,
38
+ set_seed,
39
+ )
40
+ from transformers.trainer_utils import get_last_checkpoint
41
+ from transformers.utils import check_min_version, send_example_telemetry
42
+ from transformers.utils.versions import require_version
43
+
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
48
+ check_min_version("4.27.0.dev0")
49
+
50
+ require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt")
51
+
52
+
53
+ def random_subsample(wav: np.ndarray, max_length: float, sample_rate: int = 16000):
54
+ """Randomly sample chunks of `max_length` seconds from the input audio"""
55
+ sample_length = int(round(sample_rate * max_length))
56
+ if len(wav) <= sample_length:
57
+ return wav
58
+ random_offset = randint(0, len(wav) - sample_length - 1)
59
+ return wav[random_offset : random_offset + sample_length]
60
+
61
+
62
+ @dataclass
63
+ class DataTrainingArguments:
64
+ """
65
+ Arguments pertaining to what data we are going to input our model for training and eval.
66
+ Using `HfArgumentParser` we can turn this class
67
+ into argparse arguments to be able to specify them on
68
+ the command line.
69
+ """
70
+
71
+ dataset_name: Optional[str] = field(default=None, metadata={"help": "Name of a dataset from the datasets package"})
72
+ dataset_config_name: Optional[str] = field(
73
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
74
+ )
75
+ train_file: Optional[str] = field(
76
+ default=None, metadata={"help": "A file containing the training audio paths and labels."}
77
+ )
78
+ eval_file: Optional[str] = field(
79
+ default=None, metadata={"help": "A file containing the validation audio paths and labels."}
80
+ )
81
+ train_split_name: str = field(
82
+ default="train",
83
+ metadata={
84
+ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
85
+ },
86
+ )
87
+ eval_split_name: str = field(
88
+ default="validation",
89
+ metadata={
90
+ "help": (
91
+ "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
92
+ )
93
+ },
94
+ )
95
+ audio_column_name: str = field(
96
+ default="audio",
97
+ metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
98
+ )
99
+ label_column_name: str = field(
100
+ default="label", metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}
101
+ )
102
+ max_train_samples: Optional[int] = field(
103
+ default=None,
104
+ metadata={
105
+ "help": (
106
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
107
+ "value if set."
108
+ )
109
+ },
110
+ )
111
+ max_eval_samples: Optional[int] = field(
112
+ default=None,
113
+ metadata={
114
+ "help": (
115
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
116
+ "value if set."
117
+ )
118
+ },
119
+ )
120
+ max_length_seconds: float = field(
121
+ default=20,
122
+ metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."},
123
+ )
124
+
125
+
126
+ @dataclass
127
+ class ModelArguments:
128
+ """
129
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
130
+ """
131
+
132
+ model_name_or_path: str = field(
133
+ default="facebook/wav2vec2-base",
134
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"},
135
+ )
136
+ config_name: Optional[str] = field(
137
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
138
+ )
139
+ cache_dir: Optional[str] = field(
140
+ default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"}
141
+ )
142
+ model_revision: str = field(
143
+ default="main",
144
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
145
+ )
146
+ feature_extractor_name: Optional[str] = field(
147
+ default=None, metadata={"help": "Name or path of preprocessor config."}
148
+ )
149
+ freeze_feature_encoder: bool = field(
150
+ default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
151
+ )
152
+ attention_mask: bool = field(
153
+ default=True, metadata={"help": "Whether to generate an attention mask in the feature extractor."}
154
+ )
155
+ use_auth_token: bool = field(
156
+ default=False,
157
+ metadata={
158
+ "help": (
159
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
160
+ "with private models)."
161
+ )
162
+ },
163
+ )
164
+ freeze_feature_extractor: Optional[bool] = field(
165
+ default=None, metadata={"help": "Whether to freeze the feature extractor layers of the model."}
166
+ )
167
+ ignore_mismatched_sizes: bool = field(
168
+ default=False,
169
+ metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."},
170
+ )
171
+ dropout: Optional[float] = field(
172
+ default=0., metadata={"help": "Encoder dropout to apply."}
173
+ )
174
+
175
+ def __post_init__(self):
176
+ if not self.freeze_feature_extractor and self.freeze_feature_encoder:
177
+ warnings.warn(
178
+ "The argument `--freeze_feature_extractor` is deprecated and "
179
+ "will be removed in a future version. Use `--freeze_feature_encoder`"
180
+ "instead. Setting `freeze_feature_encoder==True`.",
181
+ FutureWarning,
182
+ )
183
+ if self.freeze_feature_extractor and not self.freeze_feature_encoder:
184
+ raise ValueError(
185
+ "The argument `--freeze_feature_extractor` is deprecated and "
186
+ "should not be used in combination with `--freeze_feature_encoder`."
187
+ "Only make use of `--freeze_feature_encoder`."
188
+ )
189
+
190
+
191
+ def main():
192
+ # See all possible arguments in src/transformers/training_args.py
193
+ # or by passing the --help flag to this script.
194
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
195
+
196
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
197
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
198
+ # If we pass only one argument to the script and it's the path to a json file,
199
+ # let's parse it to get our arguments.
200
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
201
+ else:
202
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
203
+
204
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
205
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
206
+ send_example_telemetry("run_audio_classification", model_args, data_args)
207
+
208
+ # Setup logging
209
+ logging.basicConfig(
210
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
211
+ datefmt="%m/%d/%Y %H:%M:%S",
212
+ handlers=[logging.StreamHandler(sys.stdout)],
213
+ )
214
+
215
+ if training_args.should_log:
216
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
217
+ transformers.utils.logging.set_verbosity_info()
218
+
219
+ log_level = training_args.get_process_log_level()
220
+ logger.setLevel(log_level)
221
+ transformers.utils.logging.set_verbosity(log_level)
222
+ transformers.utils.logging.enable_default_handler()
223
+ transformers.utils.logging.enable_explicit_format()
224
+
225
+ # Log on each process the small summary:
226
+ logger.warning(
227
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
228
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
229
+ )
230
+ logger.info(f"Training/evaluation parameters {training_args}")
231
+
232
+ # Set seed before initializing model.
233
+ set_seed(training_args.seed)
234
+
235
+ # Detecting last checkpoint.
236
+ last_checkpoint = None
237
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
238
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
239
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
240
+ raise ValueError(
241
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
242
+ "Use --overwrite_output_dir to train from scratch."
243
+ )
244
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
245
+ logger.info(
246
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
247
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
248
+ )
249
+
250
+ # Initialize our dataset and prepare it for the audio classification task.
251
+ raw_datasets = DatasetDict()
252
+ raw_datasets["train"] = load_dataset(
253
+ data_args.dataset_name,
254
+ data_args.dataset_config_name,
255
+ split=data_args.train_split_name,
256
+ use_auth_token=True if model_args.use_auth_token else None,
257
+ )
258
+ raw_datasets["eval"] = load_dataset(
259
+ data_args.dataset_name,
260
+ data_args.dataset_config_name,
261
+ split=data_args.eval_split_name,
262
+ use_auth_token=True if model_args.use_auth_token else None,
263
+ )
264
+
265
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
266
+ raise ValueError(
267
+ f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
268
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
269
+ f"{', '.join(raw_datasets['train'].column_names)}."
270
+ )
271
+
272
+ if data_args.label_column_name not in raw_datasets["train"].column_names:
273
+ raise ValueError(
274
+ f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
275
+ "Make sure to set `--label_column_name` to the correct text column - one of "
276
+ f"{', '.join(raw_datasets['train'].column_names)}."
277
+ )
278
+
279
+ # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
280
+ # transformer outputs in the classifier, but it doesn't always lead to better accuracy
281
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
282
+ model_args.feature_extractor_name or model_args.model_name_or_path,
283
+ return_attention_mask=model_args.attention_mask,
284
+ cache_dir=model_args.cache_dir,
285
+ revision=model_args.model_revision,
286
+ use_auth_token=True if model_args.use_auth_token else None,
287
+ )
288
+
289
+ # `datasets` takes care of automatically loading and resampling the audio,
290
+ # so we just need to set the correct target sampling rate.
291
+ raw_datasets = raw_datasets.cast_column(
292
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
293
+ )
294
+
295
+ model_input_name = feature_extractor.model_input_names[0]
296
+
297
+ def train_transforms(batch):
298
+ """Apply train_transforms across a batch."""
299
+ subsampled_wavs = []
300
+ for audio in batch[data_args.audio_column_name]:
301
+ wav = random_subsample(
302
+ audio["array"], max_length=data_args.max_length_seconds, sample_rate=feature_extractor.sampling_rate
303
+ )
304
+ subsampled_wavs.append(wav)
305
+ inputs = feature_extractor(subsampled_wavs, sampling_rate=feature_extractor.sampling_rate)
306
+ output_batch = {model_input_name: inputs.get(model_input_name)}
307
+ output_batch["labels"] = list(batch[data_args.label_column_name])
308
+
309
+ return output_batch
310
+
311
+ def val_transforms(batch):
312
+ """Apply val_transforms across a batch."""
313
+ wavs = [audio["array"] for audio in batch[data_args.audio_column_name]]
314
+ inputs = feature_extractor(wavs, sampling_rate=feature_extractor.sampling_rate)
315
+ output_batch = {model_input_name: inputs.get(model_input_name)}
316
+ output_batch["labels"] = list(batch[data_args.label_column_name])
317
+
318
+ return output_batch
319
+
320
+ # Prepare label mappings.
321
+ # We'll include these in the model's config to get human readable labels in the Inference API.
322
+ labels = raw_datasets["train"].features[data_args.label_column_name].names
323
+ label2id, id2label = {}, {}
324
+ for i, label in enumerate(labels):
325
+ label2id[label] = str(i)
326
+ id2label[str(i)] = label
327
+
328
+ # Load the accuracy metric from the datasets package
329
+ metric = evaluate.load("accuracy")
330
+
331
+ # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
332
+ # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
333
+ def compute_metrics(eval_pred):
334
+ """Computes accuracy on a batch of predictions"""
335
+ predictions = np.argmax(eval_pred.predictions, axis=1)
336
+ return metric.compute(predictions=predictions, references=eval_pred.label_ids)
337
+
338
+ config = AutoConfig.from_pretrained(
339
+ model_args.config_name or model_args.model_name_or_path,
340
+ num_labels=len(labels),
341
+ label2id=label2id,
342
+ id2label=id2label,
343
+ finetuning_task="audio-classification",
344
+ cache_dir=model_args.cache_dir,
345
+ revision=model_args.model_revision,
346
+ use_auth_token=True if model_args.use_auth_token else None,
347
+ )
348
+ config.activation_dropout = config.attention_dropout = config.dropout = model_args.dropout
349
+ model = AutoModelForAudioClassification.from_pretrained(
350
+ model_args.model_name_or_path,
351
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
352
+ config=config,
353
+ cache_dir=model_args.cache_dir,
354
+ revision=model_args.model_revision,
355
+ use_auth_token=True if model_args.use_auth_token else None,
356
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
357
+ )
358
+
359
+ # freeze the convolutional waveform encoder
360
+ if model_args.freeze_feature_encoder:
361
+ model.freeze_feature_encoder()
362
+
363
+ if training_args.do_train:
364
+ if data_args.max_train_samples is not None:
365
+ raw_datasets["train"] = (
366
+ raw_datasets["train"].shuffle(seed=training_args.seed).select(range(data_args.max_train_samples))
367
+ )
368
+ # Set the training transforms
369
+ raw_datasets["train"].set_transform(train_transforms, output_all_columns=False)
370
+
371
+ if training_args.do_eval:
372
+ if data_args.max_eval_samples is not None:
373
+ raw_datasets["eval"] = (
374
+ raw_datasets["eval"].shuffle(seed=training_args.seed).select(range(data_args.max_eval_samples))
375
+ )
376
+ # Set the validation transforms
377
+ raw_datasets["eval"].set_transform(val_transforms, output_all_columns=False)
378
+
379
+ # Initialize our trainer
380
+ trainer = Trainer(
381
+ model=model,
382
+ args=training_args,
383
+ train_dataset=raw_datasets["train"] if training_args.do_train else None,
384
+ eval_dataset=raw_datasets["eval"] if training_args.do_eval else None,
385
+ compute_metrics=compute_metrics,
386
+ tokenizer=feature_extractor,
387
+ )
388
+
389
+ # Training
390
+ if training_args.do_train:
391
+ checkpoint = None
392
+ if training_args.resume_from_checkpoint is not None:
393
+ checkpoint = training_args.resume_from_checkpoint
394
+ elif last_checkpoint is not None:
395
+ checkpoint = last_checkpoint
396
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
397
+ trainer.save_model()
398
+ trainer.log_metrics("train", train_result.metrics)
399
+ trainer.save_metrics("train", train_result.metrics)
400
+ trainer.save_state()
401
+
402
+ # Evaluation
403
+ if training_args.do_eval:
404
+ metrics = trainer.evaluate()
405
+ trainer.log_metrics("eval", metrics)
406
+ trainer.save_metrics("eval", metrics)
407
+
408
+ # Write model card and (optionally) push to hub
409
+ kwargs = {
410
+ "finetuned_from": model_args.model_name_or_path,
411
+ "tasks": "audio-classification",
412
+ "dataset": data_args.dataset_name,
413
+ "tags": ["audio-classification"],
414
+ }
415
+ if training_args.push_to_hub:
416
+ trainer.push_to_hub(**kwargs)
417
+ else:
418
+ trainer.create_model_card(**kwargs)
419
+
420
+
421
+ if __name__ == "__main__":
422
+ main()