nnfp
copied
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readme
Files and versions
250 lines
9.5 KiB
250 lines
9.5 KiB
# Copyright 2021 Zilliz. All rights reserved.
|
|
#
|
|
# 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 logging
|
|
import warnings
|
|
|
|
import os
|
|
from pathlib import Path
|
|
from typing import List, Union
|
|
|
|
import torch
|
|
import torchaudio
|
|
import numpy
|
|
|
|
from towhee.operator.base import NNOperator
|
|
from towhee import register
|
|
from towhee.types.audio_frame import AudioFrame
|
|
from towhee.models.nnfp import NNFp
|
|
from towhee.models.utils.audio_preprocess import preprocess_wav, MelSpec
|
|
# from towhee.dc2 import accelerate
|
|
|
|
from .configs import default_params, hop25_params, distill_params
|
|
|
|
warnings.filterwarnings('ignore')
|
|
log = logging.getLogger('nnfp_op')
|
|
log.setLevel(logging.ERROR)
|
|
|
|
|
|
# @accelerate
|
|
class Model:
|
|
def __init__(self, params, device='cpu', model_path=None):
|
|
self.device = device
|
|
log.info('Loading model...')
|
|
try:
|
|
state_dict = torch.jit.load(model_path, map_location=self.device)
|
|
except Exception:
|
|
state_dict = torch.load(model_path, map_location=self.device)
|
|
if isinstance(state_dict, torch.nn.Module):
|
|
self.model = state_dict
|
|
else:
|
|
dim = params['dim']
|
|
h = params['h']
|
|
u = params['u']
|
|
f_bin = params['n_mels']
|
|
n_seg = int(params['segment_size'] * params['sample_rate'])
|
|
t = (n_seg + params['hop_length'] - 1) // params['hop_length']
|
|
log.info('Creating model with parameters...')
|
|
self.model = NNFp(
|
|
dim=dim, h=h, u=u,
|
|
in_f=f_bin, in_t=t,
|
|
fuller=params['fuller'],
|
|
activation=params['activation']
|
|
).to(self.device)
|
|
self.model.load_state_dict(state_dict)
|
|
self.model.eval()
|
|
log.info('Model is loaded.')
|
|
|
|
def __call__(self, *args, **kwargs):
|
|
new_args = []
|
|
new_kwargs = {}
|
|
for x in args:
|
|
new_args.append(x.to(self.device))
|
|
for k, v in kwargs.items():
|
|
new_kwargs[k] = v.to(self.device)
|
|
return self.model(*new_args, **new_kwargs)
|
|
|
|
|
|
@register(output_schema=['vecs'])
|
|
class NNFingerprint(NNOperator):
|
|
"""
|
|
Audio embedding operator using Neural Network Fingerprint
|
|
"""
|
|
def __init__(self,
|
|
model_name: str = 'nnfp_default',
|
|
model_path: str = None,
|
|
framework: str = 'pytorch',
|
|
device: str = None
|
|
):
|
|
super().__init__(framework=framework)
|
|
if device is None:
|
|
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
self.device = device
|
|
self.model_name = model_name
|
|
|
|
if model_name == 'nnfp_default':
|
|
self.params = default_params
|
|
elif model_name == 'nnfp_hop25':
|
|
self.params = hop25_params
|
|
elif model_name == 'nnfp_distill':
|
|
self.params == distill_params
|
|
else:
|
|
raise ValueError('Invalid model name. Accept value from ["nnfp_default", "nnfp_hop25", "nnfp_distill"]')
|
|
|
|
if model_path is None:
|
|
path = str(Path(__file__).parent)
|
|
model_path = os.path.join(path, 'saved_model', 'nnfp_fma.pt')
|
|
self.model = Model(params=self.params, device=self.device, model_path=model_path)
|
|
|
|
def __call__(self, data: Union[str, List[AudioFrame]]) -> numpy.ndarray:
|
|
audio_tensors = self.preprocess(data)
|
|
# print(audio_tensors.shape)
|
|
features = self.model(audio_tensors)
|
|
outs = features.detach().cpu().numpy()
|
|
return outs
|
|
|
|
@property
|
|
def _model(self):
|
|
return self.model.model
|
|
|
|
def preprocess(self, frames: Union[str, List[AudioFrame]]):
|
|
if isinstance(frames, str):
|
|
audio, sr = torchaudio.load(frames)
|
|
else:
|
|
sr = frames[0].sample_rate
|
|
layout = frames[0].layout
|
|
if layout == 'stereo':
|
|
frames = [frame.reshape(-1, 2) for frame in frames]
|
|
audio = numpy.vstack(frames).transpose()
|
|
else:
|
|
audio = numpy.hstack(frames)
|
|
if len(audio.shape) == 1:
|
|
audio = audio[None, :]
|
|
audio = self.int2float(audio)
|
|
audio = torch.from_numpy(audio)
|
|
assert len(audio.shape) == 2
|
|
|
|
if sr != self.params['sample_rate']:
|
|
resampler = torchaudio.transforms.Resample(sr, self.params['sample_rate'], dtype=audio.dtype)
|
|
audio = resampler(audio)
|
|
# import resampy
|
|
# audio = audio.detach().cpu().numpy()
|
|
# audio = resampy.resample(audio, sr, self.params['sample_rate'])
|
|
|
|
wav = preprocess_wav(audio,
|
|
segment_size=int(self.params['sample_rate'] * self.params['segment_size']),
|
|
hop_size=int(self.params['sample_rate'] * self.params['hop_size']),
|
|
frame_shift_mul=self.params['frame_shift_mul'])
|
|
wav = wav.to(torch.float32)
|
|
mel = MelSpec(sample_rate=self.params['sample_rate'],
|
|
window_length=self.params['window_length'],
|
|
hop_length=self.params['hop_length'],
|
|
f_min=self.params['f_min'],
|
|
f_max=self.params['f_max'],
|
|
n_mels=self.params['n_mels'],
|
|
naf_mode=self.params['naf_mode'],
|
|
mel_log=self.params['mel_log'],
|
|
spec_norm=self.params['spec_norm'])
|
|
wav = mel(wav)
|
|
return wav
|
|
|
|
@staticmethod
|
|
def int2float(wav: numpy.ndarray, dtype: str = 'float64'):
|
|
"""
|
|
Convert audio imgs from int to float.
|
|
The input dtype must be integers.
|
|
The output dtype is controlled by the parameter `dtype`, defaults to 'float64'.
|
|
|
|
The code is inspired by https://github.com/mgeier/python-audio/blob/master/audio-files/utility.py
|
|
"""
|
|
dtype = numpy.dtype(dtype)
|
|
assert dtype.kind == 'f'
|
|
|
|
if wav.dtype.kind in 'iu':
|
|
# ii = numpy.iinfo(wav.dtype)
|
|
# abs_max = 2 ** (ii.bits - 1)
|
|
# offset = ii.min + abs_max
|
|
# return (wav.astype(dtype) - offset) / abs_max
|
|
if wav.dtype != 'int16':
|
|
wav = (wav >> 16).astype(numpy.int16)
|
|
assert wav.dtype == 'int16'
|
|
wav = (wav / 32768.0).astype(dtype)
|
|
return wav
|
|
else:
|
|
log.warning('Converting float dtype from %s to %s.', wav.dtype, dtype)
|
|
return wav.astype(dtype)
|
|
|
|
@property
|
|
def supported_formats(self):
|
|
return ['onnx']
|
|
|
|
def save_model(self, format: str = 'pytorch', path: str = 'default'):
|
|
if path == 'default':
|
|
path = str(Path(__file__).parent)
|
|
path = os.path.join(path, 'saved', format)
|
|
os.makedirs(path, exist_ok=True)
|
|
name = self.model_name.replace('/', '-')
|
|
path = os.path.join(path, name)
|
|
if format in ['torchscript', 'pytorch']:
|
|
path = path + '.pt'
|
|
elif format == 'onnx':
|
|
path = path + '.onnx'
|
|
else:
|
|
raise ValueError(f'Invalid format {format}.')
|
|
dummy_input = torch.rand(
|
|
(1,) + (self.params['n_mels'], self.params['u'])
|
|
)
|
|
if format == 'pytorch':
|
|
torch.save(self._model, path)
|
|
elif format == 'torchscript':
|
|
try:
|
|
try:
|
|
jit_model = torch.jit.script(self._model)
|
|
except Exception:
|
|
log.warning(
|
|
'Failed to directly export as torchscript.'
|
|
'Using dummy input in shape of %s now.', dummy_input.shape)
|
|
jit_model = torch.jit.trace(self._model.to('cpu'), dummy_input, strict=False)
|
|
torch.jit.save(jit_model, path)
|
|
except Exception as e:
|
|
log.error('Fail to save as torchscript: %s.', e)
|
|
raise RuntimeError(f'Fail to save as torchscript: {e}.')
|
|
elif format == 'onnx':
|
|
try:
|
|
torch.onnx.export(self._model.to('cpu'),
|
|
dummy_input,
|
|
path,
|
|
input_names=['input'],
|
|
output_names=['output'],
|
|
opset_version=12,
|
|
do_constant_folding=True,
|
|
dynamic_axes={'input': {0: 'batch_size'},
|
|
'output': {0: 'batch_size'}
|
|
}
|
|
)
|
|
except Exception as e:
|
|
log.error(f'Fail to save as onnx: {e}.')
|
|
raise RuntimeError(f'Fail to save as onnx: {e}.')
|
|
# todo: elif format == 'tensorrt':
|
|
else:
|
|
log.error(f'Unsupported format "{format}".')
|
|
return Path(path).resolve()
|
|
|
|
def train(self, **kwargs):
|
|
from .train_nnfp import train_nnfp
|
|
config_json_path = kwargs['config_json_path']
|
|
train_nnfp(
|
|
self._model,
|
|
config_json_path=config_json_path
|
|
)
|