Spaces:
Runtime error
Runtime error
Upload ./RepCodec/examples/whisper_model.py with huggingface_hub
Browse files
RepCodec/examples/whisper_model.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) ByteDance, Inc. and its affiliates.
|
| 2 |
+
# Copyright (c) Chutong Meng
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the MIT license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
# Based on fairseq (https://github.com/facebookresearch/fairseq) and
|
| 7 |
+
# Whisper (https://github.com/openai/whisper/)
|
| 8 |
+
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from torch import Tensor
|
| 14 |
+
from whisper.model import AudioEncoder, sinusoids, Whisper, ModelDimensions
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AudioEncoder_(AudioEncoder):
|
| 18 |
+
def __init__(self, *args, **kwargs):
|
| 19 |
+
super(AudioEncoder_, self).__init__(*args, **kwargs)
|
| 20 |
+
|
| 21 |
+
def extract_feature(self, x: Tensor, target_layer: Optional[int] = None):
|
| 22 |
+
"""
|
| 23 |
+
x : torch.Tensor, shape = (batch_size, n_mels, n_ctx)
|
| 24 |
+
the mel spectrogram of the audio
|
| 25 |
+
"""
|
| 26 |
+
x = F.gelu(self.conv1(x))
|
| 27 |
+
x = F.gelu(self.conv2(x))
|
| 28 |
+
x = x.permute(0, 2, 1)
|
| 29 |
+
|
| 30 |
+
length_x = x.shape[1]
|
| 31 |
+
if length_x > self.positional_embedding.shape[0]:
|
| 32 |
+
self.register_buffer("positional_embedding", sinusoids(length_x, self.positional_embedding.shape[1]))
|
| 33 |
+
self.positional_embedding = self.positional_embedding.to(x.device)
|
| 34 |
+
x = (x + self.positional_embedding[:length_x, :]).to(x.dtype)
|
| 35 |
+
|
| 36 |
+
if target_layer is None:
|
| 37 |
+
target_layer = len(self.blocks)
|
| 38 |
+
|
| 39 |
+
for block in self.blocks[:target_layer]:
|
| 40 |
+
x = block(x)
|
| 41 |
+
|
| 42 |
+
return x
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Whisper_(Whisper):
|
| 46 |
+
def __init__(self, dims: ModelDimensions):
|
| 47 |
+
super(Whisper_, self).__init__(dims)
|
| 48 |
+
# replace audio encoder with our audio encoder
|
| 49 |
+
self.encoder = AudioEncoder_(
|
| 50 |
+
self.dims.n_mels,
|
| 51 |
+
self.dims.n_audio_ctx,
|
| 52 |
+
self.dims.n_audio_state,
|
| 53 |
+
self.dims.n_audio_head,
|
| 54 |
+
self.dims.n_audio_layer,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def extract_features(self, mel: torch.Tensor, target_layer: Optional[int] = None):
|
| 58 |
+
return self.encoder.extract_feature(mel, target_layer)
|