forked from google/lyra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
project_and_sample_test.cc
256 lines (223 loc) · 9.96 KB
/
project_and_sample_test.cc
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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "project_and_sample.h"
#include <cmath>
#include <random>
#include <string>
#include <tuple>
#include <vector>
// placeholder for get runfiles header.
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/strings/str_format.h"
#include "include/ghc/filesystem.hpp"
#include "exported_layers_test.h"
#include "lyra_types.h"
#include "sparse_inference_matrixvector.h"
namespace chromemedia {
namespace codec {
namespace {
static constexpr int kNumSplitBands = 4;
static constexpr int kTestNumGruHiddens = 4;
static constexpr int kExpandedMixesSize = 8;
static constexpr char kPrefix[] = "lyra_";
// For creating typed-tests. We want to test the template class,
// ProjectAndSampleTest, instantiated with different types:
// 1. float: C++'s generic floating point.
// 2. csrblocksparse::fixed16_type: a type that will be used in our Lyra
// implementation. See the build rule for
// audio/chromemedia/lyra/codec:wavegru_model_impl.
// Different types would require different tolerance, hence the template class
// Tolerance below.
template <typename WeightTypeKind>
struct Tolerance {
// Unspecialized Tolerance class does not define |kTolerance|, so an attempt
// to test a ComputeType that is not one of
// {float, csrblocksparse::fixed16_type} will result in a compile error.
};
template <>
struct Tolerance<float> {
static constexpr float kTolerance = 1e-7f;
};
template <>
struct Tolerance<csrblocksparse::fixed16_type> {
// Fixed-point arithmetic is less accurate than floating-point; hence a higher
// tolerance.
static constexpr float kTolerance = 1.5e-2f;
};
// A matcher to compare a tuple (used in testing::Pointwise) and verify that
// the relative error between the two elements is within a tolerance.
MATCHER_P(IsRelativelyClose, relative_tolerance,
absl::StrFormat("%s approximately equal (relative error <= %g)",
negation ? "are not" : "are", relative_tolerance)) {
const float actual = static_cast<float>(::testing::get<0>(arg));
const float expected = static_cast<float>(::testing::get<1>(arg));
return (std::abs(actual - expected) / std::abs(expected)) <=
relative_tolerance;
}
template <typename WeightTypeKind>
class ProjectAndSampleTest : public ::testing::Test {
public:
ProjectAndSampleTest()
: project_and_sample_layer_(),
gru_hiddens_(kTestNumGruHiddens, static_cast<ProjRhsType>(0.5f)),
gru_hiddens_view_(gru_hiddens_.data(), kTestNumGruHiddens, 1),
testdata_dir_(ghc::filesystem::current_path() /
"testdata"),
scratch_space_(kExpandedMixesSize) {}
protected:
using ProjectAndSampleType =
ProjectAndSample<ProjectAndSampleTypes<WeightTypeKind, 8, 8, 8, 8, 8>>;
using ScratchType = typename ProjectAndSampleType::ScratchType;
using ProjRhsType = typename ProjectAndSampleType::ProjRhsType;
static constexpr float kTolerance = Tolerance<WeightTypeKind>::kTolerance;
ProjectAndSampleType project_and_sample_layer_;
// Input to the project-and-sample layer. In Wavegru it is the hidden states
// of the GRU layer.
std::vector<ProjRhsType> gru_hiddens_;
const csrblocksparse::MutableVectorView<ProjRhsType> gru_hiddens_view_;
const ghc::filesystem::path testdata_dir_;
// Scratch space for GetSample().
csrblocksparse::CacheAlignedVector<ScratchType> scratch_space_;
};
using WeightTypeKinds = ::testing::Types<float, csrblocksparse::fixed16_type>;
TYPED_TEST_SUITE(ProjectAndSampleTest, WeightTypeKinds);
TYPED_TEST(ProjectAndSampleTest, LoadAndPrepareSucceed) {
this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix,
/*zipped=*/true);
EXPECT_EQ(this->project_and_sample_layer_.expanded_mixes_size(),
kExpandedMixesSize);
EXPECT_GT(this->project_and_sample_layer_.ModelSize(), 0);
for (const int num_threads : {1, 2, 4}) {
EXPECT_EQ(this->project_and_sample_layer_.PrepareForThreads(num_threads),
num_threads);
}
}
TYPED_TEST(ProjectAndSampleTest, GetSamplesReturnGoldenValues) {
this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix,
/*zipped=*/true);
// The result should match the golden values regardless of number of threads.
const std::vector<int> expected_samples = {-104, -1387, 238, -220};
for (const int num_threads : {1, 2, 4}) {
this->project_and_sample_layer_.PrepareForThreads(num_threads);
// Make sampling deterministic.
const std::minstd_rand::result_type kSeed = 42;
std::vector<std::minstd_rand> gen(num_threads, std::minstd_rand(kSeed));
std::vector<int> actual_samples(kNumSplitBands);
auto f = [&](csrblocksparse::SpinBarrier* barrier, int tid) {
this->project_and_sample_layer_.GetSamples(
this->gru_hiddens_view_, /*tid=*/tid, &gen[tid],
&this->scratch_space_, kNumSplitBands, actual_samples.data());
barrier->barrier();
};
LaunchOnThreadsWithBarrier(num_threads, f);
EXPECT_THAT(actual_samples,
testing::Pointwise(IsRelativelyClose(TestFixture::kTolerance),
expected_samples));
}
}
TYPED_TEST(ProjectAndSampleTest, ReportTiming) {
this->project_and_sample_layer_.LoadRaw(this->testdata_dir_.string(), kPrefix,
/*zipped=*/true);
this->project_and_sample_layer_.set_time_components(true);
this->project_and_sample_layer_.PrepareForThreads(1);
std::minstd_rand gen;
std::vector<int> actual_samples(kNumSplitBands);
this->project_and_sample_layer_.GetSamples(
this->gru_hiddens_view_, /*tid=*/0, &gen, &this->scratch_space_,
kNumSplitBands, actual_samples.data());
// Verify that the timing is non-empty. We do not care about the content.
const std::string timing = this->project_and_sample_layer_.ReportTiming();
EXPECT_FALSE(timing.empty());
}
// Test that exported layers with fixed-point and float weights produce
// matching results.
using csrblocksparse::fixed16_type;
using FixedProjectAndSampleType =
ProjectAndSample<ProjectAndSampleTypes<fixed16_type>>;
static constexpr int kNumGruHiddens = 1024;
static constexpr int kProjSize = 512;
LayerParams ProjectionLayerParams(int num_input_channels, int num_filters,
bool relu, const std::string& model_path,
const std::string& prefix) {
return LayerParams{
.num_input_channels = num_input_channels,
.num_filters = num_filters,
.length = 1,
.kernel_size = 1,
.dilation = 1,
.stride = 1,
.relu = relu,
.skip_connection = false,
.type = LayerType::kConv1D,
.num_threads = 1,
.per_column_barrier = false,
.from = LayerParams::FromDisk{.path = model_path, .zipped = true},
.prefix = prefix};
}
struct ProjLayerTypes {
using FloatLayerType = LayerWrapper<float, float, float, float>;
using FixedLayerType =
LayerWrapper<FixedProjectAndSampleType::ProjWeightType,
FixedProjectAndSampleType::ProjRhsType,
FixedProjectAndSampleType::ProjMatMulOutType,
FixedProjectAndSampleType::DiskWeightType>;
static LayerParams Params(const std::string& model_path) {
return ProjectionLayerParams(kNumGruHiddens, kProjSize, true, model_path,
"lyra_16khz_proj_");
}
};
struct ScaleLayerTypes {
using FloatLayerType = LayerWrapper<float, float, float, float>;
using FixedLayerType =
LayerWrapper<FixedProjectAndSampleType::ScaleWeightType,
FixedProjectAndSampleType::ProjMatMulOutType,
FixedProjectAndSampleType::ScaleMatMulOutType,
FixedProjectAndSampleType::DiskWeightType>;
static LayerParams Params(const std::string& model_path) {
return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize,
false, model_path, "lyra_16khz_scales_");
}
};
struct MeanLayerTypes {
using FloatLayerType = LayerWrapper<float, float, float, float>;
using FixedLayerType =
LayerWrapper<FixedProjectAndSampleType::MeanWeightType,
FixedProjectAndSampleType::ProjMatMulOutType,
FixedProjectAndSampleType::MeanMatMulOutType,
FixedProjectAndSampleType::DiskWeightType>;
static LayerParams Params(const std::string& model_path) {
return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize,
false, model_path, "lyra_16khz_means_");
}
};
struct MixLayerTypes {
using FloatLayerType = LayerWrapper<float, float, float, float>;
using FixedLayerType =
LayerWrapper<FixedProjectAndSampleType::MixWeightType,
FixedProjectAndSampleType::ProjMatMulOutType,
FixedProjectAndSampleType::MixMatMulOutType,
FixedProjectAndSampleType::DiskWeightType>;
static LayerParams Params(const std::string& model_path) {
return ProjectionLayerParams(kProjSize, kNumSplitBands * kExpandedMixesSize,
false, model_path, "lyra_16khz_mix_");
}
};
using LayerTypesList = testing::Types<ProjLayerTypes, ScaleLayerTypes,
MeanLayerTypes, MixLayerTypes>;
INSTANTIATE_TYPED_TEST_SUITE_P(ProjectAndSample, ExportedLayersTest,
LayerTypesList);
} // namespace
} // namespace codec
} // namespace chromemedia