/ Модель

Характеристики

Параметры
905 млн
Лицензия
Apache 2.0
Архитектура
whisper · dense
Библиотека
transformers
Опубликована
14 апр 2024

kotoba-whisper-v1.0

Распознавание речиАудио → текст6 профессий

Дистиллированная модель Whisper для быстрой транскрибации японской речи.

241скачиваний за 30 дней59лайковвеса обновлены23 окт 2024

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Распознавание речи» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Kotoba-Whisper v1.0 — японская модель автоматического распознавания речи, разработанная Asahi Ushio совместно с Kotoba Technologies. Это дистиллированная модель семейства Whisper: полный энкодер взят от Whisper large-v3, а двухслойный декодер инициализирован первым и последним слоями учительской модели. Модель содержит 905,2 млн параметров и предназначена для транскрибации японской речи; обучена на 1 253 часах аудио ReazonSpeech с частотой дискретизации 16 кГц.

По заявлению авторов, она работает в 6,3 раза быстрее Whisper large-v3 при сопоставимой частоте ошибок. В тестах на ReazonSpeech v1.0 показала лучшие CER и WER, чем large-v3, а на CommonVoice 8 и JSUT Basic 5000 — конкурентные результаты. Репозиторий содержит веса Safetensors; модель поддерживается Transformers версии 4.39 и новее. Лицензия — Apache-2.0.

Модель ориентирована на японскую речь и может уступать на других языках и за пределами распределения обучающих данных. Версия v2.0 новее; результаты качества зависят от набора данных и метрики.

Сценарии применения

  • транскрибация японских телепередач
  • преобразование японских аудиозаписей в текст
  • распознавание японской речи в подкастах
  • создание японских субтитров для видео

Ограничения

Модель рассчитана прежде всего на японский язык; качество на других языках не подтверждено. Авторы отмечают, что более новая версия v2.0 доступна отдельно.

Для каких профессий подходит6

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

Kotoba-Whisper (v1.0)

faster-whisper weight, whisper.cpp weight, pipeline with stable-ts/punctuation

News: Newer version of this model is availabel at https://huggingface.co/kotoba-tech/kotoba-whisper-v2.0!

Kotoba-Whisper is a collection of distilled Whisper models for Japanese ASR, developed through the collaboration bewteen Asahi Ushio and Kotoba Technologies. Following the original work of distil-whisper (Robust Knowledge Distillation via Large-Scale Pseudo Labelling), we employ OpenAI's Whisper large-v3 as the teacher model, and the student model consists the full encoder of the teacher large-v3 model and the decoder with two layers initialized from the first and last layer of the large-v3 model. Kotoba-Whisper is 6.3x faster than large-v3, while retaining as low error rate as the large-v3.

As the initial version, we release kotoba-whisper-v1.0 trained on the large subset of ReazonSpeech (the largest speech-transcription paired dataset in Japanese extracted from Japanese TV audio recordings), which amounts 1,253 hours of audio with 16,861,235 characters of transcriptions (5 sec audio with 18 text tokens in average) after those transcriptions more than 10 WER are removed (see WER Filter for detail). The model was trained for 8 epochs with batch size 256 with sampling rate of 16kHz, and the training and evaluation code to reproduce kotoba-whisper is available at https://github.com/kotoba-tech/kotoba-whisper.

Kotoba-whisper-v1.0 achieves better CER and WER than the openai/whisper-large-v3 in the in-domain held-out test set from ReazonSpeech, and achieves competitive CER and WER on the out-of-domain test sets including JSUT basic 5000 and the Japanese subset from CommonVoice 8.0 (see Evaluation for detail).

modelCommonVoice 8 (Japanese test set)JSUT Basic 5000ReazonSpeech (held out test set)
kotoba-tech/kotoba-whisper-v2.058.863.755.6
kotoba-tech/kotoba-whisper-v1.059.264.356.4
openai/whisper-large-v355.159.260.2
openai/whisper-large-v259.363.274.1
openai/whisper-large61.166.474.9
openai/whisper-medium63.469.576
openai/whisper-base87.29391.8
openai/whisper-small74.281.983
openai/whisper-tiny93.897.694.9
ModelParams / MRel. Latency
kotoba-tech/kotoba-whisper-v1.07566.3
openai/whisper-large-v315501.0

Transformers Usage

Kotoba-Whisper is supported in the Hugging Face 🤗 Transformers library from version 4.39 onwards. To run the model, first install the latest version of Transformers.

pip install --upgrade pip
pip install --upgrade transformers accelerate

Short-Form Transcription

The model can be used with the pipeline class to transcribe short-form audio files (< 30-seconds) as follows:

import torch
from transformers import pipeline
from datasets import load_dataset

# config
model_id = "kotoba-tech/kotoba-whisper-v1.0"
torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
device = "cuda:0" if torch.cuda.is_available() else "cpu"
model_kwargs = {"attn_implementation": "sdpa"} if torch.cuda.is_available() else {}
generate_kwargs = {"language": "ja", "task": "transcribe"}

# load model
pipe = pipeline(
    "automatic-speech-recognition",
    model=model_id,
    torch_dtype=torch_dtype,
    device=device,
    model_kwargs=model_kwargs
)

# load sample audio
dataset = load_dataset("japanese-asr/ja_asr.reazonspeech_test", split="test")
sample = dataset[0]["audio"]

# run inference
result = pipe(sample, generate_kwargs=generate_kwargs)
print(result["text"])
  • To transcribe a local audio file, simply pass the path to your audio file when you call the pipeline (make sure the audio is sampled in 16kHz):
- result = pipe(sample, generate_kwargs=generate_kwargs)
+ result = pipe("audio.mp3", generate_kwargs=generate_kwargs)
  • For segment-level timestamps, pass the argument return_timestamps=True and return the "chunks" output:
result = pipe(sample, return_timestamps=True, generate_kwargs=generate_kwargs)
print(result["chunks"])

Sequential Long-Form: Kotoba-whisper is designed to be compatible with OpenAI's sequential long-form transcription algorithm. This algorithm uses a sliding window for buffered inference of long audio files (> 30-seconds), and returns more accurate transcriptions compared to the chunked long-form algorithm. As default, if long audio files are passed to the model, it will transcribes with the sequential long-form transcription. The sequential long-form algorithm should be used in either of the following scenarios:

  1. Transcription accuracy is the most important factor, and latency is less of a consideration
  2. You are transcribing batches of long audio files, in which case the latency of sequential is comparable to chunked, while being up to 0.5% WER more accurate

If you are transcribing single long audio files and latency is the most important factor, you should use the chunked algorithm described below. For a detailed explanation of the different algorithms, refer to Sections 5 of the Distil-Whisper paper. The pipeline class can be used to transcribe long audio files with the sequential algorithm as follows:

Chunked Long-Form

This algorithm should be used when a single large audio file is being transcribed and the fastest possible inference is required. In such circumstances, the chunked algorithm is up to 9x faster than OpenAI's sequential long-form implementation (see Table 7 of the Distil-Whisper paper). To enable chunking, pass the chunk_length_s parameter to the pipeline. For distil-large-v3, a chunk length of 25-seconds is optimal. To activate batching over long audio files, pass the argument batch_size:

import torch
from transformers import pipeline
from datasets import load_dataset

# config
model_id = "kotoba-tech/kotoba-whisper-v1.0"
torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
device = "cuda:0" if torch.cuda.is_available() else "cpu"
model_kwargs = {"attn_implementation": "sdpa"} if torch.cuda.is_available() else {}
generate_kwargs = {"language": "japanese", "task": "transcribe"}

# load model
pipe = pipeline(
    "automatic-speech-recognition",
    model=model_id,
    torch_dtype=torch_dtype,
    device=device,
    model_kwargs=model_kwargs,
    batch_size=16
)

# load sample audio (concatenate instances to create a long audio)
dataset = load_dataset("japanese-asr/ja_asr.reazonspeech_test", split="test")
sample = {"array": np.concatenate([i["array"] for i in dataset[:20]["audio"]]), "sampling_rate": dataset[0]['audio']['sampling_rate']}

# run inference
result = pipe(sample, chunk_length_s=15, generate_kwargs=generate_kwargs)
print(result["text"])

Transcription with Prompt

Kotoba-whisper can generate transcription with prompting as below:

import re
import torch
from transformers import pipeline
from datasets import load_dataset

# config
model_id = "kotoba-tech/kotoba-whisper-v1.0"
torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
device = "cuda:0" if torch.cuda.is_available() else "cpu"
model_kwargs = {"attn_implementation": "sdpa"} if torch.cuda.is_available() else {}
generate_kwargs = {"language": "ja", "task": "transcribe"}

# load model
pipe = pipeline(
    "automatic-speech-recognition",
    model=model_id,
    torch_dtype=torch_dtype,
    device=device,
    model_kwargs=model_kwargs
)

# load sample audio
dataset = load_dataset("japanese-asr/ja_asr.reazonspeech_test", split="test")

# --- Without prompt ---
text = pipe(dataset[10]["audio"], generate_kwargs=generate_kwargs)['text']
print(text)
# 81歳、力強い走りに変わってきます。

# --- With prompt ---: Let's change `81` to `91`.
prompt = "91歳"
generate_kwargs['prompt_ids'] = pipe.tokenizer.get_prompt_ids(prompt, return_tensors="pt").to(device)
text = pipe(dataset[10]["audio"], generate_kwargs=generate_kwargs)['text']
# currently the pipeline for ASR appends the prompt at the beginning of the transcription, so remove it
text = re.sub(rf"\A\s*{prompt}\s*", "", text)
print(text)
# あっぶったでもスルガさん、91歳、力強い走りに変わってきます。

Additional Speed & Memory Improvements

You can apply additional speed and memory improvements to further reduce the inference speed and VRAM requirements. These optimisations primarily target the attention kernel, swapping it from an eager implementation to a more efficient flash attention version.

Flash Attention 2

We recommend using Flash-Attention 2 if your GPU allows for it. To do so, you first need to install Flash Attention:

pip install flash-attn --no-build-isolation

Then pass attn_implementation="flash_attention_2" to from_pretrained:

- model_kwargs = {"attn_implementation": "sdpa"} if torch.cuda.is_available() else {}
+ model_kwargs = {"attn_implementation": "flash_attention_2"} if torch.cuda.is_available() else {}

Model Details

See https://huggingface.co/distil-whisper/distil-large-v3#model-details.

Training

Please refer to https://github.com/kotoba-tech/kotoba-whisper for the model training detail. Datasets used in distillation and the whole model variations can be found at https://huggingface.co/japanese-asr.

Evaluation

The following code-snippets demonstrates how to evaluate the kotoba-whisper model on the Japanese subset of the CommonVoice 8.0. First, we need to install the required packages, including 🤗 Datasets to load the audio data, and 🤗 Evaluate to perform the WER calculation:

pip install --upgrade pip
pip install --upgrade transformers datasets[audio] evaluate jiwer

Evaluation can then be run end-to-end with the following example:

import torch
from transformers import pipeline
from datasets import load_dataset
from evaluate import load
from transformers.models.whisper.english_normalizer import BasicTextNormalizer

# model config
model_id = "kotoba-tech/kotoba-whisper-v1.0"
torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
device = "cuda:0" if torch.cuda.is_available() else "cpu"
model_kwargs = {"attn_implementation": "sdpa"} if torch.cuda.is_available() else {}
generate_kwargs = {"language": "japanese", "task": "transcribe"}
normalizer = BasicTextNormalizer()

# data config
dataset_name = "japanese-asr/ja_asr.reazonspeech_test"
audio_column = 'audio'
text_column = 'transcription'

# load model
pipe = pipeline(
    "automatic-speech-recognition",
    model=model_id,
    torch_dtype=torch_dtype,
    device=device,
    model_kwargs=model_kwargs,
    batch_size=16
)

# load the dataset and sample the audio with 16kHz
dataset = load_dataset(dataset_name, split="test")
transcriptions = pipe(dataset['audio'])
transcriptions = [normalizer(i['text']).replace(" ", "") for i in transcriptions]
references = [normalizer(i).replace(" ", "") for i in dataset['transcription']]

# compute the CER metric
cer_metric = load("cer")
cer = 100 * cer_metric.compute(predictions=transcriptions, references=references)
print(cer)

The huggingface links to the major Japanese ASR datasets for evaluation are summarized at here. For example, to evaluate the model on JSUT Basic5000, change the dataset_name:

- dataset_name = "japanese-asr/ja_asr.reazonspeech_test"
+ dataset_name = "japanese-asr/ja_asr.jsut_basic5000"

Acknowledgements

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
WhisperForConditionalGeneration
Ревизия весов
f116c5b

0 моделей