xref: /aosp_15_r20/external/libopus/dnn/training_tf2/encode_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('features', metavar='<features file>', help='binary features file (float32)')
37parser.add_argument('output', metavar='<output>', help='trained model file (.h5)')
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
51from rdovae import apply_dead_zone
52
53import sys
54import numpy as np
55from tensorflow.keras.optimizers import Adam
56from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger
57import tensorflow.keras.backend as K
58import h5py
59
60import tensorflow as tf
61from rdovae import pvq_quantize
62
63# Try reducing batch_size if you run out of memory on your GPU
64batch_size = args.batch_size
65
66model, encoder, decoder, qembedding = rdovae.new_rdovae_model(nb_used_features=20, nb_bits=80, batch_size=batch_size, cond_size=args.cond_size)
67model.load_weights(args.weights)
68
69lpc_order = 16
70
71feature_file = args.features
72nb_features = model.nb_used_features + lpc_order
73nb_used_features = model.nb_used_features
74sequence_size = args.seq_length
75
76# u for unquantised, load 16 bit PCM samples and convert to mu-law
77
78
79features = np.memmap(feature_file, dtype='float32', mode='r')
80nb_sequences = len(features)//(nb_features*sequence_size)//batch_size*batch_size
81features = features[:nb_sequences*sequence_size*nb_features]
82
83features = np.reshape(features, (nb_sequences, sequence_size, nb_features))
84print(features.shape)
85features = features[:, :, :nb_used_features]
86#features = np.random.randn(73600, 1000, 17)
87
88
89bits, gru_state_dec = encoder.predict([features], batch_size=batch_size)
90(gru_state_dec).astype('float32').tofile(args.output + "-state.f32")
91
92
93#dist = rdovae.feat_dist_loss(features, quant_out)
94#rate = rdovae.sq1_rate_loss(features, model_bits)
95#rate2 = rdovae.sq_rate_metric(features, model_bits)
96#print(dist, rate, rate2)
97
98print("shapes are:")
99print(bits.shape)
100print(gru_state_dec.shape)
101
102features.astype('float32').tofile(args.output + "-input.f32")
103#quant_out.astype('float32').tofile(args.output + "-enc_dec.f32")
104nbits=80
105bits.astype('float32').tofile(args.output + "-syms.f32")
106
107lambda_val = 0.0002 * np.ones((nb_sequences, sequence_size//2, 1))
108quant_id = np.round(3.8*np.log(lambda_val/.0002)).astype('int16')
109quant_id = quant_id[:,:,0]
110quant_embed = qembedding(quant_id)
111quant_scale = tf.math.softplus(quant_embed[:,:,:nbits])
112dead_zone = tf.math.softplus(quant_embed[:, :, nbits : 2 * nbits])
113
114bits = bits*quant_scale
115bits = np.round(apply_dead_zone([bits, dead_zone]).numpy())
116bits = bits/quant_scale
117
118gru_state_dec = pvq_quantize(gru_state_dec, 82)
119#gru_state_dec = gru_state_dec/(1e-15+tf.norm(gru_state_dec, axis=-1,keepdims=True))
120gru_state_dec = gru_state_dec[:,-1,:]
121dec_out = decoder([bits[:,1::2,:], gru_state_dec])
122
123print(dec_out.shape)
124
125dec_out.numpy().astype('float32').tofile(args.output + "-quant_out.f32")
126