File size: 11,062 Bytes
ad16788 |
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
import logging
import six
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
from chainer import cuda
from espnet.nets.chainer_backend.nets_utils import _subsamplex
from espnet.nets.e2e_asr_common import get_vgg2l_odim
# TODO(watanabe) explanation of BLSTMP
class RNNP(chainer.Chain):
"""RNN with projection layer module.
Args:
idim (int): Dimension of inputs.
elayers (int): Number of encoder layers.
cdim (int): Number of rnn units. (resulted in cdim * 2 if bidirectional)
hdim (int): Number of projection units.
subsample (np.ndarray): List to use sabsample the input array.
dropout (float): Dropout rate.
typ (str): The RNN type.
"""
def __init__(self, idim, elayers, cdim, hdim, subsample, dropout, typ="blstm"):
super(RNNP, self).__init__()
bidir = typ[0] == "b"
if bidir:
rnn = L.NStepBiLSTM if "lstm" in typ else L.NStepBiGRU
else:
rnn = L.NStepLSTM if "lstm" in typ else L.NStepGRU
rnn_label = "birnn" if bidir else "rnn"
with self.init_scope():
for i in six.moves.range(elayers):
if i == 0:
inputdim = idim
else:
inputdim = hdim
_cdim = 2 * cdim if bidir else cdim
# bottleneck layer to merge
setattr(
self, "{}{:d}".format(rnn_label, i), rnn(1, inputdim, cdim, dropout)
)
setattr(self, "bt%d" % i, L.Linear(_cdim, hdim))
self.elayers = elayers
self.rnn_label = rnn_label
self.cdim = cdim
self.subsample = subsample
self.typ = typ
self.bidir = bidir
def __call__(self, xs, ilens):
"""RNNP forward.
Args:
xs (chainer.Variable): Batch of padded charactor ids. (B, Tmax)
ilens (chainer.Variable): Batch of length of each input batch. (B,)
Returns:
xs (chainer.Variable):subsampled vector of xs.
chainer.Variable: Subsampled vector of ilens.
"""
logging.info(self.__class__.__name__ + " input lengths: " + str(ilens))
for layer in six.moves.range(self.elayers):
if "lstm" in self.typ:
_, _, ys = self[self.rnn_label + str(layer)](None, None, xs)
else:
_, ys = self[self.rnn_label + str(layer)](None, xs)
# ys: utt list of frame x cdim x 2 (2: means bidirectional)
# TODO(watanabe) replace subsample and FC layer with CNN
ys, ilens = _subsamplex(ys, self.subsample[layer + 1])
# (sum _utt frame_utt) x dim
ys = self["bt" + str(layer)](F.vstack(ys))
xs = F.split_axis(ys, np.cumsum(ilens[:-1]), axis=0)
# final tanh operation
xs = F.split_axis(F.tanh(F.vstack(xs)), np.cumsum(ilens[:-1]), axis=0)
# 1 utterance case, it becomes an array, so need to make a utt tuple
if not isinstance(xs, tuple):
xs = [xs]
return xs, ilens # x: utt list of frame x dim
class RNN(chainer.Chain):
"""RNN Module.
Args:
idim (int): Dimension of the imput.
elayers (int): Number of encoder layers.
cdim (int): Number of rnn units.
hdim (int): Number of projection units.
dropout (float): Dropout rate.
typ (str): Rnn type.
"""
def __init__(self, idim, elayers, cdim, hdim, dropout, typ="lstm"):
super(RNN, self).__init__()
bidir = typ[0] == "b"
if bidir:
rnn = L.NStepBiLSTM if "lstm" in typ else L.NStepBiGRU
else:
rnn = L.NStepLSTM if "lstm" in typ else L.NStepGRU
_cdim = 2 * cdim if bidir else cdim
with self.init_scope():
self.nbrnn = rnn(elayers, idim, cdim, dropout)
self.l_last = L.Linear(_cdim, hdim)
self.typ = typ
self.bidir = bidir
def __call__(self, xs, ilens):
"""BRNN forward propagation.
Args:
xs (chainer.Variable): Batch of padded charactor ids. (B, Tmax)
ilens (chainer.Variable): Batch of length of each input batch. (B,)
Returns:
tuple(chainer.Variable): Tuple of `chainer.Variable` objects.
chainer.Variable: `ilens` .
"""
logging.info(self.__class__.__name__ + " input lengths: " + str(ilens))
# need to move ilens to cpu
ilens = cuda.to_cpu(ilens)
if "lstm" in self.typ:
_, _, ys = self.nbrnn(None, None, xs)
else:
_, ys = self.nbrnn(None, xs)
ys = self.l_last(F.vstack(ys)) # (sum _utt frame_utt) x dim
xs = F.split_axis(ys, np.cumsum(ilens[:-1]), axis=0)
# final tanh operation
xs = F.split_axis(F.tanh(F.vstack(xs)), np.cumsum(ilens[:-1]), axis=0)
# 1 utterance case, it becomes an array, so need to make a utt tuple
if not isinstance(xs, tuple):
xs = [xs]
return xs, ilens # x: utt list of frame x dim
# TODO(watanabe) explanation of VGG2L, VGG2B (Block) might be better
class VGG2L(chainer.Chain):
"""VGG motibated cnn layers.
Args:
in_channel (int): Number of channels.
"""
def __init__(self, in_channel=1):
super(VGG2L, self).__init__()
with self.init_scope():
# CNN layer (VGG motivated)
self.conv1_1 = L.Convolution2D(in_channel, 64, 3, stride=1, pad=1)
self.conv1_2 = L.Convolution2D(64, 64, 3, stride=1, pad=1)
self.conv2_1 = L.Convolution2D(64, 128, 3, stride=1, pad=1)
self.conv2_2 = L.Convolution2D(128, 128, 3, stride=1, pad=1)
self.in_channel = in_channel
def __call__(self, xs, ilens):
"""VGG2L forward propagation.
Args:
xs (chainer.Variable): Batch of padded charactor ids. (B, Tmax)
ilens (chainer.Variable): Batch of length of each features. (B,)
Returns:
chainer.Variable: Subsampled vector of xs.
chainer.Variable: Subsampled vector of ilens.
"""
logging.info(self.__class__.__name__ + " input lengths: " + str(ilens))
# x: utt x frame x dim
xs = F.pad_sequence(xs)
# x: utt x 1 (input channel num) x frame x dim
xs = F.swapaxes(
xs.reshape(
xs.shape[0],
xs.shape[1],
self.in_channel,
xs.shape[2] // self.in_channel,
),
1,
2,
)
xs = F.relu(self.conv1_1(xs))
xs = F.relu(self.conv1_2(xs))
xs = F.max_pooling_2d(xs, 2, stride=2)
xs = F.relu(self.conv2_1(xs))
xs = F.relu(self.conv2_2(xs))
xs = F.max_pooling_2d(xs, 2, stride=2)
# change ilens accordingly
ilens = self.xp.array(
self.xp.ceil(self.xp.array(ilens, dtype=np.float32) / 2), dtype=np.int32
)
ilens = self.xp.array(
self.xp.ceil(self.xp.array(ilens, dtype=np.float32) / 2), dtype=np.int32
)
# x: utt_list of frame (remove zeropaded frames) x (input channel num x dim)
xs = F.swapaxes(xs, 1, 2)
xs = xs.reshape(xs.shape[0], xs.shape[1], xs.shape[2] * xs.shape[3])
xs = [xs[i, : ilens[i], :] for i in range(len(ilens))]
return xs, ilens
class Encoder(chainer.Chain):
"""Encoder network class.
Args:
etype (str): Type of encoder network.
idim (int): Number of dimensions of encoder network.
elayers (int): Number of layers of encoder network.
eunits (int): Number of lstm units of encoder network.
eprojs (int): Number of projection units of encoder network.
subsample (np.array): Subsampling number. e.g. 1_2_2_2_1
dropout (float): Dropout rate.
"""
def __init__(
self, etype, idim, elayers, eunits, eprojs, subsample, dropout, in_channel=1
):
super(Encoder, self).__init__()
typ = etype.lstrip("vgg").rstrip("p")
if typ not in ["lstm", "gru", "blstm", "bgru"]:
logging.error("Error: need to specify an appropriate encoder architecture")
with self.init_scope():
if etype.startswith("vgg"):
if etype[-1] == "p":
self.enc = chainer.Sequential(
VGG2L(in_channel),
RNNP(
get_vgg2l_odim(idim, in_channel=in_channel),
elayers,
eunits,
eprojs,
subsample,
dropout,
typ=typ,
),
)
logging.info("Use CNN-VGG + " + typ.upper() + "P for encoder")
else:
self.enc = chainer.Sequential(
VGG2L(in_channel),
RNN(
get_vgg2l_odim(idim, in_channel=in_channel),
elayers,
eunits,
eprojs,
dropout,
typ=typ,
),
)
logging.info("Use CNN-VGG + " + typ.upper() + " for encoder")
self.conv_subsampling_factor = 4
else:
if etype[-1] == "p":
self.enc = chainer.Sequential(
RNNP(idim, elayers, eunits, eprojs, subsample, dropout, typ=typ)
)
logging.info(
typ.upper() + " with every-layer projection for encoder"
)
else:
self.enc = chainer.Sequential(
RNN(idim, elayers, eunits, eprojs, dropout, typ=typ)
)
logging.info(typ.upper() + " without projection for encoder")
self.conv_subsampling_factor = 1
def __call__(self, xs, ilens):
"""Encoder forward.
Args:
xs (chainer.Variable): Batch of padded charactor ids. (B, Tmax)
ilens (chainer.variable): Batch of length of each features. (B,)
Returns:
chainer.Variable: Output of the encoder.
chainer.Variable: (Subsampled) vector of ilens.
"""
xs, ilens = self.enc(xs, ilens)
return xs, ilens
def encoder_for(args, idim, subsample):
"""Return the Encoder module.
Args:
idim (int): Dimension of input array.
subsample (numpy.array): Subsample number. egs).1_2_2_2_1
Return
chainer.nn.Module: Encoder module.
"""
return Encoder(
args.etype,
idim,
args.elayers,
args.eunits,
args.eprojs,
subsample,
args.dropout_rate,
)
|