xref: /aosp_15_r20/external/libopus/dnn/training_tf2/decode_rdovae.py (revision a58d3d2adb790c104798cd88c8a3aff4fa8b82cc)
1#!/usr/bin/python3
2'''Copyright (c) 2021-2022 Amazon
3   Copyright (c) 2018-2019 Mozilla
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   - Redistributions of source code must retain the above copyright
10   notice, this list of conditions and the following disclaimer.
11
12   - Redistributions in binary form must reproduce the above copyright
13   notice, this list of conditions and the following disclaimer in the
14   documentation and/or other materials provided with the distribution.
15
16   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
20   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27'''
28
29# Train an LPCNet model
30
31import argparse
32#from plc_loader import PLCLoader
33
34parser = argparse.ArgumentParser(description='Train a PLC model')
35
36parser.add_argument('bits', metavar='<bits file>', help='binary features file (int16)')
37parser.add_argument('output', metavar='<output>', help='output features')
38parser.add_argument('--model', metavar='<model>', default='rdovae', help='PLC model python definition (without .py)')
39group1 = parser.add_mutually_exclusive_group()
40group1.add_argument('--weights', metavar='<input weights>', help='model weights')
41parser.add_argument('--cond-size', metavar='<units>', default=1024, type=int, help='number of units in conditioning network (default 1024)')
42parser.add_argument('--batch-size', metavar='<batch size>', default=1, type=int, help='batch size to use (default 128)')
43parser.add_argument('--seq-length', metavar='<sequence length>', default=1000, type=int, help='sequence length to use (default 1000)')
44
45
46args = parser.parse_args()
47
48import importlib
49rdovae = importlib.import_module(args.model)
50
51import sys
52import numpy as np
53from tensorflow.keras.optimizers import Adam
54from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger
55import tensorflow.keras.backend as K
56import h5py
57
58import tensorflow as tf
59from rdovae import pvq_quantize
60from rdovae import apply_dead_zone
61
62# Try reducing batch_size if you run out of memory on your GPU
63batch_size = args.batch_size
64
65model, encoder, decoder, qembedding = rdovae.new_rdovae_model(nb_used_features=20, nb_bits=80, batch_size=batch_size, cond_size=args.cond_size)
66model.load_weights(args.weights)
67
68lpc_order = 16
69nbits=80
70
71
72bits_file = args.bits
73sequence_size = args.seq_length
74
75# u for unquantised, load 16 bit PCM samples and convert to mu-law
76
77
78bits = np.memmap(bits_file + "-syms.f32", dtype='float32', mode='r')
79nb_sequences = len(bits)//(40*sequence_size)//batch_size*batch_size
80bits = bits[:nb_sequences*sequence_size*40]
81
82bits = np.reshape(bits, (nb_sequences, sequence_size//2, 20*4))
83print(bits.shape)
84
85lambda_val = 0.001 * np.ones((nb_sequences, sequence_size//2, 1))
86quant_id = np.round(3.8*np.log(lambda_val/.0002)).astype('int16')
87quant_id = quant_id[:,:,0]
88quant_embed = qembedding(quant_id)
89quant_scale = tf.math.softplus(quant_embed[:,:,:nbits])
90dead_zone = tf.math.softplus(quant_embed[:, :, nbits : 2 * nbits])
91
92bits = bits*quant_scale
93bits = np.round(apply_dead_zone([bits, dead_zone]).numpy())
94bits = bits/quant_scale
95
96
97state = np.memmap(bits_file + "-state.f32", dtype='float32', mode='r')
98
99state = np.reshape(state, (nb_sequences, sequence_size//2, 24))
100state = state[:,-1,:]
101state = pvq_quantize(state, 82)
102#state = state/(1e-15+tf.norm(state, axis=-1,keepdims=True))
103
104print("shapes are:")
105print(bits.shape)
106print(state.shape)
107
108bits = bits[:,1::2,:]
109features = decoder.predict([bits, state], batch_size=batch_size)
110
111features.astype('float32').tofile(args.output)
112