uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff42f1d0e590550e3925cefb | train | function | def _test_split(in_shape, axis, num_Splits, dtype):
'''internal split tester taking as parameters in_shape, number of tensors to split into
and dtype (data type)'''
np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
with tf.Graph().as_default():
in_data = array_ops.placeholder(sh... | def _test_split(in_shape, axis, num_Splits, dtype):
| '''internal split tester taking as parameters in_shape, number of tensors to split into
and dtype (data type)'''
np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=in_shape, dtype=dtype)
out = array_ops.s... | return math_ops.maximum(-1, math_ops.minimum(input_tensor, 1))
if fn_name == "TANH":
return math_ops.tanh(input_tensor)
raise AssertionError("Unknown fused_activation_function {}".format(fn_name))
def _test_split(in_shape, axis, num_Splits, dtype):
| 64 | 64 | 155 | 15 | 49 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_split | _test_split | 168 | 177 | 168 | 168 | 7e66ca654c624ad8a144a4b2a8f9e5d347353a0a | bigcode/the-stack | train |
4b1203bd1c202052190baaff | train | function | def _test_pad(data):
""" One iteration of PAD """
assert len(data) == 2
# Test with tensor and constant
with tf.Graph().as_default():
in_data = [array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in')]
out = array_ops.pad(in_data[0], ops.convert_to_tensor(data[1], dt... | def _test_pad(data):
| """ One iteration of PAD """
assert len(data) == 2
# Test with tensor and constant
with tf.Graph().as_default():
in_data = [array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in')]
out = array_ops.pad(in_data[0], ops.convert_to_tensor(data[1], dtype=data[1].dtype))
... | ).reshape((1, 2, 1, 3)), [0, 2])
_test_squeeze(np.arange(6).reshape((2, 1, 3, 1)), [1, 3])
#######################################################################
# Pad
# ---
def _test_pad(data):
| 63 | 64 | 114 | 6 | 57 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_pad | _test_pad | 777 | 786 | 777 | 777 | 899789e7d988118c5e267ff7998337423ea94133 | bigcode/the-stack | train |
a88d4d99a1c7af2646613b00 | train | function | def _test_resize(tf_resize_op, data, align_corners):
""" One iteration of Resize """
assert len(data) == 2
# Test with tensor and constant
with tf.Graph().as_default():
images_tensor = array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in')
size = ops.convert_to_tens... | def _test_resize(tf_resize_op, data, align_corners):
| """ One iteration of Resize """
assert len(data) == 2
# Test with tensor and constant
with tf.Graph().as_default():
images_tensor = array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in')
size = ops.convert_to_tensor(data[1], dtype=data[1].dtype)
out_tensor =... | reshape(np.arange(6), [-1, 2])
_test_reshape(np.arange(6), [3, -1])
_test_reshape(np.arange(6), [-1])
#######################################################################
# Resize
# ------
def _test_resize(tf_resize_op, data, align_corners):
| 64 | 64 | 138 | 14 | 49 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_resize | _test_resize | 482 | 492 | 482 | 482 | 622b6ddd013bd12a8b6611d39734d9826d71f51e | bigcode/the-stack | train |
2ebba8676ea3c716a7d47256 | train | function | def _test_forward_reduce(testop):
""" Reduce """
data0 = [np.random.rand(16, 16, 16, 16).astype("float32"), None]
data1 = [np.random.rand(16, 16, 16, 16).astype("float32"), np.array([1, 2], dtype=np.int32)]
testop(data0)
testop(data0, keep_dims=False)
testop(data0, keep_dims=True)
testop(dat... | def _test_forward_reduce(testop):
| """ Reduce """
data0 = [np.random.rand(16, 16, 16, 16).astype("float32"), None]
data1 = [np.random.rand(16, 16, 16, 16).astype("float32"), np.array([1, 2], dtype=np.int32)]
testop(data0)
testop(data0, keep_dims=False)
testop(data0, keep_dims=True)
testop(data1)
testop(data1, keep_dims=Fa... | test_reduce(math_ops.reduce_prod, data, keep_dims)
#######################################################################
# Reduce_sum
# -----------
def _test_reduce_sum(data, keep_dims=None):
""" One iteration of reduce_sum """
return _test_reduce(math_ops.reduce_sum, data, keep_dims)
def _test_forward_redu... | 64 | 64 | 129 | 8 | 56 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_forward_reduce | _test_forward_reduce | 726 | 735 | 726 | 726 | bab5242fb5f7f417e3c628409a66b985e63a2739 | bigcode/the-stack | train |
16f65ae624f86ed0ba996e3d | train | function | def _test_forward_elemwise(testop):
""" Elewise"""
testop([np.arange(6.0, dtype=np.float32).reshape((2, 1, 1, 3)),
np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3))])
testop([np.arange(6.0, dtype=np.float32).reshape((2, 1, 3)),
np.arange(1.0, 7.0, dtype=np.float32).re... | def _test_forward_elemwise(testop):
| """ Elewise"""
testop([np.arange(6.0, dtype=np.float32).reshape((2, 1, 1, 3)),
np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3))])
testop([np.arange(6.0, dtype=np.float32).reshape((2, 1, 3)),
np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3))])
testop([np.ar... | """ One iteration of minimum """
return _test_elemwise(math_ops.minimum, data)
#######################################################################
# Greater
# -------
def _test_greater(data):
""" One iteration of greater """
return _test_elemwise(math_ops.greater, data)
def _test_forward_elemwise(t... | 64 | 64 | 179 | 9 | 55 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_forward_elemwise | _test_forward_elemwise | 627 | 634 | 627 | 627 | 61c482c63813ed57f19eaaae43427efef97c7d70 | bigcode/the-stack | train |
b3bc3f2914b4be16c2fc0e63 | train | function | def _test_reduce_sum(data, keep_dims=None):
""" One iteration of reduce_sum """
return _test_reduce(math_ops.reduce_sum, data, keep_dims)
| def _test_reduce_sum(data, keep_dims=None):
| """ One iteration of reduce_sum """
return _test_reduce(math_ops.reduce_sum, data, keep_dims)
| #######
# Reduce_prod
# -----------
def _test_reduce_prod(data, keep_dims=None):
""" One iteration of reduce_prod """
return _test_reduce(math_ops.reduce_prod, data, keep_dims)
#######################################################################
# Reduce_sum
# -----------
def _test_reduce_sum(data, keep_di... | 64 | 64 | 34 | 11 | 53 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reduce_sum | _test_reduce_sum | 721 | 723 | 721 | 721 | d4707d06effac16d114b16790eede35c3da64fec | bigcode/the-stack | train |
1223e71490272079f65d6e87 | train | function | def _test_pooling(input_shape, **kwargs):
_test_pooling_iteration(input_shape, **kwargs)
| def _test_pooling(input_shape, **kwargs):
| _test_pooling_iteration(input_shape, **kwargs)
| ().as_default():
in_data = array_ops.placeholder(shape=input_shape, dtype='float32')
out = nn_ops.pool(in_data, **kwargs)
compare_tflite_with_tvm(x,'Placeholder:0', [in_data], [out])
def _test_pooling(input_shape, **kwargs):
| 64 | 64 | 23 | 11 | 53 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_pooling | _test_pooling | 365 | 366 | 365 | 365 | 8e6ad958ba50c0b316b87ef547d29c47c1f41dbe | bigcode/the-stack | train |
abb2ad4d0e80d8cd99dc96eb | train | function | def _test_sub(data, fused_activation_function=None):
""" One iteration of subtract """
return _test_elemwise(math_ops.subtract, data, fused_activation_function)
| def _test_sub(data, fused_activation_function=None):
| """ One iteration of subtract """
return _test_elemwise(math_ops.subtract, data, fused_activation_function)
| #######################################################################
# Add
# ---
def _test_add(data, fused_activation_function=None):
""" One iteration of add """
return _test_elemwise(math_ops.add, data, fused_activation_function)
#######################################################################
# S... | 64 | 64 | 34 | 11 | 52 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_sub | _test_sub | 581 | 583 | 581 | 581 | 7ddc713e24c82b03d41be6e1ce9de6bbf5d42c4b | bigcode/the-stack | train |
5d559220c29402b6151d3654 | train | function | def test_forward_qnn_mobilenet_v2_net():
"""Test the Quantized TFLite Mobilenet V2 model."""
# MobilenetV2
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz",
"mobilenet_v2_1.0_2... | def test_forward_qnn_mobilenet_v2_net():
| """Test the Quantized TFLite Mobilenet V2 model."""
# MobilenetV2
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz",
"mobilenet_v2_1.0_224_quant.tflite")
with open(tflite_mo... | ite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]
tvm_output = run_tvm_graph(tflite_model_buf, data, 'input')
tvm_predictions = np.squeeze(tvm_output)
tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]
tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)
def test_forward_... | 98 | 98 | 328 | 12 | 86 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_qnn_mobilenet_v2_net | test_forward_qnn_mobilenet_v2_net | 1,049 | 1,067 | 1,049 | 1,049 | 5fbb31ee2fad12a7ed2dcb9cdac00abed3db79d4 | bigcode/the-stack | train |
dcd19e1fe881ffba926a602b | train | function | def test_forward_softmax():
""" Softmax """
_test_softmax(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
| def test_forward_softmax():
| """ Softmax """
_test_softmax(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
| of softmax """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = nn_ops.softmax(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
def test_forward_softmax():
| 64 | 64 | 35 | 6 | 58 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_softmax | test_forward_softmax | 863 | 865 | 863 | 863 | 4fdcf178b562f9b69b5ec18979952c1f9a5dc2c5 | bigcode/the-stack | train |
3fc1949ad6ff8a46f88837f4 | train | function | def _test_mul(data, fused_activation_function=None):
""" One iteration of mul """
return _test_elemwise(math_ops.multiply, data, fused_activation_function)
| def _test_mul(data, fused_activation_function=None):
| """ One iteration of mul """
return _test_elemwise(math_ops.multiply, data, fused_activation_function)
| )
#######################################################################
# Subtract
# --------
def _test_sub(data, fused_activation_function=None):
""" One iteration of subtract """
return _test_elemwise(math_ops.subtract, data, fused_activation_function)
#####################################################... | 64 | 64 | 34 | 11 | 53 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_mul | _test_mul | 587 | 589 | 587 | 587 | 03c2324521644bf66c40673423df295370ff289c | bigcode/the-stack | train |
0d3f3d3d9c6276bbbd69e549 | train | function | def test_all_resize():
""" Resize """
data = [np.random.rand(1, 16, 16, 3).astype("float32"), np.array([8, 8], dtype=np.int32)]
### RESIZE_BILINEAR
_test_resize(tf.image.resize_bilinear, data, align_corners=False)
_test_resize(tf.image.resize_bilinear, data, align_corners=True)
### RESIZE_NEARES... | def test_all_resize():
| """ Resize """
data = [np.random.rand(1, 16, 16, 3).astype("float32"), np.array([8, 8], dtype=np.int32)]
### RESIZE_BILINEAR
_test_resize(tf.image.resize_bilinear, data, align_corners=False)
_test_resize(tf.image.resize_bilinear, data, align_corners=True)
### RESIZE_NEAREST_NEIGHBOR (was added i... | [1], dtype=data[1].dtype)
out_tensor = tf_resize_op(images=images_tensor, size=size, align_corners=align_corners)
compare_tflite_with_tvm([data[0]], ['in:0'], [images_tensor], [out_tensor])
def test_all_resize():
| 64 | 64 | 176 | 5 | 59 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_all_resize | test_all_resize | 495 | 506 | 495 | 495 | 9e5a0bb3a84b8acbe07eeb4cc3707578e9956c96 | bigcode/the-stack | train |
88d7c19fc8e9a599d81672d3 | train | function | def _test_div(data, fused_activation_function=None):
""" One iteration of divide """
return _test_elemwise(math_ops.divide, data, fused_activation_function)
| def _test_div(data, fused_activation_function=None):
| """ One iteration of divide """
return _test_elemwise(math_ops.divide, data, fused_activation_function)
| _function)
#######################################################################
# Mul
# ---
def _test_mul(data, fused_activation_function=None):
""" One iteration of mul """
return _test_elemwise(math_ops.multiply, data, fused_activation_function)
############################################################... | 64 | 64 | 34 | 11 | 52 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_div | _test_div | 595 | 597 | 595 | 595 | ca8fba1fec35e950ef937d352e2f73b0e5901a0f | bigcode/the-stack | train |
cd8f6f443541833b0fc0bcf0 | train | function | def test_forward_concatenation():
_test_concatenation(
[np.arange(6).reshape((1, 2, 1, 3)),
np.arange(6).reshape((1, 2, 1, 3))], 1)
_test_concatenation(
[np.arange(6).reshape((3, 2)),
np.arange(6).reshape((3, 2))], 1)
_test_concatenation(
[np.arange(6).reshape((2,... | def test_forward_concatenation():
| _test_concatenation(
[np.arange(6).reshape((1, 2, 1, 3)),
np.arange(6).reshape((1, 2, 1, 3))], 1)
_test_concatenation(
[np.arange(6).reshape((3, 2)),
np.arange(6).reshape((3, 2))], 1)
_test_concatenation(
[np.arange(6).reshape((2, 1, 1, 3)),
np.arange(6).r... | in enumerate(data)]
out = array_ops.concat(in_data, axis=axis)
name = ["in_{}:0".format(idx) for idx in range(len(data))]
compare_tflite_with_tvm(data, name, in_data, [out])
def test_forward_concatenation():
| 64 | 64 | 168 | 8 | 56 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_concatenation | test_forward_concatenation | 528 | 541 | 528 | 529 | 54f57c8f0d39cb7e5d284fa50bf0506ca0108b78 | bigcode/the-stack | train |
50a38edfe05cbbd393ceb2a1 | train | function | def _test_reduce_prod(data, keep_dims=None):
""" One iteration of reduce_prod """
return _test_reduce(math_ops.reduce_prod, data, keep_dims)
| def _test_reduce_prod(data, keep_dims=None):
| """ One iteration of reduce_prod """
return _test_reduce(math_ops.reduce_prod, data, keep_dims)
| #######
# Reduce_mean
# -----------
def _test_reduce_mean(data, keep_dims=None):
""" One iteration of reduce_mean """
return _test_reduce(math_ops.reduce_mean, data, keep_dims)
#######################################################################
# Reduce_prod
# -----------
def _test_reduce_prod(data, keep_... | 64 | 64 | 34 | 11 | 53 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reduce_prod | _test_reduce_prod | 713 | 715 | 713 | 713 | 18ede4f3fd7385fa599376c66e017e9c04fc36a9 | bigcode/the-stack | train |
bc96bcdc13cceeb2cc22efc5 | train | function | def test_forward_logistic():
""" LOGISTIC """
_test_logistic(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
| def test_forward_logistic():
| """ LOGISTIC """
_test_logistic(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
| LOGISTIC """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = math_ops.sigmoid(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
def test_forward_logistic():
| 64 | 64 | 35 | 6 | 58 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_logistic | test_forward_logistic | 847 | 849 | 847 | 847 | 5ff3fbe384dff46d22ee96d528332fee4b437f7a | bigcode/the-stack | train |
57c2a5f6005ef9a52149c6ff | train | function | def _test_reshape(data, out_shape):
""" One iteration of reshape operation with given data and out shape """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = array_ops.reshape(in_data, out_shape)
compare_tflite_with_tvm(data, 'Place... | def _test_reshape(data, out_shape):
| """ One iteration of reshape operation with given data and out shape """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = array_ops.reshape(in_data, out_shape)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| 4, 17, 17, 12], [3, 3, 12, 2], [1, 1], [2, 2], 'VALID', 'NHWC', True)
#######################################################################
# Reshape
# -------
def _test_reshape(data, out_shape):
| 63 | 64 | 81 | 10 | 53 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reshape | _test_reshape | 462 | 468 | 462 | 462 | b86542ae884173dac4925edf49371ae39d07fbb1 | bigcode/the-stack | train |
7ef916285f9ea1b5108ff7b5 | train | function | def test_forward_pooling():
""" Pooling """
for pool_type in ['AVG', 'MAX']:
_test_pooling(input_shape=[2, 9, 10, 2],
window_shape=[1, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
... | def test_forward_pooling():
| """ Pooling """
for pool_type in ['AVG', 'MAX']:
_test_pooling(input_shape=[2, 9, 10, 2],
window_shape=[1, 1],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
strides=[1, 1])
... | _data = array_ops.placeholder(shape=input_shape, dtype='float32')
out = nn_ops.pool(in_data, **kwargs)
compare_tflite_with_tvm(x,'Placeholder:0', [in_data], [out])
def _test_pooling(input_shape, **kwargs):
_test_pooling_iteration(input_shape, **kwargs)
def test_forward_pooling():
| 76 | 76 | 254 | 6 | 70 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_pooling | test_forward_pooling | 369 | 399 | 369 | 369 | 528423826dfaef3e9a04b91baa35766bd368686b | bigcode/the-stack | train |
eed681d9092c2e578113a258 | train | function | def _test_reduce(math_op, data, keep_dims=None):
""" One iteration of reduce """
assert len(data) == 2
# Test with tensor and constant
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in')
out = math_op(in_data, data[1], keep... | def _test_reduce(math_op, data, keep_dims=None):
| """ One iteration of reduce """
assert len(data) == 2
# Test with tensor and constant
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in')
out = math_op(in_data, data[1], keep_dims)
compare_tflite_with_tvm([data[0]],... | [out])
def test_forward_zeros_like():
""" ZEROS LIKE """
_test_zeros_like(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
#######################################################################
# Reduce
# ------
def _test_reduce(math_op, data, keep_dims=None):
| 64 | 64 | 110 | 13 | 50 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reduce | _test_reduce | 673 | 682 | 673 | 673 | fb2ddd0392acca10fde33186eb884d958963ac6a | bigcode/the-stack | train |
c24c2b65dd36b7608be3c280 | train | function | def test_forward_qnn_inception_v1_net():
"""Test the Quantized TFLite Inception model."""
# InceptionV1
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/inception_v1_224_quant_20181026.tgz",
"inception_v1_224_quant.tflite")
... | def test_forward_qnn_inception_v1_net():
| """Test the Quantized TFLite Inception model."""
# InceptionV1
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/inception_v1_224_quant_20181026.tgz",
"inception_v1_224_quant.tflite")
with open(tflite_model_file, "rb") as... | float32')
tflite_output = run_tflite_graph(tflite_model_buf, data)
tvm_output = run_tvm_graph(tflite_model_buf, data, 'input')
tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]),
rtol=1e-5, atol=1e-5)
def test_forward_qnn_inception_v1_net():
| 93 | 93 | 311 | 11 | 82 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_qnn_inception_v1_net | test_forward_qnn_inception_v1_net | 1,009 | 1,027 | 1,009 | 1,009 | 86e5d83c801eaa59d2e2ab0aadf750ea05bf9d20 | bigcode/the-stack | train |
1a8de69e4c7d70ac8e7a1268 | train | function | def _test_forward_tile(in_shape, reps, dtype):
data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = array_ops.tile(in_data, reps)
compare_tflite_with_tvm(data, 'Placeholder:... | def _test_forward_tile(in_shape, reps, dtype):
| data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = array_ops.tile(in_data, reps)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| reshape((1, 6)), cast_dtype=tf.uint8)
_test_cast(np.arange(6.0, dtype=np.int32).reshape((1, 6)), cast_dtype=tf.int64)
#######################################################################
# tile
# ---------
def _test_forward_tile(in_shape, reps, dtype):
| 63 | 64 | 87 | 12 | 51 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_forward_tile | _test_forward_tile | 256 | 264 | 256 | 256 | 1a3c9c6db400cc56b2b50f1e3207f704157ecbf0 | bigcode/the-stack | train |
c065899cd53dec1c378e928c | train | function | def _test_convolution(tensor_in_sizes, filter_in_sizes,
dilations, strides, padding, data_format,
is_depthwise=False):
""" One iteration of convolution with given shapes and attributes """
total_size_1 = 1
total_size_2 = 1
for s in tensor_in_sizes:
to... | def _test_convolution(tensor_in_sizes, filter_in_sizes,
dilations, strides, padding, data_format,
is_depthwise=False):
| """ One iteration of convolution with given shapes and attributes """
total_size_1 = 1
total_size_2 = 1
for s in tensor_in_sizes:
total_size_1 *= s
for s in filter_in_sizes:
total_size_2 *= s
# Initializes the input tensor with array containing incrementing
# numbers from 1.... | =[1, 1])
_test_pooling(input_shape=[2, 10, 9, 2],
window_shape=[2, 3],
padding='SAME',
pooling_type=pool_type,
dilation_rate=[1, 1],
strides=[2, 1])
##################################################... | 105 | 105 | 352 | 31 | 74 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_convolution | _test_convolution | 406 | 441 | 406 | 408 | 62e6d4a418400d0c59ab4572e6002a2285b203ce | bigcode/the-stack | train |
378d5e448d80ba6ba5daa430 | train | function | def test_forward_mobilenet_v2():
"""Test the Mobilenet V2 TF Lite model."""
# MobilenetV2
tflite_model_file = tf_testing.get_workload_official(
"http://download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224.tgz",
"mobilenet_v2_1.0_224.tflite")
with open(tflite_model_file, "r... | def test_forward_mobilenet_v2():
| """Test the Mobilenet V2 TF Lite model."""
# MobilenetV2
tflite_model_file = tf_testing.get_workload_official(
"http://download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224.tgz",
"mobilenet_v2_1.0_224.tflite")
with open(tflite_model_file, "rb") as f:
tflite_model_bu... | = run_tvm_graph(tflite_model_buf, data, 'input')
tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]),
rtol=1e-5, atol=1e-5)
def test_forward_mobilenet_v2():
| 65 | 65 | 219 | 9 | 56 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_mobilenet_v2 | test_forward_mobilenet_v2 | 963 | 975 | 963 | 963 | 9e1f196d690aed5800e1bd373b4e470354bfe16d | bigcode/the-stack | train |
09f1e14dcdb3c08e16f01d95 | train | function | def test_forward_zeros_like():
""" ZEROS LIKE """
_test_zeros_like(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
| def test_forward_zeros_like():
| """ ZEROS LIKE """
_test_zeros_like(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
| """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = gen_array_ops.zeros_like(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
def test_forward_zeros_like():
| 64 | 64 | 39 | 7 | 57 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_zeros_like | test_forward_zeros_like | 665 | 667 | 665 | 665 | 66911d19c6bbe4b3fb26e0c4744ea40bfaea87b2 | bigcode/the-stack | train |
df7772000a0bb1edc1311453 | train | function | def compare_tflite_with_tvm(in_data, in_name, input_tensors,
output_tensors, init_global_variables=False, out_names=None):
"""Generic function to generate and compare TFLite and TVM output"""
in_data = convert_to_list(in_data)
in_name = convert_to_list(in_name)
out_names = co... | def compare_tflite_with_tvm(in_data, in_name, input_tensors,
output_tensors, init_global_variables=False, out_names=None):
| """Generic function to generate and compare TFLite and TVM output"""
in_data = convert_to_list(in_data)
in_name = convert_to_list(in_name)
out_names = convert_to_list(out_names)
in_node = [0] * len(in_name)
for i in range(len(in_name)):
in_node[i] = in_name[i].split(':')[0] if ":" in in_... | interpreter.set_tensor(input_details[i]['index'], input_data[i])
# Run
interpreter.invoke()
# get output
tflite_output = list()
for i in range(len(output_details)):
tflite_output.append(interpreter.get_tensor(output_details[i]['index']))
return tflite_output
def compare_tflite_with_t... | 99 | 99 | 333 | 32 | 66 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | compare_tflite_with_tvm | compare_tflite_with_tvm | 124 | 152 | 124 | 125 | 06faf1dba88a40ae07bffd9aac35d1da3054f212 | bigcode/the-stack | train |
a86d012b0c0caa6b1e896c9b | train | function | def test_forward_inception_v4_net():
"""Test the Inception V4 TF Lite model."""
# InceptionV4
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/tflite/model_zoo/upload_20180427/inception_v4_2018_04_27.tgz",
"inception_v4.tfli... | def test_forward_inception_v4_net():
| """Test the Inception V4 TF Lite model."""
# InceptionV4
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/tflite/model_zoo/upload_20180427/inception_v4_2018_04_27.tgz",
"inception_v4.tflite")
with open(tflite_model_file,... | = run_tvm_graph(tflite_model_buf, data, 'input')
tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]),
rtol=1e-5, atol=1e-5)
def test_forward_inception_v4_net():
| 65 | 65 | 218 | 9 | 56 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_inception_v4_net | test_forward_inception_v4_net | 995 | 1,007 | 995 | 995 | 6874dd0a92841cdf70f71529d6c172c3ddb2713e | bigcode/the-stack | train |
cc253aaf47634d522e95a651 | train | function | def test_forward_pack():
""" Pack """
_test_pack(
[np.arange(6).reshape((1, 2, 1, 3)),
np.arange(6).reshape((1, 2, 1, 3))], 1)
_test_pack(
[np.arange(6).reshape((3, 2)),
np.arange(6).reshape((3, 2))], 1)
_test_pack(
[np.arange(6).reshape((2, 1, 1, 3)),
... | def test_forward_pack():
| """ Pack """
_test_pack(
[np.arange(6).reshape((1, 2, 1, 3)),
np.arange(6).reshape((1, 2, 1, 3))], 1)
_test_pack(
[np.arange(6).reshape((3, 2)),
np.arange(6).reshape((3, 2))], 1)
_test_pack(
[np.arange(6).reshape((2, 1, 1, 3)),
np.arange(6).reshape((2,... | idx, tensor in enumerate(data)]
out = array_ops.pack(in_data, axis=axis)
name = ["in_{}:0".format(idx) for idx in range(len(data))]
compare_tflite_with_tvm(data, name, in_data, [out])
def test_forward_pack():
| 64 | 64 | 160 | 5 | 59 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_pack | test_forward_pack | 820 | 833 | 820 | 820 | a1e185346eae5ac2159fb66f13aba44419ce3c89 | bigcode/the-stack | train |
038b5ff9587c39078d5928f1 | train | function | def _test_minimum(data):
""" One iteration of minimum """
return _test_elemwise(math_ops.minimum, data)
| def _test_minimum(data):
| """ One iteration of minimum """
return _test_elemwise(math_ops.minimum, data)
| """
return _test_elemwise(math_ops.pow, data)
#######################################################################
# Maximum
# -------
def _test_maximum(data):
""" One iteration of maximum """
return _test_elemwise(math_ops.maximum, data)
################################################################... | 63 | 64 | 26 | 7 | 56 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_minimum | _test_minimum | 616 | 618 | 616 | 616 | f4f8f3c33f1178cfc9ea53e4b93ea64da982b811 | bigcode/the-stack | train |
ef90fe29927b9bfa60c6f540 | train | function | def run_tflite_graph(tflite_model_buf, input_data):
""" Generic function to execute TFLite """
input_data = convert_to_list(input_data)
interpreter = interpreter_wrapper.Interpreter(model_content=tflite_model_buf)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
o... | def run_tflite_graph(tflite_model_buf, input_data):
| """ Generic function to execute TFLite """
input_data = convert_to_list(input_data)
interpreter = interpreter_wrapper.Interpreter(model_content=tflite_model_buf)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
... | _output)
tvm_output_list = []
for i in range(0, num_output):
tvm_output = m.get_output(i)
tvm_output_list.append(tvm_output.asnumpy())
return tvm_output_list
def run_tflite_graph(tflite_model_buf, input_data):
| 64 | 64 | 167 | 15 | 48 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | run_tflite_graph | run_tflite_graph | 98 | 121 | 98 | 98 | cb1fa7a3924959c55feb78d41d91026a714874ac | bigcode/the-stack | train |
14d5df2abaae397afbc0253e | train | function | def _test_cast(data, cast_dtype):
""" One iteration of CAST """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = math_ops.cast(in_data, cast_dtype)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| def _test_cast(data, cast_dtype):
| """ One iteration of CAST """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = math_ops.cast(in_data, cast_dtype)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| _transpose((2, 3, 4, 5), (3, 0, 1, 2))
_test_forward_transpose((2, 3, 4, 5), ())
#######################################################################
# Cast
# --------
def _test_cast(data, cast_dtype):
| 64 | 64 | 73 | 9 | 54 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_cast | _test_cast | 237 | 242 | 237 | 237 | 514dd1d5830b16388c163fb74fce0345ac041fca | bigcode/the-stack | train |
84b349e8477b16716dd86cd9 | train | function | def _test_zeros_like(data):
""" One iteration of ZEROS LIKE """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = gen_array_ops.zeros_like(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| def _test_zeros_like(data):
| """ One iteration of ZEROS LIKE """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = gen_array_ops.zeros_like(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| 6"))
_test_forward_elemwise(_test_pow)
_test_forward_elemwise(_test_maximum)
_test_forward_elemwise(_test_minimum)
_test_forward_elemwise(_test_greater)
#######################################################################
# Zeros like
# --------
def _test_zeros_like(data):
| 64 | 64 | 74 | 8 | 55 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_zeros_like | _test_zeros_like | 658 | 663 | 658 | 658 | 2b7442c57b27c8e0389af117a74868991d4a2428 | bigcode/the-stack | train |
b46ebd32492e3feac1b321d4 | train | function | def _test_reduce_max(data, keep_dims=None):
""" One iteration of reduce_max """
return _test_reduce(math_ops.reduce_max, data, keep_dims)
| def _test_reduce_max(data, keep_dims=None):
| """ One iteration of reduce_max """
return _test_reduce(math_ops.reduce_max, data, keep_dims)
| #######
# Reduce_min
# ----------
def _test_reduce_min(data, keep_dims=None):
""" One iteration of reduce_min """
return _test_reduce(math_ops.reduce_min, data, keep_dims)
#######################################################################
# Reduce_max
# ----------
def _test_reduce_max(data, keep_dims=Non... | 63 | 64 | 34 | 11 | 52 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reduce_max | _test_reduce_max | 697 | 699 | 697 | 697 | d6cbcd7e104c4b80860a42f4d1915959480db930 | bigcode/the-stack | train |
462dd5c9bebbf959f446fc41 | train | function | def _test_reduce_min(data, keep_dims=None):
""" One iteration of reduce_min """
return _test_reduce(math_ops.reduce_min, data, keep_dims)
| def _test_reduce_min(data, keep_dims=None):
| """ One iteration of reduce_min """
return _test_reduce(math_ops.reduce_min, data, keep_dims)
| ='in')
out = math_op(in_data, data[1], keep_dims)
compare_tflite_with_tvm([data[0]], ['in:0'], [in_data], [out])
#######################################################################
# Reduce_min
# ----------
def _test_reduce_min(data, keep_dims=None):
| 63 | 64 | 34 | 11 | 52 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reduce_min | _test_reduce_min | 689 | 691 | 689 | 689 | 11c45fa978267c9394c912b0e1acfe8d631e4ce4 | bigcode/the-stack | train |
1abc44ece89ff44d778793bd | train | function | def _test_softmax(data):
""" One iteration of softmax """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = nn_ops.softmax(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| def _test_softmax(data):
| """ One iteration of softmax """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = nn_ops.softmax(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| Placeholder:0', [in_data], [out])
def test_forward_logistic():
""" LOGISTIC """
_test_logistic(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
#######################################################################
# Softmax
# -------
def _test_softmax(data):
| 63 | 64 | 69 | 7 | 56 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_softmax | _test_softmax | 856 | 861 | 856 | 856 | d8f317c72bbf7615b0c903856a93b4d86f4f9095 | bigcode/the-stack | train |
3388ef11f8c695df54a1eeb6 | train | function | def _test_reduce_mean(data, keep_dims=None):
""" One iteration of reduce_mean """
return _test_reduce(math_ops.reduce_mean, data, keep_dims)
| def _test_reduce_mean(data, keep_dims=None):
| """ One iteration of reduce_mean """
return _test_reduce(math_ops.reduce_mean, data, keep_dims)
| #######
# Reduce_max
# ----------
def _test_reduce_max(data, keep_dims=None):
""" One iteration of reduce_max """
return _test_reduce(math_ops.reduce_max, data, keep_dims)
#######################################################################
# Reduce_mean
# -----------
def _test_reduce_mean(data, keep_dims=... | 64 | 64 | 34 | 11 | 53 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_reduce_mean | _test_reduce_mean | 705 | 707 | 705 | 705 | ff5edad99e4115fa34e1eb5df63d9c2dace9bf0d | bigcode/the-stack | train |
87f29ee6cf37acd431b5be50 | train | function | def test_forward_split():
'''test split layer'''
# rank 1
_test_split((3,), 0, 1, 'float32')
_test_split((3,), 0, 3, 'float32')
_test_split((6,), 0, 3, 'float32')
# rank 2
_test_split((6, 2), 0, 3, 'float32')
_test_split((2, 6), 1, 6, 'float32')
# rank 3
if package_version.parse(... | def test_forward_split():
| '''test split layer'''
# rank 1
_test_split((3,), 0, 1, 'float32')
_test_split((3,), 0, 3, 'float32')
_test_split((6,), 0, 3, 'float32')
# rank 2
_test_split((6, 2), 0, 3, 'float32')
_test_split((2, 6), 1, 6, 'float32')
# rank 3
if package_version.parse(tf.VERSION) >= package_ver... |
and dtype (data type)'''
np_data = np.random.uniform(-5, 5, size=in_shape).astype(dtype)
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=in_shape, dtype=dtype)
out = array_ops.split(in_data, num_Splits, axis=axis)
out_names = ['out_' + str(n) + ':0' for n in r... | 128 | 128 | 429 | 5 | 123 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_split | test_forward_split | 179 | 203 | 179 | 179 | cd70a82d2cf01f9c4a10408bf1295d63e3546d7e | bigcode/the-stack | train |
0c38f74b7731b9e354d595b1 | train | function | def _test_pow(data):
""" One iteration of power """
return _test_elemwise(math_ops.pow, data)
| def _test_pow(data):
| """ One iteration of power """
return _test_elemwise(math_ops.pow, data)
| data, fused_activation_function)
#######################################################################
# Divide
# ------
def _test_div(data, fused_activation_function=None):
""" One iteration of divide """
return _test_elemwise(math_ops.divide, data, fused_activation_function)
#############################... | 64 | 64 | 25 | 6 | 57 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_pow | _test_pow | 602 | 604 | 602 | 602 | fb2da6251e893ac2cc815d9b2dfcefa729b0ac42 | bigcode/the-stack | train |
9f35cb35fad02ee22d0a4916 | train | function | def _test_add(data, fused_activation_function=None):
""" One iteration of add """
return _test_elemwise(math_ops.add, data, fused_activation_function)
| def _test_add(data, fused_activation_function=None):
| """ One iteration of add """
return _test_elemwise(math_ops.add, data, fused_activation_function)
| =data[1].dtype))
out = with_fused_activation_function(out, fused_activation_function)
compare_tflite_with_tvm([data[0]], ['in:0'], in_data, [out])
#######################################################################
# Add
# ---
def _test_add(data, fused_activation_function=None):
| 63 | 64 | 34 | 11 | 52 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_add | _test_add | 573 | 575 | 573 | 573 | 2297ed6717cee3f4ea2fc45d14098291f7487672 | bigcode/the-stack | train |
f119c3e306b7468717e077d7 | train | function | def test_forward_convolution():
_test_convolution([4, 8, 8, 176], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution([4, 17, 17, 19], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution([4, 17, 17, 124], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution([4... | def test_forward_convolution():
| _test_convolution([4, 8, 8, 176], [1, 1, 176, 32], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution([4, 17, 17, 19], [3, 3, 19, 19], [1, 1], [2, 2], 'VALID', 'NHWC')
_test_convolution([4, 17, 17, 124], [1, 1, 124, 19], [1, 1], [1, 1], 'SAME', 'NHWC')
_test_convolution([4, 17, 17, 12], [3, 3, 12, 32], [... | 1]
dilations = [1] + dilations + [1]
if is_depthwise:
out = nn_ops.depthwise_conv2d_native(in_data,
in_filter,
strides=strides,
padding=padding,... | 137 | 137 | 458 | 6 | 131 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_convolution | test_forward_convolution | 444 | 455 | 444 | 444 | b96a98907e82c0bbd43628d9252d6efc3d0f987e | bigcode/the-stack | train |
5ffd53d2ab96dfbde5b28bc2 | train | function | def _test_fully_connected(tensor_in_sizes, filter_in_sizes, bias_in_size=None):
""" One iteration of fully connected """
total_size_1 = 1
total_size_2 = 1
for s in tensor_in_sizes:
total_size_1 *= s
for s in filter_in_sizes:
total_size_2 *= s
# Initializes the input tensor with ... | def _test_fully_connected(tensor_in_sizes, filter_in_sizes, bias_in_size=None):
| """ One iteration of fully connected """
total_size_1 = 1
total_size_2 = 1
for s in tensor_in_sizes:
total_size_1 *= s
for s in filter_in_sizes:
total_size_2 *= s
# Initializes the input tensor with array containing incrementing
# numbers from 1.
data_array = [f * 1.0 fo... | ):
""" One iteration of ReLU """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = nn_ops.relu(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
def test_forward_relu():
""" ReLU """
_test_relu(np.aran... | 125 | 126 | 420 | 20 | 105 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_fully_connected | _test_fully_connected | 901 | 934 | 901 | 901 | 9a78d55cded8ce16ee1fed386ca241270cf0f59d | bigcode/the-stack | train |
0edd112ef6da923b748ab682 | train | function | def run_tvm_graph(tflite_model_buf, input_data, input_node, num_output=1, target='llvm',
out_names=None):
""" Generic function to compile on relay and execute on tvm """
try:
import tflite.Model
except ImportError:
raise ImportError("The tflite package must be installed")
... | def run_tvm_graph(tflite_model_buf, input_data, input_node, num_output=1, target='llvm',
out_names=None):
| """ Generic function to compile on relay and execute on tvm """
try:
import tflite.Model
except ImportError:
raise ImportError("The tflite package must be installed")
# get TFLite model from buffer
tflite_model = tflite.Model.Model.GetRootAsModel(tflite_model_buf, 0)
input_data... | variables
try:
from tensorflow import lite as interpreter_wrapper
except ImportError:
from tensorflow.contrib import lite as interpreter_wrapper
import tvm.relay.testing.tf as tf_testing
from packaging import version as package_version
#######################################################################
#... | 119 | 119 | 397 | 31 | 87 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | run_tvm_graph | run_tvm_graph | 52 | 95 | 52 | 53 | 228e3c40dca8f46e224577a842adbf0c488b3bdf | bigcode/the-stack | train |
29ccfde00f30275cfe64b299 | train | function | def _test_relu(data):
""" One iteration of ReLU """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = nn_ops.relu(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| def _test_relu(data):
| """ One iteration of ReLU """
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
out = nn_ops.relu(in_data)
compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
| , 'Placeholder:0', [in_data], [out])
def test_forward_tanh():
""" TANH """
_test_tanh(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
#######################################################################
# ReLu
# --------
def _test_relu(data):
| 64 | 64 | 68 | 6 | 57 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_relu | _test_relu | 886 | 891 | 886 | 886 | 36b3a06b9928f2dbb8f9bf7257c9ddf29b14afd5 | bigcode/the-stack | train |
e45a32786616f34503e1915f | train | function | def test_forward_qnn_mobilenet_v1_net():
"""Test the Quantized TFLite Mobilenet V1 model."""
# MobilenetV1
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz",
"mobilenet_... | def test_forward_qnn_mobilenet_v1_net():
| """Test the Quantized TFLite Mobilenet V1 model."""
# MobilenetV1
tflite_model_file = tf_testing.get_workload_official(
"https://storage.googleapis.com/download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224_quant.tgz",
"mobilenet_v1_1.0_224_quant.tflite")
with open(t... | flite_sorted_labels = tflite_predictions.argsort()[-3:][::-1]
tvm_output = run_tvm_graph(tflite_model_buf, data, 'input')
tvm_predictions = np.squeeze(tvm_output)
tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1]
tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels)
def test_forwar... | 99 | 99 | 331 | 12 | 87 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | test_forward_qnn_mobilenet_v1_net | test_forward_qnn_mobilenet_v1_net | 1,029 | 1,047 | 1,029 | 1,029 | 433451d7a0191e443a054b129929d287fd953b19 | bigcode/the-stack | train |
fe676ed76e103f56b7fa5d45 | train | function | def _test_elemwise(math_op, data, fused_activation_function=None):
""" One iteration of elemwise """
assert len(data) == 2
# Test with two tensors
with tf.Graph().as_default():
in_data = [array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in_0'),
array_ops... | def _test_elemwise(math_op, data, fused_activation_function=None):
| """ One iteration of elemwise """
assert len(data) == 2
# Test with two tensors
with tf.Graph().as_default():
in_data = [array_ops.placeholder(shape=data[0].shape, dtype=data[0].dtype, name='in_0'),
array_ops.placeholder(shape=data[1].shape, dtype=data[1].dtype, name='in_1')... | 2, 1, 1, 3)),
np.arange(6).reshape((2, 1, 1, 3)),
np.arange(6).reshape((2, 1, 1, 3))], 1)
#######################################################################
# Element-wise
# ---
def _test_elemwise(math_op, data, fused_activation_function=None):
| 77 | 78 | 263 | 15 | 62 | ElaineBao/tvm | tests/python/frontend/tflite/test_forward.py | Python | _test_elemwise | _test_elemwise | 548 | 566 | 548 | 548 | afbfb8db06937cb21649b7c56935b242ef7982bf | bigcode/the-stack | train |
7aeaf7b84e0021d2d7f0992c | train | class | class EfficientNet(nn.Module):
"""
An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained methods
Args:
blocks_args (list): A list of BlockArgs to construct blocks
global_params (namedtuple): A set of GlobalParams shared between blocks
Example:
model ... | class EfficientNet(nn.Module):
| """
An EfficientNet model. Most easily loaded with the .from_name or .from_pretrained methods
Args:
blocks_args (list): A list of BlockArgs to construct blocks
global_params (namedtuple): A set of GlobalParams shared between blocks
Example:
model = EfficientNet.from_pretrained(... | between 0 and 1)
:return: output of block
"""
# Expansion and Depthwise Convolution
x = inputs
if self._block_args.expand_ratio != 1:
x = relu_fn(self._bn0(self._expand_conv(inputs)))
x = relu_fn(self._bn1(self._depthwise_conv(x)))
# Squeeze and Exc... | 256 | 256 | 1,154 | 6 | 249 | akirasosa/CenterNet | src/lib/models/networks/efficientnet/model.py | Python | EfficientNet | EfficientNet | 96 | 213 | 96 | 96 | 6d153d05d6564bdae6fec361dfcf5435c34ab150 | bigcode/the-stack | train |
c81cc5a11baeac0c643558e5 | train | class | class MBConvBlock(nn.Module):
"""
Mobile Inverted Residual Bottleneck Block
Args:
block_args (namedtuple): BlockArgs, see above
global_params (namedtuple): GlobalParam, see above
Attributes:
has_se (bool): Whether the block contains a Squeeze and Excitation layer.
"""
... | class MBConvBlock(nn.Module):
| """
Mobile Inverted Residual Bottleneck Block
Args:
block_args (namedtuple): BlockArgs, see above
global_params (namedtuple): GlobalParam, see above
Attributes:
has_se (bool): Whether the block contains a Squeeze and Excitation layer.
"""
def __init__(self, block_args,... | import torch
from torch import nn
from torch.nn import functional as F
from .utils import (
relu_fn,
round_filters,
round_repeats,
drop_connect,
get_same_padding_conv2d,
get_model_params,
efficientnet_params,
load_pretrained_weights,
)
class MBConvBlock(nn.Module):
| 72 | 256 | 883 | 7 | 65 | akirasosa/CenterNet | src/lib/models/networks/efficientnet/model.py | Python | MBConvBlock | MBConvBlock | 17 | 93 | 17 | 17 | b874d29a741e9ece0312d0187478ca41e5de0ff2 | bigcode/the-stack | train |
438e96093b75539e4d81e4f8 | train | class | class BTChipCmdLineHandler:
def stop(self):
pass
def show_message(self, msg):
print_msg(msg)
def prompt_auth(self, msg):
import getpass
print_msg(msg)
response = getpass.getpass('')
if len(response) == 0:
return None
return response
| class BTChipCmdLineHandler:
| def stop(self):
pass
def show_message(self, msg):
print_msg(msg)
def prompt_auth(self, msg):
import getpass
print_msg(msg)
response = getpass.getpass('')
if len(response) == 0:
return None
return response
| from legder import LedgerPlugin
from fermatum.util import print_msg
class BTChipCmdLineHandler:
| 22 | 64 | 71 | 7 | 14 | Anfauglith/fermatum | plugins/ledger/cmdline.py | Python | BTChipCmdLineHandler | BTChipCmdLineHandler | 4 | 17 | 4 | 4 | 06f30e4dd24d0f5a6ec69643e75163672475e9c6 | bigcode/the-stack | train |
6d27584672d3230da8f73368 | train | class | class Plugin(LedgerPlugin):
handler = BTChipCmdLineHandler()
| class Plugin(LedgerPlugin):
| handler = BTChipCmdLineHandler()
|
def show_message(self, msg):
print_msg(msg)
def prompt_auth(self, msg):
import getpass
print_msg(msg)
response = getpass.getpass('')
if len(response) == 0:
return None
return response
class Plugin(LedgerPlugin):
| 64 | 64 | 16 | 7 | 56 | Anfauglith/fermatum | plugins/ledger/cmdline.py | Python | Plugin | Plugin | 19 | 20 | 19 | 19 | 37fdcce1ebe3b106fd245f965dc4a84d877dc869 | bigcode/the-stack | train |
a66830bea45d1e224c69eb85 | train | class | class TimeResult:
def __init__(self, hour: int, minute: int, second: int, low_bound: int = -1):
self.hour = hour
self.minute = minute
self.second = second
self.low_bound = low_bound
| class TimeResult:
| def __init__(self, hour: int, minute: int, second: int, low_bound: int = -1):
self.hour = hour
self.minute = minute
self.second = second
self.low_bound = low_bound
| from recognizers_text import ExtractResult
from ..extractors import DateTimeExtractor
class DateTimeExtra:
def __init__(self):
self.data_type: any = None
self.named_entity: Dict[str, List[str]] = dict()
self.match: Match = None
class TimeResult:
| 64 | 64 | 57 | 4 | 59 | hongman/Recognizers-Text | Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/base_date_time_extractor.py | Python | TimeResult | TimeResult | 15 | 20 | 15 | 15 | f2307c5215103089573da7df7ae9ed17a1be3b5a | bigcode/the-stack | train |
e28e98a3d8a28d1cae5a468c | train | class | class TimeResolutionUtils:
@staticmethod
def add_description(time_result: TimeResult, low_bound_map: Dict[str, int], description: str):
if description in low_bound_map and time_result.hour < low_bound_map[description]:
time_result.hour = time_result.hour + 12
time_result.low_boun... | class TimeResolutionUtils:
@staticmethod
| def add_description(time_result: TimeResult, low_bound_map: Dict[str, int], description: str):
if description in low_bound_map and time_result.hour < low_bound_map[description]:
time_result.hour = time_result.hour + 12
time_result.low_bound = low_bound_map[description]
else:
... | class TimeResult:
def __init__(self, hour: int, minute: int, second: int, low_bound: int = -1):
self.hour = hour
self.minute = minute
self.second = second
self.low_bound = low_bound
class TimeResolutionUtils:
@staticmethod
| 66 | 66 | 223 | 9 | 56 | hongman/Recognizers-Text | Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/base_date_time_extractor.py | Python | TimeResolutionUtils | TimeResolutionUtils | 22 | 51 | 22 | 23 | ebbfa4fdd1e4960562853d912de2254053e041b6 | bigcode/the-stack | train |
77944919f664f5ea2f72bb8c | train | class | class ChineseBaseDateTimeExtractor(DateTimeExtractor):
def __init__(self, regex_dict: Dict[Pattern, any]):
self._regex_dict = regex_dict
def extract(self, source: str, reference: datetime = None) -> List[ExtractResult]:
if reference is None:
reference = datetime.now()
resu... | class ChineseBaseDateTimeExtractor(DateTimeExtractor):
| def __init__(self, regex_dict: Dict[Pattern, any]):
self._regex_dict = regex_dict
def extract(self, source: str, reference: datetime = None) -> List[ExtractResult]:
if reference is None:
reference = datetime.now()
result: List[ExtractResult] = list()
if not source:... | : Pattern, numbers_map: Dict[str, int], source: str) -> int:
if not source.strip():
return -1
if regex.match(only_digit_match, source):
return int(source)
if len(source) == 1:
return numbers_map[source]
value = 1
for index, char in enumerate... | 134 | 134 | 448 | 10 | 123 | hongman/Recognizers-Text | Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/base_date_time_extractor.py | Python | ChineseBaseDateTimeExtractor | ChineseBaseDateTimeExtractor | 53 | 107 | 53 | 53 | 761ec7908bce3d2aa2b2ec3f96a1bdf47d87fade | bigcode/the-stack | train |
a902b120480c922818b5a599 | train | class | class DateTimeExtra:
def __init__(self):
self.data_type: any = None
self.named_entity: Dict[str, List[str]] = dict()
self.match: Match = None
| class DateTimeExtra:
| def __init__(self):
self.data_type: any = None
self.named_entity: Dict[str, List[str]] = dict()
self.match: Match = None
| from typing import List, Dict, Pattern, Match, Optional
from abc import ABC, abstractmethod
from datetime import datetime
import regex
from recognizers_text import ExtractResult
from ..extractors import DateTimeExtractor
class DateTimeExtra:
| 51 | 64 | 43 | 5 | 45 | hongman/Recognizers-Text | Python/libraries/recognizers-date-time/recognizers_date_time/date_time/chinese/base_date_time_extractor.py | Python | DateTimeExtra | DateTimeExtra | 9 | 13 | 9 | 9 | 34116dea02dea8a6f54a62ef021468bd1a468f83 | bigcode/the-stack | train |
9721003aa257a0d829da5915 | train | function | def modify_files(opt, split):
target_dir = os.path.join(opt.data, split)
filenames = get_file_names(target_dir)
ent, ent_dropped, ent_skipped, ent_wrong_head = 0, 0, 0, 0
eve, eve_dropped, eve_wrong_trigger = 0, 0, 0
rel, rel_dropped = 0, 0
model = Model(model_map[opt.lang])
for filename in ... | def modify_files(opt, split):
| target_dir = os.path.join(opt.data, split)
filenames = get_file_names(target_dir)
ent, ent_dropped, ent_skipped, ent_wrong_head = 0, 0, 0, 0
eve, eve_dropped, eve_wrong_trigger = 0, 0, 0
rel, rel_dropped = 0, 0
model = Model(model_map[opt.lang])
for filename in tqdm(filenames, total=len(file... | _id']
new_relation['position'] = [relation_offset['start'], relation_offset['end']]
new_relation['arguments'] = []
for argument in relation['arguments']:
if argument['entity-id'] in entities:
entity = entities[argument['entity-id']]
... | 142 | 142 | 474 | 7 | 134 | wasiahmad/ACE05-Processor | extract.py | Python | modify_files | modify_files | 533 | 581 | 533 | 533 | 5df9ec64ea5a1b3b57269341b37e181b1f3420c7 | bigcode/the-stack | train |
55572e7324efdc64466994e7 | train | function | def main(args):
args.data = os.path.join(args.data, lang_name[args.lang])
print('--' * 10 + ' Train ' + '--' * 10)
modify_files(args, 'train')
print('--' * 10 + ' Dev ' + '--' * 10)
modify_files(args, 'dev')
print('--' * 10 + ' Test ' + '--' * 10)
modify_files(args, 'test')
| def main(args):
| args.data = os.path.join(args.data, lang_name[args.lang])
print('--' * 10 + ' Train ' + '--' * 10)
modify_files(args, 'train')
print('--' * 10 + ' Dev ' + '--' * 10)
modify_files(args, 'dev')
print('--' * 10 + ' Test ' + '--' * 10)
modify_files(args, 'test')
| print('[Events] Total {:>5}, Dropped {:>4}, Wrong-Trigger {:>2}.'.format(
eve, eve_dropped, eve_wrong_trigger))
print('[Relations] Total {:>5}, Dropped {:>4}.'.format(rel, rel_dropped))
def main(args):
| 64 | 64 | 98 | 4 | 60 | wasiahmad/ACE05-Processor | extract.py | Python | main | main | 584 | 591 | 584 | 584 | fead52534270e39e02e79b6a1e4c6be69e034b65 | bigcode/the-stack | train |
ff6ec812a9ee4d19d1e13260 | train | function | def correct_events(list_of_events, list_of_entities, sentences, lang, model):
entities = dict()
for entity in list_of_entities:
entities[entity['entity-id']] = entity
corrected_events = []
dropped, wrong_trigger = 0, 0
for event in list_of_events:
new_event = dict()
new_even... | def correct_events(list_of_events, list_of_entities, sentences, lang, model):
| entities = dict()
for entity in list_of_entities:
entities[entity['entity-id']] = entity
corrected_events = []
dropped, wrong_trigger = 0, 0
for event in list_of_events:
new_event = dict()
new_event['event-id'] = event['event-id']
new_event['event_type'] = event['eve... | , 249],
# "role": "Time-Within",
# "entity-id": "AFP_ENG_20030304.0250-T2-1"
# }
# ],
# "text": "At least 19 people were killed and 114 people were wounded in\nTuesday's southern
# Philippines airport blast, officials said, but\nreports said the death toll could climb to 30",
# "position": [181, 353],
# "t... | 158 | 158 | 527 | 17 | 141 | wasiahmad/ACE05-Processor | extract.py | Python | correct_events | correct_events | 426 | 490 | 426 | 426 | 7d6c96df0ba7a0e54c841ac26b8feb83d5833b9a | bigcode/the-stack | train |
f0bc12766df44ffb517da293 | train | function | def correct_entities(list_of_entity, sentences, lang, model):
corrected_entities = []
skipped, dropped, wrong_head = 0, 0, 0
for entity in list_of_entity:
if entity['entity-type'] == 'TIM:time':
skipped += 1
continue
new_entity = dict()
new_entity['entity-id']... | def correct_entities(list_of_entity, sentences, lang, model):
| corrected_entities = []
skipped, dropped, wrong_head = 0, 0, 0
for entity in list_of_entity:
if entity['entity-type'] == 'TIM:time':
skipped += 1
continue
new_entity = dict()
new_entity['entity-id'] = entity['entity-id']
new_entity['entity-type'] = ent... | matches[index]
return [-1, -1]
# An Entity example is as follows.
# {
# "entity-id": "AFP_ENG_20030304.0250-E1-3",
# "entity-type": "ORG:Medical-Science",
# "text": "The Davao Medical Center",
# "position": [493, 516],
# "head": {
# "text": "Davao Medical Center",
# "position": [497, 516]
# }
# }
def ... | 131 | 131 | 438 | 13 | 118 | wasiahmad/ACE05-Processor | extract.py | Python | correct_entities | correct_entities | 342 | 391 | 342 | 342 | 0d0cd364888b08a1c02a1c56d71f3f518f0d3a7c | bigcode/the-stack | train |
02036efa3c1494c6f220afd5 | train | function | def find_subspan_offset(sent, offset, text, text_start, text_end, model):
ent_start, ent_end = offset
start, end = [], []
for i in range(ent_start, ent_end + 1):
offset = sent['offset'][i]
if offset[0] == text_start:
start.append(i)
if offset[1] == text_end + 1:
... | def find_subspan_offset(sent, offset, text, text_start, text_end, model):
| ent_start, ent_end = offset
start, end = [], []
for i in range(ent_start, ent_end + 1):
offset = sent['offset'][i]
if offset[0] == text_start:
start.append(i)
if offset[1] == text_end + 1:
end.append(i)
# best case
if len(start) == 1 and len(end) == 1... | there are matches such as: `my ex` in `my ex's`
# `Nashville , Tenn` in `Nashville , Tenn.`
selected_text = ' '.join(sent['word'][i: i + text_len])
selected_text_len = len(selected_text)
for j in range(selected_text_len - t... | 256 | 256 | 1,038 | 19 | 237 | wasiahmad/ACE05-Processor | extract.py | Python | find_subspan_offset | find_subspan_offset | 229 | 328 | 229 | 229 | 9a70dea048d9af38124292882bc58d2ff4d3092b | bigcode/the-stack | train |
043b3c2976f7aa574753a27e | train | function | def load_json(json_file):
with open(json_file) as f:
data = json.load(f)
return data
| def load_json(json_file):
| with open(json_file) as f:
data = json.load(f)
return data
| ',
'ar': 'Arabic',
'zh': 'Chinese'
}
def get_file_names(dirpath):
filenames = []
for file in os.listdir(dirpath):
if file.endswith(".conllu"):
filenames.append(os.path.splitext(file)[0])
return filenames
def load_json(json_file):
| 64 | 64 | 26 | 6 | 57 | wasiahmad/ACE05-Processor | extract.py | Python | load_json | load_json | 31 | 34 | 31 | 31 | 41722bc7074f1c00ee11fd73f8b73f963f91c35a | bigcode/the-stack | train |
10859fc3b61b79f0a02cdea9 | train | function | def find_span_offset(sentences, text, text_start, text_end, model, lang):
match_positions = [-1, -1]
type_of_match_found = ''
best_sent_id = None
best_sent = None
tokenized_text = model.tokenize(text, 'ranges')
conllu = parse(model.write(tokenized_text, "conllu"))
text_words = [w['form'] fo... | def find_span_offset(sentences, text, text_start, text_end, model, lang):
| match_positions = [-1, -1]
type_of_match_found = ''
best_sent_id = None
best_sent = None
tokenized_text = model.tokenize(text, 'ranges')
conllu = parse(model.write(tokenized_text, "conllu"))
text_words = [w['form'] for sent in conllu for w in sent]
text_len = len(text_words)
tokeniz... | '].split(':')
offset.append([int(indices[0]), int(indices[1])])
elif len(reserved_offsets) > 0:
offset.append(reserved_offsets.pop())
else:
offset.append([-1, -1])
assert len(tokens) == len(offse... | 256 | 256 | 1,383 | 19 | 236 | wasiahmad/ACE05-Processor | extract.py | Python | find_span_offset | find_span_offset | 89 | 226 | 89 | 89 | 756f33c7a9ee73d58198cc263bd03d87d8946ce2 | bigcode/the-stack | train |
052c4747f5ae48dbe04f4f1d | train | function | def compare_string_without_space(src_words, tgt_words, ignore_punc=False):
src_chars = list(' '.join(src_words).replace(" ", ""))
tgt_chars = list(' '.join(tgt_words).replace(" ", ""))
if ignore_punc:
src_chars = [ch for ch in src_chars if ch not in string.punctuation]
tgt_chars = [ch for ch... | def compare_string_without_space(src_words, tgt_words, ignore_punc=False):
| src_chars = list(' '.join(src_words).replace(" ", ""))
tgt_chars = list(' '.join(tgt_words).replace(" ", ""))
if ignore_punc:
src_chars = [ch for ch in src_chars if ch not in string.punctuation]
tgt_chars = [ch for ch in tgt_chars if ch not in string.punctuation]
return src_chars == tgt_... | ', tokens),
('upos', upos),
('head', head),
('deprel', deprel),
('offset', offset)
])
conllu_data.append(sent_obj)
return conllu_data
def compare_string_without_space(src_words, tgt_words, ignore_punc=False):
| 64 | 64 | 101 | 16 | 47 | wasiahmad/ACE05-Processor | extract.py | Python | compare_string_without_space | compare_string_without_space | 80 | 86 | 80 | 80 | fbc03f9cfc59fa7c277282d98081c16942036e06 | bigcode/the-stack | train |
6abbf3e7e0c0e3fab4cfde63 | train | function | def load_conllu(conllu_file):
conllu_data = []
with open(conllu_file, 'r', encoding='utf-8') as content_file:
content = content_file.read()
sentences = parse(content)
for idx, sentence in enumerate(sentences):
tokens, upos, head, deprel, offset = [], [], [], [], []
... | def load_conllu(conllu_file):
| conllu_data = []
with open(conllu_file, 'r', encoding='utf-8') as content_file:
content = content_file.read()
sentences = parse(content)
for idx, sentence in enumerate(sentences):
tokens, upos, head, deprel, offset = [], [], [], [], []
reserved_offsets = []
... | 191206.udpipe'
}
lang_name = {
'en': 'English',
'ar': 'Arabic',
'zh': 'Chinese'
}
def get_file_names(dirpath):
filenames = []
for file in os.listdir(dirpath):
if file.endswith(".conllu"):
filenames.append(os.path.splitext(file)[0])
return filenames
def load_json(json_fil... | 108 | 108 | 360 | 8 | 99 | wasiahmad/ACE05-Processor | extract.py | Python | load_conllu | load_conllu | 37 | 77 | 37 | 37 | 6a3a4ab5a9bc77bc7a937cb33d14213ce5c196d7 | bigcode/the-stack | train |
12c6bc2463cbf90f737df85f | train | function | def get_file_names(dirpath):
filenames = []
for file in os.listdir(dirpath):
if file.endswith(".conllu"):
filenames.append(os.path.splitext(file)[0])
return filenames
| def get_file_names(dirpath):
| filenames = []
for file in os.listdir(dirpath):
if file.endswith(".conllu"):
filenames.append(os.path.splitext(file)[0])
return filenames
| -191206.udpipe',
'ar': 'udpipe/arabic-padt-ud-2.5-191206.udpipe'
}
lang_name = {
'en': 'English',
'ar': 'Arabic',
'zh': 'Chinese'
}
def get_file_names(dirpath):
| 64 | 64 | 42 | 7 | 57 | wasiahmad/ACE05-Processor | extract.py | Python | get_file_names | get_file_names | 23 | 28 | 23 | 23 | 3cd956588f1722aea199f64aca2708ca3229bedc | bigcode/the-stack | train |
67dc17fdd04b631b532df58d | train | function | def correct_relations(list_of_relations, list_of_entities, sentences, lang, model):
entities = dict()
for entity in list_of_entities:
entities[entity['entity-id']] = entity
corrected_relations = []
dropped = 0
for relation in list_of_relations:
new_relation = dict()
new_rela... | def correct_relations(list_of_relations, list_of_entities, sentences, lang, model):
| entities = dict()
for entity in list_of_entities:
entities[entity['entity-id']] = entity
corrected_relations = []
dropped = 0
for relation in list_of_relations:
new_relation = dict()
new_relation['relation-id'] = relation['relation-id']
new_relation['relation-type'] ... | _offset['start'], event_offset['end']]
new_event['trigger'] = {
'text': event['trigger']['text'],
'position': [trigger_offset[0], trigger_offset[1]]
}
corrected_events.append(new_event)
else:
dropped += 1
return corrected_event... | 89 | 89 | 299 | 19 | 69 | wasiahmad/ACE05-Processor | extract.py | Python | correct_relations | correct_relations | 493 | 530 | 493 | 493 | 3bb0abaa3d775cdf1ccae75497c6f6922954ceb3 | bigcode/the-stack | train |
758378b4bef9b499c54d3749 | train | function | def lambda_handler(event, context):
filters = [
{
'Name': 'tag:AutoStart',
'Values': ['TRUE','True','true']
},
{
'Name': 'instance-state-name',
'Values': ['stopped']
}
]
instances = ec2.instances.filter(Filters=fi... | def lambda_handler(event, context):
| filters = [
{
'Name': 'tag:AutoStart',
'Values': ['TRUE','True','true']
},
{
'Name': 'instance-state-name',
'Values': ['stopped']
}
]
instances = ec2.instances.filter(Filters=filters)
StoppedInstances = [instanc... | import boto3
import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
region = os.environ['AWS_REGION']
ec2 = boto3.resource('ec2', region_name=region)
def lambda_handler(event, context):
| 52 | 64 | 192 | 7 | 45 | aws-samples/aws-cfn-save-costs-auto-start-stop-ec2 | sam_auto_start_stop_ec2/lambda/AutoStartEC2Instance.py | Python | lambda_handler | lambda_handler | 11 | 35 | 11 | 12 | bb316a0fe08e7782c98d2624d77bfa7d36c2b25c | bigcode/the-stack | train |
b2c0b8854b2d385e0cf8dd6e | train | function | def VGG16(include_top=True, weights='imagenet',
input_tensor=None, input_shape=None,
pooling=None,
classes=1000):
"""Instantiates the VGG16 architecture.
Optionally loads weights pre-trained
on ImageNet. Note that when using TensorFlow,
for best performance you should set
... | def VGG16(include_top=True, weights='imagenet',
input_tensor=None, input_shape=None,
pooling=None,
classes=1000):
| """Instantiates the VGG16 architecture.
Optionally loads weights pre-trained
on ImageNet. Note that when using TensorFlow,
for best performance you should set
`image_data_format='channels_last'` in your Keras config
at ~/.keras/keras.json.
The model and the weights are compatible with both... | 6)
"""
from __future__ import print_function
from __future__ import absolute_import
import warnings
from ..models import Model
from ..layers import Flatten
from ..layers import Dense
from ..layers import Input
from ..layers import Conv2D
from ..layers import MaxPooling2D
from ..layers import GlobalAveragePooling2D
f... | 256 | 256 | 1,761 | 32 | 224 | go2carter/keras_augtest | keras/applications/vgg16.py | Python | VGG16 | VGG16 | 35 | 190 | 35 | 38 | e91a8d1ad1128d0c525507af900c1dc3d8128922 | bigcode/the-stack | train |
5014649eaa003fee896e7cda | train | function | def jgit_repos():
if LOCAL_JGIT_REPO:
native.local_repository(
name = "jgit",
path = LOCAL_JGIT_REPO,
)
jgit_maven_repos_dev()
else:
jgit_maven_repos()
| def jgit_repos():
| if LOCAL_JGIT_REPO:
native.local_repository(
name = "jgit",
path = LOCAL_JGIT_REPO,
)
jgit_maven_repos_dev()
else:
jgit_maven_repos()
| ERS + "/apidocs"
_JGIT_REPO = MAVEN_CENTRAL # Leave here even if set to MAVEN_CENTRAL.
# set this to use a local version.
# "/home/<user>/projects/jgit"
LOCAL_JGIT_REPO = ""
def jgit_repos():
| 64 | 64 | 59 | 6 | 58 | LogtalkDotOrg/gerrit | lib/jgit/jgit.bzl | Python | jgit_repos | jgit_repos | 15 | 23 | 15 | 15 | f53a4a59dd200e2bfbff4b1718ec45e6f6aa79e3 | bigcode/the-stack | train |
0fd629556331ba0a77969e02 | train | function | def jgit_maven_repos_dev():
# Transitive dependencies from JGit's WORKSPACE.
maven_jar(
name = "hamcrest-library",
artifact = "org.hamcrest:hamcrest-library:1.3",
sha1 = "4785a3c21320980282f9f33d0d1264a69040538f",
)
maven_jar(
name = "jzlib",
artifact = "com.jcraf... | def jgit_maven_repos_dev():
# Transitive dependencies from JGit's WORKSPACE.
| maven_jar(
name = "hamcrest-library",
artifact = "org.hamcrest:hamcrest-library:1.3",
sha1 = "4785a3c21320980282f9f33d0d1264a69040538f",
)
maven_jar(
name = "jzlib",
artifact = "com.jcraft:jzlib:1.1.1",
sha1 = "a1551373315ffc2f96130a0e5704f74e151777ba",
)
| native.local_repository(
name = "jgit",
path = LOCAL_JGIT_REPO,
)
jgit_maven_repos_dev()
else:
jgit_maven_repos()
def jgit_maven_repos_dev():
# Transitive dependencies from JGit's WORKSPACE.
| 64 | 64 | 141 | 21 | 43 | LogtalkDotOrg/gerrit | lib/jgit/jgit.bzl | Python | jgit_maven_repos_dev | jgit_maven_repos_dev | 25 | 36 | 25 | 26 | 8fd5bab7892530d9d7132629b920466a810e85f6 | bigcode/the-stack | train |
47d6dc75945b932ec7667af9 | train | function | def jgit_dep(name):
mapping = {
"@jgit-junit//jar": "@jgit//org.eclipse.jgit.junit:junit",
"@jgit-lib//jar:src": "@jgit//org.eclipse.jgit:libjgit-src.jar",
"@jgit-lib//jar": "@jgit//org.eclipse.jgit:jgit",
"@jgit-servlet//jar": "@jgit//org.eclipse.jgit.http.server:jgit-servlet",
... | def jgit_dep(name):
| mapping = {
"@jgit-junit//jar": "@jgit//org.eclipse.jgit.junit:junit",
"@jgit-lib//jar:src": "@jgit//org.eclipse.jgit:libjgit-src.jar",
"@jgit-lib//jar": "@jgit//org.eclipse.jgit:jgit",
"@jgit-servlet//jar": "@jgit//org.eclipse.jgit.http.server:jgit-servlet",
"@jgit-archive//... | .eclipse.jgit.junit:" + _JGIT_VERS,
repository = _JGIT_REPO,
sha1 = "1dc8f86bba3c461cb90c9dc3e91bf343889ca684",
unsign = True,
)
def jgit_dep(name):
| 64 | 64 | 145 | 6 | 58 | LogtalkDotOrg/gerrit | lib/jgit/jgit.bzl | Python | jgit_dep | jgit_dep | 68 | 80 | 68 | 68 | eb8e96be2aaa5722fa37e8ec2a2a1e93abfec099 | bigcode/the-stack | train |
595ac63505960eac3e980527 | train | function | def jgit_maven_repos():
maven_jar(
name = "jgit-lib",
artifact = "org.eclipse.jgit:org.eclipse.jgit:" + _JGIT_VERS,
repository = _JGIT_REPO,
sha1 = "f270dbd1d792d5ad06074abe018a18644c90b60e",
src_sha1 = "00e24ee2b721040edbb8520d705607a7f7bafd64",
unsign = True,
)
... | def jgit_maven_repos():
| maven_jar(
name = "jgit-lib",
artifact = "org.eclipse.jgit:org.eclipse.jgit:" + _JGIT_VERS,
repository = _JGIT_REPO,
sha1 = "f270dbd1d792d5ad06074abe018a18644c90b60e",
src_sha1 = "00e24ee2b721040edbb8520d705607a7f7bafd64",
unsign = True,
)
maven_jar(
n... | :hamcrest-library:1.3",
sha1 = "4785a3c21320980282f9f33d0d1264a69040538f",
)
maven_jar(
name = "jzlib",
artifact = "com.jcraft:jzlib:1.1.1",
sha1 = "a1551373315ffc2f96130a0e5704f74e151777ba",
)
def jgit_maven_repos():
| 108 | 108 | 360 | 8 | 100 | LogtalkDotOrg/gerrit | lib/jgit/jgit.bzl | Python | jgit_maven_repos | jgit_maven_repos | 38 | 66 | 38 | 38 | c5116da7cd69fb4185ca2db285ffbdea2a3933f5 | bigcode/the-stack | train |
8ca8892d5b0840fa98aa43f3 | train | class | @armregistry.register_tag("VPOP", ARMOpcode)
class ARMVectorVectorPop(ARMOpcode):
"""Retrieves multiple consecutive extension registers from the stack.
tags[1]: <c>
args[0]: index of stackpointer in armdictionary
args[1]: index of register list in armdictionary
args[2]: index of multiple memory loc... | @armregistry.register_tag("VPOP", ARMOpcode)
class ARMVectorVectorPop(ARMOpcode):
| """Retrieves multiple consecutive extension registers from the stack.
tags[1]: <c>
args[0]: index of stackpointer in armdictionary
args[1]: index of register list in armdictionary
args[2]: index of multiple memory locations in armdictionary
"""
def __init__(
self,
d... | import ARMOperand
import chb.util.fileutil as UF
from chb.util.IndexedTable import IndexedTableValue
if TYPE_CHECKING:
from chb.arm.ARMDictionary import ARMDictionary
@armregistry.register_tag("VPOP", ARMOpcode)
class ARMVectorVectorPop(ARMOpcode):
| 64 | 64 | 189 | 21 | 42 | kestreltechnology/CodeHawk-Binary | chb/arm/opcodes/ARMVectorPop.py | Python | ARMVectorVectorPop | ARMVectorVectorPop | 44 | 66 | 44 | 45 | b3dd7968bea737002c494b5ae600998304a111d7 | bigcode/the-stack | train |
59781673dd1e1f5c88be4356 | train | function | def do_test(test_variables):
"""
Main test body. Execute each subtest in turn.
"""
use_api = test_variables["use_api"]
if use_api:
info("Using API")
else:
info("Using CLI")
new_session_template = do_subtest("Generate BOS session template to be created", generate_session_tem... | def do_test(test_variables):
| """
Main test body. Execute each subtest in turn.
"""
use_api = test_variables["use_api"]
if use_api:
info("Using API")
else:
info("Using CLI")
new_session_template = do_subtest("Generate BOS session template to be created", generate_session_template)
template_name = ne... | subtest_func, **subtest_kwargs):
"""
Log that we are about to run a subtest with the specified name, then call the specified function
with the specified arguments. Raise exception in case of an error.
"""
subtest(subtest_name)
try:
return subtest_func(**subtest_kwargs)
except CMSTes... | 108 | 108 | 362 | 6 | 102 | Cray-HPE/bos | ct-tests/lib/bos_functional_test.py | Python | do_test | do_test | 64 | 100 | 64 | 64 | 3c8bd590edadc75006a6ce5fa4bb625f72c8bfc9 | bigcode/the-stack | train |
91ce0e6d7f8ebf718b50ee45 | train | function | def test_wrapper():
test_variables = { "test_template_name": None }
parse_args(test_variables)
init_logger(test_name=TEST_NAME, verbose=test_variables["verbose"])
info("Starting test")
debug("Arguments: %s" % sys.argv[1:])
debug("test_variables: %s" % str(test_variables))
try:
do_tes... | def test_wrapper():
| test_variables = { "test_template_name": None }
parse_args(test_variables)
init_logger(test_name=TEST_NAME, verbose=test_variables["verbose"])
info("Starting test")
debug("Arguments: %s" % sys.argv[1:])
debug("test_variables: %s" % str(test_variables))
try:
do_test(test_variables=tes... | ("List all BOS session templates", list_bos_session_templates, use_api=use_api)
do_subtest("Verify template is no longer listed", verify_template_list, template_map=all_templates,
template_name=template_name, should_exist=False)
section("Test passed")
def test_wrapper():
| 64 | 64 | 174 | 4 | 60 | Cray-HPE/bos | ct-tests/lib/bos_functional_test.py | Python | test_wrapper | test_wrapper | 102 | 118 | 102 | 102 | 64f0cbf7e42194b1232fffbf4059bab4be1b5f38 | bigcode/the-stack | train |
f5a96ed24e7278410b8c508f | train | function | def do_subtest(subtest_name, subtest_func, **subtest_kwargs):
"""
Log that we are about to run a subtest with the specified name, then call the specified function
with the specified arguments. Raise exception in case of an error.
"""
subtest(subtest_name)
try:
return subtest_func(**subte... | def do_subtest(subtest_name, subtest_func, **subtest_kwargs):
| """
Log that we are about to run a subtest with the specified name, then call the specified function
with the specified arguments. Raise exception in case of an error.
"""
subtest(subtest_name)
try:
return subtest_func(**subtest_kwargs)
except CMSTestError:
raise
except E... | Error, debug, error_exit, exit_test, \
init_logger, info, log_exception_error, raise_test_exception_error, \
section, subtest, warn
import sys
TEST_NAME = "bos_functional_test"
def do_subtest(subtest_name, subtest_func, **subtest_kwargs):
| 64 | 64 | 110 | 17 | 47 | Cray-HPE/bos | ct-tests/lib/bos_functional_test.py | Python | do_subtest | do_subtest | 51 | 62 | 51 | 51 | d14100a6217810dc8fcaab3da2eb0429315f483a | bigcode/the-stack | train |
e5892366b9924b5dfcf1bd63 | train | class | class DS3225Server(dbus.service.Object):
def __init__(self):
bus = dbus.SessionBus()
bus_name = dbus.service.BusName(BUS_NAME, bus)
super(DS3225Server, self).__init__(bus_name, OBJECT_PATH)
self.ds3225 = DS3225(18, ZeroOffsetDuty=0, Angle=UNLOCKED_DEG)
@dbus.service.method(INTERF... | class DS3225Server(dbus.service.Object):
| def __init__(self):
bus = dbus.SessionBus()
bus_name = dbus.service.BusName(BUS_NAME, bus)
super(DS3225Server, self).__init__(bus_name, OBJECT_PATH)
self.ds3225 = DS3225(18, ZeroOffsetDuty=0, Angle=UNLOCKED_DEG)
@dbus.service.method(INTERFACE, out_signature='q') # uint16
def ... | .mainloop.glib.DBusGMainLoop(set_as_default=True)
BUS_NAME = 'jp.kimura.DS3225Service'
OBJECT_PATH = '/jp/kimura/DS3225Server'
INTERFACE = 'jp.kimura.DS3225'
class DS3225Server(dbus.service.Object):
| 64 | 64 | 165 | 10 | 54 | kim-tom/dbus_server | ds3225_server.py | Python | DS3225Server | DS3225Server | 14 | 26 | 14 | 14 | 406da967a54fd34f99244c0730c0221ca7c0e1a1 | bigcode/the-stack | train |
a95d5affb0c62d37cc682135 | train | function | def main():
choice = menu()
while choice != 3:
if choice == 1:
c = eval(input("Enter degrees Celsius: "))
print(str(c) + "C = " + str(toFahrenheit(c)) + "F")
elif choice == 2:
f = eval(input("Enter degrees Fahrenheit: "))
print(str(f) + "F = " + str(toCelsius(f)) + "C")
else:
print("Invalid choic... | def main():
| choice = menu()
while choice != 3:
if choice == 1:
c = eval(input("Enter degrees Celsius: "))
print(str(c) + "C = " + str(toFahrenheit(c)) + "F")
elif choice == 2:
f = eval(input("Enter degrees Fahrenheit: "))
print(str(f) + "F = " + str(toCelsius(f)) + "C")
else:
print("Invalid choice.")
choic... | Celsius")
print("3. Exit")
choice = int(input("Enter a choice: "))
return choice
def toCelsius(f):
return int((f - 32) / 1.8)
def toFahrenheit(c):
return int(c * 1.8 + 32)
def main():
| 63 | 64 | 107 | 3 | 60 | Mark-Kinyua/python_public | conversions/temp_converter.py | Python | main | main | 16 | 27 | 16 | 16 | 1746ab20de4389acb0073e1a0a40552186a72b2d | bigcode/the-stack | train |
350d0ea3cd8670f1903c70c6 | train | function | def toFahrenheit(c):
return int(c * 1.8 + 32)
| def toFahrenheit(c):
| return int(c * 1.8 + 32)
| ():
print("\n1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")
choice = int(input("Enter a choice: "))
return choice
def toCelsius(f):
return int((f - 32) / 1.8)
def toFahrenheit(c):
| 64 | 64 | 18 | 6 | 58 | Mark-Kinyua/python_public | conversions/temp_converter.py | Python | toFahrenheit | toFahrenheit | 13 | 14 | 13 | 13 | aa10a4b99f24f14886bc79cfb93504dd188e5949 | bigcode/the-stack | train |
cb8610b442f167dfca12a767 | train | function | def toCelsius(f):
return int((f - 32) / 1.8)
| def toCelsius(f):
| return int((f - 32) / 1.8)
| # Temperature Conversion Program
def menu():
print("\n1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")
choice = int(input("Enter a choice: "))
return choice
def toCelsius(f):
| 51 | 64 | 20 | 6 | 44 | Mark-Kinyua/python_public | conversions/temp_converter.py | Python | toCelsius | toCelsius | 10 | 11 | 10 | 10 | 1bda7dfb984069bdfd01259adb7c1ec312cee5ee | bigcode/the-stack | train |
dc80e84b7b87c86cfb860420 | train | function | def menu():
print("\n1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")
choice = int(input("Enter a choice: "))
return choice
| def menu():
| print("\n1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Exit")
choice = int(input("Enter a choice: "))
return choice
| # Temperature Conversion Program
def menu():
| 8 | 64 | 40 | 3 | 4 | Mark-Kinyua/python_public | conversions/temp_converter.py | Python | menu | menu | 3 | 8 | 3 | 3 | 72484e6543232561f591a2aafccb93672f78ac6c | bigcode/the-stack | train |
732cbd7e96b2476c9a2f49ce | train | class | class Xwd(AutotoolsPackage, XorgPackage):
"""xwd - dump an image of an X window."""
homepage = "http://cgit.freedesktop.org/xorg/app/xwd"
xorg_mirror_path = "app/xwd-1.0.6.tar.gz"
version('1.0.6', sha256='ff01f0a4b736f955aaf7c8c3942211bc52f9fb75d96f2b19777f33fff5dc5b83')
depends_on('libx11')
... | class Xwd(AutotoolsPackage, XorgPackage):
| """xwd - dump an image of an X window."""
homepage = "http://cgit.freedesktop.org/xorg/app/xwd"
xorg_mirror_path = "app/xwd-1.0.6.tar.gz"
version('1.0.6', sha256='ff01f0a4b736f955aaf7c8c3942211bc52f9fb75d96f2b19777f33fff5dc5b83')
depends_on('libx11')
depends_on('libxkbfile')
depends_on('... | 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xwd(AutotoolsPackage, XorgPackage):
| 64 | 64 | 175 | 13 | 51 | carlabguillen/spack | var/spack/repos/builtin/packages/xwd/package.py | Python | Xwd | Xwd | 9 | 22 | 9 | 9 | b90720efe9e461731c7cc98fb5297ec34a73324f | bigcode/the-stack | train |
5cb3af334421b8c7d898385d | train | class | class Vocab:
def __init__(self, list_of_tokens=None, padding_token='<pad>', unknown_token='<unk>',
bos_token='<bos>', eos_token='<eos>', reserved_tokens=None, unknown_token_idx=0):
self._unknown_token = unknown_token
self._padding_token = padding_token
self._bos_token = bos_... | class Vocab:
| def __init__(self, list_of_tokens=None, padding_token='<pad>', unknown_token='<unk>',
bos_token='<bos>', eos_token='<eos>', reserved_tokens=None, unknown_token_idx=0):
self._unknown_token = unknown_token
self._padding_token = padding_token
self._bos_token = bos_token
... | from typing import List, Callable, Union
class Vocab:
| 13 | 175 | 585 | 4 | 8 | modudeepnlp/NLP_Tensorflow2.0 | seungmoo/convolutional_neural_networks_for_sentence_classification_torch/model/utils.py | Python | Vocab | Vocab | 4 | 81 | 4 | 4 | 686ba65921bf457770c34eacec20880075fe2bba | bigcode/the-stack | train |
274e3ba7a1fcd646825d05d3 | train | class | class PadSequence:
def __init__(self, length, pad_val=0, clip=True):
self._length = length
self._pad_val = pad_val
self_clip = clip
def __call__(self, sample):
sample_length = len(sample)
if sample_length >= self._length:
if self._clip and sample_length > sel... | class PadSequence:
| def __init__(self, length, pad_val=0, clip=True):
self._length = length
self._pad_val = pad_val
self_clip = clip
def __call__(self, sample):
sample_length = len(sample)
if sample_length >= self._length:
if self._clip and sample_length > self._length:
... | list_of_indices = self._pad(list_of_indices) if self._pad else list_of_indices
return list_of_indices
def split_and_transform(self, string):
return self.transform(self.split(string))
@property
def vocab(self):
return self._vocab
class PadSequence:
| 64 | 64 | 119 | 4 | 59 | modudeepnlp/NLP_Tensorflow2.0 | seungmoo/convolutional_neural_networks_for_sentence_classification_torch/model/utils.py | Python | PadSequence | PadSequence | 107 | 121 | 107 | 107 | 6c7f6748160e2237f775abd09c79b886e4d657ad | bigcode/the-stack | train |
66d98667c53d4a2e31354b54 | train | class | class Tokenizer:
def __init__(self, vocab:Vocab, split_fn, pad_fn):
self._vocab = vocab
self._split = split_fn
self._pad = pad_fn
def split(self, string):
list_of_tokens = self._split(string)
return list_of_tokens
def transform(self, list_of_tokens):
list_of... | class Tokenizer:
| def __init__(self, vocab:Vocab, split_fn, pad_fn):
self._vocab = vocab
self._split = split_fn
self._pad = pad_fn
def split(self, string):
list_of_tokens = self._split(string)
return list_of_tokens
def transform(self, list_of_tokens):
list_of_indices = self._... | ):
return self._bos_token
@property
def eos_token(self):
return self._eos_token
@property
def embedding(self):
return self._embedding
@embedding.setter
def embedding(self, array):
self._embedding = array
class Tokenizer:
| 64 | 64 | 153 | 4 | 59 | modudeepnlp/NLP_Tensorflow2.0 | seungmoo/convolutional_neural_networks_for_sentence_classification_torch/model/utils.py | Python | Tokenizer | Tokenizer | 84 | 104 | 84 | 84 | 49a459b0932aaf69934aa81fab17d9291707dd71 | bigcode/the-stack | train |
f4a4aa38b63f80108ab8f87a | train | class | class Writer(object):
''' Writer class to log to TensorBoard, SummaryWriter, and JSON logger.'''
def __init__(self, tb, json_logger, tb_path, json_file_path, purge_step, logger=None):
# local logging
self.log = logger if logger is not None else log
# tb writer
if tb is not Non... | class Writer(object):
| ''' Writer class to log to TensorBoard, SummaryWriter, and JSON logger.'''
def __init__(self, tb, json_logger, tb_path, json_file_path, purge_step, logger=None):
# local logging
self.log = logger if logger is not None else log
# tb writer
if tb is not None:
self.tb... | tag, text_string, global_step=None, walltime=None):
self.tb.add_text(tag, text_string, global_step, walltime)
def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, walltime=None):
self.tb.add_dict(main_tag, tag_scalar_dict, global_step, walltime)
def add_dict(self, main_tag, val_... | 152 | 152 | 507 | 4 | 148 | IBM/regen | utils/tensorboard.py | Python | Writer | Writer | 109 | 157 | 109 | 109 | 92bd53289557a41bb4a28ddfc9a47a737f0085e8 | bigcode/the-stack | train |
f5d56dfb46f885aa72a1b35c | train | class | class LoggingWriter(object):
''' Provides an alternative to TensorBoard using python logging infrastructure.'''
def __init__(self, writer_path='', writer_type='log'):
self.writer_path = writer_path
self.writer_type = writer_type
def add_anything(self, type_name, key, value, global_step, wa... | class LoggingWriter(object):
| ''' Provides an alternative to TensorBoard using python logging infrastructure.'''
def __init__(self, writer_path='', writer_type='log'):
self.writer_path = writer_path
self.writer_type = writer_type
def add_anything(self, type_name, key, value, global_step, walltime=None):
log.inf... | from collections import OrderedDict
import glob
import json
import shutil
import os
import logging
import torch
logger = logging.getLogger(__name__)
log = logger
class LoggingWriter(object):
| 41 | 96 | 320 | 5 | 35 | IBM/regen | utils/tensorboard.py | Python | LoggingWriter | LoggingWriter | 13 | 36 | 13 | 13 | ae2f1b027f24d78f40eefc527652bfa9ba1a0a0e | bigcode/the-stack | train |
10f765b2d8b31d3437d12c77 | train | class | class JsonLoggingWriter(object):
''' Provides an alternative to TensorBoard using python-json-logger library.'''
def __init__(self, json_logger, writer_log_file=''):
self.json_log = logging.getLogger('json-log')
self.json_log.propagate = False
# format for json logger
format_st... | class JsonLoggingWriter(object):
| ''' Provides an alternative to TensorBoard using python-json-logger library.'''
def __init__(self, json_logger, writer_log_file=''):
self.json_log = logging.getLogger('json-log')
self.json_log.propagate = False
# format for json logger
format_str = '%(asctime)%(created)%(leveln... | _step=None, walltime=None):
self.add_dict(main_tag, tag_scalar_dict, global_step, walltime, type_name='scalars')
def add_dict(self, main_tag, val_dict, global_step=None, walltime=None, type_name='dict'):
self.add_anything(type_name, main_tag, val_dict, global_step, walltime)
def add_text_list(... | 119 | 119 | 397 | 6 | 113 | IBM/regen | utils/tensorboard.py | Python | JsonLoggingWriter | JsonLoggingWriter | 39 | 74 | 39 | 39 | c973f34e0d585e08ea428f34cec1f3afd2bdb07e | bigcode/the-stack | train |
060aa4bb3212a188f3ea9ecc | train | function | def get_tensorboard(args, iteration, logger):
''' Returns a "tensorboard" writer '''
return get_summary_writer(tb_path=args.tensorboard_dir, json_file_path=args.results_json_log, global_iteration=iteration, logger=logger)
| def get_tensorboard(args, iteration, logger):
| ''' Returns a "tensorboard" writer '''
return get_summary_writer(tb_path=args.tensorboard_dir, json_file_path=args.results_json_log, global_iteration=iteration, logger=logger)
| _logger = None
log.warning('# OVERRIDE: force global_iteration/purge_step to be None')
global_iteration = None
writer = Writer(tb, json_logger, tb_path, json_file_path, global_iteration, logger=log)
return writer
def get_tensorboard(args, iteration, logger):
| 64 | 64 | 49 | 10 | 53 | IBM/regen | utils/tensorboard.py | Python | get_tensorboard | get_tensorboard | 192 | 194 | 192 | 192 | d80614ea093ee6ffaa3e9939482c5d9efbb6b522 | bigcode/the-stack | train |
74d76fa08ec8058a9ff12ed8 | train | function | def read_json_logs(fname, quiet=True):
''' Reads json logs and returns a list of objects '''
loglines = []
with open(fname, 'r') as f:
lines = f.read().splitlines()
for idx, line in enumerate(lines):
# log.info(line)
try:
obj = json.loads(line)
loglines... | def read_json_logs(fname, quiet=True):
| ''' Reads json logs and returns a list of objects '''
loglines = []
with open(fname, 'r') as f:
lines = f.read().splitlines()
for idx, line in enumerate(lines):
# log.info(line)
try:
obj = json.loads(line)
loglines.append(obj)
except json.JSONDe... | log)
return writer
def get_tensorboard(args, iteration, logger):
''' Returns a "tensorboard" writer '''
return get_summary_writer(tb_path=args.tensorboard_dir, json_file_path=args.results_json_log, global_iteration=iteration, logger=logger)
def read_json_logs(fname, quiet=True):
| 64 | 64 | 152 | 9 | 55 | IBM/regen | utils/tensorboard.py | Python | read_json_logs | read_json_logs | 197 | 217 | 197 | 197 | db40d67db0305ffa99c2d280e9a38bb0ebace60e | bigcode/the-stack | train |
05585014816e347e2213d7a1 | train | function | def get_json_logs_train(output_dir):
''' Given an output_dir for training, collects all jsonlog results files '''
pathsL = sorted(glob.glob(f'{output_dir}/jsonlog/*/results.json.*.rank.0.log'))
if not pathsL:
raise RuntimeError(f'cannot find json log files in [{output_dir}]')
# sort by epoch
... | def get_json_logs_train(output_dir):
| ''' Given an output_dir for training, collects all jsonlog results files '''
pathsL = sorted(glob.glob(f'{output_dir}/jsonlog/*/results.json.*.rank.0.log'))
if not pathsL:
raise RuntimeError(f'cannot find json log files in [{output_dir}]')
# sort by epoch
filesD = {}
for path in pathsL... | ) # {output_dir}/01
job_id = os.path.basename(dirname2) # 01
job_num = float(job_id)
filesD[job_num] = path
od = OrderedDict(sorted(filesD.items()))
return od
def get_json_logs_train(output_dir):
| 64 | 64 | 158 | 8 | 55 | IBM/regen | utils/tensorboard.py | Python | get_json_logs_train | get_json_logs_train | 242 | 259 | 242 | 242 | b30307704ab8708332f3c20f0e459a276422b4f5 | bigcode/the-stack | train |
ffd58b0b20632229c161bcc0 | train | function | def get_summary_writer(tb_path='', json_file_path='', global_iteration=0, logger=None):
''' Returns a summary writer with tensorboard, JSON logger if available '''
if logger is not None:
log = logger
else:
logger = logging.getLogger(__name__)
log = logger
# TensorBoard ?
try... | def get_summary_writer(tb_path='', json_file_path='', global_iteration=0, logger=None):
| ''' Returns a summary writer with tensorboard, JSON logger if available '''
if logger is not None:
log = logger
else:
logger = logging.getLogger(__name__)
log = logger
# TensorBoard ?
try:
import torch.utils.tensorboard as tb
log.info("# module tensorboard ex... | )
def add_text_list(self, tag, text_list, global_step=None, walltime=None):
for writer in self.writers:
writer.add_text_list(tag, text_list, global_step, walltime)
def get_summary_writer(tb_path='', json_file_path='', global_iteration=0, logger=None):
| 64 | 64 | 212 | 19 | 45 | IBM/regen | utils/tensorboard.py | Python | get_summary_writer | get_summary_writer | 160 | 189 | 160 | 160 | 4aa9b0c1eef1d12fb8d6a3a6ecac5d7aedcf6023 | bigcode/the-stack | train |
d2ffa5cb37befe895b3c0a73 | train | class | class TbWriter(object):
''' Provides a lightweight wrapper to TensorBoard.'''
def __init__(self, tb, tb_path, purge_step, remove_past_events=True):
# remove previous events files
if remove_past_events and os.path.exists(tb_path):
log.info(f'# clean {tb_path}')
tb_path_b... | class TbWriter(object):
| ''' Provides a lightweight wrapper to TensorBoard.'''
def __init__(self, tb, tb_path, purge_step, remove_past_events=True):
# remove previous events files
if remove_past_events and os.path.exists(tb_path):
log.info(f'# clean {tb_path}')
tb_path_bak = tb_path + '.bak'
... | _name='scalars')
def add_dict(self, main_tag, val_dict, global_step=None, walltime=None, type_name='dict'):
self.log.info(type_name, extra={'iteration': global_step, main_tag: val_dict})
def add_text_list(self, key, value, global_step=None, walltime=None):
self.add_anything('text_list', key, v... | 93 | 93 | 313 | 5 | 88 | IBM/regen | utils/tensorboard.py | Python | TbWriter | TbWriter | 77 | 106 | 77 | 77 | 9f0399b18308622d6c0ccc96814b5c8f0de8c02f | bigcode/the-stack | train |
1014373b4a9c630e0a46570a | train | function | def get_json_logs(output_dir):
''' Given an output_dir for evaluation, collects all jsonlog results files '''
pathsL = sorted(glob.glob(f'{output_dir}/*/jsonlog/results.json.log'))
if not pathsL:
raise RuntimeError(f'cannot find json log files in [{output_dir}]')
# sort by epoch
filesD = ... | def get_json_logs(output_dir):
| ''' Given an output_dir for evaluation, collects all jsonlog results files '''
pathsL = sorted(glob.glob(f'{output_dir}/*/jsonlog/results.json.log'))
if not pathsL:
raise RuntimeError(f'cannot find json log files in [{output_dir}]')
# sort by epoch
filesD = {}
for path in pathsL:
... | ': line {idx} raises an exception by json decoder\n: line= {line}")
raise RuntimeError(f"Failed parsing '{fname}'") from err
if not quiet:
log.info(f'# read fname [{len(line)} lines]')
return loglines
def get_json_logs(output_dir):
| 64 | 64 | 169 | 7 | 56 | IBM/regen | utils/tensorboard.py | Python | get_json_logs | get_json_logs | 220 | 239 | 220 | 220 | 67a3a8a852bb0448915502a9d5f3f2926d62b6f3 | bigcode/the-stack | train |
4ebf66a96dde3e3f32a0fd08 | train | function | def broadcast_to(x, new_shape):
x_shape = list(x.shape)
num_x_dims = len(x_shape)
num_shape_dims = len(new_shape)
diff = num_shape_dims - num_x_dims
if diff == 0:
return mx.nd.broadcast_to(x, new_shape)
x = mx.nd.reshape(x, [1] * diff + x_shape)
return mx.nd.broadcast_to(x, new_shape... | def broadcast_to(x, new_shape):
| x_shape = list(x.shape)
num_x_dims = len(x_shape)
num_shape_dims = len(new_shape)
diff = num_shape_dims - num_x_dims
if diff == 0:
return mx.nd.broadcast_to(x, new_shape)
x = mx.nd.reshape(x, [1] * diff + x_shape)
return mx.nd.broadcast_to(x, new_shape)
| ):
return float(self._mx_finfo.tiny)
# noinspection PyShadowingBuiltins
def finfo(type: Union[type, str, mx.nd.NDArray]) -> Finfo:
return Finfo(np.finfo(ivy.as_native_dtype(type)))
def broadcast_to(x, new_shape):
| 63 | 64 | 91 | 8 | 55 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | broadcast_to | broadcast_to | 92 | 100 | 92 | 92 | 265188a10194e9364add04dd7a7f301d480f51d3 | bigcode/the-stack | train |
19b9f8a9c9424a00c41636cf | train | function | def dtype(x, as_native=False):
dt = x.dtype
if as_native:
return x.dtype
return as_ivy_dtype(dt)
| def dtype(x, as_native=False):
| dt = x.dtype
if as_native:
return x.dtype
return as_ivy_dtype(dt)
| return 1
return int(
dtype_str.replace("<class 'numpy.", "")
.replace("'>", "")
.replace("uint", "")
.replace("int", "")
.replace("bfloat", "")
.replace("float", "")
)
def dtype(x, as_native=False):
| 64 | 64 | 32 | 8 | 56 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | dtype | dtype | 123 | 127 | 123 | 123 | c05241e843156c7310cbd3818e3cb49dd13bd2b6 | bigcode/the-stack | train |
183d15db9c5b7d4e3855db77 | train | class | class Finfo:
def __init__(self, mx_finfo):
self._mx_finfo = mx_finfo
@property
def bits(self):
return self._mx_finfo.bits
@property
def eps(self):
return float(self._mx_finfo.eps)
@property
def max(self):
return float(self._mx_finfo.max)
@property
... | class Finfo:
| def __init__(self, mx_finfo):
self._mx_finfo = mx_finfo
@property
def bits(self):
return self._mx_finfo.bits
@property
def eps(self):
return float(self._mx_finfo.eps)
@property
def max(self):
return float(self._mx_finfo.max)
@property
def min(self)... | "float64": _np.float64,
"bool": _np.bool_,
}
# noinspection PyShadowingBuiltins
def iinfo(type: Union[type, str, mx.nd.NDArray]) -> np.iinfo:
return np.iinfo(ivy.as_native_dtype(type))
class Finfo:
| 64 | 64 | 123 | 4 | 60 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | Finfo | Finfo | 62 | 84 | 62 | 62 | 6d270619282fd802be0029ed921749e7831cc983 | bigcode/the-stack | train |
6877837ce39ba4c1c95109d7 | train | function | def as_native_dtype(dtype_in):
if not isinstance(dtype_in, str):
return dtype_in
return native_dtype_dict[ivy.Dtype(dtype_in)]
| def as_native_dtype(dtype_in):
| if not isinstance(dtype_in, str):
return dtype_in
return native_dtype_dict[ivy.Dtype(dtype_in)]
| .dtype
if as_native:
return x.dtype
return as_ivy_dtype(dt)
def as_ivy_dtype(dtype_in):
if isinstance(dtype_in, str):
return ivy.Dtype(dtype_in)
return ivy.Dtype(ivy_dtype_dict[dtype_in])
def as_native_dtype(dtype_in):
| 64 | 64 | 33 | 7 | 57 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | as_native_dtype | as_native_dtype | 136 | 139 | 136 | 136 | b477cf3c1a4a83075c8ce8e8313a53d4675243e9 | bigcode/the-stack | train |
c031252650df427d62158267 | train | function | def iinfo(type: Union[type, str, mx.nd.NDArray]) -> np.iinfo:
return np.iinfo(ivy.as_native_dtype(type))
| def iinfo(type: Union[type, str, mx.nd.NDArray]) -> np.iinfo:
| return np.iinfo(ivy.as_native_dtype(type))
| _np.float16,
"float32": _np.float32,
"float64": _np.float64,
"bool": _np.bool_,
}
# noinspection PyShadowingBuiltins
def iinfo(type: Union[type, str, mx.nd.NDArray]) -> np.iinfo:
| 64 | 64 | 33 | 21 | 42 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | iinfo | iinfo | 58 | 59 | 58 | 58 | 5869dee783d8d10a787abcd9ab42d071297e54a9 | bigcode/the-stack | train |
d189c52d8045164459b2715b | train | function | def finfo(type: Union[type, str, mx.nd.NDArray]) -> Finfo:
return Finfo(np.finfo(ivy.as_native_dtype(type)))
| def finfo(type: Union[type, str, mx.nd.NDArray]) -> Finfo:
| return Finfo(np.finfo(ivy.as_native_dtype(type)))
| def min(self):
return float(self._mx_finfo.min)
@property
def smallest_normal(self):
return float(self._mx_finfo.tiny)
# noinspection PyShadowingBuiltins
def finfo(type: Union[type, str, mx.nd.NDArray]) -> Finfo:
| 64 | 64 | 34 | 20 | 43 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | finfo | finfo | 88 | 89 | 88 | 88 | 55bdae00539f5b393442de1a175e7c5d1303be89 | bigcode/the-stack | train |
2790677ac14a9919a030c077 | train | function | def dtype_bits(dtype_in):
dtype_str = as_ivy_dtype(dtype_in)
if "bool" in dtype_str:
return 1
return int(
dtype_str.replace("<class 'numpy.", "")
.replace("'>", "")
.replace("uint", "")
.replace("int", "")
.replace("bfloat", "")
.replace("float", "")
... | def dtype_bits(dtype_in):
| dtype_str = as_ivy_dtype(dtype_in)
if "bool" in dtype_str:
return 1
return int(
dtype_str.replace("<class 'numpy.", "")
.replace("'>", "")
.replace("uint", "")
.replace("int", "")
.replace("bfloat", "")
.replace("float", "")
)
| x = mx.nd.reshape(x, [1] * diff + x_shape)
return mx.nd.broadcast_to(x, new_shape)
@_handle_flat_arrays_in_out
def astype(x, dtype):
dtype = ivy.as_native_dtype(dtype)
return x.astype(dtype)
def dtype_bits(dtype_in):
| 64 | 64 | 83 | 6 | 58 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | dtype_bits | dtype_bits | 109 | 120 | 109 | 109 | 6271db61b1886f98d85c9a06326923fd972536ff | bigcode/the-stack | train |
0850281728b9f36e69188935 | train | function | @_handle_flat_arrays_in_out
def astype(x, dtype):
dtype = ivy.as_native_dtype(dtype)
return x.astype(dtype)
| @_handle_flat_arrays_in_out
def astype(x, dtype):
| dtype = ivy.as_native_dtype(dtype)
return x.astype(dtype)
| _x_dims
if diff == 0:
return mx.nd.broadcast_to(x, new_shape)
x = mx.nd.reshape(x, [1] * diff + x_shape)
return mx.nd.broadcast_to(x, new_shape)
@_handle_flat_arrays_in_out
def astype(x, dtype):
| 64 | 64 | 30 | 15 | 49 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | astype | astype | 103 | 106 | 103 | 104 | bea79741b78395e8622133183da56d4e6aab8261 | bigcode/the-stack | train |
f1eef3f8946bfdc204c6f29f | train | function | def as_ivy_dtype(dtype_in):
if isinstance(dtype_in, str):
return ivy.Dtype(dtype_in)
return ivy.Dtype(ivy_dtype_dict[dtype_in])
| def as_ivy_dtype(dtype_in):
| if isinstance(dtype_in, str):
return ivy.Dtype(dtype_in)
return ivy.Dtype(ivy_dtype_dict[dtype_in])
| .replace("int", "")
.replace("bfloat", "")
.replace("float", "")
)
def dtype(x, as_native=False):
dt = x.dtype
if as_native:
return x.dtype
return as_ivy_dtype(dt)
def as_ivy_dtype(dtype_in):
| 64 | 64 | 37 | 8 | 56 | VedPatwardhan/ivy | ivy/functional/backends/mxnet/data_type.py | Python | as_ivy_dtype | as_ivy_dtype | 130 | 133 | 130 | 130 | f1ebdd6d1d3b150d407ebfa5b31264f343573670 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.