Spaces:
Running
on
Zero
Running
on
Zero
File size: 3,197 Bytes
b9d6819 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
import torch
import torch.nn as nn
from .dac import DAC
from .stable_vae import load_vae
class Autoencoder(nn.Module):
def __init__(self, ckpt_path, model_type='dac', quantization_first=False):
super(Autoencoder, self).__init__()
self.model_type = model_type
if self.model_type == 'dac':
model = DAC.load(ckpt_path)
elif self.model_type == 'stable_vae':
model = load_vae(ckpt_path)
else:
raise NotImplementedError(f"Model type not implemented: {self.model_type}")
self.ae = model.eval()
self.quantization_first = quantization_first
print(f'Autoencoder quantization first mode: {quantization_first}')
@torch.no_grad()
def forward(self, audio=None, embedding=None):
if self.model_type == 'dac':
return self.process_dac(audio, embedding)
elif self.model_type == 'encodec':
return self.process_encodec(audio, embedding)
elif self.model_type == 'stable_vae':
return self.process_stable_vae(audio, embedding)
else:
raise NotImplementedError(f"Model type not implemented: {self.model_type}")
def process_dac(self, audio=None, embedding=None):
if audio is not None:
z = self.ae.encoder(audio)
if self.quantization_first:
z, *_ = self.ae.quantizer(z, None)
return z
elif embedding is not None:
z = embedding
if self.quantization_first:
audio = self.ae.decoder(z)
else:
z, *_ = self.ae.quantizer(z, None)
audio = self.ae.decoder(z)
return audio
else:
raise ValueError("Either audio or embedding must be provided.")
def process_encodec(self, audio=None, embedding=None):
if audio is not None:
z = self.ae.encoder(audio)
if self.quantization_first:
code = self.ae.quantizer.encode(z)
z = self.ae.quantizer.decode(code)
return z
elif embedding is not None:
z = embedding
if self.quantization_first:
audio = self.ae.decoder(z)
else:
code = self.ae.quantizer.encode(z)
z = self.ae.quantizer.decode(code)
audio = self.ae.decoder(z)
return audio
else:
raise ValueError("Either audio or embedding must be provided.")
def process_stable_vae(self, audio=None, embedding=None):
if audio is not None:
z = self.ae.encoder(audio)
if self.quantization_first:
z = self.ae.bottleneck.encode(z)
return z
if embedding is not None:
z = embedding
if self.quantization_first:
audio = self.ae.decoder(z)
else:
z = self.ae.bottleneck.encode(z)
audio = self.ae.decoder(z)
return audio
else:
raise ValueError("Either audio or embedding must be provided.")
|