added hubert safetensors
This commit is contained in:
+3
-4
@@ -1,9 +1,8 @@
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
from typing import Union
|
||||
import zlib
|
||||
from .utils import get_hash, get_merge_func
|
||||
from .utils import get_merge_func
|
||||
import numpy as np
|
||||
import librosa
|
||||
import soundfile as sf
|
||||
@@ -40,8 +39,8 @@ def load_audio(file, sr, **kwargs):
|
||||
.output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
|
||||
.run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
|
||||
)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to load audio: {e}")
|
||||
except Exception as error:
|
||||
raise RuntimeError(f"Failed to load audio: {error=} {file=}")
|
||||
|
||||
return remix_audio((np.frombuffer(out, np.float32).flatten(), sr),**kwargs)
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import torch
|
||||
from transformers import HubertModel, HubertConfig
|
||||
import safetensors.torch as st
|
||||
from safetensors import safe_open
|
||||
import json
|
||||
|
||||
class HubertModelWithFinalProj(HubertModel):
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
|
||||
# The final projection layer is only used for backward compatibility.
|
||||
# Following https://github.com/auspicious3000/contentvec/issues/6
|
||||
# Remove this layer is necessary to achieve the desired outcome.
|
||||
self.final_proj = torch.nn.Linear(config.hidden_size, config.classifier_proj_size)
|
||||
|
||||
@staticmethod
|
||||
def load_safetensors(path: str, device="cpu"):
|
||||
assert path.endswith(".safetensors"), f"{path} must end with '.safetensors'"
|
||||
|
||||
with safe_open(path, framework="pt", device="cpu") as f:
|
||||
metadata = f.metadata()
|
||||
state_dict = {}
|
||||
for key in f.keys():
|
||||
state_dict[key] = f.get_tensor(key)
|
||||
model = HubertModelWithFinalProj(HubertConfig.from_dict(json.loads(metadata["config"])))
|
||||
model.load_state_dict(state_dict=state_dict)
|
||||
return model.to(device)
|
||||
|
||||
def save_safetensors(self, path: str):
|
||||
assert path.endswith(".safetensors"), f"{path} must end with '.safetensors'"
|
||||
|
||||
with open(path,"wb") as f:
|
||||
state_dict = self.state_dict()
|
||||
f.write(st.save(state_dict,dict(config=json.dumps(self.config.to_dict()))))
|
||||
|
||||
def extract_features(self, source: torch.Tensor, version="v2", **kwargs):
|
||||
with torch.no_grad():
|
||||
output_layer = 9 if version == "v1" else 12
|
||||
output = self(source.to(self.config.torch_dtype), output_hidden_states=True)["hidden_states"][output_layer]
|
||||
features = self.final_proj(output) if version == "v1" else output
|
||||
return features.to(source.dtype)
|
||||
+15
-11
@@ -1,10 +1,11 @@
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import torch.nn.functional as F
|
||||
import librosa
|
||||
import torch
|
||||
|
||||
from .infer_pack.loaders import HubertModelWithFinalProj
|
||||
|
||||
def get_hash(model_path):
|
||||
try:
|
||||
with open(model_path, 'rb') as f:
|
||||
@@ -15,18 +16,21 @@ def get_hash(model_path):
|
||||
|
||||
return model_hash
|
||||
|
||||
def load_hubert(model_path,config):
|
||||
def load_hubert(model_path: str, config):
|
||||
try:
|
||||
from fairseq import checkpoint_utils
|
||||
models, _, _ = checkpoint_utils.load_model_ensemble_and_task([model_path],suffix="",)
|
||||
hubert_model = models[0]
|
||||
hubert_model = hubert_model.to(config.device)
|
||||
if config.is_half:
|
||||
hubert_model = hubert_model.half()
|
||||
if model_path.endswith(".safetensors"):
|
||||
return HubertModelWithFinalProj.load_safetensors(model_path, device=config.device)
|
||||
else:
|
||||
hubert_model = hubert_model.float()
|
||||
hubert_model.eval()
|
||||
return hubert_model
|
||||
from fairseq import checkpoint_utils
|
||||
models, _, _ = checkpoint_utils.load_model_ensemble_and_task([model_path],suffix="",)
|
||||
hubert_model = models[0]
|
||||
hubert_model = hubert_model.to(config.device)
|
||||
if config.is_half:
|
||||
hubert_model = hubert_model.half()
|
||||
else:
|
||||
hubert_model = hubert_model.float()
|
||||
hubert_model.eval()
|
||||
return hubert_model
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user