This repository has been archived by the owner on Jan 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 538
/
test_sequence_sampler.py
222 lines (198 loc) · 8.22 KB
/
test_sequence_sampler.py
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
import collections
import functools
import mxnet as mx
import numpy as np
import scipy
import pytest
from mxnet.gluon import nn, HybridBlock
from numpy.testing import assert_allclose
from gluonnlp.sequence_sampler import BeamSearchScorer, BeamSearchSampler
mx.npx.set_np()
@pytest.mark.parametrize('length', [False, True])
@pytest.mark.parametrize('alpha', [0.0, 1.0])
@pytest.mark.parametrize('K', [1.0, 5.0])
@pytest.mark.parametrize('batch_size', [1, 2])
@pytest.mark.parametrize('vocab_size', [2, 5])
@pytest.mark.parametrize('from_logits', [False, True])
@pytest.mark.parametrize('hybridize', [False, True])
def test_beam_search_score(length, alpha, K, batch_size, vocab_size, from_logits, hybridize):
scorer = BeamSearchScorer(alpha=alpha, K=K, from_logits=from_logits)
if hybridize:
scorer.hybridize()
sum_log_probs = mx.np.zeros((batch_size,))
scores = mx.np.zeros((batch_size,))
for step in range(1, length + 1):
if not from_logits:
log_probs = np.random.normal(0, 1, (batch_size, vocab_size))
log_probs = np.log((scipy.special.softmax(log_probs, axis=-1)))
else:
log_probs = np.random.uniform(-10, 0, (batch_size, vocab_size))
log_probs = mx.np.array(log_probs, dtype=np.float32)
sum_log_probs += log_probs[:, 0]
scores = scorer(log_probs, scores, mx.np.array(step))[:, 0]
lp = (K + length) ** alpha / (K + 1) ** alpha
assert_allclose(scores.asnumpy(), sum_log_probs.asnumpy() / lp, 1E-5, 1E-5)
# TODO(sxjscience) Test for the state_batch_axis
@pytest.mark.parametrize('early_return', [False, True])
@pytest.mark.parametrize('eos_id', [0, None])
def test_beam_search(early_return, eos_id):
class SimpleStepDecoder(HybridBlock):
def __init__(self, vocab_size=5, hidden_units=4):
super().__init__()
self.x2h_map = nn.Embedding(input_dim=vocab_size, output_dim=hidden_units)
self.h2h_map = nn.Dense(units=hidden_units, flatten=False)
self.vocab_map = nn.Dense(units=vocab_size, flatten=False)
@property
def state_batch_axis(self):
return 0
@property
def data_batch_axis(self):
return 0
def forward(self, data, state):
"""
Parameters
----------
F
data :
(batch_size,)
states :
(batch_size, C)
Returns
-------
out :
(batch_size, vocab_size)
new_state :
(batch_size, C)
"""
new_state = self.h2h_map(state)
out = self.vocab_map(self.x2h_map(data) + new_state)
return out, new_state
vocab_size = 3
batch_size = 2
hidden_units = 3
beam_size = 4
step_decoder = SimpleStepDecoder(vocab_size, hidden_units)
step_decoder.initialize()
sampler = BeamSearchSampler(beam_size=4, decoder=step_decoder, eos_id=eos_id, vocab_size=vocab_size,
max_length_b=100, early_return=early_return)
states = mx.np.random.normal(0, 1, (batch_size, hidden_units))
inputs = mx.np.random.randint(0, vocab_size, (batch_size,))
samples, scores, valid_length = sampler(inputs, states)
samples = samples.asnumpy()
valid_length = valid_length.asnumpy()
for i in range(batch_size):
for j in range(beam_size):
vl = valid_length[i, j]
if eos_id is not None:
assert samples[i, j, vl - 1] == eos_id
if vl < samples.shape[2]:
assert (samples[i, j, vl:] == -1).all()
assert (samples[i, :, 0] == inputs[i].asnumpy()).all()
# TODO(sxjscience) Test for the state_batch_axis
@pytest.mark.parametrize('early_return', [False, True])
@pytest.mark.parametrize('eos_id', [0, None])
def test_beam_search_stochastic(early_return, eos_id):
class SimpleStepDecoder(HybridBlock):
def __init__(self, vocab_size=5, hidden_units=4):
super().__init__()
self.x2h_map = nn.Embedding(input_dim=vocab_size, output_dim=hidden_units)
self.h2h_map = nn.Dense(units=hidden_units, flatten=False)
self.vocab_map = nn.Dense(units=vocab_size, flatten=False)
@property
def state_batch_axis(self):
return 0
@property
def data_batch_axis(self):
return 0
def forward(self, data, state):
"""
Parameters
----------
F
data :
(batch_size,)
states :
(batch_size, C)
Returns
-------
out :
(batch_size, vocab_size)
new_state :
(batch_size, C)
"""
new_state = self.h2h_map(state)
out = self.vocab_map(self.x2h_map(data) + new_state)
return out, new_state
vocab_size = 3
batch_size = 2
hidden_units = 3
beam_size = 4
step_decoder = SimpleStepDecoder(vocab_size, hidden_units)
step_decoder.initialize()
sampler = BeamSearchSampler(beam_size=4, decoder=step_decoder, eos_id=eos_id, vocab_size=vocab_size,
stochastic=True, max_length_b=100, early_return=early_return)
states = mx.np.random.normal(0, 1, (batch_size, hidden_units))
inputs = mx.np.random.randint(0, vocab_size, (batch_size,))
samples, scores, valid_length = sampler(inputs, states)
samples = samples.asnumpy()
valid_length = valid_length.asnumpy()
for i in range(batch_size):
for j in range(beam_size):
vl = valid_length[i, j]
if eos_id is not None:
assert samples[i, j, vl-1] == eos_id
if vl < samples.shape[2]:
assert (samples[i, j, vl:] == -1).all()
assert (samples[i, :, 0] == inputs[i].asnumpy()).all()
# test for repeativeness
has_different_sample = False
for _ in range(10):
new_samples, scores, valid_length = sampler(inputs, states)
if not np.array_equal(new_samples.asnumpy(), samples):
has_different_sample = True
break
assert has_different_sample
@pytest.mark.parametrize('early_return', [False, True])
@pytest.mark.parametrize('sampling_paras', [(-1.0, -1), (0.05, -1), (-1.0, 1), (-1.0, 3)])
@pytest.mark.parametrize('eos_id', [0, None])
def test_multinomial_sampling(early_return, sampling_paras, eos_id):
class SimpleStepDecoder(HybridBlock):
def __init__(self, vocab_size=5, hidden_units=4):
super().__init__()
self.x2h_map = nn.Embedding(input_dim=vocab_size, output_dim=hidden_units)
self.h2h_map = nn.Dense(units=hidden_units, flatten=False)
self.vocab_map = nn.Dense(units=vocab_size, flatten=False)
@property
def state_batch_axis(self):
return 0
@property
def data_batch_axis(self):
return 0
def forward(self, data, state):
new_state = self.h2h_map(state)
out = self.vocab_map(self.x2h_map(data) + new_state)
return out, new_state
vocab_size = 5
batch_size = 2
hidden_units = 3
beam_size = 4
step_decoder = SimpleStepDecoder(vocab_size, hidden_units)
step_decoder.initialize()
sampling_topp, sampling_topk = sampling_paras
sampler = BeamSearchSampler(beam_size=4, decoder=step_decoder, eos_id=eos_id, vocab_size=vocab_size,
stochastic=False,
sampling=True, sampling_topp=sampling_topp, sampling_topk=sampling_topk,
max_length_b=100, early_return=early_return)
states = mx.np.random.normal(0, 1, (batch_size, hidden_units))
inputs = mx.np.random.randint(0, vocab_size, (batch_size,))
samples, scores, valid_length = sampler(inputs, states)
samples = samples.asnumpy()
valid_length = valid_length.asnumpy()
for i in range(batch_size):
for j in range(beam_size):
vl = valid_length[i, j]
if eos_id is not None:
assert samples[i, j, vl - 1] == eos_id
if vl < samples.shape[2]:
assert (samples[i, j, vl:] == -1).all()
assert (samples[i, :, 0] == inputs[i].asnumpy()).all()