sanchit-gandhi HF staff commited on
Commit
401e1f5
1 Parent(s): f248ee9
Files changed (2) hide show
  1. run.sh +29 -0
  2. run_audio_classification.py +418 -0
run.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python run_audio_classification.py \
2
+ --model_name_or_path openai/whisper-small \
3
+ --dataset_name common_language \
4
+ --output_dir ./ \
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 16 \
16
+ --gradient_accumulation_steps 2 \
17
+ --per_device_eval_batch_size 16 \
18
+ --gradient_checkpointing \
19
+ --dataloader_num_workers 4 \
20
+ --logging_strategy steps \
21
+ --logging_steps 25 \
22
+ --evaluation_strategy epoch \
23
+ --save_strategy epoch \
24
+ --load_best_model_at_end True \
25
+ --metric_for_best_model accuracy \
26
+ --seed 0 \
27
+ --freeze_feature_encoder False \
28
+ --label_column_name language \
29
+ --push_to_hub
run_audio_classification.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
172
+ def __post_init__(self):
173
+ if not self.freeze_feature_extractor and self.freeze_feature_encoder:
174
+ warnings.warn(
175
+ "The argument `--freeze_feature_extractor` is deprecated and "
176
+ "will be removed in a future version. Use `--freeze_feature_encoder`"
177
+ "instead. Setting `freeze_feature_encoder==True`.",
178
+ FutureWarning,
179
+ )
180
+ if self.freeze_feature_extractor and not self.freeze_feature_encoder:
181
+ raise ValueError(
182
+ "The argument `--freeze_feature_extractor` is deprecated and "
183
+ "should not be used in combination with `--freeze_feature_encoder`."
184
+ "Only make use of `--freeze_feature_encoder`."
185
+ )
186
+
187
+
188
+ def main():
189
+ # See all possible arguments in src/transformers/training_args.py
190
+ # or by passing the --help flag to this script.
191
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
192
+
193
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
194
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
195
+ # If we pass only one argument to the script and it's the path to a json file,
196
+ # let's parse it to get our arguments.
197
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
198
+ else:
199
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
200
+
201
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
202
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
203
+ send_example_telemetry("run_audio_classification", model_args, data_args)
204
+
205
+ # Setup logging
206
+ logging.basicConfig(
207
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
208
+ datefmt="%m/%d/%Y %H:%M:%S",
209
+ handlers=[logging.StreamHandler(sys.stdout)],
210
+ )
211
+
212
+ if training_args.should_log:
213
+ # The default of training_args.log_level is passive, so we set log level at info here to have that default.
214
+ transformers.utils.logging.set_verbosity_info()
215
+
216
+ log_level = training_args.get_process_log_level()
217
+ logger.setLevel(log_level)
218
+ transformers.utils.logging.set_verbosity(log_level)
219
+ transformers.utils.logging.enable_default_handler()
220
+ transformers.utils.logging.enable_explicit_format()
221
+
222
+ # Log on each process the small summary:
223
+ logger.warning(
224
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
225
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
226
+ )
227
+ logger.info(f"Training/evaluation parameters {training_args}")
228
+
229
+ # Set seed before initializing model.
230
+ set_seed(training_args.seed)
231
+
232
+ # Detecting last checkpoint.
233
+ last_checkpoint = None
234
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
235
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
236
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
237
+ raise ValueError(
238
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
239
+ "Use --overwrite_output_dir to train from scratch."
240
+ )
241
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
242
+ logger.info(
243
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
244
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
245
+ )
246
+
247
+ # Initialize our dataset and prepare it for the audio classification task.
248
+ raw_datasets = DatasetDict()
249
+ raw_datasets["train"] = load_dataset(
250
+ data_args.dataset_name,
251
+ data_args.dataset_config_name,
252
+ split=data_args.train_split_name,
253
+ use_auth_token=True if model_args.use_auth_token else None,
254
+ )
255
+ raw_datasets["eval"] = load_dataset(
256
+ data_args.dataset_name,
257
+ data_args.dataset_config_name,
258
+ split=data_args.eval_split_name,
259
+ use_auth_token=True if model_args.use_auth_token else None,
260
+ )
261
+
262
+ if data_args.audio_column_name not in raw_datasets["train"].column_names:
263
+ raise ValueError(
264
+ f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
265
+ "Make sure to set `--audio_column_name` to the correct audio column - one of "
266
+ f"{', '.join(raw_datasets['train'].column_names)}."
267
+ )
268
+
269
+ if data_args.label_column_name not in raw_datasets["train"].column_names:
270
+ raise ValueError(
271
+ f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
272
+ "Make sure to set `--label_column_name` to the correct text column - one of "
273
+ f"{', '.join(raw_datasets['train'].column_names)}."
274
+ )
275
+
276
+ # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
277
+ # transformer outputs in the classifier, but it doesn't always lead to better accuracy
278
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
279
+ model_args.feature_extractor_name or model_args.model_name_or_path,
280
+ return_attention_mask=model_args.attention_mask,
281
+ cache_dir=model_args.cache_dir,
282
+ revision=model_args.model_revision,
283
+ use_auth_token=True if model_args.use_auth_token else None,
284
+ )
285
+
286
+ # `datasets` takes care of automatically loading and resampling the audio,
287
+ # so we just need to set the correct target sampling rate.
288
+ raw_datasets = raw_datasets.cast_column(
289
+ data_args.audio_column_name, datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate)
290
+ )
291
+
292
+ model_input_name = feature_extractor.model_input_names[0]
293
+
294
+ def train_transforms(batch):
295
+ """Apply train_transforms across a batch."""
296
+ subsampled_wavs = []
297
+ for audio in batch[data_args.audio_column_name]:
298
+ wav = random_subsample(
299
+ audio["array"], max_length=data_args.max_length_seconds, sample_rate=feature_extractor.sampling_rate
300
+ )
301
+ subsampled_wavs.append(wav)
302
+ inputs = feature_extractor(subsampled_wavs, sampling_rate=feature_extractor.sampling_rate)
303
+ output_batch = {model_input_name: inputs.get(model_input_name)}
304
+ output_batch["labels"] = list(batch[data_args.label_column_name])
305
+
306
+ return output_batch
307
+
308
+ def val_transforms(batch):
309
+ """Apply val_transforms across a batch."""
310
+ wavs = [audio["array"] for audio in batch[data_args.audio_column_name]]
311
+ inputs = feature_extractor(wavs, sampling_rate=feature_extractor.sampling_rate)
312
+ output_batch = {model_input_name: inputs.get(model_input_name)}
313
+ output_batch["labels"] = list(batch[data_args.label_column_name])
314
+
315
+ return output_batch
316
+
317
+ # Prepare label mappings.
318
+ # We'll include these in the model's config to get human readable labels in the Inference API.
319
+ labels = raw_datasets["train"].features[data_args.label_column_name].names
320
+ label2id, id2label = {}, {}
321
+ for i, label in enumerate(labels):
322
+ label2id[label] = str(i)
323
+ id2label[str(i)] = label
324
+
325
+ # Load the accuracy metric from the datasets package
326
+ metric = evaluate.load("accuracy")
327
+
328
+ # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
329
+ # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
330
+ def compute_metrics(eval_pred):
331
+ """Computes accuracy on a batch of predictions"""
332
+ predictions = np.argmax(eval_pred.predictions, axis=1)
333
+ return metric.compute(predictions=predictions, references=eval_pred.label_ids)
334
+
335
+ config = AutoConfig.from_pretrained(
336
+ model_args.config_name or model_args.model_name_or_path,
337
+ num_labels=len(labels),
338
+ label2id=label2id,
339
+ id2label=id2label,
340
+ finetuning_task="audio-classification",
341
+ cache_dir=model_args.cache_dir,
342
+ revision=model_args.model_revision,
343
+ use_auth_token=True if model_args.use_auth_token else None,
344
+ )
345
+ model = AutoModelForAudioClassification.from_pretrained(
346
+ model_args.model_name_or_path,
347
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
348
+ config=config,
349
+ cache_dir=model_args.cache_dir,
350
+ revision=model_args.model_revision,
351
+ use_auth_token=True if model_args.use_auth_token else None,
352
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
353
+ )
354
+
355
+ # freeze the convolutional waveform encoder
356
+ if model_args.freeze_feature_encoder:
357
+ model.freeze_feature_encoder()
358
+
359
+ if training_args.do_train:
360
+ if data_args.max_train_samples is not None:
361
+ raw_datasets["train"] = (
362
+ raw_datasets["train"].shuffle(seed=training_args.seed).select(range(data_args.max_train_samples))
363
+ )
364
+ # Set the training transforms
365
+ raw_datasets["train"].set_transform(train_transforms, output_all_columns=False)
366
+
367
+ if training_args.do_eval:
368
+ if data_args.max_eval_samples is not None:
369
+ raw_datasets["eval"] = (
370
+ raw_datasets["eval"].shuffle(seed=training_args.seed).select(range(data_args.max_eval_samples))
371
+ )
372
+ # Set the validation transforms
373
+ raw_datasets["eval"].set_transform(val_transforms, output_all_columns=False)
374
+
375
+ # Initialize our trainer
376
+ trainer = Trainer(
377
+ model=model,
378
+ args=training_args,
379
+ train_dataset=raw_datasets["train"] if training_args.do_train else None,
380
+ eval_dataset=raw_datasets["eval"] if training_args.do_eval else None,
381
+ compute_metrics=compute_metrics,
382
+ tokenizer=feature_extractor,
383
+ )
384
+
385
+ # Training
386
+ if training_args.do_train:
387
+ checkpoint = None
388
+ if training_args.resume_from_checkpoint is not None:
389
+ checkpoint = training_args.resume_from_checkpoint
390
+ elif last_checkpoint is not None:
391
+ checkpoint = last_checkpoint
392
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
393
+ trainer.save_model()
394
+ trainer.log_metrics("train", train_result.metrics)
395
+ trainer.save_metrics("train", train_result.metrics)
396
+ trainer.save_state()
397
+
398
+ # Evaluation
399
+ if training_args.do_eval:
400
+ metrics = trainer.evaluate()
401
+ trainer.log_metrics("eval", metrics)
402
+ trainer.save_metrics("eval", metrics)
403
+
404
+ # Write model card and (optionally) push to hub
405
+ kwargs = {
406
+ "finetuned_from": model_args.model_name_or_path,
407
+ "tasks": "audio-classification",
408
+ "dataset": data_args.dataset_name,
409
+ "tags": ["audio-classification"],
410
+ }
411
+ if training_args.push_to_hub:
412
+ trainer.push_to_hub(**kwargs)
413
+ else:
414
+ trainer.create_model_card(**kwargs)
415
+
416
+
417
+ if __name__ == "__main__":
418
+ main()