xref: /aosp_15_r20/external/libopus/dnn/training_tf2/lpcnet_plc.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
29import math
30import tensorflow as tf
31from tensorflow.keras.models import Model
32from tensorflow.keras.layers import Input, GRU, Dense, Embedding, Reshape, Concatenate, Lambda, Conv1D, Multiply, Add, Bidirectional, MaxPooling1D, Activation, GaussianNoise
33from tensorflow.compat.v1.keras.layers import CuDNNGRU
34from tensorflow.keras import backend as K
35from tensorflow.keras.constraints import Constraint
36from tensorflow.keras.initializers import Initializer
37from tensorflow.keras.callbacks import Callback
38import numpy as np
39
40def quant_regularizer(x):
41    Q = 128
42    Q_1 = 1./Q
43    #return .01 * tf.reduce_mean(1 - tf.math.cos(2*3.1415926535897931*(Q*x-tf.round(Q*x))))
44    return .01 * tf.reduce_mean(K.sqrt(K.sqrt(1.0001 - tf.math.cos(2*3.1415926535897931*(Q*x-tf.round(Q*x))))))
45
46
47class WeightClip(Constraint):
48    '''Clips the weights incident to each hidden unit to be inside a range
49    '''
50    def __init__(self, c=2):
51        self.c = c
52
53    def __call__(self, p):
54        # Ensure that abs of adjacent weights don't sum to more than 127. Otherwise there's a risk of
55        # saturation when implementing dot products with SSSE3 or AVX2.
56        return self.c*p/tf.maximum(self.c, tf.repeat(tf.abs(p[:, 1::2])+tf.abs(p[:, 0::2]), 2, axis=1))
57        #return K.clip(p, -self.c, self.c)
58
59    def get_config(self):
60        return {'name': self.__class__.__name__,
61            'c': self.c}
62
63constraint = WeightClip(0.992)
64
65def new_lpcnet_plc_model(rnn_units=256, nb_used_features=20, nb_burg_features=36, batch_size=128, training=False, adaptation=False, quantize=False, cond_size=128):
66    feat = Input(shape=(None, nb_used_features+nb_burg_features), batch_size=batch_size)
67    lost = Input(shape=(None, 1), batch_size=batch_size)
68
69    fdense1 = Dense(cond_size, activation='tanh', name='plc_dense1')
70
71    cfeat = Concatenate()([feat, lost])
72    cfeat = fdense1(cfeat)
73    #cfeat = Conv1D(cond_size, 3, padding='causal', activation='tanh', name='plc_conv1')(cfeat)
74
75    quant = quant_regularizer if quantize else None
76
77    if training:
78        rnn = CuDNNGRU(rnn_units, return_sequences=True, return_state=True, name='plc_gru1', stateful=True,
79              kernel_constraint=constraint, recurrent_constraint = constraint, kernel_regularizer=quant, recurrent_regularizer=quant)
80        rnn2 = CuDNNGRU(rnn_units, return_sequences=True, return_state=True, name='plc_gru2', stateful=True,
81              kernel_constraint=constraint, recurrent_constraint = constraint, kernel_regularizer=quant, recurrent_regularizer=quant)
82    else:
83        rnn = GRU(rnn_units, return_sequences=True, return_state=True, recurrent_activation="sigmoid", reset_after='true', name='plc_gru1', stateful=True,
84              kernel_constraint=constraint, recurrent_constraint = constraint, kernel_regularizer=quant, recurrent_regularizer=quant)
85        rnn2 = GRU(rnn_units, return_sequences=True, return_state=True, recurrent_activation="sigmoid", reset_after='true', name='plc_gru2', stateful=True,
86              kernel_constraint=constraint, recurrent_constraint = constraint, kernel_regularizer=quant, recurrent_regularizer=quant)
87
88    gru_out1, _ = rnn(cfeat)
89    gru_out1 = GaussianNoise(.005)(gru_out1)
90    gru_out2, _ = rnn2(gru_out1)
91
92    out_dense = Dense(nb_used_features, activation='linear', name='plc_out')
93    plc_out = out_dense(gru_out2)
94
95    model = Model([feat, lost], plc_out)
96    model.rnn_units = rnn_units
97    model.cond_size = cond_size
98    model.nb_used_features = nb_used_features
99    model.nb_burg_features = nb_burg_features
100
101    return model
102