Add whisper test (#9808)
* add whisper benchmark code * add librispeech_asr.py * add bigdl license
This commit is contained in:
		
							parent
							
								
									6584539c91
								
							
						
					
					
						commit
						f5752ead36
					
				
					 6 changed files with 687 additions and 0 deletions
				
			
		
							
								
								
									
										295
									
								
								python/llm/test/benchmark/whisper/librispeech_asr.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										295
									
								
								python/llm/test/benchmark/whisper/librispeech_asr.py
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,295 @@
 | 
				
			||||||
 | 
					# coding=utf-8
 | 
				
			||||||
 | 
					# Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Licensed under the Apache License, Version 2.0 (the "License");
 | 
				
			||||||
 | 
					# you may not use this file except in compliance with the License.
 | 
				
			||||||
 | 
					# You may obtain a copy of the License at
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					#     http://www.apache.org/licenses/LICENSE-2.0
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Unless required by applicable law or agreed to in writing, software
 | 
				
			||||||
 | 
					# distributed under the License is distributed on an "AS IS" BASIS,
 | 
				
			||||||
 | 
					# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
				
			||||||
 | 
					# See the License for the specific language governing permissions and
 | 
				
			||||||
 | 
					# limitations under the License.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Lint as: python3
 | 
				
			||||||
 | 
					"""Librispeech automatic speech recognition dataset."""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Copyright 2016 The BigDL Authors.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Licensed under the Apache License, Version 2.0 (the "License");
 | 
				
			||||||
 | 
					# you may not use this file except in compliance with the License.
 | 
				
			||||||
 | 
					# You may obtain a copy of the License at
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					#     http://www.apache.org/licenses/LICENSE-2.0
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Unless required by applicable law or agreed to in writing, software
 | 
				
			||||||
 | 
					# distributed under the License is distributed on an "AS IS" BASIS,
 | 
				
			||||||
 | 
					# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
				
			||||||
 | 
					# See the License for the specific language governing permissions and
 | 
				
			||||||
 | 
					# limitations under the License.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import os
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import datasets
 | 
				
			||||||
 | 
					from datasets.tasks import AutomaticSpeechRecognition
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_CITATION = """\
 | 
				
			||||||
 | 
					@inproceedings{panayotov2015librispeech,
 | 
				
			||||||
 | 
					  title={Librispeech: an ASR corpus based on public domain audio books},
 | 
				
			||||||
 | 
					  author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev},
 | 
				
			||||||
 | 
					  booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2015 IEEE International Conference on},
 | 
				
			||||||
 | 
					  pages={5206--5210},
 | 
				
			||||||
 | 
					  year={2015},
 | 
				
			||||||
 | 
					  organization={IEEE}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_DESCRIPTION = """\
 | 
				
			||||||
 | 
					LibriSpeech is a corpus of approximately 1000 hours of read English speech with sampling rate of 16 kHz,
 | 
				
			||||||
 | 
					prepared by Vassil Panayotov with the assistance of Daniel Povey. The data is derived from read
 | 
				
			||||||
 | 
					audiobooks from the LibriVox project, and has been carefully segmented and aligned.87
 | 
				
			||||||
 | 
					"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_URL = "http://www.openslr.org/12"
 | 
				
			||||||
 | 
					#_DL_URL = "http://www.openslr.org/resources/12/"
 | 
				
			||||||
 | 
					_DL_URL = "./librispeech/"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_DL_URLS = {
 | 
				
			||||||
 | 
					    "clean": {
 | 
				
			||||||
 | 
					        "dev": _DL_URL + "dev-clean.tar.gz",
 | 
				
			||||||
 | 
					        "test": _DL_URL + "test-clean.tar.gz",
 | 
				
			||||||
 | 
					        "train.100": _DL_URL + "train-clean-100.tar.gz",
 | 
				
			||||||
 | 
					        "train.360": _DL_URL + "train-clean-360.tar.gz",
 | 
				
			||||||
 | 
					    },
 | 
				
			||||||
 | 
					    "other": {
 | 
				
			||||||
 | 
					        "test": _DL_URL + "test-other.tar.gz",
 | 
				
			||||||
 | 
					        "dev": _DL_URL + "dev-other.tar.gz",
 | 
				
			||||||
 | 
					        "train.500": _DL_URL + "train-other-500.tar.gz",
 | 
				
			||||||
 | 
					    },
 | 
				
			||||||
 | 
					    "all": {
 | 
				
			||||||
 | 
					        "dev.clean": _DL_URL + "dev-clean.tar.gz",
 | 
				
			||||||
 | 
					        "dev.other": _DL_URL + "dev-other.tar.gz",
 | 
				
			||||||
 | 
					        "test.clean": _DL_URL + "test-clean.tar.gz",
 | 
				
			||||||
 | 
					        "test.other": _DL_URL + "test-other.tar.gz",
 | 
				
			||||||
 | 
					        #"train.clean.100": _DL_URL + "train-clean-100.tar.gz",
 | 
				
			||||||
 | 
					        #"train.clean.360": _DL_URL + "train-clean-360.tar.gz",
 | 
				
			||||||
 | 
					        #"train.other.500": _DL_URL + "train-other-500.tar.gz",
 | 
				
			||||||
 | 
					    },
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class LibrispeechASRConfig(datasets.BuilderConfig):
 | 
				
			||||||
 | 
					    """BuilderConfig for LibriSpeechASR."""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def __init__(self, **kwargs):
 | 
				
			||||||
 | 
					        """
 | 
				
			||||||
 | 
					        Args:
 | 
				
			||||||
 | 
					          data_dir: `string`, the path to the folder containing the files in the
 | 
				
			||||||
 | 
					            downloaded .tar
 | 
				
			||||||
 | 
					          citation: `string`, citation for the data set
 | 
				
			||||||
 | 
					          url: `string`, url for information about the data set
 | 
				
			||||||
 | 
					          **kwargs: keyword arguments forwarded to super.
 | 
				
			||||||
 | 
					        """
 | 
				
			||||||
 | 
					        super(LibrispeechASRConfig, self).__init__(version=datasets.Version("2.1.0", ""), **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class LibrispeechASR(datasets.GeneratorBasedBuilder):
 | 
				
			||||||
 | 
					    """Librispeech dataset."""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    DEFAULT_WRITER_BATCH_SIZE = 256
 | 
				
			||||||
 | 
					    DEFAULT_CONFIG_NAME = "all"
 | 
				
			||||||
 | 
					    BUILDER_CONFIGS = [
 | 
				
			||||||
 | 
					        LibrispeechASRConfig(name="clean", description="'Clean' speech."),
 | 
				
			||||||
 | 
					        LibrispeechASRConfig(name="other", description="'Other', more challenging, speech."),
 | 
				
			||||||
 | 
					        LibrispeechASRConfig(name="all", description="Combined clean and other dataset."),
 | 
				
			||||||
 | 
					    ]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def _info(self):
 | 
				
			||||||
 | 
					        return datasets.DatasetInfo(
 | 
				
			||||||
 | 
					            description=_DESCRIPTION,
 | 
				
			||||||
 | 
					            features=datasets.Features(
 | 
				
			||||||
 | 
					                {
 | 
				
			||||||
 | 
					                    "file": datasets.Value("string"),
 | 
				
			||||||
 | 
					                    "audio": datasets.Audio(sampling_rate=16_000),
 | 
				
			||||||
 | 
					                    "text": datasets.Value("string"),
 | 
				
			||||||
 | 
					                    "speaker_id": datasets.Value("int64"),
 | 
				
			||||||
 | 
					                    "chapter_id": datasets.Value("int64"),
 | 
				
			||||||
 | 
					                    "id": datasets.Value("string"),
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					            supervised_keys=("file", "text"),
 | 
				
			||||||
 | 
					            homepage=_URL,
 | 
				
			||||||
 | 
					            citation=_CITATION,
 | 
				
			||||||
 | 
					            task_templates=[AutomaticSpeechRecognition(audio_column="audio", transcription_column="text")],
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def _split_generators(self, dl_manager):
 | 
				
			||||||
 | 
					        archive_path = dl_manager.download(_DL_URLS[self.config.name])
 | 
				
			||||||
 | 
					        # (Optional) In non-streaming mode, we can extract the archive locally to have actual local audio files:
 | 
				
			||||||
 | 
					        local_extracted_archive = dl_manager.extract(archive_path) if not dl_manager.is_streaming else {}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        if self.config.name == "clean":
 | 
				
			||||||
 | 
					            train_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="train.100",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("train.100"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["train.100"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ),
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="train.360",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("train.360"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["train.360"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ),
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					            dev_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name=datasets.Split.VALIDATION,
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("dev"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["dev"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                )
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					            test_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name=datasets.Split.TEST,
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("test"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["test"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                )
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					        elif self.config.name == "other":
 | 
				
			||||||
 | 
					            train_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="train.500",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("train.500"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["train.500"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                )
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					            dev_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name=datasets.Split.VALIDATION,
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("dev"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["dev"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                )
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					            test_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name=datasets.Split.TEST,
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("test"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["test"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                )
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					        elif self.config.name == "all":
 | 
				
			||||||
 | 
					            #train_splits = [
 | 
				
			||||||
 | 
					            #    datasets.SplitGenerator(
 | 
				
			||||||
 | 
					            #        name="train.clean.100",
 | 
				
			||||||
 | 
					            #        gen_kwargs={
 | 
				
			||||||
 | 
					            #            "local_extracted_archive": local_extracted_archive.get("train.clean.100"),
 | 
				
			||||||
 | 
					            #            "files": dl_manager.iter_archive(archive_path["train.clean.100"]),
 | 
				
			||||||
 | 
					            #        },
 | 
				
			||||||
 | 
					            #    ),
 | 
				
			||||||
 | 
					            #    datasets.SplitGenerator(
 | 
				
			||||||
 | 
					            #        name="train.clean.360",
 | 
				
			||||||
 | 
					            #        gen_kwargs={
 | 
				
			||||||
 | 
					            #            "local_extracted_archive": local_extracted_archive.get("train.clean.360"),
 | 
				
			||||||
 | 
					            #            "files": dl_manager.iter_archive(archive_path["train.clean.360"]),
 | 
				
			||||||
 | 
					            #        },
 | 
				
			||||||
 | 
					            #    ),
 | 
				
			||||||
 | 
					            #    datasets.SplitGenerator(
 | 
				
			||||||
 | 
					            #        name="train.other.500",
 | 
				
			||||||
 | 
					            #        gen_kwargs={
 | 
				
			||||||
 | 
					            #            "local_extracted_archive": local_extracted_archive.get("train.other.500"),
 | 
				
			||||||
 | 
					            #            "files": dl_manager.iter_archive(archive_path["train.other.500"]),
 | 
				
			||||||
 | 
					            #        },
 | 
				
			||||||
 | 
					            #    ),
 | 
				
			||||||
 | 
					            #]
 | 
				
			||||||
 | 
					            dev_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="validation.clean",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("dev.clean"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["dev.clean"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ),
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="validation.other",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("dev.other"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["dev.other"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ),
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					            test_splits = [
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="test.clean",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("test.clean"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["test.clean"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ),
 | 
				
			||||||
 | 
					                datasets.SplitGenerator(
 | 
				
			||||||
 | 
					                    name="test.other",
 | 
				
			||||||
 | 
					                    gen_kwargs={
 | 
				
			||||||
 | 
					                        "local_extracted_archive": local_extracted_archive.get("test.other"),
 | 
				
			||||||
 | 
					                        "files": dl_manager.iter_archive(archive_path["test.other"]),
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                ),
 | 
				
			||||||
 | 
					            ]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return train_splits + dev_splits + test_splits
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def _generate_examples(self, files, local_extracted_archive):
 | 
				
			||||||
 | 
					        """Generate examples from a LibriSpeech archive_path."""
 | 
				
			||||||
 | 
					        key = 0
 | 
				
			||||||
 | 
					        audio_data = {}
 | 
				
			||||||
 | 
					        transcripts = []
 | 
				
			||||||
 | 
					        for path, f in files:
 | 
				
			||||||
 | 
					            if path.endswith(".flac"):
 | 
				
			||||||
 | 
					                id_ = path.split("/")[-1][: -len(".flac")]
 | 
				
			||||||
 | 
					                audio_data[id_] = f.read()
 | 
				
			||||||
 | 
					            elif path.endswith(".trans.txt"):
 | 
				
			||||||
 | 
					                for line in f:
 | 
				
			||||||
 | 
					                    if line:
 | 
				
			||||||
 | 
					                        line = line.decode("utf-8").strip()
 | 
				
			||||||
 | 
					                        id_, transcript = line.split(" ", 1)
 | 
				
			||||||
 | 
					                        audio_file = f"{id_}.flac"
 | 
				
			||||||
 | 
					                        speaker_id, chapter_id = [int(el) for el in id_.split("-")[:2]]
 | 
				
			||||||
 | 
					                        audio_file = (
 | 
				
			||||||
 | 
					                            os.path.join(local_extracted_archive, audio_file)
 | 
				
			||||||
 | 
					                            if local_extracted_archive
 | 
				
			||||||
 | 
					                            else audio_file
 | 
				
			||||||
 | 
					                        )
 | 
				
			||||||
 | 
					                        transcripts.append(
 | 
				
			||||||
 | 
					                            {
 | 
				
			||||||
 | 
					                                "id": id_,
 | 
				
			||||||
 | 
					                                "speaker_id": speaker_id,
 | 
				
			||||||
 | 
					                                "chapter_id": chapter_id,
 | 
				
			||||||
 | 
					                                "file": audio_file,
 | 
				
			||||||
 | 
					                                "text": transcript,
 | 
				
			||||||
 | 
					                            }
 | 
				
			||||||
 | 
					                        )
 | 
				
			||||||
 | 
					            if audio_data and len(audio_data) == len(transcripts):
 | 
				
			||||||
 | 
					                for transcript in transcripts:
 | 
				
			||||||
 | 
					                    audio = {"path": transcript["file"], "bytes": audio_data[transcript["id"]]}
 | 
				
			||||||
 | 
					                    yield key, {"audio": audio, **transcript}
 | 
				
			||||||
 | 
					                    key += 1
 | 
				
			||||||
 | 
					                audio_data = {}
 | 
				
			||||||
 | 
					                transcripts = []
 | 
				
			||||||
							
								
								
									
										78
									
								
								python/llm/test/benchmark/whisper/run_whisper.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										78
									
								
								python/llm/test/benchmark/whisper/run_whisper.py
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,78 @@
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Copyright 2016 The BigDL Authors.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Licensed under the Apache License, Version 2.0 (the "License");
 | 
				
			||||||
 | 
					# you may not use this file except in compliance with the License.
 | 
				
			||||||
 | 
					# You may obtain a copy of the License at
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					#     http://www.apache.org/licenses/LICENSE-2.0
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Unless required by applicable law or agreed to in writing, software
 | 
				
			||||||
 | 
					# distributed under the License is distributed on an "AS IS" BASIS,
 | 
				
			||||||
 | 
					# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
				
			||||||
 | 
					# See the License for the specific language governing permissions and
 | 
				
			||||||
 | 
					# limitations under the License.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from datasets import load_dataset
 | 
				
			||||||
 | 
					from bigdl.llm.transformers import AutoModelForSpeechSeq2Seq
 | 
				
			||||||
 | 
					from transformers import WhisperProcessor
 | 
				
			||||||
 | 
					import torch
 | 
				
			||||||
 | 
					from evaluate import load
 | 
				
			||||||
 | 
					import time
 | 
				
			||||||
 | 
					import argparse
 | 
				
			||||||
 | 
					from bigdl.llm import optimize_model
 | 
				
			||||||
 | 
					import intel_extension_for_pytorch as ipex
 | 
				
			||||||
 | 
					 
 | 
				
			||||||
 | 
					# python whisper_bigdl.py --model_path ./whisper-pretrained-model/whisper-base --data_type other --device xpu
 | 
				
			||||||
 | 
					def get_args():
 | 
				
			||||||
 | 
					    parser = argparse.ArgumentParser(description="Evaluate Whisper performance and accuracy")
 | 
				
			||||||
 | 
					    parser.add_argument('--model_path', required=True, help='pretrained model path')
 | 
				
			||||||
 | 
					    parser.add_argument('--data_type', required=True, help='clean, other')
 | 
				
			||||||
 | 
					    parser.add_argument('--device', required=False, help='cpu, xpu')
 | 
				
			||||||
 | 
					 
 | 
				
			||||||
 | 
					    args = parser.parse_args()
 | 
				
			||||||
 | 
					    return args
 | 
				
			||||||
 | 
					 
 | 
				
			||||||
 | 
					if __name__ == '__main__':
 | 
				
			||||||
 | 
					    args = get_args()
 | 
				
			||||||
 | 
					    if args.device == "":
 | 
				
			||||||
 | 
					        args.device = "cpu"
 | 
				
			||||||
 | 
					 
 | 
				
			||||||
 | 
					    speech_dataset = load_dataset('./librispeech_asr.py', name=args.data_type, split='test').select(range(500))
 | 
				
			||||||
 | 
					    processor = WhisperProcessor.from_pretrained(args.model_path)
 | 
				
			||||||
 | 
					    forced_decoder_ids = processor.get_decoder_prompt_ids(language='en', task='transcribe')
 | 
				
			||||||
 | 
					    # model = AutoModelForSpeechSeq2Seq.from_pretrained(args.model_path)
 | 
				
			||||||
 | 
					    # model = optimize_model(model, low_bit="sym_int4", optimize_llm=False, modules_to_not_convert=[]).to(args.device)
 | 
				
			||||||
 | 
					   
 | 
				
			||||||
 | 
					    model = AutoModelForSpeechSeq2Seq.from_pretrained(args.model_path, load_in_low_bit="sym_int4", optimize_model=True).eval().to(args.device)
 | 
				
			||||||
 | 
					    # model = AutoModelForSpeechSeq2Seq.from_pretrained(args.model_path, load_in_low_bit="fp8_e5m2", optimize_model=True).eval().to(args.device)
 | 
				
			||||||
 | 
					    model.config.forced_decoder_ids = None
 | 
				
			||||||
 | 
					   
 | 
				
			||||||
 | 
					    def map_to_pred(batch):
 | 
				
			||||||
 | 
					        audio = batch["audio"]
 | 
				
			||||||
 | 
					        start_time = time.time()
 | 
				
			||||||
 | 
					        input_features = processor(audio["array"], sampling_rate=audio["sampling_rate"], return_tensors="pt").input_features
 | 
				
			||||||
 | 
					        batch["reference"] = processor.tokenizer._normalize(batch['text'])
 | 
				
			||||||
 | 
					 
 | 
				
			||||||
 | 
					        with torch.no_grad():
 | 
				
			||||||
 | 
					            predicted_ids = model.generate(input_features.to(args.device), forced_decoder_ids=forced_decoder_ids, use_cache=True)[0]
 | 
				
			||||||
 | 
					            if args.device == "xpu":
 | 
				
			||||||
 | 
					                torch.xpu.synchronize()
 | 
				
			||||||
 | 
					 
 | 
				
			||||||
 | 
					        infer_time = time.time() - start_time
 | 
				
			||||||
 | 
					        transcription = processor.decode(predicted_ids)
 | 
				
			||||||
 | 
					        batch["prediction"] = processor.tokenizer._normalize(transcription)
 | 
				
			||||||
 | 
					        batch["length"] = len(audio["array"])/audio["sampling_rate"]
 | 
				
			||||||
 | 
					        batch["time"] = infer_time
 | 
				
			||||||
 | 
					        print(batch["reference"])
 | 
				
			||||||
 | 
					        print(batch["prediction"])
 | 
				
			||||||
 | 
					        return batch
 | 
				
			||||||
 | 
					   
 | 
				
			||||||
 | 
					    result = speech_dataset.map(map_to_pred, keep_in_memory=True)
 | 
				
			||||||
 | 
					    wer = load("wer")
 | 
				
			||||||
 | 
					    speech_length = sum(result["length"][1:])
 | 
				
			||||||
 | 
					    prc_time = sum(result["time"][1:])
 | 
				
			||||||
 | 
					    print("Realtime Factor(RTF) is : %.4f" % (prc_time/speech_length))
 | 
				
			||||||
 | 
					    print("Realtime X(RTX) is : %.2f" % (speech_length/prc_time))
 | 
				
			||||||
 | 
					    print(100 * wer.compute(references=result["reference"], predictions=result["prediction"]))
 | 
				
			||||||
							
								
								
									
										158
									
								
								python/llm/test/benchmark/whisper/wer/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										158
									
								
								python/llm/test/benchmark/whisper/wer/README.md
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,158 @@
 | 
				
			||||||
 | 
					---
 | 
				
			||||||
 | 
					title: WER
 | 
				
			||||||
 | 
					emoji: 🤗 
 | 
				
			||||||
 | 
					colorFrom: blue
 | 
				
			||||||
 | 
					colorTo: red
 | 
				
			||||||
 | 
					sdk: gradio
 | 
				
			||||||
 | 
					sdk_version: 3.0.2
 | 
				
			||||||
 | 
					app_file: app.py
 | 
				
			||||||
 | 
					pinned: false
 | 
				
			||||||
 | 
					tags:
 | 
				
			||||||
 | 
					- evaluate
 | 
				
			||||||
 | 
					- metric
 | 
				
			||||||
 | 
					description: >-
 | 
				
			||||||
 | 
					  Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  Word error rate can then be computed as:
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  WER = (S + D + I) / N = (S + D + I) / (S + D + C)
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  where
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  S is the number of substitutions,
 | 
				
			||||||
 | 
					  D is the number of deletions,
 | 
				
			||||||
 | 
					  I is the number of insertions,
 | 
				
			||||||
 | 
					  C is the number of correct words,
 | 
				
			||||||
 | 
					  N is the number of words in the reference (N=S+D+C).
 | 
				
			||||||
 | 
					  
 | 
				
			||||||
 | 
					  This value indicates the average number of errors per reference word. The lower the value, the better the
 | 
				
			||||||
 | 
					  performance of the ASR system with a WER of 0 being a perfect score.
 | 
				
			||||||
 | 
					---
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Metric Card for WER
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Metric description
 | 
				
			||||||
 | 
					Word error rate (WER) is a common metric of the performance of an automatic speech recognition (ASR) system. 
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					The general difficulty of measuring the performance of ASR systems lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance), working at the word level.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between [perplexity](https://huggingface.co/metrics/perplexity) and word error rate (see [this article](https://www.cs.cmu.edu/~roni/papers/eval-metrics-bntuw-9802.pdf) for further information).
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Word error rate can then be computed as:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					`WER = (S + D + I) / N = (S + D + I) / (S + D + C)`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					where
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					`S` is the number of substitutions,
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					`D` is the number of deletions,
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					`I` is the number of insertions,
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					`C` is the number of correct words,
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					`N` is the number of words in the reference (`N=S+D+C`).
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## How to use 
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					The metric takes two inputs: references (a list of references for each speech input) and predictions (a list of transcriptions to score).
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```python
 | 
				
			||||||
 | 
					from evaluate import load
 | 
				
			||||||
 | 
					wer = load("wer")
 | 
				
			||||||
 | 
					wer_score = wer.compute(predictions=predictions, references=references)
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					## Output values
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					This metric outputs a float representing the word error rate.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					print(wer_score)
 | 
				
			||||||
 | 
					0.5
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					This value indicates the average number of errors per reference word. 
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					The **lower** the value, the **better** the performance of the ASR system, with a WER of 0 being a perfect score.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					### Values from popular papers
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					This metric is highly dependent on the content and quality of the dataset, and therefore users can expect very different values for the same model but on different datasets.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					For example, datasets such as [LibriSpeech](https://huggingface.co/datasets/librispeech_asr) report a WER in the 1.8-3.3 range, whereas ASR models evaluated on [Timit](https://huggingface.co/datasets/timit_asr) report a WER in the 8.3-20.4 range. 
 | 
				
			||||||
 | 
					See the leaderboards for [LibriSpeech](https://paperswithcode.com/sota/speech-recognition-on-librispeech-test-clean) and [Timit](https://paperswithcode.com/sota/speech-recognition-on-timit) for the most recent values.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Examples 
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Perfect match between prediction and reference:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```python
 | 
				
			||||||
 | 
					from evaluate import load
 | 
				
			||||||
 | 
					wer = load("wer")
 | 
				
			||||||
 | 
					predictions = ["hello world", "good night moon"]
 | 
				
			||||||
 | 
					references = ["hello world", "good night moon"]
 | 
				
			||||||
 | 
					wer_score = wer.compute(predictions=predictions, references=references)
 | 
				
			||||||
 | 
					print(wer_score)
 | 
				
			||||||
 | 
					0.0
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Partial match between prediction and reference:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```python
 | 
				
			||||||
 | 
					from evaluate import load
 | 
				
			||||||
 | 
					wer = load("wer")
 | 
				
			||||||
 | 
					predictions = ["this is the prediction", "there is an other sample"]
 | 
				
			||||||
 | 
					references = ["this is the reference", "there is another one"]
 | 
				
			||||||
 | 
					wer_score = wer.compute(predictions=predictions, references=references)
 | 
				
			||||||
 | 
					print(wer_score)
 | 
				
			||||||
 | 
					0.5
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					No match between prediction and reference:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```python
 | 
				
			||||||
 | 
					from evaluate import load
 | 
				
			||||||
 | 
					wer = load("wer")
 | 
				
			||||||
 | 
					predictions = ["hello world", "good night moon"]
 | 
				
			||||||
 | 
					references = ["hi everyone", "have a great day"]
 | 
				
			||||||
 | 
					wer_score = wer.compute(predictions=predictions, references=references)
 | 
				
			||||||
 | 
					print(wer_score)
 | 
				
			||||||
 | 
					1.0
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Limitations and bias
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. 
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Citation
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```bibtex
 | 
				
			||||||
 | 
					@inproceedings{woodard1982,
 | 
				
			||||||
 | 
					author = {Woodard, J.P. and Nelson, J.T.,
 | 
				
			||||||
 | 
					year = {1982},
 | 
				
			||||||
 | 
					journal = {Workshop on standardisation for speech I/O technology, Naval Air Development Center, Warminster, PA},
 | 
				
			||||||
 | 
					title = {An information theoretic measure of speech recognition performance}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```bibtex
 | 
				
			||||||
 | 
					@inproceedings{morris2004,
 | 
				
			||||||
 | 
					author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
 | 
				
			||||||
 | 
					year = {2004},
 | 
				
			||||||
 | 
					month = {01},
 | 
				
			||||||
 | 
					pages = {},
 | 
				
			||||||
 | 
					title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Further References 
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- [Word Error Rate -- Wikipedia](https://en.wikipedia.org/wiki/Word_error_rate)
 | 
				
			||||||
 | 
					- [Hugging Face Tasks -- Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition)
 | 
				
			||||||
							
								
								
									
										22
									
								
								python/llm/test/benchmark/whisper/wer/app.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								python/llm/test/benchmark/whisper/wer/app.py
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,22 @@
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Copyright 2016 The BigDL Authors.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Licensed under the Apache License, Version 2.0 (the "License");
 | 
				
			||||||
 | 
					# you may not use this file except in compliance with the License.
 | 
				
			||||||
 | 
					# You may obtain a copy of the License at
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					#     http://www.apache.org/licenses/LICENSE-2.0
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Unless required by applicable law or agreed to in writing, software
 | 
				
			||||||
 | 
					# distributed under the License is distributed on an "AS IS" BASIS,
 | 
				
			||||||
 | 
					# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
				
			||||||
 | 
					# See the License for the specific language governing permissions and
 | 
				
			||||||
 | 
					# limitations under the License.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import evaluate
 | 
				
			||||||
 | 
					from evaluate.utils import launch_gradio_widget
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					module = evaluate.load("wer")
 | 
				
			||||||
 | 
					launch_gradio_widget(module)
 | 
				
			||||||
							
								
								
									
										2
									
								
								python/llm/test/benchmark/whisper/wer/requirements.txt
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								python/llm/test/benchmark/whisper/wer/requirements.txt
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,2 @@
 | 
				
			||||||
 | 
					git+https://github.com/huggingface/evaluate@{COMMIT_PLACEHOLDER}
 | 
				
			||||||
 | 
					jiwer
 | 
				
			||||||
							
								
								
									
										132
									
								
								python/llm/test/benchmark/whisper/wer/wer.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										132
									
								
								python/llm/test/benchmark/whisper/wer/wer.py
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
					@ -0,0 +1,132 @@
 | 
				
			||||||
 | 
					# Copyright 2021 The HuggingFace Evaluate Authors.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Licensed under the Apache License, Version 2.0 (the "License");
 | 
				
			||||||
 | 
					# you may not use this file except in compliance with the License.
 | 
				
			||||||
 | 
					# You may obtain a copy of the License at
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					#     http://www.apache.org/licenses/LICENSE-2.0
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Unless required by applicable law or agreed to in writing, software
 | 
				
			||||||
 | 
					# distributed under the License is distributed on an "AS IS" BASIS,
 | 
				
			||||||
 | 
					# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
				
			||||||
 | 
					# See the License for the specific language governing permissions and
 | 
				
			||||||
 | 
					# limitations under the License.
 | 
				
			||||||
 | 
					""" Word Error Ratio (WER) metric. """
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Copyright 2016 The BigDL Authors.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Licensed under the Apache License, Version 2.0 (the "License");
 | 
				
			||||||
 | 
					# you may not use this file except in compliance with the License.
 | 
				
			||||||
 | 
					# You may obtain a copy of the License at
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					#     http://www.apache.org/licenses/LICENSE-2.0
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					# Unless required by applicable law or agreed to in writing, software
 | 
				
			||||||
 | 
					# distributed under the License is distributed on an "AS IS" BASIS,
 | 
				
			||||||
 | 
					# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | 
				
			||||||
 | 
					# See the License for the specific language governing permissions and
 | 
				
			||||||
 | 
					# limitations under the License.
 | 
				
			||||||
 | 
					#
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import datasets
 | 
				
			||||||
 | 
					from jiwer import compute_measures
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import evaluate
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_CITATION = """\
 | 
				
			||||||
 | 
					@inproceedings{inproceedings,
 | 
				
			||||||
 | 
					    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
 | 
				
			||||||
 | 
					    year = {2004},
 | 
				
			||||||
 | 
					    month = {01},
 | 
				
			||||||
 | 
					    pages = {},
 | 
				
			||||||
 | 
					    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_DESCRIPTION = """\
 | 
				
			||||||
 | 
					Word error rate (WER) is a common metric of the performance of an automatic speech recognition system.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Word error rate can then be computed as:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					WER = (S + D + I) / N = (S + D + I) / (S + D + C)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					where
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					S is the number of substitutions,
 | 
				
			||||||
 | 
					D is the number of deletions,
 | 
				
			||||||
 | 
					I is the number of insertions,
 | 
				
			||||||
 | 
					C is the number of correct words,
 | 
				
			||||||
 | 
					N is the number of words in the reference (N=S+D+C).
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					This value indicates the average number of errors per reference word. The lower the value, the better the
 | 
				
			||||||
 | 
					performance of the ASR system with a WER of 0 being a perfect score.
 | 
				
			||||||
 | 
					"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					_KWARGS_DESCRIPTION = """
 | 
				
			||||||
 | 
					Compute WER score of transcribed segments against references.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Args:
 | 
				
			||||||
 | 
					    references: List of references for each speech input.
 | 
				
			||||||
 | 
					    predictions: List of transcriptions to score.
 | 
				
			||||||
 | 
					    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Returns:
 | 
				
			||||||
 | 
					    (float): the word error rate
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					Examples:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    >>> predictions = ["this is the prediction", "there is an other sample"]
 | 
				
			||||||
 | 
					    >>> references = ["this is the reference", "there is another one"]
 | 
				
			||||||
 | 
					    >>> wer = evaluate.load("wer")
 | 
				
			||||||
 | 
					    >>> wer_score = wer.compute(predictions=predictions, references=references)
 | 
				
			||||||
 | 
					    >>> print(wer_score)
 | 
				
			||||||
 | 
					    0.5
 | 
				
			||||||
 | 
					"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
 | 
				
			||||||
 | 
					class WER(evaluate.Metric):
 | 
				
			||||||
 | 
					    def _info(self):
 | 
				
			||||||
 | 
					        return evaluate.MetricInfo(
 | 
				
			||||||
 | 
					            description=_DESCRIPTION,
 | 
				
			||||||
 | 
					            citation=_CITATION,
 | 
				
			||||||
 | 
					            inputs_description=_KWARGS_DESCRIPTION,
 | 
				
			||||||
 | 
					            features=datasets.Features(
 | 
				
			||||||
 | 
					                {
 | 
				
			||||||
 | 
					                    "predictions": datasets.Value("string", id="sequence"),
 | 
				
			||||||
 | 
					                    "references": datasets.Value("string", id="sequence"),
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					            codebase_urls=["https://github.com/jitsi/jiwer/"],
 | 
				
			||||||
 | 
					            reference_urls=[
 | 
				
			||||||
 | 
					                "https://en.wikipedia.org/wiki/Word_error_rate",
 | 
				
			||||||
 | 
					            ],
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def _compute(self, predictions=None, references=None, concatenate_texts=False):
 | 
				
			||||||
 | 
					        if concatenate_texts:
 | 
				
			||||||
 | 
					            return compute_measures(references, predictions)["wer"]
 | 
				
			||||||
 | 
					        else:
 | 
				
			||||||
 | 
					            incorrect = 0
 | 
				
			||||||
 | 
					            total = 0
 | 
				
			||||||
 | 
					            max = 0
 | 
				
			||||||
 | 
					            id = 0
 | 
				
			||||||
 | 
					            id_max = 0
 | 
				
			||||||
 | 
					            for prediction, reference in zip(predictions, references):
 | 
				
			||||||
 | 
					                measures = compute_measures(reference, prediction)
 | 
				
			||||||
 | 
					                if measures["substitutions"] + measures["deletions"] + measures["insertions"] > max:
 | 
				
			||||||
 | 
					                    max = measures["substitutions"] + measures["deletions"] + measures["insertions"]
 | 
				
			||||||
 | 
					                    id_max = id
 | 
				
			||||||
 | 
					                incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
 | 
				
			||||||
 | 
					                total += measures["substitutions"] + measures["deletions"] + measures["hits"]
 | 
				
			||||||
 | 
					                id += 1
 | 
				
			||||||
 | 
					            print(id_max, max)
 | 
				
			||||||
 | 
					            print(predictions[id_max])
 | 
				
			||||||
 | 
					            print(references[id_max])
 | 
				
			||||||
 | 
					            return incorrect / total
 | 
				
			||||||
		Loading…
	
		Reference in a new issue