generate_convolution_ref.py 19.3 KB
Newer Older
1
#!/usr/bin/env python
2
# ******************************************************************************
3
# Copyright 2017-2019 Intel Corporation
4
#
5 6 7 8
# 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
#
9
#     http://www.apache.org/licenses/LICENSE-2.0
10 11 12 13 14
#
# 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
15
# limitations under the License.
16
# ******************************************************************************
17 18 19 20

import sys
import numpy as np
import math
21
import random
22 23
from operator import mul

24
# Generates an array of random floating point literals of the given length, from a fixed seed.
25 26 27


def random_array_float_literals(length, seed=8086):
28
    literals = []
29

30
    random.seed(seed)
31

32 33
    for i in range(0, length):
        # generate numbers that can be exactly represented in binary
34 35 36 37
        sig_bits = 6
        range_bits = 2
        literal_n = np.float32(random.randint(-pow(2, sig_bits-1),
                                              pow(2, sig_bits-1))) / pow(2.0, sig_bits - range_bits)
38
        literals.append(str(literal_n))
39

40
    return literals
41 42

# Elementwise addition on tuples.
43 44 45


def tuple_plus(t1, t2):
46 47 48 49
    assert(len(t1) == len(t2))

    res = ()

50
    for (x, y) in zip(list(t1), list(t2)):
51 52 53 54 55
        res = res + (x+y,)

    return res

# Elementwise multiplication on tuples.
56 57 58


def tuple_times(t1, t2):
59 60 61 62
    assert(len(t1) == len(t2))

    res = ()

63
    for (x, y) in zip(list(t1), list(t2)):
64 65 66 67 68 69 70 71
        res = res + (x*y,)

    return res

#
# Convolution reference
#
#    Arguments:
72
#    data_batch       : [N ][Ci][D1]...[Dn], n > 0
73 74
#    filter           : [Co][Ci][W1]...[Wn]
#    move_strides     = (s1,...,sn)
75
#    filter_dilation  = (l1,...,ln)
76 77
#    below_pads       = (p1,...,pn)
#    above_pads       = (q1,...,qn)
78
#    data_dilation    = (t1,...,tn)
79 80 81 82
#
#    Returns:
#    output_batch     : [N ][Co][D'1]...[D'n]
#
83
# Where the D's are computed according to TensorFlow-style "valid" convolution rules, but *after* padding.
84 85
# See https://www.tensorflow.org/api_docs/python/tf/nn/convolution.
#
86 87


88 89 90 91 92 93 94 95
def convolution_ref(data_batch, filter, move_strides, filter_dilation, below_pads, above_pads, data_dilation):
    assert(len(data_batch.shape) == len(filter.shape))
    assert(len(data_batch.shape) > 2)
    assert(len(data_batch.shape) <= 6)
    assert(data_batch.shape[1] == filter.shape[1])
    assert(len(move_strides) == len(data_batch.shape) - 2)
    assert(len(filter_dilation) == len(data_batch.shape) - 2)
    assert(len(data_dilation) == len(data_batch.shape) - 2)
96 97

    # dilate the input batch
98
    new_item_shape = (np.array(data_batch.shape[2:]) - 1) * data_dilation + 1
99 100
    new_data_batch_shape = list(
        np.array(data_batch.shape[:2])) + list(new_item_shape)
101 102
    new_data_batch = np.zeros(new_data_batch_shape)

103 104
    for n in range(0, new_data_batch_shape[0]):
        for c in range(0, new_data_batch_shape[1]):
105 106 107
            if new_data_batch.ndim == 3:
                new_data_batch[n, c, 0::data_dilation[0]] = data_batch[n][c]
            elif new_data_batch.ndim == 4:
108 109
                new_data_batch[n, c, 0::data_dilation[0],
                               0::data_dilation[1]] = data_batch[n][c]
110
            elif new_data_batch.ndim == 5:
111 112
                new_data_batch[n, c, 0::data_dilation[0],
                               0::data_dilation[1], 0::data_dilation[2]] = data_batch[n][c]
113
            elif new_data_batch.ndim == 6:
114 115
                new_data_batch[n, c, 0::data_dilation[0], 0::data_dilation[1],
                               0::data_dilation[2], 0::data_dilation[3]] = data_batch[n][c]
116 117 118
            else:
                assert(False)

119
    data_batch = new_data_batch
120

121
    # Pad the input batch wherever the pads are positive.
122 123 124 125 126 127
    # Have to add values for the spatial and channel dims.
    below_pads_pos = (0, 0) + tuple(np.clip(below_pads, 0, None))
    # Have to add values for the spatial and channel dims.
    above_pads_pos = (0, 0) + tuple(np.clip(above_pads, 0, None))
    data_batch = np.pad(data_batch, list(
        zip(below_pads_pos, above_pads_pos)), mode='constant', constant_values=0)
128 129

    # Slice the input batch wherever the pads are negative.
130 131 132 133
    slice_bottoms = (0, 0) + tuple(-np.clip(below_pads, None, 0))
    slice_tops = (0, 0) + tuple(np.clip(above_pads, None, 0))
    slices = list(map(lambda p: slice(
        p[0], p[1] if p[1] < 0 else None), zip(slice_bottoms, slice_tops)))
134
    data_batch = data_batch[tuple(slices)]
135

136 137 138 139 140
    item_count = data_batch.shape[0]               # N
    ci_count = data_batch.shape[1]                 # Ci
    co_count = filter.shape[0]                     # Co
    input_item_shape = list(data_batch.shape[2:])  # D1, ..., Dn
    window_virtual_shape = list(filter.shape[2:])  # W1, ..., Wn
141 142 143

    # This is not used in computation but we will calculate it for a check to make sure the window fits.
    window_physical_shape = []
144
    for (d_in, d_virt, dil) in zip(input_item_shape, window_virtual_shape, filter_dilation):
145
        d_phys = (d_virt - 1) * dil + 1
146
        assert(d_phys <= d_in)
147 148
        window_physical_shape.append(d_phys)

149
    output_item_shape = []  # D'1,...,D'n
150 151 152 153
    for (d_in, d_win, dil, mov) in zip(input_item_shape, window_virtual_shape, filter_dilation, move_strides):
        # Formula is taken from TF's definition for VALID convolution.
        d_out = int(
            math.ceil((float(d_in) - (float(d_win) - 1.0) * float(dil))/float(mov)))
154
        assert(d_out > 0)
155
        output_item_shape.append(d_out)
156

157
    output_shape = [item_count, co_count]+output_item_shape  # N,Co,D'1,...,D'n
158 159 160 161 162
    output_batch = np.zeros(output_shape)

    # Walk over the output batch space.
    output_it = np.nditer(output_batch, flags=['multi_index'])
    while not output_it.finished:
163
        # Break up the output coordinate to figure out where we are in terms of batch index, output channel, and spatial position.
164
        output_index = output_it.multi_index
165
        item, co, output_pos = output_index[0], output_index[1], output_index[2:]
166 167 168 169 170 171 172 173 174

        # Walk over the filter for the current output channel.
        filter_it = np.nditer(filter[co], flags=['multi_index'])
        while not filter_it.finished:
            # Break up the filter coordinate to figure out where we are in terms of input channel and filter shape position.
            filter_index = filter_it.multi_index
            ci, filter_pos = filter_index[0], filter_index[1:]

            # Build up the coordinate within the space N,Ci,D1,...,Dn that we need to read from in the input batch.
175 176
            input_index = (item, ci) + (tuple_plus(tuple_times(output_pos,
                                                               move_strides), tuple_times(filter_pos, filter_dilation)))
177 178

            # Add to the sum-of-products.
179 180
            output_batch[output_index] = output_batch[output_index] + \
                filter[(co,) + filter_index] * data_batch[input_index]
181 182 183 184 185 186 187

            filter_it.iternext()

        output_it.iternext()

    return output_batch

188

189 190 191 192 193 194 195 196 197 198 199
def shape_str(shape):
    result = ''
    first = True
    for d in shape:
        if first:
            result = ('%d' % d)
            first = False
        else:
            result = result + (',%d' % d)
    return result

200

201 202 203 204 205 206
def scalar_str(x):
    result = ('%.1000g' % x)
    # This next part is a bit stupid.
    if "." not in result and "e" not in result:
        result = result + ".0f"
    else:
207
        result = "%.8ff" % float(result)
208 209
    return result

210

211 212 213 214 215
def data_str(data):
    result = ''
    first = True
    for x in np.nditer(data):
        if first:
216
            result = scalar_str(x)
217 218
            first = False
        else:
219
            result = result + ',' + scalar_str(x)
220 221
    return result

222

223 224 225 226 227
def shape_size(shape):
    result = 1
    for l in shape:
        result = result * l
    return result
228

229 230 231 232 233 234 235 236 237

def emit_test(t, f):
    test_name, input_batch_shape, filters_shape, move_strides, filter_dilation, below_pads, above_pads, data_dilation, bprop = t

    input_batch_literals = random_array_float_literals(
        shape_size(input_batch_shape))
    filters_literals = random_array_float_literals(shape_size(filters_shape))
    input_batch_array = np.array(
        list(map(lambda s: np.float32(s), input_batch_literals)))
238
    input_batch_array.shape = input_batch_shape
239 240
    filters_array = np.array(
        list(map(lambda s: np.float32(s), filters_literals)))
241
    filters_array.shape = filters_shape
242

243
    print("Generating convolution test '%s'..." % test_name)
244

245 246
    output_batch_data = convolution_ref(
        input_batch_array, filters_array, move_strides, filter_dilation, below_pads, above_pads, data_dilation)
247 248

    template = '''
249 250 251 252 253 254 255 256
// !!!!!!!!!!!!!! THIS FILE IS AUTOGENERATED OUTSIDE OF THE BUILD PROCESS !!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT EDIT THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// DO NOT EDIT THIS FILE. If you want to add new tests, you should edit
//  test/ref_generators/generate_convolution_ref.py and regenerate this file.
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT EDIT THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!! THIS FILE IS AUTOGENERATED OUTSIDE OF THE BUILD PROCESS !!!!!!!!!!!!!!
257
NGRAPH_TEST (${BACKEND_NAME}, %s)
258
{
259 260 261
    Shape shape_a{%s};
    Shape shape_b{%s};
    Shape shape_r{%s};
262 263 264
    auto make_graph = [shape_a, shape_b] {
        auto A = make_shared<op::Parameter>(element::f32, shape_a);
        auto B = make_shared<op::Parameter>(element::f32, shape_b);
adstraw's avatar
adstraw committed
265 266 267 268 269
        return make_shared<Function>(make_shared<op::Convolution>(A, B,
                                                                  Strides{%s},        // move_strides
                                                                  Strides{%s},        // filter_dilation
                                                                  CoordinateDiff{%s}, // below_pads
                                                                  CoordinateDiff{%s}, // above_pads
270
                                                                  Strides{%s}),       // data_dilation
271
                                     ParameterVector{A, B});
adstraw's avatar
adstraw committed
272
    };
273

274 275
    auto backend = runtime::Backend::create("${BACKEND_NAME}");
    auto function = make_graph();
276 277

    // Create some tensors for input/output
278
    auto a = backend->create_tensor(element::f32, shape_a);
279
    copy_data(a, vector<float>{%s});
280
    auto b = backend->create_tensor(element::f32, shape_b);
281
    copy_data(b, vector<float>{%s});
282
    auto result = backend->create_tensor(element::f32, shape_r);
283

284
    vector<float> expected_result{%s};
285

286
    auto handle = backend->compile(function);
287
    handle->call_with_validate({result}, {a, b});
288
    EXPECT_TRUE(test::all_close_f(vector<float>{expected_result}, read_vector<float>(result), tolerance));
adstraw's avatar
adstraw committed
289
    // only test backprop for certain cases as it takes significant compute resources
290
    %sEXPECT_TRUE(autodiff_numeric_compare<float>(backend.get(), make_graph, {a, b}, .01f, .01f));
291 292
}
'''
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    f.write(template % (test_name,
                        shape_str(input_batch_shape),
                        shape_str(filters_shape),
                        shape_str(output_batch_data.shape),
                        shape_str(move_strides),
                        shape_str(filter_dilation),
                        shape_str(below_pads),
                        shape_str(above_pads),
                        shape_str(data_dilation),
                        ",".join(map(lambda s: "%.8ff" %
                                     float(s), input_batch_literals)),
                        ",".join(map(lambda s: "%.8ff" %
                                     float(s), filters_literals)),
                        data_str(output_batch_data),
                        bprop))

309

310
#                                                                              filter                                      data
311
#         test name                                skip list   i             batch shape   filts shape   stride    dilation  below-pads  above-pads  dilation   bprop?
312
tests = [
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    ("convolution_2d_1item",                  (1, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (1, 1),     ""),
    ("convolution_2d_1item_padded_1_1x1_1",   (1, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (1, 1),    (1, 1),      (1, 1),      (1, 1),     ""),
    ("convolution_2d_1item_padded_2_3x4_5",   (1, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (1, 1),    (2, 3),      (4, 5),      (1, 1),     ""),
    ("convolution_2d_2items",                 (2, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (1, 1),     ""),
    ("convolution_2d_2items_strided",         (2, 1, 3, 5),    (2, 1, 2, 2),
     (2, 2),    (1, 1),    (0, 0),      (0, 0),      (1, 1),     ""),
    ("convolution_2d_2items_strided_padded",  (2, 1, 3, 5),    (2, 1, 2, 2),
     (2, 2),    (1, 1),    (4, 2),      (5, 7),      (1, 1),     ""),
    ("convolution_2d_2items_strided_padded_same", (2, 1, 3, 5), (2, 1, 2, 2),
     (2, 2),    (1, 1),    (2, 2),      (2, 2),      (1, 1),     ""),
    ("convolution_2d_2items_dilated",         (2, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (2, 2),    (0, 0),      (0, 0),      (1, 1),     ""),
    ("convolution_2d_2items_dilated_padded",  (2, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (2, 2),    (4, 2),      (5, 7),      (1, 1),     ""),
    ("convolution_3d_2items",                 (2, 1, 3, 5, 8),  (2, 1, 2, 2, 3),
     (1, 1, 1),  (1, 1, 1),  (0, 0, 0),    (0, 0, 0),    (1, 1, 1),   ""),
    ("convolution_4d_2items",                 (2, 1, 3, 5, 8, 7), (2, 1, 2, 2, 3, 1),
     (1, 1, 1, 1), (1, 1, 1, 1), (0, 0, 0, 0),  (0, 0, 0, 0),  (1, 1, 1, 1), "// "),
    ("convolution_4d_4items",                 (4, 3, 3, 5, 8, 7), (4, 3, 2, 2, 3, 1),
     (1, 1, 1, 1), (1, 1, 1, 1), (0, 0, 0, 0),  (0, 0, 0, 0),  (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_padded_neg",      (4, 3, 3, 5, 8, 7), (4, 3, 2, 2, 3, 1),
     (1, 1, 1, 1), (1, 1, 1, 1), (-1, 2, -3, 2), (1, 0, 0, -3), (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_strided",         (4, 3, 3, 5, 8, 7), (4, 3, 2, 2, 3, 1),
     (2, 1, 3, 2), (1, 1, 1, 1), (0, 0, 0, 0),  (0, 0, 0, 0),  (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_dilated",         (4, 3, 3, 5, 8, 7), (4, 3, 2, 2, 3, 1),
     (1, 1, 1, 1), (2, 1, 3, 2), (0, 0, 0, 0),  (0, 0, 0, 0),  (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_strided_dilated", (4, 3, 8, 8, 8, 8), (4, 3, 2, 2, 3, 1),
     (3, 2, 2, 3), (2, 1, 3, 2), (0, 0, 0, 0),  (0, 0, 0, 0),  (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_strided_dilated_padded",
     (4, 3, 8, 8, 8, 8), (4, 3, 2, 2, 3, 1), (3, 2, 2, 3), (2, 1, 3, 2), (2, 4, 6, 8),  (1, 3, 5, 7),  (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_strided_dilated_padded_neg",
     (4, 3, 8, 8, 8, 8), (4, 3, 2, 2, 3, 1), (3, 2, 2, 3), (2, 1, 3, 2), (-2, 4, 0, 5), (1, 3, -1, -4), (1, 1, 1, 1), "// "),
    ("convolution_4d_4items_strided_dilated_padded_same",
     (4, 3, 8, 8, 8, 8), (4, 3, 2, 2, 3, 1), (3, 2, 2, 3), (2, 1, 3, 2), (3, 3, 3, 3),  (3, 3, 3, 3),  (1, 1, 1, 1), "// "),
    ("convolution_2d_1item_1o1i_data_dilated", (1, 1, 3, 5),    (1, 1, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     ""),
    ("convolution_2d_1item_2o1i_data_dilated", (1, 1, 3, 5),    (2, 1, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     ""),
    ("convolution_2d_1item_2o2i_data_dilated", (1, 2, 3, 5),    (2, 2, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     ""),
    ("convolution_2d_1item_5o3i_data_dilated", (1, 3, 3, 5),    (5, 3, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     ""),
    ("convolution_2d_2item_5o3i_data_dilated", (2, 3, 3, 5),    (5, 3, 2, 2),
     (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     ""),
    ("convolution_2d_8item_large_5o3i_data_dilated",
     (8, 3, 16, 16),  (5, 3, 2, 2),    (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     "// "),
    ("convolution_2d_8item_large_5o3i_uneven_filter_data_dilated",
     (8, 3, 16, 16),  (5, 3, 2, 3),    (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 2),     "// "),
    ("convolution_2d_8item_large_5o3i_uneven_filter_uneven_data_dilation_data_dilated",
     (8, 3, 16, 16),  (5, 3, 2, 3),    (1, 1),    (1, 1),    (0, 0),      (0, 0),      (2, 3),     "// "),
    ("convolution_3d_2item_large_5o3i_uneven_filter_uneven_data_dilation_data_dilated",
     (2, 3, 8, 8, 8),  (5, 3, 2, 3, 4),  (1, 1, 1),  (1, 1, 1),  (0, 0, 0),    (0, 0, 0),    (2, 3, 2),   "// "),
    ("convolution_3d_1item_large_5o3i_padded_uneven_filter_uneven_data_dilation_data_dilated",
     (1, 3, 8, 8, 8),  (5, 3, 2, 3, 4),  (1, 1, 1),  (1, 1, 1),  (2, 1, 2),    (1, 2, 3),    (2, 3, 2),   "// "),
    ("convolution_3d_2item_large_5o3i_padded_strided_uneven_filter_uneven_data_dilation_data_dilated",
     (2, 3, 8, 8, 8),  (5, 3, 2, 3, 4),  (2, 3, 2),  (1, 1, 1),  (2, 1, 2),    (1, 2, 3),    (2, 3, 2),   "// "),
    ("convolution_3d_2item_large_5o3i_padded_strided_uneven_filter_uneven_data_dilation_filter_dilated_data_dilated",
     (2, 3, 8, 8, 8),  (5, 3, 2, 3, 4),  (2, 3, 2),  (3, 2, 2),  (2, 1, 2),    (1, 2, 3),    (2, 3, 2),   "// "),
]

377
def main():
378
    assert(len(sys.argv) > 1)
379

380
    f = open(sys.argv[1], 'w')
381
    f.write('''//*****************************************************************************
382
// Copyright 2017-2019 Intel Corporation
383 384 385 386
//
// 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
387
//
388 389 390 391 392 393 394 395 396
//     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.
//*****************************************************************************

397 398
// !!!!!!!!!!!!!! THIS FILE IS AUTOGENERATED OUTSIDE OF THE BUILD PROCESS !!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT EDIT THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
399
//
400
// It takes quite a while to compute the results.
401
//
402 403
// DO NOT EDIT THIS FILE. If you want to add new tests, you should edit
//  test/ref_generators/generate_convolution_ref.py and regenerate this file.
404
//
405
// To regenerate:
406 407
//
//   $ cd <ngraph source dir>/test
408
//   $ ./update_convolution_reference.sh
409
//
410 411
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT EDIT THIS FILE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!! THIS FILE IS AUTOGENERATED OUTSIDE OF THE BUILD PROCESS !!!!!!!!!!!!!!
412
//
413
// clang-format off
414 415 416 417 418 419

#include <cmath>

#include "gtest/gtest.h"

#include "ngraph/ngraph.hpp"
adstraw's avatar
adstraw committed
420 421
#include "util/test_tools.hpp"
#include "util/autodiff/numeric_compare.hpp"
422
#include "util/all_close_f.hpp"
423
#include "util/test_control.hpp"
424 425 426 427

using namespace std;
using namespace ngraph;

428 429
static string s_manifest = "${MANIFEST}";

430 431 432 433 434
// for float this will be 18 bits matching
// for bfloat this will be 6 bits matching
constexpr int three_quarters_of_available_bits = (MAX_FLOAT_BITS * 3) / 4;
constexpr int tolerance = FLOAT_MANTISSA_BITS - three_quarters_of_available_bits;

435
''')
436

437
    for t in tests:
438
        emit_test(t, f)
439 440 441 442 443

    f.write('''
// clang-format on
''')

444 445
    f.close()

446

447 448
if __name__ == "__main__":
    main()